GGMM/GrossesMitaines/GrossesMitainesAPI/Controllers/InvoiceController.cs

274 lines
11 KiB
C#
Raw Normal View History

2022-11-02 12:40:09 -04:00
namespace GrossesMitainesAPI.Controllers;
2022-11-02 21:00:48 -04:00
#region Dependencies
2022-11-02 12:40:09 -04:00
using GrossesMitainesAPI.Data;
2022-11-02 21:00:48 -04:00
using GrossesMitainesAPI.Models;
using GrossesMitainesAPI.Services;
using Microsoft.AspNetCore.Identity;
2022-11-01 14:07:49 -04:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
2022-11-02 21:00:48 -04:00
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNet.Identity;
using System.Data;
using System.Linq;
#endregion
2022-11-01 14:07:49 -04:00
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"),
2022-11-08 10:44:41 -05:00
Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Client, Administrateur")]
2022-11-01 14:07:49 -04:00
public class InvoiceController : Controller {
2022-11-02 21:00:48 -04:00
#region DI Fields
2022-11-01 14:07:49 -04:00
private readonly ILogger<InvoiceController> _logger;
private readonly InventoryContext _context;
2022-11-02 21:00:48 -04:00
private readonly DatabaseCacheService _cache;
private readonly SignInManager<InventoryUser> _signInMan;
private readonly Microsoft.AspNetCore.Identity.UserManager<InventoryUser> _userMan;
#endregion
#region Ctor
public InvoiceController(ILogger<InvoiceController> logger,
InventoryContext context,
2022-11-02 21:00:48 -04:00
DatabaseCacheService cache,
2022-11-03 12:45:59 -04:00
SignInManager<InventoryUser> signInMan,
Microsoft.AspNetCore.Identity.UserManager<InventoryUser> userMan) {
2022-11-02 21:00:48 -04:00
_logger = logger;
_context = context;
_cache = cache;
_userMan = userMan;
2022-11-03 12:45:59 -04:00
_signInMan = signInMan;
2022-11-02 21:00:48 -04:00
}
#endregion
#region API Methods
2022-11-08 10:44:41 -05:00
[HttpGet]
public ActionResult<List<InvoiceModel>> Get(bool? all = false) {
2022-11-02 21:00:48 -04:00
IList<string> roles;
string id;
try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver.
var user = _userMan.GetUserAsync(_signInMan.Context.User);
user.Wait();
var rolecall = _userMan.GetRolesAsync(user.Result);
rolecall.Wait();
roles = rolecall.Result;
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(10, e.Message);
roles = new List<string>();
}
2022-11-05 10:55:09 -04:00
try {
2022-11-02 21:00:48 -04:00
id = _signInMan.Context.User.Identity.GetUserId();
if (all is not null && all == true && roles.Contains("Administrateur"))
return Ok(_context.Invoices
.Include(x => x.ShippingAddress)
.Include(x => x.LinkedAccount)
.Include(x => x.Products)
.ThenInclude(y => y.Product)
.ToList());
else return Ok(_context.Invoices
.Include(x => x.ShippingAddress)
.Include(x => x.LinkedAccount)
.Include(x => x.Products)
.ThenInclude(y => y.Product)
.Where(x => x.LinkedAccount != null && x.LinkedAccount.Id == id).ToList());
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(10, e.Message);
return BadRequest();
}
}
2022-11-08 10:44:41 -05:00
[HttpGet("{id}")]
2022-11-02 21:00:48 -04:00
public async Task<ActionResult<InvoiceModel>> Get(int id) {
IList<string> roles;
InvoiceModel inv;
try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver.
roles = await _userMan.GetRolesAsync(await _userMan.GetUserAsync(_signInMan.Context.User));
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(10, e.Message);
roles = new List<string>();
}
try {
inv = _context.Invoices.Where(x => x.Id == id).Include("ShippingAddress").First();
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(10, e.Message);
return BadRequest();
}
if (roles.Contains("Administrateur") ||
(inv.LinkedAccount is not null &&
inv.LinkedAccount.Id == _signInMan.Context.User.Identity.GetUserId()))
return inv;
else return Unauthorized();
}
2022-11-01 14:07:49 -04:00
2022-11-02 21:00:48 -04:00
[HttpPost, AllowAnonymous]
2022-11-13 20:54:56 -05:00
public ActionResult<InvoiceModel> Post(SendInvoiceModel sinv) {
var user = _userMan.GetUserAsync(_signInMan.Context.User);
2022-11-04 18:22:24 -04:00
var prodcom = sinv.ProdQuant;
Dictionary<int, uint> badprods = new();
2022-11-02 21:00:48 -04:00
List<ProductModel> prods;
InvoiceModel inv = new() {
2022-11-04 18:22:24 -04:00
FirstName = sinv.FirstName,
LastName = sinv.LastName,
EmailAddress = sinv.EmailAddress,
PhoneNumber = sinv.PhoneNumber,
2022-11-23 17:35:55 -05:00
PurchaseDate = DateTime.Now,
Products = new List<InvoiceModel.ProductInvoice>()
2022-11-04 18:22:24 -04:00
};
2022-11-08 10:44:41 -05:00
AddressModel ad;
2022-11-13 20:54:56 -05:00
user.Wait();
2022-11-08 10:44:41 -05:00
2022-11-13 20:54:56 -05:00
if (user.Result is not null) {
inv.LinkedAccount = user.Result;
2022-11-08 10:44:41 -05:00
ad = _context.Addresses.FirstOrDefault(x => x.CivicNumber == sinv.CivicNumber &&
2022-11-04 18:22:24 -04:00
x.Appartment == sinv.Appartment &&
x.Street == sinv.Street &&
x.City == sinv.City &&
x.Province == sinv.Province &&
x.Country == sinv.Country) ??
new() {
2022-11-04 18:22:24 -04:00
CivicNumber = sinv.CivicNumber,
Appartment = sinv.Appartment,
Street = sinv.Street,
City = sinv.City,
Province = sinv.Province,
Country = sinv.Country,
PostalCode = sinv.PostalCode
};
2022-11-08 10:44:41 -05:00
}
else ad = new() {
CivicNumber = sinv.CivicNumber,
Appartment = sinv.Appartment,
Street = sinv.Street,
City = sinv.City,
Province = sinv.Province,
Country = sinv.Country,
PostalCode = sinv.PostalCode
};
2022-11-04 18:22:24 -04:00
inv.ShippingAddress = ad;
2022-11-02 21:00:48 -04:00
try {
2022-11-04 18:22:24 -04:00
prods = _context.Products.Where(x => sinv.ProdQuant.Select(x => x.Key).Contains(x.Id)).ToList();
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(8, e.Message);
return BadRequest();
}
2022-11-23 19:53:22 -05:00
foreach (var prod in prods) {
inv.Products.Add(new() {
Product = prod,
Quantity = sinv.ProdQuant.First(x => x.Key == prod.Id).Value
});
}
2022-11-03 12:45:59 -04:00
if (prods.Count == 0)
return BadRequest("Vous devez inclure au moins un produit à votre commande.");
2022-11-04 18:22:24 -04:00
foreach (var prod in sinv.ProdQuant) { // Update de quantités dans l'inventaire.
ProductModel inventProd = prods.Where(x => x.Id == prod.Key).First();
2022-11-22 11:07:06 -05:00
if (inventProd.Quantity < prod.Value)
badprods.Add(prod.Key, inventProd.Quantity);
else if (inventProd.Quantity == prod.Value) {
2022-11-02 21:00:48 -04:00
inventProd.Quantity = 0;
inventProd.Status = inventProd.Status == ProductModel.States.Clearance ?
ProductModel.States.Discontinued :
ProductModel.States.BackOrder;
2022-11-08 10:44:41 -05:00
} else inventProd.Quantity -= prod.Value;
2022-11-03 12:45:59 -04:00
inventProd.LastSale = DateTime.Now;
2022-11-04 18:22:24 -04:00
inventProd.Sales += prod.Value;
2022-11-02 21:00:48 -04:00
}
2022-11-03 12:45:59 -04:00
if (badprods.Count > 0) // Retour des produits non-achetable avec l'inventaire restant.
return BadRequest(badprods.ToArray());
2022-11-02 21:00:48 -04:00
try { // Faire les updates dans la BD.
2022-11-13 20:54:56 -05:00
if (ad.Id == 0)
_context.Addresses.Add(ad);
2022-11-02 21:00:48 -04:00
_context.Invoices.Add(inv);
_context.Products.UpdateRange(prods);
_context.SaveChanges();
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(8, e.Message);
2022-11-04 18:22:24 -04:00
return BadRequest(e.InnerException.Message);
2022-11-02 21:00:48 -04:00
}
_cache.askForRefresh();
return Ok(inv);
2022-11-01 14:07:49 -04:00
}
2022-11-23 18:00:50 -05:00
[HttpPost("Cancel/{id}")]
2022-11-14 10:19:33 -05:00
public ActionResult<InvoiceModel> Cancel(int id) {
2022-11-02 21:00:48 -04:00
InvoiceModel inv;
2022-11-14 10:19:33 -05:00
List<ProductModel> prods;
2022-11-02 21:00:48 -04:00
IList<string> roles;
try { // Trouver la commande.
inv = _context.Invoices.Where(x => x.Id == id)
2022-11-14 10:19:33 -05:00
.Include(x => x.Products).ThenInclude(x => x.Product).First();
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(8, e.Message);
return BadRequest();
}
2022-11-01 14:07:49 -04:00
2022-11-02 21:00:48 -04:00
try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver.
2022-11-14 10:19:33 -05:00
var user = _userMan.GetUserAsync(_signInMan.Context.User);
user.Wait();
var rolecall = _userMan.GetRolesAsync(user.Result);
rolecall.Wait();
roles = rolecall.Result;
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(10, e.Message);
roles = new List<string>();
}
2022-11-01 14:07:49 -04:00
2022-11-02 21:00:48 -04:00
// Pour ne pas pouvoir arbitrairement annuler la commande d'un autre client en tant que client.
if (!((inv.LinkedAccount is not null &&
2022-11-02 21:00:48 -04:00
inv.LinkedAccount.Id == _signInMan.Context.User.Identity.GetUserId()) ||
roles.Contains("Administrateur")))
return Unauthorized();
2022-11-03 12:45:59 -04:00
if (inv.Status == InvoiceModel.InStates.Cancelled ||
inv.Status == InvoiceModel.InStates.Returned)
return BadRequest("La commande à déjà été annulée.");
if (inv.Status == InvoiceModel.InStates.Shipped)
return BadRequest("Il est trop tard pour annuler votre commande, veuillez contacter le service à la clientèle pour retourner la commande.");
2022-11-02 21:00:48 -04:00
inv.Status = InvoiceModel.InStates.Cancelled;
2022-11-14 10:19:33 -05:00
try {
prods = _context.Products.Where(x => inv.Products.Select(x => x.Product.Id).Contains(x.Id)).ToList();
foreach (var prod in inv.Products) { // Revert de quantités dans l'inventaire.
ProductModel inventProd = prods.First(x => x.Id == prod.Product.Id);
inventProd.Quantity += prod.Quantity;
inventProd.Status = inventProd.Status == ProductModel.States.Discontinued ?
ProductModel.States.Clearance :
ProductModel.States.Available;
if (inventProd.Sales - prod.Quantity < 0)
inventProd.Sales = 0;
else inventProd.Sales -= prod.Quantity;
}
} catch (Exception e) {
_logger.LogError(8, e.Message);
return BadRequest();
}
2022-11-02 21:00:48 -04:00
try {
_context.Update(inv);
_context.SaveChanges();
2022-11-08 10:44:41 -05:00
} catch (Exception e) {
2022-11-02 21:00:48 -04:00
_logger.LogError(8, e.Message);
return BadRequest();
}
_cache.askForRefresh();
return Ok(inv);
}
2022-11-01 14:07:49 -04:00
2022-11-02 21:00:48 -04:00
#endregion
}