329 lines
9.4 KiB
C#
329 lines
9.4 KiB
C#
using Asp.Versioning;
|
|
using MAX.Framework.Commons;
|
|
using MAX.Framework.Dtos;
|
|
using Microsoft.AspNetCore.Http;
|
|
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;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Text.Json.Nodes;
|
|
|
|
namespace Store.Modules.CloudProduct.Controllers
|
|
{
|
|
[ApiVersionNeutral]
|
|
[Route("/CloudProduct/[action]")]
|
|
public class ProductController : AppControllerBase
|
|
{
|
|
private readonly IProductService _productService;
|
|
private readonly IOpenSearchServer _searchServer;
|
|
private readonly RawDataStorage _rawDataStorage;
|
|
|
|
public ProductController(IProductService productService, IOpenSearchServer searchServer, RawDataStorage rawDataStorage)
|
|
{
|
|
_productService = productService;
|
|
_searchServer = searchServer;
|
|
_rawDataStorage = rawDataStorage;
|
|
}
|
|
[HttpGet]
|
|
public async Task<string> Time()
|
|
{
|
|
return DateTime.Now.ToLongDateString();
|
|
}
|
|
/// <summary>
|
|
/// 搜索
|
|
/// </summary>
|
|
/// <param name="keyword"></param>
|
|
/// <returns></returns>
|
|
[HttpPost]
|
|
public async Task<PageData<ProductEntity>> SearchGoods(ProductSearchRequest 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 _productService.SearchGoods(request);
|
|
return new PageData<ProductEntity>
|
|
{
|
|
List = result.List,
|
|
Total = result.Total,
|
|
PageSize = request.PageSize,
|
|
PageIndex = request.PageIndex,
|
|
};
|
|
}
|
|
|
|
|
|
[HttpGet]
|
|
public async Task<PageData<ProductSearchInfo>> SearchGoodsToIds(string keyword, int pageindex = 1, int pagesize = 20)
|
|
{
|
|
|
|
if (string.IsNullOrWhiteSpace(keyword))
|
|
{
|
|
throw new AppException("填写关键字", ResultCode.ValidationError);
|
|
}
|
|
var ret = await _searchServer.SearchByTitleAsync(new ProductSearchRequest
|
|
{
|
|
Title = keyword,
|
|
PageIndex = pageindex,
|
|
PageSize = pagesize,
|
|
});
|
|
return new PageData<ProductSearchInfo>
|
|
{
|
|
PageIndex = pageindex,
|
|
PageSize = pagesize,
|
|
List = ret.list,
|
|
Total = ret.Total,
|
|
};
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// 导入测试数据:读取 ImportConverters/data.txt 并走完整解析 + 入库 + 分词流程。
|
|
/// </summary>
|
|
[HttpGet]
|
|
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 = ConverterToGoodsFactory.ConvertContent(content);
|
|
if (goods == null)
|
|
{
|
|
throw new AppException("未找到匹配的转换器,无法解析测试数据");
|
|
}
|
|
|
|
return await _productService.ImportGoodsAsync(new[]
|
|
{
|
|
new GoodsImportItem { ProductEntity = goods, RawData = content }
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// 导入接口:接收客户端批量上传的 JSON 文件,解析后入库并写入分词索引。
|
|
/// </summary>
|
|
[HttpPost]
|
|
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 = ConverterToGoodsFactory.ConvertContent(content);
|
|
if (goods == null)
|
|
{
|
|
parseErrors.Add($"{file.FileName}: 未找到匹配的转换器");
|
|
}
|
|
else
|
|
{
|
|
items.Add(new GoodsImportItem { ProductEntity = goods, RawData = content });
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
parseErrors.Add($"{file.FileName}: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
var result = await _productService.ImportGoodsAsync(items);
|
|
result.Failed += parseErrors.Count;
|
|
result.Errors.InsertRange(0, parseErrors);
|
|
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询 OpenSearch 状态。
|
|
/// </summary>
|
|
[HttpGet]
|
|
public async Task<OpenSearchStatusDto> GetOpenSearchStatus()
|
|
{
|
|
return await _searchServer.GetStatusAsync();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取指定商品详情:解压缩原始数据并返回 JSON。
|
|
/// </summary>
|
|
[HttpGet]
|
|
public async Task<JsonNode> GetGoodsDetail([FromQuery] long goodsId)
|
|
{
|
|
var raw = await GetRawDataOrThrowAsync(goodsId);
|
|
var node = JsonNode.Parse(raw);
|
|
return node ?? throw new AppException("商品详情解析失败", ResultCode.BusinessError);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取指定商品的原始数据(解压缩后原样返回)。
|
|
/// </summary>
|
|
[HttpGet]
|
|
public async Task<string> GetGoodsRawData([FromQuery] long goodsId)
|
|
{
|
|
return await GetRawDataOrThrowAsync(goodsId);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 重新从数据库读取指定商品,覆盖 OpenSearch 已有分词并重新分词。
|
|
/// ids 为空时重建全部商品。
|
|
/// </summary>
|
|
[HttpPost]
|
|
public async Task<long> RebuildIndex([FromBody] long[]? ids)
|
|
{
|
|
return await _productService.RebuildSearchIndexAsync(ids);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 删除商品(按数据库主键 ID)。是否软删除由配置 Delete:SoftDelete 决定,
|
|
/// 软删除将 Status 置 1,硬删除物理删除记录;两种方式都会删除 OpenSearch 中对应文档。
|
|
/// </summary>
|
|
[HttpPost]
|
|
public async Task<long> DeleteGoods([FromBody] long[]? ids)
|
|
{
|
|
if (ids == null || ids.Length == 0)
|
|
{
|
|
throw new AppException("请提供要删除的商品ID", ResultCode.ValidationError);
|
|
}
|
|
|
|
return await _productService.DeleteGoodsAsync(ids);
|
|
}
|
|
[HttpGet]
|
|
public async Task<bool> ClearSearch()
|
|
{
|
|
return await _searchServer.ClearIndexAsync();
|
|
}
|
|
[HttpGet]
|
|
public async Task<long> GetSearchCount()
|
|
{
|
|
return await _searchServer.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)
|
|
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;
|
|
}
|
|
}
|
|
}
|