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>
This commit is contained in:
zhougfandCursor committed 2026-05-24 14:17:47 +08:00
commit fa1b286463
241 files changed
+31188

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
namespace WmsLite.Api.Common;
public class BusinessException : Exception
{
public BusinessException(string message, string code = BusinessResult.BadRequestCode)
: base(message)
{
Code = code;
}
public string Code { get; }
}
+52
View File
@@ -0,0 +1,52 @@
using System.Text.Json.Serialization;
namespace WmsLite.Api.Common;
[JsonConverter(typeof(BusinessResultJsonConverter))]
public class BusinessResult
{
public const string SuccessCode = "200";
public const string BadRequestCode = "400";
public const string NotFoundCode = "404";
public const string ServerErrorCode = "500";
public bool Success { get; set; }
public string Code { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public object? Data { get; set; }
public static BusinessResult Ok(object? data = null, string message = "OK")
{
return new BusinessResult
{
Success = true,
Code = SuccessCode,
Message = message,
Data = data
};
}
public static BusinessResult Fail(string message, string code = ServerErrorCode, object? data = null)
{
return new BusinessResult
{
Success = false,
Code = code,
Message = message,
Data = data
};
}
public static BusinessResult BadRequest(string message, object? data = null)
{
return Fail(message, BadRequestCode, data);
}
public static BusinessResult NotFound(string message, object? data = null)
{
return Fail(message, NotFoundCode, data);
}
}
@@ -0,0 +1,35 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace WmsLite.Api.Common;
/// <summary>
/// <see cref="BusinessResult.Data"/> 为 object 时,默认序列化可能不会按运行时类型正确套用 long 转换器;
/// 显式按运行时类型写出,确保嵌套 DTO 中的雪花 Id 以字符串输出。
/// </summary>
public sealed class BusinessResultJsonConverter : JsonConverter<BusinessResult>
{
public override BusinessResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new JsonException("BusinessResult deserialization is not supported.");
}
public override void Write(Utf8JsonWriter writer, BusinessResult value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteBoolean("success", value.Success);
writer.WriteString("code", value.Code ?? string.Empty);
writer.WriteString("message", value.Message ?? string.Empty);
writer.WritePropertyName("data");
if (value.Data is null)
{
writer.WriteNullValue();
}
else
{
JsonSerializer.Serialize(writer, value.Data, value.Data.GetType(), options);
}
writer.WriteEndObject();
}
}
+43
View File
@@ -0,0 +1,43 @@
using System;
using System.ComponentModel;
using System.Reflection;
namespace WmsLite.Api.Common;
/// <summary>
/// 枚举与 <see cref="DescriptionAttribute"/> 的辅助扩展,便于返回用户可读文案。
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// 获取枚举值的 Description;未标注时返回 <see cref="Enum.ToString"/>。
/// </summary>
public static string GetDescription(this Enum value)
{
ArgumentNullException.ThrowIfNull(value);
var field = value.GetType().GetField(value.ToString());
if (field is null)
{
return value.ToString();
}
var attr = field.GetCustomAttribute<DescriptionAttribute>(inherit: false);
return string.IsNullOrWhiteSpace(attr?.Description) ? value.ToString() : attr!.Description;
}
/// <summary>
/// 将整型值解析为枚举后取 Description;无法解析时返回 <paramref name="fallback"/> 或数字字符串。
/// </summary>
public static string GetDescription<TEnum>(int value, string? fallback = null)
where TEnum : struct, Enum
{
if (!Enum.IsDefined(typeof(TEnum), value))
{
return fallback ?? value.ToString();
}
var e = Enum.ToObject(typeof(TEnum), value);
return e is Enum en ? en.GetDescription() : value.ToString();
}
}
@@ -0,0 +1,52 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace WmsLite.Api.Common;
/// <summary>
/// 将 Int64 以 JSON 字符串写出,避免前端 number 精度丢失(Snowflake 等主键)。
/// 反序列化同时支持 JSON 数字与字符串。
/// </summary>
public sealed class JsonLongAsStringConverter : JsonConverter<long>
{
public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.Number => reader.GetInt64(),
JsonTokenType.String => long.Parse(reader.GetString()!, NumberStyles.Integer, CultureInfo.InvariantCulture),
_ => throw new JsonException($"Unexpected token {reader.TokenType} when reading long."),
};
}
public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));
}
}
public sealed class JsonNullableLongAsStringConverter : JsonConverter<long?>
{
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.Null => null,
JsonTokenType.Number => reader.GetInt64(),
JsonTokenType.String => long.Parse(reader.GetString()!, NumberStyles.Integer, CultureInfo.InvariantCulture),
_ => throw new JsonException($"Unexpected token {reader.TokenType} when reading long?."),
};
}
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
return;
}
writer.WriteStringValue(value.Value.ToString(CultureInfo.InvariantCulture));
}
}
@@ -0,0 +1,106 @@
using System.Globalization;
using System.Text.RegularExpressions;
using WmsLite.Api.Enums;
namespace WmsLite.Api.Common;
public static class LocationShelfBatchHelper
{
public const int MaxGeneratedLocationsPerRequest = 10_000;
public const int MaxLocationCodeLength = 64;
public const int MaxLocationNameLength = 256;
/// <summary>占位符正则:Label 或 Label:格式(如 Row:D2)。</summary>
private static readonly Regex PlaceholderRegex = new(
@"\{(\w+)(?::([^}]+))?\}",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
public static int[] RowsForShelf(ShelfDepthKind kind) =>
kind switch
{
ShelfDepthKind.SingleShallowTwoRows => new[] { 1, 2 },
ShelfDepthKind.SingleSideDoubleTwoRows => new[] { 1, 2 },
ShelfDepthKind.DoubleDeepFourRows => new[] { 1, 2, 3, 4 },
_ => throw new BusinessException($"无效的伸位类型:{kind}。")
};
public static bool ResolveIsOuter(ShelfDepthKind kind, int rowNo) =>
kind switch
{
ShelfDepthKind.SingleShallowTwoRows => false,
ShelfDepthKind.SingleSideDoubleTwoRows => rowNo != 1,
ShelfDepthKind.DoubleDeepFourRows => rowNo is not (1 or 4),
_ => false
};
public static string FormatTemplate(
string template,
string warehouseCode,
string areaCode,
string zoneCode,
string aisleCode,
int row,
int column,
int layer)
{
return PlaceholderRegex.Replace(template, m =>
{
var token = m.Groups[1].Value;
var format = m.Groups[2].Success ? m.Groups[2].Value : null;
return token.ToUpperInvariant() switch
{
"WAREHOUSE" when format is null => warehouseCode,
"WAREHOUSE" => string.IsNullOrEmpty(format)
? warehouseCode
: FormatStringWithOptionalFormat(warehouseCode, format),
"AREA" when format is null => areaCode,
"AREA" => FormatStringWithOptionalFormat(areaCode, format!),
"ZONE" when format is null => zoneCode,
"ZONE" => FormatStringWithOptionalFormat(zoneCode, format),
"AISLE" when format is null => aisleCode,
"AISLE" => FormatStringWithOptionalFormat(aisleCode, format!),
"ROW" => FormatIntegerToken(row, format),
"COL" => FormatIntegerToken(column, format),
"LAYER" => FormatIntegerToken(layer, format),
_ => throw new BusinessException($"模板中存在未知占位符:{{{token}}}。")
};
});
}
private static string FormatIntegerToken(int value, string? format)
{
if (string.IsNullOrEmpty(format))
{
return value.ToString(CultureInfo.InvariantCulture);
}
try
{
return value.ToString(format, CultureInfo.InvariantCulture);
}
catch (FormatException ex)
{
throw new BusinessException($"占位符的数字格式无效:{format}。{ex.Message}");
}
}
private static string FormatStringWithOptionalFormat(string value, string format)
{
try
{
return string.Format(CultureInfo.InvariantCulture, $"{{0:{format}}}", value);
}
catch (FormatException)
{
return value;
}
}
}
+14
View File
@@ -0,0 +1,14 @@
using System.Collections.Generic;
namespace WmsLite.Api.Common;
public class PagedResult<T>
{
public int PageIndex { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
public List<T> Items { get; set; } = new();
}
@@ -0,0 +1,280 @@
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;
}
}
}