ShoppingApp/Weifer.ShoppingApp.API/RestApi/ShoppingItemApiController.cs
2024-03-03 23:24:48 +01:00

106 lines
3.6 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Weifer.Database.EF;
using Weifer.Database.EF.Entitys;
using Weifer.ShoppingApp.API.Models;
namespace Weifer.ShoppingApp.API.RestApi
{
[ApiController]
[Route("api/[controller]")]
public class ShoppingItemApiController : ControllerBase
{
public readonly DatabaseContext dbContext;
public ShoppingItemApiController(DatabaseContext dbContext)
{
this.dbContext = dbContext;
}
[HttpGet("getItems")]
public async Task<IActionResult> GetMainItems([FromQuery] string customerId)
{
if (!Guid.TryParse(customerId, out var guidCustomerId))
{
return BadRequest("Invalid Customer ID");
}
var shoppingItems = await dbContext.ShoppingLists
.Where(x => x.CustomerId == guidCustomerId && x.ShoppingListName == "MainList")
.Include(x => x.ShoppingItems)
.SelectMany(x => x.ShoppingItems) // Wählt nur die ShoppingItems aus
.ToListAsync();
return Ok(shoppingItems);
}
[HttpPost("addMainItem")]
public async Task<IActionResult> AddMainItem([FromBody] AddItemRequest request)
{
if (!Guid.TryParse(request.CustomerId, out var guidCustomerId))
{
return BadRequest("Invalid Customer ID");
}
var itemToAdd = new ShoppingItem
{
ShoppingItemId = new Guid(request.ShoppingItemId),
ShoppingListId = await dbContext.ShoppingLists
.Where(x => x.CustomerId == guidCustomerId && x.ShoppingListName == "MainList")
.Select(x => x.ShoppingListId)
.FirstOrDefaultAsync(),
Description = request.ItemName,
Number = 1,
Purchased = false,
};
dbContext.ShoppingItems.Add(itemToAdd);
await dbContext.SaveChangesAsync();
return Ok();
}
[HttpDelete("removeItem/{shoppingItemId}")]
public async Task<IActionResult> RemoveItem(string shoppingItemId)
{
if (!Guid.TryParse(shoppingItemId, out Guid guidShoppingItemId))
{
return BadRequest("Invalid GUID format for Shopping Item ID");
}
var item = dbContext.ShoppingItems.FirstOrDefault(item => item.ShoppingItemId == guidShoppingItemId);
if (item == null)
{
return NotFound("Item not found");
}
dbContext.ShoppingItems.Remove(item);
await dbContext.SaveChangesAsync();
return Ok(new { message = "Item removed" });
}
[HttpPost("addCustomListItem")]
public async Task<IActionResult> AddCustomListItem([FromBody] AddItemRequest request)
{
var itemToAdd = new ShoppingItem
{
ShoppingItemId = new Guid(request.ShoppingItemId),
ShoppingListId = new Guid(request.ShoppingListId),
Description = request.ItemName,
Number = 1,
Purchased = false,
};
dbContext.ShoppingItems.Add(itemToAdd);
await dbContext.SaveChangesAsync();
return Ok();
}
}
public class AddItemRequest
{
public string CustomerId { get; set; }
public string ItemName { get; set; }
public string ShoppingItemId { get; set; }
public string ShoppingListId { get; set; }
}
}