LabelTemplateScopeSchemaHelper.cs 13.3 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
using SqlSugar;

namespace FoodLabeling.Application.Helpers;

/// <summary>
/// 探测标签模板 Company/Region scope 列与关联表是否已迁移(<c>fl_label_template_scope.sql</c>)。
/// 未迁移时 ORM 实体不含 <c>AppliedPartnerType</c>/<c>AppliedRegionType</c>,读写走 raw SQL 或关联表推断。
/// </summary>
public static class LabelTemplateScopeSchemaHelper
{
    private static LabelTemplateScopeSchemaStatus? _cached;

    public sealed class LabelTemplateScopeSchemaStatus
    {
        public bool HasAppliedPartnerTypeColumn { get; init; }

        public bool HasAppliedRegionTypeColumn { get; init; }

        public bool HasPartnerScopeTable { get; init; }

        public bool HasRegionScopeTable { get; init; }

        public bool HasBorderTypeColumn { get; init; }

        public bool HasContentsColumn { get; init; }

        /// <summary>partner/region 关联表均已创建(用于多选明细)。</summary>
        public bool HasPartnerRegionScopeTables => HasPartnerScopeTable && HasRegionScopeTable;

        /// <summary>列 + 关联表均已迁移。</summary>
        public bool IsFullSchema =>
            HasAppliedPartnerTypeColumn
            && HasAppliedRegionTypeColumn
            && HasPartnerRegionScopeTables;
    }

    public static async Task<LabelTemplateScopeSchemaStatus> GetStatusAsync(ISqlSugarClient db)
    {
        if (_cached is not null)
        {
            return _cached;
        }

        try
        {
            var partnerColCount = await db.Ado.GetIntAsync(
                """
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'fl_label_template'
                  AND COLUMN_NAME = 'AppliedPartnerType'
                """);

            var regionColCount = await db.Ado.GetIntAsync(
                """
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'fl_label_template'
                  AND COLUMN_NAME = 'AppliedRegionType'
                """);

            var partnerTableCount = await db.Ado.GetIntAsync(
                """
                SELECT COUNT(*)
                FROM information_schema.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'fl_label_template_partner'
                """);

            var regionTableCount = await db.Ado.GetIntAsync(
                """
                SELECT COUNT(*)
                FROM information_schema.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'fl_label_template_region'
                """);

            var borderColCount = await db.Ado.GetIntAsync(
                """
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'fl_label_template'
                  AND COLUMN_NAME = 'BorderType'
                """);

            var contentsColCount = await db.Ado.GetIntAsync(
                """
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'fl_label_template'
                  AND COLUMN_NAME = 'Contents'
                """);

            _cached = new LabelTemplateScopeSchemaStatus
            {
                HasAppliedPartnerTypeColumn = partnerColCount > 0,
                HasAppliedRegionTypeColumn = regionColCount > 0,
                HasPartnerScopeTable = partnerTableCount > 0,
                HasRegionScopeTable = regionTableCount > 0,
                HasBorderTypeColumn = borderColCount > 0,
                HasContentsColumn = contentsColCount > 0
            };
        }
        catch
        {
            _cached = new LabelTemplateScopeSchemaStatus();
        }

        return _cached;
    }

    /// <summary>单元测试或切换库后调用。</summary>
    public static void ResetCacheForTests() => _cached = null;

    /// <summary>清除缓存并重新探测 schema(应用启动早于迁移脚本执行后调用)。</summary>
    public static async Task<LabelTemplateScopeSchemaStatus> RefreshStatusAsync(ISqlSugarClient db)
    {
        _cached = null;
        return await GetStatusAsync(db);
    }

    /// <summary>
    /// 是否已创建 <c>fl_label_template_partner</c> 与 <c>fl_label_template_region</c>。
    /// </summary>
    public static async Task<bool> HasPartnerRegionScopeTablesAsync(ISqlSugarClient db)
    {
        var status = await GetStatusAsync(db);
        return status.HasPartnerRegionScopeTables;
    }

    /// <summary>
    /// 是否已创建 <c>fl_label_template_partner</c>;缓存未命中时刷新后再探测。
    /// </summary>
    public static async Task<bool> EnsurePartnerScopeTableAsync(ISqlSugarClient db, bool needsPartnerRows)
    {
        var status = await GetStatusAsync(db);
        if (status.HasPartnerScopeTable)
        {
            return true;
        }

        if (!needsPartnerRows)
        {
            return false;
        }

        status = await RefreshStatusAsync(db);
        return status.HasPartnerScopeTable;
    }

    /// <summary>
    /// 是否已创建 <c>fl_label_template_region</c>;缓存未命中时刷新后再探测。
    /// </summary>
    public static async Task<bool> EnsureRegionScopeTableAsync(ISqlSugarClient db, bool needsRegionRows)
    {
        var status = await GetStatusAsync(db);
        if (status.HasRegionScopeTable)
        {
            return true;
        }

        if (!needsRegionRows)
        {
            return false;
        }

        status = await RefreshStatusAsync(db);
        return status.HasRegionScopeTable;
    }

    /// <summary>
    /// 已迁移 scope 列时,写入 <c>AppliedPartnerType</c> / <c>AppliedRegionType</c>(未迁移则 no-op)。
    /// </summary>
    public static async Task SetAppliedScopeTypesAsync(
        ISqlSugarClient db,
        string templateId,
        string appliedPartnerType,
        string appliedRegionType)
    {
        if (string.IsNullOrWhiteSpace(templateId))
        {
            return;
        }

        var status = await GetStatusAsync(db);
        if (!status.HasAppliedPartnerTypeColumn && !status.HasAppliedRegionTypeColumn)
        {
            return;
        }

        if (status.HasAppliedPartnerTypeColumn && status.HasAppliedRegionTypeColumn)
        {
            await db.Ado.ExecuteCommandAsync(
                """
                UPDATE fl_label_template
                SET AppliedPartnerType = @partnerType,
                    AppliedRegionType = @regionType
                WHERE Id = @id
                """,
                new
                {
                    partnerType = appliedPartnerType.Trim(),
                    regionType = appliedRegionType.Trim(),
                    id = templateId.Trim()
                });
            return;
        }

        if (status.HasAppliedPartnerTypeColumn)
        {
            await db.Ado.ExecuteCommandAsync(
                "UPDATE fl_label_template SET AppliedPartnerType = @type WHERE Id = @id",
                new { type = appliedPartnerType.Trim(), id = templateId.Trim() });
        }

        if (status.HasAppliedRegionTypeColumn)
        {
            await db.Ado.ExecuteCommandAsync(
                "UPDATE fl_label_template SET AppliedRegionType = @type WHERE Id = @id",
                new { type = appliedRegionType.Trim(), id = templateId.Trim() });
        }
    }

    /// <summary>已迁移 <c>BorderType</c> 列时写入(未迁移则 no-op)。</summary>
    public static async Task SetBorderTypeAsync(ISqlSugarClient db, string templateId, string borderType)
    {
        if (string.IsNullOrWhiteSpace(templateId))
        {
            return;
        }

        var status = await GetStatusAsync(db);
        if (!status.HasBorderTypeColumn)
        {
            return;
        }

        await db.Ado.ExecuteCommandAsync(
            "UPDATE fl_label_template SET BorderType = @border WHERE Id = @id",
            new { border = borderType.Trim(), id = templateId.Trim() });
    }

    /// <summary>读取模板外框类型;列不存在时返回 <c>none</c>。</summary>
    public static async Task<string> GetBorderTypeForTemplateAsync(ISqlSugarClient db, string templateId)
    {
        if (string.IsNullOrWhiteSpace(templateId))
        {
            return "none";
        }

        var status = await GetStatusAsync(db);
        if (!status.HasBorderTypeColumn)
        {
            return "none";
        }

        var value = await db.Ado.GetScalarAsync(
            "SELECT BorderType FROM fl_label_template WHERE Id = @id LIMIT 1",
            new { id = templateId.Trim() });

        var text = value?.ToString()?.Trim();
        return string.IsNullOrWhiteSpace(text) ? "none" : text;
    }

    /// <summary>批量读取模板 Contents;列不存在时返回空字典。</summary>
    public static async Task<Dictionary<string, string>> GetContentsMapAsync(
        ISqlSugarClient db,
        IReadOnlyList<string> templateIds)
    {
        var result = new Dictionary<string, string>(StringComparer.Ordinal);
        if (templateIds.Count == 0)
        {
            return result;
        }

        var status = await GetStatusAsync(db);
        if (!status.HasContentsColumn)
        {
            return result;
        }

        var rows = await db.Ado.SqlQueryAsync<ContentsRow>(
            """
            SELECT Id, Contents
            FROM fl_label_template
            WHERE Id IN (@ids)
            """,
            new { ids = templateIds.ToArray() });

        foreach (var row in rows)
        {
            var text = row.Contents?.Trim();
            if (!string.IsNullOrWhiteSpace(text))
            {
                result[row.Id] = text;
            }
        }

        return result;
    }

    /// <summary>读取单条模板 Contents;列不存在或未写入时返回 null。</summary>
    public static async Task<string?> GetContentsForTemplateAsync(ISqlSugarClient db, string templateId)
    {
        if (string.IsNullOrWhiteSpace(templateId))
        {
            return null;
        }

        var map = await GetContentsMapAsync(db, new[] { templateId.Trim() });
        return map.TryGetValue(templateId.Trim(), out var text) ? text : null;
    }

    /// <summary>批量读取模板 Company/Region 维度 ALL/SPECIFIED;列不存在时返回空字典。</summary>
    public static async Task<Dictionary<string, (string PartnerType, string RegionType)>> GetAppliedScopeTypesMapAsync(
        ISqlSugarClient db,
        IReadOnlyList<string> templateIds)
    {
        var result = new Dictionary<string, (string PartnerType, string RegionType)>(StringComparer.Ordinal);
        if (templateIds.Count == 0)
        {
            return result;
        }

        var status = await GetStatusAsync(db);
        if (!status.HasAppliedPartnerTypeColumn && !status.HasAppliedRegionTypeColumn)
        {
            return result;
        }

        var ids = templateIds.Where(x => !string.IsNullOrWhiteSpace(x))
            .Select(x => x.Trim())
            .Distinct(StringComparer.Ordinal)
            .ToArray();
        if (ids.Length == 0)
        {
            return result;
        }

        var rows = await db.Ado.SqlQueryAsync<AppliedScopeTypesRow>(
            """
            SELECT Id, AppliedPartnerType, AppliedRegionType
            FROM fl_label_template
            WHERE Id IN (@ids)
            """,
            new { ids });

        foreach (var row in rows)
        {
            if (string.IsNullOrWhiteSpace(row.Id))
            {
                continue;
            }

            var partnerType = status.HasAppliedPartnerTypeColumn
                ? NormalizeScopeTypeValue(row.AppliedPartnerType)
                : ScopeAll;
            var regionType = status.HasAppliedRegionTypeColumn
                ? NormalizeScopeTypeValue(row.AppliedRegionType)
                : ScopeAll;
            result[row.Id.Trim()] = (partnerType, regionType);
        }

        return result;
    }

    private static string NormalizeScopeTypeValue(string? type)
    {
        var normalized = (type ?? ScopeAll).Trim().ToUpperInvariant();
        return normalized == ScopeSpecified ? ScopeSpecified : ScopeAll;
    }

    private const string ScopeAll = "ALL";
    private const string ScopeSpecified = "SPECIFIED";

    private sealed class AppliedScopeTypesRow
    {
        public string Id { get; init; } = string.Empty;

        public string? AppliedPartnerType { get; init; }

        public string? AppliedRegionType { get; init; }
    }

    /// <summary>已迁移 <c>Contents</c> 列时写入(未迁移则 no-op)。</summary>
    public static async Task SetContentsAsync(ISqlSugarClient db, string templateId, string? contents)
    {
        if (string.IsNullOrWhiteSpace(templateId))
        {
            return;
        }

        var status = await GetStatusAsync(db);
        if (!status.HasContentsColumn)
        {
            return;
        }

        await db.Ado.ExecuteCommandAsync(
            "UPDATE fl_label_template SET Contents = @contents WHERE Id = @id",
            new { contents = contents?.Trim() ?? string.Empty, id = templateId.Trim() });
    }

    private sealed class ContentsRow
    {
        public string Id { get; init; } = string.Empty;

        public string? Contents { get; init; }
    }
}