Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add orders full data #15

Merged
merged 7 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions NorthwindCRUD/Controllers/OrdersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public ActionResult<OrderDto[]> GetAll()
return StatusCode(500);
}
}

[HttpGet("{id}")]
[Authorize]
public ActionResult<OrderDto> GetById(int id)
Expand Down Expand Up @@ -75,10 +75,10 @@ public ActionResult<OrderDetailDto[]> GetDetailsByOrderId(int id)
{
try
{
var order = this.orderService.GetById(id);
if (order != null)
var orderDetail = this.orderService.GetOrderDetailsById(id);
if (orderDetail != null)
{
return Ok(this.mapper.Map<OrderDetailDb[], OrderDetailDto[]>(order.Details.ToArray()));
return Ok(this.mapper.Map<OrderDetailDb[], OrderDetailDto[]>(orderDetail));
}

return NotFound();
Expand Down Expand Up @@ -174,10 +174,10 @@ public ActionResult<ProductDto[]> GetProductsByOrderId(int id)
{
try
{
var order = this.orderService.GetById(id);
if (order != null)
var orderDetails = this.orderService.GetOrderDetailsById(id);
if (orderDetails != null)
{
var productIds = order.Details.Select(o => o.ProductId).ToArray();
var productIds = orderDetails.Select(o => o.ProductId).ToArray();
var products = this.productService.GetProductsByIds(productIds);

if (products != null)
Expand All @@ -196,6 +196,22 @@ public ActionResult<ProductDto[]> GetProductsByOrderId(int id)
}
}

[HttpGet("retrieve/{ordersToRetrieve}")]
[Authorize]
public ActionResult<OrderDto[]> OrdersToRetrieve(int ordersToRetrieve)
{
try
{
var orders = this.orderService.GetNOrders(ordersToRetrieve);
return Ok(this.mapper.Map<OrderDb[], OrderDto[]>(orders));
}
catch (Exception error)
{
logger.LogError(error.Message);
return StatusCode(500);
}
}

[HttpPost]
[Authorize]
public ActionResult<OrderDto> Create(OrderDto model)
Expand Down
103 changes: 103 additions & 0 deletions NorthwindCRUD/Controllers/SalesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
namespace NorthwindCRUD.Controllers
{
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NorthwindCRUD.Models.DbModels;
using NorthwindCRUD.Models.Dtos;
using NorthwindCRUD.Models.InputModels;
using NorthwindCRUD.Services;
using System.ComponentModel.DataAnnotations;

[ApiController]
[Route("[controller]")]
public class SalesController : ControllerBase
{
private readonly SalesService salesService;
private readonly ProductService productService;
private readonly IMapper mapper;
private readonly ILogger logger;

public SalesController(SalesService salesService, IMapper mapper, ILogger logger)
{
this.salesService = salesService;
this.mapper = mapper;
this.logger = logger;
}

[HttpGet("ByCategory")]
[Authorize]
public IActionResult GetSalesByCategoryAndYear([FromQuery] [Required] string categoryName, [FromQuery] int? orderYear = null)
{
try {
var response = this.salesService.GetSalesDataByCategoryAndYear(categoryName, orderYear);
return Ok(response);
}
catch
{
return BadRequest();
}
}

[HttpGet("ByCountry/{country}")]
[Authorize]
public IActionResult GetSalesByCountry(
string country,
[FromQuery] [Required] string startDate,
[FromQuery] [Required] string endDate)
{

try
{
var salesData = this.salesService.RetrieveSalesDataByCountry(startDate, endDate, country);

if (salesData == null)
{
return NotFound("No sales data found for the specified parameters.");
}

return Ok(salesData);
}
catch (ArgumentException exception)
{
return StatusCode(400, exception.Message);
}
catch (Exception error)
{
logger.LogError(error.Message);
return StatusCode(500);
}
}

[HttpGet("ByYear/{year}")]
[Authorize]
public IActionResult GetSalesByYear(
int year,
[FromQuery] int startMounth,
[FromQuery] int endMounth)
{

try
{
var salesData = this.salesService.RetrieveSalesDataByYear(year, startMounth, endMounth);

if (salesData == null)
{
return NotFound("No sales data found for the specified parameters.");
}

return Ok(salesData);
}
catch (ArgumentException exception)
{
return StatusCode(400, exception.Message);
}
catch (Exception error)
{
logger.LogError(error.Message);
return StatusCode(500);
}
}
}
}
8 changes: 0 additions & 8 deletions NorthwindCRUD/DataContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
.WithMany(s => s.Orders)
.OnDelete(DeleteBehavior.SetNull);

modelBuilder.Entity<OrderDetailDb>()
.HasOne(od => od.Product)
.WithMany(p => p.Details);

modelBuilder.Entity<OrderDetailDb>()
.HasOne(o => o.Order)
.WithMany(o => o.Details);

modelBuilder.Entity<EmployeeDb>()
.HasOne(e => e.Address)
.WithMany(a => a.Employees)
Expand Down
35 changes: 21 additions & 14 deletions NorthwindCRUD/Helpers/DBSeeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public static void Seed(DataContext dbContext)
SeedEmployees(dbContext);
SeedCustomers(dbContext);
SeedOrders(dbContext);
SeedOrderDetails(dbContext);
SeedEmployeesTerritories(dbContext);

transaction.Commit();
Expand Down Expand Up @@ -109,24 +110,24 @@ private static void SeedOrders(DataContext dbContext)
dbContext.Addresses.Add(order.ShipAddress);
}

if (!dbContext.OrderDetails.Any(o => o.OrderId == order.OrderId))
{
var orderDetailsData = order.Details.ToList();

orderDetailsData.ForEach(o =>
{
o.OrderId = order.OrderId;
});

dbContext.OrderDetails.AddRange(order.Details);
}

dbContext.Orders.Add(order);
}
dbContext.SaveChanges();
}
}

private static void SeedOrderDetails(DataContext dbContext)
{
if (!dbContext.OrderDetails.Any())
{
var ordersDetailsData = File.ReadAllText("./Resources/orderDetails.json");
var parsedordersDetails = JsonConvert.DeserializeObject<OrderDetailDb[]>(ordersDetailsData);
dbContext.OrderDetails.AddRange(parsedordersDetails);
dbContext.SaveChanges();
}
}

private static void SeedEmployees(DataContext dbContext)
{
if (!dbContext.Employees.Any())
Expand Down Expand Up @@ -155,11 +156,17 @@ private static void SeedCustomers(DataContext dbContext)

foreach (var customer in parsedCustomers)
{
if (dbContext.Addresses.FirstOrDefault(a => a.Street == customer.Address.Street) == null)
var existingCustomer = dbContext.Customers.Find(customer.CustomerId);

if (existingCustomer == null)
{
dbContext.Addresses.Add(customer.Address);
if (dbContext.Addresses.FirstOrDefault(a => a.Street == customer.Address.Street) == null)
{
dbContext.Addresses.Add(customer.Address);
}

dbContext.Customers.Add(customer);
}
dbContext.Customers.Add(customer);
}
dbContext.SaveChanges();
}
Expand Down
2 changes: 1 addition & 1 deletion NorthwindCRUD/Models/Contracts/IAddress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ public interface IAddress

string Country { get; set; }

string Phone { get; set; }
string? Phone { get; set; }
}
}
2 changes: 0 additions & 2 deletions NorthwindCRUD/Models/Contracts/IOrder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,5 @@ public interface IOrder
string ShipName { get; set; }

AddressDto ShipAddress { get; set; }

ICollection<OrderDetailDto> OrderDetails { get; set; }
}
}
2 changes: 1 addition & 1 deletion NorthwindCRUD/Models/DbModels/AddressDb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class AddressDb : IAddress

public string Country { get; set; }

public string Phone { get; set; }
public string? Phone { get; set; }

public ICollection<CustomerDb> Customers { get; set; }

Expand Down
3 changes: 0 additions & 3 deletions NorthwindCRUD/Models/DbModels/OrderDb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ public class OrderDb
{
public OrderDb()
{
this.Details = new List<OrderDetailDb>();
}

[Key]
Expand Down Expand Up @@ -46,7 +45,5 @@ public OrderDb()
public string? ShipAddressId { get; set; }

public AddressDb? ShipAddress { get; set; }

public ICollection<OrderDetailDb> Details { get; set; }
}
}
12 changes: 0 additions & 12 deletions NorthwindCRUD/Models/Dtos/OrderDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,6 @@ public class OrderDto : IOrder

public string ShipName { get; set; }

public string ShipAddressId { get; set; }

public int ProductId { get; set; }

public double UnitPrice { get; set; }

public int Quantity { get; set; }

public float Discount { get; set; }

public AddressDto ShipAddress { get; set; }

public ICollection<OrderDetailDto> OrderDetails { get; set; }
}
}
9 changes: 9 additions & 0 deletions NorthwindCRUD/Models/Dtos/SalesDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace NorthwindCRUD.Models.Dtos
{
public class SalesDto
{
public int ProductId { get; set; }
public int QuantitySold { get; set; }
public double SaleAmount { get; set; }
}
}
1 change: 1 addition & 0 deletions NorthwindCRUD/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@
builder.Services.AddTransient<ShipperService>();
builder.Services.AddTransient<SupplierService>();
builder.Services.AddTransient<TerritoryService>();
builder.Services.AddTransient<SalesService>();

var app = builder.Build();

Expand Down
42 changes: 42 additions & 0 deletions NorthwindCRUD/Resources/customers.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,46 @@
[
{
"customerId": "ALFKI",
"companyName": "Alfreds Futterkiste",
"contactName": "Maria Anders",
"contactTitle": "Sales Representative",
"address": {
"street": "Obere Str. 57",
"city": "Berlin",
"region": "",
"postalCode": "12209",
"country": "Germany",
"phone": "(171) 555-7788"
}
},
{
"customerId": "ANATR",
"companyName": "Ana Trujillo Emparedados y helados",
"contactName": "Ana Trujillo",
"contactTitle": "Owner",
"address": {
"street": "Avda. de la Constitución 2222",
"city": "México D.F.",
"region": "",
"postalCode": "05021",
"country": "Mexico",
"phone": "(5) 555-4729"
}
},
{
"customerId": "ANTON",
"companyName": "Antonio Moreno Taquería",
"contactName": "Antonio Moreno",
"contactTitle": "Owner",
"address": {
"street": "Mataderos 2312",
"city": "México D.F.",
"region": "",
"postalCode": "05023",
"country": "Mexico",
"phone": "(5) 555-3932"
}
},
{
"customerID": "AROUT",
"companyName": "Around the Horn",
Expand Down
Loading