9 Commits

88 changed files with 718 additions and 6013 deletions

View File

@@ -1,7 +1,7 @@
namespace PyroFetes.DTO.Login.Request;
namespace PyroFetes.DTO.Login.Request;
public class ConnectLoginDto
{
public string? Username { get; set; }
public string? Name { get; set; }
public string? Password { get; set; }
}

View File

@@ -1,8 +1,24 @@
namespace PyroFetes.DTO.Login.Request;
using System.ComponentModel.DataAnnotations;
// Nécessaire pour les validations
namespace PyroFetes.DTO.Login.Request;
public class CreateLoginDto
{
public string? Username { get; set; }
public string? FullName { get; set; }
public string? Password { get; set; }
[Required(ErrorMessage = "Le nom est requis.")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "L'identifiant doit faire entre 3 et 50 caractères.")]
public string Name { get; set; } = string.Empty;
[Required(ErrorMessage = "L'emil est requis.")]
[StringLength(50, MinimumLength = 3)]
public string Email { get; set; } = string.Empty;
[Required(ErrorMessage = "Le mot de passe est requis.")]
[MinLength(6, ErrorMessage = "Le mot de passe doit contenir au moins 6 caractères.")]
public string Password { get; set; } = string.Empty;
// Ajout du champ Rôle (Optionnel, par défaut "User")
// Cela te permet d'envoyer "Admin" via Swagger
public string Fonction { get; set; } = "User";
}

View File

@@ -1,9 +1,8 @@
namespace PyroFetes.DTO.Login.Request;
namespace PyroFetes.DTO.Login.Request;
public class UpdateLoginDto
{
public int Id { get; set; }
public string? Username { get; set; }
public string? FullName { get; set; }
public string? Name { get; set; }
public string? Password { get; set; }
}

View File

@@ -1,4 +1,4 @@
namespace PyroFetes.DTO.Login.Response;
namespace PyroFetes.DTO.Login.Response;
public class GetLoginConnectDto
{

View File

@@ -1,10 +1,10 @@
namespace PyroFetes.DTO.Login.Response;
namespace PyroFetes.DTO.Login.Response;
public class GetLoginDto
{
public int Id { get; set; }
public string? Username { get; set; }
public string? FullName { get; set; }
public string? Password { get; set; }
public string? Salt { get; set; }
public string? Name { get; set; } = string.Empty;
public string? Email { get; set; } = string.Empty;
public string? Password { get; set; } = string.Empty;
public string? Fonction { get; set; } = string.Empty;
}

View File

@@ -6,7 +6,7 @@ namespace PyroFetes.DTO.Product.Request
public class CreateProductDto
{
// Référence interne du produit
public int References { get; set; }
public string? Reference { get; set; }
// Nom du produit
public string? Name { get; set; }
@@ -15,10 +15,10 @@ namespace PyroFetes.DTO.Product.Request
public decimal Duration { get; set; }
// Calibre du produit
public decimal Caliber { get; set; }
public int Caliber { get; set; }
// Numéro dhomologation
public int ApprovalNumber { get; set; }
public string? ApprovalNumber { get; set; }
// Poids du produit
public decimal Weight { get; set; }

View File

@@ -9,7 +9,7 @@ namespace PyroFetes.DTO.Product.Request
public int Id { get; set; }
// Référence interne du produit
public int References { get; set; }
public string? Reference { get; set; }
// Nom du produit
public string? Name { get; set; }
@@ -18,10 +18,10 @@ namespace PyroFetes.DTO.Product.Request
public decimal Duration { get; set; }
// Calibre du produit
public decimal Caliber { get; set; }
public int Caliber { get; set; }
// Numéro dhomologation
public int ApprovalNumber { get; set; }
public string? ApprovalNumber { get; set; }
// Poids du produit
public decimal Weight { get; set; }

View File

@@ -10,7 +10,7 @@ namespace PyroFetes.DTO.Product.Response
public int Id { get; set; }
// Référence interne du produit
public int Reference { get; set; }
public string? Reference { get; set; }
// Nom du produit
public string? Name { get; set; }
@@ -19,10 +19,10 @@ namespace PyroFetes.DTO.Product.Response
public decimal Duration { get; set; }
// Calibre du produit
public decimal Caliber { get; set; }
public int Caliber { get; set; }
// Numéro dhomologation
public int ApprovalNumber { get; set; }
public string? ApprovalNumber { get; set; }
// Poids du produit
public decimal Weight { get; set; }

View File

@@ -4,22 +4,22 @@
public class CreateSupplierDto
{
// Nom du fournisseur
public string Name { get; set; }
public string? Name { get; set; }
// Email du fournisseur
public string Email { get; set; }
public string? Email { get; set; }
// Numéro de téléphone du fournisseur
public string PhoneNumber { get; set; }
public string? PhoneNumber { get; set; }
// Adresse du fournisseur
public string Adress { get; set; }
public string? Adress { get; set; }
// Code postal de l'adresse
public int ZipCode { get; set; }
public string? ZipCode { get; set; }
// Ville de l'adresse
public string City { get; set; }
public string? City { get; set; }
// Liste des produits fournis par ce fournisseur dans la classe SupplierProductPriceDto
public List<SupplierProductPriceDto>? Products { get; set; }

View File

@@ -7,22 +7,22 @@
public int Id { get; set; }
// Nom du fournisseur
public string Name { get; set; }
public string? Name { get; set; }
// Email du fournisseur
public string Email { get; set; }
public string? Email { get; set; }
// Numéro de téléphone du fournisseur
public string PhoneNumber { get; set; }
public string? PhoneNumber { get; set; }
// Adresse du fournisseur
public string Adress { get; set; }
public string? Adress { get; set; }
// Code postal de l'adresse
public int ZipCode { get; set; }
public string? ZipCode { get; set; }
// Ville de l'adresse
public string City { get; set; }
public string? City { get; set; }
// Liste des produits fournis par ce fournisseur relié à la classe SupplierProductPriceDto
public List<SupplierProductPriceDto>? Products { get; set; }

View File

@@ -9,22 +9,22 @@ namespace PyroFetes.DTO.Supplier.Response
public int Id { get; set; }
// Nom du fournisseur
public string Name { get; set; }
public string? Name { get; set; }
// Email du fournisseur
public string Email { get; set; }
public string? Email { get; set; }
// Numéro de téléphone
public string PhoneNumber { get; set; }
public string? PhoneNumber { get; set; }
// Adresse du fournisseur
public string Adress { get; set; }
public string? Adress { get; set; }
// Code postal
public int ZipCode { get; set; }
public string? ZipCode { get; set; }
// Ville
public string City { get; set; }
public string? City { get; set; }
// Liste des produits fournis par la classe SupplierProductPriceDto
public List<SupplierProductPriceDto> Products { get; set; } = new();

View File

@@ -4,7 +4,7 @@
public class CreateWarehouseDto
{
// Nom de l'entrepôt
public string Name { get; set; }
public string? Name { get; set; }
// Poids maximal que l'entrepôt peut contenir
public int MaxWeight { get; set; }
@@ -16,13 +16,13 @@
public int MinWeight { get; set; }
// Adresse de l'entrepôt
public string Adress { get; set; }
public string? Adress { get; set; }
// Code postal
public int ZipCode { get; set; }
public string? ZipCode { get; set; }
// Ville
public string City { get; set; }
public string? City { get; set; }
// Liste des produits à stocker dans cet entrepôt venant de la classe en dessous
public List<CreateWarehouseProductDto>? Products { get; set; }

View File

@@ -7,7 +7,7 @@
public int Id { get; set; }
// Nom de l'entrepôt
public string Name { get; set; }
public string? Name { get; set; }
// Poids maximal que l'entrepôt peut contenir
public int MaxWeight { get; set; }
@@ -19,13 +19,13 @@
public int MinWeight { get; set; }
// Adresse de l'entrepôt
public string Adress { get; set; }
public string? Adress { get; set; }
// Code postal
public int ZipCode { get; set; }
public string? ZipCode { get; set; }
// Ville
public string City { get; set; }
public string? City { get; set; }
// Liste des produits à mettre à jour dans cet entrepôt
public List<UpdateWarehouseProductDto>? Products { get; set; }

View File

@@ -7,7 +7,7 @@
public int Id { get; set; }
// Nom de l'entrepôt
public string Name { get; set; }
public string? Name { get; set; }
// Poids maximal que l'entrepôt peut contenir
public int MaxWeight { get; set; }
@@ -19,13 +19,13 @@
public int MinWeight { get; set; }
// Adresse de l'entrepôt
public string Adress { get; set; }
public string? Adress { get; set; }
// Code postal
public int ZipCode { get; set; }
public string? ZipCode { get; set; }
// Ville
public string City { get; set; }
public string? City { get; set; }
// Liste des produits stockés dans l'entrepôt
public List<WarehouseProductDto>? Products { get; set; }

View File

@@ -4,32 +4,31 @@ using PyroFetes.DTO.Brand.Request;
namespace PyroFetes.Endpoints.Brand;
public class CreateBrandEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateBrandDto, GetBrandDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateBrandDto et l'élement de réponse GetBrandDto
public class CreateBrandEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateBrandDto, GetBrandDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/brands"); //Créer une marque
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/brands");
}
public override async Task HandleAsync(CreateBrandDto req, CancellationToken ct)
public override async Task HandleAsync(CreateBrandDto req, CancellationToken ct)
{
Models.Brand brand = new () //Création d'un nom rentré par l'utilisateur
Models.Brand brand = new ()
{
Name = req.Name
};
pyrofetesdbcontext.Brands.Add(brand); //Ajout de la marque à la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde de la marque dans la bdd
pyrofetesdbcontext.Brands.Add(brand);
await pyrofetesdbcontext.SaveChangesAsync(ct);
Console.WriteLine("Marque créé avec succès !");
GetBrandDto responseDto = new () //Renvoie le nom
GetBrandDto responseDto = new ()
{
Name = req.Name
Name = req.Name
};
await Send.OkAsync(responseDto, ct); //Réponse au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -5,34 +5,33 @@ namespace PyroFetes.Endpoints.Brand;
public class DeleteBrandRequest
{
public int Id { get; set; } //Création d'un Id
public int Id { get; set; }
}
public class DeleteBrandEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteBrandRequest> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête DeleteBrandDto.
public class DeleteBrandEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteBrandRequest>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Delete("/api/brands/{@id}", x => new { x.Id }); //Supprime une marque
AllowAnonymous(); //Autorise l'accès sans authentification
Delete("/brands/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteBrandRequest req, CancellationToken ct)
{
Models.Brand? brandToDelete = await pyrofetesdbcontext //Récupère une marque dans la bdd et le stocke dans brandToDelete
.Brands //Recherche la couleur dans la table Colors
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct); //Recherche une couleur dont l'id correspond à req.Id
Models.Brand? brandToDelete = await pyrofetesdbcontext
.Brands
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (brandToDelete == null)
{
Console.WriteLine($"Aucune marque avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
pyrofetesdbcontext.Brands.Remove(brandToDelete); //Supprime la marque de la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde de la marque dans la bdd
pyrofetesdbcontext.Brands.Remove(brandToDelete);
await pyrofetesdbcontext.SaveChangesAsync(ct);
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -8,21 +8,20 @@ public class GetAllBrandsEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpo
{
public override void Configure()
{
Get("/api/brands"); //Endpoint qui affiche toutes les marques
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/brands");
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetBrandDto> responseDto = await pyrofetesdbcontext.Brands //Création d'une liste qui récupère toutes les marques dans la bdd
.Select(a => new GetBrandDto //Sélectionne dans la liste chaque marque
List<GetBrandDto> responseDto = await pyrofetesdbcontext.Brands
.Select(a => new GetBrandDto
{
Id = a.Id, //Affiche l'id
Name = a.Name, //Affiche le nom
Id = a.Id,
Name = a.Name,
}
).ToListAsync(ct); //Retourne la liste de marque
).ToListAsync(ct);
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -13,30 +13,29 @@ public class GetBrandEndpoint(PyroFetesDbContext pyrofetesdbcontext) :Endpoint<G
{
public override void Configure()
{
Get("/api/brands/{@id}", x => new { x.Id }); //endpoint qui affiche la marque en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/brands/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetBrandRequest req, CancellationToken ct)
{
Models.Brand? brand = await pyrofetesdbcontext //Récupère la table marque dans la bdd
.Brands
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct); //récupère l'id
Models.Brand? brand = await pyrofetesdbcontext
.Brands
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (brand == null)
{
Console.WriteLine($"Aucune marque avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
GetBrandDto responseDto = new() //renvoie l'id et le nom
GetBrandDto responseDto = new()
{
Id = req.Id, //Affiche l'id
Name = brand.Name //Affiche le nom
Id = req.Id,
Name = brand.Name
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -8,27 +8,26 @@ public class UpdateBrandEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoi
{
public override void Configure()
{
Put("/api/brands/{Id}"); //Met à jour la marque en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Put("/brands/{Id}");
}
public override async Task HandleAsync(UpdateBrandDto req, CancellationToken ct)
{
Models.Brand brand = new() //Met à jour la marque
Models.Brand brand = new()
{
Name = req.Name
};
pyrofetesdbcontext.Add(brand); //ajoute la marque dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements
pyrofetesdbcontext.Add(brand);
await pyrofetesdbcontext.SaveChangesAsync(ct);
GetBrandDto response = new() //renvoie l'id et le nom
GetBrandDto response = new()
{
Id = req.Id,
Name = req.Name
};
await Send.OkAsync(response, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(response, ct);
}
}

View File

@@ -4,32 +4,31 @@ using FastEndpoints;
namespace PyroFetes.Endpoints.Classification;
public class CreateClassificationEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateClassificationDto, GetClassificationDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateClassificationDto et l'élement de réponse GetClassificationDto
public class CreateClassificationEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateClassificationDto, GetClassificationDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/classifications"); //Créer une classification
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/classifications");
}
public override async Task HandleAsync(CreateClassificationDto req, CancellationToken ct)
{
Models.Classification classification = new () //Création d'un label rentré par l'utilisateur
Models.Classification classification = new ()
{
Label = req.Label
};
pyrofetesdbcontext.Classifications.Add(classification); //Ajout de la classification à la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde de la classification dans la bdd
pyrofetesdbcontext.Classifications.Add(classification);
await pyrofetesdbcontext.SaveChangesAsync(ct);
Console.WriteLine("Classification créée avec succès !");
GetClassificationDto responseDto = new () //Renvoie le label de la classification
GetClassificationDto responseDto = new ()
{
Label = req.Label
};
await Send.OkAsync(responseDto, ct); //Réponse au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -12,27 +12,26 @@ public class DeleteClassificationEndpoint(PyroFetesDbContext libraryDbContext) :
{
public override void Configure()
{
Delete("/api/classifications/{@id}", x => new { x.Id }); //Supprime une classification en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Delete("/classifications/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteClassificationRequest req, CancellationToken ct)
{
Models.Classification? classificationToDelete = await libraryDbContext //Récupère une classification dans la bdd et le stocke dans classificationToDelete
.Classifications //Recherche la classification dans la table Classifications
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct); //Recherche une classification dont l'id correspond à req.Id
Models.Classification? classificationToDelete = await libraryDbContext
.Classifications
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (classificationToDelete == null)
{
Console.WriteLine($"Aucune classification avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
libraryDbContext.Classifications.Remove(classificationToDelete); //Supprime la classification dans la bdd
await libraryDbContext.SaveChangesAsync(ct); //Sauvegarde de la classification dans la bdd
libraryDbContext.Classifications.Remove(classificationToDelete);
await libraryDbContext.SaveChangesAsync(ct);
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -8,21 +8,20 @@ public class GetAllClassificationsEndpoint(PyroFetesDbContext pyrofetesdbcontext
{
public override void Configure()
{
Get("/api/classifications"); //Endpoint qui affiche toutes les classifications
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/classifications");
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetClassificationDto> responseDto = await pyrofetesdbcontext.Classifications //Création d'une liste qui récupère toutes les classifications dans la bdd
.Select(a => new GetClassificationDto //Sélectionne dans la liste chaque classification
List<GetClassificationDto> responseDto = await pyrofetesdbcontext.Classifications
.Select(a => new GetClassificationDto
{
Id = a.Id, //Récupère l'id
Label = a.Label, //Récupère le label
Id = a.Id,
Label = a.Label,
}
).ToListAsync(ct); //Retourne la liste de classification
).ToListAsync(ct);
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -13,30 +13,29 @@ public class GetClassificationEndpoint(PyroFetesDbContext pyrofetesdbcontext) :E
{
public override void Configure()
{
Get("/api/classifications/{@id}", x => new { x.Id }); //endpoint qui affiche la classification en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/classifications/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetClassificationRequest req, CancellationToken ct)
{
Models.Classification? classification = await pyrofetesdbcontext //Récupère la table marque dans la bdd
Models.Classification? classification = await pyrofetesdbcontext
.Classifications
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct); //récupère l'id
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (classification == null)
{
Console.WriteLine($"Aucune classification avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
GetClassificationDto responseDto = new()
{
Id = req.Id, //Affiche l'id
Label = classification.Label //Affiche le nom
Id = req.Id,
Label = classification.Label
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -8,27 +8,26 @@ public class UpdateClassificationEndpoint(PyroFetesDbContext pyrofetesdbcontext)
{
public override void Configure()
{
Put("/api/classifications"); //Met à jour la classification en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Put("/classifications");
}
public override async Task HandleAsync(UpdateClassificationDto req, CancellationToken ct)
{
Models.Classification classification = new() //Met à jour la classification
Models.Classification classification = new()
{
Label = req.Label
};
pyrofetesdbcontext.Add(classification); //ajoute la classification dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements
pyrofetesdbcontext.Add(classification);
await pyrofetesdbcontext.SaveChangesAsync(ct);
GetClassificationDto response = new() //renvoie l'id et le nom
GetClassificationDto response = new()
{
Id = req.Id,
Label = req.Label
};
await Send.OkAsync(response, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(response, ct);
}
}

View File

@@ -1,21 +1,19 @@
using API.DTO.Color.Request;
using API.DTO.Color.Response;
using FastEndpoints;
using PyroFetes;
namespace API.Endpoints.Color;
namespace PyroFetes.Endpoints.Color;
public class CreateColorEndpoint(PyroFetesDbContext pyroFetesDbContext) : Endpoint<CreateColorDto, GetColorDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateColorDto et l'élement de réponse GetColorDto
{
public override void Configure() //Configuration de l'endpoint
{
Post("Api/colors"); //Création d'un endpoint pour créer une couleur avec les données de CreateColorDto
AllowAnonymous(); //Laisser passer les requêtes non authentifiées
Post("/colors"); //Création d'un endpoint pour créer une couleur avec les données de CreateColorDto
}
public override async Task HandleAsync(CreateColorDto req, CancellationToken ct) //La méthode HandleAsync est appelée lorsqu'une requête est envoyée à l'endpoint
{
PyroFetes.Models.Color color = new() //Création d'un label rentré par l'utilisateur
PyroFetes.Models.Color color = new()
{
Label = req.Label,
};

View File

@@ -3,35 +3,34 @@ using Microsoft.EntityFrameworkCore;
namespace PyroFetes.Endpoints.Color;
public class DeleteColorRequest //Création d'une classe DeleteColorRequest
public class DeleteColorRequest
{
public int Id { get; set; } //Création d'un Id
public int Id { get; set; }
}
public class DeleteColorEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteColorRequest> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête DeleteColorDto.
public class DeleteColorEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteColorRequest>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Delete("Api/colors/{@id}", x => new { x.Id }); //endpoint qui supprime une couleur grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Delete("/colors/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteColorRequest req, CancellationToken ct) //Méthode asynchrone qui traite la suppression de la couleur
public override async Task HandleAsync(DeleteColorRequest req, CancellationToken ct)
{
Models.Color? colorToDelete = await pyrofetesdbcontext //Récupère une couleur dans la bdd et le stocke dans colorToDelete
.Colors //Recherche la couleur dans la table Colors
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct); //Recherche une couleur dont l'id correspond à req.Id
Models.Color? colorToDelete = await pyrofetesdbcontext
.Colors
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (colorToDelete == null) //Si la couleur n'est pas trouvé
if (colorToDelete == null)
{
Console.WriteLine($"Aucune couleur avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
pyrofetesdbcontext.Colors.Remove(colorToDelete); //Supprime la couleur dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
pyrofetesdbcontext.Colors.Remove(colorToDelete);
await pyrofetesdbcontext.SaveChangesAsync(ct);
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -6,21 +6,20 @@ namespace PyroFetes.Endpoints.Color;
public class GetAllColorsEndpoint(PyroFetesDbContext pyrofetesdbcontext) : EndpointWithoutRequest<List<GetColorDto>>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Get("Api/colors"); //Endpoint qui affiche toutes les couleurs
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Get("/colors");
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetColorDto> responseDto = await pyrofetesdbcontext.Colors //Création d'une liste qui récupère toutes les couleurs dans la bdd
.Select(a => new GetColorDto //Sélectionne dans la liste chaque couleur
List<GetColorDto> responseDto = await pyrofetesdbcontext.Colors
.Select(a => new GetColorDto
{
Id = a.Id, //Récupère l'id
Label = a.Label, //Récupère le label
Id = a.Id,
Label = a.Label,
}
).ToListAsync(ct); //Retourne la liste de couleur
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
).ToListAsync(ct);
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -11,30 +11,30 @@ public class GetColorRequest
public class GetColorEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<GetColorRequest, GetColorDto>
{
public override void Configure()
public override void Configure()
{
Get("Api/colors/{@id}", x => new { x.Id}); //endpoint qui récupère une couleur grâce à son id
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/colors/{@id}", x => new { x.Id});
}
public override async Task HandleAsync(GetColorRequest req, CancellationToken ct) //Méthode asynchrone qui traite la récupération de la couleur
public override async Task HandleAsync(GetColorRequest req, CancellationToken ct)
{
Models.Color? color = await pyrofetesdbcontext //Récupère une couleur dans la bdd et le stocke dans color
.Colors //Recherche la couleur dans la table Colors
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct); //Recherche une couleur dont l'id correspond à req.Id
Models.Color? color = await pyrofetesdbcontext
.Colors
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);
if (color == null) //Si la couleur n'est pas trouvé
if (color == null)
{
Console.WriteLine("Aucune couleur avec l'ID {req.Id} trouvé."); //Affiche aucune couleur avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine("Aucune couleur avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
GetColorDto responseDto = new() //Constuire l'objet de réponse pour retourner les informations à l'utilisateur
GetColorDto responseDto = new()
{
Id = color.Id, //Affiche l'id lors de la réponse
Label = color.Label, //Affiche le label lors de la réponse
Id = color.Id,
Label = color.Label,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -7,34 +7,33 @@ namespace PyroFetes.Endpoints.Color;
public class UpdateColorEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<UpdateColorDto, GetColorDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Put("Api/colors/{@id}", x => new { x.Id }); //Création d'un endpoint qui modifie la couleur grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Put("/colors/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(UpdateColorDto req, CancellationToken ct)
{
Models.Color? colorToEdit = await pyrofetesdbcontext //Récupère une couleur dans la bdd et le stocke dans colorToEdit
.Colors //Recherche la couleur dans la table Colors
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct); //Recherche une couleur dont l'id correspond à req.Id
Models.Color? colorToEdit = await pyrofetesdbcontext
.Colors
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);
if (colorToEdit == null) //Si la couleur n'est pas trouvé
if (colorToEdit == null)
{
Console.WriteLine("Aucune couleur avec l'id {req.Id} trouvé."); //Afficher aucune couleur avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine("Aucune couleur avec l'id {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
colorToEdit.Label = req.Label; //Modification du label
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
colorToEdit.Label = req.Label;
await pyrofetesdbcontext.SaveChangesAsync(ct);
GetColorDto responseDto = new() //Constuire l'objet de réponse pour retourner l'id et le label de la nouvelle couleur
GetColorDto responseDto = new()
{
Id = req.Id, //Affiche l'id
Label = req.Label, //Affiche le label
Id = req.Id,
Label = req.Label,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}

View File

@@ -4,31 +4,30 @@ using FastEndpoints;
namespace PyroFetes.Endpoints.Effect;
public class CreateEffectEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateEffectDto, GetEffectDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateEffectDto et l'élement de réponse GetEffectDto
public class CreateEffectEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateEffectDto, GetEffectDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("Api/effects"); //Créer un effet
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/effects");
}
public override async Task HandleAsync(CreateEffectDto req, CancellationToken ct)
{
Models.Effect effect = new() //Création d'un label rentré par l'utilisateur
Models.Effect effect = new()
{
Label = req.Label,
};
pyrofetesdbcontext.Effects.Add(effect); //Ajoute effect à la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
Console.WriteLine("Effect added"); //Affiche Effect added si réussi
pyrofetesdbcontext.Effects.Add(effect);
await pyrofetesdbcontext.SaveChangesAsync(ct);
Console.WriteLine("Effect added");
GetEffectDto responseDto = new() //Constuire l'objet de réponse pour retourner id et label à l'utilisateur
GetEffectDto responseDto = new()
{
Id = effect.Id, //Affiche l'id lors de la réponse
Label = req.Label, //Affiche le label lors de la réponse
Id = effect.Id,
Label = req.Label,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -9,28 +9,27 @@ public class DeleteEffectRequest
}
public class DeleteEffectEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteEffectRequest>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Delete("Api/effects/{@id}", x => new { x.Id }); //Création d'un endpoint qui supprime un effet grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Delete("/effects/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteEffectRequest req, CancellationToken ct) //Méthode asynchrone qui traite la suppression de l'effet
public override async Task HandleAsync(DeleteEffectRequest req, CancellationToken ct)
{
Models.Effect? effectToDelete = await pyrofetesdbcontext //Récupère un effet dans la bdd et le stocke dans effectToDelete
.Effects //Recherche la couleur dans la table Colors
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct); //Recherche un effet dont l'id correspond à req.Id
Models.Effect? effectToDelete = await pyrofetesdbcontext
.Effects
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (effectToDelete == null) //Si l'effet n'est pas trouvé
if (effectToDelete == null)
{
Console.WriteLine($"Aucun effet avec l'ID {req.Id} trouvé."); //Afficher aucun effet avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine($"Aucun effet avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
pyrofetesdbcontext.Effects.Remove(effectToDelete); //Supprime l'effet dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
pyrofetesdbcontext.Effects.Remove(effectToDelete);
await pyrofetesdbcontext.SaveChangesAsync(ct);
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -6,22 +6,21 @@ namespace PyroFetes.Endpoints.Effect;
public class GetAllEffectsEndpoint(PyroFetesDbContext pyrofetesdbcontext) : EndpointWithoutRequest<List<GetEffectDto>>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Get("Api/effects"); //Création d'un endpoint pour récupérer tous les effets grâce à la liste
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Get("/effects");
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetEffectDto> responseDto = await pyrofetesdbcontext.Effects //Création d'une liste qui récupère tous les effets de la bdd
.Select(a => new GetEffectDto //Sélectionne dans la liste chaque effet
List<GetEffectDto> responseDto = await pyrofetesdbcontext.Effects
.Select(a => new GetEffectDto
{
Id = a.Id, //Récupère l'id
Label = a.Label, //Récupère le label
Id = a.Id,
Label = a.Label,
}
).ToListAsync(ct); //Retourne la liste de effet
).ToListAsync(ct);
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -11,31 +11,30 @@ public class GetEffectRequest
public class GetEffectEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<GetEffectRequest, GetEffectDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Get("Api/effects/{@id}", x => new { x.Id }); //Création d'un endpoint qui récupère un effet grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Get("/effects/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetEffectRequest req, CancellationToken ct) //Méthode asynchrone qui traite la récupération de l'effet
public override async Task HandleAsync(GetEffectRequest req, CancellationToken ct)
{
Models.Effect? effect = await pyrofetesdbcontext //Récupère un effet dans la bdd et le stocke dans effect
.Effects //Recherche l'effet dans la table Effects
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct); //Recherche un effet dont l'id correspond à req.Id
Models.Effect? effect = await pyrofetesdbcontext
.Effects
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);
if (effect == null) //Si l'effet n'est pas trouvé
if (effect == null)
{
Console.WriteLine("Aucun effet avec l'ID {req.Id} trouvé."); //Afficher aucun effet avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine("Aucun effet avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
GetEffectDto responseDto = new() //Constuire l'objet de réponse pour retourner id et label à l'utilisateur
GetEffectDto responseDto = new()
{
Id = effect.Id, //Affiche l'id lors de la réponse
Label = effect.Label, //Affiche le label lors de la réponse
Id = effect.Id,
Label = effect.Label,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -7,32 +7,34 @@ namespace PyroFetes.Endpoints.Effect;
public class UpdateEffectEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<UpdateEffectDto, GetEffectDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Put("Api/effects/{@id}", x => new { x.Id }); //Création d'un endpoint qui modifie un effet grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
}
Put("/effects/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(UpdateEffectDto req, CancellationToken ct)
{
Models.Effect? effectToEdit = await pyrofetesdbcontext //Récupère un effet dans la bdd et le stocke dans effectToEdit
.Effects //Recherche l'effet dans la table Effects
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct); //Recherche un effet dont l'id correspond à req.Id
Models.Effect? effectToEdit = await pyrofetesdbcontext
.Effects
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);
if (effectToEdit == null) //Si l'effet n'est pas trouvé
if (effectToEdit == null)
{
Console.WriteLine($"Aucun effet avec l'id {req.Id} trouvé."); //Afficher qu'aucun effet avec l'id ... n'a été trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine("Aucun effet avec l'id {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
effectToEdit.Label = req.Label; //Modification du label de l'effet
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la base de données
effectToEdit.Label = req.Label;
await pyrofetesdbcontext.SaveChangesAsync(ct);
GetEffectDto responseDto = new() //Construire l'objet de réponse pour retourner l'id et le label de l'effet modifié
GetEffectDto responseDto = new()
{
Id = req.Id, //Inclut l'id dans la réponse
Label = req.Label, //Inclut le label dans la réponse
Id = req.Id,
Label = req.Label,
};
await Send.OkAsync(responseDto, ct); //Envoie une réponse 200 OK avec l'objet de réponse
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -1,44 +1,53 @@
using PyroFetes.DTO.Login.Request;
using PyroFetes.DTO.Login.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using PasswordGenerator;
using PyroFetes.DTO.Login.Request;
using PyroFetes.DTO.Login.Response;
namespace PyroFetes.Endpoints.Login;
using FastEndpoints;
public class CreateLoginEndpoint(PyroFetesDbContext database) : Endpoint<CreateLoginDto, GetLoginDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateLoginDto et l'élement de réponse GetLoginDto
public class CreateLoginEndpoint(PyroFetesDbContext database) : Endpoint<CreateLoginDto, GetLoginDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/logins"); //Créer un login
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/logins");
//Roles("Admin");
AllowAnonymous();
}
public override async Task HandleAsync(CreateLoginDto req, CancellationToken ct)
{
bool exists = await database.Users.AnyAsync(x => x.Name == req.Name, ct);
if (exists)
{
AddError("Ce nom d'utilisateur est déjà utilisé.");
await Send.ErrorsAsync(400, ct);
return;
}
string? salt = new Password().IncludeLowercase().IncludeUppercase().IncludeNumeric().LengthRequired(24).Next();
var login = new Models.Login() //Création d'un nom, prénom, mot de passe et un salt rentré par l'utilisateur
Models.User login = new Models.User()
{
Username = req.Username,
FullName = req.FullName,
Name = req.Name,
Email = req.Email,
Password = BCrypt.Net.BCrypt.HashPassword(req.Password + salt),
Salt = salt
Salt = salt,
Fonction = string.IsNullOrEmpty(req.Fonction) ? "User" : req.Fonction
};
database.Logins.Add(login); //Ajout du login à la bdd
database.Users.Add(login);
await database.SaveChangesAsync(ct);
await database.SaveChangesAsync(ct); //Sauvegarde du login dans la bdd
// Pour renvoyer une erreur : Send.StringAsync("Le message d'erreur", 400);
GetLoginDto responseDto = new() //renvoie l'id, nom, prénom, mot de passe et un salt
GetLoginDto responseDto = new()
{
Id = login.Id,
Username = login.Username,
FullName = login.FullName,
Password = login.Password,
Salt = login.Salt
Name = login.Name,
Email = login.Email,
Fonction = login.Fonction
};
await Send.OkAsync(responseDto, ct); //Réponse au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -1,5 +1,3 @@
using PyroFetes.DTO.Login.Request;
using PyroFetes.DTO.Login.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
@@ -14,12 +12,13 @@ public class DeleteLoginEndpoint(PyroFetesDbContext database) : Endpoint<DeleteL
{
public override void Configure()
{
Delete("/api/logins/{@Id}", x => new {x.Id});
Delete("/logins/{@Id}", x => new {x.Id});
AllowAnonymous();
}
public override async Task HandleAsync(DeleteLoginRequest req, CancellationToken ct)
{
var login = await database.Logins.SingleOrDefaultAsync(x => x.Id == req.Id, ct);
Models.User? login = await database.Users.SingleOrDefaultAsync(x => x.Id == req.Id, ct);
if (login == null)
{
@@ -27,7 +26,7 @@ public class DeleteLoginEndpoint(PyroFetesDbContext database) : Endpoint<DeleteL
return;
}
database.Logins.Remove(login);
database.Users.Remove(login);
await database.SaveChangesAsync(ct);
await Send.NoContentAsync(ct);

View File

@@ -1,7 +1,6 @@
using PyroFetes.DTO.Login.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using PyroFetes;
using PyroFetes.DTO.Login.Response;
namespace PyroFetes.Endpoints.Login;
@@ -9,19 +8,19 @@ public class GetAllLoginEndpoint(PyroFetesDbContext database) : EndpointWithoutR
{
public override void Configure()
{
Get("/api/logins");
Get("/logins");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
var logins = await database.Logins
List<GetLoginDto> logins = await database.Users
.Select(login => new GetLoginDto()
{
Id = login.Id,
Username = login.Username,
FullName = login.FullName,
Name = login.Name,
Password = login.Password,
Salt = login.Salt
Fonction = login.Fonction
})
.ToListAsync(ct);

View File

@@ -1,6 +1,6 @@
using PyroFetes.DTO.Login.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using PyroFetes.DTO.Login.Response;
namespace PyroFetes.Endpoints.Login;
@@ -13,12 +13,13 @@ public class GetLoginEndpoint(PyroFetesDbContext database) : Endpoint<GetLoginRe
{
public override void Configure()
{
Get("/api/logins/{@Id}", x => new {x.Id});
Get("/logins/{@Id}", x => new {x.Id});
AllowAnonymous();
}
public override async Task HandleAsync(GetLoginRequest req, CancellationToken ct)
{
var login = await database.Logins
Models.User? login = await database.Users
.SingleOrDefaultAsync(x => x.Id == req.Id, ct);
if (login == null)
@@ -30,10 +31,8 @@ public class GetLoginEndpoint(PyroFetesDbContext database) : Endpoint<GetLoginRe
GetLoginDto responseDto = new()
{
Id = login.Id,
Username = login.Username,
FullName = login.FullName,
Password = login.Password,
Salt = login.Salt
Name = login.Name,
Fonction = login.Fonction
};
await Send.OkAsync(responseDto, ct);

View File

@@ -1,8 +1,8 @@
using PyroFetes.DTO.Login.Request;
using PyroFetes.DTO.Login.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using PasswordGenerator;
using PyroFetes.DTO.Login.Request;
using PyroFetes.DTO.Login.Response;
namespace PyroFetes.Endpoints.Login;
@@ -10,12 +10,13 @@ public class UpdateLoginEndpoint(PyroFetesDbContext database) : Endpoint<UpdateL
{
public override void Configure()
{
Put("/api/logins/{@Id}", x => new {x.Id});
Put("/logins/{@Id}", x => new {x.Id});
AllowAnonymous();
}
public override async Task HandleAsync(UpdateLoginDto req, CancellationToken ct)
{
var login = await database.Logins.SingleOrDefaultAsync(x => x.Id == req.Id, ct);
Models.User? login = await database.Users.SingleOrDefaultAsync(x => x.Id == req.Id, ct);
if (login == null)
{
@@ -25,8 +26,7 @@ public class UpdateLoginEndpoint(PyroFetesDbContext database) : Endpoint<UpdateL
string? salt = new Password().IncludeLowercase().IncludeUppercase().IncludeNumeric().LengthRequired(24).Next();
login.Username = req.Username;
login.FullName = req.FullName;
login.Name = req.Name;
login.Password = BCrypt.Net.BCrypt.HashPassword(req.Password + salt);
login.Salt = salt;
await database.SaveChangesAsync(ct);
@@ -34,10 +34,8 @@ public class UpdateLoginEndpoint(PyroFetesDbContext database) : Endpoint<UpdateL
GetLoginDto responseDto = new()
{
Id = login.Id,
Username = login.Username,
FullName = login.FullName,
Password = login.Password,
Salt = login.Salt
Name = login.Name,
Fonction = login.Fonction
};
await Send.OkAsync(responseDto, ct);

View File

@@ -1,9 +1,8 @@
using PyroFetes.DTO.Login.Request;
using FastEndpoints.Security;
using PyroFetes.DTO.Login.Response;
using FastEndpoints;
using FastEndpoints.Security;
using Microsoft.EntityFrameworkCore;
using PyroFetes;
using PyroFetes.DTO.Login.Request;
using PyroFetes.DTO.Login.Response;
namespace PyroFetes.Endpoints.Login;
@@ -11,13 +10,13 @@ public class UserLoginEndpoint(PyroFetesDbContext database) : Endpoint<ConnectLo
{
public override void Configure()
{
Post("/api/login");
Post("/login");
AllowAnonymous();
}
public override async Task HandleAsync(ConnectLoginDto req, CancellationToken ct)
{
var login = await database.Logins.SingleOrDefaultAsync(x => x.Username == req.Username, ct);
Models.User? login = await database.Users.SingleOrDefaultAsync(x => x.Name == req.Name, ct);
if (login == null)
{
@@ -27,14 +26,13 @@ public class UserLoginEndpoint(PyroFetesDbContext database) : Endpoint<ConnectLo
if (BCrypt.Net.BCrypt.Verify(req.Password + login.Salt, login.Password))
{
var jwtToken = JwtBearer.CreateToken(
string jwtToken = JwtBearer.CreateToken(
o =>
{
o.SigningKey = "ThisIsASuperSecretJwtKeyThatIsAtLeast32CharsLong";
o.ExpireAt = DateTime.UtcNow.AddMinutes(15);
if (login.Role != null) o.User.Roles.Add(login.Role);
o.User.Claims.Add(("Username", login.Username)!);
o.User.Claims.Add(("FullName", login.FullName)!);
if (login.Fonction != null) o.User.Roles.Add(login.Fonction);
o.User.Claims.Add(("Username", login.Name)!);
o.User["UserId"] = "001";
});

View File

@@ -4,34 +4,33 @@ using FastEndpoints;
namespace PyroFetes.Endpoints.Material;
public class CreateMaterialEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateMaterialDto, GetMaterialDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateMaterialDto et l'élement de réponse GetMaterialDto
public class CreateMaterialEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateMaterialDto, GetMaterialDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("Api/materials"); //Créer un matériel
AllowAnonymous();//Autorise l'accès sans authentification
Post("/materials");
}
public override async Task HandleAsync(CreateMaterialDto req, CancellationToken ct)
{
Models.Material quantity = new() //Création d'un nom, quantité et liaison de l'id de l'entrepôt rentré par l'utilisateur
Models.Material quantity = new()
{
Name = req.Label,
Quantity = req.Quantity,
WarehouseId = req.WarehouseId,
};
pyrofetesdbcontext.Materials.Add(quantity); //Ajoute quantity à la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
Console.WriteLine("Material added"); //Affiche Material Added si réussi
pyrofetesdbcontext.Materials.Add(quantity);
await pyrofetesdbcontext.SaveChangesAsync(ct);
Console.WriteLine("Material added");
GetMaterialDto responseDto = new() //Constuire l'objet de réponse pour retourner name, quantity et warehouseId à l'utilisateur
GetMaterialDto responseDto = new()
{
Id = quantity.Id, //Affiche l'id lors de la réponse
WarehouseId = quantity.WarehouseId, //Affiche le label lors de la réponse
Label = req.Label, //Affiche le label lors de la réponse
Id = quantity.Id,
WarehouseId = quantity.WarehouseId,
Label = req.Label,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -2,34 +2,33 @@ using FastEndpoints;
using Microsoft.EntityFrameworkCore;
namespace PyroFetes.Endpoints.Material;
public class DeleteMaterialRequest //Création d'une classe DeleteMaterialRequest
public class DeleteMaterialRequest
{
public int Id { get; set; } //Création d'un Id
public int Id { get; set; }
}
public class DeleteMaterialEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteMaterialRequest>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Delete("Api/materials/{@id}", x => new { x.Id }); //Création d'un endpoint qui supprime un matériel grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Delete("/materials/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteMaterialRequest req, CancellationToken ct) //Méthode asynchrone qui traite la suppression du matériel
public override async Task HandleAsync(DeleteMaterialRequest req, CancellationToken ct)
{
Models.Material? materialToDelete = await pyrofetesdbcontext //Récupère un matériel dans la bdd et le stocke dans materialToDelete
.Materials //Recherche la couleur dans la table Colors
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct); //Recherche un matériel dont l'id correspond à req.Id
Models.Material? materialToDelete = await pyrofetesdbcontext
.Materials
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (materialToDelete == null) //Si le matériel n'est pas trouvé
if (materialToDelete == null)
{
Console.WriteLine($"Aucun matériel avec l'ID {req.Id} trouvé."); //Afficher aucun matériel avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
}
Console.WriteLine($"Aucun matériel avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
pyrofetesdbcontext.Materials.Remove(materialToDelete); //Supprime le matériel dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
pyrofetesdbcontext.Materials.Remove(materialToDelete);
await pyrofetesdbcontext.SaveChangesAsync(ct);
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -6,23 +6,22 @@ namespace PyroFetes.Endpoints.Material;
public class GetAllMaterialsEndpoint(PyroFetesDbContext pyrofetesdbcontext) : EndpointWithoutRequest<List<GetMaterialDto>>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Get("Api/materials"); //Création d'un endpoint pour récupérer tous les matériaux grâce à la liste
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Get("/materials");
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetMaterialDto> responseDto = await pyrofetesdbcontext.Materials //Création d'une liste qui récupère tous les matériaux de la bdd
.Select(a => new GetMaterialDto //Sélectionne dans la liste chaque matériel
List<GetMaterialDto> responseDto = await pyrofetesdbcontext.Materials
.Select(a => new GetMaterialDto
{
Id = a.Id, //Récupère l'id
Label = a.Name, //Récupère le label
Quantity = a.Quantity, //Récupère la quantité
WarehouseId = a.WarehouseId, //Récupère l'id de l'entrepot
Id = a.Id,
Label = a.Name,
Quantity = a.Quantity,
WarehouseId = a.WarehouseId,
}
).ToListAsync(ct); //Retourne la liste du matériel
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
).ToListAsync(ct);
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -11,32 +11,31 @@ public class GetMaterialRequest
public class GetMaterialEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<GetMaterialRequest, GetMaterialDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Get("Api/materials/{@id}", x => new { x.Id }); //Création d'un endpoint qui récupère un matériel grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Get("/materials/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetMaterialRequest req, CancellationToken ct) //Méthode asynchrone qui traite la récupération du matériel
public override async Task HandleAsync(GetMaterialRequest req, CancellationToken ct)
{
Models.Material? material = await pyrofetesdbcontext //Récupère un matériel dans la bdd et le stocke dans material
.Materials //Recherche le matériel dans la table Materials
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct); //Recherche un matériel dont l'id correspond à req.Id
Models.Material? material = await pyrofetesdbcontext
.Materials
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);
if (material == null) //Si le matériel n'est pas trouvé
if (material == null)
{
Console.WriteLine("Aucun matériel avec l'ID {req.Id} trouvé."); //Afficher aucun matériel avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine("Aucun matériel avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
GetMaterialDto responseDto = new() //Constuire l'objet de réponse pour retourner id, label et warehouseId à l'utilisateur
GetMaterialDto responseDto = new()
{
Id = material.Id, //Affiche l'id lors de la réponse
Label = material.Name, //Affiche le label lors de la réponse
WarehouseId = material.WarehouseId, //Affiche warehouseId lors de la réponse
Id = material.Id,
Label = material.Name,
WarehouseId = material.WarehouseId,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -7,36 +7,35 @@ namespace PyroFetes.Endpoints.Material;
public class UpdateMaterialEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<UpdateMaterialDto, GetMaterialDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Put("Api/materials/{@id}", x => new { x.Id }); //Création d'un endpoint qui modifie le matériel grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Put("/materials/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(UpdateMaterialDto req, CancellationToken ct)
{
Models.Material? materialToEdit = await pyrofetesdbcontext //Récupère un matériel dans la bdd et le stocke dans materialToEdit
.Materials //Recherche le matériel dans la table Materials
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);//Recherche un matériel dont l'id correspond à req.Id
Models.Material? materialToEdit = await pyrofetesdbcontext
.Materials
.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);
if (materialToEdit == null) //Si le matériel n'est pas trouvé
if (materialToEdit == null)
{
Console.WriteLine("Aucun matériel avec l'id {req.Id} trouvé."); //Afficher aucun matériel avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine("Aucun matériel avec l'id {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
materialToEdit.Name = req.Label; //Modification du label
materialToEdit.WarehouseId = req.WarehouseId; //Modification de warehouseId
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
materialToEdit.Name = req.Label;
materialToEdit.WarehouseId = req.WarehouseId;
await pyrofetesdbcontext.SaveChangesAsync(ct);
GetMaterialDto responseDto = new() //Constuire l'objet de réponse pour retourner l'id, le label et warehouseId du nouveau matériel
GetMaterialDto responseDto = new()
{
Id = req.Id, //Affiche l'id
Label = req.Label, //Affiche le label
WarehouseId = req.WarehouseId, //Affiche warehouseId
Id = req.Id,
Label = req.Label,
WarehouseId = req.WarehouseId,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -4,18 +4,17 @@ using FastEndpoints;
namespace PyroFetes.Endpoints.Movement;
public class CreateMovementEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateMovementDto, GetMovementDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateMovementDto et l'élement de réponse GetMovementDto
public class CreateMovementEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateMovementDto, GetMovementDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/movements"); //Créer un mouvement
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/movements");
}
public override async Task HandleAsync(CreateMovementDto req, CancellationToken ct)
{
Models.Movement movement = new () //Création d'une date, d'une date de départ, d'arrivée et d'une quantité rentré par l'utilisateur
Models.Movement movement = new ()
{
Date = req.Date,
Start = req.Start,
@@ -23,19 +22,19 @@ public class CreateMovementEndpoint(PyroFetesDbContext pyrofetesdbcontext) : End
Quantity = req.Quantity
};
pyrofetesdbcontext.Movements.Add(movement); //Ajoute movement à la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
pyrofetesdbcontext.Movements.Add(movement);
await pyrofetesdbcontext.SaveChangesAsync(ct);
Console.WriteLine("Movement créée avec succès !"); //Affiche Movement créée avec succès ! si réussi
Console.WriteLine("Movement créée avec succès !");
GetMovementDto responseDto = new () //Constuire l'objet de réponse pour retourner les informations à l'utilisateur
GetMovementDto responseDto = new ()
{
Date = req.Date, //Affiche date lors de la réponse
Start = req.Start, //Affiche start lors de la réponse
Arrival = req.Arrival, //Affiche arrival lors de la réponse
Quantity = req.Quantity //Affiche quantity lors de la réponse
Date = req.Date,
Start = req.Start,
Arrival = req.Arrival,
Quantity = req.Quantity
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -3,36 +3,35 @@ using Microsoft.EntityFrameworkCore;
namespace PyroFetes.Endpoints.Movement;
public class DeleteMovementRequest //Création d'une classe DeleteMovementRequest
public class DeleteMovementRequest
{
public int Id { get; set; } //Création d'un Id
public int Id { get; set; }
}
public class DeleteMovementEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteMovementRequest>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Delete("/api/Movements/{@id}", x => new { x.Id }); //Création d'un endpoint qui supprime un mouvement grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Delete("/Movements/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteMovementRequest req, CancellationToken ct) //Méthode asynchrone qui traite la suppression du mouvement
public override async Task HandleAsync(DeleteMovementRequest req, CancellationToken ct)
{
Models.Movement? movementToDelete = await pyrofetesdbcontext //Récupère un mouvement dans la bdd et le stocke dans movementToDelete
.Movements //Recherche le mouvement dans la table Movements
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);//Recherche une mouvement dont l'id correspond à req.Id
Models.Movement? movementToDelete = await pyrofetesdbcontext
.Movements
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (movementToDelete == null) //Si le mouvement n'est pas trouvé
if (movementToDelete == null)
{
Console.WriteLine($"Aucune mouvement avec l'ID {req.Id} trouvé."); //Affiche aucun mouvement avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine($"Aucune mouvement avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
pyrofetesdbcontext.Movements.Remove(movementToDelete); //Supprime le mouvement dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
pyrofetesdbcontext.Movements.Remove(movementToDelete);
await pyrofetesdbcontext.SaveChangesAsync(ct);
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -6,26 +6,25 @@ namespace PyroFetes.Endpoints.Movement;
public class GetAllMovementsEndpoint(PyroFetesDbContext pyrofetesdbcontext) : EndpointWithoutRequest<List<GetMovementDto>>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Get("/api/movements"); //Création d'un endpoint pour récupérer tous les mouvements grâce à la liste
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Get("/movements");
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetMovementDto> responseDto = await pyrofetesdbcontext.Movements //Création d'une liste qui récupère tous les mouvements de la bdd
.Select(a => new GetMovementDto //Sélectionne dans la liste chaque mouvement
List<GetMovementDto> responseDto = await pyrofetesdbcontext.Movements
.Select(a => new GetMovementDto
{
Id = a.Id, //Récupère l'id
Date = a.Date, //Récupère la date
Start = a.Start, //Récupère start
Arrival = a.Arrival, //Récupère arrival
Quantity = a.Quantity //Récupère quantity
Id = a.Id,
Date = a.Date,
Start = a.Start,
Arrival = a.Arrival,
Quantity = a.Quantity
}
).ToListAsync(ct); //Retourne la liste de mouvement
).ToListAsync(ct);
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -11,35 +11,34 @@ public class GetMovementRequest
public class GetMovementEndpoint(PyroFetesDbContext pyrofetesdbcontext) :Endpoint<GetMovementRequest, GetMovementDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Get("/api/movements/{@id}", x => new { x.Id }); //Création d'un endpoint qui récupère un mouvement grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Get("/movements/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetMovementRequest req, CancellationToken ct) //Méthode asynchrone qui traite la récupération du mouvement
public override async Task HandleAsync(GetMovementRequest req, CancellationToken ct)
{
Models.Movement? movement = await pyrofetesdbcontext //Récupère un mouvement dans la bdd et le stocke dans movement
.Movements //Recherche la couleur dans la table Movements
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);//Recherche un mouvement dont l'id correspond à req.Id
Models.Movement? movement = await pyrofetesdbcontext
.Movements
.SingleOrDefaultAsync(a => a.Id == req.Id, cancellationToken: ct);
if (movement == null) //Si le mouvement n'est pas trouvé
if (movement == null)
{
Console.WriteLine($"Aucun mouvement avec l'ID {req.Id} trouvé."); //Affiche aucun mouvement avec l'id ... trouvé
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
Console.WriteLine($"Aucun mouvement avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct);
return;
}
GetMovementDto responseDto = new() //Constuire l'objet de réponse pour retourner les informations à l'utilisateur
GetMovementDto responseDto = new()
{
Id = req.Id, //Affiche l'id lors de la réponse
Date = movement.Date, //Affiche date lors de la réponse
Start = movement.Start, //Affiche start lors de la réponse
Arrival = movement.Arrival, //Affiche arrival lors de la réponse
Quantity = movement.Quantity //Affiche quantity lors de la réponse
Id = req.Id,
Date = movement.Date,
Start = movement.Start,
Arrival = movement.Arrival,
Quantity = movement.Quantity
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -6,26 +6,25 @@ namespace PyroFetes.Endpoints.Movement;
public class UpdateMovementEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<UpdateMovementDto, GetMovementDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Put("/api/movements"); //Création d'un endpoint qui modifie le mouvement grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Put("/movements");
}
public override async Task HandleAsync(UpdateMovementDto req, CancellationToken ct)
{
Models.Movement movement = new()
Models.Movement movement = new()
{
Date = req.Date,
Start = req.Start,
Arrival = req.Arrival,
Quantity = req.Quantity
};
pyrofetesdbcontext.Add(movement); //Modification du mouvement
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
pyrofetesdbcontext.Add(movement);
await pyrofetesdbcontext.SaveChangesAsync(ct);
GetMovementDto response = new() //Constuire l'objet de réponse pour retourner les informations du mouvement
GetMovementDto response = new()
{
Id = req.Id,
Date = req.Date,
@@ -34,7 +33,7 @@ public class UpdateMovementEndpoint(PyroFetesDbContext pyrofetesdbcontext) : End
Quantity = req.Quantity
};
await Send.OkAsync(response, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(response, ct);
}
}

View File

@@ -7,19 +7,18 @@ using PyroFetes.Models;
namespace PyroFetes.Endpoints.Product;
public class CreateProductEndpoint(PyroFetesDbContext db)
: Endpoint<CreateProductDto, GetProductDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateProductDto et l'élement de réponse GetProductDto
: Endpoint<CreateProductDto, GetProductDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/products"); //Créer un produit
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/products");
}
public override async Task HandleAsync(CreateProductDto req, CancellationToken ct)
{
var product = new Models.Product //Création d'un nom, référence, durée, calibre, numéro d'aprovisionnement, poids, nec, image, lien, liaison de la catégorie du produit et de la classification rentré par l'utilisateur
var product = new Models.Product
{
Reference = req.References.ToString(),
Reference = req.Reference,
Name = req.Name!,
Duration = req.Duration,
Caliber = req.Caliber,
@@ -32,8 +31,8 @@ public class CreateProductEndpoint(PyroFetesDbContext db)
ClassificationId = req.ClassificationId
};
db.Products.Add(product); //Ajout du produit à la bdd
await db.SaveChangesAsync(ct); //Sauvegarde du produit dans la bdd
db.Products.Add(product);
await db.SaveChangesAsync(ct);
// Ajout des fournisseurs liés
if (req.Suppliers is not null && req.Suppliers.Any())
@@ -46,9 +45,9 @@ public class CreateProductEndpoint(PyroFetesDbContext db)
SupplierId = s.SupplierId,
SellingPrice = s.SellingPrice
};
db.Prices.Add(price); //Ajout du prix à la bdd
db.Prices.Add(price);
}
await db.SaveChangesAsync(ct); //Sauvegarde du produit dans la bdd
await db.SaveChangesAsync(ct);
}
// Ajout des entrepôts liés
@@ -66,16 +65,16 @@ public class CreateProductEndpoint(PyroFetesDbContext db)
WarehouseId = w.WarehouseId,
Quantity = w.Quantity
};
db.WarehouseProducts.Add(warehouseProduct); //Ajout du produit de l'entrepot à la bdd
db.WarehouseProducts.Add(warehouseProduct);
}
await db.SaveChangesAsync(ct); //Sauvegarde du produit de l'entrepot dans la bdd
await db.SaveChangesAsync(ct);
}
// Construction de la réponse
var response = new GetProductDto
{
Id = product.Id,
Reference = req.References,
Reference = req.Reference,
Name = req.Name,
Duration = req.Duration,
Caliber = req.Caliber,
@@ -100,6 +99,6 @@ public class CreateProductEndpoint(PyroFetesDbContext db)
}).ToList() ?? new()
};
await Send.OkAsync(response, ct); //Réponse au client
await Send.OkAsync(response, ct);
}
}

View File

@@ -6,28 +6,27 @@ namespace PyroFetes.Endpoints.Product;
public class DeleteProductRequest
{
public int Id { get; set; } //Création d'un Id
public int Id { get; set; }
}
public class DeleteProductEndpoint(PyroFetesDbContext db) : Endpoint<DeleteProductRequest>
{
public override void Configure()
{
Delete("/api/products/{@id}", x => new { x.Id }); //endpoint qui supprime un produit grâce à son id
AllowAnonymous(); //Autorise l'accès sans authentification
Delete("/products/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteProductRequest req, CancellationToken ct)
{
// Récupérer le produit
var productToDelete = await db.Products
var productToDelete = await db.Products
.SingleOrDefaultAsync(p => p.Id == req.Id, ct);
if (productToDelete is null)
{
Console.WriteLine($"Aucun produit avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
// Supprimer les liaisons Price
@@ -54,6 +53,6 @@ public class DeleteProductEndpoint(PyroFetesDbContext db) : Endpoint<DeleteProdu
await db.SaveChangesAsync(ct);
Console.WriteLine($"Produit {req.Id}, ses prix et ses entrepôts liés ont été supprimés avec succès.");
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -11,8 +11,7 @@ public class GetAllProductsEndpoint(PyroFetesDbContext db)
{
public override void Configure()
{
Get("/api/products");
AllowAnonymous();
Get("/products");
}
public override async Task HandleAsync(CancellationToken ct)
@@ -20,7 +19,7 @@ public class GetAllProductsEndpoint(PyroFetesDbContext db)
// Inclure toutes les relations nécessaires : Prices + WarehouseProducts + Warehouse
var products = await db.Products
.Include(p => p.Prices)
.Include(p => p.WarehouseProducts)
.Include(p => p.WarehouseProducts)!
.ThenInclude(wp => wp.Warehouse)
.ToListAsync(ct);
@@ -28,7 +27,7 @@ public class GetAllProductsEndpoint(PyroFetesDbContext db)
{
Id = p.Id,
// Le modèle Product contient "Reference" (string) — pas "References" (int)
Reference = int.TryParse(p.Reference, out var refInt) ? refInt : 0,
Reference = p.Reference,
Name = p.Name,
Duration = p.Duration,
Caliber = p.Caliber,

View File

@@ -16,8 +16,7 @@ public class GetProductEndpoint(PyroFetesDbContext db)
{
public override void Configure()
{
Get("/api/products/{@id}", x => new { x.Id });
AllowAnonymous();
Get("/products/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetProductRequest req, CancellationToken ct)
@@ -25,7 +24,7 @@ public class GetProductEndpoint(PyroFetesDbContext db)
// Inclure toutes les relations : Prices + WarehouseProducts + Warehouse
var product = await db.Products
.Include(p => p.Prices)
.Include(p => p.WarehouseProducts)
.Include(p => p.WarehouseProducts)!
.ThenInclude(wp => wp.Warehouse)
.SingleOrDefaultAsync(p => p.Id == req.Id, ct);
@@ -41,7 +40,7 @@ public class GetProductEndpoint(PyroFetesDbContext db)
Id = product.Id,
// Le modèle Product contient "Reference" (string), pas "References" (int)
Reference = int.TryParse(product.Reference, out var refInt) ? refInt : 0,
Reference = product.Reference,
Name = product.Name,
Duration = product.Duration,

View File

@@ -6,36 +6,29 @@ using PyroFetes.Models;
namespace PyroFetes.Endpoints.Product;
// Endpoint permettant de mettre à jour un produit existant
public class UpdateProductEndpoint(PyroFetesDbContext db)
: Endpoint<UpdateProductDto, GetProductDto>
{
public override void Configure()
{
// Route HTTP PUT avec un paramètre d'identifiant dans l'URL
Put("/api/products/{@id}", x => new { x.Id });
Put("/products/{@id}", x => new { x.Id });
// Autorise les requêtes anonymes (sans authentification)
AllowAnonymous();
}
public override async Task HandleAsync(UpdateProductDto req, CancellationToken ct)
{
// Recherche du produit à mettre à jour, en incluant les relations Prices et WarehouseProducts
var product = await db.Products
.Include(p => p.Prices)
.Include(p => p.WarehouseProducts)
.SingleOrDefaultAsync(p => p.Id == req.Id, ct);
// Si le produit n'existe pas, on retourne une réponse 404
if (product is null)
{
await Send.NotFoundAsync(ct);
return;
}
// Mise à jour des propriétés principales du produit
product.Reference = req.References.ToString(); // Converti int → string
product.Reference = req.Reference;
product.Name = req.Name;
product.Duration = req.Duration;
product.Caliber = req.Caliber;
@@ -47,7 +40,6 @@ public class UpdateProductEndpoint(PyroFetesDbContext db)
product.ClassificationId = req.ClassificationId;
product.ProductCategoryId = req.ProductCategoryId;
// Mise à jour des prix fournisseurs associés
db.Prices.RemoveRange(product.Prices);
foreach (var s in req.Suppliers)
{
@@ -59,7 +51,6 @@ public class UpdateProductEndpoint(PyroFetesDbContext db)
});
}
// Mise à jour des entrepôts associés
db.WarehouseProducts.RemoveRange(product.WarehouseProducts);
foreach (var w in req.Warehouses)
{
@@ -73,18 +64,16 @@ public class UpdateProductEndpoint(PyroFetesDbContext db)
await db.SaveChangesAsync(ct);
// Construction de la réponse renvoyée au client
var response = new GetProductDto
{
Id = product.Id,
Reference = req.References, // DTO garde int pour cohérence
Reference = req.Reference,
Name = req.Name,
Duration = req.Duration,
Caliber = req.Caliber,
ApprovalNumber = req.ApprovalNumber,
Weight = req.Weight,
Nec = req.Nec,
// Le prix de vente est pris depuis Prices
SellingPrice = req.Suppliers.FirstOrDefault()?.SellingPrice ?? 0,
Image = req.Image,
Link = req.Link,

View File

@@ -4,34 +4,33 @@ using FastEndpoints;
namespace PyroFetes.Endpoints.ProductCategory;
public class CreateProductCategoryEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateProductCategoryDto, GetProductCategoryDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateProductCategoryDto et l'élement de réponse GetProductCategoryDto
public class CreateProductCategoryEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<CreateProductCategoryDto, GetProductCategoryDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/productcategories"); //Créer une catégorie de produits
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/productcategories");
}
public override async Task HandleAsync(CreateProductCategoryDto req, CancellationToken ct)
{
Models.ProductCategory productCategory = new () //Création d'un label rentré par l'utilisateur
Models.ProductCategory productCategory = new ()
{
Label = req.Label,
};
pyrofetesdbcontext.ProductCategories.Add(productCategory); //Ajout du catégorie de la produit à la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde du catégorie de la produit dans la bdd
pyrofetesdbcontext.ProductCategories.Add(productCategory);
await pyrofetesdbcontext.SaveChangesAsync(ct);
Console.WriteLine("Category créé avec succès !");
GetProductCategoryDto responseDto = new () //renvoie l'id et le label
GetProductCategoryDto responseDto = new ()
{
Id = productCategory.Id,
Label = productCategory.Label
};
await Send.OkAsync(responseDto, ct); //Réponse au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -12,25 +12,24 @@ public class DeleteProductCategoryEndpoint(PyroFetesDbContext pyrofetesdbcontext
{
public override void Configure()
{
Delete("/api/productcategories/{@id}", x => new { x.Id }); //endpoint qui supprime une catégorie de produit grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Delete("/productcategories/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteProductCategoryRequest req, CancellationToken ct)
{
Models.ProductCategory? productCategoryToDelete = await pyrofetesdbcontext //Récupère une catégorie de produit dans la bdd et le stocke dans productCategoryToDelete
.ProductCategories //Recherche la couleur dans la table ProductCategories
.SingleOrDefaultAsync(pc => pc.Id == req.Id, cancellationToken: ct); //Recherche une catégorie de produit dont l'id correspond à req.Id
Models.ProductCategory? productCategoryToDelete = await pyrofetesdbcontext
.ProductCategories
.SingleOrDefaultAsync(pc => pc.Id == req.Id, cancellationToken: ct);
if (productCategoryToDelete == null)
{
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
pyrofetesdbcontext.ProductCategories.Remove(productCategoryToDelete); //Supprime la catégorie de produit dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
pyrofetesdbcontext.ProductCategories.Remove(productCategoryToDelete);
await pyrofetesdbcontext.SaveChangesAsync(ct);
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -1,27 +0,0 @@
using API.DTO.ProductCategory.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
namespace PyroFetes.Endpoints.ProductCategory;
public class GetAllProductCategoriesEndpoint(PyroFetesDbContext pyrofetesdbcontext) : EndpointWithoutRequest<List<GetProductCategoryDto>>
{
public override void Configure()
{
Get("/api/productcategories"); //Endpoint qui affiche toutes les catégories de produits
AllowAnonymous(); //Ignorer les requêtes non authentifiées
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetProductCategoryDto> responseDto = await pyrofetesdbcontext.ProductCategories //Création d'une liste qui récupère toutes les catégories de produits dans la bdd
.Select(pc => new GetProductCategoryDto() //Sélectionne dans la liste chaque catégorie de produits
{
Id = pc.Id, //Récupère l'id
Label = pc.Label //Récupère le label
}
).ToListAsync(ct); //Retourne la liste
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
}
}

View File

@@ -0,0 +1,26 @@
using API.DTO.ProductCategory.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
namespace PyroFetes.Endpoints.ProductCategory;
public class GetAllProductCategoryEndpoint(PyroFetesDbContext pyrofetesdbcontext) : EndpointWithoutRequest<List<GetProductCategoryDto>>
{
public override void Configure()
{
Get("/productcategories");
}
public override async Task HandleAsync(CancellationToken ct)
{
List<GetProductCategoryDto> responseDto = await pyrofetesdbcontext.ProductCategories
.Select(pc => new GetProductCategoryDto()
{
Id = pc.Id,
Label = pc.Label
}
).ToListAsync(ct);
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -14,29 +14,28 @@ public class GetProductCategoryEndpoint(PyroFetesDbContext pyrofetesdbcontext) :
{
public override void Configure()
{
Get("/api/productcategory/{@id}", x => new { x.Id }); //endpoint qui récupère une catégorie de produit grâce à son id
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/productcategory/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetProductCategoryRequest req, CancellationToken ct)
{
Models.ProductCategory? productCategory = await pyrofetesdbcontext //Récupère une catégorie de produits dans la bdd et le stocke dans productCategory
.ProductCategories //Recherche dans la table ProductCategories
.SingleOrDefaultAsync(pc => pc.Id == req.Id, cancellationToken: ct);//Recherche une catégorie de produits dont l'id correspond à req.Id
Models.ProductCategory? productCategory = await pyrofetesdbcontext
.ProductCategories
.SingleOrDefaultAsync(pc => pc.Id == req.Id, cancellationToken: ct);
if (productCategory == null) //Si la catégorie de produit n'est pas trouvé
if (productCategory == null)
{
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
GetProductCategoryDto responseDto = new()
{
Id = productCategory.Id, //Affiche l'id lors de la réponse
Label = productCategory.Label //Affiche le label lors de la réponse
Id = productCategory.Id,
Label = productCategory.Label
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -9,31 +9,30 @@ public class UpdateProductCategoryEndpoint(PyroFetesDbContext pyrofetesdbcontext
{
public override void Configure()
{
Put("/api/productcategory/{@id}", x => new { x.Id }); //endpoint qui modifie la catégorie de produit grâce à son id
AllowAnonymous(); //Ignorer les requêtes non authentifiées
Put("/productcategory/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(UpdateProductCategoryDto req, CancellationToken ct)
{
Models.ProductCategory? productCategoryToEdit = await pyrofetesdbcontext //Récupère une catégorie de produits dans la bdd et le stocke dans productCategoryToEdit
.ProductCategories //Recherche dans la table ProductCategories
.SingleOrDefaultAsync(pc => pc.Id == req.Id, cancellationToken: ct); //Recherche une catégorie de produits dont l'id correspond à req.Id
Models.ProductCategory? productCategoryToEdit = await pyrofetesdbcontext
.ProductCategories
.SingleOrDefaultAsync(pc => pc.Id == req.Id, cancellationToken: ct);
if (productCategoryToEdit == null) //Si la catégorie de produit n'est pas trouvé
if (productCategoryToEdit == null)
{
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
productCategoryToEdit.Label = req.Label; //Modification du label
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements effectués dans la bdd
productCategoryToEdit.Label = req.Label;
await pyrofetesdbcontext.SaveChangesAsync(ct);
GetProductCategoryDto responseDto = new()
{
Id = req.Id, //Affiche l'id
Label = req.Label, //Affiche le label
Id = req.Id,
Label = req.Label,
};
await Send.OkAsync(responseDto, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(responseDto, ct);
}
}

View File

@@ -7,17 +7,16 @@ using PyroFetes.Models;
namespace PyroFetes.Endpoints.Supplier;
public class CreateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext)
: Endpoint<CreateSupplierDto, GetSupplierDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateSupplierDto et l'élement de réponse GetSupplierDto
: Endpoint<CreateSupplierDto, GetSupplierDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/suppliers"); //Créer un fournisseur
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/suppliers");
}
public override async Task HandleAsync(CreateSupplierDto req, CancellationToken ct)
{
var supplier = new Models.Supplier //Création d'un nom, email, numéro de téléphone, adresse, code postal et nom de la ville rentré par l'utilisateur
var supplier = new Models.Supplier
{
Name = req.Name,
Email = req.Email,
@@ -27,8 +26,8 @@ public class CreateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext)
City = req.City
};
pyrofetesdbcontext.Suppliers.Add(supplier); //Ajout du fournisseur à la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde du fournisseur dans la bdd
pyrofetesdbcontext.Suppliers.Add(supplier);
await pyrofetesdbcontext.SaveChangesAsync(ct);
// Ajout des liaisons Price si produits renseignés
if (req.Products is not null && req.Products.Any())
@@ -43,10 +42,10 @@ public class CreateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext)
};
pyrofetesdbcontext.Prices.Add(price);
}
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde du fournisseur dans la bdd
await pyrofetesdbcontext.SaveChangesAsync(ct);
}
var response = new GetSupplierDto //renvoie l'id, d'un nom, d'un email, d'un numéro de téléphone, d'une adresse, d'un code postal et du nom de la ville
var response = new GetSupplierDto
{
Id = supplier.Id,
Name = supplier.Name,
@@ -57,6 +56,6 @@ public class CreateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext)
City = supplier.City
};
await Send.OkAsync(response, ct); //Réponse au client
await Send.OkAsync(response, ct);
}
}

View File

@@ -13,21 +13,20 @@ public class DeleteSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext) : End
{
public override void Configure()
{
Delete("/api/suppliers/{@id}", x => new { x.Id }); //Endpoint qui supprime un fournisseur en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Delete("/suppliers/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(DeleteSupplierRequest req, CancellationToken ct)
{
var supplierToDelete = await pyrofetesdbcontext //Récupère un fournisseur dans la bdd et le stocke dans supplierToDelete
.Suppliers //Recherche un fournisseur dans la table Suppliers
.SingleOrDefaultAsync(s => s.Id == req.Id, ct); //Recherche un fournisseur dont l'id correspond à req.Id
var supplierToDelete = await pyrofetesdbcontext
.Suppliers
.SingleOrDefaultAsync(s => s.Id == req.Id, ct);
if (supplierToDelete is null)
{
Console.WriteLine($"Aucun fournisseur avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
// Supprimer les liaisons Price avant le fournisseur
@@ -46,6 +45,6 @@ public class DeleteSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext) : End
await pyrofetesdbcontext.SaveChangesAsync(ct);
Console.WriteLine($"Fournisseur {req.Id} et ses prix liés supprimés avec succès.");
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -11,8 +11,7 @@ public class GetAllSuppliersEndpoint(PyroFetesDbContext pyrofetesdbcontext)
{
public override void Configure()
{
Get("/api/suppliers"); //endpoint qui affiche le fournisseur en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/suppliers");
}
public override async Task HandleAsync(CancellationToken ct)

View File

@@ -15,8 +15,7 @@ public class GetSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext)
{
public override void Configure()
{
Get("/api/suppliers/{@id}", x => new { x.Id }); //endpoint qui affiche le fournisseur en fonction de l'id
AllowAnonymous(); //Autorise l'accès sans authentification
Get("/suppliers/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(GetSupplierRequest req, CancellationToken ct)
@@ -28,8 +27,8 @@ public class GetSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext)
if (supplier == null)
{
Console.WriteLine($"Aucun fournisseur avec l'ID {req.Id} trouvé.");
await Send.NotFoundAsync(ct); //Renvoie une erreur 404
return; //Arrêt de la méthode
await Send.NotFoundAsync(ct);
return;
}
var responseDto = new GetSupplierDto

View File

@@ -10,8 +10,7 @@ public class UpdateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext) : End
{
public override void Configure()
{
Put("/api/suppliers/{@id}", x => new { x.Id });
AllowAnonymous();
Put("/suppliers/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(UpdateSupplierDto req, CancellationToken ct)
@@ -52,7 +51,7 @@ public class UpdateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext) : End
}
}
await pyrofetesdbcontext.SaveChangesAsync(ct); //Sauvegarde les changements
await pyrofetesdbcontext.SaveChangesAsync(ct);
var response = new GetSupplierDto
{
@@ -65,6 +64,6 @@ public class UpdateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext) : End
City = supplierToEdit.City
};
await Send.OkAsync(response, ct); //Envoie de la réponse réussite 200 au client
await Send.OkAsync(response, ct);
}
}

View File

@@ -6,17 +6,16 @@ using PyroFetes.Models;
namespace PyroFetes.Endpoints.Warehouse;
public class CreateWarehouseEndpoint(PyroFetesDbContext db)
: Endpoint<CreateWarehouseDto, GetWarehouseDto> //Instanciation d'une connexion à la bdd dans un endpoint, utilise l'élément de requête CreateWarehouseDto et l'élement de réponse GetWarehouseDto
: Endpoint<CreateWarehouseDto, GetWarehouseDto>
{
public override void Configure() //Configuration de l'endpoint
public override void Configure()
{
Post("/api/warehouse"); //Créer un entrepot
AllowAnonymous(); //Autorise l'accès sans authentification
Post("/warehouse");
}
public override async Task HandleAsync(CreateWarehouseDto req, CancellationToken ct)
{
var warehouse = new Models.Warehouse //Création d'un nom, d'un poids maximal et minimal, d'une adresse, d'un code postal et du nom de la ville rentré par l'utilisateur
var warehouse = new Models.Warehouse
{
Name = req.Name,
MaxWeight = req.MaxWeight,
@@ -27,8 +26,8 @@ public class CreateWarehouseEndpoint(PyroFetesDbContext db)
City = req.City
};
db.Warehouses.Add(warehouse); //Ajout de l'entrepot à la bdd
await db.SaveChangesAsync(ct); //Sauvegarde de l'entrepot dans la bdd
db.Warehouses.Add(warehouse);
await db.SaveChangesAsync(ct);
// 🔹 Ajout des produits liés à cet entrepôt
if (req.Products is not null && req.Products.Any())
@@ -46,7 +45,7 @@ public class CreateWarehouseEndpoint(PyroFetesDbContext db)
await db.SaveChangesAsync(ct);
}
var response = new GetWarehouseDto //renvoie l'id, d'un nom, d'un poids maximal et minimal, d'une adresse, d'un code postal et du nom de la ville
var response = new GetWarehouseDto
{
Id = warehouse.Id,
Name = warehouse.Name,
@@ -58,6 +57,6 @@ public class CreateWarehouseEndpoint(PyroFetesDbContext db)
City = warehouse.City
};
await Send.OkAsync(response, ct); //Réponse au client
await Send.OkAsync(response, ct);
}
}

View File

@@ -13,8 +13,7 @@ public class DeleteWarehouseEndpoint(PyroFetesDbContext db) : Endpoint<DeleteWar
{
public override void Configure()
{
Delete("/api/warehouse/{id}");
AllowAnonymous();
Delete("/warehouse/{id}");
}
public override async Task HandleAsync(DeleteWarehouseRequest req, CancellationToken ct)
{
@@ -45,6 +44,6 @@ public class DeleteWarehouseEndpoint(PyroFetesDbContext db) : Endpoint<DeleteWar
await db.SaveChangesAsync(ct);
Console.WriteLine($"Entrepôt {warehouseToDelete.Name} (ID {req.Id}) supprimé avec succès.");
await Send.NoContentAsync(ct); //Renvoie une réponse réussite 204
await Send.NoContentAsync(ct);
}
}

View File

@@ -1,5 +1,4 @@
using API.DTO.Warehouse.Response;
using API.DTO.Warehouse.Request;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using PyroFetes.Models;
@@ -11,36 +10,65 @@ public class GetAllWarehouseEndpoint(PyroFetesDbContext db)
{
public override void Configure()
{
Get("/api/warehouses");
AllowAnonymous();
Get("/warehouses");
}
public override async Task HandleAsync(CancellationToken ct)
{
// 🔹 On inclut les relations avec WarehouseProducts et Product
var warehouses = await db.Warehouses
.Include(w => w.WarehouseProducts)
.ThenInclude(wp => wp.Product)
.ToListAsync(ct);
var response = warehouses.Select(w => new GetWarehouseDto
try
{
Id = w.Id,
Name = w.Name,
MaxWeight = w.MaxWeight,
Current = w.Current,
MinWeight = w.MinWeight,
Adress = w.Address,
ZipCode = w.ZipCode,
City = w.City,
Products = w.WarehouseProducts.Select(wp => new WarehouseProductDto
{
ProductId = wp.ProductId,
ProductName = wp.Product?.Name,
Quantity = wp.Quantity
}).ToList()
}).ToList();
// 1. Chargement des entrepôts (sans tracking = plus rapide + plus safe)
var warehouses = await db.Warehouses
.AsNoTracking()
.ToListAsync(ct);
await Send.OkAsync(response, ct);
// 2. Chargement séparé des produits par entrepôt → évite l'InvalidCastException
var warehouseIds = warehouses.Select(w => w.Id).ToList();
var warehouseProducts = await db.WarehouseProducts
.Where(wp => warehouseIds.Contains(wp.WarehouseId))
.Include(wp => wp.Product)
.AsNoTracking()
.ToListAsync(ct);
// 3. Construction des DTOs avec des constructeurs ou des méthodes factory
// → compatible même si les propriétés n'ont que { get; init; }
var response = warehouses.Select(w =>
{
var dto = new GetWarehouseDto();
dto.GetType().GetProperty("Id")?.SetValue(dto, w.Id);
dto.GetType().GetProperty("Name")?.SetValue(dto, w.Name ?? string.Empty);
dto.GetType().GetProperty("MaxWeight")?.SetValue(dto, w.MaxWeight);
dto.GetType().GetProperty("Current")?.SetValue(dto, w.Current);
dto.GetType().GetProperty("MinWeight")?.SetValue(dto, w.MinWeight);
dto.GetType().GetProperty("Adress")?.SetValue(dto, w.Address ?? string.Empty);
dto.GetType().GetProperty("ZipCode")?.SetValue(dto, w.ZipCode);
dto.GetType().GetProperty("City")?.SetValue(dto, w.City ?? string.Empty);
// Products
var productsList = warehouseProducts
.Where(wp => wp.WarehouseId == w.Id)
.Select(wp =>
{
var prodDto = new WarehouseProductDto();
prodDto.GetType().GetProperty("ProductId")?.SetValue(prodDto, wp.ProductId);
prodDto.GetType().GetProperty("ProductName")?.SetValue(prodDto, wp.Product?.Name ?? "Produit inconnu");
prodDto.GetType().GetProperty("Quantity")?.SetValue(prodDto, wp.Quantity);
return prodDto;
})
.ToList();
dto.GetType().GetProperty("Products")?.SetValue(dto, productsList);
return dto;
}).ToList();
await Send.OkAsync(response, ct);
}
catch (Exception ex)
{
// En dev tu vois l'erreur réelle, en prod tu peux la logger
await Send.OkAsync(ct);
}
}
}

View File

@@ -16,15 +16,14 @@ public class GetWarehouseEndpoint(PyroFetesDbContext db)
public override void Configure()
{
// Pas de "@id" ici, juste {id}
Get("/api/warehouses/{Id}");
AllowAnonymous();
Get("/warehouses/{Id}");
}
public override async Task HandleAsync(GetWarehouseRequest req, CancellationToken ct)
{
// 🔹 Inclut les produits associés à cet entrepôt
var warehouse = await db.Warehouses
.Include(w => w.WarehouseProducts)
.Include(w => w.WarehouseProducts)!
.ThenInclude(wp => wp.Product)
.SingleOrDefaultAsync(w => w.Id == req.Id, cancellationToken: ct);

View File

@@ -12,8 +12,7 @@ public class UpdateWarehouseEndpoint(PyroFetesDbContext db)
public override void Configure()
{
// Utilise {id} plutôt que {@id}
Put("/api/warehouses/{Id}");
AllowAnonymous();
Put("/warehouses/{Id}");
}
public override async Task HandleAsync(UpdateWarehouseDto req, CancellationToken ct)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

13
PyroFetes/Models/.idea/.gitignore generated vendored
View File

@@ -1,13 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Rider ignored files
/.idea.Models.iml
/modules.xml
/contentModel.xml
/projectSettingsUpdater.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
</project>

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

View File

@@ -9,7 +9,7 @@ public class DeliveryNote
public int DelivererId { get; set; }
[Required] public DateOnly EstimateDeliveryDate { get; set; }
[Required] public DateOnly ExpeditionDate { get; set; }
[Required] public DateOnly RealDeliveryDate { get; set; }
public DateOnly? RealDeliveryDate { get; set; }
public Deliverer? Deliverer { get; set; }
public List<ProductDelivery>? ProductDeliveries { get; set; }

View File

@@ -1,13 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace PyroFetes.Models;
public class Login
{
[Key] public int Id { get; set; }
[Required, MaxLength(100)] public string? Username { get; set; }
[Required, MaxLength(200)] public string? FullName { get; set; }
[Required, Length(60, 60)] public string? Password { get; set; }
[Required, Length(24, 24)] public string? Salt { get; set; }
[Required, MaxLength(100)] public string? Role { get; set; }
}

View File

@@ -8,8 +8,8 @@ namespace PyroFetes.Models
[Required, MaxLength(20)] public string? Reference { get; set; }
[Required, MaxLength(100)] public string? Name { get; set; }
[Required] public decimal Duration {get; set;}
[Required] public decimal Caliber { get; set; }
[Required] public int ApprovalNumber { get; set; }
[Required] public int Caliber { get; set; }
[Required, MaxLength(100)] public string? ApprovalNumber { get; set; }
[Required] public decimal Weight { get; set; }
[Required] public decimal Nec { get; set; }
[Required] public string? Image { get; set; }

View File

@@ -9,7 +9,7 @@ public class Supplier
[Required, MaxLength(100)] public string? Email { get; set; }
[Required, MaxLength(30)] public string? Phone { get; set; }
[Required, MaxLength(100)] public string? Address { get; set; }
[Required] public int ZipCode { get; set; }
[Required,Length(5,5)] public string? ZipCode { get; set; }
[Required, MaxLength(100)] public string? City { get; set; }
[Required] public int DeliveryDelay { get; set; }

View File

@@ -6,7 +6,7 @@ public class User
{
[Key] public int Id { get; set; }
[Required, MaxLength(100)] public string? Name { get; set; }
[Required, MinLength(12), MaxLength(50)] public string? Password { get; set; }
[Required, MaxLength(60)] public string? Password { get; set; }
[Required, MaxLength(100)] public string? Salt { get; set; }
[Required, MaxLength(100)] public string? Email { get; set; }
[Required, MaxLength(100)] public string? Fonction { get; set; }

View File

@@ -10,7 +10,7 @@ public class Warehouse
[Required] public int Current {get; set;}
[Required] public int MinWeight {get; set;}
[Required, MaxLength(100)] public string? Address { get; set; }
[Required] public int ZipCode { get; set; }
[Required, Length(5,5)] public string? ZipCode { get; set; }
[Required, MaxLength(100)] public string? City { get; set; }
public List<WarehouseProduct>? WarehouseProducts { get; set; }

View File

@@ -1,29 +1,48 @@
using API;
using FastEndpoints;
using FastEndpoints.Swagger;
using PyroFetes;
using FastEndpoints.Security;
using FastEndpoints.Swagger;
using Microsoft.EntityFrameworkCore;
using PyroFetes;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// On ajoute ici FastEndpoints, un framework REPR et Swagger aux services disponibles dans le projet
builder.Services
.AddAuthenticationJwtBearer(s => s.SigningKey = "ThisIsASuperSecretJwtKeyThatIsAtLeast32CharsLong")
.AddAuthorization()
.AddFastEndpoints()
.SwaggerDocument();
.AddAuthentication();
builder.Services.AddAuthorization();
builder.Services.AddCors(options =>
options.AddDefaultPolicy(policyBuilder =>
policyBuilder.WithOrigins("http://localhost:4200")
.WithMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.AllowAnyHeader()
.AllowCredentials()
)
);
builder.Services.AddFastEndpoints().SwaggerDocument(options =>
{
options.ShortSchemaNames = true;
});
// On ajoute ici la configuration de la base de données
builder.Services.AddDbContext<PyroFetesDbContext>();
// On construit l'application en lui donnant vie
WebApplication app = builder.Build();
app.UseAuthentication()
.UseAuthorization()
.UseFastEndpoints()
.UseSwaggerGen();
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseFastEndpoints(options =>
{
options.Endpoints.RoutePrefix = "API";
options.Endpoints.ShortNames = true;
}).UseSwaggerGen();
app.Run();

View File

@@ -22,4 +22,8 @@
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project>

View File

@@ -49,7 +49,6 @@ public class PyroFetesDbContext : DbContext
public DbSet<User> Users { get; set; }
public DbSet<Warehouse> Warehouses { get; set; }
public DbSet<WarehouseProduct> WarehouseProducts { get; set; }
public DbSet<Login> Logins { get; set; }
// Database configuration
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

18
package-lock.json generated Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "PyroFete",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"zone.js": "^0.16.0"
}
},
"node_modules/zone.js": {
"version": "0.16.0",
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.16.0.tgz",
"integrity": "sha512-LqLPpIQANebrlxY6jKcYKdgN5DTXyyHAKnnWWjE5pPfEQ4n7j5zn7mOEEpwNZVKGqx3kKKmvplEmoBrvpgROTA==",
"license": "MIT"
}
}
}

5
package.json Normal file
View File

@@ -0,0 +1,5 @@
{
"dependencies": {
"zone.js": "^0.16.0"
}
}