changes to transaction entity and endpoints

This commit is contained in:
Maciej Maciejewski 2024-05-06 21:25:10 +02:00
parent fc8ac5d51d
commit 31f920a048
9 changed files with 152 additions and 33 deletions

View File

@ -1,8 +1,9 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server.nHibernate.Transactions; using FirmTracker_Server.nHibernate.Transactions;
using FirmTracker_Server; using System;
using System.Collections.Generic; using System.Text.Json.Serialization;
using System.Text.Json;
using System.Transactions;
namespace FirmTracker_Server.Controllers namespace FirmTracker_Server.Controllers
{ {
@ -24,7 +25,7 @@ namespace FirmTracker_Server.Controllers
[HttpPost] [HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult CreateTransaction([FromBody] Transaction transaction) public IActionResult CreateTransaction([FromBody] nHibernate.Transactions.Transaction transaction)
{ {
try try
{ {
@ -53,7 +54,7 @@ namespace FirmTracker_Server.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult UpdateTransaction(int id, [FromBody] Transaction transaction) public IActionResult UpdateTransaction(int id, [FromBody] nHibernate.Transactions.Transaction transaction)
{ {
if (id != transaction.Id) if (id != transaction.Id)
return BadRequest("Transaction ID mismatch"); return BadRequest("Transaction ID mismatch");
@ -90,9 +91,22 @@ namespace FirmTracker_Server.Controllers
[HttpGet] [HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetAllTransactions() public IActionResult GetAllTransactions()
{ {
var transactions = _transactionCRUD.GetAllTransactions(); var transactions = _transactionCRUD.GetAllTransactions();
if (transactions == null)
return NotFound();
// Ustawienie opcji serializatora JSON
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve // Obsługa cykli obiektów
};
// var json = JsonSerializer.Serialize(transactions, options);
// Zwrócenie odpowiedzi z JSON
return Ok(transactions); return Ok(transactions);
} }

View File

@ -17,6 +17,7 @@
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.18" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.18" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.12" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.12" />
<PackageReference Include="NHibernate" Version="5.5.1" /> <PackageReference Include="NHibernate" Version="5.5.1" />
<PackageReference Include="NSwag.Annotations" Version="14.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" /> <PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
</ItemGroup> </ItemGroup>

View File

@ -1,6 +1,7 @@
using FirmTracker_Server.Controllers; using FirmTracker_Server.Controllers;
using FirmTracker_Server.nHibernate; using FirmTracker_Server.nHibernate;
using FirmTracker_Server.nHibernate.Products; using FirmTracker_Server.nHibernate.Products;
using FirmTracker_Server.nHibernate.Transactions;
using NHibernate; using NHibernate;
namespace FirmTracker_Server namespace FirmTracker_Server
@ -27,14 +28,13 @@ namespace FirmTracker_Server
Type = 0, Type = 0,
Availability = 0 Availability = 0
}; };
var transaction1 = new nHibernate.Transactions.Transaction var transaction1 = new Transaction
{ {
Date = DateTime.Now, Date = DateTime.Now,
Description = "testowa transakcja", Description = "testowa transakcja",
Discount = 10, Discount = 10,
EmployeeId = 1, EmployeeId = 1,
PaymentType = "Karta kredytowa", PaymentType = "Karta kredytowa",
Products = new List<Product> { product, product2 }
}; };
try try
@ -44,9 +44,22 @@ namespace FirmTracker_Server
crud.AddProduct(product); crud.AddProduct(product);
crud.AddProduct(product2); crud.AddProduct(product2);
transactionCrud.AddTransaction(transaction1); transactionCrud.AddTransaction(transaction1);
List<TransactionProduct> testTransactionProducts = new List<TransactionProduct> {
new TransactionProduct { Product = product, Quantity = 2, UnitPrice = product.Price },
new TransactionProduct { Product = product2, Quantity = 1, UnitPrice = product2.Price }
};
foreach (var transactionProduct in testTransactionProducts)
{
transactionCrud.AddTransactionProductToTransaction(transaction1.Id, transactionProduct);
}
} }
catch(Exception ex) catch(Exception ex)
{ {
Console.WriteLine(ex.ToString());
throw; throw;
} }
} }

View File

@ -29,7 +29,8 @@ namespace FirmTracker_Server.nHibernate
{ {
m.FluentMappings m.FluentMappings
.AddFromAssemblyOf<Products.ProductMapping>() .AddFromAssemblyOf<Products.ProductMapping>()
.AddFromAssemblyOf<Transactions.TransactionMapping>(); .AddFromAssemblyOf<Transactions.TransactionMapping>()
.AddFromAssemblyOf<Transactions.TransactionProductMapping>();
}) })
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update
.BuildSessionFactory(); .BuildSessionFactory();

View File

@ -1,5 +1,7 @@
using FirmTracker_Server.nHibernate.Products; using FirmTracker_Server.nHibernate.Products;
using System.Text.Json.Serialization; using System;
using System.Collections.Generic;
using System.Linq;
namespace FirmTracker_Server.nHibernate.Transactions namespace FirmTracker_Server.nHibernate.Transactions
{ {
@ -8,14 +10,15 @@ namespace FirmTracker_Server.nHibernate.Transactions
public virtual int Id { get; set; } public virtual int Id { get; set; }
public virtual DateTime Date { get; set; } public virtual DateTime Date { get; set; }
public virtual int EmployeeId { get; set; } public virtual int EmployeeId { get; set; }
public virtual IList<Product> Products { get; set; } = new List<Product>(); public virtual IList<TransactionProduct> TransactionProducts { get; set; } = new List<TransactionProduct>();
public virtual string PaymentType { get; set; } public virtual string PaymentType { get; set; }
public virtual int Discount { get; set; } public virtual decimal Discount { get; set; }
public virtual string Description { get; set; } public virtual string Description { get; set; }
public virtual decimal TotalPrice => TransactionProducts.Sum(tp => ((tp.Quantity * tp.UnitPrice)* ((1 - (Discount / 100)))));// (1 - (Discount / 100)));
public Transaction() public Transaction()
{ {
Products = new List<Product>(); TransactionProducts = new List<TransactionProduct>();
} }
} }
} }

View File

@ -1,11 +1,9 @@
using FirmTracker_Server.nHibernate; using FirmTracker_Server.nHibernate.Products;
using FirmTracker_Server.nHibernate.Products;
using NHibernate; using NHibernate;
using System.Collections.Generic;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Http.HttpResults;
using FirmTracker_Server.nHibernate.Transactions;
using NHibernate.Linq; using NHibernate.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FirmTracker_Server.nHibernate.Transactions namespace FirmTracker_Server.nHibernate.Transactions
{ {
@ -18,7 +16,24 @@ namespace FirmTracker_Server.nHibernate.Transactions
{ {
try try
{ {
foreach (var transactionProduct in transaction.TransactionProducts)
{
transactionProduct.TransactionId = transaction.Id;
session.Save(transactionProduct);
}
session.Save(transaction); session.Save(transaction);
// Decrease product quantities based on transaction
foreach (var transactionProduct in transaction.TransactionProducts)
{
var product = session.Get<Product>(transactionProduct.Product.Id);
if (product.Type != 0)
{
product.Availability -= transactionProduct.Quantity;
session.Update(product);
}
}
sessionTransaction.Commit(); sessionTransaction.Commit();
} }
catch catch
@ -29,17 +44,25 @@ namespace FirmTracker_Server.nHibernate.Transactions
} }
} }
//usage of HQL
public Transaction GetTransaction(int transactionId) public Transaction GetTransaction(int transactionId)
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
{ {
var transaction = session.Query<Transaction>() var query = session.CreateQuery(@"
.Fetch(t => t.Products) SELECT t
.FirstOrDefault(t => t.Id == transactionId); FROM Transaction t
LEFT JOIN FETCH t.TransactionProducts tp
LEFT JOIN FETCH tp.Product
WHERE t.Id = :transactionId
");
query.SetParameter("transactionId", transactionId);
var transaction = query.UniqueResult<Transaction>();
return transaction; return transaction;
} }
} }
public void UpdateTransaction(Transaction transaction) public void UpdateTransaction(Transaction transaction)
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
@ -65,7 +88,7 @@ namespace FirmTracker_Server.nHibernate.Transactions
{ {
try try
{ {
var transaction = session.Get<Product>(transactionId); var transaction = session.Get<Transaction>(transactionId);
if (transaction != null) if (transaction != null)
{ {
session.Delete(transaction); session.Delete(transaction);
@ -79,17 +102,46 @@ namespace FirmTracker_Server.nHibernate.Transactions
} }
} }
} }
public void AddTransactionProductToTransaction(int transactionId, TransactionProduct transactionProduct)
{
using (var session = SessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
try
{
var transactionToUpdate = session.Get<Transaction>(transactionId);
if (transactionToUpdate != null)
{
transactionProduct.TransactionId = transactionToUpdate.Id;
session.Save(transactionProduct);
transaction.Commit();
}
else
{
throw new Exception("Transaction not found.");
}
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
}
public IList<Transaction> GetAllTransactions() public IList<Transaction> GetAllTransactions()
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
{ {
var transactions = session.Query<Transaction>() var transactions = session.Query<Transaction>()
.FetchMany(t => t.Products) .FetchMany(t => t.TransactionProducts)
.ThenFetch(tp => tp.Product)
.ToList(); .ToList();
return transactions; return transactions;
} }
} }
}
}
} }

View File

@ -2,7 +2,7 @@
namespace FirmTracker_Server.nHibernate.Transactions namespace FirmTracker_Server.nHibernate.Transactions
{ {
public class TransactionMapping:ClassMap<Transaction> public class TransactionMapping : ClassMap<Transaction>
{ {
public TransactionMapping() public TransactionMapping()
{ {
@ -14,11 +14,10 @@ namespace FirmTracker_Server.nHibernate.Transactions
Map(x => x.Discount); Map(x => x.Discount);
Map(x => x.Description); Map(x => x.Description);
HasManyToMany(x => x.Products) HasMany(x => x.TransactionProducts)
.Table("TransactionProducts") .KeyColumn("TransactionId")
.ParentKeyColumn("TransactionId") .Cascade.AllDeleteOrphan()
.ChildKeyColumn("ProductId") .Inverse(); // Ustawienie Inverse() wskazuje, że to `TransactionProduct` jest właścicielem relacji
.Cascade.All();
} }
} }
} }

View File

@ -0,0 +1,17 @@
using FirmTracker_Server.nHibernate.Products;
using Newtonsoft.Json;
using NSwag.Annotations;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionProduct
{
public virtual int Id { get; set; }
[JsonIgnore]
[SwaggerIgnore]
public virtual int TransactionId { get; set; }
public virtual Products.Product Product { get; set; }
public virtual int Quantity { get; set; }
public virtual decimal UnitPrice { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using FluentNHibernate.Mapping;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionProductMapping : ClassMap<TransactionProduct>
{
public TransactionProductMapping()
{
Table("TransactionProducts");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.TransactionId).Column("TransactionId").Not.Nullable();
References(x => x.Product).Column("ProductId").Not.Nullable();
Map(x => x.Quantity);
Map(x => x.UnitPrice);
}
}
}