TrainingFileScopeHelper.cs 17.7 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
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Shared.Helpers;
using SqlSugar;
using Volo.Abp;

namespace FoodLabeling.Application.Helpers;

/// <summary>
/// 培训文件适用范围:Company / Region / Location 三维度独立 ALL/SPECIFIED。
/// </summary>
public static class TrainingFileScopeHelper
{
    public sealed class TrainingFileScopeSaveResult
    {
        public string AppliedPartnerType { get; init; } = AllScopeBindingHelper.ScopeAll;

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

        public string AppliedRegionType { get; init; } = AllScopeBindingHelper.ScopeAll;

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

        public string AvailabilityType { get; init; } = AllScopeBindingHelper.ScopeAll;

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

    public sealed class TrainingFileScopeDisplay
    {
        public string AppliedPartnerType { get; init; } = AllScopeBindingHelper.ScopeAll;

        public string Company { get; init; } = LabelEntityPartnerScopeHelper.AllCompaniesDisplay;

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

        public string AppliedRegionType { get; init; } = AllScopeBindingHelper.ScopeAll;

        public string Region { get; init; } = FoodLabelingDisplayConsts.AllRegion;

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

        public string AvailabilityType { get; init; } = AllScopeBindingHelper.ScopeAll;

        public string Location { get; init; } = FoodLabelingDisplayConsts.AllLocation;

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

    public sealed class LocationScopeContext
    {
        public string LocationId { get; init; } = string.Empty;

        public string? PartnerId { get; init; }

        public string? GroupId { get; init; }
    }

    /// <summary>
    /// 解析保存入参中的三维度范围。
    /// </summary>
    public static async Task<TrainingFileScopeSaveResult> ResolveScopeForSaveAsync(
        ISqlSugarClient db,
        string? appliedPartnerType,
        IReadOnlyList<string>? partnerIds,
        IReadOnlyList<string>? companyIds,
        string? appliedRegionType,
        IReadOnlyList<string>? regionIds,
        IReadOnlyList<string>? groupIds,
        string? availabilityType,
        IReadOnlyList<string>? locationIds)
    {
        var partnerScope = await LabelEntityPartnerScopeHelper.ResolvePartnerScopeForSaveAsync(
            db,
            appliedPartnerType,
            partnerIds,
            companyIds);

        var partnerContext = string.Equals(
            partnerScope.AppliedPartnerType,
            AllScopeBindingHelper.ScopeSpecified,
            StringComparison.OrdinalIgnoreCase)
            ? partnerScope.PartnerIds
            : null;

        var mergedRegionIds = NormalizeRegionIds(regionIds, groupIds);
        var hasRegionArray = regionIds is not null || groupIds is not null;
        var (regionType, regionIdsForSave) = await AllScopeBindingHelper.NormalizeRegionScopeAsync(
            db,
            appliedRegionType,
            mergedRegionIds,
            hasRegionArray,
            partnerContext);

        if (string.Equals(regionType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase)
            && regionIdsForSave.Count > 0)
        {
            await ValidateGroupIdsExistAsync(db, regionIdsForSave);
        }

        var hasLocationArray = locationIds is not null;
        var (locationType, locationIdsForSave) = await AllScopeBindingHelper.NormalizeLocationScopeAsync(
            db,
            availabilityType,
            locationIds ?? new List<string>(),
            hasLocationArray,
            partnerContext,
            regionIdsForSave);

        if (string.Equals(locationType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase)
            && locationIdsForSave.Count > 0)
        {
            await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(db, locationIdsForSave);
        }

        return new TrainingFileScopeSaveResult
        {
            AppliedPartnerType = partnerScope.AppliedPartnerType,
            PartnerIds = partnerScope.PartnerIds,
            AppliedRegionType = regionType,
            RegionIds = regionIdsForSave,
            AvailabilityType = locationType,
            LocationIds = locationIdsForSave
        };
    }

    /// <summary>
    /// 保存培训文件三维度范围关联。
    /// </summary>
    public static async Task SaveScopeAsync(
        ISqlSugarClient db,
        string trainingFileId,
        TrainingFileScopeSaveResult scope,
        string? currentUserId,
        DateTime now)
    {
        await db.Deleteable<FlTrainingFilePartnerDbEntity>()
            .Where(x => x.TrainingFileId == trainingFileId)
            .ExecuteCommandAsync();
        await db.Deleteable<FlTrainingFileRegionDbEntity>()
            .Where(x => x.TrainingFileId == trainingFileId)
            .ExecuteCommandAsync();
        await db.Deleteable<FlTrainingFileLocationDbEntity>()
            .Where(x => x.TrainingFileId == trainingFileId)
            .ExecuteCommandAsync();

        if (string.Equals(scope.AppliedPartnerType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase)
            && scope.PartnerIds.Count > 0)
        {
            var rows = scope.PartnerIds.Select(pid => new FlTrainingFilePartnerDbEntity
            {
                Id = YitIdHelper.NextId().ToString(),
                TrainingFileId = trainingFileId,
                PartnerId = pid,
                CreationTime = now,
                CreatorId = currentUserId
            }).ToList();
            await db.Insertable(rows).ExecuteCommandAsync();
        }

        if (string.Equals(scope.AppliedRegionType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase)
            && scope.RegionIds.Count > 0)
        {
            var rows = scope.RegionIds.Select(gid => new FlTrainingFileRegionDbEntity
            {
                Id = YitIdHelper.NextId().ToString(),
                TrainingFileId = trainingFileId,
                GroupId = gid,
                CreationTime = now,
                CreatorId = currentUserId
            }).ToList();
            await db.Insertable(rows).ExecuteCommandAsync();
        }

        if (string.Equals(scope.AvailabilityType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase)
            && scope.LocationIds.Count > 0)
        {
            var rows = scope.LocationIds.Select(lid => new FlTrainingFileLocationDbEntity
            {
                Id = YitIdHelper.NextId().ToString(),
                TrainingFileId = trainingFileId,
                LocationId = lid,
                CreationTime = now,
                CreatorId = currentUserId
            }).ToList();
            await db.Insertable(rows).ExecuteCommandAsync();
        }
    }

    /// <summary>
    /// 构建多个培训文件的适用范围回显(列表/树批量用)。
    /// </summary>
    public static async Task<Dictionary<string, TrainingFileScopeDisplay>> BuildScopeDisplayMapAsync(
        ISqlSugarClient db,
        IReadOnlyList<FlTrainingFileDbEntity> files)
    {
        if (files.Count == 0)
        {
            return new Dictionary<string, TrainingFileScopeDisplay>(StringComparer.Ordinal);
        }

        var tasks = files.Select(async file =>
            (file.Id, Display: await BuildScopeDisplayAsync(db, file)));
        var results = await Task.WhenAll(tasks);
        return results.ToDictionary(x => x.Id, x => x.Display, StringComparer.Ordinal);
    }

    /// <summary>
    /// 删除培训文件全部范围关联。
    /// </summary>
    public static async Task DeleteScopeRowsAsync(ISqlSugarClient db, string trainingFileId)
    {
        await db.Deleteable<FlTrainingFilePartnerDbEntity>()
            .Where(x => x.TrainingFileId == trainingFileId)
            .ExecuteCommandAsync();
        await db.Deleteable<FlTrainingFileRegionDbEntity>()
            .Where(x => x.TrainingFileId == trainingFileId)
            .ExecuteCommandAsync();
        await db.Deleteable<FlTrainingFileLocationDbEntity>()
            .Where(x => x.TrainingFileId == trainingFileId)
            .ExecuteCommandAsync();
    }

    /// <summary>
    /// 构建详情/编辑回显用的范围数据。
    /// </summary>
    public static async Task<TrainingFileScopeDisplay> BuildScopeDisplayAsync(
        ISqlSugarClient db,
        FlTrainingFileDbEntity file)
    {
        var partnerIds = string.Equals(
            file.AppliedPartnerType,
            AllScopeBindingHelper.ScopeSpecified,
            StringComparison.OrdinalIgnoreCase)
            ? await db.Queryable<FlTrainingFilePartnerDbEntity>()
                .Where(x => x.TrainingFileId == file.Id)
                .Select(x => x.PartnerId)
                .ToListAsync()
            : new List<string>();

        var regionIds = string.Equals(
            file.AppliedRegionType,
            AllScopeBindingHelper.ScopeSpecified,
            StringComparison.OrdinalIgnoreCase)
            ? await db.Queryable<FlTrainingFileRegionDbEntity>()
                .Where(x => x.TrainingFileId == file.Id)
                .Select(x => x.GroupId)
                .ToListAsync()
            : new List<string>();

        var locationIds = string.Equals(
            file.AvailabilityType,
            AllScopeBindingHelper.ScopeSpecified,
            StringComparison.OrdinalIgnoreCase)
            ? await db.Queryable<FlTrainingFileLocationDbEntity>()
                .Where(x => x.TrainingFileId == file.Id)
                .Select(x => x.LocationId)
                .ToListAsync()
            : new List<string>();

        partnerIds = LocationScopeBindingHelper.NormalizeIds(partnerIds);
        regionIds = LocationScopeBindingHelper.NormalizeIds(regionIds);
        locationIds = LocationScopeBindingHelper.NormalizeIds(locationIds);

        var collapsed = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync(
            db,
            partnerIds,
            regionIds,
            locationIds,
            ScopeAllEchoHelper.ForLabelTemplateDimensions(
                file.AppliedPartnerType,
                file.AppliedRegionType,
                file.AvailabilityType));

        return new TrainingFileScopeDisplay
        {
            AppliedPartnerType = file.AppliedPartnerType,
            Company = await BuildPartnerDisplayAsync(db, file.AppliedPartnerType, collapsed.PartnerIds),
            PartnerIds = collapsed.PartnerIds,
            AppliedRegionType = file.AppliedRegionType,
            Region = await BuildRegionDisplayAsync(db, file.AppliedRegionType, collapsed.RegionIds),
            RegionIds = collapsed.RegionIds,
            AvailabilityType = file.AvailabilityType,
            Location = await BuildLocationDisplayAsync(db, file.AvailabilityType, collapsed.LocationIds),
            LocationIds = collapsed.LocationIds
        };
    }

    /// <summary>
    /// 按门店上下文过滤可见文件(Company + Region + Location 三维度 AND)。
    /// </summary>
    public static ISugarQueryable<FlTrainingFileDbEntity> ApplyLocationVisibilityFilter(
        ISugarQueryable<FlTrainingFileDbEntity> query,
        LocationScopeContext? context)
    {
        if (context is null || string.IsNullOrWhiteSpace(context.LocationId))
        {
            return query;
        }

        var locationId = context.LocationId.Trim();
        var partnerId = context.PartnerId?.Trim();
        var groupId = context.GroupId?.Trim();

        return query.Where(f =>
            f.AppliedPartnerType == AllScopeBindingHelper.ScopeAll
            || (partnerId != null
                && SqlFunc.Subqueryable<FlTrainingFilePartnerDbEntity>()
                    .Where(p => p.TrainingFileId == f.Id && p.PartnerId == partnerId)
                    .Any()))
            .Where(f =>
                f.AppliedRegionType == AllScopeBindingHelper.ScopeAll
                || (groupId != null
                    && SqlFunc.Subqueryable<FlTrainingFileRegionDbEntity>()
                        .Where(r => r.TrainingFileId == f.Id && r.GroupId == groupId)
                        .Any()))
            .Where(f =>
                f.AvailabilityType == AllScopeBindingHelper.ScopeAll
                || SqlFunc.Subqueryable<FlTrainingFileLocationDbEntity>()
                    .Where(l => l.TrainingFileId == f.Id && l.LocationId == locationId)
                    .Any());
    }

    /// <summary>
    /// 解析门店对应的 Company / Region 上下文。
    /// </summary>
    public static async Task<LocationScopeContext?> ResolveLocationScopeContextAsync(
        ISqlSugarClient db,
        string locationId)
    {
        if (string.IsNullOrWhiteSpace(locationId))
        {
            return null;
        }

        var normalized = locationId.Trim();
        var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(db, new[] { normalized });
        var groupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(db, new[] { normalized });

        return new LocationScopeContext
        {
            LocationId = normalized,
            PartnerId = partnerIds.FirstOrDefault(),
            GroupId = groupIds.FirstOrDefault()
        };
    }

    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 ValidateGroupIdsExistAsync(ISqlSugarClient db, List<string> groupIds)
    {
        if (groupIds.Count == 0)
        {
            return;
        }

        var existing = await db.Queryable<FlGroupDbEntity>()
            .Where(x => !x.IsDeleted && groupIds.Contains(x.Id))
            .Select(x => x.Id)
            .ToListAsync();
        var existingSet = new HashSet<string>(existing, StringComparer.OrdinalIgnoreCase);
        var missing = groupIds.Where(id => !existingSet.Contains(id)).ToList();
        if (missing.Count > 0)
        {
            throw new UserFriendlyException("存在无效的 Region Id");
        }
    }

    private static async Task<string> BuildPartnerDisplayAsync(
        ISqlSugarClient db,
        string appliedPartnerType,
        IReadOnlyList<string> partnerIds)
    {
        if (!string.Equals(appliedPartnerType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase))
        {
            return LabelEntityPartnerScopeHelper.AllCompaniesDisplay;
        }

        if (LocationScopeBindingHelper.ContainsAllScopeSentinel(partnerIds))
        {
            return LabelEntityPartnerScopeHelper.AllCompaniesDisplay;
        }

        if (partnerIds.Count == 0)
        {
            return FoodLabelingDisplayConsts.NotAvailable;
        }

        var rows = await db.Queryable<FlPartnerDbEntity>()
            .Where(x => !x.IsDeleted && partnerIds.Contains(x.Id))
            .Select(x => x.PartnerName)
            .ToListAsync();
        var names = rows.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x!.Trim()).Distinct().OrderBy(x => x).ToList();
        return names.Count > 0 ? string.Join(", ", names) : FoodLabelingDisplayConsts.NotAvailable;
    }

    private static async Task<string> BuildRegionDisplayAsync(
        ISqlSugarClient db,
        string appliedRegionType,
        IReadOnlyList<string> regionIds)
    {
        if (!string.Equals(appliedRegionType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase))
        {
            return FoodLabelingDisplayConsts.AllRegion;
        }

        if (LocationScopeBindingHelper.ContainsAllScopeSentinel(regionIds) || regionIds.Count == 0)
        {
            return regionIds.Count == 0
                ? FoodLabelingDisplayConsts.NotAvailable
                : FoodLabelingDisplayConsts.AllRegion;
        }

        var rows = await db.Queryable<FlGroupDbEntity>()
            .Where(x => !x.IsDeleted && regionIds.Contains(x.Id))
            .Select(x => x.GroupName)
            .ToListAsync();
        var names = rows.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x!.Trim()).Distinct().OrderBy(x => x).ToList();
        return names.Count > 0 ? string.Join(", ", names) : FoodLabelingDisplayConsts.NotAvailable;
    }

    private static async Task<string> BuildLocationDisplayAsync(
        ISqlSugarClient db,
        string availabilityType,
        IReadOnlyList<string> locationIds)
    {
        if (!string.Equals(availabilityType, AllScopeBindingHelper.ScopeSpecified, StringComparison.OrdinalIgnoreCase))
        {
            return FoodLabelingDisplayConsts.AllLocation;
        }

        if (LocationScopeBindingHelper.ContainsAllScopeSentinel(locationIds) || locationIds.Count == 0)
        {
            return locationIds.Count == 0
                ? FoodLabelingDisplayConsts.NotAvailable
                : FoodLabelingDisplayConsts.AllLocation;
        }

        var guidList = locationIds.Where(x => Guid.TryParse(x, out _)).Select(Guid.Parse).ToList();
        if (guidList.Count == 0)
        {
            return FoodLabelingDisplayConsts.NotAvailable;
        }

        var rows = await db.Queryable<FoodLabeling.Domain.Entities.LocationAggregateRoot>()
            .Where(x => !x.IsDeleted && guidList.Contains(x.Id))
            .Select(x => x.LocationName)
            .ToListAsync();
        var names = rows.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x!.Trim()).Distinct().OrderBy(x => x).ToList();
        return names.Count > 0 ? string.Join(", ", names) : FoodLabelingDisplayConsts.NotAvailable;
    }
}