WMSlite/WmsLite.Api/Common/TemplateConfigJsonValidator.cs
zhougf fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

281 lines
10 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.Json;
using WmsLite.Api.Common;
using WmsLite.Api.Models.Templates;
namespace WmsLite.Api.Common;
/// <summary>
/// 统一解析与校验 sys_template.config_json,供保存模板与库存扩展字段校验共用。
/// </summary>
public static class TemplateConfigJsonValidator
{
private static readonly HashSet<string> AllowedTypes = new(StringComparer.OrdinalIgnoreCase)
{
"text", "number", "decimal", "int", "bool", "date", "datetime"
};
private static readonly HashSet<string> AllowedQueryModes = new(StringComparer.OrdinalIgnoreCase)
{
"eq", "like"
};
/// <summary>
/// 校验并解析为字段列表;非法 JSON、结构或业务规则抛 <see cref="BusinessException"/>。
/// </summary>
public static IReadOnlyList<TemplateFieldConfig> ValidateAndParse(string? configJson)
{
if (string.IsNullOrWhiteSpace(configJson))
{
return Array.Empty<TemplateFieldConfig>();
}
JsonDocument doc;
try
{
doc = JsonDocument.Parse(configJson);
}
catch (JsonException ex)
{
throw new BusinessException($"Invalid template config JSON: {ex.Message}");
}
using (doc)
{
if (doc.RootElement.ValueKind != JsonValueKind.Array)
{
throw new BusinessException("ConfigJson must be a JSON array.");
}
var list = new List<TemplateFieldConfig>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var element in doc.RootElement.EnumerateArray())
{
if (element.ValueKind != JsonValueKind.Object)
{
throw new BusinessException("Each template field must be a JSON object.");
}
if (!element.TryGetProperty("field", out var fieldProp))
{
throw new BusinessException("Each template field must include a 'field' property.");
}
var rawField = fieldProp.ValueKind == JsonValueKind.String ? fieldProp.GetString() : null;
if (string.IsNullOrWhiteSpace(rawField))
{
throw new BusinessException("Template field 'field' must be a non-empty string.");
}
var fieldName = rawField.Trim();
if (!seen.Add(fieldName))
{
throw new BusinessException($"Duplicate template field '{fieldName}'.");
}
var label = fieldName;
if (element.TryGetProperty("label", out var labelProp))
{
if (labelProp.ValueKind != JsonValueKind.String)
{
throw new BusinessException($"Template field '{fieldName}': label must be a string.");
}
var ls = labelProp.GetString();
if (!string.IsNullOrWhiteSpace(ls))
{
label = ls.Trim();
}
}
var typeNorm = "text";
if (element.TryGetProperty("type", out var typeProp))
{
if (typeProp.ValueKind != JsonValueKind.String)
{
throw new BusinessException($"Template field '{fieldName}': type must be a string.");
}
var t = typeProp.GetString();
if (!string.IsNullOrWhiteSpace(t))
{
typeNorm = t.Trim().ToLowerInvariant();
}
}
if (!AllowedTypes.Contains(typeNorm))
{
throw new BusinessException($"Unsupported template field type '{typeNorm}' for field '{fieldName}'.");
}
var required = element.TryGetProperty("required", out var reqProp)
&& reqProp.ValueKind == JsonValueKind.True;
var queryable = element.TryGetProperty("queryable", out var qProp)
&& qProp.ValueKind == JsonValueKind.True;
string? queryMode = null;
if (element.TryGetProperty("queryMode", out var qmProp))
{
if (qmProp.ValueKind == JsonValueKind.Null)
{
queryMode = null;
}
else if (qmProp.ValueKind == JsonValueKind.String)
{
var qm = qmProp.GetString()?.Trim();
if (!string.IsNullOrEmpty(qm))
{
if (!AllowedQueryModes.Contains(qm))
{
throw new BusinessException($"Unsupported queryMode '{qm}' for field '{fieldName}'.");
}
queryMode = qm.ToLowerInvariant();
}
}
else
{
throw new BusinessException($"Template field '{fieldName}': queryMode must be a string.");
}
}
object? defaultValue = null;
if (element.TryGetProperty("defaultValue", out var dvProp))
{
defaultValue = ExtractDefaultValueObject(dvProp);
ValidateDefaultMatchesType(fieldName, typeNorm, dvProp);
}
list.Add(new TemplateFieldConfig
{
Field = fieldName,
Label = label,
Type = typeNorm,
Required = required,
Queryable = queryable,
QueryMode = queryMode,
DefaultValue = defaultValue
});
}
return list;
}
}
private static object? ExtractDefaultValueObject(JsonElement dvProp)
{
return dvProp.ValueKind switch
{
JsonValueKind.Null => null,
JsonValueKind.String => dvProp.GetString(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Number => dvProp.TryGetInt64(out var l) ? l : dvProp.GetDecimal(),
_ => throw new BusinessException("defaultValue must be null, string, number, or boolean.")
};
}
private static void ValidateDefaultMatchesType(string fieldName, string typeNorm, JsonElement dvProp)
{
if (dvProp.ValueKind == JsonValueKind.Null)
{
return;
}
switch (typeNorm)
{
case "text":
if (dvProp.ValueKind != JsonValueKind.String)
{
throw new BusinessException($"Template field '{fieldName}': defaultValue for type text must be a string.");
}
break;
case "number":
case "decimal":
if (dvProp.ValueKind == JsonValueKind.String)
{
if (string.IsNullOrWhiteSpace(dvProp.GetString()))
{
break;
}
if (!decimal.TryParse(dvProp.GetString(), out _))
{
throw new BusinessException($"Template field '{fieldName}': defaultValue is not a valid decimal.");
}
}
else if (dvProp.ValueKind != JsonValueKind.Number)
{
throw new BusinessException($"Template field '{fieldName}': defaultValue for numeric type must be a number or numeric string.");
}
break;
case "int":
if (dvProp.ValueKind == JsonValueKind.String)
{
if (string.IsNullOrWhiteSpace(dvProp.GetString()))
{
break;
}
if (!int.TryParse(dvProp.GetString(), out _))
{
throw new BusinessException($"Template field '{fieldName}': defaultValue is not a valid integer.");
}
}
else if (dvProp.ValueKind == JsonValueKind.Number)
{
if (!dvProp.TryGetInt32(out _))
{
throw new BusinessException($"Template field '{fieldName}': defaultValue must be a whole number for type int.");
}
}
else
{
throw new BusinessException($"Template field '{fieldName}': defaultValue for int must be an integer or integer string.");
}
break;
case "bool":
if (dvProp.ValueKind is not (JsonValueKind.True or JsonValueKind.False or JsonValueKind.String))
{
throw new BusinessException($"Template field '{fieldName}': defaultValue for bool must be true, false, or a string 'true'/'false'.");
}
if (dvProp.ValueKind == JsonValueKind.String
&& !bool.TryParse(dvProp.GetString(), out _))
{
throw new BusinessException($"Template field '{fieldName}': defaultValue is not a valid boolean.");
}
break;
case "date":
case "datetime":
if (dvProp.ValueKind == JsonValueKind.String)
{
if (string.IsNullOrWhiteSpace(dvProp.GetString()))
{
break;
}
if (!DateTime.TryParse(dvProp.GetString(), out _))
{
throw new BusinessException($"Template field '{fieldName}': defaultValue is not a valid date/time.");
}
}
else
{
throw new BusinessException($"Template field '{fieldName}': defaultValue for date/datetime must be a string.");
}
break;
}
}
}