zmiany związane z poprawkami transakcji (wymagane tylko ID towaru oraz ilość), poprawki w obliczeniach

This commit is contained in:
Maciej Maciejewski 2024-05-16 00:42:06 +02:00
parent 31f920a048
commit 4e023be7ca
14 changed files with 239 additions and 26 deletions

View File

@ -4,6 +4,7 @@ using System;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using System.Text.Json; using System.Text.Json;
using System.Transactions; using System.Transactions;
using FirmTracker_Server.nHibernate.Products;
namespace FirmTracker_Server.Controllers namespace FirmTracker_Server.Controllers
{ {
@ -12,11 +13,14 @@ namespace FirmTracker_Server.Controllers
public class TransactionController : ControllerBase public class TransactionController : ControllerBase
{ {
private readonly TransactionCRUD _transactionCRUD; private readonly TransactionCRUD _transactionCRUD;
private readonly ProductCRUD _productCRUD;
public TransactionController() public TransactionController()
{ {
_transactionCRUD = new TransactionCRUD(); _transactionCRUD = new TransactionCRUD();
_productCRUD = new ProductCRUD();
} }
// POST: api/Transaction // POST: api/Transaction
/// <summary> /// <summary>
@ -29,7 +33,34 @@ namespace FirmTracker_Server.Controllers
{ {
try try
{ {
// Before adding the transaction, ensure each product is linked properly
foreach (var product in transaction.TransactionProducts)
{
product.TransactionId = transaction.Id; // This might be 0 at this point if transaction isn't saved yet
decimal price = _productCRUD.GetProductPrice(product.ProductID);
int type = _productCRUD.GetProductType(product.ProductID);
if (type == 1)
{
transaction.TotalPrice += ((product.Quantity * price) * ((1 - (transaction.Discount / 100))));
}
else
{
transaction.TotalPrice += (price * ((1 - (transaction.Discount / 100))));
}
}
_transactionCRUD.AddTransaction(transaction); _transactionCRUD.AddTransaction(transaction);
// Now that the transaction is saved, update each product with the correct TransactionId
foreach (var product in transaction.TransactionProducts)
{
product.TransactionId = transaction.Id; // Now transaction.Id is a valid ID after saving
_transactionCRUD.UpdateTransactionProduct(product);
}
// session.Flush(); // Ensure changes are committed if managing session manually
return CreatedAtAction(nameof(GetTransaction), new { id = transaction.Id }, transaction); return CreatedAtAction(nameof(GetTransaction), new { id = transaction.Id }, transaction);
} }
catch (Exception ex) catch (Exception ex)
@ -38,6 +69,7 @@ namespace FirmTracker_Server.Controllers
} }
} }
// GET: api/Transaction/5 // GET: api/Transaction/5
[HttpGet("{id}")] [HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
@ -61,7 +93,21 @@ namespace FirmTracker_Server.Controllers
try try
{ {
// Before adding the transaction, ensure each product is linked properly
foreach (var product in transaction.TransactionProducts)
{
product.TransactionId = transaction.Id; // This might be 0 at this point if transaction isn't saved yet
decimal price = _productCRUD.GetProductPrice(product.ProductID);
transaction.TotalPrice += ((product.Quantity * price) * ((1 - (transaction.Discount / 100))));
}
_transactionCRUD.UpdateTransaction(transaction); _transactionCRUD.UpdateTransaction(transaction);
// Now that the transaction is saved, update each product with the correct TransactionId
foreach (var product in transaction.TransactionProducts)
{
product.TransactionId = transaction.Id; // Now transaction.Id is a valid ID after saving
_transactionCRUD.UpdateTransactionProduct(product);
}
return NoContent(); return NoContent();
} }
catch (Exception ex) catch (Exception ex)

View File

@ -36,6 +36,13 @@ namespace FirmTracker_Server
TestClass test = new TestClass(); TestClass test = new TestClass();
test.AddTestProduct(); test.AddTestProduct();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
policy => policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod());
});
builder.Services.AddControllers(); builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
@ -68,11 +75,14 @@ namespace FirmTracker_Server
{ {
Console.WriteLine("Nie uda³o siê uruchomiæ swaggera"); Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
} }
app.UseHttpsRedirection();
app.UseCors("AllowSpecificOrigin");
app.UseAuthorization(); app.UseAuthorization();
app.MapControllers(); app.MapControllers();
var configuration = new Configuration(); var configuration = new Configuration();

View File

@ -46,8 +46,8 @@ namespace FirmTracker_Server
transactionCrud.AddTransaction(transaction1); transactionCrud.AddTransaction(transaction1);
List<TransactionProduct> testTransactionProducts = new List<TransactionProduct> { List<TransactionProduct> testTransactionProducts = new List<TransactionProduct> {
new TransactionProduct { Product = product, Quantity = 2, UnitPrice = product.Price }, new TransactionProduct { ProductID = 1, Quantity = 2 },
new TransactionProduct { Product = product2, Quantity = 1, UnitPrice = product2.Price } new TransactionProduct { ProductID = 2, Quantity = 1 }
}; };
foreach (var transactionProduct in testTransactionProducts) foreach (var transactionProduct in testTransactionProducts)
{ {

View File

@ -1,6 +1,6 @@
{ {
"AppSettings": { "AppSettings": {
"ConnectionString": "Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;", "ConnectionString": "Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;TrustServerCertificate=True;"
}, },
"profiles": { "profiles": {
"http": { "http": {

View File

@ -4,6 +4,7 @@ using NHibernate;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNetCore.OpenApi; using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Http.HttpResults;
using System.Security.Cryptography.X509Certificates;
namespace FirmTracker_Server.nHibernate.Products namespace FirmTracker_Server.nHibernate.Products
{ {
@ -25,8 +26,33 @@ namespace FirmTracker_Server.nHibernate.Products
throw; throw;
} }
} }
} }
public decimal GetProductPrice(int productId)
{
using (var session = SessionFactory.OpenSession())
{
var product = session.Query<Product>()
.Where(p => p.Id == productId)
.Select(p => p.Price)
.FirstOrDefault();
return product;
}
}
public int GetProductType(int productId)
{
using (var session = SessionFactory.OpenSession())
{
var product = session.Query<Product>()
.Where(p => p.Id == productId)
.Select(p => p.Type)
.FirstOrDefault();
return product;
}
}
public Product GetProduct(int productId) public Product GetProduct(int productId)
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())

View File

@ -30,7 +30,9 @@ namespace FirmTracker_Server.nHibernate
m.FluentMappings m.FluentMappings
.AddFromAssemblyOf<Products.ProductMapping>() .AddFromAssemblyOf<Products.ProductMapping>()
.AddFromAssemblyOf<Transactions.TransactionMapping>() .AddFromAssemblyOf<Transactions.TransactionMapping>()
.AddFromAssemblyOf<Transactions.TransactionProductMapping>(); .AddFromAssemblyOf<Transactions.TransactionProductMapping>()
.AddFromAssemblyOf<Transactions.Transaction2Mapping>()
.AddFromAssemblyOf<Transactions.TransactionWithProductsMapping>();
}) })
.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

@ -14,7 +14,7 @@ namespace FirmTracker_Server.nHibernate.Transactions
public virtual string PaymentType { get; set; } public virtual string PaymentType { get; set; }
public virtual decimal 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 virtual decimal TotalPrice { get; set; }//=> TransactionProducts.Sum(tp => ((tp.Quantity * tp.UnitPrice)* ((1 - (Discount / 100)))));// (1 - (Discount / 100)));
public Transaction() public Transaction()
{ {

View File

@ -0,0 +1,24 @@
using FirmTracker_Server.nHibernate.Products;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class Transaction2
{
public virtual int Id { get; set; }
public virtual DateTime Date { get; set; }
public virtual int EmployeeId { get; set; }
public virtual IList<TransactionWithProducts> TransactionProducts { get; set; } = new List<TransactionWithProducts>();
public virtual string PaymentType { get; set; }
public virtual decimal Discount { get; set; }
public virtual string Description { get; set; }
public virtual decimal TotalPrice { get; set; }//=> TransactionProducts.Sum(tp => ((tp.Quantity * tp.UnitPrice)* ((1 - (Discount / 100)))));// (1 - (Discount / 100)));
public Transaction2()
{
TransactionProducts = new List<TransactionWithProducts>();
}
}
}

View File

@ -0,0 +1,23 @@
using FluentNHibernate.Mapping;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class Transaction2Mapping : ClassMap<Transaction2>
{
public Transaction2Mapping()
{
Table("Transactions");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Date);
Map(x => x.EmployeeId);
Map(x => x.PaymentType);
Map(x => x.Discount);
Map(x => x.Description);
HasMany(x => x.TransactionProducts)
.KeyColumn("TransactionId")
.Cascade.AllDeleteOrphan()
.Inverse(); // Ustawienie Inverse() wskazuje, że to `TransactionProduct` jest właścicielem relacji
}
}
}

View File

@ -4,6 +4,7 @@ using NHibernate.Linq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Transactions;
namespace FirmTracker_Server.nHibernate.Transactions namespace FirmTracker_Server.nHibernate.Transactions
{ {
@ -18,6 +19,7 @@ namespace FirmTracker_Server.nHibernate.Transactions
{ {
foreach (var transactionProduct in transaction.TransactionProducts) foreach (var transactionProduct in transaction.TransactionProducts)
{ {
transactionProduct.TransactionId = transaction.Id; transactionProduct.TransactionId = transaction.Id;
session.Save(transactionProduct); session.Save(transactionProduct);
} }
@ -26,7 +28,8 @@ namespace FirmTracker_Server.nHibernate.Transactions
// Decrease product quantities based on transaction // Decrease product quantities based on transaction
foreach (var transactionProduct in transaction.TransactionProducts) foreach (var transactionProduct in transaction.TransactionProducts)
{ {
var product = session.Get<Product>(transactionProduct.Product.Id);
var product = session.Get<Product>(transactionProduct.ProductID);
if (product.Type != 0) if (product.Type != 0)
{ {
product.Availability -= transactionProduct.Quantity; product.Availability -= transactionProduct.Quantity;
@ -45,32 +48,71 @@ namespace FirmTracker_Server.nHibernate.Transactions
} }
//usage of HQL //usage of HQL
public Transaction GetTransaction(int transactionId) public Transaction2 GetTransaction(int transactionId)
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
{ {
var query = session.CreateQuery(@" var query = session.CreateQuery(@"
SELECT t SELECT t
FROM Transaction t FROM Transaction2 t
LEFT JOIN FETCH t.TransactionProducts tp LEFT JOIN FETCH t.TransactionProducts tp
LEFT JOIN FETCH tp.Product LEFT JOIN FETCH tp.Product
WHERE t.Id = :transactionId WHERE t.Id = :transactionId
"); ");
query.SetParameter("transactionId", transactionId); query.SetParameter("transactionId", transactionId);
var transaction = query.UniqueResult<Transaction>();
var transaction = query.UniqueResult<Transaction2>();
return transaction; return transaction;
} }
} }
public void UpdateTransaction(Transaction transaction) public void UpdateTransaction(Transaction transaction)
{
using (var session = SessionFactory.OpenSession())
using (var sessionTransaction = session.BeginTransaction())
{
try
{
foreach (var transactionProduct in transaction.TransactionProducts)
{
transactionProduct.TransactionId = transaction.Id;
session.Update(transactionProduct);
}
session.Update(transaction);
// Decrease product quantities based on transaction
foreach (var transactionProduct in transaction.TransactionProducts)
{
var product = session.Get<Product>(transactionProduct.ProductID);
if (product.Type != 0)
{
product.Availability -= transactionProduct.Quantity;
session.Update(product);
}
}
sessionTransaction.Commit();
}
catch
{
sessionTransaction.Rollback();
throw;
}
}
}
public void UpdateTransactionProduct(TransactionProduct transactionProduct)
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
using (var t = session.BeginTransaction()) using (var t = session.BeginTransaction())
{ {
try try
{ {
session.Update(transaction); session.Update(transactionProduct);
t.Commit(); t.Commit();
} }
catch catch
@ -112,9 +154,17 @@ namespace FirmTracker_Server.nHibernate.Transactions
var transactionToUpdate = session.Get<Transaction>(transactionId); var transactionToUpdate = session.Get<Transaction>(transactionId);
if (transactionToUpdate != null) if (transactionToUpdate != null)
{ {
transactionProduct.TransactionId = transactionToUpdate.Id; transactionProduct.TransactionId= transactionToUpdate.Id;
session.Save(transactionProduct); session.Save(transactionProduct);
transaction.Commit(); transaction.Commit();
var product = session.Get<Product>(transactionProduct.ProductID);
if (product.Type != 0)
{
product.Availability -= transactionProduct.Quantity;
session.Update(product);
}
} }
else else
{ {
@ -130,13 +180,13 @@ namespace FirmTracker_Server.nHibernate.Transactions
} }
public IList<Transaction> GetAllTransactions() public IList<Transaction2> GetAllTransactions()
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
{ {
var transactions = session.Query<Transaction>() var transactions = session.Query<Transaction2>()
.FetchMany(t => t.TransactionProducts) .FetchMany(t => t.TransactionProducts)
.ThenFetch(tp => tp.Product) .ThenFetch(tp => tp.Product)
.ToList(); .ToList();
return transactions; return transactions;

View File

@ -7,11 +7,8 @@ namespace FirmTracker_Server.nHibernate.Transactions
public class TransactionProduct public class TransactionProduct
{ {
public virtual int Id { get; set; } public virtual int Id { get; set; }
[JsonIgnore] public virtual int TransactionId { get; set; }
[SwaggerIgnore] public virtual int ProductID { get; set; }
public virtual int TransactionId { get; set; }
public virtual Products.Product Product { get; set; }
public virtual int Quantity { get; set; } public virtual int Quantity { get; set; }
public virtual decimal UnitPrice { get; set; }
} }
} }

View File

@ -10,10 +10,10 @@ namespace FirmTracker_Server.nHibernate.Transactions
Id(x => x.Id).GeneratedBy.Identity(); Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.TransactionId).Column("TransactionId").Not.Nullable(); Map(x => x.TransactionId).Column("TransactionId").Not.Nullable();
References(x => x.Product).Column("ProductId").Not.Nullable(); Map(x => x.ProductID).Column("ProductId").Not.Nullable();
Map(x => x.Quantity); Map(x => x.Quantity);
Map(x => x.UnitPrice); //Map(x => x.UnitPrice);
} }
} }
} }

View File

@ -0,0 +1,16 @@
using FirmTracker_Server.nHibernate.Products;
using Newtonsoft.Json;
using NSwag.Annotations;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionWithProducts
{
public virtual int Id { get; set; }
public virtual int TransactionId { get; set; }
public virtual Products.Product Product { get; set; }
public virtual int Quantity { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using FluentNHibernate.Mapping;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionWithProductsMapping : ClassMap<TransactionWithProducts>
{
public TransactionWithProductsMapping()
{
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);
}
}
}