Compare commits
19
Commits
58abbb5b4f
...
模块暂未改成插件
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86ee692a04 | ||
|
|
53a4887d35 | ||
|
|
d0f9f00b76 | ||
|
|
d6cb5b966b | ||
|
|
fdc9b9e36d | ||
|
|
f1fa0401c2 | ||
|
|
08757d15e4 | ||
|
|
ecba3b7ee6 | ||
|
|
db4f030c17 | ||
|
|
2f406c840f | ||
|
|
707eb5664a | ||
|
|
c7fb447034 | ||
|
|
03dd9b8f6b | ||
|
|
c732ecb1d2 | ||
|
|
0e1620c1f9 | ||
|
|
75d0e85218 | ||
|
|
f2caec6083 | ||
|
|
8526e5e0d2 | ||
|
|
f84c4c1949 |
No files matched your search
@@ -1,6 +1,6 @@
|
|||||||
|
|
||||||
using MAX.Core.DependencyInjection;
|
using MAX.Core.DependencyInjection;
|
||||||
using MAX.Core.Infrastructure;
|
using MAX.Core.Interfaces;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
namespace MAX.Core.DependencyInjection;
|
using MAX.Core.Interfaces;
|
||||||
|
|
||||||
|
namespace MAX.Core.DependencyInjection;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 依赖注册器:把当前模块的服务注册到 <see cref="IServiceRegistrar"/>。
|
/// 依赖注册器:把当前模块的服务注册到 <see cref="IServiceRegistrar"/>。
|
||||||
/// 底层使用哪个容器由宿主项目决定,MAX.Core 不引用任何容器。
|
/// 底层使用哪个容器由宿主项目决定,MAX.Core 不引用任何容器。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IDependencyRegistrar
|
public interface IDependencyRegistrar: IPriority
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 注册服务
|
/// 注册服务
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
namespace MAX.Core.Interfaces;
|
||||||
|
|
||||||
|
public interface IPriority
|
||||||
|
{
|
||||||
|
/// <summary> 优先级(优先级越高越先执行) </summary>
|
||||||
|
int Priority { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class IntPriority
|
||||||
|
{
|
||||||
|
public const int Highest = 5000;
|
||||||
|
|
||||||
|
public const int VeryHigh = 4000;
|
||||||
|
|
||||||
|
public const int Higher = 3000;
|
||||||
|
|
||||||
|
public const int High = 2000;
|
||||||
|
|
||||||
|
public const int AboveNormal = 1000;
|
||||||
|
|
||||||
|
public const int Normal = 0;
|
||||||
|
|
||||||
|
public const int BelowNormal = -1000;
|
||||||
|
|
||||||
|
public const int Low = -2000;
|
||||||
|
|
||||||
|
public const int Lower = -3000;
|
||||||
|
|
||||||
|
public const int VeryLow = -4000;
|
||||||
|
|
||||||
|
public const int Lowest = -5000;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,18 +1,19 @@
|
|||||||
using MAX.Core.DependencyInjection;
|
using MAX.Core.DependencyInjection;
|
||||||
|
using System;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace MAX.Core.Infrastructure;
|
namespace MAX.Core.Interfaces;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启动器:实现 <see cref="IDependencyRegistrar"/>,由宿主项目统一发现并按 <see cref="Priority"/> 排序执行。
|
/// 启动器:实现 <see cref="IDependencyRegistrar"/>,由宿主项目统一发现并按 <see cref="Priority"/> 排序执行。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IStartup : IDependencyRegistrar
|
public interface IStartup : IDependencyRegistrar
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 优先级(优先级越高越先执行)
|
|
||||||
/// </summary>
|
|
||||||
int Priority { get; }
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 初始化
|
/// 初始化
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void Initialize();
|
void Initialize();
|
||||||
|
|
||||||
|
void Start(IServiceProvider serviceProvider);
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
|
||||||
namespace MAX.Core.Infrastructure;
|
namespace MAX.Core.Interfaces;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 单例,需要在当前类中定义
|
/// 单例,需要在当前类中定义
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using MAX.Core.Infrastructure;
|
|
||||||
|
|
||||||
namespace MAX.Core.Logger;
|
namespace MAX.Core.Logger;
|
||||||
|
|
||||||
/// <summary>自定义日志记录器接口</summary>
|
/// <summary>自定义日志记录器接口</summary>
|
||||||
|
|||||||
@@ -24,7 +24,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
using MAX.Core.DependencyInjection;
|
using MAX.Core.DependencyInjection;
|
||||||
using MAX.Core.Infrastructure;
|
using MAX.Core.Interfaces;
|
||||||
|
using System;
|
||||||
|
|
||||||
namespace MAX.Core;
|
namespace MAX.Core;
|
||||||
|
|
||||||
@@ -42,4 +43,9 @@ public class Startup : IStartup
|
|||||||
// 示例:恢复 LazyServiceProvider 后,可在这里注册为单例
|
// 示例:恢复 LazyServiceProvider 后,可在这里注册为单例
|
||||||
// registrar.RegisterSingleton<ILazyServiceProvider, LazyServiceProvider>();
|
// registrar.RegisterSingleton<ILazyServiceProvider, LazyServiceProvider>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Start(IServiceProvider serviceProvider)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Commons
|
||||||
|
{
|
||||||
|
public class AppException : Exception
|
||||||
|
{
|
||||||
|
public int Code { get; }
|
||||||
|
|
||||||
|
public AppException(string message, int code = ResultCode.BusinessError)
|
||||||
|
: base(message)
|
||||||
|
{
|
||||||
|
Code = code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Commons
|
||||||
|
{
|
||||||
|
public class GlobalExceptionFilter : IExceptionFilter
|
||||||
|
{
|
||||||
|
private readonly ILogger<GlobalExceptionFilter> _logger;
|
||||||
|
|
||||||
|
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnException(ExceptionContext context)
|
||||||
|
{
|
||||||
|
var traceId = context.HttpContext.TraceIdentifier;
|
||||||
|
|
||||||
|
var result = context.Exception switch
|
||||||
|
{
|
||||||
|
AppException be => ApiResult.Fail(be.Message, be.Code),
|
||||||
|
ValidationException ve => ApiResult.Fail(ve.Message, ResultCode.ValidationError),
|
||||||
|
UnauthorizedAccessException => ApiResult.Fail("未授权访问", ResultCode.Unauthorized),
|
||||||
|
_ => ApiResult.Fail("服务器内部错误", ResultCode.ServerError)
|
||||||
|
};
|
||||||
|
|
||||||
|
_logger.LogError(context.Exception, "请求异常 TraceId: {TraceId}", traceId);
|
||||||
|
|
||||||
|
context.Result = new ObjectResult(result)
|
||||||
|
{
|
||||||
|
StatusCode = 200 // 关键:HTTP状态码统一200,业务状态用Code表达
|
||||||
|
};
|
||||||
|
context.ExceptionHandled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Commons
|
||||||
|
{
|
||||||
|
public class PageData<T>
|
||||||
|
{
|
||||||
|
public long Total { get; set; }
|
||||||
|
public int PageIndex { get; set; }
|
||||||
|
public int PageSize { get; set; }
|
||||||
|
public int TotalPages => PageSize > 0 ? (int)Math.Ceiling((double)Total / PageSize) : 0;
|
||||||
|
public List<T> List { get; set; } = new();
|
||||||
|
|
||||||
|
public PageData() { }
|
||||||
|
|
||||||
|
public PageData(List<T> list, long total, int pageIndex, int pageSize)
|
||||||
|
{
|
||||||
|
List = list;
|
||||||
|
Total = total;
|
||||||
|
PageIndex = pageIndex;
|
||||||
|
PageSize = pageSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Commons
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 返回过滤
|
||||||
|
/// </summary>
|
||||||
|
public class UnifyResultFilter : IActionFilter
|
||||||
|
{
|
||||||
|
public void OnActionExecuted(ActionExecutedContext context)
|
||||||
|
{
|
||||||
|
if (context.Result is ObjectResult objResult)
|
||||||
|
{
|
||||||
|
if (objResult.Value is ApiResultBase)
|
||||||
|
{
|
||||||
|
objResult.StatusCode = 200;
|
||||||
|
objResult.DeclaredType = objResult.Value.GetType();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 非成功响应交由状态码中间件处理,避免先包装成业务成功。
|
||||||
|
var statusCode = objResult.StatusCode ?? 200;
|
||||||
|
if (statusCode >= 200 && statusCode < 300)
|
||||||
|
{
|
||||||
|
var apiResult = ApiResult<object>.Ok(objResult.Value);
|
||||||
|
|
||||||
|
objResult.Value = apiResult;
|
||||||
|
objResult.DeclaredType = null;
|
||||||
|
objResult.StatusCode = 200;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (context.Result is EmptyResult || context.Result is NoContentResult)
|
||||||
|
{
|
||||||
|
context.Result = new ObjectResult(ApiResult.Ok()) { StatusCode = 200 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnActionExecuting(ActionExecutingContext context) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.IO;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Commons
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 统一状态码中间件
|
||||||
|
/// 统一返回200 固定格式
|
||||||
|
/// </summary>
|
||||||
|
internal class UnifyStatusCodeMiddleware
|
||||||
|
{
|
||||||
|
|
||||||
|
private readonly RequestDelegate _next;
|
||||||
|
private readonly ILogger<UnifyStatusCodeMiddleware> _logger;
|
||||||
|
|
||||||
|
// 静态复用,全局唯一的内存池管理器
|
||||||
|
private static readonly RecyclableMemoryStreamManager _streamManager = new();
|
||||||
|
|
||||||
|
// 需要直接透传、不做缓冲的 Content-Type 前缀
|
||||||
|
private static readonly string[] _passthroughPrefixes =
|
||||||
|
{
|
||||||
|
"image/",
|
||||||
|
"audio/",
|
||||||
|
"video/",
|
||||||
|
"application/octet-stream",
|
||||||
|
"application/zip",
|
||||||
|
"application/pdf",
|
||||||
|
"application/x-msdownload",
|
||||||
|
"text/event-stream"
|
||||||
|
};
|
||||||
|
|
||||||
|
public UnifyStatusCodeMiddleware(RequestDelegate next, ILogger<UnifyStatusCodeMiddleware> logger)
|
||||||
|
{
|
||||||
|
_next = next;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InvokeAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
// 1. 只处理 /api 路径(按需调整或删除)
|
||||||
|
if (!context.Request.Path.StartsWithSegments("/api"))
|
||||||
|
{
|
||||||
|
await _next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 二进制 / 流式响应:不缓冲,直接透传
|
||||||
|
var accept = context.Request.Headers.Accept.ToString();
|
||||||
|
if (IsPassthroughByRequest(context) || IsPassthroughByAccept(accept))
|
||||||
|
{
|
||||||
|
await _next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var originalBody = context.Response.Body;
|
||||||
|
using var buffer = _streamManager.GetStream();
|
||||||
|
|
||||||
|
context.Response.Body = buffer;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _next(context);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 兜底:Filter 没抓到的异常
|
||||||
|
_logger.LogError(ex, "未处理异常: {Path}", context.Request.Path);
|
||||||
|
|
||||||
|
// 清空已写入的内容,准备返回 500 统一格式
|
||||||
|
buffer.SetLength(0);
|
||||||
|
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||||
|
}
|
||||||
|
|
||||||
|
var statusCode = context.Response.StatusCode;
|
||||||
|
var contentType = context.Response.ContentType ?? string.Empty;
|
||||||
|
|
||||||
|
// 3. 响应体如果本身就是二进制/流式,透传不处理
|
||||||
|
if (IsPassthroughByResponseContentType(contentType))
|
||||||
|
{
|
||||||
|
buffer.Position = 0;
|
||||||
|
context.Response.Body = originalBody;
|
||||||
|
await buffer.CopyToAsync(originalBody);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 2xx 且已有响应体:透传(已被 UnifyResultFilter 包装过,不再包一层)
|
||||||
|
if (statusCode >= 200 && statusCode < 300 && buffer.Length > 0)
|
||||||
|
{
|
||||||
|
buffer.Position = 0;
|
||||||
|
context.Response.Body = originalBody;
|
||||||
|
await buffer.CopyToAsync(originalBody);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 非 2xx:统一改写为 200 + ApiResult
|
||||||
|
var (code, msg) = MapStatusCode(statusCode);
|
||||||
|
|
||||||
|
// 如果是 2xx 但响应体为空(少见,例如 204),也当作成功
|
||||||
|
if (statusCode >= 200 && statusCode < 300)
|
||||||
|
{
|
||||||
|
code = (int)ResultCode.Success;
|
||||||
|
msg = "success";
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = statusCode >= 200 && statusCode < 300
|
||||||
|
? ApiResult.Ok()
|
||||||
|
: ApiResult.Fail(msg, code);
|
||||||
|
|
||||||
|
// 恢复原始流并写出
|
||||||
|
context.Response.Body = originalBody;
|
||||||
|
context.Response.StatusCode = StatusCodes.Status200OK;
|
||||||
|
context.Response.ContentType = "application/json; charset=utf-8";
|
||||||
|
context.Response.ContentLength = null;
|
||||||
|
|
||||||
|
// 清理可能存在的旧响应头
|
||||||
|
context.Response.Headers.Remove("WWW-Authenticate");
|
||||||
|
|
||||||
|
await context.Response.WriteAsJsonAsync(result, new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsPassthroughByRequest(HttpContext context)
|
||||||
|
{
|
||||||
|
// 上传大文件等场景,请求体大,避免缓冲
|
||||||
|
var contentLength = context.Request.ContentLength;
|
||||||
|
if (contentLength.HasValue && contentLength.Value > 1_000_000) // >1MB
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Range 请求(断点续传)不缓冲
|
||||||
|
if (context.Request.Headers.ContainsKey("Range"))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsPassthroughByAccept(string accept)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(accept)) return false;
|
||||||
|
|
||||||
|
foreach (var prefix in _passthroughPrefixes)
|
||||||
|
{
|
||||||
|
if (accept.Contains(prefix, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsPassthroughByResponseContentType(string contentType)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(contentType)) return false;
|
||||||
|
|
||||||
|
foreach (var prefix in _passthroughPrefixes)
|
||||||
|
{
|
||||||
|
if (contentType.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int code, string msg) MapStatusCode(int statusCode) => statusCode switch
|
||||||
|
{
|
||||||
|
400 => ((int)ResultCode.ValidationError, "请求参数错误"),
|
||||||
|
401 => ((int)ResultCode.Unauthorized, "未授权,请先登录"),
|
||||||
|
403 => ((int)ResultCode.Forbidden, "禁止访问"),
|
||||||
|
404 => ((int)ResultCode.NotFound, "资源不存在"),
|
||||||
|
405 => ((int)ResultCode.Fail, "请求方法不允许"),
|
||||||
|
429 => ((int)ResultCode.Fail, "请求过于频繁"),
|
||||||
|
500 => ((int)ResultCode.ServerError, "服务器内部错误"),
|
||||||
|
502 => ((int)ResultCode.ServerError, "网关错误"),
|
||||||
|
503 => ((int)ResultCode.ServerError, "服务暂不可用"),
|
||||||
|
504 => ((int)ResultCode.ServerError, "网关超时"),
|
||||||
|
_ => ((int)ResultCode.Fail, $"请求失败({statusCode})")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Commons
|
||||||
|
{
|
||||||
|
public class UnsupportedMediaTypeHandlingMiddleware
|
||||||
|
{
|
||||||
|
private readonly RequestDelegate _next;
|
||||||
|
|
||||||
|
public UnsupportedMediaTypeHandlingMiddleware(RequestDelegate next)
|
||||||
|
{
|
||||||
|
_next = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InvokeAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
// 用一个内存流替换原始的Response.Body,方便判断状态码后决定是否要改写
|
||||||
|
var originalBodyStream = context.Response.Body;
|
||||||
|
using var memoryStream = new MemoryStream();
|
||||||
|
context.Response.Body = memoryStream;
|
||||||
|
|
||||||
|
await _next(context);
|
||||||
|
|
||||||
|
if (context.Response.StatusCode == StatusCodes.Status415UnsupportedMediaType)
|
||||||
|
{
|
||||||
|
var result = ApiResult.Fail("请求参数格式不正确", ResultCode.ValidationError);
|
||||||
|
|
||||||
|
var json = JsonSerializer.Serialize(result);
|
||||||
|
var bytes = Encoding.UTF8.GetBytes(json);
|
||||||
|
|
||||||
|
context.Response.Clear();
|
||||||
|
context.Response.StatusCode = StatusCodes.Status200OK; // 统一成200,和其他接口一致
|
||||||
|
context.Response.ContentType = "application/json; charset=utf-8";
|
||||||
|
context.Response.ContentLength = bytes.Length;
|
||||||
|
|
||||||
|
await context.Response.Body.WriteAsync(bytes);
|
||||||
|
await context.Response.Body.FlushAsync(originalBodyStream is null ? default : default);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 非415的情况,把内存流内容原样写回真正的Response.Body
|
||||||
|
memoryStream.Seek(0, SeekOrigin.Begin);
|
||||||
|
await memoryStream.CopyToAsync(originalBodyStream);
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Response.Body = originalBodyStream;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -4,7 +4,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace StoreHub.Framework.DependencyInjection
|
namespace MAX.Framework.DependencyInjection
|
||||||
{
|
{
|
||||||
public static class FreeSqlDB
|
public static class FreeSqlDB
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
//using MAX.Framework.Interfaces;
|
||||||
|
//using Microsoft.AspNetCore.Builder;
|
||||||
|
//using Microsoft.Extensions.Configuration;
|
||||||
|
//using Microsoft.Extensions.Configuration.Json;
|
||||||
|
//using Microsoft.Extensions.DependencyInjection;
|
||||||
|
//using System.Reflection;
|
||||||
|
|
||||||
|
//namespace MAX.Framework.DependencyInjection
|
||||||
|
//{
|
||||||
|
// /// <summary>
|
||||||
|
// /// 宿主(Program.cs)入口:模块两阶段装配 + 模块自己的配置文件。
|
||||||
|
// /// <code>
|
||||||
|
// /// var builder = WebApplication.CreateBuilder(args);
|
||||||
|
// /// builder.AddStoreHub(); // 阶段一:加载各模块配置文件 + 自动执行所有 IModule.AddModule
|
||||||
|
// ///
|
||||||
|
// /// var app = builder.Build();
|
||||||
|
// /// // ... 宿主自己的中间件、认证、端点 ...
|
||||||
|
// /// app.UseStoreHubModules(); // 阶段二:管道装配(自动执行所有 IModule.UseModule)
|
||||||
|
// /// app.Run();
|
||||||
|
// /// </code>
|
||||||
|
// /// </summary>
|
||||||
|
// public static class HostBuilderExtensions
|
||||||
|
// {
|
||||||
|
// /// <summary>
|
||||||
|
// /// 在 <see cref="WebApplicationBuilder"/> 上注册应用框架服务:
|
||||||
|
// /// <list type="number">
|
||||||
|
// /// <item>发现所有 <see cref="IModule"/>;</item>
|
||||||
|
// /// <item>把每个模块声明的 <see cref="IModule.ConfigurationFile"/> 并入宿主配置树(宿主 appsettings.json 不需要放模块的配置);</item>
|
||||||
|
// /// <item>再执行 <c>builder.Services.AddStoreHub(builder.Configuration, builder.Environment)</c>。</item>
|
||||||
|
// /// </list>
|
||||||
|
// /// </summary>
|
||||||
|
// public static WebApplicationBuilder AddStore(this WebApplicationBuilder builder)
|
||||||
|
// {
|
||||||
|
// IEnumerable<Assembly> assemblies = ServiceCollectionExtensions.GetApplicationAssemblies();
|
||||||
|
|
||||||
|
// // 同一个类可能同时实现 IStartup 与 IModule,这里缓存实例,保证后面两个阶段拿到的是同一个对象
|
||||||
|
// Dictionary<Type, object> instances = [];
|
||||||
|
// ModuleRegistry modules = ServiceCollectionExtensions.DiscoverModules(assemblies, instances);
|
||||||
|
|
||||||
|
// // 必须在跑 AddModule 之前并入,模块注册时才读得到自己的配置节
|
||||||
|
// foreach (IModule module in modules.Modules)
|
||||||
|
// {
|
||||||
|
// AddModuleConfigurationFile(builder.Configuration, module);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// builder.Services.AddStoreHubCore(assemblies, modules, instances, builder.Configuration, builder.Environment);
|
||||||
|
// return builder;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// /// <summary>
|
||||||
|
// /// 执行所有模块的管道阶段(<see cref="IModule.UseModule"/>):注册中间件、看板、Map 端点等。
|
||||||
|
// /// </summary>
|
||||||
|
// public static WebApplication UseStoreHubModules(this WebApplication app)
|
||||||
|
// {
|
||||||
|
// // 宿主没调用过 AddStoreHub() 时容器里没有注册表,直接返回即可
|
||||||
|
// ModuleRegistry? registry = app.Services.GetService<ModuleRegistry>();
|
||||||
|
// if (registry is null)
|
||||||
|
// {
|
||||||
|
// return app;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// foreach (IModule module in registry.Modules)
|
||||||
|
// {
|
||||||
|
// try
|
||||||
|
// {
|
||||||
|
// module.UseModule(app);
|
||||||
|
// }
|
||||||
|
// catch (Exception ex)
|
||||||
|
// {
|
||||||
|
// throw new InvalidOperationException($"模块 {module.GetType().FullName} 的 UseModule 执行失败。", ex);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return app;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// /// <summary>
|
||||||
|
// /// 把模块自己的配置文件并进宿主配置:插在 appsettings*.json 之后、环境变量/命令行之前,
|
||||||
|
// /// 这样模块配置能覆盖宿主 appsettings.json,同时仍然允许用环境变量/命令行覆盖它。
|
||||||
|
// /// </summary>
|
||||||
|
// private static void AddModuleConfigurationFile(IConfigurationBuilder configuration, IModule module)
|
||||||
|
// {
|
||||||
|
// string? fileName = module.ConfigurationFile;
|
||||||
|
// if (string.IsNullOrWhiteSpace(fileName))
|
||||||
|
// {
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// string path = Path.IsPathRooted(fileName)
|
||||||
|
// ? fileName
|
||||||
|
// : Path.Combine(AppContext.BaseDirectory, fileName);
|
||||||
|
|
||||||
|
// JsonConfigurationSource source = new()
|
||||||
|
// {
|
||||||
|
// Path = path,
|
||||||
|
// Optional = true, // 文件不存在时不报错(模块没配就是没有)
|
||||||
|
// ReloadOnChange = true // 允许改配置不重启(与 appsettings.json 行为一致)
|
||||||
|
// };
|
||||||
|
// source.ResolveFileProvider();
|
||||||
|
|
||||||
|
// IList<IConfigurationSource> sources = configuration.Sources;
|
||||||
|
// int index = sources.Count;
|
||||||
|
|
||||||
|
// // 找到最后一个 appsettings*.json,插到它后面
|
||||||
|
// for (int i = sources.Count - 1; i >= 0; i--)
|
||||||
|
// {
|
||||||
|
// if (sources[i] is FileConfigurationSource file
|
||||||
|
// && Path.GetFileName(file.Path).StartsWith("appsettings", StringComparison.OrdinalIgnoreCase))
|
||||||
|
// {
|
||||||
|
// index = i + 1;
|
||||||
|
// break;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// sources.Insert(index, source);
|
||||||
|
|
||||||
|
// if (configuration is IConfigurationRoot root)
|
||||||
|
// {
|
||||||
|
// root.Reload();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//}
|
||||||
+7
-7
@@ -1,15 +1,15 @@
|
|||||||
using Asp.Versioning.OpenApi;
|
using Asp.Versioning.OpenApi;
|
||||||
|
using MAX.Framework.Security;
|
||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using Microsoft.OpenApi;
|
using Microsoft.OpenApi;
|
||||||
using StoreHub.Framework.Security;
|
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace StoreHub.Framework.DependencyInjection;
|
namespace MAX.Framework.DependencyInjection;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// JWT 认证服务注册入口(由宿主 Program.cs 调用)。
|
/// JWT 认证服务注册入口(由宿主 Program.cs 调用)。
|
||||||
@@ -21,7 +21,7 @@ public static class JwtServiceCollectionExtensions
|
|||||||
/// <list type="number">
|
/// <list type="number">
|
||||||
/// <item>绑定 <c>Jwt</c> 配置节到 <see cref="JwtOptions"/>,并在启动时校验签名密钥长度;</item>
|
/// <item>绑定 <c>Jwt</c> 配置节到 <see cref="JwtOptions"/>,并在启动时校验签名密钥长度;</item>
|
||||||
/// <item>注册 <see cref="ITokenService"/>(令牌生成/校验)与 <see cref="ICurrentUser"/>(当前用户访问器);</item>
|
/// <item>注册 <see cref="ITokenService"/>(令牌生成/校验)与 <see cref="ICurrentUser"/>(当前用户访问器);</item>
|
||||||
/// <item>注册 <see cref="JwtBearerDefaults"/> 认证,认证失败/授权失败统一返回 <see cref="StoreHub.Framework.Commons.ApiResult{T}"/> 格式;</item>
|
/// <item>注册 <see cref="JwtBearerDefaults"/> 认证,认证失败/授权失败统一返回 <see cref="Dtos.ApiResult{T}"/> 格式;</item>
|
||||||
/// <item>注册 <see cref="IOnlineUserStore"/>(基于 <c>IMemoryCache</c> 的在线会话存储):单点登录、在线人员查询、退出销毁;</item>
|
/// <item>注册 <see cref="IOnlineUserStore"/>(基于 <c>IMemoryCache</c> 的在线会话存储):单点登录、在线人员查询、退出销毁;</item>
|
||||||
/// <item>为 OpenAPI 文档声明 Bearer(JWT) 安全方案,并对标记了 [Authorize] 的接口声明需要携带令牌。</item>
|
/// <item>为 OpenAPI 文档声明 Bearer(JWT) 安全方案,并对标记了 [Authorize] 的接口声明需要携带令牌。</item>
|
||||||
/// </list>
|
/// </list>
|
||||||
@@ -68,12 +68,12 @@ public static class JwtServiceCollectionExtensions
|
|||||||
{
|
{
|
||||||
IOnlineUserStore onlineUserStore = context.HttpContext.RequestServices.GetRequiredService<IOnlineUserStore>();
|
IOnlineUserStore onlineUserStore = context.HttpContext.RequestServices.GetRequiredService<IOnlineUserStore>();
|
||||||
ClaimsPrincipal? principal = context.Principal;
|
ClaimsPrincipal? principal = context.Principal;
|
||||||
string? userIdValue = principal?.FindFirst(JwtClaimTypes.UserId)?.Value;
|
string? userName = principal?.FindFirst(JwtClaimTypes.UserName)?.Value;
|
||||||
string? jti = principal?.FindFirst(JwtClaimTypes.Jti)?.Value;
|
string? jti = principal?.FindFirst(JwtClaimTypes.Jti)?.Value;
|
||||||
|
|
||||||
if (!int.TryParse(userIdValue, out int userId)
|
if (string.IsNullOrWhiteSpace(userName)
|
||||||
|| string.IsNullOrWhiteSpace(jti)
|
|| string.IsNullOrWhiteSpace(jti)
|
||||||
|| !onlineUserStore.IsTokenActive(userId, jti))
|
|| !onlineUserStore.IsTokenActive(userName, jti))
|
||||||
{
|
{
|
||||||
context.Fail(new SecurityTokenException("登录已失效,请重新登录"));
|
context.Fail(new SecurityTokenException("登录已失效,请重新登录"));
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Serilog;
|
||||||
|
using Serilog.Debugging;
|
||||||
|
|
||||||
|
namespace MAX.Framework.DependencyInjection
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Serilog 日志接入:读取 appsettings.Serilog.json(文件缺失时回退到主配置里的 Serilog 节点),
|
||||||
|
/// 再把 Serilog 接入 ASP.NET Core 日志管线,使 ILogger<T> 与 Log 静态入口共用同一套 Sink。
|
||||||
|
/// 日志按等级分目录(logs/等级/日期.log)由 appsettings.Serilog.json 里的 File sink + rollingInterval 负责。
|
||||||
|
/// </summary>
|
||||||
|
public static class LoggerExtensions
|
||||||
|
{
|
||||||
|
/// <summary>Serilog 独立配置文件(构建/发布会复制到输出目录)。</summary>
|
||||||
|
private const string ConfigurationFileName = "appsettings.Serilog.json";
|
||||||
|
|
||||||
|
public static IHostApplicationBuilder AddLogger(this IHostApplicationBuilder host)
|
||||||
|
{
|
||||||
|
IConfigurationManager configuration = host.Configuration;
|
||||||
|
|
||||||
|
// Serilog 默认会静默吞掉配置错误(Sink 名写错、过滤器语法错误等),
|
||||||
|
// 开发环境把自诊断信息输出到控制台,避免再出现「配置了却没有日志」却查不到原因。
|
||||||
|
if (host.Environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
SelfLog.Enable(Console.Error.WriteLine);
|
||||||
|
}
|
||||||
|
|
||||||
|
string? configurationPath = ResolveConfigurationPath(host);
|
||||||
|
if (configurationPath is null)
|
||||||
|
{
|
||||||
|
// 不直接抛异常:允许把 Serilog 节点写进 appsettings.json,但必须显式提示,而不是静默降级成「无任何 Sink」。
|
||||||
|
Console.Error.WriteLine($"[Serilog] 未找到 {ConfigurationFileName},将使用主配置中的 Serilog 节点。");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
configuration.AddJsonFile(configurationPath, optional: false, reloadOnChange: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.Logger = new LoggerConfiguration()
|
||||||
|
.ReadFrom.Configuration(configuration)
|
||||||
|
.Enrich.FromLogContext()
|
||||||
|
.WriteTo.Console()
|
||||||
|
.CreateLogger();
|
||||||
|
|
||||||
|
// 接管 ASP.NET Core 日志管线:宿主日志与 ILogger<T> 统一写入 Log.Logger;
|
||||||
|
// dispose: true 让宿主停止时自动 CloseAndFlush,保证缓冲中的日志落盘。
|
||||||
|
host.Services.AddSerilog(Log.Logger, dispose: true);
|
||||||
|
|
||||||
|
return host;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 定位 Serilog 配置文件:支持绝对路径,其余情况依次在内容根目录(开发时即项目目录)与程序输出目录中查找。
|
||||||
|
/// </summary>
|
||||||
|
private static string? ResolveConfigurationPath(IHostApplicationBuilder host)
|
||||||
|
{
|
||||||
|
if (Path.IsPathRooted(ConfigurationFileName))
|
||||||
|
{
|
||||||
|
return File.Exists(ConfigurationFileName) ? ConfigurationFileName : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
string[] candidates =
|
||||||
|
[
|
||||||
|
Path.Combine(host.Environment.ContentRootPath, ConfigurationFileName),
|
||||||
|
Path.Combine(AppContext.BaseDirectory, ConfigurationFileName),
|
||||||
|
];
|
||||||
|
|
||||||
|
return candidates.FirstOrDefault(File.Exists);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Core.Interfaces;
|
||||||
|
using MAX.Core.Logger;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using MAX.Framework.Interfaces;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Win32;
|
||||||
|
using System.Configuration;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace MAX.Framework.DependencyInjection
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// IOC 注册入口(由宿主 Program.cs 调用)
|
||||||
|
/// </summary>
|
||||||
|
public static class ServiceCollectionExtensions
|
||||||
|
{
|
||||||
|
private static readonly Type[] DependencyMarkers =
|
||||||
|
[
|
||||||
|
typeof(ISingletonDependency),
|
||||||
|
typeof(IScopedDependency),
|
||||||
|
typeof(ITransientDependency),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 添加框架注册
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddStore(this IHostApplicationBuilder host)
|
||||||
|
{
|
||||||
|
host.AddLogger();
|
||||||
|
//host.Services.AddSingleton<ILoggerFacade>(NLogger.Instance);//注册log
|
||||||
|
|
||||||
|
IEnumerable<Assembly> assemblies = GetApplicationAssemblies();
|
||||||
|
// 同一个类可能同时实现 IStartup 与 IModule,这里缓存实例,保证两个阶段拿到的是同一个对象
|
||||||
|
Dictionary<Type, object> instances = [];
|
||||||
|
return AddStoreCore(host, assemblies, instances);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 注册应用服务的公共实现:宿主入口(<c>builder.AddStoreHub()</c>)与 <see cref="IServiceCollection"/> 入口共用。
|
||||||
|
/// </summary>
|
||||||
|
internal static IServiceCollection AddStoreCore(
|
||||||
|
IHostApplicationBuilder host,
|
||||||
|
IEnumerable<Assembly> assemblies,
|
||||||
|
IDictionary<Type, object> instances)
|
||||||
|
{
|
||||||
|
RegisterDependencyMarkers(host.Services, assemblies);
|
||||||
|
|
||||||
|
RunModules(host, assemblies, instances);
|
||||||
|
|
||||||
|
RunStartups(host.Services, assemblies, instances);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
host.Services.AddControllers(options =>
|
||||||
|
{
|
||||||
|
options.Filters.Add<GlobalExceptionFilter>();
|
||||||
|
options.Filters.Add<UnifyResultFilter>();
|
||||||
|
}).ConfigureApiBehaviorOptions(options =>
|
||||||
|
{
|
||||||
|
options.InvalidModelStateResponseFactory = context =>
|
||||||
|
{
|
||||||
|
// 取出所有校验错误信息,拼成一个字符串(或者只取第一个)
|
||||||
|
var errors = context.ModelState
|
||||||
|
.Where(e => e.Value?.Errors.Count > 0)
|
||||||
|
.SelectMany(e => e.Value!.Errors.Select(err => err.ErrorMessage))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var msg = string.Join("; ", errors);
|
||||||
|
|
||||||
|
var result = ApiResult.Fail(msg, ResultCode.ValidationError);
|
||||||
|
|
||||||
|
return new ObjectResult(result)
|
||||||
|
{
|
||||||
|
StatusCode = 200 // 和其他接口保持一致,用Code表达失败,而不是HTTP 400
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
});
|
||||||
|
return host.Services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 自动注册标记接口(ISingletonDependency / IScopedDependency / ITransientDependency)的实现类型
|
||||||
|
/// </summary>
|
||||||
|
private static void RegisterDependencyMarkers(IServiceCollection services, IEnumerable<Assembly> assemblies)
|
||||||
|
{
|
||||||
|
foreach (Type type in GetConcreteTypes(assemblies))
|
||||||
|
{
|
||||||
|
Debug.WriteLine(type.Namespace);
|
||||||
|
Type? marker = DependencyMarkers.FirstOrDefault(m => m.IsAssignableFrom(type));
|
||||||
|
if (marker is null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ServiceLifetime lifetime = marker == typeof(ISingletonDependency) ? ServiceLifetime.Singleton
|
||||||
|
: marker == typeof(IScopedDependency) ? ServiceLifetime.Scoped
|
||||||
|
: ServiceLifetime.Transient;
|
||||||
|
|
||||||
|
// 注册为自身
|
||||||
|
services.Add(new ServiceDescriptor(type, type, lifetime));
|
||||||
|
|
||||||
|
// 注册为实现的接口(排除标记接口与系统接口)
|
||||||
|
foreach (Type iface in type.GetInterfaces())
|
||||||
|
{
|
||||||
|
if (DependencyMarkers.Contains(iface) || IsSystemInterface(iface))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
services.Add(new ServiceDescriptor(iface, type, lifetime));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static IEnumerable<IStartup> Startups = [];
|
||||||
|
/// <summary>
|
||||||
|
/// 发现所有 <see cref="IStartup"/> 实现,按 <see cref="IStartup.Priority"/> 降序执行
|
||||||
|
/// </summary>
|
||||||
|
private static void RunStartups(IServiceCollection services, IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances)
|
||||||
|
{
|
||||||
|
IServiceRegistrar registrar = new ServiceRegistrarProxy(services);
|
||||||
|
Startups = CreateInstances<IStartup>(assemblies, instances).OrderByDescending(s => s.Priority);
|
||||||
|
foreach (IStartup startup in Startups)
|
||||||
|
{
|
||||||
|
startup.Initialize();
|
||||||
|
startup.Register(registrar);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<IModule> Modules = [];
|
||||||
|
/// <summary>
|
||||||
|
/// 执行所有模块的服务注册阶段(<see cref="IModule.AddModule"/>)
|
||||||
|
/// </summary>
|
||||||
|
private static void RunModules(IHostApplicationBuilder host, IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances)
|
||||||
|
{
|
||||||
|
Modules = CreateInstances<IModule>(assemblies, instances).OrderByDescending(s => s.Priority);
|
||||||
|
foreach (IModule module in Modules)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
module.AddModule(host);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 带上模块名,避免只看到一个没有上下文的异常
|
||||||
|
throw new InvalidOperationException($"模块 {module.GetType().FullName} 的 AddModule 执行失败。", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 反射创建(或复用)所有实现 <typeparamref name="T"/> 的具体类型实例
|
||||||
|
/// </summary>
|
||||||
|
private static IEnumerable<T> CreateInstances<T>(IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances) where T : class
|
||||||
|
{
|
||||||
|
foreach (Type type in GetConcreteTypes(assemblies).Where(t => typeof(T).IsAssignableFrom(t)))
|
||||||
|
{
|
||||||
|
if (!instances.TryGetValue(type, out object? instance))
|
||||||
|
{
|
||||||
|
instance = Activator.CreateInstance(type, true)
|
||||||
|
?? throw new InvalidOperationException($"无法创建 {type.FullName} 的实例(需要有参数量为 0 的构造函数)。");
|
||||||
|
instances[type] = instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return (T)instance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<Type> GetConcreteTypes(IEnumerable<Assembly> assemblies)
|
||||||
|
{
|
||||||
|
return assemblies
|
||||||
|
.SelectMany(SafeGetTypes)
|
||||||
|
.Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericTypeDefinition);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<Type> SafeGetTypes(Assembly assembly)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return assembly.GetTypes();
|
||||||
|
}
|
||||||
|
catch (ReflectionTypeLoadException ex)
|
||||||
|
{
|
||||||
|
return ex.Types.OfType<Type>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用程序集(模块、Startup 都从这里发现)
|
||||||
|
/// </summary>
|
||||||
|
internal static IEnumerable<Assembly> GetApplicationAssemblies()
|
||||||
|
{
|
||||||
|
// 使用 AppTypeFinder:扫描应用输出目录 + 已加载程序集,
|
||||||
|
return StoreAppTypeFinder.Current.GetAssemblies();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSystemInterface(Type type)
|
||||||
|
{
|
||||||
|
return type.Namespace is null
|
||||||
|
|| type.Namespace.StartsWith("System", StringComparison.Ordinal)
|
||||||
|
|| type.Namespace.StartsWith("Microsoft", StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static IApplicationBuilder UseStore(this IApplicationBuilder app)
|
||||||
|
{
|
||||||
|
app.UseMiddleware<UnifyStatusCodeMiddleware>();
|
||||||
|
foreach (IStartup startup in Startups)
|
||||||
|
{
|
||||||
|
startup.Start((app as IHost).Services);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (IModule module in Modules)
|
||||||
|
{
|
||||||
|
module.UseModule(app);
|
||||||
|
}
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
using MAX.Core.DependencyInjection;
|
using MAX.Core.DependencyInjection;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
namespace StoreHub.Framework.DependencyInjection
|
namespace MAX.Framework.DependencyInjection
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 将 <see cref="IServiceRegistrar"/> 适配到 Microsoft.Extensions.DependencyInjection
|
/// 将 <see cref="IServiceRegistrar"/> 适配到 Microsoft.Extensions.DependencyInjection
|
||||||
+4
-4
@@ -1,18 +1,18 @@
|
|||||||
using MAX.Core.Reflections;
|
using MAX.Core.Reflections;
|
||||||
|
|
||||||
namespace StoreHub.Framework.DependencyInjection
|
namespace MAX.Framework.DependencyInjection
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 本应用的类型查找器:在 AppTypeFinder 默认前缀(MAX. / Nexus.)之外,
|
/// 本应用的类型查找器:在 AppTypeFinder 默认前缀(MAX. / Nexus.)之外,
|
||||||
/// 增加 StoreHub、KJD 前缀,用于发现宿主和各业务模块的程序集。
|
/// 增加 StoreHub、KJD 前缀,用于发现宿主和各业务模块的程序集。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class StoreHubAppTypeFinder : AppTypeFinder
|
internal sealed class StoreAppTypeFinder : AppTypeFinder
|
||||||
{
|
{
|
||||||
public static StoreHubAppTypeFinder Current { get; } = new();
|
public static StoreAppTypeFinder Current { get; } = new();
|
||||||
|
|
||||||
protected override List<string> AvailablePrefix()
|
protected override List<string> AvailablePrefix()
|
||||||
{
|
{
|
||||||
return ["StoreHub"];
|
return ["Store"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Dtos
|
||||||
|
{
|
||||||
|
public static class ResultCode
|
||||||
|
{
|
||||||
|
public const int Success = 200;
|
||||||
|
public const int Fail = 500;
|
||||||
|
|
||||||
|
public const int Unauthorized = 401;
|
||||||
|
public const int Forbidden = 403;
|
||||||
|
public const int NotFound = 404;
|
||||||
|
/// <summary>
|
||||||
|
/// 参数校验失败
|
||||||
|
/// </summary>
|
||||||
|
public const int ValidationError = 1001;
|
||||||
|
/// <summary>
|
||||||
|
/// 业务逻辑异常
|
||||||
|
/// </summary>
|
||||||
|
public const int BusinessError = 2001;
|
||||||
|
/// <summary>
|
||||||
|
/// 服务器内部错误
|
||||||
|
/// </summary>
|
||||||
|
public const int ServerError = 5000;
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// 非泛型基类,用于统一处理
|
||||||
|
/// </summary>
|
||||||
|
public abstract class ApiResultBase
|
||||||
|
{
|
||||||
|
/// <summary>业务状态码</summary>
|
||||||
|
public int Code { get; init; } = ResultCode.Success;
|
||||||
|
|
||||||
|
/// <summary>提示信息</summary>
|
||||||
|
public string? Msg { get; init; }
|
||||||
|
|
||||||
|
/// <summary>请求是否成功</summary>
|
||||||
|
public bool Success => Code == ResultCode.Success;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 泛型响应
|
||||||
|
/// </summary>
|
||||||
|
public class ApiResult<T> : ApiResultBase
|
||||||
|
{
|
||||||
|
/// <summary>响应数据;失败时不应依赖该值,值类型默认值并非 null。</summary>
|
||||||
|
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
|
||||||
|
public T? Data { get; init; }
|
||||||
|
|
||||||
|
/// <summary>将无数据响应转换为当前数据类型,保留状态码和提示信息。</summary>
|
||||||
|
public static implicit operator ApiResult<T>(ApiResult result)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(result);
|
||||||
|
return new ApiResult<T> { Code = result.Code, Msg = result.Msg, Data = default };
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ApiResult<T> Ok(T data, string msg = "操作成功")
|
||||||
|
=> new ApiResult<T> { Code = ResultCode.Success, Data = data, Msg = msg };
|
||||||
|
|
||||||
|
public static ApiResult<T> Fail(string msg = "操作失败", int code = ResultCode.Fail, T? data = default)
|
||||||
|
{
|
||||||
|
ApiResult.ValidateFailureCode(code);
|
||||||
|
return new ApiResult<T> { Code = code, Msg = msg, Data = data };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 响应
|
||||||
|
/// </summary>
|
||||||
|
public class ApiResult : ApiResultBase
|
||||||
|
{
|
||||||
|
/// <summary>无数据响应仍输出 data: null,保持统一的响应字段。</summary>
|
||||||
|
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
|
||||||
|
public object? Data => null;
|
||||||
|
|
||||||
|
/// <summary>创建带数据的成功响应,自动推断数据类型。</summary>
|
||||||
|
public static ApiResult<T> Ok<T>(T data, string msg = "操作成功")
|
||||||
|
=> ApiResult<T>.Ok(data, msg);
|
||||||
|
|
||||||
|
/// <summary>创建带数据的失败响应,自动推断数据类型。</summary>
|
||||||
|
public static ApiResult<T> Fail<T>(string msg, T data, int code = ResultCode.Fail)
|
||||||
|
=> ApiResult<T>.Fail(msg, code, data);
|
||||||
|
|
||||||
|
public static ApiResult Ok()
|
||||||
|
=> new ApiResult { Code = ResultCode.Success, Msg = "操作成功" };
|
||||||
|
|
||||||
|
public static ApiResult Fail(string msg = "操作失败", int code = ResultCode.Fail)
|
||||||
|
{
|
||||||
|
ValidateFailureCode(code);
|
||||||
|
return new ApiResult { Code = code, Msg = msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void ValidateFailureCode(int code)
|
||||||
|
{
|
||||||
|
if (code == ResultCode.Success)
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(code), code, "失败响应不能使用成功状态码。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -4,7 +4,7 @@ using System.Linq;
|
|||||||
using System.Linq.Expressions;
|
using System.Linq.Expressions;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Helpers;
|
namespace MAX.Framework.Helpers;
|
||||||
|
|
||||||
public static class ObjectHelper
|
public static class ObjectHelper
|
||||||
{
|
{
|
||||||
+1
-1
@@ -3,7 +3,7 @@ using System;
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Helpers;
|
namespace MAX.Framework.Helpers;
|
||||||
|
|
||||||
public class WinCmdHelper
|
public class WinCmdHelper
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using MAX.Core.Interfaces;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
|
namespace MAX.Framework.Interfaces
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 模块实例由反射创建,因此实现类必须有无参构造函数。
|
||||||
|
/// </summary>
|
||||||
|
public interface IModule : IPriority
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 添加Module
|
||||||
|
/// </summary>
|
||||||
|
void AddModule(IHostApplicationBuilder host);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 管道装配阶段
|
||||||
|
/// </summary>
|
||||||
|
void UseModule(IApplicationBuilder app);
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
-5
@@ -8,10 +8,6 @@
|
|||||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\Core\MAX.Core\MAX.Core.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.2.1" />
|
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.2.1" />
|
||||||
<PackageReference Include="Asp.Versioning.OpenApi" Version="10.2.1" />
|
<PackageReference Include="Asp.Versioning.OpenApi" Version="10.2.1" />
|
||||||
@@ -19,8 +15,27 @@
|
|||||||
<PackageReference Include="FreeSql.Provider.MySql" Version="3.5.311" />
|
<PackageReference Include="FreeSql.Provider.MySql" Version="3.5.311" />
|
||||||
<PackageReference Include="FreeSql.Repository" Version="3.5.311" />
|
<PackageReference Include="FreeSql.Repository" Version="3.5.311" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
|
||||||
<PackageReference Include="NLog" Version="6.1.4" />
|
<PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="3.0.1" />
|
||||||
<PackageReference Include="Riok.Mapperly" Version="4.3.1" />
|
<PackageReference Include="Riok.Mapperly" Version="4.3.1" />
|
||||||
|
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
|
||||||
|
<PackageReference Include="Serilog.Filters.Expressions" Version="2.1.0" />
|
||||||
|
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||||
|
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\MAX.Core\MAX.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="Models\" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="appsettings.Serilog.json">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
+2
-12
@@ -1,8 +1,8 @@
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 从 <see cref="IHttpContextAccessor"/> 读取当前请求认证票据的默认实现。
|
/// 从 <see cref="IHttpContextAccessor"/> 读取当前请求认证票据的默认实现。
|
||||||
@@ -24,16 +24,6 @@ public class CurrentUser : ICurrentUser
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool IsAuthenticated => Principal?.Identity?.IsAuthenticated == true;
|
public bool IsAuthenticated => Principal?.Identity?.IsAuthenticated == true;
|
||||||
|
|
||||||
/// <inheritdoc />
|
|
||||||
public int? Id
|
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
string? value = GetClaimValue(JwtClaimTypes.UserId);
|
|
||||||
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) ? id : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public string? UserName => GetClaimValue(JwtClaimTypes.UserName);
|
public string? UserName => GetClaimValue(JwtClaimTypes.UserName);
|
||||||
|
|
||||||
+2
-7
@@ -1,6 +1,6 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 当前登录用户访问器:从当前请求的认证票据中读取用户信息。
|
/// 当前登录用户访问器:从当前请求的认证票据中读取用户信息。
|
||||||
@@ -12,11 +12,6 @@ public interface ICurrentUser
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
bool IsAuthenticated { get; }
|
bool IsAuthenticated { get; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 当前用户ID(未登录为 null)
|
|
||||||
/// </summary>
|
|
||||||
int? Id { get; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 当前登录账户名(未登录为 null)
|
/// 当前登录账户名(未登录为 null)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
+5
-5
@@ -1,4 +1,4 @@
|
|||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 在线用户会话存储:基于 <see cref="Microsoft.Extensions.Caching.Memory.IMemoryCache"/> 的进程内实现,
|
/// 在线用户会话存储:基于 <see cref="Microsoft.Extensions.Caching.Memory.IMemoryCache"/> 的进程内实现,
|
||||||
@@ -12,14 +12,14 @@ public interface IOnlineUserStore
|
|||||||
void SignIn(OnlineUserInfo info);
|
void SignIn(OnlineUserInfo info);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 判断指定用户、指定令牌会话是否仍然有效(未被退出、未被新登录顶替)。
|
/// 判断指定登录账户、指定令牌会话是否仍然有效(未被退出、未被新登录顶替)。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
bool IsTokenActive(int userId, string jti);
|
bool IsTokenActive(string userName, string jti);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 退出登录:销毁该用户的在线会话,令牌立即失效。
|
/// 退出登录:销毁该账户的在线会话,令牌立即失效。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void SignOut(int userId);
|
void SignOut(string userName);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取当前在线人员列表。
|
/// 获取当前在线人员列表。
|
||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 令牌生成结果
|
/// 令牌生成结果
|
||||||
@@ -18,9 +18,9 @@ public class TokenResult
|
|||||||
public string Token { get; set; } = string.Empty;
|
public string Token { get; set; } = string.Empty;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 过期时间(本地时间)
|
/// 有效时间(分钟)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public DateTime ExpiresAt { get; set; }
|
public uint ExpiresInMinutes { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
+4
-4
@@ -1,10 +1,10 @@
|
|||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using StoreHub.Framework.Commons;
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// JwtBearer 认证失败/授权失败时,统一返回 <see cref="ApiResult{T}"/> 格式的 JSON 响应。
|
/// JwtBearer 认证失败/授权失败时,统一返回 <see cref="ApiResult{T}"/> 格式的 JSON 响应。
|
||||||
@@ -38,7 +38,7 @@ internal static class JwtBearerResponseHandler
|
|||||||
httpContext.Response.StatusCode = statusCode;
|
httpContext.Response.StatusCode = statusCode;
|
||||||
httpContext.Response.ContentType = "application/json; charset=utf-8";
|
httpContext.Response.ContentType = "application/json; charset=utf-8";
|
||||||
|
|
||||||
string body = JsonSerializer.Serialize(ApiResult.Error(message, statusCode), JsonOptions);
|
string body = JsonSerializer.Serialize(ApiResult.Fail(message, statusCode), JsonOptions);
|
||||||
await httpContext.Response.WriteAsync(body, Encoding.UTF8);
|
await httpContext.Response.WriteAsync(body, Encoding.UTF8);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-5
@@ -1,14 +1,11 @@
|
|||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// JWT 自定义声明类型常量。
|
/// JWT 自定义声明类型常量。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class JwtClaimTypes
|
public static class JwtClaimTypes
|
||||||
{
|
{
|
||||||
/// <summary>用户ID</summary>
|
/// <summary>登录账户(唯一)</summary>
|
||||||
public const string UserId = "uid";
|
|
||||||
|
|
||||||
/// <summary>登录账户</summary>
|
|
||||||
public const string UserName = "user_name";
|
public const string UserName = "user_name";
|
||||||
|
|
||||||
/// <summary>用户昵称</summary>
|
/// <summary>用户昵称</summary>
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// JWT 配置选项,默认绑定配置节 <c>Jwt</c>。
|
/// JWT 配置选项,默认绑定配置节 <c>Jwt</c>。
|
||||||
+2
-5
@@ -1,14 +1,11 @@
|
|||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 在线用户会话信息(单点登录:同一用户仅保留一个有效会话)。
|
/// 在线用户会话信息(单点登录:同一用户仅保留一个有效会话)。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class OnlineUserInfo
|
public class OnlineUserInfo
|
||||||
{
|
{
|
||||||
/// <summary>用户ID</summary>
|
/// <summary>登录账户(唯一,作为会话键)</summary>
|
||||||
public int UserId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>登录账户</summary>
|
|
||||||
public string UserName { get; set; } = string.Empty;
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
/// <summary>用户昵称</summary>
|
/// <summary>用户昵称</summary>
|
||||||
+14
-14
@@ -1,7 +1,7 @@
|
|||||||
using Microsoft.Extensions.Caching.Memory;
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 基于 <see cref="IMemoryCache"/> 的在线用户会话存储。
|
/// 基于 <see cref="IMemoryCache"/> 的在线用户会话存储。
|
||||||
@@ -11,7 +11,7 @@ public class OnlineUserStore : IOnlineUserStore
|
|||||||
private const string CacheKeyPrefix = "online:user:";
|
private const string CacheKeyPrefix = "online:user:";
|
||||||
private readonly IMemoryCache _cache;
|
private readonly IMemoryCache _cache;
|
||||||
// 在线人员索引:IMemoryCache 不提供公共枚举 API,这里用字典维护便于查询在线列表
|
// 在线人员索引:IMemoryCache 不提供公共枚举 API,这里用字典维护便于查询在线列表
|
||||||
private readonly ConcurrentDictionary<int, OnlineUserInfo> _onlineIndex = new();
|
private readonly ConcurrentDictionary<string, OnlineUserInfo> _onlineIndex = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
public OnlineUserStore(IMemoryCache cache)
|
public OnlineUserStore(IMemoryCache cache)
|
||||||
{
|
{
|
||||||
@@ -23,33 +23,33 @@ public class OnlineUserStore : IOnlineUserStore
|
|||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(info);
|
ArgumentNullException.ThrowIfNull(info);
|
||||||
|
|
||||||
// 以 userId 为键覆盖写入:旧会话(jti)被顶替,实现单点登录
|
// 以登录账户为键覆盖写入:旧会话(jti)被顶替,实现单点登录
|
||||||
_cache.Set(GetKey(info.UserId), info, new MemoryCacheEntryOptions
|
_cache.Set(GetKey(info.UserName), info, new MemoryCacheEntryOptions
|
||||||
{
|
{
|
||||||
// 缓存条目与令牌同时过期,过期后自动失效
|
// 缓存条目与令牌同时过期,过期后自动失效
|
||||||
AbsoluteExpiration = info.ExpiresAt,
|
AbsoluteExpiration = info.ExpiresAt,
|
||||||
});
|
});
|
||||||
_onlineIndex[info.UserId] = info;
|
_onlineIndex[info.UserName] = info;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool IsTokenActive(int userId, string jti)
|
public bool IsTokenActive(string userName, string jti)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(jti))
|
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(jti))
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return _cache.TryGetValue(GetKey(userId), out OnlineUserInfo? info)
|
return _cache.TryGetValue(GetKey(userName), out OnlineUserInfo? info)
|
||||||
&& info is not null
|
&& info is not null
|
||||||
&& string.Equals(info.Jti, jti, StringComparison.Ordinal);
|
&& string.Equals(info.Jti, jti, StringComparison.Ordinal);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void SignOut(int userId)
|
public void SignOut(string userName)
|
||||||
{
|
{
|
||||||
_cache.Remove(GetKey(userId));
|
_cache.Remove(GetKey(userName));
|
||||||
_onlineIndex.TryRemove(userId, out _);
|
_onlineIndex.TryRemove(userName, out _);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@@ -57,7 +57,7 @@ public class OnlineUserStore : IOnlineUserStore
|
|||||||
{
|
{
|
||||||
DateTime now = DateTime.Now;
|
DateTime now = DateTime.Now;
|
||||||
List<OnlineUserInfo> result = [];
|
List<OnlineUserInfo> result = [];
|
||||||
foreach (KeyValuePair<int, OnlineUserInfo> pair in _onlineIndex)
|
foreach (KeyValuePair<string, OnlineUserInfo> pair in _onlineIndex)
|
||||||
{
|
{
|
||||||
if (pair.Value.ExpiresAt > now)
|
if (pair.Value.ExpiresAt > now)
|
||||||
{
|
{
|
||||||
@@ -75,6 +75,6 @@ public class OnlineUserStore : IOnlineUserStore
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public int Count => GetOnlineUsers().Count;
|
public int Count => GetOnlineUsers().Count;
|
||||||
|
|
||||||
private static string GetKey(int userId) => $"{CacheKeyPrefix}{userId}";
|
private static string GetKey(string userName) => $"{CacheKeyPrefix}{userName}";
|
||||||
}
|
}
|
||||||
|
|
||||||
+9
-10
@@ -1,10 +1,10 @@
|
|||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.IdentityModel.JsonWebTokens;
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace StoreHub.Framework.Security;
|
namespace MAX.Framework.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 基于 <see cref="JwtOptions"/> 的 JWT 令牌服务。
|
/// 基于 <see cref="JwtOptions"/> 的 JWT 令牌服务。
|
||||||
@@ -50,7 +50,7 @@ public class TokenService : ITokenService
|
|||||||
return new TokenResult
|
return new TokenResult
|
||||||
{
|
{
|
||||||
Token = token,
|
Token = token,
|
||||||
ExpiresAt = expires,
|
ExpiresInMinutes = (uint)_options.ExpiresMinutes,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,9 +74,9 @@ public class TokenService : ITokenService
|
|||||||
ClaimsPrincipal principal = new(result.ClaimsIdentity);
|
ClaimsPrincipal principal = new(result.ClaimsIdentity);
|
||||||
|
|
||||||
// 单点登录校验:会话必须仍然有效(未被退出、未被新登录顶替)
|
// 单点登录校验:会话必须仍然有效(未被退出、未被新登录顶替)
|
||||||
string? userIdValue = principal.FindFirst(JwtClaimTypes.UserId)?.Value;
|
string? userName = principal.FindFirst(JwtClaimTypes.UserName)?.Value;
|
||||||
string? jti = principal.FindFirst(JwtClaimTypes.Jti)?.Value;
|
string? jti = principal.FindFirst(JwtClaimTypes.Jti)?.Value;
|
||||||
if (!int.TryParse(userIdValue, out int userId) || string.IsNullOrWhiteSpace(jti) || !_onlineUserStore.IsTokenActive(userId, jti))
|
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(jti) || !_onlineUserStore.IsTokenActive(userName, jti))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -94,16 +94,15 @@ public class TokenService : ITokenService
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private void RegisterSession(IEnumerable<Claim> claims, string jti, DateTime loginTime, DateTime expiresAt)
|
private void RegisterSession(IEnumerable<Claim> claims, string jti, DateTime loginTime, DateTime expiresAt)
|
||||||
{
|
{
|
||||||
string? userIdValue = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserId)?.Value;
|
string? userName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserName)?.Value;
|
||||||
if (!int.TryParse(userIdValue, out int userId))
|
if (string.IsNullOrWhiteSpace(userName))
|
||||||
{
|
{
|
||||||
return; // 未携带用户ID的令牌不纳入在线会话管理
|
return; // 未携带登录账户的令牌不纳入在线会话管理
|
||||||
}
|
}
|
||||||
|
|
||||||
_onlineUserStore.SignIn(new OnlineUserInfo
|
_onlineUserStore.SignIn(new OnlineUserInfo
|
||||||
{
|
{
|
||||||
UserId = userId,
|
UserName = userName,
|
||||||
UserName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserName)?.Value ?? string.Empty,
|
|
||||||
NickName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.NickName)?.Value ?? string.Empty,
|
NickName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.NickName)?.Value ?? string.Empty,
|
||||||
Jti = jti,
|
Jti = jti,
|
||||||
LoginTime = loginTime,
|
LoginTime = loginTime,
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using FreeSql;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Core.Interfaces;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace MAX.Framework
|
||||||
|
{
|
||||||
|
public class Startup : IStartup
|
||||||
|
{
|
||||||
|
public int Priority => IntPriority.Highest;
|
||||||
|
|
||||||
|
public void Initialize()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Register(IServiceRegistrar registrar)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start(IServiceProvider serviceProvider)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
{
|
||||||
|
"Serilog": {
|
||||||
|
"Using": [
|
||||||
|
"Serilog.Sinks.Console",
|
||||||
|
"Serilog.Sinks.File",
|
||||||
|
"Serilog.Filters.Expressions"
|
||||||
|
],
|
||||||
|
"MinimumLevel": {
|
||||||
|
"Default": "Debug",
|
||||||
|
"Override": {
|
||||||
|
"Microsoft": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning",
|
||||||
|
"System": "Warning",
|
||||||
|
"Hangfire": "Information"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Enrich": [
|
||||||
|
"FromLogContext"
|
||||||
|
],
|
||||||
|
"Properties": {
|
||||||
|
"Application": "MyAspNetCore"
|
||||||
|
},
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "Logger",
|
||||||
|
"Args": {
|
||||||
|
"configureLogger": {
|
||||||
|
"Filter": [
|
||||||
|
{ "Name": "ByIncludingOnly", "Args": { "expression": "@Level = 'Debug'" } }
|
||||||
|
],
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "Logs/Debug/.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
||||||
|
"retainedFileCountLimit": 365,
|
||||||
|
"fileSizeLimitBytes": 104857600,
|
||||||
|
"rollOnFileSizeLimit": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "Logger",
|
||||||
|
"Args": {
|
||||||
|
"configureLogger": {
|
||||||
|
"Filter": [
|
||||||
|
{ "Name": "ByIncludingOnly", "Args": { "expression": "@Level = 'Information'" } }
|
||||||
|
],
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "Logs/Info/.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
||||||
|
"retainedFileCountLimit": 365,
|
||||||
|
"fileSizeLimitBytes": 104857600,
|
||||||
|
"rollOnFileSizeLimit": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "Logger",
|
||||||
|
"Args": {
|
||||||
|
"configureLogger": {
|
||||||
|
"Filter": [
|
||||||
|
{ "Name": "ByIncludingOnly", "Args": { "expression": "@Level = 'Warning'" } }
|
||||||
|
],
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "Logs/Warning/.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
||||||
|
"retainedFileCountLimit": 365,
|
||||||
|
"fileSizeLimitBytes": 104857600,
|
||||||
|
"rollOnFileSizeLimit": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "Logger",
|
||||||
|
"Args": {
|
||||||
|
"configureLogger": {
|
||||||
|
"Filter": [
|
||||||
|
{ "Name": "ByIncludingOnly", "Args": { "expression": "@Level = 'Error'" } }
|
||||||
|
],
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "Logs/Error/.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
||||||
|
"retainedFileCountLimit": 365,
|
||||||
|
"fileSizeLimitBytes": 104857600,
|
||||||
|
"rollOnFileSizeLimit": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "Logger",
|
||||||
|
"Args": {
|
||||||
|
"configureLogger": {
|
||||||
|
"Filter": [
|
||||||
|
{ "Name": "ByIncludingOnly", "Args": { "expression": "@Level = 'Fatal'" } }
|
||||||
|
],
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "Logs/Fatal/.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
||||||
|
"retainedFileCountLimit": 365,
|
||||||
|
"fileSizeLimitBytes": 104857600,
|
||||||
|
"rollOnFileSizeLimit": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
<CheckEolTargetFramework>false</CheckEolTargetFramework>
|
<CheckEolTargetFramework>false</CheckEolTargetFramework>
|
||||||
<SuppressNETCoreSdkPreviewMessage>true</SuppressNETCoreSdkPreviewMessage>
|
<SuppressNETCoreSdkPreviewMessage>true</SuppressNETCoreSdkPreviewMessage>
|
||||||
<Nullable>annotations</Nullable>
|
<Nullable>annotations</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<NoWarn>CS1591</NoWarn>
|
<NoWarn>CS1591</NoWarn>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
using Hangfire;
|
||||||
|
using Hangfire.MySql;
|
||||||
|
using HangfireBasicAuthenticationFilter;
|
||||||
|
using MAX.Core.Interfaces;
|
||||||
|
using MAX.Framework.Interfaces;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using MySql.Data.MySqlClient;
|
||||||
|
using Store.Modules.CloudProduct.Services;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct
|
||||||
|
{
|
||||||
|
|
||||||
|
public class CloudProductModule : IModule
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 本模块自己的配置文件
|
||||||
|
/// </summary>
|
||||||
|
public const string ConfigurationFileName = "appsettings.CloudProduct.json";
|
||||||
|
|
||||||
|
public int Priority => IntPriority.Normal;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 服务注册阶段(builder.Build() 之前):这里只能拿到容器和配置,碰不到 app
|
||||||
|
/// </summary>
|
||||||
|
public void AddModule(IHostApplicationBuilder host)
|
||||||
|
{
|
||||||
|
IServiceCollection services = host.Services;
|
||||||
|
IConfigurationManager configuration = host.Configuration;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(ConfigurationFileName))
|
||||||
|
{
|
||||||
|
string path = Path.IsPathRooted(ConfigurationFileName)? ConfigurationFileName: Path.Combine(AppContext.BaseDirectory, ConfigurationFileName);
|
||||||
|
configuration.AddJsonFile(path, optional: false, reloadOnChange: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//// 本模块的配置节(Search / RawData / Indexing / Delete)都在模块自己的配置文件里,
|
||||||
|
//// 关键项缺失直接报错,避免 OpenSearch 地址为空、原始数据写到意外目录之类的隐性故障
|
||||||
|
RequireConfiguration(configuration, "Search:Url");
|
||||||
|
RequireConfiguration(configuration, "Search:IndexName");
|
||||||
|
RequireConfiguration(configuration, "Search:FavoritesIndexName");
|
||||||
|
RequireConfiguration(configuration, "RawData:Path");
|
||||||
|
|
||||||
|
// ===== Hangfire 后台定时任务(商品分词同步) =====
|
||||||
|
var hangfireConnection = configuration.GetValue<string>("CloudProductConnection")
|
||||||
|
?? throw new InvalidOperationException("缺少配置 ConnectionStrings:DefaultConnection,CloudProduct 模块的 Hangfire 无法启动。");
|
||||||
|
|
||||||
|
// AllowUserVariables=true:Hangfire.MySqlStorage 的建表/查询语句依赖用户变量
|
||||||
|
var connectionStringBuilder = new MySqlConnectionStringBuilder(hangfireConnection)
|
||||||
|
{
|
||||||
|
AllowUserVariables = true
|
||||||
|
};
|
||||||
|
|
||||||
|
services.AddHangfire(config => config
|
||||||
|
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
|
||||||
|
.UseSimpleAssemblyNameTypeSerializer()
|
||||||
|
.UseRecommendedSerializerSettings()
|
||||||
|
.UseStorage(new MySqlStorage(connectionStringBuilder.ConnectionString, new MySqlStorageOptions() { TablesPrefix = "Hangfire_" })));
|
||||||
|
services.AddHangfireServer();
|
||||||
|
services.AddTransient<GoodsIndexJob>();
|
||||||
|
services.AddTransient<GoodsViolationIndexJob>();
|
||||||
|
services.AddAuthorization(options => options.AddPolicy("CloudGoodsViolationWrite",
|
||||||
|
policy => policy.RequireAuthenticatedUser().RequireClaim("permission", "cloudgoods:violation:write")));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 管道装配阶段(builder.Build() 之后、app.Run() 之前):这里可以挂中间件、解析容器里的服务
|
||||||
|
/// </summary>
|
||||||
|
public void UseModule(IApplicationBuilder app)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var Configuration = app.ApplicationServices.GetService<IConfiguration>()!;
|
||||||
|
// Hangfire 后台任务看板(默认地址 /hangfire)
|
||||||
|
app.UseHangfireDashboard("/hangfire", new DashboardOptions
|
||||||
|
{
|
||||||
|
Authorization = new[]
|
||||||
|
{
|
||||||
|
new HangfireCustomBasicAuthenticationFilter(){
|
||||||
|
User = Configuration.GetValue<string>("Hangfire:Dashboard:User") ?? "admin",
|
||||||
|
Pass = Configuration.GetValue<string>("Hangfire:Dashboard:Pass") ?? "1234560"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 注册定时任务:把未同步(IndexStatus=0)的商品写入 OpenSearch 分词索引
|
||||||
|
var cron = Configuration.GetValue<string>("Indexing:Cron") ?? "*/5 * * * *";
|
||||||
|
|
||||||
|
// 用容器里的 IRecurringJobManager,而不是静态 RecurringJob:
|
||||||
|
// AddHangfire 只把 JobStorage 注册进容器(没有设置 JobStorage.Current),静态 API 在 Build() 之后调用会直接抛异常。
|
||||||
|
app.ApplicationServices.GetRequiredService<IRecurringJobManager>().AddOrUpdate<GoodsIndexJob>(
|
||||||
|
"goods-index-pending",
|
||||||
|
job => job.ProcessPendingAsync(),
|
||||||
|
cron);
|
||||||
|
app.ApplicationServices.GetRequiredService<IRecurringJobManager>().AddOrUpdate<GoodsViolationIndexJob>(
|
||||||
|
"goods-violation-delete-pending", job => job.ProcessPendingAsync(), "* * * * *");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 数据库不可用/表未初始化时避免阻断应用启动(看板与定时任务都会连库),恢复后重启即可重新装配
|
||||||
|
Console.WriteLine("[Hangfire] 看板/定时任务装配失败: " + ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 校验模块配置项存在(值来自模块自己的 <see cref="ConfigurationFileName"/>)
|
||||||
|
/// </summary>
|
||||||
|
private static void RequireConfiguration(IConfiguration configuration, string key)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(configuration.GetValue<string>(key)))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"缺少配置 {key},请检查模块配置文件 {ConfigurationFileName}。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,471 @@
|
|||||||
|
using Asp.Versioning;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Store.Framework.Base;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using Store.Modules.CloudProduct.ImportConverters;
|
||||||
|
using Store.Modules.CloudProduct.Services;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Controllers
|
||||||
|
{
|
||||||
|
/// <summary>云商品管理:商品查询、导入、违规上报及搜索索引维护。</summary>
|
||||||
|
[Tags("云商品")]
|
||||||
|
[ApiVersionNeutral]
|
||||||
|
[Route("api/CloudGoods/[action]")]
|
||||||
|
public class GoodsController : AppControllerBase
|
||||||
|
{
|
||||||
|
private readonly IGoodsService _goodsService;
|
||||||
|
private readonly IOpenSearchService _searchService;
|
||||||
|
private readonly IRawDataStorage _rawDataStorage;
|
||||||
|
private readonly GoodsIndexJob _goodsIndexJob;
|
||||||
|
private readonly GoodsViolationService _violations;
|
||||||
|
|
||||||
|
public GoodsController(IGoodsService goodsService, IOpenSearchService searchService, IRawDataStorage rawDataStorage, GoodsIndexJob goodsIndexJob, GoodsViolationService violations)
|
||||||
|
{
|
||||||
|
_violations = violations;
|
||||||
|
_goodsService = goodsService;
|
||||||
|
_searchService = searchService;
|
||||||
|
_rawDataStorage = rawDataStorage;
|
||||||
|
_goodsIndexJob = goodsIndexJob;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>获取全部违规原因字典,包含未启用违规判定的原因,按ID升序返回。</summary>
|
||||||
|
[HttpGet]
|
||||||
|
[EndpointSummary("获取违规原因字典")]
|
||||||
|
public Task<List<ViolationReasonDto>> GetViolationReasons()
|
||||||
|
=> _violations.GetReasonsAsync();
|
||||||
|
|
||||||
|
/// <summary>批量上报违规商品;重复上报合并原因。</summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("批量上报违规商品")]
|
||||||
|
public Task<List<ReportGoodsViolationsResult>> ReportViolations([FromBody] ReportGoodsViolationItem[] items)
|
||||||
|
=> _violations.ReportAsync(items);
|
||||||
|
|
||||||
|
/// <summary>批量解除商品违规,恢复正常商品索引;失败后由后台索引任务重试。</summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("解除商品违规并恢复索引")]
|
||||||
|
public Task<RemoveGoodsViolationsResult> RemoveViolations([FromBody] long[] ids)
|
||||||
|
=> _violations.RemoveAsync(ids);
|
||||||
|
|
||||||
|
/// <summary>按商品编号批量查询是否违规。</summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("批量查询商品违规状态")]
|
||||||
|
public Task<List<GoodsViolationStatus>> GetViolationStatus([FromBody] long[] ids)
|
||||||
|
=> _violations.GetStatusAsync(ids);
|
||||||
|
|
||||||
|
/// <summary>获取服务器当前日期(长日期格式)。</summary>
|
||||||
|
[HttpGet]
|
||||||
|
[EndpointSummary("获取服务器当前日期")]
|
||||||
|
public async Task<string> Time()
|
||||||
|
{
|
||||||
|
return DateTime.Now.ToLongDateString();
|
||||||
|
}
|
||||||
|
/// <summary>手动执行待处理商品的索引任务。</summary>
|
||||||
|
[HttpGet]
|
||||||
|
[EndpointSummary("处理待建立索引的商品")]
|
||||||
|
public async Task Job()
|
||||||
|
{
|
||||||
|
await _goodsIndexJob.ProcessPendingAsync();
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// 分页搜索商品,可按标题、价格、类目、销量和平台筛选。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">商品筛选条件及分页参数。</param>
|
||||||
|
/// <returns>符合条件的商品列表及总数。</returns>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("分页搜索商品")]
|
||||||
|
public async Task<PageData<GoodsEntity>> SearchGoods(GoodsSearchRequest request)
|
||||||
|
{
|
||||||
|
// 1. 参数基础校验
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 分页参数校验
|
||||||
|
if (request.PageIndex < 1)
|
||||||
|
{
|
||||||
|
throw new AppException("页码必须大于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.PageSize < 1 || request.PageSize > 2000)
|
||||||
|
{
|
||||||
|
throw new AppException("每页数量必须在1-2000之间", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 价格区间校验
|
||||||
|
if (request.MinPrice.HasValue && request.MinPrice < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最低价格不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MaxPrice.HasValue && request.MaxPrice < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最高价格不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MinPrice.HasValue && request.MaxPrice.HasValue && request.MinPrice > request.MaxPrice)
|
||||||
|
{
|
||||||
|
throw new AppException("最低价格不能大于最高价格", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 销量区间校验
|
||||||
|
if (request.MinSoldQuantity.HasValue && request.MinSoldQuantity < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最低销量不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MaxSoldQuantity.HasValue && request.MaxSoldQuantity < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最高销量不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MinSoldQuantity.HasValue && request.MaxSoldQuantity.HasValue &&
|
||||||
|
request.MinSoldQuantity > request.MaxSoldQuantity)
|
||||||
|
{
|
||||||
|
throw new AppException("最低销量不能大于最高销量", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 类目层级校验
|
||||||
|
if (request.CatId2.HasValue && !request.CatId1.HasValue)
|
||||||
|
{
|
||||||
|
throw new AppException("选择二级类目时必须先选择一级类目", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.CatId3.HasValue && !request.CatId2.HasValue)
|
||||||
|
{
|
||||||
|
throw new AppException("选择三级类目时必须先选择二级类目", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.CatId4.HasValue && !request.CatId3.HasValue)
|
||||||
|
{
|
||||||
|
throw new AppException("选择四级类目时必须先选择三级类目", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 平台校验
|
||||||
|
if (request.Platform.HasValue && request.Platform < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("平台类型无效", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 10. 至少有一个搜索条件
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Title) &&
|
||||||
|
!request.MinPrice.HasValue && !request.MaxPrice.HasValue &&
|
||||||
|
!request.CatId1.HasValue && !request.CatId2.HasValue &&
|
||||||
|
!request.CatId3.HasValue && !request.CatId4.HasValue &&
|
||||||
|
!request.MinSoldQuantity.HasValue && !request.MaxSoldQuantity.HasValue &&
|
||||||
|
!request.Platform.HasValue)
|
||||||
|
{
|
||||||
|
throw new AppException("请至少提供一个搜索条件", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await _goodsService.SearchGoodsAsync(request);
|
||||||
|
return new PageData<GoodsEntity>
|
||||||
|
{
|
||||||
|
List = result.List,
|
||||||
|
Total = result.Total,
|
||||||
|
PageSize = request.PageSize,
|
||||||
|
PageIndex = request.PageIndex,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分词搜索,直接返回索引中的商品摘要(路由保持 SearchGoodsToIds 不变)
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
[ActionName("SearchGoodsToIds")]
|
||||||
|
[EndpointSummary("按关键词搜索商品摘要")]
|
||||||
|
public async Task<PageData<GoodsSearchDocument>> SearchGoodsSummary(string keyword, int pageindex = 1, int pagesize = 20)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(keyword))
|
||||||
|
{
|
||||||
|
throw new AppException("填写关键字", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await _searchService.SearchByTitleAsync(new GoodsSearchRequest
|
||||||
|
{
|
||||||
|
Title = keyword,
|
||||||
|
PageIndex = pageindex,
|
||||||
|
PageSize = pagesize,
|
||||||
|
});
|
||||||
|
|
||||||
|
return new PageData<GoodsSearchDocument>
|
||||||
|
{
|
||||||
|
PageIndex = pageindex,
|
||||||
|
PageSize = pagesize,
|
||||||
|
List = result.Documents,
|
||||||
|
Total = result.Total,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 导入测试数据:读取 ImportConverters/data.txt 并走完整解析 + 入库 + 分词流程。
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
[EndpointSummary("导入测试商品数据")]
|
||||||
|
public async Task<GoodsImportResult> ImportTestData()
|
||||||
|
{
|
||||||
|
var filePath = GetDataFilePath();
|
||||||
|
|
||||||
|
if (!System.IO.File.Exists(filePath))
|
||||||
|
{
|
||||||
|
throw new AppException($"找不到测试数据文件: {filePath}", ResultCode.NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
var content = await System.IO.File.ReadAllTextAsync(filePath);
|
||||||
|
var goods = GoodsConverterFactory.ConvertContent(content);
|
||||||
|
if (goods == null)
|
||||||
|
{
|
||||||
|
throw new AppException("未找到匹配的转换器,无法解析测试数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _goodsService.ImportGoodsAsync(new[]
|
||||||
|
{
|
||||||
|
new GoodsImportItem { Goods = goods, RawData = content }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 导入接口:接收客户端批量上传的 JSON 文件,解析后入库并写入分词索引。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("批量导入商品 JSON 文件")]
|
||||||
|
public async Task<GoodsImportResult> ImportFiles([FromForm] List<IFormFile> files)
|
||||||
|
{
|
||||||
|
if (files == null || files.Count == 0)
|
||||||
|
{
|
||||||
|
throw new AppException("请选择要导入的 JSON 文件", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var items = new List<GoodsImportItem>();
|
||||||
|
var parseErrors = new List<string>();
|
||||||
|
|
||||||
|
foreach (var file in files)
|
||||||
|
{
|
||||||
|
if (file == null || file.Length == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var reader = new StreamReader(file.OpenReadStream());
|
||||||
|
var content = await reader.ReadToEndAsync();
|
||||||
|
|
||||||
|
var goods = GoodsConverterFactory.ConvertContent(content);
|
||||||
|
if (goods == null)
|
||||||
|
{
|
||||||
|
parseErrors.Add($"{file.FileName}: 未找到匹配的转换器");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
items.Add(new GoodsImportItem { Goods = goods, RawData = content });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
parseErrors.Add($"{file.FileName}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await _goodsService.ImportGoodsAsync(items);
|
||||||
|
result.FailedCount += parseErrors.Count;
|
||||||
|
result.Errors.InsertRange(0, parseErrors);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 查询 OpenSearch 状态。
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
[EndpointSummary("查询 OpenSearch 服务状态")]
|
||||||
|
public async Task<OpenSearchStatusDto> GetOpenSearchStatus()
|
||||||
|
{
|
||||||
|
return await _searchService.GetStatusAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检查搜索索引是否存在。
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
[EndpointSummary("检查商品搜索索引是否存在")]
|
||||||
|
public async Task<bool> IndexExists()
|
||||||
|
{
|
||||||
|
return await _searchService.IndexExistsAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检查索引映射(分析器)是否符合当前服务要求。
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
[EndpointSummary("检查商品索引映射是否正常")]
|
||||||
|
public async Task<bool> IndexMappingHealthy()
|
||||||
|
{
|
||||||
|
return await _searchService.IsIndexMappingHealthyAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建搜索索引(含 IK 分词映射,已存在且映射正常时跳过)。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("创建商品搜索索引")]
|
||||||
|
public async Task<bool> CreateIndex()
|
||||||
|
{
|
||||||
|
return await _searchService.CreateIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除搜索索引。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("删除商品搜索索引")]
|
||||||
|
public async Task DeleteIndex()
|
||||||
|
{
|
||||||
|
await _searchService.DeleteIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 手动刷新搜索索引,使最新写入立即可搜索。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("刷新商品搜索索引")]
|
||||||
|
public async Task RefreshIndex()
|
||||||
|
{
|
||||||
|
await _searchService.RefreshIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 手动新增或覆盖一条搜索文档。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("新增或覆盖商品搜索文档")]
|
||||||
|
public async Task AddSearchDocument([FromBody] GoodsSearchDocument document)
|
||||||
|
{
|
||||||
|
if (document == null || document.Id <= 0)
|
||||||
|
{
|
||||||
|
throw new AppException("请提供有效的搜索文档", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _searchService.AddDocumentAsync(document);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取指定商品详情:解压缩原始数据并返回 JSON。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("查询商品详情")]
|
||||||
|
public async Task<JsonNode> GetGoodsDetail([FromQuery] long goodsId)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var raw = await GetRawDataOrThrowAsync(goodsId);
|
||||||
|
var node = JsonNode.Parse(raw);
|
||||||
|
return node ?? throw new AppException("商品详情解析失败", ResultCode.BusinessError);
|
||||||
|
}
|
||||||
|
catch(Exception ex)
|
||||||
|
{
|
||||||
|
throw new AppException(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取指定商品的原始数据(解压缩后原样返回)。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("读取商品原始数据")]
|
||||||
|
public async Task<string> GetGoodsRawData([FromQuery] long goodsId)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await GetRawDataOrThrowAsync(goodsId);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
throw new AppException(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 重新从数据库读取指定商品,覆盖 OpenSearch 已有分词并重新分词。
|
||||||
|
/// ids 为空时重建全部商品。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("重建商品搜索文档")]
|
||||||
|
public async Task<long> RebuildIndex([FromBody] long[]? ids)
|
||||||
|
{
|
||||||
|
return await _goodsService.RebuildSearchIndexAsync(ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除商品(按商品编号)。是否软删除由配置 Delete:SoftDelete 决定,
|
||||||
|
/// 软删除将 Status 置 1,硬删除物理删除记录;两种方式都会删除 OpenSearch 中对应文档。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
[EndpointSummary("批量删除商品")]
|
||||||
|
public async Task<long> DeleteGoods([FromBody] long[]? ids)
|
||||||
|
{
|
||||||
|
if (ids == null || ids.Length == 0)
|
||||||
|
{
|
||||||
|
throw new AppException("请提供要删除的商品ID", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _goodsService.DeleteGoodsAsync(ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 清空并重建搜索索引(路由保持 ClearSearch 不变)。
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
[ActionName("ClearSearch")]
|
||||||
|
[EndpointSummary("清空并重建商品搜索索引")]
|
||||||
|
public async Task<bool> ClearSearchIndex()
|
||||||
|
{
|
||||||
|
return await _searchService.ClearIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 统计索引中的文档数(路由保持 GetSearchCount 不变)。
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
[ActionName("GetSearchCount")]
|
||||||
|
[EndpointSummary("统计商品搜索文档数量")]
|
||||||
|
public async Task<long> GetSearchDocumentCount()
|
||||||
|
{
|
||||||
|
return await _searchService.CountDocumentsAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string> GetRawDataOrThrowAsync(long goodsId)
|
||||||
|
{
|
||||||
|
if (goodsId <= 0)
|
||||||
|
throw new AppException("商品ID无效", ResultCode.ValidationError);
|
||||||
|
|
||||||
|
var raw = await _rawDataStorage.ReadAsync(goodsId);
|
||||||
|
if (raw == null)
|
||||||
|
{
|
||||||
|
System.IO.File.WriteAllText("./NoGoods.txt", goodsId.ToString());
|
||||||
|
throw new AppException($"商品原始数据不存在: {goodsId}", ResultCode.NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetDataFilePath()
|
||||||
|
{
|
||||||
|
var outputPath = Path.Combine(AppContext.BaseDirectory, "ImportConverters", "data.txt");
|
||||||
|
if (System.IO.File.Exists(outputPath))
|
||||||
|
return outputPath;
|
||||||
|
|
||||||
|
var workPath = Path.Combine(Directory.GetCurrentDirectory(), "ImportConverters", "data.txt");
|
||||||
|
if (System.IO.File.Exists(workPath))
|
||||||
|
return workPath;
|
||||||
|
|
||||||
|
return outputPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
using Asp.Versioning;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using MAX.Framework.Security;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Store.Framework.Base;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
using Store.Modules.CloudProduct.Services;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Controllers
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品:收藏/取消收藏(数据库 + 收藏索引同步)、收藏分组、收藏状态查询、收藏检索与索引重建。
|
||||||
|
/// 请求中的 userName 允许为空,为空时取当前登录用户。
|
||||||
|
/// </summary>
|
||||||
|
[ApiVersionNeutral]
|
||||||
|
[Route("api/CloudGoods/[action]")]
|
||||||
|
public class UserFavoritesController : AppControllerBase
|
||||||
|
{
|
||||||
|
private readonly IUserFavoritesService _favoritesService;
|
||||||
|
private readonly ICurrentUser _currentUser;
|
||||||
|
|
||||||
|
public UserFavoritesController(IUserFavoritesService favoritesService, ICurrentUser currentUser)
|
||||||
|
{
|
||||||
|
_favoritesService = favoritesService;
|
||||||
|
_currentUser = currentUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量收藏商品:写入 user_goods_favorites 并同步写入收藏索引,返回本次成功收藏的商品数量。
|
||||||
|
/// 商品已收藏时视为修改收藏分组;商品不存在/已删除的编号会被跳过。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<int> AddFavorite(AddUserFavoriteRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.UserName = ResolveUserName(request.UserName);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.UserName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.GoodsIds == null || request.GoodsIds.Count == 0)
|
||||||
|
{
|
||||||
|
throw new AppException("请提供要收藏的商品编号", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.GroupId < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("收藏分组无效", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _favoritesService.AddFavoritesAsync(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量取消收藏:删除 user_goods_favorites 记录并同步删除收藏索引文档,返回实际取消的条数。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<int> RemoveFavorites(RemoveUserFavoritesRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.UserName = ResolveUserName(request.UserName);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.UserName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.GoodsIds == null || request.GoodsIds.Count == 0)
|
||||||
|
{
|
||||||
|
throw new AppException("请提供要取消收藏的商品编号", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _favoritesService.RemoveFavoritesAsync(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建收藏分组:创建成功返回 true,同名分组已存在返回 false。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<bool> CreateGroup(CreateUserFavoriteGroupRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.UserName = ResolveUserName(request.UserName);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.UserName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.GroupName))
|
||||||
|
{
|
||||||
|
throw new AppException("分组名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _favoritesService.CreateGroupAsync(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 查询用户的收藏分组(含默认分组)及分组下收藏数量。
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<List<UserFavoriteGroupDto>> GetGroups(string? userName = null)
|
||||||
|
{
|
||||||
|
var resolved = ResolveUserName(userName);
|
||||||
|
if (string.IsNullOrWhiteSpace(resolved))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _favoritesService.GetGroupsAsync(resolved);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 按 GoodsIds 顺序返回每个商品是否已被收藏(如 [true,false,...]),前台可按顺序直接渲染。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<List<bool>> GetFavoriteStatus(UserFavoriteStatusRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.UserName = ResolveUserName(request.UserName);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.UserName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _favoritesService.GetFavoriteStatusAsync(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检索用户收藏的商品(标题、销量、价格、类目、分组)。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<PageData<UserFavoriteItem>> SearchFavorites(UserFavoritesSearchRequest request)
|
||||||
|
{
|
||||||
|
// 1. 参数基础校验
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.UserName = ResolveUserName(request.UserName);
|
||||||
|
if (string.IsNullOrWhiteSpace(request.UserName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 分页参数校验
|
||||||
|
if (request.PageIndex < 1)
|
||||||
|
{
|
||||||
|
throw new AppException("页码必须大于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.PageSize < 1 || request.PageSize > 2000)
|
||||||
|
{
|
||||||
|
throw new AppException("每页数量必须在1-2000之间", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 价格区间校验
|
||||||
|
if (request.MinPrice.HasValue && request.MinPrice < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最低价格不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MaxPrice.HasValue && request.MaxPrice < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最高价格不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MinPrice.HasValue && request.MaxPrice.HasValue && request.MinPrice > request.MaxPrice)
|
||||||
|
{
|
||||||
|
throw new AppException("最低价格不能大于最高价格", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 销量区间校验
|
||||||
|
if (request.MinSoldQuantity.HasValue && request.MinSoldQuantity < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最低销量不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MaxSoldQuantity.HasValue && request.MaxSoldQuantity < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("最高销量不能小于0", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MinSoldQuantity.HasValue && request.MaxSoldQuantity.HasValue &&
|
||||||
|
request.MinSoldQuantity > request.MaxSoldQuantity)
|
||||||
|
{
|
||||||
|
throw new AppException("最低销量不能大于最高销量", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 类目层级校验
|
||||||
|
if (request.CatId2.HasValue && !request.CatId1.HasValue)
|
||||||
|
{
|
||||||
|
throw new AppException("选择二级类目时必须先选择一级类目", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.CatId3.HasValue && !request.CatId2.HasValue)
|
||||||
|
{
|
||||||
|
throw new AppException("选择三级类目时必须先选择二级类目", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.CatId4.HasValue && !request.CatId3.HasValue)
|
||||||
|
{
|
||||||
|
throw new AppException("选择四级类目时必须先选择三级类目", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 分组校验
|
||||||
|
if (request.GroupId.HasValue && request.GroupId < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("收藏分组无效", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. 平台校验
|
||||||
|
if (request.Platform.HasValue && request.Platform < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("平台类型无效", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await _favoritesService.SearchFavoritesAsync(request);
|
||||||
|
|
||||||
|
return new PageData<UserFavoriteItem>
|
||||||
|
{
|
||||||
|
List = result.List,
|
||||||
|
Total = result.Total,
|
||||||
|
PageSize = request.PageSize,
|
||||||
|
PageIndex = request.PageIndex,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 移除所有用户收藏索引并重新创建,随后按 user_goods_favorites 关联 goods 全量回填。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<long> RebuildSearchIndex()
|
||||||
|
{
|
||||||
|
return await _favoritesService.RebuildSearchIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 取用户名:显式传入优先,否则取当前登录用户。
|
||||||
|
/// </summary>
|
||||||
|
private string ResolveUserName(string? userName)
|
||||||
|
{
|
||||||
|
return string.IsNullOrWhiteSpace(userName)
|
||||||
|
? (_currentUser.UserName ?? string.Empty)
|
||||||
|
: userName.Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏商品请求(支持多选批量收藏)
|
||||||
|
/// </summary>
|
||||||
|
public class AddUserFavoriteRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名(为空时取当前登录用户)
|
||||||
|
/// </summary>
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商品编号集合(可多选)
|
||||||
|
/// </summary>
|
||||||
|
public List<long> GoodsIds { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏分组ID(默认0,表示默认分组;大于0时必须存在且属于该用户)
|
||||||
|
/// </summary>
|
||||||
|
public int GroupId { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 创建收藏分组请求
|
||||||
|
/// </summary>
|
||||||
|
public class CreateUserFavoriteGroupRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名(为空时取当前登录用户)
|
||||||
|
/// </summary>
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分组名
|
||||||
|
/// </summary>
|
||||||
|
public string GroupName { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 导入项:商品模型 + 原始数据
|
||||||
|
/// </summary>
|
||||||
|
public class GoodsImportItem
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 解析后的商品模型
|
||||||
|
/// </summary>
|
||||||
|
public GoodsEntity Goods { get; set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 原始数据(JSON 原文,压缩后落盘)
|
||||||
|
/// </summary>
|
||||||
|
public string RawData { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品导入结果
|
||||||
|
/// </summary>
|
||||||
|
public class GoodsImportResult
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 成功条数
|
||||||
|
/// </summary>
|
||||||
|
public int SuccessCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 失败条数
|
||||||
|
/// </summary>
|
||||||
|
public int FailedCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 总条数
|
||||||
|
/// </summary>
|
||||||
|
public int Total => SuccessCount + FailedCount;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 错误明细
|
||||||
|
/// </summary>
|
||||||
|
public List<string> Errors { get; set; } = new();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using OpenSearch.Client;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品搜索文档:OpenSearch 索引中的商品模型,Id 为主键,Title 用于分词搜索
|
||||||
|
/// </summary>
|
||||||
|
public class GoodsSearchDocument
|
||||||
|
{
|
||||||
|
[Number(NumberType.Byte, Name = "platform")]
|
||||||
|
public byte Platform { get; set; }
|
||||||
|
|
||||||
|
[Number(NumberType.Long, Name = "id")]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[Text(Name = "title", Analyzer = "ik_max_word", SearchAnalyzer = "ik_smart")]
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Text(Name = "thumbUrl")]
|
||||||
|
public string? ThumbUrl { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>一级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_1")]
|
||||||
|
public int? CatId1 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>二级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_2")]
|
||||||
|
public int? CatId2 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>三级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_3")]
|
||||||
|
public int? CatId3 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>四级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_4")]
|
||||||
|
public int? CatId4 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>最低价快照,用于价格区间过滤和按价格排序</summary>
|
||||||
|
[Number(NumberType.Long, Name = "min_price")]
|
||||||
|
public long? MinPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>销量,用于按销量排序</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "sold_quantity")]
|
||||||
|
public int SoldQuantity { get; set; }
|
||||||
|
|
||||||
|
public override string ToString() => $"[Id={Id}] Title={Title} Cat=({CatId1},{CatId2},{CatId3},{CatId4}) Price={MinPrice} Sold={SoldQuantity}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品搜索请求
|
||||||
|
/// </summary>
|
||||||
|
public class GoodsSearchRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 标题(模糊搜索)
|
||||||
|
/// </summary>
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最低价格(分)
|
||||||
|
/// </summary>
|
||||||
|
public long? MinPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最高价格(分)
|
||||||
|
/// </summary>
|
||||||
|
public long? MaxPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 一级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId1 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 二级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId2 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 三级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId3 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 四级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId4 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最低销量
|
||||||
|
/// </summary>
|
||||||
|
public int? MinSoldQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最高销量
|
||||||
|
/// </summary>
|
||||||
|
public int? MaxSoldQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 平台类型
|
||||||
|
/// </summary>
|
||||||
|
public byte? Platform { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 页码(默认1)
|
||||||
|
/// </summary>
|
||||||
|
public int PageIndex { get; set; } = 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 每页数量(默认20)
|
||||||
|
/// </summary>
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序字段
|
||||||
|
/// </summary>
|
||||||
|
public string SortBy { get; set; } = "CreatedTime";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序方式:asc/desc(默认desc)
|
||||||
|
/// </summary>
|
||||||
|
public string SortOrder { get; set; } = "desc";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos;
|
||||||
|
|
||||||
|
public class ViolationReasonDto
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public bool IsViolation { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ReportGoodsViolationItem
|
||||||
|
{
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
/// <summary>原因名称,例如“出售假冒商品”;新名称默认仅记录字典,不判定违规。</summary>
|
||||||
|
public string Reasons { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ReportGoodsViolationsResult
|
||||||
|
{
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
/// <summary>存在违规记录且已完成索引下架时为 true,否则为 false。</summary>
|
||||||
|
public bool IsOffShelf { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class GoodsViolationStatus
|
||||||
|
{
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
public bool IsViolation { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class RemoveGoodsViolationsResult
|
||||||
|
{
|
||||||
|
public int RemovedCount { get; set; }
|
||||||
|
public long[] RestoredGoodsIds { get; set; } = [];
|
||||||
|
public long[] PendingRestoreGoodsIds { get; set; } = [];
|
||||||
|
/// <summary>商品不存在、已删除或恢复期间再次被上报违规的编号。</summary>
|
||||||
|
public long[] SkippedGoodsIds { get; set; } = [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// OpenSearch 运行状态
|
||||||
|
/// </summary>
|
||||||
|
public class OpenSearchStatusDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 节点地址
|
||||||
|
/// </summary>
|
||||||
|
public string NodeUrl { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 索引名称
|
||||||
|
/// </summary>
|
||||||
|
public string IndexName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否可连接
|
||||||
|
/// </summary>
|
||||||
|
public bool Connected { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// OpenSearch 服务及目标索引是否健康
|
||||||
|
/// </summary>
|
||||||
|
public bool Healthy { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 集群名称
|
||||||
|
/// </summary>
|
||||||
|
public string? ClusterName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 集群状态(green、yellow 或 red)
|
||||||
|
/// </summary>
|
||||||
|
public string? ClusterStatus { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 集群节点总数
|
||||||
|
/// </summary>
|
||||||
|
public int NumberOfNodes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数据节点数量
|
||||||
|
/// </summary>
|
||||||
|
public int NumberOfDataNodes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 活跃主分片数量
|
||||||
|
/// </summary>
|
||||||
|
public int ActivePrimaryShards { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 活跃分片总数
|
||||||
|
/// </summary>
|
||||||
|
public int ActiveShards { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 正在迁移的分片数量
|
||||||
|
/// </summary>
|
||||||
|
public int RelocatingShards { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 正在初始化的分片数量
|
||||||
|
/// </summary>
|
||||||
|
public int InitializingShards { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 未分配的分片数量
|
||||||
|
/// </summary>
|
||||||
|
public int UnassignedShards { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 索引是否存在
|
||||||
|
/// </summary>
|
||||||
|
public bool IndexExists { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 索引映射是否符合当前服务要求
|
||||||
|
/// </summary>
|
||||||
|
public bool MappingHealthy { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 标题字段的索引分析器
|
||||||
|
/// </summary>
|
||||||
|
public string? IndexAnalyzer { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 标题字段的搜索分析器
|
||||||
|
/// </summary>
|
||||||
|
public string? SearchAnalyzer { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 文档总数(索引不存在或读取失败时为 -1)
|
||||||
|
/// </summary>
|
||||||
|
public long DocumentCount { get; set; } = -1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 状态检测耗时(毫秒)
|
||||||
|
/// </summary>
|
||||||
|
public long ElapsedMilliseconds { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 状态说明或错误信息
|
||||||
|
/// </summary>
|
||||||
|
public string? Message { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 取消收藏(批量)请求
|
||||||
|
/// </summary>
|
||||||
|
public class RemoveUserFavoritesRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名(为空时取当前登录用户)
|
||||||
|
/// </summary>
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 要取消收藏的商品编号集合
|
||||||
|
/// </summary>
|
||||||
|
public List<long> GoodsIds { get; set; } = new();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏分组
|
||||||
|
/// </summary>
|
||||||
|
public class UserFavoriteGroupDto
|
||||||
|
{
|
||||||
|
/// <summary>分组ID</summary>
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>用户名</summary>
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>分组名</summary>
|
||||||
|
public string GroupName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>该分组下的收藏数量</summary>
|
||||||
|
public long FavoriteCount { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品(索引文档回显模型)
|
||||||
|
/// </summary>
|
||||||
|
public class UserFavoriteItem
|
||||||
|
{
|
||||||
|
/// <summary>收藏记录自增主键</summary>
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>用户名</summary>
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>收藏分组ID(0 表示默认分组)</summary>
|
||||||
|
public int GroupId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>收藏分组名</summary>
|
||||||
|
public string GroupName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>商品编号</summary>
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>平台类型</summary>
|
||||||
|
public byte Platform { get; set; }
|
||||||
|
|
||||||
|
/// <summary>商品标题</summary>
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>缩略图</summary>
|
||||||
|
public string? ThumbUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>一级类目ID</summary>
|
||||||
|
public int? CatId1 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>二级类目ID</summary>
|
||||||
|
public int? CatId2 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>三级类目ID</summary>
|
||||||
|
public int? CatId3 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>四级类目ID</summary>
|
||||||
|
public int? CatId4 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>最低价快照(分)</summary>
|
||||||
|
public long? MinPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>销量</summary>
|
||||||
|
public int SoldQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>收藏时间</summary>
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 查询商品是否已被收藏请求:按 GoodsIds 顺序返回是否已收藏
|
||||||
|
/// </summary>
|
||||||
|
public class UserFavoriteStatusRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名(为空时取当前登录用户)
|
||||||
|
/// </summary>
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商品编号集合
|
||||||
|
/// </summary>
|
||||||
|
public List<long> GoodsIds { get; set; } = new();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
using OpenSearch.Client;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品搜索文档:OpenSearch 索引中的收藏模型。
|
||||||
|
/// 一条收藏记录 = 用户 + 商品快照(标题/价格/销量/类目)+ 收藏分组,
|
||||||
|
/// 文档 Id 固定为 "{user_name}:{goods_id}"(表 uk_user_goods 保证唯一),便于收藏/取消收藏时幂等覆盖与删除。
|
||||||
|
/// </summary>
|
||||||
|
public class UserFavoritesSearchDocument
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 文档主键(同时作为 OpenSearch 的 _id):{user_name}:{goods_id}
|
||||||
|
/// </summary>
|
||||||
|
[Keyword(Name = "id")]
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏记录自增主键(user_goods_favorites.id)
|
||||||
|
/// </summary>
|
||||||
|
[Number(NumberType.Long, Name = "fav_id")]
|
||||||
|
public long FavId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>用户名(收藏归属人,检索时强制过滤)</summary>
|
||||||
|
[Keyword(Name = "user_name")]
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>收藏分组ID(0 表示默认分组)</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "group_id")]
|
||||||
|
public int GroupId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>收藏分组名(分组ID为0时为默认分组名)</summary>
|
||||||
|
[Keyword(Name = "group_name")]
|
||||||
|
public string GroupName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>商品编号</summary>
|
||||||
|
[Number(NumberType.Long, Name = "goods_id")]
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>平台类型(1 PDD、2 WX)</summary>
|
||||||
|
[Number(NumberType.Byte, Name = "platform")]
|
||||||
|
public byte Platform { get; set; }
|
||||||
|
|
||||||
|
/// <summary>商品标题,用于分词搜索</summary>
|
||||||
|
[Text(Name = "title", Analyzer = "ik_max_word", SearchAnalyzer = "ik_smart")]
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>缩略图</summary>
|
||||||
|
[Text(Name = "thumb_url")]
|
||||||
|
public string? ThumbUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>一级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_1")]
|
||||||
|
public int? CatId1 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>二级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_2")]
|
||||||
|
public int? CatId2 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>三级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_3")]
|
||||||
|
public int? CatId3 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>四级类目ID</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "cat_id_4")]
|
||||||
|
public int? CatId4 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>最低价快照(分),用于价格区间过滤和按价格排序</summary>
|
||||||
|
[Number(NumberType.Long, Name = "min_price")]
|
||||||
|
public long? MinPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>销量,用于按销量排序</summary>
|
||||||
|
[Number(NumberType.Integer, Name = "sold_quantity")]
|
||||||
|
public int SoldQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>收藏时间,默认按此字段倒序</summary>
|
||||||
|
[Date(Name = "created_at")]
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 生成文档主键:{user_name}:{goods_id}
|
||||||
|
/// </summary>
|
||||||
|
public static string BuildId(string userName, long goodsId) => $"{userName}:{goodsId}";
|
||||||
|
|
||||||
|
public override string ToString() => $"[Id={Id}] User={UserName} Goods={GoodsId} Group={GroupId}({GroupName}) Title={Title} Price={MinPrice} Sold={SoldQuantity}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Dtos
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品搜索请求(仅检索当前用户自己的收藏)
|
||||||
|
/// </summary>
|
||||||
|
public class UserFavoritesSearchRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名(为空时取当前登录用户)
|
||||||
|
/// </summary>
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 标题关键字(分词模糊搜索)
|
||||||
|
/// </summary>
|
||||||
|
public string? Title { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏分组ID(0 表示默认分组)
|
||||||
|
/// </summary>
|
||||||
|
public int? GroupId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏分组名(与分组ID二选一,同时传入时以分组ID为准)
|
||||||
|
/// </summary>
|
||||||
|
public string? GroupName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最低价格(分)
|
||||||
|
/// </summary>
|
||||||
|
public long? MinPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最高价格(分)
|
||||||
|
/// </summary>
|
||||||
|
public long? MaxPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 一级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId1 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 二级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId2 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 三级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId3 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 四级类目ID
|
||||||
|
/// </summary>
|
||||||
|
public int? CatId4 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最低销量
|
||||||
|
/// </summary>
|
||||||
|
public int? MinSoldQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最高销量
|
||||||
|
/// </summary>
|
||||||
|
public int? MaxSoldQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 平台类型
|
||||||
|
/// </summary>
|
||||||
|
public byte? Platform { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 页码(默认1)
|
||||||
|
/// </summary>
|
||||||
|
public int PageIndex { get; set; } = 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 每页数量(默认20)
|
||||||
|
/// </summary>
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序方式:CreatedTimeDesc(默认,收藏时间倒序)/ CreatedTimeAsc / PriceAsc / PriceDesc / SoldDesc
|
||||||
|
/// </summary>
|
||||||
|
public string SortBy { get; set; } = "CreatedTimeDesc";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Entities
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品表实体(对应数据库表 goods)
|
||||||
|
/// </summary>
|
||||||
|
[Table(Name = "goods")]
|
||||||
|
public class GoodsEntity
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 自增ID
|
||||||
|
/// </summary>
|
||||||
|
[Column(IsPrimary = true, IsIdentity = true)]
|
||||||
|
[JsonIgnore]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 平台类型
|
||||||
|
/// 1 PDD
|
||||||
|
/// </summary>
|
||||||
|
[Column(IsNullable = false)]
|
||||||
|
public byte Platform { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商品编号
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "goods_id", IsNullable = false)]
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 标题
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "title", IsNullable = false, StringLength = 500)]
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 描述
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "description", IsNullable = true)]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 缩略图
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "thumb_url", IsNullable = true, StringLength = 512)]
|
||||||
|
public string? ThumbUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 一级类目ID
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "cat_id_1", IsNullable = true)]
|
||||||
|
public int? CatId1 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 二级类目ID
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "cat_id_2", IsNullable = true)]
|
||||||
|
public int? CatId2 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 三级类目ID
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "cat_id_3", IsNullable = true)]
|
||||||
|
public int? CatId3 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 四级类目ID
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "cat_id_4", IsNullable = true)]
|
||||||
|
public int? CatId4 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最低价快照(元),导入时计算
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "min_price")]
|
||||||
|
public long? MinPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 最高价快照(元),导入时计算
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "max_price")]
|
||||||
|
public long? MaxPrice { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 销量
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "sold_quantity", IsNullable = false)]
|
||||||
|
public int SoldQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 状态:0正常 1已删除
|
||||||
|
/// </summary>
|
||||||
|
[Column(IsNullable = false)]
|
||||||
|
[JsonIgnore]
|
||||||
|
public byte Status { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建时间
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "createdTime", IsNullable = false, ServerTime = DateTimeKind.Utc)]
|
||||||
|
[JsonIgnore]
|
||||||
|
public DateTime CreatedTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新时间(自动更新)
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "updatedTime", IsNullable = false, ServerTime = DateTimeKind.Utc)]
|
||||||
|
[JsonIgnore]
|
||||||
|
public DateTime UpdatedTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否已分词:0未 1已
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "is_segmented", IsNullable = false)]
|
||||||
|
[JsonIgnore]
|
||||||
|
public byte IsSegmented { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Entities;
|
||||||
|
|
||||||
|
[Table(Name = "goods_violation")]
|
||||||
|
public class GoodsViolationEntity
|
||||||
|
{
|
||||||
|
[Column(Name = "goods_id", IsPrimary = true)]
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
|
||||||
|
[Column(Name = "reason_id", IsPrimary = true, IsNullable = false)]
|
||||||
|
public uint ReasonId { get; set; }
|
||||||
|
|
||||||
|
[Column(Name = "is_index_deleted")]
|
||||||
|
public bool IsIndexDeleted { get; set; }
|
||||||
|
|
||||||
|
[Column(Name = "created_time")]
|
||||||
|
public DateTime CreatedTime { get; set; }
|
||||||
|
|
||||||
|
[Column(Name = "updated_time")]
|
||||||
|
public DateTime UpdatedTime { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Entities
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品表实体(对应数据库表 user_goods_favorites)
|
||||||
|
/// </summary>
|
||||||
|
[Table(Name = "user_goods_favorites")]
|
||||||
|
public class UserGoodsFavoriteEntity
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 自增主键
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
|
||||||
|
[JsonIgnore]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名(同一用户不能重复收藏同一商品)
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "user_name", IsNullable = false, StringLength = 50)]
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏分组ID(0 表示默认分组),对应 user_goods_favorites_group.id
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "group_id", IsNullable = false)]
|
||||||
|
public int GroupId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商品编号,对应 goods.goods_id
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "goods_id", IsNullable = false)]
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏时间
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "created_at", IsNullable = false)]
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Entities
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏分组表实体(对应数据库表 user_goods_favorites_group)
|
||||||
|
/// </summary>
|
||||||
|
[Table(Name = "user_goods_favorites_group")]
|
||||||
|
public class UserGoodsFavoriteGroupEntity
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 自增主键,即收藏表 user_goods_favorites.group_id 的取值
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
|
||||||
|
[JsonIgnore]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "user_name", IsNullable = false, StringLength = 50)]
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分组名
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "group_name", IsNullable = false, StringLength = 255)]
|
||||||
|
public string GroupName { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Entities;
|
||||||
|
|
||||||
|
[Table(Name = "violation_reason")]
|
||||||
|
public class ViolationReasonEntity
|
||||||
|
{
|
||||||
|
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
|
||||||
|
public uint Id { get; set; }
|
||||||
|
|
||||||
|
[Column(Name = "name", StringLength = 100, IsNullable = false)]
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Column(Name = "is_violation", IsNullable = false)]
|
||||||
|
public bool IsViolation { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Enums
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 搜索排序方式
|
||||||
|
/// </summary>
|
||||||
|
public enum GoodsSearchSortBy
|
||||||
|
{
|
||||||
|
/// <summary>相关性(默认)</summary>
|
||||||
|
Relevance = 0,
|
||||||
|
|
||||||
|
/// <summary>价格从低到高</summary>
|
||||||
|
PriceAsc = 1,
|
||||||
|
|
||||||
|
/// <summary>价格从高到低</summary>
|
||||||
|
PriceDesc = 2,
|
||||||
|
|
||||||
|
/// <summary>销量从高到低</summary>
|
||||||
|
SoldDesc = 3,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Enums
|
||||||
|
{
|
||||||
|
public enum PlatformType
|
||||||
|
{
|
||||||
|
None = 0,
|
||||||
|
PDD = 1,
|
||||||
|
WX = 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace Store.Modules.CloudProduct.Enums
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品搜索排序方式
|
||||||
|
/// </summary>
|
||||||
|
public enum UserFavoritesSortBy
|
||||||
|
{
|
||||||
|
/// <summary>按收藏时间倒序(默认)</summary>
|
||||||
|
CreatedTimeDesc = 0,
|
||||||
|
|
||||||
|
/// <summary>按收藏时间正序</summary>
|
||||||
|
CreatedTimeAsc = 1,
|
||||||
|
|
||||||
|
/// <summary>价格从低到高</summary>
|
||||||
|
PriceAsc = 2,
|
||||||
|
|
||||||
|
/// <summary>价格从高到低</summary>
|
||||||
|
PriceDesc = 3,
|
||||||
|
|
||||||
|
/// <summary>销量从高到低</summary>
|
||||||
|
SoldDesc = 4,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using Store.Modules.CloudProduct.Enums;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.ImportConverters
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 导入商品数据转换器
|
||||||
|
/// </summary>
|
||||||
|
public interface IGoodsConverter
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 原始数据(JSON 原文)
|
||||||
|
/// </summary>
|
||||||
|
string RawData { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取转换器名称
|
||||||
|
/// </summary>
|
||||||
|
string ConverterName { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 支持的平台类型
|
||||||
|
/// </summary>
|
||||||
|
PlatformType Platform { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取内容
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="content">JSON 原文内容</param>
|
||||||
|
void ReadContent(string content);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 判断是否匹配当前转换器
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>是否匹配</returns>
|
||||||
|
bool IsMatch();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 转换为标准商品模型
|
||||||
|
/// </summary>
|
||||||
|
GoodsEntity Convert();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 转换器基类:统一实现读取、校验与转换骨架,子类只需实现匹配判定与字段映射。
|
||||||
|
/// </summary>
|
||||||
|
public abstract class GoodsConverter : IGoodsConverter
|
||||||
|
{
|
||||||
|
private bool _isMatch = false;
|
||||||
|
|
||||||
|
public string RawData { get; private set; } = null!;
|
||||||
|
|
||||||
|
public abstract string ConverterName { get; }
|
||||||
|
|
||||||
|
public abstract PlatformType Platform { get; }
|
||||||
|
|
||||||
|
void IGoodsConverter.ReadContent(string content)
|
||||||
|
{
|
||||||
|
ReadContent(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected virtual void ReadContent(string content)
|
||||||
|
{
|
||||||
|
RawData = content;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual bool IsMatch()
|
||||||
|
{
|
||||||
|
_isMatch = true;
|
||||||
|
return IsMatchCore();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 由子类实现的具体匹配判定
|
||||||
|
/// </summary>
|
||||||
|
protected abstract bool IsMatchCore();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 带校验的转换(基类统一实现)
|
||||||
|
/// </summary>
|
||||||
|
public virtual GoodsEntity Convert()
|
||||||
|
{
|
||||||
|
if (_isMatch == false) throw new Exception("未校验数据");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
JsonNode.Parse(RawData);
|
||||||
|
}
|
||||||
|
catch { throw new Exception("数据解析失败,不是有效的JSON格式"); }
|
||||||
|
|
||||||
|
var goods = ConvertCore();
|
||||||
|
if (goods == null)
|
||||||
|
throw new Exception("转换失败");
|
||||||
|
|
||||||
|
// 基础校验
|
||||||
|
if (goods.GoodsId == 0)
|
||||||
|
throw new Exception("商品ID不能为空");
|
||||||
|
|
||||||
|
return goods;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 由子类实现的具体字段映射
|
||||||
|
/// </summary>
|
||||||
|
protected abstract GoodsEntity ConvertCore();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.ImportConverters
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 导入商品转换工厂:按顺序尝试各转换器,返回标准商品模型。
|
||||||
|
/// </summary>
|
||||||
|
public class GoodsConverterFactory
|
||||||
|
{
|
||||||
|
private static readonly List<IGoodsConverter> _converters = new List<IGoodsConverter>
|
||||||
|
{
|
||||||
|
new PddGoodsConverter(),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据本地 JSON 文件路径转换。
|
||||||
|
/// </summary>
|
||||||
|
public static GoodsEntity? Convert(string filePath)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(filePath))
|
||||||
|
throw new ArgumentNullException(nameof(filePath));
|
||||||
|
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
throw new FileNotFoundException("找不到导入文件", filePath);
|
||||||
|
|
||||||
|
var content = File.ReadAllText(filePath);
|
||||||
|
return ConvertContent(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据 JSON 内容字符串转换。
|
||||||
|
/// </summary>
|
||||||
|
public static GoodsEntity? ConvertContent(string content)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(content))
|
||||||
|
throw new ArgumentNullException(nameof(content));
|
||||||
|
|
||||||
|
foreach (var converter in _converters)
|
||||||
|
{
|
||||||
|
converter.ReadContent(content);
|
||||||
|
if (converter.IsMatch())
|
||||||
|
{
|
||||||
|
var goods = converter.Convert();
|
||||||
|
if (goods != null)
|
||||||
|
return goods;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using Store.Modules.CloudProduct.Enums;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.ImportConverters
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// PDD 前端商品详情数据转换器(数据源格式见 data.txt)
|
||||||
|
/// </summary>
|
||||||
|
internal class PddGoodsConverter : GoodsConverter
|
||||||
|
{
|
||||||
|
public override string ConverterName => nameof(PddGoodsConverter);
|
||||||
|
|
||||||
|
public override PlatformType Platform => PlatformType.PDD;
|
||||||
|
|
||||||
|
protected override bool IsMatchCore()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (JsonNode.Parse(RawData) is not JsonObject root)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// data.txt:顶层包含 goods.goods_id
|
||||||
|
if (root["goods"] is JsonObject goodsObj && goodsObj["goods_id"] != null)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
// 也兼容顶层直接是商品对象的情况
|
||||||
|
if (root["goods_id"] != null && (root["goods_name"] != null || root["title"] != null))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override GoodsEntity ConvertCore()
|
||||||
|
{
|
||||||
|
if (JsonNode.Parse(RawData) is not JsonObject root)
|
||||||
|
throw new Exception("无法解析 PDD 商品数据");
|
||||||
|
|
||||||
|
var goodsNode = root["goods"] as JsonObject ?? root;
|
||||||
|
var priceNode = root["price"] as JsonObject;
|
||||||
|
|
||||||
|
var goods = new GoodsEntity
|
||||||
|
{
|
||||||
|
Platform = (byte)PlatformType.PDD,
|
||||||
|
GoodsId = GetLong(goodsNode, "goods_id"),
|
||||||
|
Title = GetString(goodsNode, "goods_name")
|
||||||
|
?? GetString(goodsNode, "short_name")
|
||||||
|
?? string.Empty,
|
||||||
|
Description = GetString(goodsNode, "share_desc") ?? GetString(goodsNode, "short_name"),
|
||||||
|
ThumbUrl = GetString(goodsNode, "hd_url") ?? GetString(goodsNode, "thumb_url") ?? GetString(goodsNode, "hd_thumb_url") ?? GetString(goodsNode, "image_url"),
|
||||||
|
CatId1 = GetIntOrNull(goodsNode, "cat_id_1"),
|
||||||
|
CatId2 = GetIntOrNull(goodsNode, "cat_id_2"),
|
||||||
|
CatId3 = GetIntOrNull(goodsNode, "cat_id_3"),
|
||||||
|
CatId4 = GetIntOrNull(goodsNode, "cat_id_4"),
|
||||||
|
SoldQuantity = GetInt(goodsNode, "sold_quantity"),
|
||||||
|
Status = 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
var price = GetPriceRange(priceNode, root);
|
||||||
|
goods.MinPrice = price.Min;
|
||||||
|
goods.MaxPrice = price.Max;
|
||||||
|
|
||||||
|
return goods;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? GetString(JsonObject? obj, string key)
|
||||||
|
{
|
||||||
|
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (node is JsonValue value && value.TryGetValue<string>(out var str))
|
||||||
|
return str;
|
||||||
|
|
||||||
|
return node.ToJsonString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long GetLong(JsonObject? obj, string key)
|
||||||
|
{
|
||||||
|
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
if (node is JsonValue value)
|
||||||
|
{
|
||||||
|
if (value.TryGetValue<long>(out var l)) return l;
|
||||||
|
if (value.TryGetValue<decimal>(out var d)) return (long)d;
|
||||||
|
if (long.TryParse(value.ToString(), out var l2)) return l2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int GetInt(JsonObject? obj, string key)
|
||||||
|
{
|
||||||
|
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
if (node is JsonValue value)
|
||||||
|
{
|
||||||
|
if (value.TryGetValue<int>(out var i)) return i;
|
||||||
|
if (value.TryGetValue<long>(out var l)) return (int)l;
|
||||||
|
if (int.TryParse(value.ToString(), out var i2)) return i2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int? GetIntOrNull(JsonObject? obj, string key)
|
||||||
|
{
|
||||||
|
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (node is JsonValue value)
|
||||||
|
{
|
||||||
|
if (value.TryGetValue<int>(out var i) && i > 0) return i;
|
||||||
|
if (value.TryGetValue<long>(out var l) && l > 0) return (int)l;
|
||||||
|
if (int.TryParse(value.ToString(), out var i2) && i2 > 0) return i2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long? GetLongOrNull(JsonObject? obj, string key)
|
||||||
|
{
|
||||||
|
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (node is JsonValue value)
|
||||||
|
{
|
||||||
|
if (value.TryGetValue<long>(out var d)) return d;
|
||||||
|
if (value.TryGetValue<long>(out var l)) return l;
|
||||||
|
if (long.TryParse(value.ToString(), out var d2)) return d2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 计算价格区间。优先使用顶层 price 节点,其次遍历 sku。
|
||||||
|
/// </summary>
|
||||||
|
private static (long? Min, long? Max) GetPriceRange(JsonObject? priceNode, JsonObject root)
|
||||||
|
{
|
||||||
|
long? min = null;
|
||||||
|
long? max = null;
|
||||||
|
|
||||||
|
if (priceNode != null)
|
||||||
|
{
|
||||||
|
min = GetLongOrNull(priceNode, "min_group_price");
|
||||||
|
max = GetLongOrNull(priceNode, "max_group_price");
|
||||||
|
if (min.HasValue || max.HasValue)
|
||||||
|
return (min, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (root["sku"] is JsonArray skuArray && skuArray.Count > 0)
|
||||||
|
{
|
||||||
|
foreach (var item in skuArray.OfType<JsonObject>())
|
||||||
|
{
|
||||||
|
var price = GetLongOrNull(item, "group_price") ?? GetLongOrNull(item, "normal_price");
|
||||||
|
if (price == null) continue;
|
||||||
|
|
||||||
|
min = min.HasValue ? Math.Min(min.Value, price.Value) : price;
|
||||||
|
max = max.HasValue ? Math.Max(max.Value, price.Value) : price;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (min.HasValue || max.HasValue)
|
||||||
|
return (min, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using FreeSql;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Repositorys
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品仓储(对应 goods 表)
|
||||||
|
/// </summary>
|
||||||
|
public class GoodsRepository : BaseRepository<GoodsEntity>, IScopedDependency
|
||||||
|
{
|
||||||
|
public GoodsRepository([FromKeyedServices("CloudProductConnection")] IFreeSql fsql) : base(fsql)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
using FreeSql;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Repositorys;
|
||||||
|
|
||||||
|
public class GoodsViolationRepository(
|
||||||
|
[FromKeyedServices("CloudProductConnection")] IFreeSql fsql)
|
||||||
|
: BaseRepository<GoodsViolationEntity>(fsql), IScopedDependency
|
||||||
|
{
|
||||||
|
public Task<List<ViolationReasonDto>> GetReasonsAsync() => Orm.Select<ViolationReasonEntity>()
|
||||||
|
.OrderBy(x => x.Id).ToListAsync(x => new ViolationReasonDto
|
||||||
|
{
|
||||||
|
Name = x.Name,
|
||||||
|
IsViolation = x.IsViolation
|
||||||
|
});
|
||||||
|
|
||||||
|
public Task<List<long>> GetViolationIdsAsync(long[] ids) => Select
|
||||||
|
.Where(x => ids.Contains(x.GoodsId)).Distinct().ToListAsync(x => x.GoodsId);
|
||||||
|
|
||||||
|
public async Task<List<long>> GetOffShelfGoodsIdsAsync(long[] ids)
|
||||||
|
{
|
||||||
|
var records = await Select.Where(x => ids.Contains(x.GoodsId)).ToListAsync();
|
||||||
|
return records.GroupBy(x => x.GoodsId).Where(x => x.All(row => row.IsIndexDeleted))
|
||||||
|
.Select(x => x.Key).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解除违规和设置待同步必须一起提交,进程中断后后台索引任务仍可恢复。
|
||||||
|
public async Task<int> RemoveAndScheduleRestoreAsync(long[] ids)
|
||||||
|
{
|
||||||
|
using var unit = Orm.CreateUnitOfWork();
|
||||||
|
var violations = unit.GetRepository<GoodsViolationEntity>();
|
||||||
|
var goods = unit.GetRepository<GoodsEntity>();
|
||||||
|
var removedIds = await violations.Select.Where(x => ids.Contains(x.GoodsId)).Distinct().ToListAsync(x => x.GoodsId);
|
||||||
|
await violations.DeleteAsync(x => ids.Contains(x.GoodsId));
|
||||||
|
await goods.UpdateDiy.Set(x => x.IsSegmented, (byte)0)
|
||||||
|
.Where(x => ids.Contains(x.GoodsId) && x.Status == 0).ExecuteAffrowsAsync();
|
||||||
|
unit.Commit();
|
||||||
|
return removedIds.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<List<GoodsEntity>> GetRestorableGoodsAsync(long[] ids) => Orm.Select<GoodsEntity>()
|
||||||
|
.Where(x => ids.Contains(x.GoodsId) && x.Status == 0).ToListAsync();
|
||||||
|
|
||||||
|
public Task<int> MarkRestoredAsync(long[] ids) => Orm.Update<GoodsEntity>()
|
||||||
|
.Set(x => x.IsSegmented, (byte)1)
|
||||||
|
.Where(x => ids.Contains(x.GoodsId) && x.Status == 0).ExecuteAffrowsAsync();
|
||||||
|
|
||||||
|
// 调用方持有 GoodsIndexLock,事务内合并原因,避免并发覆盖。
|
||||||
|
public async Task<long[]> MergeAsync(Dictionary<long, string[]> items)
|
||||||
|
{
|
||||||
|
using var unit = Orm.CreateUnitOfWork();
|
||||||
|
var repository = unit.GetRepository<GoodsViolationEntity>();
|
||||||
|
var reasonRepository = unit.GetRepository<ViolationReasonEntity>();
|
||||||
|
var reasonIds = new Dictionary<string, uint>(StringComparer.Ordinal);
|
||||||
|
foreach (var name in items.Values.SelectMany(x => x).Distinct(StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
// 让数据库按字典表的排序规则匹配名称,与唯一索引保持一致。
|
||||||
|
var reason = await reasonRepository.Select.Where(x => x.Name == name).FirstAsync();
|
||||||
|
// 新类型只收录到字典,绝不因首次上报自动启用商品封禁。
|
||||||
|
reason ??= await reasonRepository.InsertAsync(new ViolationReasonEntity { Name = name, IsViolation = false });
|
||||||
|
// 数据库排序规则可能忽略部分字符差异;判定时仍要求名称完整相等。
|
||||||
|
if (reason.IsViolation && string.Equals(reason.Name, name, StringComparison.Ordinal))
|
||||||
|
reasonIds.Add(name, reason.Id);
|
||||||
|
}
|
||||||
|
var ids = items.Keys.ToArray();
|
||||||
|
var existing = (await repository.Select.Where(x => ids.Contains(x.GoodsId))
|
||||||
|
.ToListAsync()).ToLookup(x => x.GoodsId);
|
||||||
|
var now = DateTime.UtcNow;
|
||||||
|
var recordedIds = new List<long>();
|
||||||
|
foreach (var (goodsId, reasons) in items)
|
||||||
|
{
|
||||||
|
var accepted = reasons.Where(reasonIds.ContainsKey).Select(x => reasonIds[x]).Distinct().ToArray();
|
||||||
|
// 忽略原因仅记录字典,不新增或改变该商品已有的违规状态。
|
||||||
|
if (accepted.Length == 0) continue;
|
||||||
|
var rows = existing[goodsId].ToArray();
|
||||||
|
var previous = rows.Select(x => x.ReasonId).ToHashSet();
|
||||||
|
var added = accepted.Where(x => !previous.Contains(x)).ToArray();
|
||||||
|
if (added.Length == 0 && rows.All(x => x.IsIndexDeleted)) continue;
|
||||||
|
|
||||||
|
// 下架是商品级操作:新增原因或存在失败记录时,整件商品重新标记待下架。
|
||||||
|
foreach (var row in rows)
|
||||||
|
{
|
||||||
|
row.IsIndexDeleted = false;
|
||||||
|
row.UpdatedTime = now;
|
||||||
|
await repository.UpdateAsync(row);
|
||||||
|
}
|
||||||
|
foreach (var reasonId in added)
|
||||||
|
{
|
||||||
|
await repository.InsertAsync(new GoodsViolationEntity
|
||||||
|
{
|
||||||
|
GoodsId = goodsId, ReasonId = reasonId, IsIndexDeleted = false,
|
||||||
|
CreatedTime = now, UpdatedTime = now
|
||||||
|
});
|
||||||
|
}
|
||||||
|
recordedIds.Add(goodsId);
|
||||||
|
}
|
||||||
|
unit.Commit();
|
||||||
|
return recordedIds.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<int> MarkDeletedAsync(long[] ids) => Orm.Update<GoodsViolationEntity>()
|
||||||
|
.Set(x => x.IsIndexDeleted, true)
|
||||||
|
.Set(x => x.UpdatedTime, DateTime.UtcNow)
|
||||||
|
.Where(x => ids.Contains(x.GoodsId)).ExecuteAffrowsAsync();
|
||||||
|
|
||||||
|
public Task<List<long>> GetBatchAsync(long afterId, int size, bool pendingOnly) => Select
|
||||||
|
.Where(x => x.GoodsId > afterId)
|
||||||
|
.WhereIf(pendingOnly, x => !x.IsIndexDeleted)
|
||||||
|
.Distinct().OrderBy(x => x.GoodsId).Limit(size).ToListAsync(x => x.GoodsId);
|
||||||
|
|
||||||
|
public Task<List<long>> GetByReasonAsync(uint reasonId, long afterId, int size) => Select
|
||||||
|
.Where(x => x.ReasonId == reasonId)
|
||||||
|
.Where(x => x.GoodsId > afterId).OrderBy(x => x.GoodsId)
|
||||||
|
.Limit(size).ToListAsync(x => x.GoodsId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using FreeSql;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Repositorys
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏分组仓储(对应 user_goods_favorites_group 表)
|
||||||
|
/// </summary>
|
||||||
|
public class UserGoodsFavoriteGroupRepository : BaseRepository<UserGoodsFavoriteGroupEntity>, IScopedDependency
|
||||||
|
{
|
||||||
|
public UserGoodsFavoriteGroupRepository([FromKeyedServices("CloudProductConnection")] IFreeSql fsql) : base(fsql)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using FreeSql;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Repositorys
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品仓储(对应 user_goods_favorites 表)
|
||||||
|
/// </summary>
|
||||||
|
public class UserGoodsFavoriteRepository : BaseRepository<UserGoodsFavoriteEntity>, IScopedDependency
|
||||||
|
{
|
||||||
|
public UserGoodsFavoriteRepository([FromKeyedServices("CloudProductConnection")] IFreeSql fsql) : base(fsql)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Hangfire 定时任务:把数据库中未同步(IndexStatus=0)的商品写入 OpenSearch 分词索引。
|
||||||
|
/// </summary>
|
||||||
|
public class GoodsIndexJob
|
||||||
|
{
|
||||||
|
private readonly IServiceScopeFactory _scopeFactory;
|
||||||
|
private readonly IConfiguration _configuration;
|
||||||
|
private readonly ILogger<GoodsIndexJob> _logger;
|
||||||
|
|
||||||
|
public GoodsIndexJob(IServiceScopeFactory scopeFactory, IConfiguration configuration,ILogger<GoodsIndexJob> logger)
|
||||||
|
{
|
||||||
|
_scopeFactory = scopeFactory;
|
||||||
|
_configuration = configuration;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ProcessPendingAsync()
|
||||||
|
{
|
||||||
|
var batchSize = _configuration.GetValue<int?>("Indexing:BatchSize") ?? 1000;
|
||||||
|
using var scope = _scopeFactory.CreateScope();
|
||||||
|
var service = scope.ServiceProvider.GetRequiredService<GoodsService>();
|
||||||
|
var count = await service.IndexPendingGoodsAsync(batchSize);
|
||||||
|
_logger.LogInformation($"[Hangfire] 商品分词定时任务完成,本次同步 {count} 条");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using MySql.Data.MySqlClient;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services;
|
||||||
|
|
||||||
|
/// <summary>跨实例串行化违规上报和商品索引写入,防止下架后被旧批次写回。</summary>
|
||||||
|
public class GoodsIndexLock(IConfiguration configuration) : ISingletonDependency
|
||||||
|
{
|
||||||
|
public async Task<IAsyncDisposable> AcquireAsync()
|
||||||
|
{
|
||||||
|
// 禁用连接池:即使释放锁失败,关闭物理连接也会释放会话锁。
|
||||||
|
var settings = new MySqlConnectionStringBuilder(configuration["CloudProductConnection"])
|
||||||
|
{
|
||||||
|
Pooling = false
|
||||||
|
};
|
||||||
|
var connection = new MySqlConnection(settings.ConnectionString);
|
||||||
|
var name = "goods-index:" + Convert.ToHexString(SHA256.HashData(
|
||||||
|
Encoding.UTF8.GetBytes(settings.Database)))[..40];
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await connection.OpenAsync();
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = "SELECT GET_LOCK(@name, 30)";
|
||||||
|
command.CommandTimeout = 35;
|
||||||
|
command.Parameters.AddWithValue("@name", name);
|
||||||
|
var result = await command.ExecuteScalarAsync();
|
||||||
|
if (result == null || result == DBNull.Value || Convert.ToInt32(result) != 1)
|
||||||
|
throw new AppException("商品索引正在处理,请稍后重试");
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
await connection.DisposeAsync();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using Store.Modules.CloudProduct.Repositorys;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services
|
||||||
|
{
|
||||||
|
public interface IGoodsService : IScopedDependency
|
||||||
|
{
|
||||||
|
Task<int> DeleteGoodsAsync(IEnumerable<long> ids);
|
||||||
|
Task<List<GoodsEntity>> GetGoodsByGoodsIdsAsync(IEnumerable<long> goodsIds);
|
||||||
|
Task<GoodsImportResult> ImportGoodsAsync(IEnumerable<GoodsImportItem> items);
|
||||||
|
Task<int> IndexPendingGoodsAsync(int batchSize);
|
||||||
|
Task<long> RebuildSearchIndexAsync(IEnumerable<long>? ids = null);
|
||||||
|
Task<(List<GoodsEntity> List, long Total)> SearchGoodsAsync(GoodsSearchRequest request);
|
||||||
|
Task<int> UpdateThumbUrlAsync(IEnumerable<GoodsEntity> goodsList);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class GoodsService : IGoodsService
|
||||||
|
{
|
||||||
|
private readonly GoodsRepository _repository;
|
||||||
|
private readonly IOpenSearchService _searchService;
|
||||||
|
private readonly IRawDataStorage _rawDataStorage;
|
||||||
|
private readonly IConfiguration _configuration;
|
||||||
|
private readonly GoodsViolationService _violations;
|
||||||
|
|
||||||
|
public GoodsService(GoodsRepository repository, IOpenSearchService searchService, IRawDataStorage rawDataStorage, IConfiguration configuration, GoodsViolationService violations)
|
||||||
|
{
|
||||||
|
_violations = violations;
|
||||||
|
_repository = repository;
|
||||||
|
_searchService = searchService;
|
||||||
|
_rawDataStorage = rawDataStorage;
|
||||||
|
_configuration = configuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<(List<GoodsEntity> List, long Total)> SearchGoodsAsync(GoodsSearchRequest request)
|
||||||
|
{
|
||||||
|
// 1. 从搜索引擎获取标题匹配的商品
|
||||||
|
var searchResult = await _searchService.SearchByTitleAsync(request);
|
||||||
|
|
||||||
|
var goodsList = searchResult.Documents.Select(a => new GoodsEntity
|
||||||
|
{
|
||||||
|
Platform = a.Platform,
|
||||||
|
GoodsId = a.Id,
|
||||||
|
Title = a.Title,
|
||||||
|
CatId1 = a.CatId1,
|
||||||
|
CatId2 = a.CatId2,
|
||||||
|
CatId3 = a.CatId3,
|
||||||
|
CatId4 = a.CatId4,
|
||||||
|
MinPrice = a.MinPrice,
|
||||||
|
MaxPrice = 0,
|
||||||
|
SoldQuantity = a.SoldQuantity,
|
||||||
|
ThumbUrl = a.ThumbUrl,
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
return (goodsList, searchResult.Total);
|
||||||
|
|
||||||
|
//// 2. 构建数据库查询(只查正常状态,排除软删除)
|
||||||
|
//var query = _repository.Select.Where(x => x.Status == 0);
|
||||||
|
|
||||||
|
//// 如果有标题搜索,先用ID过滤
|
||||||
|
//if (goodsIds.Any())
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => goodsIds.Contains(x.GoodsId));
|
||||||
|
//}
|
||||||
|
|
||||||
|
//// 3. 价格区间查询
|
||||||
|
//if (request.MinPrice.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.MinPrice >= request.MinPrice.Value);
|
||||||
|
//}
|
||||||
|
//if (request.MaxPrice.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.MaxPrice <= request.MaxPrice.Value);
|
||||||
|
//}
|
||||||
|
|
||||||
|
//// 4. 类目查询
|
||||||
|
//if (request.CatId1.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.CatId1 == request.CatId1);
|
||||||
|
//}
|
||||||
|
//if (request.CatId2.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.CatId2 == request.CatId2);
|
||||||
|
//}
|
||||||
|
//if (request.CatId3.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.CatId3 == request.CatId3);
|
||||||
|
//}
|
||||||
|
//if (request.CatId4.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.CatId4 == request.CatId4);
|
||||||
|
//}
|
||||||
|
|
||||||
|
//// 5. 销量区间查询
|
||||||
|
//if (request.MinSoldQuantity.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.SoldQuantity >= request.MinSoldQuantity.Value);
|
||||||
|
//}
|
||||||
|
//if (request.MaxSoldQuantity.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.SoldQuantity <= request.MaxSoldQuantity.Value);
|
||||||
|
//}
|
||||||
|
|
||||||
|
//// 6. 平台过滤
|
||||||
|
//if (request.Platform.HasValue)
|
||||||
|
//{
|
||||||
|
// query = query.Where(x => x.Platform == request.Platform);
|
||||||
|
//}
|
||||||
|
|
||||||
|
//// 8. 获取总数
|
||||||
|
//total = await query.CountAsync();
|
||||||
|
|
||||||
|
//// 9. 排序
|
||||||
|
//if (!string.IsNullOrEmpty(request.SortBy))
|
||||||
|
//{
|
||||||
|
// var isAsc = request.SortOrder?.ToLower() == "asc";
|
||||||
|
// query = query.OrderByPropertyName(request.SortBy, isAsc);
|
||||||
|
//}
|
||||||
|
//else
|
||||||
|
//{
|
||||||
|
// query = query.OrderByDescending(x => x.CreatedTime);
|
||||||
|
//}
|
||||||
|
|
||||||
|
//// 10. 分页查询
|
||||||
|
//var list = await query
|
||||||
|
// //.Skip((request.PageIndex - 1) * request.PageSize)
|
||||||
|
// //.Limit(request.PageSize)
|
||||||
|
// .ToListAsync();
|
||||||
|
////内存排序
|
||||||
|
//var orderMap = goodsIds.Select((id, idx) => new { id, idx })
|
||||||
|
// .ToDictionary(x => x.id, x => x.idx);
|
||||||
|
//list = list.OrderBy(x => orderMap.TryGetValue(x.GoodsId, out var idx) ? idx : int.MaxValue)
|
||||||
|
// .ToList();
|
||||||
|
//return (list, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量导入商品:先落库(按平台 + 商品编号去重)+ 保存原始数据,
|
||||||
|
/// 然后根据配置决定“立即分词”还是“标记未同步交给后台任务分词”。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<GoodsImportResult> ImportGoodsAsync(IEnumerable<GoodsImportItem> items)
|
||||||
|
{
|
||||||
|
var result = new GoodsImportResult();
|
||||||
|
if (items == null)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
var indexImmediately = IsImmediateIndexing();
|
||||||
|
var documents = new List<GoodsSearchDocument>();
|
||||||
|
|
||||||
|
foreach (var item in items)
|
||||||
|
{
|
||||||
|
var goods = item?.Goods;
|
||||||
|
if (goods == null)
|
||||||
|
{
|
||||||
|
result.FailedCount++;
|
||||||
|
result.Errors.Add("商品数据为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var goodsId = goods.GoodsId;
|
||||||
|
if (goodsId == 0)
|
||||||
|
{
|
||||||
|
result.FailedCount++;
|
||||||
|
result.Errors.Add("商品编号(GoodsId)不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 导入时统一先标记“未同步”;立即分词成功后再置为“已同步”,
|
||||||
|
// 后台模式下保持“未同步”,由 Hangfire 定时任务分词。
|
||||||
|
goods.IsSegmented = 0;
|
||||||
|
var saved = await UpsertGoodsAsync(goods);
|
||||||
|
|
||||||
|
var rawData = item?.RawData ?? string.Empty;
|
||||||
|
if (!string.IsNullOrWhiteSpace(rawData))
|
||||||
|
{
|
||||||
|
await _rawDataStorage.SaveAsync(saved.GoodsId, rawData);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (indexImmediately)
|
||||||
|
{
|
||||||
|
documents.Add(new GoodsSearchDocument
|
||||||
|
{
|
||||||
|
Platform = saved.Platform,
|
||||||
|
Id = saved.GoodsId,
|
||||||
|
Title = saved.Title ?? string.Empty,
|
||||||
|
ThumbUrl = saved.ThumbUrl,
|
||||||
|
CatId1 = saved.CatId1,
|
||||||
|
CatId2 = saved.CatId2,
|
||||||
|
CatId3 = saved.CatId3,
|
||||||
|
CatId4 = saved.CatId4,
|
||||||
|
MinPrice = saved.MinPrice,
|
||||||
|
SoldQuantity = saved.SoldQuantity,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
result.SuccessCount++;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
result.FailedCount++;
|
||||||
|
result.Errors.Add($"GoodsId={goodsId}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (documents.Count > 0)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var indexedIds = await _searchService.BulkIndexGoodsAsync(documents);
|
||||||
|
await MarkIndexedAsync(indexedIds);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 写入失败时保持“未同步”,由后台定时任务重试
|
||||||
|
result.FailedCount += documents.Count;
|
||||||
|
result.SuccessCount -= documents.Count;
|
||||||
|
result.Errors.Add("写入 OpenSearch 失败: " + ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 后台任务:批量处理未同步(IsSegmented=0)的商品,写入 OpenSearch 后标记为已同步。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> IndexPendingGoodsAsync(int batchSize)
|
||||||
|
{
|
||||||
|
if (batchSize <= 0)
|
||||||
|
batchSize = 200;
|
||||||
|
|
||||||
|
var pending = await _repository.Select.As("g")
|
||||||
|
.Where(x => x.IsSegmented == 0 && x.Status == 0)
|
||||||
|
.Where("NOT EXISTS (SELECT 1 FROM goods_violation v WHERE v.goods_id = g.goods_id)")
|
||||||
|
.OrderBy(x => x.GoodsId)
|
||||||
|
.Limit(batchSize)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
if (pending.Count == 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
var documents = pending
|
||||||
|
.Select(x => new GoodsSearchDocument
|
||||||
|
{
|
||||||
|
Platform = x.Platform,
|
||||||
|
Id = x.GoodsId,
|
||||||
|
Title = x.Title ?? string.Empty,
|
||||||
|
ThumbUrl = x.ThumbUrl,
|
||||||
|
CatId1 = x.CatId1,
|
||||||
|
CatId2 = x.CatId2,
|
||||||
|
CatId3 = x.CatId3,
|
||||||
|
CatId4 = x.CatId4,
|
||||||
|
MinPrice = x.MinPrice,
|
||||||
|
SoldQuantity = x.SoldQuantity,
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var indexedIds = await _searchService.BulkIndexGoodsAsync(documents);
|
||||||
|
await MarkIndexedAsync(indexedIds);
|
||||||
|
return indexedIds.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 按平台 + 商品编号查找已存在记录,存在则更新,不存在则新增。
|
||||||
|
/// </summary>
|
||||||
|
private async Task<GoodsEntity> UpsertGoodsAsync(GoodsEntity goods)
|
||||||
|
{
|
||||||
|
var existing = await _repository.Select
|
||||||
|
.Where(x => x.Platform == goods.Platform && x.GoodsId == goods.GoodsId)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (existing != null)
|
||||||
|
{
|
||||||
|
goods.Id = existing.Id;
|
||||||
|
goods.GoodsId = existing.GoodsId;
|
||||||
|
goods.CreatedTime = existing.CreatedTime;
|
||||||
|
goods.UpdatedTime = DateTime.Now;
|
||||||
|
await _repository.UpdateAsync(goods);
|
||||||
|
return goods;
|
||||||
|
}
|
||||||
|
|
||||||
|
goods.CreatedTime = DateTime.Now;
|
||||||
|
goods.UpdatedTime = DateTime.Now;
|
||||||
|
return await _repository.InsertAsync(goods);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据商品编号(GoodsId)列表读取商品。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<List<GoodsEntity>> GetGoodsByGoodsIdsAsync(IEnumerable<long> goodsIds)
|
||||||
|
{
|
||||||
|
var idList = goodsIds?.ToList();
|
||||||
|
if (idList == null || idList.Count == 0)
|
||||||
|
return new List<GoodsEntity>();
|
||||||
|
|
||||||
|
return await _repository.Select
|
||||||
|
.Where(x => idList.Contains(x.GoodsId))
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 重新从数据库读取指定商品,覆盖 OpenSearch 中已有的分词并重新分词。
|
||||||
|
/// ids 为空时重建全部商品。重建成功的记录标记为已同步。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<long> RebuildSearchIndexAsync(IEnumerable<long>? ids = null)
|
||||||
|
{
|
||||||
|
await _violations.DeleteViolationIndexesAsync(pendingOnly: false);
|
||||||
|
var idList = ids?.Distinct().ToArray() ?? [];
|
||||||
|
long lastId = 0, count = 0;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var goodsList = await _repository.Select.As("g")
|
||||||
|
.Where(x => x.Status == 0 && x.GoodsId > 0 && x.Id > lastId)
|
||||||
|
.WhereIf(idList.Length > 0, x => idList.Contains(x.GoodsId))
|
||||||
|
.Where("NOT EXISTS (SELECT 1 FROM goods_violation v WHERE v.goods_id = g.goods_id)")
|
||||||
|
.OrderBy(x => x.Id).Limit(1000).ToListAsync();
|
||||||
|
if (goodsList.Count == 0) break;
|
||||||
|
var indexedIds = await _searchService.RebuildIndexAsync(goodsList);
|
||||||
|
await MarkIndexedAsync(indexedIds);
|
||||||
|
count += indexedIds.Length;
|
||||||
|
lastId = goodsList[^1].Id;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除商品:按配置决定软删除(Status=1)还是硬删除(物理删除),
|
||||||
|
/// 两种方式都会删除 OpenSearch 中对应的文档。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> DeleteGoodsAsync(IEnumerable<long> ids)
|
||||||
|
{
|
||||||
|
var idList = ids?.Distinct().ToList();
|
||||||
|
if (idList == null || idList.Count == 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
if (IsSoftDelete())
|
||||||
|
{
|
||||||
|
// 软删除:仅用 Status 标记(0正常 1已删除)
|
||||||
|
await _repository.Orm.Update<GoodsEntity>()
|
||||||
|
.Set(x => x.Status, (byte)1)
|
||||||
|
.Where(x => idList.Contains(x.GoodsId))
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 硬删除:直接删除数据库记录
|
||||||
|
await _repository.Orm.Delete<GoodsEntity>()
|
||||||
|
.Where(x => idList.Contains(x.GoodsId))
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 无论软删除还是硬删除,都要删除 OpenSearch 中的对应文档
|
||||||
|
await _searchService.DeleteDocumentsAsync(idList);
|
||||||
|
return idList.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量更新商品缩略图。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> UpdateThumbUrlAsync(IEnumerable<GoodsEntity> goodsList)
|
||||||
|
{
|
||||||
|
//string sql = _repository.Orm.Update<GoodsEntity>().SetSource(goodsList, a => a.GoodsId).UpdateColumns(a => new { a.ThumbUrl }).ToSql();
|
||||||
|
return await _repository.Orm.Update<GoodsEntity>()
|
||||||
|
.SetSource(goodsList, a => a.GoodsId)
|
||||||
|
.UpdateColumns(a => new { a.ThumbUrl })
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否导入时立即分词(Indexing:Mode = Immediate)。
|
||||||
|
/// </summary>
|
||||||
|
private bool IsImmediateIndexing()
|
||||||
|
{
|
||||||
|
var mode = _configuration.GetValue<string>("Indexing:Mode");
|
||||||
|
return string.Equals(mode, "Immediate", StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否软删除(Delete:SoftDelete,默认 true)。
|
||||||
|
/// </summary>
|
||||||
|
private bool IsSoftDelete()
|
||||||
|
{
|
||||||
|
return _configuration.GetValue<bool?>("Delete:SoftDelete") ?? true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task MarkIndexedAsync(IEnumerable<long> ids)
|
||||||
|
{
|
||||||
|
var idList = ids?.ToList();
|
||||||
|
if (idList == null || idList.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
await _repository.Orm.Update<GoodsEntity>()
|
||||||
|
.Set(x => x.IsSegmented, (byte)1)
|
||||||
|
.Where(x => idList.Contains(x.GoodsId))
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services;
|
||||||
|
|
||||||
|
public class GoodsViolationIndexJob(IServiceScopeFactory scopeFactory)
|
||||||
|
{
|
||||||
|
public async Task ProcessPendingAsync()
|
||||||
|
{
|
||||||
|
using var scope = scopeFactory.CreateScope();
|
||||||
|
await scope.ServiceProvider.GetRequiredService<GoodsViolationService>()
|
||||||
|
.DeleteViolationIndexesAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
using Store.Modules.CloudProduct.Repositorys;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services;
|
||||||
|
|
||||||
|
public class GoodsViolationService(
|
||||||
|
GoodsViolationRepository repository,
|
||||||
|
GoodsIndexLock indexLock,
|
||||||
|
IOpenSearchService search,
|
||||||
|
ILogger<GoodsViolationService> logger) : IScopedDependency
|
||||||
|
{
|
||||||
|
public Task<List<ViolationReasonDto>> GetReasonsAsync() => repository.GetReasonsAsync();
|
||||||
|
|
||||||
|
public static Dictionary<long, string[]> ValidateAndGroup(ReportGoodsViolationItem[]? items)
|
||||||
|
{
|
||||||
|
if (items == null || items.Length is < 1 or > 1000)
|
||||||
|
throw new AppException("每次请提供1-1000条违规记录", ResultCode.ValidationError);
|
||||||
|
for (var i = 0; i < items.Length; i++)
|
||||||
|
{
|
||||||
|
var item = items[i];
|
||||||
|
if (item == null || item.GoodsId <= 0 || string.IsNullOrWhiteSpace(item.Reasons)
|
||||||
|
|| item.Reasons.Trim().Length > 100)
|
||||||
|
throw new AppException($"第{i + 1}条记录须提供有效商品编号和一个违规原因,原因去除首尾空白后须为1-100个字符", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
return items.GroupBy(x => x.GoodsId).ToDictionary(x => x.Key,
|
||||||
|
x => x.Select(y => y.Reasons.Trim()).Distinct(StringComparer.Ordinal).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<ReportGoodsViolationsResult>> ReportAsync(ReportGoodsViolationItem[]? items)
|
||||||
|
{
|
||||||
|
var grouped = ValidateAndGroup(items);
|
||||||
|
await using var lease = await indexLock.AcquireAsync();
|
||||||
|
var pendingIds = await repository.MergeAsync(grouped);
|
||||||
|
if (pendingIds.Length > 0)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await search.DeleteDocumentsAsync(pendingIds);
|
||||||
|
await repository.MarkDeletedAsync(pendingIds);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "违规记录已保存,{Count}个商品等待重试下架", pendingIds.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 返回商品当前持久化状态,包括本次原因被忽略但历史已下架的商品。
|
||||||
|
var offShelfIds = (await repository.GetOffShelfGoodsIdsAsync(grouped.Keys.ToArray())).ToHashSet();
|
||||||
|
return grouped.Keys.Select(id => new ReportGoodsViolationsResult
|
||||||
|
{
|
||||||
|
GoodsId = id,
|
||||||
|
IsOffShelf = offShelfIds.Contains(id)
|
||||||
|
}).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<GoodsViolationStatus>> GetStatusAsync(long[]? ids)
|
||||||
|
{
|
||||||
|
if (ids == null || ids.Length is < 1 or > 1000 || ids.Any(x => x <= 0))
|
||||||
|
throw new AppException("请提供1-1000个正数商品编号", ResultCode.ValidationError);
|
||||||
|
var distinct = ids.Distinct().ToArray();
|
||||||
|
var violations = (await repository.GetViolationIdsAsync(distinct)).ToHashSet();
|
||||||
|
return distinct.Select(x => new GoodsViolationStatus { GoodsId = x, IsViolation = violations.Contains(x) }).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<RemoveGoodsViolationsResult> RemoveAsync(long[]? ids)
|
||||||
|
{
|
||||||
|
if (ids == null || ids.Length is < 1 or > 1000 || ids.Any(x => x <= 0))
|
||||||
|
throw new AppException("请提供1-1000个正数商品编号", ResultCode.ValidationError);
|
||||||
|
var distinct = ids.Distinct().ToArray();
|
||||||
|
var result = new RemoveGoodsViolationsResult();
|
||||||
|
await using (var lease = await indexLock.AcquireAsync())
|
||||||
|
result.RemovedCount = await repository.RemoveAndScheduleRestoreAsync(distinct);
|
||||||
|
|
||||||
|
// 索引服务自行持锁并再次检查违规,避免与新的上报交错时重新上架违规商品。
|
||||||
|
var goods = await repository.GetRestorableGoodsAsync(distinct);
|
||||||
|
var candidates = goods.Select(x => x.GoodsId).Distinct().ToArray();
|
||||||
|
result.SkippedGoodsIds = distinct.Except(candidates).ToArray();
|
||||||
|
if (candidates.Length == 0) return result;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var restored = await search.RebuildIndexAsync(goods);
|
||||||
|
if (restored.Length > 0)
|
||||||
|
{
|
||||||
|
await using var lease = await indexLock.AcquireAsync();
|
||||||
|
var blocked = await repository.GetViolationIdsAsync(restored);
|
||||||
|
restored = restored.Except(blocked).ToArray();
|
||||||
|
if (restored.Length > 0) await repository.MarkRestoredAsync(restored);
|
||||||
|
}
|
||||||
|
result.RestoredGoodsIds = restored;
|
||||||
|
result.SkippedGoodsIds = distinct.Except(restored).ToArray();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "已解除违规,{Count}个商品等待后台任务恢复索引", candidates.Length);
|
||||||
|
result.PendingRestoreGoodsIds = candidates;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暂不注册 HTTP 路由。
|
||||||
|
public Task<List<long>> GetGoodsIdsByReasonAsync(uint reasonId, long afterGoodsId = 0, int pageSize = 100)
|
||||||
|
{
|
||||||
|
if (reasonId == 0 || afterGoodsId < 0 || pageSize is < 1 or > 1000)
|
||||||
|
throw new AppException("原因ID或分页参数无效", ResultCode.ValidationError);
|
||||||
|
return repository.GetByReasonAsync(reasonId, afterGoodsId, pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteViolationIndexesAsync(bool pendingOnly = true)
|
||||||
|
{
|
||||||
|
long afterId = 0;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
await using var lease = await indexLock.AcquireAsync();
|
||||||
|
var ids = await repository.GetBatchAsync(afterId, 1000, pendingOnly);
|
||||||
|
if (ids.Count == 0) return;
|
||||||
|
await search.DeleteDocumentsAsync(ids);
|
||||||
|
await repository.MarkDeletedAsync(ids.ToArray());
|
||||||
|
afterId = ids[^1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,567 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using OpenSearch.Client;
|
||||||
|
using OpenSearch.Net;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using Store.Modules.CloudProduct.Enums;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services
|
||||||
|
{
|
||||||
|
public interface IOpenSearchService : ISingletonDependency
|
||||||
|
{
|
||||||
|
Task AddDocumentAsync(GoodsSearchDocument document);
|
||||||
|
Task<long[]> BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents);
|
||||||
|
Task<bool> ClearIndexAsync();
|
||||||
|
Task<long> CountDocumentsAsync();
|
||||||
|
Task<bool> CreateIndexAsync();
|
||||||
|
Task DeleteDocumentsAsync(IEnumerable<long> ids);
|
||||||
|
Task DeleteIndexAsync();
|
||||||
|
Task<OpenSearchStatusDto> GetStatusAsync();
|
||||||
|
Task<bool> IndexExistsAsync();
|
||||||
|
Task<bool> IsIndexMappingHealthyAsync();
|
||||||
|
Task RefreshIndexAsync();
|
||||||
|
Task<long[]> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList);
|
||||||
|
Task<(long Total, List<GoodsSearchDocument> Documents)> SearchByTitleAsync(GoodsSearchRequest request, GoodsSearchSortBy sortBy = GoodsSearchSortBy.Relevance);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class OpenSearchService : IOpenSearchService
|
||||||
|
{
|
||||||
|
private readonly string _nodeUrl;
|
||||||
|
private readonly string _indexName;
|
||||||
|
private readonly IOpenSearchClient _client = null!;
|
||||||
|
|
||||||
|
// 查询类操作(search/count/status/ping)统一超时
|
||||||
|
private static readonly TimeSpan QueryTimeout = TimeSpan.FromSeconds(5);
|
||||||
|
// 批量写入/建索引/删除索引等管理类操作超时(数据量大时需要更长,可挪到配置文件)
|
||||||
|
private static readonly TimeSpan AdminTimeout = TimeSpan.FromSeconds(30);
|
||||||
|
private readonly ILogger<OpenSearchService> _logger;
|
||||||
|
private readonly IFreeSql _database;
|
||||||
|
private readonly GoodsIndexLock _indexLock;
|
||||||
|
|
||||||
|
public OpenSearchService(IConfiguration configuration,ILogger<OpenSearchService> logger,
|
||||||
|
[FromKeyedServices("CloudProductConnection")] IFreeSql database, GoodsIndexLock indexLock)
|
||||||
|
{
|
||||||
|
_database = database;
|
||||||
|
_indexLock = indexLock;
|
||||||
|
var config = configuration.GetSection("Search");
|
||||||
|
_nodeUrl = config.GetValue<string>("Url") ?? "";
|
||||||
|
_indexName = config.GetValue<string>("IndexName") ?? "";
|
||||||
|
_client = CreateClient();
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
private IOpenSearchClient CreateClient()
|
||||||
|
{
|
||||||
|
var pool = new SingleNodeConnectionPool(new Uri(_nodeUrl));
|
||||||
|
var settings = new ConnectionSettings(pool)
|
||||||
|
.DefaultIndex(_indexName)
|
||||||
|
.DefaultMappingFor<GoodsSearchDocument>(m => m.IndexName(_indexName))
|
||||||
|
.RequestTimeout(QueryTimeout)
|
||||||
|
.MaxRetryTimeout(QueryTimeout)
|
||||||
|
.PrettyJson()
|
||||||
|
.DisableDirectStreaming(); // 便于调试打印请求/响应报文
|
||||||
|
|
||||||
|
return new OpenSearchClient(settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 1. 创建索引 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> CreateIndexAsync()
|
||||||
|
{
|
||||||
|
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (existsResponse.Exists)
|
||||||
|
{
|
||||||
|
if (await IsIndexMappingHealthyAsync())
|
||||||
|
{
|
||||||
|
Console.WriteLine($"索引 [{_indexName}] 已存在且映射正确,无需重复创建。");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"索引 [{_indexName}] 的映射不完整(可能由清空索引等操作造成),正在重建...");
|
||||||
|
var deleteResponse = await _client.Indices.DeleteAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (!deleteResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("删除损坏索引失败: " + deleteResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 优先尝试使用 IK 中文分词(需集群安装 analysis-ik 插件)
|
||||||
|
var createResponse = await TryCreateIndexAsync(useIk: true);
|
||||||
|
|
||||||
|
if (!createResponse.IsValid)
|
||||||
|
{
|
||||||
|
Console.WriteLine("IK 分词插件不可用,已回退到 standard 分析器,中文分词将失效,请检查集群是否安装 analysis-ik 插件。");
|
||||||
|
createResponse = await TryCreateIndexAsync(useIk: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (createResponse.IsValid)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"索引 [{_indexName}] 创建成功。");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new AppException("索引创建失败: " + createResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> IsIndexMappingHealthyAsync()
|
||||||
|
{
|
||||||
|
var mappingStatus = await GetIndexMappingStatusAsync();
|
||||||
|
return mappingStatus.Healthy;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<(bool Healthy, string? IndexAnalyzer, string? SearchAnalyzer)> GetIndexMappingStatusAsync()
|
||||||
|
{
|
||||||
|
var getResponse = await _client.Indices.GetAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
if (!getResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("读取索引映射失败: " + getResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
if (!getResponse.Indices.TryGetValue(_indexName, out var indexState))
|
||||||
|
{
|
||||||
|
return (false, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var mapping = indexState.Mappings;
|
||||||
|
if (mapping?.Properties == null
|
||||||
|
|| !mapping.Properties.TryGetValue(new PropertyName("title"), out var property)
|
||||||
|
|| property is not ITextProperty textProperty)
|
||||||
|
{
|
||||||
|
return (false, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var indexAnalyzer = textProperty.Analyzer;
|
||||||
|
var searchAnalyzer = textProperty.SearchAnalyzer;
|
||||||
|
var usesIk = indexAnalyzer == "ik_max_word" && searchAnalyzer == "ik_smart";
|
||||||
|
var usesStandard = indexAnalyzer == "standard" && searchAnalyzer == "standard";
|
||||||
|
return (usesIk || usesStandard, indexAnalyzer, searchAnalyzer);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<CreateIndexResponse> TryCreateIndexAsync(bool useIk)
|
||||||
|
{
|
||||||
|
var indexAnalyzer = useIk ? "ik_max_word" : "standard";
|
||||||
|
var searchAnalyzer = useIk ? "ik_smart" : "standard";
|
||||||
|
|
||||||
|
return await _client.Indices.CreateAsync(_indexName, c => c
|
||||||
|
.Settings(s => s
|
||||||
|
.NumberOfShards(1)
|
||||||
|
.NumberOfReplicas(0)
|
||||||
|
)
|
||||||
|
.Map<GoodsSearchDocument>(m => m
|
||||||
|
.Properties(p => p
|
||||||
|
.Number(n => n.Name(x => x.Id).Type(NumberType.Long))
|
||||||
|
.Text(t => t
|
||||||
|
.Name(x => x.Title)
|
||||||
|
.Analyzer(indexAnalyzer)
|
||||||
|
.SearchAnalyzer(searchAnalyzer)
|
||||||
|
)
|
||||||
|
.Number(n => n.Name(x => x.CatId1).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.CatId2).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.CatId3).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.CatId4).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.MinPrice).Type(NumberType.Long))
|
||||||
|
.Number(n => n.Name(x => x.SoldQuantity).Type(NumberType.Integer))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 2. 删除索引 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task DeleteIndexAsync()
|
||||||
|
{
|
||||||
|
var response = await _client.Indices.DeleteAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (!response.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("删除失败: " + response.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> IndexExistsAsync()
|
||||||
|
{
|
||||||
|
var response = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
return response.Exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task RefreshIndexAsync()
|
||||||
|
{
|
||||||
|
var response = await _client.Indices.RefreshAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (!response.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("刷新索引失败: " + response.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 3.1 批量写入商品搜索文档(存在则覆盖) ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<long[]> BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents)
|
||||||
|
{
|
||||||
|
if (documents == null) throw new ArgumentNullException(nameof(documents));
|
||||||
|
|
||||||
|
var list = documents.ToList();
|
||||||
|
if (list.Count == 0) return [];
|
||||||
|
await using var lease = await _indexLock.AcquireAsync();
|
||||||
|
var ids = list.Select(x => x.Id).Distinct().ToArray();
|
||||||
|
var blocked = (await _database.Select<GoodsViolationEntity>()
|
||||||
|
.Where(x => ids.Contains(x.GoodsId)).ToListAsync(x => x.GoodsId)).ToHashSet();
|
||||||
|
list = list.Where(x => !blocked.Contains(x.Id)).ToList();
|
||||||
|
if (list.Count == 0) return [];
|
||||||
|
|
||||||
|
// 确保索引已按 IK 分词映射创建,否则中文分词无效
|
||||||
|
await CreateIndexAsync();
|
||||||
|
|
||||||
|
var bulkResponse = await _client.BulkAsync(b => b
|
||||||
|
.Index(_indexName)
|
||||||
|
.IndexMany(list, (descriptor, doc) => descriptor.Id(doc.Id))
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!bulkResponse.IsValid || bulkResponse.Errors)
|
||||||
|
{
|
||||||
|
throw new AppException("写入 OpenSearch 失败: " + bulkResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 刷新索引,保证数据立即可搜索(仅用于演示,生产环境不建议频繁 Refresh)
|
||||||
|
await RefreshIndexAsync();
|
||||||
|
return list.Select(x => x.Id).Distinct().ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 3.2 根据数据库商品重建搜索索引 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<long[]> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList)
|
||||||
|
{
|
||||||
|
if (goodsList == null) throw new ArgumentNullException(nameof(goodsList));
|
||||||
|
|
||||||
|
var documents = goodsList
|
||||||
|
.Where(x => x != null && x.GoodsId > 0)
|
||||||
|
.Select(x => new GoodsSearchDocument
|
||||||
|
{
|
||||||
|
Platform = x.Platform,
|
||||||
|
ThumbUrl = x.ThumbUrl,
|
||||||
|
Id = x.GoodsId,
|
||||||
|
Title = x.Title ?? string.Empty,
|
||||||
|
CatId1 = x.CatId1,
|
||||||
|
CatId2 = x.CatId2,
|
||||||
|
CatId3 = x.CatId3,
|
||||||
|
CatId4 = x.CatId4,
|
||||||
|
MinPrice = x.MinPrice,
|
||||||
|
SoldQuantity = x.SoldQuantity
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
return await BulkIndexGoodsAsync(documents);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 3.3 按商品编号批量删除 OpenSearch 文档(软/硬删除共用) ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task DeleteDocumentsAsync(IEnumerable<long> ids)
|
||||||
|
{
|
||||||
|
var list = ids?.Distinct().ToList() ?? new List<long>();
|
||||||
|
if (list.Count == 0) return;
|
||||||
|
|
||||||
|
var exists = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
if (!exists.Exists)
|
||||||
|
{
|
||||||
|
if (exists.ApiCall?.HttpStatusCode == 404) return;
|
||||||
|
throw new AppException("检查 OpenSearch 索引失败: " + exists.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
var response = await _client.BulkAsync(b =>
|
||||||
|
{
|
||||||
|
foreach (var id in list)
|
||||||
|
{
|
||||||
|
b.Delete<GoodsSearchDocument>(d => d.Index(_indexName).Id(id));
|
||||||
|
}
|
||||||
|
b.RequestConfiguration(r => r.RequestTimeout(AdminTimeout));
|
||||||
|
return b;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ApiCall?.HttpStatusCode is not (>= 200 and < 300)
|
||||||
|
|| response.Items.Count != list.Count
|
||||||
|
|| response.Items.Any(x => x.Status != 404 && (x.Error != null || x.Status < 200 || x.Status >= 300)))
|
||||||
|
{
|
||||||
|
throw new AppException("删除 OpenSearch 文档失败: " + response.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
await RefreshIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 4. 手动新增一条搜索文档 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task AddDocumentAsync(GoodsSearchDocument document)
|
||||||
|
{
|
||||||
|
if (document == null) throw new ArgumentNullException(nameof(document));
|
||||||
|
await using var lease = await _indexLock.AcquireAsync();
|
||||||
|
if (await _database.Select<GoodsViolationEntity>().AnyAsync(x => x.GoodsId == document.Id))
|
||||||
|
throw new AppException("违规商品不能写入搜索索引");
|
||||||
|
|
||||||
|
var response = await _client.IndexAsync(document, i => i
|
||||||
|
.Index(_indexName)
|
||||||
|
.Id(document.Id)
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.IsValid)
|
||||||
|
{
|
||||||
|
await RefreshIndexAsync();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new AppException("新增失败: " + response.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 5. 分词搜索(分页 + 类目/价格/销量/平台过滤 + 排序) ============
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">搜索条件(关键词、类目、价格、销量、平台、分页)</param>
|
||||||
|
/// <param name="sortBy">排序方式</param>
|
||||||
|
public async Task<(long Total, List<GoodsSearchDocument> Documents)> SearchByTitleAsync(GoodsSearchRequest request,
|
||||||
|
GoodsSearchSortBy sortBy = GoodsSearchSortBy.Relevance)
|
||||||
|
{
|
||||||
|
var keyword = request.Title;
|
||||||
|
int? catId1 = request.CatId1;
|
||||||
|
int? catId2 = request.CatId2;
|
||||||
|
int? catId3 = request.CatId3;
|
||||||
|
int? catId4 = request.CatId4;
|
||||||
|
long? minPrice = request.MinPrice;
|
||||||
|
long? maxPrice = request.MaxPrice;
|
||||||
|
int? minSoldQuantity = request.MinSoldQuantity;
|
||||||
|
int? maxSoldQuantity = request.MaxSoldQuantity;
|
||||||
|
int? platform = request.Platform;
|
||||||
|
int pageIndex = request.PageIndex;
|
||||||
|
int pageSize = request.PageSize;
|
||||||
|
|
||||||
|
if (pageIndex < 1) pageIndex = 1;
|
||||||
|
if (pageSize < 1) pageSize = 20;
|
||||||
|
if (pageSize > 2000) pageSize = 2000; // 避免深分页/单页过大拖垮性能,按需调整上限
|
||||||
|
|
||||||
|
var from = (pageIndex - 1) * pageSize;
|
||||||
|
|
||||||
|
ISearchResponse<GoodsSearchDocument> searchResponse;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
searchResponse = await _client.SearchAsync<GoodsSearchDocument>(s => s
|
||||||
|
.Index(_indexName)
|
||||||
|
.Query(q => q
|
||||||
|
.Bool(b =>
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(keyword) == false)
|
||||||
|
{
|
||||||
|
b.Must(m => m.Match(mm => mm.Field(f => f.Title).Query(keyword)));
|
||||||
|
}
|
||||||
|
|
||||||
|
var filters = new List<Func<QueryContainerDescriptor<GoodsSearchDocument>, QueryContainer>>();
|
||||||
|
if (platform.HasValue && platform!.Value > 0) filters.Add(f => f.Term(t => t.Field(x => x.Platform).Value(platform.Value)));
|
||||||
|
|
||||||
|
if (catId1.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId1).Value(catId1.Value)));
|
||||||
|
if (catId2.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId2).Value(catId2.Value)));
|
||||||
|
if (catId3.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId3).Value(catId3.Value)));
|
||||||
|
if (catId4.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId4).Value(catId4.Value)));
|
||||||
|
|
||||||
|
if (minPrice.HasValue || maxPrice.HasValue)
|
||||||
|
{
|
||||||
|
filters.Add(f => f.Range(r =>
|
||||||
|
{
|
||||||
|
var range = r.Field(x => x.MinPrice);
|
||||||
|
if (minPrice.HasValue) range = range.GreaterThanOrEquals(minPrice.Value);
|
||||||
|
if (maxPrice.HasValue) range = range.LessThanOrEquals(maxPrice.Value);
|
||||||
|
return range;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (minSoldQuantity.HasValue || maxSoldQuantity.HasValue)
|
||||||
|
{
|
||||||
|
filters.Add(f => f.Range(r =>
|
||||||
|
{
|
||||||
|
var range = r.Field(x => x.SoldQuantity);
|
||||||
|
if (minSoldQuantity.HasValue) range = range.GreaterThanOrEquals(minSoldQuantity.Value);
|
||||||
|
if (maxSoldQuantity.HasValue) range = range.LessThanOrEquals(maxSoldQuantity.Value);
|
||||||
|
return range;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filters.Count > 0) b.Filter(filters.ToArray());
|
||||||
|
return b;
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.Sort(sort => sortBy switch
|
||||||
|
{
|
||||||
|
GoodsSearchSortBy.PriceAsc => sort.Ascending(f => f.MinPrice),
|
||||||
|
GoodsSearchSortBy.PriceDesc => sort.Descending(f => f.MinPrice),
|
||||||
|
GoodsSearchSortBy.SoldDesc => sort.Descending(f => f.SoldQuantity),
|
||||||
|
_ => sort.Descending(SortSpecialField.Score)
|
||||||
|
})
|
||||||
|
.From(from)
|
||||||
|
.Size(pageSize)
|
||||||
|
.TrackTotalHits(true) // 命中数超过 10000 时默认不精确统计,需要显式开启
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (OpenSearchClientException ex) when (ex.Response?.Success == false)
|
||||||
|
{
|
||||||
|
throw new AppException($"搜索超时或失败({QueryTimeout.TotalSeconds}秒): " + ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!searchResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("搜索失败: " + searchResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (searchResponse.Total, searchResponse.Documents.ToList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 6. 统计文档数 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<long> CountDocumentsAsync()
|
||||||
|
{
|
||||||
|
var countResponse = await _client.CountAsync<GoodsSearchDocument>(c => c
|
||||||
|
.Index(_indexName)
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
|
||||||
|
);
|
||||||
|
if (countResponse.IsValid)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"索引 [{_indexName}] 当前文档总数: {countResponse.Count}");
|
||||||
|
return countResponse.Count;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine("统计失败: " + countResponse.DebugInformation);
|
||||||
|
throw new AppException(countResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 7. 查询 OpenSearch 状态 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<OpenSearchStatusDto> GetStatusAsync()
|
||||||
|
{
|
||||||
|
var stopwatch = Stopwatch.StartNew();
|
||||||
|
var status = new OpenSearchStatusDto
|
||||||
|
{
|
||||||
|
NodeUrl = _nodeUrl,
|
||||||
|
IndexName = _indexName,
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var ping = await _client.PingAsync(p => p
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
status.Connected = ping.IsValid;
|
||||||
|
if (!ping.IsValid)
|
||||||
|
{
|
||||||
|
status.Message = ping.DebugInformation;
|
||||||
|
_logger.LogError(ping.DebugInformation);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
_logger.LogInformation("OpenSerach 已连接");
|
||||||
|
var clusterHealth = await _client.Cluster.HealthAsync(Indices.All, h => h
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
if (!clusterHealth.IsValid)
|
||||||
|
{
|
||||||
|
status.Message = clusterHealth.DebugInformation;
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
status.ClusterName = clusterHealth.ClusterName;
|
||||||
|
status.ClusterStatus = clusterHealth.Status.ToString().ToLowerInvariant();
|
||||||
|
status.NumberOfNodes = clusterHealth.NumberOfNodes;
|
||||||
|
status.NumberOfDataNodes = clusterHealth.NumberOfDataNodes;
|
||||||
|
status.ActivePrimaryShards = clusterHealth.ActivePrimaryShards;
|
||||||
|
status.ActiveShards = clusterHealth.ActiveShards;
|
||||||
|
status.RelocatingShards = clusterHealth.RelocatingShards;
|
||||||
|
status.InitializingShards = clusterHealth.InitializingShards;
|
||||||
|
status.UnassignedShards = clusterHealth.UnassignedShards;
|
||||||
|
status.IndexExists = await IndexExistsAsync();
|
||||||
|
|
||||||
|
if (status.IndexExists)
|
||||||
|
{
|
||||||
|
var mappingStatus = await GetIndexMappingStatusAsync();
|
||||||
|
status.MappingHealthy = mappingStatus.Healthy;
|
||||||
|
status.IndexAnalyzer = mappingStatus.IndexAnalyzer;
|
||||||
|
status.SearchAnalyzer = mappingStatus.SearchAnalyzer;
|
||||||
|
|
||||||
|
var count = await _client.CountAsync<GoodsSearchDocument>(c => c
|
||||||
|
.Index(_indexName)
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
status.DocumentCount = count.IsValid ? count.Count : -1;
|
||||||
|
if (!count.IsValid)
|
||||||
|
{
|
||||||
|
status.Message = count.DebugInformation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
status.Message = $"索引 [{_indexName}] 不存在";
|
||||||
|
}
|
||||||
|
|
||||||
|
status.Healthy = status.IndexExists
|
||||||
|
&& status.MappingHealthy
|
||||||
|
&& status.ClusterStatus != "red"
|
||||||
|
&& status.DocumentCount >= 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
status.Healthy = false;
|
||||||
|
status.Message = ex.Message;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
stopwatch.Stop();
|
||||||
|
status.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
|
||||||
|
}
|
||||||
|
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 清空索引:删除后按统一映射重建,重建期间该索引不可查(由后台定时任务负责回填数据,接受短暂空窗)
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> ClearIndexAsync()
|
||||||
|
{
|
||||||
|
await using var lease = await _indexLock.AcquireAsync();
|
||||||
|
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
if (!existsResponse.Exists)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"索引 {_indexName} 不存在");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var deleteResponse = await _client.Indices.DeleteAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (!deleteResponse.IsValid)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"删除索引 {_indexName} 失败: {deleteResponse.DebugInformation}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Console.WriteLine($"索引 {_indexName} 已删除");
|
||||||
|
|
||||||
|
var created = await CreateIndexAsync();
|
||||||
|
await _database.Update<GoodsEntity>().Set(x => x.IsSegmented, (byte)0)
|
||||||
|
.Where(x => x.Status == 0).ExecuteAffrowsAsync();
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品原始数据文件存储:按 goodsId % 100 分目录,文件名即商品ID,GZip 压缩保存。
|
||||||
|
/// </summary>
|
||||||
|
public interface IRawDataStorage : IScopedDependency
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 保存原始数据,返回保存后的完整路径。
|
||||||
|
/// </summary>
|
||||||
|
Task<string> SaveAsync(long goodsId, string rawData);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取并解压原始数据;文件不存在时返回 null。
|
||||||
|
/// </summary>
|
||||||
|
Task<string?> ReadAsync(long goodsId);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 判断指定商品的原始数据文件是否存在。
|
||||||
|
/// </summary>
|
||||||
|
bool Exists(long goodsId);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class RawDataStorage : IRawDataStorage
|
||||||
|
{
|
||||||
|
private readonly string _rootPath;
|
||||||
|
|
||||||
|
public RawDataStorage(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var configured = configuration.GetValue<string>("RawData:Path");
|
||||||
|
if (string.IsNullOrWhiteSpace(configured))
|
||||||
|
configured = "RawData";
|
||||||
|
|
||||||
|
_rootPath = Path.GetFullPath(configured);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<string> SaveAsync(long goodsId, string rawData)
|
||||||
|
{
|
||||||
|
var filePath = GetFilePath(goodsId);
|
||||||
|
var dir = Path.GetDirectoryName(filePath)!;
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
|
||||||
|
await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||||
|
await using var gzip = new GZipStream(fileStream, CompressionLevel.Fastest);
|
||||||
|
await using var writer = new StreamWriter(gzip, new UTF8Encoding(false));
|
||||||
|
await writer.WriteAsync(rawData);
|
||||||
|
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<string?> ReadAsync(long goodsId)
|
||||||
|
{
|
||||||
|
var filePath = GetFilePath(goodsId);
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
await using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||||
|
await using var gzip = new GZipStream(fileStream, CompressionMode.Decompress);
|
||||||
|
using var reader = new StreamReader(gzip, new UTF8Encoding(false));
|
||||||
|
return await reader.ReadToEndAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Exists(long goodsId)
|
||||||
|
{
|
||||||
|
return File.Exists(GetFilePath(goodsId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetFilePath(long goodsId)
|
||||||
|
{
|
||||||
|
var subDir = (goodsId % 100).ToString();
|
||||||
|
return Path.Combine(_rootPath, subDir, goodsId.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using OpenSearch.Client;
|
||||||
|
using OpenSearch.Net;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
using Store.Modules.CloudProduct.Enums;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品索引服务:负责收藏索引(Search:FavoritesIndexName)的
|
||||||
|
/// 创建、写入、删除、重建与检索,索引文档由 user_goods_favorites 关联 goods 补全而来。
|
||||||
|
/// </summary>
|
||||||
|
public interface IUserFavoritesIndexService : ISingletonDependency
|
||||||
|
{
|
||||||
|
/// <summary>检查索引是否存在</summary>
|
||||||
|
Task<bool> IndexExistsAsync();
|
||||||
|
|
||||||
|
/// <summary>检查索引映射(分析器)是否符合当前服务要求</summary>
|
||||||
|
Task<bool> IsIndexMappingHealthyAsync();
|
||||||
|
|
||||||
|
/// <summary>创建索引(含 IK 分词映射;已存在且映射正常时跳过)</summary>
|
||||||
|
Task<bool> CreateIndexAsync();
|
||||||
|
|
||||||
|
/// <summary>删除并重建索引(映射统一,重建期间该索引不可查)</summary>
|
||||||
|
Task<bool> ClearIndexAsync();
|
||||||
|
|
||||||
|
/// <summary>批量写入收藏文档(存在则覆盖)</summary>
|
||||||
|
Task IndexDocumentsAsync(IEnumerable<UserFavoritesSearchDocument> documents);
|
||||||
|
|
||||||
|
/// <summary>按文档Id批量删除收藏文档</summary>
|
||||||
|
Task DeleteDocumentsAsync(IEnumerable<string> documentIds);
|
||||||
|
|
||||||
|
/// <summary>统计索引文档数</summary>
|
||||||
|
Task<long> CountDocumentsAsync();
|
||||||
|
|
||||||
|
/// <summary>按用户检索收藏商品(标题/销量/价格/类目/分组)</summary>
|
||||||
|
Task<(long Total, List<UserFavoritesSearchDocument> Documents)> SearchAsync(UserFavoritesSearchRequest request, UserFavoritesSortBy sortBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class UserFavoritesIndexService : IUserFavoritesIndexService
|
||||||
|
{
|
||||||
|
private readonly string _nodeUrl;
|
||||||
|
private readonly string _indexName;
|
||||||
|
private readonly IOpenSearchClient _client = null!;
|
||||||
|
private readonly ILogger<UserFavoritesIndexService> _logger;
|
||||||
|
|
||||||
|
// 查询类操作(search/count/exists)统一超时
|
||||||
|
private static readonly TimeSpan QueryTimeout = TimeSpan.FromSeconds(5);
|
||||||
|
// 批量写入/建索引/删除索引等管理类操作超时(数据量大时需要更长)
|
||||||
|
private static readonly TimeSpan AdminTimeout = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
public UserFavoritesIndexService(IConfiguration configuration, ILogger<UserFavoritesIndexService> logger)
|
||||||
|
{
|
||||||
|
var config = configuration.GetSection("Search");
|
||||||
|
_nodeUrl = config.GetValue<string>("Url") ?? "";
|
||||||
|
_indexName = config.GetValue<string>("FavoritesIndexName") ?? "";
|
||||||
|
_logger = logger;
|
||||||
|
_client = CreateClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
private IOpenSearchClient CreateClient()
|
||||||
|
{
|
||||||
|
var pool = new SingleNodeConnectionPool(new Uri(_nodeUrl));
|
||||||
|
var settings = new ConnectionSettings(pool)
|
||||||
|
.DefaultIndex(_indexName)
|
||||||
|
.DefaultMappingFor<UserFavoritesSearchDocument>(m => m.IndexName(_indexName))
|
||||||
|
.RequestTimeout(QueryTimeout)
|
||||||
|
.MaxRetryTimeout(QueryTimeout)
|
||||||
|
.PrettyJson()
|
||||||
|
.DisableDirectStreaming();
|
||||||
|
|
||||||
|
return new OpenSearchClient(settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 1. 索引是否存在 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> IndexExistsAsync()
|
||||||
|
{
|
||||||
|
var response = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
return response.Exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 2. 索引映射是否健康 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> IsIndexMappingHealthyAsync()
|
||||||
|
{
|
||||||
|
var getResponse = await _client.Indices.GetAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
if (!getResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("读取收藏索引映射失败: " + getResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
if (!getResponse.Indices.TryGetValue(_indexName, out var indexState))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var mapping = indexState.Mappings;
|
||||||
|
if (mapping?.Properties == null
|
||||||
|
|| !mapping.Properties.TryGetValue(new PropertyName("title"), out var property)
|
||||||
|
|| property is not ITextProperty textProperty)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var indexAnalyzer = textProperty.Analyzer;
|
||||||
|
var searchAnalyzer = textProperty.SearchAnalyzer;
|
||||||
|
var usesIk = indexAnalyzer == "ik_max_word" && searchAnalyzer == "ik_smart";
|
||||||
|
var usesStandard = indexAnalyzer == "standard" && searchAnalyzer == "standard";
|
||||||
|
return usesIk || usesStandard;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 3. 创建索引 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> CreateIndexAsync()
|
||||||
|
{
|
||||||
|
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (existsResponse.Exists)
|
||||||
|
{
|
||||||
|
if (await IsIndexMappingHealthyAsync())
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogWarning("收藏索引 [{Index}] 的映射不完整,正在重建...", _indexName);
|
||||||
|
var deleteResponse = await _client.Indices.DeleteAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (!deleteResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("删除损坏的收藏索引失败: " + deleteResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 优先尝试使用 IK 中文分词(需集群安装 analysis-ik 插件)
|
||||||
|
var createResponse = await TryCreateIndexAsync(useIk: true);
|
||||||
|
|
||||||
|
if (!createResponse.IsValid)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("IK 分词插件不可用,收藏索引已回退到 standard 分析器,中文分词将失效。");
|
||||||
|
createResponse = await TryCreateIndexAsync(useIk: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!createResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("收藏索引创建失败: " + createResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("收藏索引 [{Index}] 创建成功。", _indexName);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<CreateIndexResponse> TryCreateIndexAsync(bool useIk)
|
||||||
|
{
|
||||||
|
var indexAnalyzer = useIk ? "ik_max_word" : "standard";
|
||||||
|
var searchAnalyzer = useIk ? "ik_smart" : "standard";
|
||||||
|
|
||||||
|
return await _client.Indices.CreateAsync(_indexName, c => c
|
||||||
|
.Settings(s => s
|
||||||
|
.NumberOfShards(1)
|
||||||
|
.NumberOfReplicas(0)
|
||||||
|
)
|
||||||
|
.Map<UserFavoritesSearchDocument>(m => m
|
||||||
|
.Properties(p => p
|
||||||
|
.Keyword(k => k.Name(x => x.Id))
|
||||||
|
.Number(n => n.Name(x => x.FavId).Type(NumberType.Long))
|
||||||
|
.Keyword(k => k.Name(x => x.UserName))
|
||||||
|
.Number(n => n.Name(x => x.GroupId).Type(NumberType.Integer))
|
||||||
|
.Keyword(k => k.Name(x => x.GroupName))
|
||||||
|
.Number(n => n.Name(x => x.GoodsId).Type(NumberType.Long))
|
||||||
|
.Number(n => n.Name(x => x.Platform).Type(NumberType.Byte))
|
||||||
|
.Text(t => t
|
||||||
|
.Name(x => x.Title)
|
||||||
|
.Analyzer(indexAnalyzer)
|
||||||
|
.SearchAnalyzer(searchAnalyzer)
|
||||||
|
)
|
||||||
|
.Text(t => t.Name(x => x.ThumbUrl))
|
||||||
|
.Number(n => n.Name(x => x.CatId1).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.CatId2).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.CatId3).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.CatId4).Type(NumberType.Integer))
|
||||||
|
.Number(n => n.Name(x => x.MinPrice).Type(NumberType.Long))
|
||||||
|
.Number(n => n.Name(x => x.SoldQuantity).Type(NumberType.Integer))
|
||||||
|
.Date(d => d.Name(x => x.CreatedAt))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 4. 删除并重建索引 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> ClearIndexAsync()
|
||||||
|
{
|
||||||
|
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||||
|
if (!existsResponse.Exists)
|
||||||
|
{
|
||||||
|
return await CreateIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
var deleteResponse = await _client.Indices.DeleteAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (!deleteResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException($"删除收藏索引 {_indexName} 失败: " + deleteResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("收藏索引 [{Index}] 已删除,准备重建。", _indexName);
|
||||||
|
return await CreateIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RefreshIndexAsync()
|
||||||
|
{
|
||||||
|
var response = await _client.Indices.RefreshAsync(_indexName, d => d
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
|
||||||
|
if (!response.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("刷新收藏索引失败: " + response.DebugInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 5. 批量写入收藏文档(存在则覆盖) ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task IndexDocumentsAsync(IEnumerable<UserFavoritesSearchDocument> documents)
|
||||||
|
{
|
||||||
|
if (documents == null) throw new ArgumentNullException(nameof(documents));
|
||||||
|
|
||||||
|
var list = documents.Where(x => x != null && string.IsNullOrWhiteSpace(x.Id) == false).ToList();
|
||||||
|
if (list.Count == 0) return;
|
||||||
|
|
||||||
|
await CreateIndexAsync();
|
||||||
|
|
||||||
|
var bulkResponse = await _client.BulkAsync(b => b
|
||||||
|
.Index(_indexName)
|
||||||
|
.IndexMany(list, (descriptor, doc) => descriptor.Id(doc.Id))
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!bulkResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("批量写入收藏索引失败: " + bulkResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
await RefreshIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 6. 按文档Id批量删除收藏文档 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task DeleteDocumentsAsync(IEnumerable<string> documentIds)
|
||||||
|
{
|
||||||
|
var list = documentIds?.Where(x => string.IsNullOrWhiteSpace(x) == false).Distinct().ToList() ?? new List<string>();
|
||||||
|
if (list.Count == 0) return;
|
||||||
|
|
||||||
|
if (await IndexExistsAsync() == false)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var response = await _client.BulkAsync(b =>
|
||||||
|
{
|
||||||
|
foreach (var id in list)
|
||||||
|
{
|
||||||
|
b.Delete<UserFavoritesSearchDocument>(d => d.Index(_indexName).Id(id));
|
||||||
|
}
|
||||||
|
b.RequestConfiguration(r => r.RequestTimeout(AdminTimeout));
|
||||||
|
return b;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("删除收藏索引文档失败: " + response.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
await RefreshIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 7. 统计文档数 ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<long> CountDocumentsAsync()
|
||||||
|
{
|
||||||
|
var countResponse = await _client.CountAsync<UserFavoritesSearchDocument>(c => c
|
||||||
|
.Index(_indexName)
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
|
||||||
|
);
|
||||||
|
if (!countResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("统计收藏索引失败: " + countResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
return countResponse.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ============ 8. 检索用户收藏商品(标题/价格/销量/类目/分组 + 排序 + 分页) ============
|
||||||
|
/// </summary>
|
||||||
|
public async Task<(long Total, List<UserFavoritesSearchDocument> Documents)> SearchAsync(UserFavoritesSearchRequest request, UserFavoritesSortBy sortBy)
|
||||||
|
{
|
||||||
|
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||||
|
if (string.IsNullOrWhiteSpace(request.UserName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var keyword = request.Title;
|
||||||
|
int? groupId = request.GroupId;
|
||||||
|
var groupName = request.GroupName;
|
||||||
|
int pageIndex = request.PageIndex;
|
||||||
|
int pageSize = request.PageSize;
|
||||||
|
|
||||||
|
if (pageIndex < 1) pageIndex = 1;
|
||||||
|
if (pageSize < 1) pageSize = 20;
|
||||||
|
if (pageSize > 2000) pageSize = 2000; // 避免深分页/单页过大拖垮性能
|
||||||
|
|
||||||
|
var from = (pageIndex - 1) * pageSize;
|
||||||
|
|
||||||
|
ISearchResponse<UserFavoritesSearchDocument> searchResponse;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
searchResponse = await _client.SearchAsync<UserFavoritesSearchDocument>(s => s
|
||||||
|
.Index(_indexName)
|
||||||
|
.Query(q => q
|
||||||
|
.Bool(b =>
|
||||||
|
{
|
||||||
|
var filters = new List<Func<QueryContainerDescriptor<UserFavoritesSearchDocument>, QueryContainer>>();
|
||||||
|
|
||||||
|
// 只检索当前用户自己的收藏 —— 放进 filters,避免被后面的 Filter 覆盖
|
||||||
|
filters.Add(f => f.Term(t => t.Field(x => x.UserName).Value(request.UserName)));
|
||||||
|
|
||||||
|
if (groupId.HasValue)
|
||||||
|
{
|
||||||
|
filters.Add(f => f.Term(t => t.Field(x => x.GroupId).Value(groupId.Value)));
|
||||||
|
}
|
||||||
|
else if (string.IsNullOrWhiteSpace(groupName) == false)
|
||||||
|
{
|
||||||
|
filters.Add(f => f.Term(t => t.Field(x => x.GroupName).Value(groupName)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Platform.HasValue && request.Platform.Value > 0)
|
||||||
|
{
|
||||||
|
filters.Add(f => f.Term(t => t.Field(x => x.Platform).Value(request.Platform.Value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.CatId1.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId1).Value(request.CatId1.Value)));
|
||||||
|
if (request.CatId2.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId2).Value(request.CatId2.Value)));
|
||||||
|
if (request.CatId3.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId3).Value(request.CatId3.Value)));
|
||||||
|
if (request.CatId4.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId4).Value(request.CatId4.Value)));
|
||||||
|
|
||||||
|
if (request.MinPrice.HasValue || request.MaxPrice.HasValue)
|
||||||
|
{
|
||||||
|
filters.Add(f => f.Range(r =>
|
||||||
|
{
|
||||||
|
var range = r.Field(x => x.MinPrice);
|
||||||
|
if (request.MinPrice.HasValue) range = range.GreaterThanOrEquals(request.MinPrice.Value);
|
||||||
|
if (request.MaxPrice.HasValue) range = range.LessThanOrEquals(request.MaxPrice.Value);
|
||||||
|
return range;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.MinSoldQuantity.HasValue || request.MaxSoldQuantity.HasValue)
|
||||||
|
{
|
||||||
|
filters.Add(f => f.Range(r =>
|
||||||
|
{
|
||||||
|
var range = r.Field(x => x.SoldQuantity);
|
||||||
|
if (request.MinSoldQuantity.HasValue) range = range.GreaterThanOrEquals(request.MinSoldQuantity.Value);
|
||||||
|
if (request.MaxSoldQuantity.HasValue) range = range.LessThanOrEquals(request.MaxSoldQuantity.Value);
|
||||||
|
return range;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 统一一次性应用所有 filter,避免覆盖
|
||||||
|
b.Filter(filters.ToArray());
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(keyword) == false)
|
||||||
|
{
|
||||||
|
b.Must(m => m.Match(mm => mm.Field(f => f.Title).Query(keyword)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return b;
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.Sort(sort => sortBy switch
|
||||||
|
{
|
||||||
|
UserFavoritesSortBy.CreatedTimeAsc => sort.Ascending(f => f.CreatedAt),
|
||||||
|
UserFavoritesSortBy.PriceAsc => sort.Ascending(f => f.MinPrice),
|
||||||
|
UserFavoritesSortBy.PriceDesc => sort.Descending(f => f.MinPrice),
|
||||||
|
UserFavoritesSortBy.SoldDesc => sort.Descending(f => f.SoldQuantity),
|
||||||
|
_ => sort.Descending(f => f.CreatedAt)
|
||||||
|
})
|
||||||
|
.From(from)
|
||||||
|
.Size(pageSize)
|
||||||
|
.TrackTotalHits(true)
|
||||||
|
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
|
||||||
|
);}
|
||||||
|
catch (OpenSearchClientException ex) when (ex.Response?.Success == false)
|
||||||
|
{
|
||||||
|
throw new AppException($"收藏检索超时或失败({QueryTimeout.TotalSeconds}秒): " + ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!searchResponse.IsValid)
|
||||||
|
{
|
||||||
|
throw new AppException("收藏检索失败: " + searchResponse.DebugInformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (searchResponse.Total, searchResponse.Documents.ToList());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,603 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Framework.Commons;
|
||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Store.Modules.CloudProduct.Dtos;
|
||||||
|
using Store.Modules.CloudProduct.Entities;
|
||||||
|
using Store.Modules.CloudProduct.Enums;
|
||||||
|
using Store.Modules.CloudProduct.Repositorys;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct.Services
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户收藏商品业务:收藏/取消收藏(数据库 + 收藏索引同步写入)、收藏分组维护、收藏状态查询、收藏检索与索引重建。
|
||||||
|
/// </summary>
|
||||||
|
public interface IUserFavoritesService : IScopedDependency
|
||||||
|
{
|
||||||
|
/// <summary>批量收藏商品,返回本次成功收藏的商品数量(已收藏的商品视为修改收藏分组)</summary>
|
||||||
|
Task<int> AddFavoritesAsync(AddUserFavoriteRequest request);
|
||||||
|
|
||||||
|
/// <summary>批量取消收藏,返回实际取消的条数</summary>
|
||||||
|
Task<int> RemoveFavoritesAsync(RemoveUserFavoritesRequest request);
|
||||||
|
|
||||||
|
/// <summary>创建收藏分组:创建成功返回 true,同名分组已存在返回 false</summary>
|
||||||
|
Task<bool> CreateGroupAsync(CreateUserFavoriteGroupRequest request);
|
||||||
|
|
||||||
|
/// <summary>查询用户的收藏分组(含默认分组)及分组下收藏数量</summary>
|
||||||
|
Task<List<UserFavoriteGroupDto>> GetGroupsAsync(string userName);
|
||||||
|
|
||||||
|
/// <summary>按 GoodsIds 顺序返回每个商品是否已被该用户收藏</summary>
|
||||||
|
Task<List<bool>> GetFavoriteStatusAsync(UserFavoriteStatusRequest request);
|
||||||
|
|
||||||
|
/// <summary>检索用户收藏的商品(标题/销量/价格/类目/分组)</summary>
|
||||||
|
Task<(List<UserFavoriteItem> List, long Total)> SearchFavoritesAsync(UserFavoritesSearchRequest request);
|
||||||
|
|
||||||
|
/// <summary>移除所有用户收藏索引并按数据库数据全量重建,返回重建的文档数</summary>
|
||||||
|
Task<long> RebuildSearchIndexAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class UserFavoritesService : IUserFavoritesService
|
||||||
|
{
|
||||||
|
/// <summary>未归属任何分组的收藏所使用的分组名(对应 group_id = 0)</summary>
|
||||||
|
public const string DefaultGroupName = "默认分组";
|
||||||
|
|
||||||
|
/// <summary>重建索引时单次 bulk 的文档数,避免一次请求过大</summary>
|
||||||
|
private const int RebuildBatchSize = 2000;
|
||||||
|
|
||||||
|
private readonly UserGoodsFavoriteRepository _favoriteRepository;
|
||||||
|
private readonly UserGoodsFavoriteGroupRepository _groupRepository;
|
||||||
|
private readonly GoodsRepository _goodsRepository;
|
||||||
|
private readonly IUserFavoritesIndexService _indexService;
|
||||||
|
private readonly ILogger<UserFavoritesService> _logger;
|
||||||
|
|
||||||
|
public UserFavoritesService(
|
||||||
|
UserGoodsFavoriteRepository favoriteRepository,
|
||||||
|
UserGoodsFavoriteGroupRepository groupRepository,
|
||||||
|
GoodsRepository goodsRepository,
|
||||||
|
IUserFavoritesIndexService indexService,
|
||||||
|
ILogger<UserFavoritesService> logger)
|
||||||
|
{
|
||||||
|
_favoriteRepository = favoriteRepository;
|
||||||
|
_groupRepository = groupRepository;
|
||||||
|
_goodsRepository = goodsRepository;
|
||||||
|
_indexService = indexService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量收藏商品:先落库(user_goods_favorites),再同步写入收藏索引;
|
||||||
|
/// 商品不存在/已删除的编号会被跳过,返回本次成功收藏的商品数量。
|
||||||
|
/// 任意一步失败都会回滚本次已写入的数据库记录,保证“数据库中有收藏 = 索引中可搜索到”。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> AddFavoritesAsync(AddUserFavoriteRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var userName = request.UserName?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(userName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var goodsIds = request.GoodsIds?.Where(x => x > 0).Distinct().ToList() ?? new List<long>();
|
||||||
|
if (goodsIds.Count == 0)
|
||||||
|
{
|
||||||
|
throw new AppException("请提供要收藏的商品编号", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.GroupId < 0)
|
||||||
|
{
|
||||||
|
throw new AppException("收藏分组无效", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 校验分组归属(分组ID > 0 时必须是该用户自己创建的分组)
|
||||||
|
if (request.GroupId > 0)
|
||||||
|
{
|
||||||
|
var group = await _groupRepository.Select
|
||||||
|
.Where(x => x.Id == request.GroupId && x.UserName == userName)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (group == null)
|
||||||
|
{
|
||||||
|
throw new AppException($"收藏分组不存在: {request.GroupId}", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var groupName = await ResolveGroupNameAsync(userName, request.GroupId);
|
||||||
|
|
||||||
|
// 2. 批量取商品快照(不存在/已删除的商品不收藏,直接跳过)
|
||||||
|
var goodsList = await _goodsRepository.Select
|
||||||
|
.Where(x => goodsIds.Contains(x.GoodsId) && x.Status == 0)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
if (goodsList.Count == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var goodsMap = new Dictionary<long, GoodsEntity>();
|
||||||
|
foreach (var goods in goodsList)
|
||||||
|
{
|
||||||
|
goodsMap[goods.GoodsId] = goods;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 批量取已存在的收藏记录
|
||||||
|
var existingList = await _favoriteRepository.Select
|
||||||
|
.Where(x => x.UserName == userName && goodsIds.Contains(x.GoodsId))
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var existingMap = new Dictionary<long, UserGoodsFavoriteEntity>();
|
||||||
|
foreach (var favorite in existingList)
|
||||||
|
{
|
||||||
|
existingMap[favorite.GoodsId] = favorite;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 逐条落库:不存在则新增,已存在且分组不同则修改分组
|
||||||
|
var insertedIds = new List<long>();
|
||||||
|
var changedGroupIds = new List<(long Id, int PreviousGroupId)>();
|
||||||
|
var documents = new List<UserFavoritesSearchDocument>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var goods in goodsMap.Values)
|
||||||
|
{
|
||||||
|
if (existingMap.TryGetValue(goods.GoodsId, out var favorite) == false)
|
||||||
|
{
|
||||||
|
favorite = new UserGoodsFavoriteEntity
|
||||||
|
{
|
||||||
|
UserName = userName,
|
||||||
|
GoodsId = goods.GoodsId,
|
||||||
|
GroupId = request.GroupId,
|
||||||
|
CreatedAt = DateTime.Now,
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _favoriteRepository.InsertAsync(favorite);
|
||||||
|
insertedIds.Add(favorite.Id);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 并发收藏同一商品时可能命中唯一键 uk_user_goods,回读已存在记录后按“修改分组”处理
|
||||||
|
favorite = await _favoriteRepository.Select
|
||||||
|
.Where(x => x.UserName == userName && x.GoodsId == goods.GoodsId)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (favorite == null)
|
||||||
|
{
|
||||||
|
throw new AppException($"收藏商品失败({goods.GoodsId}): {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (favorite.GroupId != request.GroupId)
|
||||||
|
{
|
||||||
|
changedGroupIds.Add((favorite.Id, favorite.GroupId));
|
||||||
|
await _favoriteRepository.Orm.Update<UserGoodsFavoriteEntity>()
|
||||||
|
.Set(x => x.GroupId, request.GroupId)
|
||||||
|
.Where(x => x.Id == favorite.Id)
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
favorite.GroupId = request.GroupId;
|
||||||
|
}
|
||||||
|
|
||||||
|
documents.Add(BuildDocument(favorite, goods, groupName));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
await CompensateWriteFailureAsync(insertedIds, changedGroupIds);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 批量同步写入索引
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _indexService.IndexDocumentsAsync(documents);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
await CompensateWriteFailureAsync(insertedIds, changedGroupIds);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
return documents.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量取消收藏:先删除数据库记录,再删除索引文档;
|
||||||
|
/// 索引删除失败时回补数据库记录,避免“库里有收藏但搜索不到”。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> RemoveFavoritesAsync(RemoveUserFavoritesRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var userName = request.UserName?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(userName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var goodsIds = request.GoodsIds?.Where(x => x > 0).Distinct().ToList() ?? new List<long>();
|
||||||
|
if (goodsIds.Count == 0)
|
||||||
|
{
|
||||||
|
throw new AppException("请提供要取消收藏的商品编号", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var favorites = await _favoriteRepository.Select
|
||||||
|
.Where(x => x.UserName == userName && goodsIds.Contains(x.GoodsId))
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
if (favorites.Count == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _favoriteRepository.Orm.Delete<UserGoodsFavoriteEntity>()
|
||||||
|
.Where(x => x.UserName == userName && goodsIds.Contains(x.GoodsId))
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _indexService.DeleteDocumentsAsync(
|
||||||
|
favorites.Select(x => UserFavoritesSearchDocument.BuildId(x.UserName, x.GoodsId)));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 索引删除失败:回补数据库记录(自增主键会重新生成,检索以“用户名+商品编号”为准,不受影响)
|
||||||
|
_logger.LogError(ex, "删除收藏索引失败,回补数据库收藏记录。UserName={UserName} Count={Count}", userName, favorites.Count);
|
||||||
|
await _favoriteRepository.InsertAsync(favorites);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
return favorites.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建收藏分组:创建成功返回 true,同一用户同名分组已存在返回 false。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> CreateGroupAsync(CreateUserFavoriteGroupRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var userName = request.UserName?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(userName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var groupName = request.GroupName?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(groupName))
|
||||||
|
{
|
||||||
|
throw new AppException("分组名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (groupName.Length > 255)
|
||||||
|
{
|
||||||
|
throw new AppException("分组名长度不能超过255个字符", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var existing = await _groupRepository.Select
|
||||||
|
.Where(x => x.UserName == userName && x.GroupName == groupName)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (existing != null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _groupRepository.InsertAsync(new UserGoodsFavoriteGroupEntity
|
||||||
|
{
|
||||||
|
UserName = userName,
|
||||||
|
GroupName = groupName,
|
||||||
|
});
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 查询用户的收藏分组及分组下收藏数量,默认分组(分组ID=0)存在收藏时一并返回。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<List<UserFavoriteGroupDto>> GetGroupsAsync(string userName)
|
||||||
|
{
|
||||||
|
userName = userName?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(userName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var groups = await _groupRepository.Select
|
||||||
|
.Where(x => x.UserName == userName)
|
||||||
|
.OrderBy(x => x.Id)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var countList = await _favoriteRepository.Select
|
||||||
|
.Where(x => x.UserName == userName)
|
||||||
|
.GroupBy(x => x.GroupId)
|
||||||
|
.ToListAsync(x => new { GroupId = x.Key, Count = x.Count() });
|
||||||
|
|
||||||
|
var countMap = countList.ToDictionary(x => x.GroupId, x => (long)x.Count);
|
||||||
|
|
||||||
|
var result = new List<UserFavoriteGroupDto>();
|
||||||
|
|
||||||
|
if (countMap.TryGetValue(0, out var defaultCount) && defaultCount > 0)
|
||||||
|
{
|
||||||
|
result.Add(new UserFavoriteGroupDto
|
||||||
|
{
|
||||||
|
Id = 0,
|
||||||
|
UserName = userName,
|
||||||
|
GroupName = DefaultGroupName,
|
||||||
|
FavoriteCount = defaultCount,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
result.AddRange(groups.Select(x => new UserFavoriteGroupDto
|
||||||
|
{
|
||||||
|
Id = x.Id,
|
||||||
|
UserName = x.UserName,
|
||||||
|
GroupName = x.GroupName,
|
||||||
|
FavoriteCount = countMap.TryGetValue((int)x.Id, out var count) ? count : 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 按 GoodsIds 顺序返回每个商品是否已被该用户收藏(商品编号无效的返回 false)。
|
||||||
|
/// 以数据库为准,不依赖索引,索引重建期间结果依然准确。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<List<bool>> GetFavoriteStatusAsync(UserFavoriteStatusRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var userName = request.UserName?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(userName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var goodsIds = request.GoodsIds ?? new List<long>();
|
||||||
|
if (goodsIds.Count == 0)
|
||||||
|
{
|
||||||
|
return new List<bool>();
|
||||||
|
}
|
||||||
|
|
||||||
|
var validIds = goodsIds.Where(x => x > 0).Distinct().ToList();
|
||||||
|
var favoritedIds = new HashSet<long>();
|
||||||
|
|
||||||
|
if (validIds.Count > 0)
|
||||||
|
{
|
||||||
|
var favorited = await _favoriteRepository.Select
|
||||||
|
.Where(x => x.UserName == userName && validIds.Contains(x.GoodsId))
|
||||||
|
.ToListAsync(x => x.GoodsId);
|
||||||
|
|
||||||
|
favoritedIds = favorited.ToHashSet();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 结果与入参顺序一一对应,前台可直接按下标渲染
|
||||||
|
return goodsIds.Select(x => x > 0 && favoritedIds.Contains(x)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从收藏索引检索当前用户的收藏商品。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<(List<UserFavoriteItem> List, long Total)> SearchFavoritesAsync(UserFavoritesSearchRequest request)
|
||||||
|
{
|
||||||
|
if (request == null)
|
||||||
|
{
|
||||||
|
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
var userName = request.UserName?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(userName))
|
||||||
|
{
|
||||||
|
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.UserName = userName;
|
||||||
|
|
||||||
|
var searchResult = await _indexService.SearchAsync(request, ParseSortBy(request.SortBy));
|
||||||
|
var list = searchResult.Documents.Select(ToItem).ToList();
|
||||||
|
return (list, searchResult.Total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 移除所有用户收藏索引并重新创建,然后从 user_goods_favorites 关联 goods 全量回填。
|
||||||
|
/// </summary>
|
||||||
|
public async Task<long> RebuildSearchIndexAsync()
|
||||||
|
{
|
||||||
|
// 1. 删除并重建索引(清空所有用户收藏索引)
|
||||||
|
await _indexService.ClearIndexAsync();
|
||||||
|
|
||||||
|
// 2. 从数据库读取全部收藏记录
|
||||||
|
var favorites = await _favoriteRepository.Select
|
||||||
|
.OrderBy(x => x.Id)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
if (favorites.Count == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 关联 goods 补全商品数据(标题/价格/销量/类目/平台/缩略图)
|
||||||
|
var goodsIds = favorites.Select(x => x.GoodsId).Distinct().ToList();
|
||||||
|
var goodsList = await _goodsRepository.Select
|
||||||
|
.Where(x => goodsIds.Contains(x.GoodsId))
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var goodsMap = new Dictionary<long, GoodsEntity>();
|
||||||
|
foreach (var goods in goodsList)
|
||||||
|
{
|
||||||
|
goodsMap[goods.GoodsId] = goods;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 关联分组表补全分组名
|
||||||
|
var groupIds = favorites.Where(x => x.GroupId > 0).Select(x => (long)x.GroupId).Distinct().ToList();
|
||||||
|
var groupMap = new Dictionary<int, string>();
|
||||||
|
|
||||||
|
if (groupIds.Count > 0)
|
||||||
|
{
|
||||||
|
var groups = await _groupRepository.Select
|
||||||
|
.Where(x => groupIds.Contains(x.Id))
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
foreach (var group in groups)
|
||||||
|
{
|
||||||
|
groupMap[(int)group.Id] = group.GroupName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var documents = new List<UserFavoritesSearchDocument>();
|
||||||
|
var missingGoodsCount = 0;
|
||||||
|
|
||||||
|
foreach (var favorite in favorites)
|
||||||
|
{
|
||||||
|
if (goodsMap.TryGetValue(favorite.GoodsId, out var goods) == false)
|
||||||
|
{
|
||||||
|
// 商品已被物理删除,跳过该收藏(不写入索引)
|
||||||
|
missingGoodsCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var groupName = favorite.GroupId <= 0
|
||||||
|
? DefaultGroupName
|
||||||
|
: (groupMap.TryGetValue(favorite.GroupId, out var name) ? name : string.Empty);
|
||||||
|
|
||||||
|
documents.Add(BuildDocument(favorite, goods, groupName));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 分批写入索引
|
||||||
|
for (var offset = 0; offset < documents.Count; offset += RebuildBatchSize)
|
||||||
|
{
|
||||||
|
await _indexService.IndexDocumentsAsync(documents.Skip(offset).Take(RebuildBatchSize));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"用户收藏索引重建完成:收藏 {FavoriteCount} 条,写入索引 {IndexedCount} 条,商品缺失跳过 {MissingCount} 条。",
|
||||||
|
favorites.Count, documents.Count, missingGoodsCount);
|
||||||
|
|
||||||
|
return documents.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 收藏落库成功但索引写入失败时的补偿:撤销本次新增的收藏记录、还原被修改的收藏分组。
|
||||||
|
/// </summary>
|
||||||
|
private async Task CompensateWriteFailureAsync(List<long> insertedIds, List<(long Id, int PreviousGroupId)> changedGroupIds)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (insertedIds.Count > 0)
|
||||||
|
{
|
||||||
|
await _favoriteRepository.Orm.Delete<UserGoodsFavoriteEntity>()
|
||||||
|
.Where(x => insertedIds.Contains(x.Id))
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (id, previousGroupId) in changedGroupIds)
|
||||||
|
{
|
||||||
|
await _favoriteRepository.Orm.Update<UserGoodsFavoriteEntity>()
|
||||||
|
.Set(x => x.GroupId, previousGroupId)
|
||||||
|
.Where(x => x.Id == id)
|
||||||
|
.ExecuteAffrowsAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"回滚用户收藏记录失败。Inserted={InsertedCount} GroupChanged={GroupChangedCount}",
|
||||||
|
insertedIds.Count, changedGroupIds.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 取分组名:分组ID <= 0 返回默认分组名,分组不存在返回空串。
|
||||||
|
/// </summary>
|
||||||
|
private async Task<string> ResolveGroupNameAsync(string userName, int groupId)
|
||||||
|
{
|
||||||
|
if (groupId <= 0)
|
||||||
|
{
|
||||||
|
return DefaultGroupName;
|
||||||
|
}
|
||||||
|
|
||||||
|
var group = await _groupRepository.Select
|
||||||
|
.Where(x => x.Id == groupId && x.UserName == userName)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
return group?.GroupName ?? string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 组装收藏索引文档:收藏记录 + 商品快照 + 分组名。
|
||||||
|
/// </summary>
|
||||||
|
private static UserFavoritesSearchDocument BuildDocument(UserGoodsFavoriteEntity favorite, GoodsEntity goods, string groupName)
|
||||||
|
{
|
||||||
|
return new UserFavoritesSearchDocument
|
||||||
|
{
|
||||||
|
Id = UserFavoritesSearchDocument.BuildId(favorite.UserName, favorite.GoodsId),
|
||||||
|
FavId = favorite.Id,
|
||||||
|
UserName = favorite.UserName,
|
||||||
|
GroupId = favorite.GroupId,
|
||||||
|
GroupName = groupName,
|
||||||
|
GoodsId = goods.GoodsId,
|
||||||
|
Platform = goods.Platform,
|
||||||
|
Title = goods.Title ?? string.Empty,
|
||||||
|
ThumbUrl = goods.ThumbUrl,
|
||||||
|
CatId1 = goods.CatId1,
|
||||||
|
CatId2 = goods.CatId2,
|
||||||
|
CatId3 = goods.CatId3,
|
||||||
|
CatId4 = goods.CatId4,
|
||||||
|
MinPrice = goods.MinPrice,
|
||||||
|
SoldQuantity = goods.SoldQuantity,
|
||||||
|
CreatedAt = favorite.CreatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UserFavoriteItem ToItem(UserFavoritesSearchDocument document)
|
||||||
|
{
|
||||||
|
return new UserFavoriteItem
|
||||||
|
{
|
||||||
|
Id = document.FavId,
|
||||||
|
UserName = document.UserName,
|
||||||
|
GroupId = document.GroupId,
|
||||||
|
GroupName = document.GroupName,
|
||||||
|
GoodsId = document.GoodsId,
|
||||||
|
Platform = document.Platform,
|
||||||
|
Title = document.Title,
|
||||||
|
ThumbUrl = document.ThumbUrl,
|
||||||
|
CatId1 = document.CatId1,
|
||||||
|
CatId2 = document.CatId2,
|
||||||
|
CatId3 = document.CatId3,
|
||||||
|
CatId4 = document.CatId4,
|
||||||
|
MinPrice = document.MinPrice,
|
||||||
|
SoldQuantity = document.SoldQuantity,
|
||||||
|
CreatedAt = document.CreatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 解析排序方式,非法值一律按“收藏时间倒序”处理。
|
||||||
|
/// </summary>
|
||||||
|
private static UserFavoritesSortBy ParseSortBy(string? sortBy)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(sortBy))
|
||||||
|
{
|
||||||
|
return UserFavoritesSortBy.CreatedTimeDesc;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Enum.TryParse<UserFavoritesSortBy>(sortBy, ignoreCase: true, out var value)
|
||||||
|
? value
|
||||||
|
: UserFavoritesSortBy.CreatedTimeDesc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Core.Interfaces;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Store.Modules.CloudProduct.Services;
|
||||||
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct
|
||||||
|
{
|
||||||
|
|
||||||
|
public class Startup : IStartup
|
||||||
|
{
|
||||||
|
public int Priority => IntPriority.Normal;
|
||||||
|
|
||||||
|
public void Initialize()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Register(IServiceRegistrar registrar)
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Func<IServiceProvider, IFreeSql> KJDFsqlFactory = r =>
|
||||||
|
{
|
||||||
|
var config = r.GetRequiredService<IConfiguration>();
|
||||||
|
var connection = config.GetValue<string>("CloudProductConnection");
|
||||||
|
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||||
|
.UseConnectionString(FreeSql.DataType.MySql, connection)
|
||||||
|
.UseAdoConnectionPool(true)
|
||||||
|
.Build();
|
||||||
|
return fsql;
|
||||||
|
};
|
||||||
|
registrar.RegisterSingleton<IFreeSql>("CloudProductConnection", (s, k) =>
|
||||||
|
{
|
||||||
|
return KJDFsqlFactory(s);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async void Start(IServiceProvider serviceProvider)
|
||||||
|
{
|
||||||
|
var openSearchService = serviceProvider.GetRequiredService<OpenSearchService>();
|
||||||
|
await openSearchService.GetStatusAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\Store.Framework\Store.Framework.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
<!--<ItemGroup>
|
||||||
|
--><!-- 本模块自己的配置文件:源码里叫 appsettings.json,构建后复制到宿主输出目录时改名为
|
||||||
|
appsettings.CloudProduct.json,避免和宿主自己的 appsettings.json 互相覆盖。
|
||||||
|
由 builder.AddStoreHub() 自动并入宿主配置树(在 appsettings*.json 之后、环境变量之前)。 --><!--
|
||||||
|
<None Update="appsettings.json" Link="appsettings.CloudProduct.json" CopyToOutputDirectory="PreserveNewest" />
|
||||||
|
</ItemGroup>-->
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="appsettings.CloudProduct.json">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.25" />
|
||||||
|
<PackageReference Include="Hangfire.Dashboard.Basic.Authentication" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Hangfire.MySqlStorage" Version="2.0.3" />
|
||||||
|
<PackageReference Include="OpenSearch.Client" Version="2.1.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"CloudProductConnection": "Server=192.168.0.200;Port=3306;Database=goods_center;Uid=root;Pwd=123456;Allow User Variables=true",
|
||||||
|
"Search": {
|
||||||
|
"Url": "http://192.168.0.200:9200",
|
||||||
|
"IndexName": "goods_search",
|
||||||
|
"FavoritesIndexName": "user_goods_favorites_search"
|
||||||
|
},
|
||||||
|
"RawData": {
|
||||||
|
"Path": "E:\\GoodsRawData"
|
||||||
|
},
|
||||||
|
"Indexing": {
|
||||||
|
"Mode": "Background",
|
||||||
|
"Cron": "*/5 * * * *",
|
||||||
|
"BatchSize": 20000
|
||||||
|
},
|
||||||
|
"Delete": {
|
||||||
|
"SoftDelete": true
|
||||||
|
},
|
||||||
|
"Hangfire": {
|
||||||
|
"Dashboard" :{
|
||||||
|
"User": "admin",
|
||||||
|
"Pass": "1234560"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
using Asp.Versioning;
|
||||||
|
using MAX.Framework.Dtos;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using MySqlX.XDevAPI.Common;
|
||||||
|
using Store.Framework.Base;
|
||||||
|
using Store.Framework.Models;
|
||||||
|
using Store.ImageCache.Dtos;
|
||||||
|
using Store.ImageCache.Services;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
|
||||||
|
namespace KJD_Web.Controllers
|
||||||
|
{
|
||||||
|
[ApiVersionNeutral]
|
||||||
|
[Route("api/ImageCache/[action]")]
|
||||||
|
public class ImageCacheController : AppControllerBase
|
||||||
|
{
|
||||||
|
private readonly ImageCacheService _imageCacheService;
|
||||||
|
private readonly ILogger<ImageCacheController> _logger;
|
||||||
|
|
||||||
|
public ImageCacheController(ImageCacheService imageCacheService, ILogger<ImageCacheController> logger)
|
||||||
|
{
|
||||||
|
if (imageCacheService == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException("imageCacheService");
|
||||||
|
}
|
||||||
|
|
||||||
|
_imageCacheService = imageCacheService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量按 MD5 查询图片缓存。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public ApiResult<List<ImageCacheDto>> GetImageCache(ImageCacheBatchQueryRequest request)
|
||||||
|
{
|
||||||
|
List<ImageCacheDto> data = new List<ImageCacheDto>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (request != null && request.Md5s != null)
|
||||||
|
{
|
||||||
|
data = _imageCacheService.GetByMd5s(request.Md5s, request.Platform);
|
||||||
|
}
|
||||||
|
return ApiResult.Ok(data);
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
return ApiResult.Fail(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 按 MD5 和平台更新平台图片 URL。
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public ApiResult<List<string>> AddOrUpdate(ImageCacheUpdateUrlRequest[] requests)
|
||||||
|
{
|
||||||
|
if (requests == null || requests.Length == 0)
|
||||||
|
{
|
||||||
|
return ApiResult.Fail("参数不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
var failedItems = new List<string>();
|
||||||
|
foreach (var item in requests)
|
||||||
|
{
|
||||||
|
if (item == null)
|
||||||
|
{
|
||||||
|
return ApiResult.Fail("图片参数不能包含空项", ResultCode.ValidationError);
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!_imageCacheService.AddOrUpdate(item.Md5, item.Platform, item.PlatformUrl))
|
||||||
|
{
|
||||||
|
failedItems.Add(item.Md5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "AddOrUpdate 失败, Md5={Md5}", item.Md5);
|
||||||
|
failedItems.Add(item.Md5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return failedItems.Count == 0
|
||||||
|
? ApiResult.Ok()
|
||||||
|
: ApiResult.Fail("部分图片失败", failedItems);
|
||||||
|
}
|
||||||
|
public class ImageCacheBatchQueryRequest
|
||||||
|
{
|
||||||
|
public List<string> Md5s { get; set; }
|
||||||
|
public byte? Platform { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ImageCacheUpdateUrlRequest
|
||||||
|
{
|
||||||
|
public string Md5 { get; set; }
|
||||||
|
public byte Platform { get; set; }
|
||||||
|
public string PlatformUrl { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Store.ImageCache.Dtos
|
||||||
|
{
|
||||||
|
public class ImageCacheDto
|
||||||
|
{
|
||||||
|
public byte platform { get; set; }
|
||||||
|
public string md5 { get; set; }
|
||||||
|
public string platform_url { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Store.ImageCache.Entities
|
||||||
|
{
|
||||||
|
[Table(Name = "images_0")]
|
||||||
|
public class ImageCacheEntity
|
||||||
|
{
|
||||||
|
[JsonIgnore]
|
||||||
|
[Column(Name = "id", IsIdentity = true, IsPrimary = true)]
|
||||||
|
public long id { get; set; }
|
||||||
|
|
||||||
|
[Column(Name = "platform")]
|
||||||
|
public byte platform { get; set; }
|
||||||
|
|
||||||
|
//[JsonProperty("md5")]
|
||||||
|
[Column(Name = "source_url_md5", StringLength = 32)]
|
||||||
|
public string source_url_md5 { get; set; }
|
||||||
|
|
||||||
|
[Column(Name = "platform_url", StringLength = 1000)]
|
||||||
|
public string platform_url { get; set; }
|
||||||
|
[JsonIgnore]
|
||||||
|
[Column(Name = "create_time")]
|
||||||
|
public DateTime create_time { get; set; }
|
||||||
|
[JsonIgnore]
|
||||||
|
[Column(Name = "update_time")]
|
||||||
|
public DateTime update_time { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using Riok.Mapperly.Abstractions;
|
||||||
|
using Store.Framework.Models;
|
||||||
|
using Store.ImageCache.Dtos;
|
||||||
|
using Store.ImageCache.Entities;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Store.ImageCache.Mapper
|
||||||
|
{
|
||||||
|
[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)]
|
||||||
|
public partial class ImageCacheMapper
|
||||||
|
{
|
||||||
|
[MapProperty(nameof(ImageCacheEntity.source_url_md5), nameof(ImageCacheDto.md5))]
|
||||||
|
public partial ImageCacheDto ToDto(ImageCacheEntity entity);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
|
||||||
|
using MAX.Core.Interfaces;
|
||||||
|
using MAX.Framework.Interfaces;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using MySql.Data.MySqlClient;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct
|
||||||
|
{
|
||||||
|
public class Module : IModule
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 本模块自己的配置文件
|
||||||
|
/// </summary>
|
||||||
|
public const string ConfigurationFileName = "appsettings.ImageCache.json";
|
||||||
|
|
||||||
|
public int Priority => IntPriority.Normal;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 服务注册阶段(builder.Build() 之前):这里只能拿到容器和配置,碰不到 app
|
||||||
|
/// </summary>
|
||||||
|
public void AddModule(IHostApplicationBuilder host)
|
||||||
|
{
|
||||||
|
IServiceCollection services = host.Services;
|
||||||
|
IConfigurationManager configuration = host.Configuration;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(ConfigurationFileName))
|
||||||
|
{
|
||||||
|
string path = Path.IsPathRooted(ConfigurationFileName)? ConfigurationFileName: Path.Combine(AppContext.BaseDirectory, ConfigurationFileName);
|
||||||
|
configuration.AddJsonFile(path, optional: false, reloadOnChange: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 管道装配阶段(builder.Build() 之后、app.Run() 之前):这里可以挂中间件、解析容器里的服务
|
||||||
|
/// </summary>
|
||||||
|
public void UseModule(IApplicationBuilder app)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Store.ImageCache.Dtos;
|
||||||
|
using Store.ImageCache.Entities;
|
||||||
|
using Store.ImageCache.Mapper;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Store.ImageCache.Services
|
||||||
|
{
|
||||||
|
public class ImageCacheService : ISingletonDependency
|
||||||
|
{
|
||||||
|
private const int Md5Length = 32;
|
||||||
|
private const int PlatformUrlMaxLength = 1000;
|
||||||
|
|
||||||
|
private readonly IFreeSql _freeSql;
|
||||||
|
private ImageCacheMapper mapper;
|
||||||
|
public ImageCacheService([FromKeyedServices("ImageCacheConnection")] IFreeSql freeSql)
|
||||||
|
{
|
||||||
|
mapper = new ImageCacheMapper();
|
||||||
|
if (freeSql == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException("freeSql");
|
||||||
|
}
|
||||||
|
|
||||||
|
_freeSql = freeSql;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 按 MD5 查询图片缓存;platform 为空时返回该 MD5 在所有平台的缓存。
|
||||||
|
/// </summary>
|
||||||
|
public ImageCacheDto GetByMd5(string sourceUrlMd5, byte? platform = null)
|
||||||
|
{
|
||||||
|
var md5 = NormalizeMd5(sourceUrlMd5);
|
||||||
|
return GetByMd5sInternal(new List<string> { md5 }, platform).FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量按 MD5 查询图片缓存。MD5 会按首字符分组,只查询对应的 images_0 到 images_f 分表。
|
||||||
|
/// </summary>
|
||||||
|
public List<ImageCacheDto> GetByMd5s(IEnumerable<string> sourceUrlMd5s, byte? platform = null)
|
||||||
|
{
|
||||||
|
return GetByMd5sInternal(NormalizeMd5s(sourceUrlMd5s), platform);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 按 MD5 和平台直接修改平台图片 URL,未找到时返回 false。
|
||||||
|
/// </summary>
|
||||||
|
public bool AddOrUpdate(string sourceUrlMd5, byte platform, string platformUrl)
|
||||||
|
{
|
||||||
|
var md5 = NormalizeMd5(sourceUrlMd5);
|
||||||
|
ValidatePlatformUrl(platformUrl);
|
||||||
|
var tableName = GetTableName(md5[0]);
|
||||||
|
var existing = _freeSql.Select<ImageCacheEntity>()
|
||||||
|
.AsTable((type, oldName) => tableName)
|
||||||
|
.Where(a => a.source_url_md5 == sourceUrlMd5 && a.platform == platform)
|
||||||
|
.First();
|
||||||
|
|
||||||
|
var now = DateTime.Now;
|
||||||
|
if (existing != null)
|
||||||
|
{
|
||||||
|
var affected = _freeSql.Update<ImageCacheEntity>()
|
||||||
|
.AsTable(tableName)
|
||||||
|
.Set(a => a.platform_url, platformUrl)
|
||||||
|
.Set(a => a.update_time, now)
|
||||||
|
.Where(a => a.source_url_md5 == md5 && a.platform == platform)
|
||||||
|
.ExecuteAffrows();
|
||||||
|
return affected > 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ImageCacheEntity imageCache = new ImageCacheEntity();
|
||||||
|
imageCache.id = 0;
|
||||||
|
imageCache.source_url_md5 = md5;
|
||||||
|
imageCache.platform = platform;
|
||||||
|
imageCache.platform_url = platformUrl;
|
||||||
|
imageCache.create_time = now;
|
||||||
|
imageCache.update_time = now;
|
||||||
|
imageCache.id = _freeSql.Insert(imageCache)
|
||||||
|
.AsTable(tableName)
|
||||||
|
.ExecuteIdentity();
|
||||||
|
return imageCache.id > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<ImageCacheDto> GetByMd5sInternal(List<string> md5s, byte? platform)
|
||||||
|
{
|
||||||
|
var result = new List<ImageCacheDto>();
|
||||||
|
if (md5s.Count == 0)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var shard in md5s.GroupBy(a => a[0]))
|
||||||
|
{
|
||||||
|
var tableName = GetTableName(shard.Key);
|
||||||
|
var md5sInTable = shard.ToList();
|
||||||
|
var query = _freeSql.Select<ImageCacheEntity>()
|
||||||
|
.AsTable((type, oldName) => tableName)
|
||||||
|
.Where(a => md5sInTable.Contains(a.source_url_md5));
|
||||||
|
|
||||||
|
if (platform.HasValue)
|
||||||
|
{
|
||||||
|
var platformValue = platform.Value;
|
||||||
|
query = query.Where(a => a.platform == platformValue);
|
||||||
|
}
|
||||||
|
result.AddRange(query.ToList().Select(mapper.ToDto));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<string> NormalizeMd5s(IEnumerable<string> sourceUrlMd5s)
|
||||||
|
{
|
||||||
|
if (sourceUrlMd5s == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException("sourceUrlMd5s");
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new List<string>();
|
||||||
|
foreach (var sourceUrlMd5 in sourceUrlMd5s)
|
||||||
|
{
|
||||||
|
var md5 = NormalizeMd5(sourceUrlMd5);
|
||||||
|
if (!result.Contains(md5))
|
||||||
|
{
|
||||||
|
result.Add(md5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string NormalizeMd5(string sourceUrlMd5)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(sourceUrlMd5))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("MD5 不能为空", "sourceUrlMd5");
|
||||||
|
}
|
||||||
|
|
||||||
|
var md5 = sourceUrlMd5.Trim().ToLowerInvariant();
|
||||||
|
if (md5.Length != Md5Length || md5.Any(a => !Uri.IsHexDigit(a)))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("MD5 必须是 32 位十六进制字符串", "sourceUrlMd5");
|
||||||
|
}
|
||||||
|
|
||||||
|
return md5;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetTableName(char shard)
|
||||||
|
{
|
||||||
|
return "images_" + shard;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private void ValidatePlatformUrl(string platformUrl)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(platformUrl))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("平台图片 URL 不能为空", "platformUrl");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platformUrl.Length > PlatformUrlMaxLength)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("平台图片 URL 长度不能超过 1000", "platformUrl");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Core.Interfaces;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
namespace Store.Modules.CloudProduct
|
||||||
|
{
|
||||||
|
|
||||||
|
public class Startup : IStartup
|
||||||
|
{
|
||||||
|
public int Priority => IntPriority.Normal;
|
||||||
|
|
||||||
|
public void Initialize()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Register(IServiceRegistrar registrar)
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Func<IServiceProvider, IFreeSql> KJDFsqlFactory = r =>
|
||||||
|
{
|
||||||
|
var config = r.GetRequiredService<IConfiguration>();
|
||||||
|
var connection = config.GetValue<string>("ImageCache:ConnectionString");
|
||||||
|
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||||
|
.UseConnectionString(FreeSql.DataType.MySql, connection)
|
||||||
|
.UseAdoConnectionPool(true)
|
||||||
|
.Build();
|
||||||
|
return fsql;
|
||||||
|
};
|
||||||
|
registrar.RegisterSingleton<IFreeSql>("ImageCacheConnection", (s, k) =>
|
||||||
|
{
|
||||||
|
return KJDFsqlFactory(s);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start(IServiceProvider serviceProvider)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\Store.Framework\Store.Framework.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="appsettings.ImageCache.json">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"ImageCache": {
|
||||||
|
"ConnectionString": "Server=192.168.0.200;Port=3306;Database=ImageCache;Uid=root;Pwd=123456;Allow User Variables=true"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Store.Shops.Contracts
|
||||||
|
{
|
||||||
|
public interface IShopQueryService
|
||||||
|
{
|
||||||
|
DateTime GetExpireTime(string shopId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace YourNamespace
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 店铺表
|
||||||
|
/// </summary>
|
||||||
|
[Table(Name = "wxxd.shop")]
|
||||||
|
public class ShopEntity
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 表id
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// login_name
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "login_name")]
|
||||||
|
public string LoginName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// login_pass
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "login_pass")]
|
||||||
|
public string LoginPass { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// cookie
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "cookie")]
|
||||||
|
public string Cookie { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// cookie2
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "cookie2")]
|
||||||
|
public string Cookie2 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// anti_contents
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "anti_contents")]
|
||||||
|
public string AntiContents { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// openid
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "openid")]
|
||||||
|
public string Openid { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// shop_id
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "shop_id")]
|
||||||
|
public string ShopId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// shop_account
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "shop_account")]
|
||||||
|
public string ShopAccount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// sub_user_name
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "sub_user_name")]
|
||||||
|
public string SubUserName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// user_name
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "user_name")]
|
||||||
|
public string UserName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 店铺分组名称(非子账号分组)
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "group_name")]
|
||||||
|
public string GroupName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// add_time
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "add_time")]
|
||||||
|
public DateTime? AddTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// mdy_time
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "mdy_time")]
|
||||||
|
public DateTime? MdyTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 店铺所属公司
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "company_name")]
|
||||||
|
public string CompanyName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 备注
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "notes")]
|
||||||
|
public string Notes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// login_status
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "login_status")]
|
||||||
|
public string LoginStatus { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 店铺每月商品上传限额剩余
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "add_product_remaining")]
|
||||||
|
public int AddProductRemaining { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上传限额所处月份
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "add_product_month")]
|
||||||
|
public byte AddProductMonth { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分配的二级超管的user_name
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "operate_sub_sa_name")]
|
||||||
|
public string OperateSubSaName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分配二级超管的时间
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "add_sub_sa_time")]
|
||||||
|
public DateTime? AddSubSaTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// login_status2
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "login_status2")]
|
||||||
|
public string LoginStatus2 { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using FreeSql.DataAnnotations;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Store.Users.Entities
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商店过期
|
||||||
|
/// </summary>
|
||||||
|
[Table(Name = "wxxd.user_points_shop_expire")]
|
||||||
|
public class ShopExpireEntity
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商店ID
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "shop_id")]
|
||||||
|
public string ShopId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 过期时间
|
||||||
|
/// </summary>
|
||||||
|
// 数据库列名末尾包含 U+200C,不能改成普通 expire_time。
|
||||||
|
[Column(Name = "expire_time")]
|
||||||
|
public int ExpireTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 添加时间
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "add_time")]
|
||||||
|
public DateTime AddTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 修改时间
|
||||||
|
/// </summary>
|
||||||
|
[Column(Name = "mdy_time")]
|
||||||
|
public DateTime MdyTime { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using FreeSql;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Core.Helpers;
|
||||||
|
using Store.Users.Entities;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using YourNamespace;
|
||||||
|
|
||||||
|
namespace Store.Shops.Repositories
|
||||||
|
{
|
||||||
|
public interface IShopRepository : IBaseRepository<ShopEntity>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 获取用户商铺过期时间
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ShopId"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
DateTime GetExpireTime(string ShopId);
|
||||||
|
}
|
||||||
|
internal class ShopRepository : BaseRepository<ShopEntity>, IShopRepository, ITransientDependency
|
||||||
|
{
|
||||||
|
private readonly IFreeSql _freeSql;
|
||||||
|
|
||||||
|
public ShopRepository(IFreeSql freeSql) : base(freeSql)
|
||||||
|
{
|
||||||
|
_freeSql = freeSql;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取用户商铺过期时间
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ShopId"></param>
|
||||||
|
public DateTime GetExpireTime(string ShopId)
|
||||||
|
{
|
||||||
|
ShopExpireEntity currentExpire = _freeSql.Select<ShopExpireEntity>()
|
||||||
|
.Where(a => a.ShopId == ShopId)
|
||||||
|
.ForUpdate()
|
||||||
|
.First();
|
||||||
|
if (currentExpire == null)
|
||||||
|
{
|
||||||
|
return DateTime.MinValue;
|
||||||
|
}
|
||||||
|
return DateHelper.ConvertFromUnixTimestampInSeconds(currentExpire.ExpireTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Store.Shops.Contracts;
|
||||||
|
using Store.Shops.Repositories;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Store.Shops.Services
|
||||||
|
{
|
||||||
|
internal class ShopQueryService: IShopQueryService, ITransientDependency
|
||||||
|
{
|
||||||
|
private readonly IShopRepository _shopRepository;
|
||||||
|
|
||||||
|
public ShopQueryService(IShopRepository shopRepository)
|
||||||
|
{
|
||||||
|
_shopRepository = shopRepository;
|
||||||
|
}
|
||||||
|
public DateTime GetExpireTime(string shopId)
|
||||||
|
{
|
||||||
|
return _shopRepository.GetExpireTime(shopId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using MAX.Core.Interfaces;
|
||||||
|
|
||||||
|
namespace Store.Shops
|
||||||
|
{
|
||||||
|
public class Startup : IStartup
|
||||||
|
{
|
||||||
|
public int Priority => IntPriority.Normal;
|
||||||
|
|
||||||
|
public void Initialize()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Register(IServiceRegistrar registrar)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start(IServiceProvider serviceProvider)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\Store.Framework\Store.Framework.csproj" />
|
||||||
|
<ProjectReference Include="..\Store.Shops.Contracts\Store.Shops.Contracts.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Store.Users.Contracts.Dtos
|
||||||
|
{
|
||||||
|
public class UserInfo
|
||||||
|
{/// <summary>
|
||||||
|
/// ID
|
||||||
|
/// </summary>
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户昵称
|
||||||
|
/// </summary>
|
||||||
|
public string NickName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名称(登录账户)
|
||||||
|
/// </summary>
|
||||||
|
public string UserName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 登录密码
|
||||||
|
/// </summary>
|
||||||
|
public string Password { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// card_id
|
||||||
|
/// </summary>
|
||||||
|
public string CardId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户分组 3主号 4客服 5加盟 8登录 9采购 10加盟 11上货
|
||||||
|
/// </summary>
|
||||||
|
public byte GroupId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 父账户用户名
|
||||||
|
/// </summary>
|
||||||
|
public string ParentUserName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// oem编号,仅oem用户有值
|
||||||
|
/// </summary>
|
||||||
|
public string OemId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 手机号
|
||||||
|
/// </summary>
|
||||||
|
public string Mobile { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 添加时间
|
||||||
|
/// </summary>
|
||||||
|
public DateTime? AddTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 修改时间
|
||||||
|
/// </summary>
|
||||||
|
public DateTime? MdyTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 公司名称
|
||||||
|
/// </summary>
|
||||||
|
public string CompanyName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 备注
|
||||||
|
/// </summary>
|
||||||
|
public string Notes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 超管等级 0 普通用户 1 超级管理员
|
||||||
|
/// </summary>
|
||||||
|
public short? SaLevel { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 账户权限
|
||||||
|
/// </summary>
|
||||||
|
public string Authority { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 子账号被禁止展示的功能页面
|
||||||
|
/// </summary>
|
||||||
|
public string ForbiddenPage { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 账户积分,1积分=1元
|
||||||
|
/// </summary>
|
||||||
|
public decimal Points { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 积分历史累计充值金额
|
||||||
|
/// </summary>
|
||||||
|
public decimal? RechargePointsTotal { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 店铺每续费一个月需要的积分,单位元
|
||||||
|
/// </summary>
|
||||||
|
public int ShopPointsPerMonth { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 可用余额
|
||||||
|
/// </summary>
|
||||||
|
public decimal? Balance { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 累计充值金额
|
||||||
|
/// </summary>
|
||||||
|
public decimal? RechargeAmountTotal { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 每单中转仓快递费用,单位元,两位小数
|
||||||
|
/// </summary>
|
||||||
|
public decimal? PostagePerOrder { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 每单中转仓退货快递费用,单位元,两位小数
|
||||||
|
/// </summary>
|
||||||
|
public decimal? RefundPostagePerOrder { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 礼物每单额外收取费用,单位元,两位小数
|
||||||
|
/// </summary>
|
||||||
|
public decimal? GiftOemAmountPerOrder { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 同步物流费用,单位元,两位小数
|
||||||
|
/// </summary>
|
||||||
|
public decimal? SyncLogisticsPerOrder { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否主账户
|
||||||
|
/// </summary>
|
||||||
|
public bool IsMainUser
|
||||||
|
{
|
||||||
|
get => string.IsNullOrWhiteSpace(ParentUserName);
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// 是否OEM租户
|
||||||
|
/// </summary>
|
||||||
|
public bool IsOEMTenant => !string.IsNullOrWhiteSpace(OemId);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user