Added transaction object, crud class and controller for transactions

This commit is contained in:
Maciej Maciejewski 2024-05-05 22:08:27 +02:00
parent c94363b790
commit fc8ac5d51d
8 changed files with 294 additions and 11 deletions

View File

@ -1,7 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server.nHibernate.Products;
using FirmTracker_Server;
using System.Collections.Generic;
using FirmTracker_Server.nHibernate.Products;
using Microsoft.AspNetCore.Mvc;
namespace FirmTracker_Server.Controllers
{
[Route("api/[controller]")]
@ -93,5 +91,37 @@ namespace FirmTracker_Server.Controllers
var products = _productCrud.GetAllProducts();
return Ok(products);
}
[HttpPost("CalculateTotalPrice")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
public IActionResult CalculateTotalPrice([FromBody] ProductOrder[] orders)
{
decimal totalPrice = 0;
decimal discount = 0;
foreach (var order in orders)
{
discount = order.Discount;
var product = _productCrud.GetProduct(order.ProductId);
if (product == null)
{
return BadRequest($"Product with ID {order.ProductId} not found.");
}
totalPrice += product.Price * order.Quantity;
}
// Apply discount
decimal discountAmount = totalPrice * (discount / 100);
totalPrice -= discountAmount;
return Ok(new { TotalPrice = totalPrice });
}
public class ProductOrder
{
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal Discount { get; set; }
}
}
}

View File

@ -0,0 +1,100 @@
using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server.nHibernate.Transactions;
using FirmTracker_Server;
using System.Collections.Generic;
namespace FirmTracker_Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TransactionController : ControllerBase
{
private readonly TransactionCRUD _transactionCRUD;
public TransactionController()
{
_transactionCRUD = new TransactionCRUD();
}
// POST: api/Transaction
/// <summary>
/// Creates a new transaction.
/// </summary>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult CreateTransaction([FromBody] Transaction transaction)
{
try
{
_transactionCRUD.AddTransaction(transaction);
return CreatedAtAction(nameof(GetTransaction), new { id = transaction.Id }, transaction);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// GET: api/Transaction/5
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetTransaction(int id)
{
var transaction = _transactionCRUD.GetTransaction(id);
if (transaction == null)
return NotFound();
return Ok(transaction);
}
// PUT: api/Transaction/5
[HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult UpdateTransaction(int id, [FromBody] Transaction transaction)
{
if (id != transaction.Id)
return BadRequest("Transaction ID mismatch");
try
{
_transactionCRUD.UpdateTransaction(transaction);
return NoContent();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// DELETE: api/Transaction/5
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult DeleteTransaction(int id)
{
try
{
_transactionCRUD.DeleteTransaction(id);
return NoContent();
}
catch (Exception ex)
{
return NotFound(ex.Message);
}
}
// GET: api/Transaction
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult GetAllTransactions()
{
var transactions = _transactionCRUD.GetAllTransactions();
return Ok(transactions);
}
}
}

View File

@ -14,18 +14,15 @@ namespace FirmTracker_Server
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
string appDirectory = Directory.GetCurrentDirectory();
// Combine the application directory with the relative path to the config file
string appDirectory = Directory.GetCurrentDirectory();
string configFilePath = Path.Combine(appDirectory, "appsettings.json");
string connectionString = "";
// Check if the config file exists
if (File.Exists(configFilePath))
{
var config = new ConfigurationBuilder()
.AddJsonFile(configFilePath)
.Build();
var connectionstringsection = config.GetSection("AppSettings:ConnectionString");
connectionString = connectionstringsection.Value;
@ -72,7 +69,6 @@ namespace FirmTracker_Server
Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
}
Console.WriteLine("raz dwa trzy");
app.UseAuthorization();

View File

@ -1,4 +1,5 @@
using FirmTracker_Server.nHibernate;
using FirmTracker_Server.Controllers;
using FirmTracker_Server.nHibernate;
using FirmTracker_Server.nHibernate.Products;
using NHibernate;
@ -26,12 +27,23 @@ namespace FirmTracker_Server
Type = 0,
Availability = 0
};
var transaction1 = new nHibernate.Transactions.Transaction
{
Date = DateTime.Now,
Description = "testowa transakcja",
Discount = 10,
EmployeeId = 1,
PaymentType = "Karta kredytowa",
Products = new List<Product> { product, product2 }
};
try
{
FirmTracker_Server.nHibernate.Products.ProductCRUD crud = new ProductCRUD();
FirmTracker_Server.nHibernate.Transactions.TransactionCRUD transactionCrud = new nHibernate.Transactions.TransactionCRUD();
crud.AddProduct(product);
crud.AddProduct(product2);
transactionCrud.AddTransaction(transaction1);
}
catch(Exception ex)
{

View File

@ -25,7 +25,12 @@ namespace FirmTracker_Server.nHibernate
.Database(MsSqlConfiguration.MsSql2012
.ConnectionString(c => c.Is(connectionString))
.ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Products.ProductMapping>())
.Mappings(m =>
{
m.FluentMappings
.AddFromAssemblyOf<Products.ProductMapping>()
.AddFromAssemblyOf<Transactions.TransactionMapping>();
})
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update
.BuildSessionFactory();
}

View File

@ -0,0 +1,21 @@
using FirmTracker_Server.nHibernate.Products;
using System.Text.Json.Serialization;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class Transaction
{
public virtual int Id { get; set; }
public virtual DateTime Date { get; set; }
public virtual int EmployeeId { get; set; }
public virtual IList<Product> Products { get; set; } = new List<Product>();
public virtual string PaymentType { get; set; }
public virtual int Discount { get; set; }
public virtual string Description { get; set; }
public Transaction()
{
Products = new List<Product>();
}
}
}

View File

@ -0,0 +1,95 @@
using FirmTracker_Server.nHibernate;
using FirmTracker_Server.nHibernate.Products;
using NHibernate;
using System.Collections.Generic;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Http.HttpResults;
using FirmTracker_Server.nHibernate.Transactions;
using NHibernate.Linq;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionCRUD
{
public void AddTransaction(Transaction transaction)
{
using (var session = SessionFactory.OpenSession())
using (var sessionTransaction = session.BeginTransaction())
{
try
{
session.Save(transaction);
sessionTransaction.Commit();
}
catch
{
sessionTransaction.Rollback();
throw;
}
}
}
public Transaction GetTransaction(int transactionId)
{
using (var session = SessionFactory.OpenSession())
{
var transaction = session.Query<Transaction>()
.Fetch(t => t.Products)
.FirstOrDefault(t => t.Id == transactionId);
return transaction;
}
}
public void UpdateTransaction(Transaction transaction)
{
using (var session = SessionFactory.OpenSession())
using (var t = session.BeginTransaction())
{
try
{
session.Update(transaction);
t.Commit();
}
catch
{
t.Rollback();
throw;
}
}
}
public void DeleteTransaction(int transactionId)
{
using (var session = SessionFactory.OpenSession())
using (var t = session.BeginTransaction())
{
try
{
var transaction = session.Get<Product>(transactionId);
if (transaction != null)
{
session.Delete(transaction);
t.Commit();
}
}
catch
{
t.Rollback();
throw;
}
}
}
public IList<Transaction> GetAllTransactions()
{
using (var session = SessionFactory.OpenSession())
{
var transactions = session.Query<Transaction>()
.FetchMany(t => t.Products)
.ToList();
return transactions;
}
}
}
}

View File

@ -0,0 +1,24 @@
using FluentNHibernate.Mapping;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionMapping:ClassMap<Transaction>
{
public TransactionMapping()
{
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);
HasManyToMany(x => x.Products)
.Table("TransactionProducts")
.ParentKeyColumn("TransactionId")
.ChildKeyColumn("ProductId")
.Cascade.All();
}
}
}