diff --git a/AssetManager.API/Controllers/PortfolioController.cs b/AssetManager.API/Controllers/PortfolioController.cs index 715eb16..5b64834 100644 --- a/AssetManager.API/Controllers/PortfolioController.cs +++ b/AssetManager.API/Controllers/PortfolioController.cs @@ -501,4 +501,94 @@ public class PortfolioController : ControllerBase }); } } + + /// + /// 删除投资组合 + /// + /// 投资组合ID + /// 删除结果 + [HttpDelete("{id}")] + public async Task>> DeletePortfolio(string id) + { + try + { + var userId = GetCurrentUserId(); + if (string.IsNullOrEmpty(userId)) + { + return Unauthorized(new ApiResponse + { + code = AssetManager.Models.StatusCodes.Unauthorized, + data = false, + message = "用户未授权" + }); + } + + _logger.LogInformation($"Request to delete portfolio: {id}"); + + var db = _databaseService.GetDb(); + + // 校验组合是否存在且属于当前用户 + var portfolio = db.Queryable() + .Where(p => p.Id == id && p.UserId == userId) + .First(); + + if (portfolio == null) + { + return NotFound(new ApiResponse + { + code = AssetManager.Models.StatusCodes.NotFound, + data = false, + message = "投资组合不存在或无权限删除" + }); + } + + // 开启事务删除相关数据 + db.Ado.BeginTran(); + try + { + // 删除交易记录 + db.Deleteable() + .Where(t => t.PortfolioId == id) + .ExecuteCommand(); + + // 删除持仓 + db.Deleteable() + .Where(p => p.PortfolioId == id) + .ExecuteCommand(); + + // 删除组合本身 + db.Deleteable() + .Where(p => p.Id == id) + .ExecuteCommand(); + + db.Ado.CommitTran(); + } + catch (Exception ex) + { + db.Ado.RollbackTran(); + _logger.LogError(ex, "删除投资组合事务失败"); + throw; + } + + _logger.LogInformation($"Portfolio {id} deleted successfully"); + + return Ok(new ApiResponse + { + code = AssetManager.Models.StatusCodes.Success, + data = true, + message = "删除成功" + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error deleting portfolio"); + + return StatusCode(AssetManager.Models.StatusCodes.InternalServerError, new ApiResponse + { + code = AssetManager.Models.StatusCodes.InternalServerError, + data = false, + message = ex.Message + }); + } + } }