云库增加 AI识图,缓存,我的云库收藏增加安全标志
调用外部API 扣费
This commit is contained in:
1 parent
7c29e57623
commit
150e8644b7
49 files changed
+1069
-28
No files matched your search
@@ -11,7 +11,12 @@ namespace Store.Modules.CloudProduct.Services;
|
||||
/// <summary>跨实例串行化违规上报和商品索引写入,防止下架后被旧批次写回。</summary>
|
||||
public class GoodsIndexLock([FromKeyedServices("CloudProduct")] PluginContext context) : ISingletonDependency
|
||||
{
|
||||
public async Task<IAsyncDisposable> AcquireAsync()
|
||||
public Task<IAsyncDisposable> AcquireAsync() => AcquireAsync("goods-index:");
|
||||
|
||||
/// <summary>收藏重建、整条文档写入和安全状态更新共用独立锁,防止旧快照覆盖新结论。</summary>
|
||||
public virtual Task<IAsyncDisposable> AcquireFavoritesAsync() => AcquireAsync("favorites-index:");
|
||||
|
||||
private async Task<IAsyncDisposable> AcquireAsync(string prefix)
|
||||
{
|
||||
// 禁用连接池:即使释放锁失败,关闭物理连接也会释放会话锁。
|
||||
var settings = new MySqlConnectionStringBuilder(context.Configuration["CloudProductConnection"])
|
||||
@@ -19,7 +24,7 @@ public class GoodsIndexLock([FromKeyedServices("CloudProduct")] PluginContext co
|
||||
Pooling = false
|
||||
};
|
||||
var connection = new MySqlConnection(settings.ConnectionString);
|
||||
var name = "goods-index:" + Convert.ToHexString(SHA256.HashData(
|
||||
var name = prefix + Convert.ToHexString(SHA256.HashData(
|
||||
Encoding.UTF8.GetBytes(settings.Database)))[..40];
|
||||
try
|
||||
{
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
using MAX.Framework.Commons;
|
||||
using MAX.Framework.Dtos;
|
||||
using MAX.Framework.Validation;
|
||||
using MAX.Plugins;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Store.Modules.CloudProduct.Dtos;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services;
|
||||
|
||||
/// <summary>调用外部网站的图片识别额度接口,单例复用 HTTP 连接。</summary>
|
||||
public sealed class ImageAnalysisQuotaService : IDisposable
|
||||
{
|
||||
private readonly HttpClient client;
|
||||
private readonly PluginContext<CloudProductPlugin> context;
|
||||
|
||||
/// <summary>从站点根地址创建客户端,定期更新连接以跟随 DNS 变化。</summary>
|
||||
public ImageAnalysisQuotaService(PluginContext<CloudProductPlugin> context)
|
||||
{
|
||||
this.context = context;
|
||||
var url = context.RequireConfiguration("ImageAnalysisQuota:Url");
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var endpoint) ||
|
||||
(endpoint.Scheme != Uri.UriSchemeHttp && endpoint.Scheme != Uri.UriSchemeHttps))
|
||||
throw new InvalidOperationException("ImageAnalysisQuota:Url 必须是 HTTP 或 HTTPS 站点地址。");
|
||||
|
||||
client = new HttpClient(new SocketsHttpHandler
|
||||
{
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
|
||||
AllowAutoRedirect = false
|
||||
})
|
||||
{ BaseAddress = endpoint };
|
||||
}
|
||||
|
||||
/// <summary>随服务释放客户端及连接池。</summary>
|
||||
public void Dispose() => client.Dispose();
|
||||
|
||||
/// <summary>
|
||||
/// 使用指定用户的识别额度,返回外部接口原始响应;HTTP 失败直接抛出异常。
|
||||
/// 额度扣减不自动重试,避免请求已执行但响应丢失时重复扣减。
|
||||
/// </summary>
|
||||
public async Task<bool> UseImageAnalysisQuotaAsync(UseImageAnalysisQuotaRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
RequestValidator.Validate(request);
|
||||
// 外部协议要求 token 和 username 放在查询字符串中,统一编码特殊字符。
|
||||
var requestUrl = QueryHelpers.AddQueryString("/wxxd_user/UseImageAnalysisQuota", new Dictionary<string, string?>
|
||||
{
|
||||
["token"] = context.RequireConfiguration("ImageAnalysisQuota:APIKey"),
|
||||
["username"] = request.UserName
|
||||
});
|
||||
using var response = await client.PostAsync(requestUrl, null, cancellationToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
// shortcut: 尚未提供响应协议,明确业务成功字段后再添加响应 DTO 和业务失败判断。
|
||||
string html = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
var result = JsonSerializer.Deserialize<ApiResult>(html);
|
||||
if (result != null && result.Success)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
throw new AppException(result.Msg);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Framework.Security;
|
||||
using MAX.Framework.Validation;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Store.Modules.CloudProduct.Contracts;
|
||||
using Store.Modules.CloudProduct.Dtos;
|
||||
using Store.Modules.CloudProduct.Entities;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Unicode;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services;
|
||||
|
||||
/// <summary>商品检测业务入口,负责上传图片识别、MD5 缓存和当前用户的商品安全记录。</summary>
|
||||
public sealed class ProductInspectionService(IInspectionIntegration integration, ICurrentUser user, ImageAnalysisQuotaService imageAnalysisQuotaService,
|
||||
[FromKeyedServices("CloudProductConnection")] IFreeSql database,
|
||||
[FromKeyedServices("ProductInspectionAnalysisGate")] SemaphoreSlim gate,
|
||||
ILogger<ProductInspectionService> logger
|
||||
) : IScopedDependency
|
||||
{
|
||||
public const int MaxBytes = 10 * 1024 * 1024;
|
||||
|
||||
// 缓存 JSON 保留中文原文,字符串中的引号和控制字符仍由序列化器转义。
|
||||
private static readonly JsonSerializerOptions CacheJsonOptions = new()
|
||||
{
|
||||
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
|
||||
};
|
||||
|
||||
// 每三个图片字节编码为四个 Base64 字符,末组向上取整。
|
||||
public const int MaxBase64Length = (MaxBytes + 2) / 3 * 4;
|
||||
|
||||
public async Task<string[]> InspectAsync(InspectImageRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
RequestValidator.Validate(request);
|
||||
if (request.Md5.Length != 32 || !request.Md5.All(char.IsAsciiHexDigit))
|
||||
throw new ValidationException("md5 必须是 32 位十六进制缓存键。");
|
||||
var md5 = request.Md5.ToLowerInvariant();
|
||||
if (request.Image.Length > MaxBase64Length)
|
||||
throw new ValidationException("图片超过 10 MiB 或 Base64 文本过长。");
|
||||
|
||||
byte[] image;
|
||||
try { image = Convert.FromBase64String(request.Image); }
|
||||
catch (FormatException) { throw new ValidationException("image 必须是有效的 Base64 字符串。"); }
|
||||
if (image.Length is < 12 or > MaxBytes)
|
||||
throw new ValidationException("图片为空、格式无效或超过 10 MiB。");
|
||||
// 依据文件签名识别允许的图片类型,避免信任客户端文件名和 MIME 类型。
|
||||
string mediaType;
|
||||
if (image[0] == 0xff && image[1] == 0xd8 && image[2] == 0xff) mediaType = "image/jpeg";
|
||||
else if (image.AsSpan(0, 8).SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 })) mediaType = "image/png";
|
||||
else if (image.AsSpan(0, 4).SequenceEqual("RIFF"u8) && image.AsSpan(8, 4).SequenceEqual("WEBP"u8)) mediaType = "image/webp";
|
||||
else throw new ValidationException("请上传 JPEG、PNG 或 WebP 图片。");
|
||||
var cached = await database.Select<ImageAnalysisCache>().Where(x => x.CacheKey == md5).FirstAsync();
|
||||
string[] result;
|
||||
// 旧对象格式缺少逐项阅读顺序,重新识别成功后再覆盖。
|
||||
if (cached?.RecognitionResult.TrimStart().StartsWith('[') == true)
|
||||
result = JsonSerializer.Deserialize<string[]>(cached.RecognitionResult)!;
|
||||
else
|
||||
{
|
||||
await gate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
using var stream = new MemoryStream(image, writable: false);
|
||||
var recognized = await integration.AnalyzeAsync(stream, mediaType, cancellationToken);
|
||||
result = recognized.Distinct(StringComparer.Ordinal).ToArray();
|
||||
await database.InsertOrUpdate<ImageAnalysisCache>().SetSource(new ImageAnalysisCache
|
||||
{
|
||||
CacheKey = md5,
|
||||
RecognitionResult = JsonSerializer.Serialize(result, CacheJsonOptions),
|
||||
UpdatedAt = DateTime.UtcNow
|
||||
}).ExecuteAffrowsAsync();
|
||||
}
|
||||
finally { gate.Release(); }
|
||||
}
|
||||
try
|
||||
{
|
||||
var useRet = await imageAnalysisQuotaService.UseImageAnalysisQuotaAsync(new UseImageAnalysisQuotaRequest
|
||||
{
|
||||
UserName = request.UserName
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "调用图片识别扣费程序失败");
|
||||
//扣费失败显示空
|
||||
result = [];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Plugins;
|
||||
using Store.Modules.CloudProduct.Contracts;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services;
|
||||
|
||||
/// <summary>通过千问兼容接口识别上传图片中的文字及品牌。</summary>
|
||||
public sealed class QwenInspectionIntegration : IInspectionIntegration, ISingletonDependency, IDisposable
|
||||
{
|
||||
private readonly HttpClient client;
|
||||
private readonly string model;
|
||||
|
||||
/// <summary>按插件配置创建并复用模型客户端,定期更新池内连接以跟随 DNS 变化。</summary>
|
||||
public QwenInspectionIntegration(PluginContext<CloudProductPlugin> context)
|
||||
{
|
||||
model = context.RequireConfiguration("ProductInspection:Model");
|
||||
var endpoint = new Uri(context.RequireConfiguration("ProductInspection:Endpoint"));
|
||||
var key = context.Configuration["ProductInspection:ApiKey"];
|
||||
if (string.IsNullOrWhiteSpace(key)) key = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
|
||||
|
||||
client = new HttpClient(new SocketsHttpHandler
|
||||
{
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
|
||||
//Proxy = new WebProxy("http://127.0.0.1:8080")
|
||||
})
|
||||
{
|
||||
BaseAddress = endpoint,
|
||||
Timeout = TimeSpan.FromMinutes(10)
|
||||
};
|
||||
if (!string.IsNullOrWhiteSpace(key))
|
||||
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", key);
|
||||
}
|
||||
|
||||
public void Dispose() => client.Dispose();
|
||||
|
||||
private const string Prompt = """
|
||||
你是图像品牌与文字识别引擎。请识别图片中的文字和品牌 Logo,并严格按下方规则输出。
|
||||
|
||||
【识别范围】
|
||||
- 所有可见文字(标题、正文、按钮文字、标签、说明等),原样识别输出。
|
||||
- 品牌 Logo:识别 Logo 对应的品牌,输出品牌中文名(不输出 Logo 上的原始英文/字母)。
|
||||
- 图片、图标、二维码、条形码、分隔线等非文字非品牌元素:忽略,不输出。
|
||||
|
||||
【Logo 处理规则】
|
||||
- 遇到品牌 Logo 时,不要输出 Logo 上的原始英文/字母。
|
||||
- 必须输出该品牌对应的中文品牌名。
|
||||
- 示例:
|
||||
* 看到 "ERKE" 或鸿鹄图形 → 输出 "鸿星尔克"
|
||||
* 看到 "Nike" 或钩子图形 → 输出 "耐克"
|
||||
* 看到 "Adidas" 或三叶草/三条纹 → 输出 "阿迪达斯"
|
||||
* 看到 "Li-Ning" 或李宁图形 → 输出 "李宁"
|
||||
* 看到 "ANTA" 或安踏图形 → 输出 "安踏"
|
||||
* 看到 "Xtep" 或特步图形 → 输出 "特步"
|
||||
* 看到 "361°" → 输出 "361度"
|
||||
- 如遇无法识别为已知品牌的 Logo,输出 "未知品牌"。
|
||||
- 如 Logo 上同时有中英文,优先输出中文品牌名。
|
||||
|
||||
【品牌名归一化规则(重要)】
|
||||
- 输出的品牌必须是一个独立、纯净的品牌名,不能包含子品牌、系列名、品类词、修饰词,也不能用连接符拼接。
|
||||
- 子品牌或系列要归并到主品牌,只输出主品牌名。
|
||||
- 正例:
|
||||
* "安踏儿童" → 输出 "安踏"(不要输出 "安踏儿童")
|
||||
* "安踏冠军系列" → 输出 "安踏"
|
||||
* "Nike Air" / "耐克 Air" → 输出 "耐克"
|
||||
* "Adidas Originals" / "阿迪达斯三叶草" → 输出 "阿迪达斯"
|
||||
* "李宁中国李宁" → 输出 "李宁"
|
||||
* "鸿星尔克ERKE" → 输出 "鸿星尔克"
|
||||
- 反例(禁止输出):
|
||||
* "安踏儿童"、"安踏-儿童"、"安踏 儿童"、"安踏(儿童)"
|
||||
* "耐克/Nike"、"阿迪达斯 Adidas"
|
||||
- 禁止使用 "/"、"-"、"·"、空格、括号等连接符拼接多个名称。
|
||||
|
||||
【输出要求】
|
||||
1. 只输出一个 JSON 字符串数组,不要输出对象、markdown 代码块、解释性文字或多余内容。
|
||||
2. 格式固定为:["文字1", "文字2", "文字3", ...]
|
||||
3. 按从上到下、从左到右的阅读顺序排列。
|
||||
4. 每个元素只包含文字本身,不包含类型、坐标等额外字段。
|
||||
5. 文字中的双引号需转义(\"),确保输出是合法 JSON。
|
||||
6. 若图中没有任何可识别文字或品牌,输出 []。
|
||||
""";
|
||||
|
||||
public async Task<string[]> AnalyzeAsync(Stream image, string mediaType, CancellationToken cancellationToken)
|
||||
{
|
||||
if (client.DefaultRequestHeaders.Authorization is null)
|
||||
throw new InvalidOperationException("请配置 ProductInspection:ApiKey 或 DASHSCOPE_API_KEY。");
|
||||
|
||||
|
||||
using var buffer = new MemoryStream();
|
||||
await image.CopyToAsync(buffer, cancellationToken);
|
||||
var url = $"data:{mediaType};base64,{Convert.ToBase64String(buffer.GetBuffer(), 0, (int)buffer.Length)}";
|
||||
using var response = await client.PostAsJsonAsync("", new
|
||||
{
|
||||
model,
|
||||
messages = new[] { new { role = "user", content = new object[]
|
||||
{
|
||||
new { type = "image_url", image_url = new { url } },
|
||||
new { type = "text", text = Prompt }
|
||||
} } },
|
||||
stream = false,
|
||||
enable_thinking = false
|
||||
}, cancellationToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
using var body = await response.Content.ReadFromJsonAsync<JsonDocument>(cancellationToken);
|
||||
var content = body!.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
|
||||
var words = JsonSerializer.Deserialize<string[]>(content ?? throw new JsonException("模型未返回识别内容。"));
|
||||
if (words == null || words.Any(word => word == null)) throw new JsonException("模型必须返回 JSON 字符串数组。");
|
||||
return words;
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
/// <summary>批量写入收藏文档(存在则覆盖)</summary>
|
||||
Task IndexDocumentsAsync(IEnumerable<UserFavoritesSearchDocument> documents);
|
||||
|
||||
/// <summary>更新单条收藏的安全字段并等待对检索可见。</summary>
|
||||
Task UpdateSafetyAsync(string documentId, bool isSafe);
|
||||
|
||||
/// <summary>按文档Id批量删除收藏文档</summary>
|
||||
Task DeleteDocumentsAsync(IEnumerable<string> documentIds);
|
||||
|
||||
@@ -172,6 +175,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
)
|
||||
.Map<UserFavoritesSearchDocument>(m => m
|
||||
.Properties(p => p
|
||||
.Boolean(b => b.Name(x => x.IsSafe))
|
||||
.Keyword(k => k.Name(x => x.Id))
|
||||
.Number(n => n.Name(x => x.FavId).Type(NumberType.Long))
|
||||
.Keyword(k => k.Name(x => x.UserName))
|
||||
@@ -221,6 +225,14 @@ namespace Store.Modules.CloudProduct.Services
|
||||
return await CreateIndexAsync();
|
||||
}
|
||||
|
||||
public async Task UpdateSafetyAsync(string documentId, bool isSafe)
|
||||
{
|
||||
var response = await _client.UpdateAsync<UserFavoritesSearchDocument, object>(documentId, u => u
|
||||
.Index(_indexName).Doc(new { is_safe = isSafe }).Refresh(Refresh.WaitFor));
|
||||
if (!response.IsValid)
|
||||
throw new AppException("更新收藏安全状态索引失败: " + response.DebugInformation);
|
||||
}
|
||||
|
||||
private async Task RefreshIndexAsync()
|
||||
{
|
||||
var response = await _client.Indices.RefreshAsync(_indexName, d => d
|
||||
@@ -316,6 +328,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||
}
|
||||
|
||||
if (request.SafeStatus is < 0 or > 3)
|
||||
throw new AppException("状态必须为 0(全部)、1(安全)、2(违规)或 3(未检测)", ResultCode.ValidationError);
|
||||
|
||||
var keyword = request.Title;
|
||||
int? groupId = request.GroupId;
|
||||
var groupName = request.GroupName;
|
||||
@@ -341,6 +356,12 @@ namespace Store.Modules.CloudProduct.Services
|
||||
// 只检索当前用户自己的收藏 —— 放进 filters,避免被后面的 Filter 覆盖
|
||||
filters.Add(f => f.Term(t => t.Field(x => x.UserName).Value(request.UserName)));
|
||||
|
||||
// is_safe 为 null 或缺失时没有索引值,两者均表示暂无检测结论。
|
||||
if (request.SafeStatus is 1 or 2)
|
||||
filters.Add(f => f.Term(t => t.Field(x => x.IsSafe).Value(request.SafeStatus == 1)));
|
||||
else if (request.SafeStatus == 3)
|
||||
filters.Add(f => f.Bool(b => b.MustNot(q => q.Exists(e => e.Field(x => x.IsSafe)))));
|
||||
|
||||
if (groupId.HasValue)
|
||||
{
|
||||
filters.Add(f => f.Term(t => t.Field(x => x.GroupId).Value(groupId.Value)));
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Framework.Commons;
|
||||
using MAX.Framework.Dtos;
|
||||
using MAX.Framework.Validation;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Store.Modules.CloudProduct.Dtos;
|
||||
using Store.Modules.CloudProduct.Entities;
|
||||
using Store.Modules.CloudProduct.Enums;
|
||||
using Store.Modules.CloudProduct.Repositorys;
|
||||
using Store.Users.Contracts;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services
|
||||
{
|
||||
@@ -17,6 +20,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
/// <summary>批量收藏商品,返回本次成功收藏的商品数量(已收藏的商品视为修改收藏分组)</summary>
|
||||
Task<int> AddFavoritesAsync(AddUserFavoriteRequest request);
|
||||
|
||||
/// <summary>按用户和商品编号更新已存在的收藏记录。</summary>
|
||||
Task SaveProductSafetyAsync(SaveProductSafetyRequest request);
|
||||
|
||||
/// <summary>批量取消收藏,返回实际取消的条数</summary>
|
||||
Task<int> RemoveFavoritesAsync(RemoveUserFavoritesRequest request);
|
||||
|
||||
@@ -47,6 +53,8 @@ namespace Store.Modules.CloudProduct.Services
|
||||
private readonly UserGoodsFavoriteRepository _favoriteRepository;
|
||||
private readonly UserGoodsFavoriteGroupRepository _groupRepository;
|
||||
private readonly GoodsRepository _goodsRepository;
|
||||
private readonly IUserQueryService _queryService;
|
||||
private readonly GoodsIndexLock _indexLock;
|
||||
private readonly IUserFavoritesIndexService _indexService;
|
||||
private readonly ILogger<UserFavoritesService> _logger;
|
||||
|
||||
@@ -54,13 +62,16 @@ namespace Store.Modules.CloudProduct.Services
|
||||
UserGoodsFavoriteRepository favoriteRepository,
|
||||
UserGoodsFavoriteGroupRepository groupRepository,
|
||||
GoodsRepository goodsRepository,
|
||||
IUserQueryService queryService,
|
||||
IUserFavoritesIndexService indexService,
|
||||
ILogger<UserFavoritesService> logger)
|
||||
ILogger<UserFavoritesService> logger, GoodsIndexLock indexLock)
|
||||
{
|
||||
_favoriteRepository = favoriteRepository;
|
||||
_groupRepository = groupRepository;
|
||||
_goodsRepository = goodsRepository;
|
||||
_queryService = queryService;
|
||||
_indexService = indexService;
|
||||
_indexLock = indexLock;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -81,6 +92,8 @@ namespace Store.Modules.CloudProduct.Services
|
||||
{
|
||||
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||
}
|
||||
var mainUser = await _queryService.GetMainUser(userName);
|
||||
userName = mainUser.UserName;
|
||||
|
||||
var goodsIds = request.GoodsIds?.Where(x => x > 0).Distinct().ToList() ?? new List<long>();
|
||||
if (goodsIds.Count == 0)
|
||||
@@ -93,6 +106,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
throw new AppException("收藏分组无效", ResultCode.ValidationError);
|
||||
}
|
||||
|
||||
await using var lease = await _indexLock.AcquireFavoritesAsync();
|
||||
// 1. 校验分组归属(分组ID > 0 时必须是该用户自己创建的分组)
|
||||
if (request.GroupId > 0)
|
||||
{
|
||||
@@ -206,6 +220,28 @@ namespace Store.Modules.CloudProduct.Services
|
||||
return documents.Count;
|
||||
}
|
||||
|
||||
/// <summary>仅修改安全字段,避免覆盖同时发生的收藏分组变更。</summary>
|
||||
public async Task SaveProductSafetyAsync(SaveProductSafetyRequest request)
|
||||
{
|
||||
RequestValidator.Validate(request);
|
||||
if (!long.TryParse(request.ProductId, NumberStyles.None, CultureInfo.InvariantCulture, out var goodsId) || goodsId <= 0)
|
||||
throw new AppException("商品编号必须是正整数", ResultCode.ValidationError);
|
||||
|
||||
var userName = request.UserName.Trim();
|
||||
await using var lease = await _indexLock.AcquireFavoritesAsync();
|
||||
using var work = _favoriteRepository.Orm.CreateUnitOfWork();
|
||||
work.GetOrBeginTransaction();
|
||||
var favorite = await work.Orm.Select<UserGoodsFavoriteEntity>()
|
||||
.Where(x => x.UserName == userName && x.GoodsId == goodsId).FirstAsync()
|
||||
?? throw new AppException("该用户尚未收藏此商品", ResultCode.NotFound);
|
||||
|
||||
await work.Orm.Update<UserGoodsFavoriteEntity>().Set(x => x.IsSafe, request.IsSafe)
|
||||
.Where(x => x.Id == favorite.Id).ExecuteAffrowsAsync();
|
||||
// 重复上报也同步索引,索引明确失败时由工作单元回滚数据库。
|
||||
await _indexService.UpdateSafetyAsync(UserFavoritesSearchDocument.BuildId(favorite.UserName, goodsId), request.IsSafe!.Value);
|
||||
work.Commit();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量取消收藏:先删除数据库记录,再删除索引文档;
|
||||
/// 索引删除失败时回补数据库记录,避免“库里有收藏但搜索不到”。
|
||||
@@ -229,6 +265,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
throw new AppException("请提供要取消收藏的商品编号", ResultCode.ValidationError);
|
||||
}
|
||||
|
||||
await using var lease = await _indexLock.AcquireFavoritesAsync();
|
||||
var favorites = await _favoriteRepository.Select
|
||||
.Where(x => x.UserName == userName && goodsIds.Contains(x.GoodsId))
|
||||
.ToListAsync();
|
||||
@@ -404,8 +441,8 @@ namespace Store.Modules.CloudProduct.Services
|
||||
{
|
||||
throw new AppException("用户名不能为空", ResultCode.ValidationError);
|
||||
}
|
||||
|
||||
request.UserName = userName;
|
||||
var mainUser = await _queryService.GetMainUser(userName);
|
||||
request.UserName = mainUser.UserName;
|
||||
|
||||
var searchResult = await _indexService.SearchAsync(request, ParseSortBy(request.SortBy));
|
||||
var list = searchResult.Documents.Select(ToItem).ToList();
|
||||
@@ -417,6 +454,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
/// </summary>
|
||||
public async Task<long> RebuildSearchIndexAsync()
|
||||
{
|
||||
await using var lease = await _indexLock.AcquireFavoritesAsync();
|
||||
// 1. 删除并重建索引(清空所有用户收藏索引)
|
||||
await _indexService.ClearIndexAsync();
|
||||
|
||||
@@ -546,6 +584,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
{
|
||||
Id = UserFavoritesSearchDocument.BuildId(favorite.UserName, favorite.GoodsId),
|
||||
FavId = favorite.Id,
|
||||
IsSafe = favorite.IsSafe,
|
||||
UserName = favorite.UserName,
|
||||
GroupId = favorite.GroupId,
|
||||
GroupName = groupName,
|
||||
@@ -568,6 +607,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
return new UserFavoriteItem
|
||||
{
|
||||
Id = document.FavId,
|
||||
IsSafe = document.IsSafe,
|
||||
UserName = document.UserName,
|
||||
GroupId = document.GroupId,
|
||||
GroupName = document.GroupName,
|
||||
|
||||
Reference in new issue
Block a user