using Apimanager_backend.Data; using Apimanager_backend.Dtos; using Apimanager_backend.Exceptions; using Apimanager_backend.Models; using Apimanager_backend.Tools; using AutoMapper; using Microsoft.EntityFrameworkCore; namespace Apimanager_backend.Services { public class OrderService:IOrderService { private ApiContext _apiContext; private IMapper mapper; private ILogger logger; public OrderService(ApiContext apiContext,IMapper mapper,ILogger logger) { _apiContext = apiContext; this.mapper = mapper; this.logger = logger; } #region 创建订单 /// /// 创建订单 /// /// 订单信息 /// /// public async Task CreateOrderAsync(OrderDto order) { var transaction = await _apiContext.Database.BeginTransactionAsync(); try { Order orderInfo = mapper.Map(order); //初始化信息 orderInfo.Status = OrderStatus.Pending; orderInfo.CreatedAt = DateTime.Now; orderInfo.OrderNumber = OrderNumberGenerator.Generate(order.UserId); _apiContext.Orders.Add(orderInfo); await _apiContext.SaveChangesAsync(); await transaction.CommitAsync(); return orderInfo; }catch(Exception e) { //异常回滚 await transaction.RollbackAsync(); logger.LogError(e.Message); throw new BaseException(4006,"支付系统错误"); } } #endregion #region 获取订单列表 /// /// 获取订单列表 /// /// 索引 /// 页大小 /// 是否倒序 /// 指定用户订单 /// public async Task> GetOrdersAsync(int pageIndex, int pageSize, bool desc, int? userId) { IQueryable query = _apiContext.Orders.AsQueryable().OrderBy(x => x.Id); if(userId != null) { query.Where(x => x.UserId == userId); } //倒序 if (desc) { query.OrderDescending(); } //分页 query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize); return await query.ToListAsync(); } #endregion #region 更新订单状态 public async Task UpdateOrderAsync(OrderDto order) { var transaction = await _apiContext.Database.BeginTransactionAsync(); try { var data = await _apiContext.Orders.SingleOrDefaultAsync(x => x.OrderNumber == order.OrderNumber || x.ThirdPartyOrderId == order.ThirdPartyOrderId); if (data == null) { throw new BaseException(4003, "订单未找到"); } data.UpdatedAt = DateTime.Now; data.Status = order.Status; data.PaiAt = order.Status == OrderStatus.Completed ? DateTime.Now : null; var user = await _apiContext.Users.FirstOrDefaultAsync(x => x.Id == order.UserId); if (user == null) { throw new BaseException(2004, "用户未找到"); } user.Balance += order.Amount; _apiContext.Orders.Update(data); _apiContext.Users.Update(user); await _apiContext.SaveChangesAsync(); await transaction.CommitAsync(); return true; }catch(Exception e) { await transaction.RollbackAsync(); logger.LogError(e.Message); throw; } } #endregion } }