diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json
new file mode 100644
index 0000000..677ed3f
--- /dev/null
+++ b/.config/dotnet-tools.json
@@ -0,0 +1,12 @@
+{
+ "version": 1,
+ "isRoot": true,
+ "tools": {
+ "dotnet-ef": {
+ "version": "8.0.4",
+ "commands": [
+ "dotnet-ef"
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/Controllers/ExpenseController.cs b/Controllers/ExpenseController.cs
new file mode 100644
index 0000000..cb6b8e6
--- /dev/null
+++ b/Controllers/ExpenseController.cs
@@ -0,0 +1,98 @@
+using FirmTracker_Server.nHibernate.Expenses;
+using Microsoft.AspNetCore.Mvc;
+namespace FirmTracker_Server.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class ExpensesController : ControllerBase
+ {
+ private readonly ExpenseCRUD _expenseCrud;
+
+ public ExpensesController()
+ {
+ _expenseCrud = new ExpenseCRUD();
+ }
+ // POST: api/Expenses
+ [HttpPost]
+ [ProducesResponseType(201)] // Created
+ [ProducesResponseType(400)] // Bad Request
+ public IActionResult CreateExpense([FromBody] Expense expense) {
+ try
+ {
+ _expenseCrud.AddExpense(expense);
+ return CreatedAtAction("GetExpense", new { id = expense.Id }, expense);
+ }
+ catch (System.Exception ex) {
+ return BadRequest(ex.Message);
+ }
+ }
+
+ // GET: api/Expenses
+ [HttpGet("{id}")]
+ [ProducesResponseType(200)] // Created
+ [ProducesResponseType(400)] // Bad Request
+ public IActionResult GetExpense(int id)
+ {
+ var expense = _expenseCrud.GetExpense(id);
+ if (expense == null)
+ {
+ return NotFound();
+ }
+ return Ok(expense);
+ }
+
+ //PUT: api/Expenses
+ [HttpPut("{id}")]
+ [ProducesResponseType(200)]
+ [ProducesResponseType(200)]
+ public IActionResult UpdateExpense(int id, [FromBody] Expense expense)
+ {
+ if (id != expense.Id)
+ {
+ return BadRequest("Expense ID mismatch");
+ }
+ try
+ {
+ _expenseCrud.UpdateExpense(expense);
+ return NoContent();
+ }
+ catch (System.Exception ex)
+ {
+ return BadRequest(ex.Message);
+ }
+ }
+
+ [HttpDelete("{id}")]
+ [ProducesResponseType(200)]
+ [ProducesResponseType(400)]
+ public IActionResult DeleteExpense(int id)
+ {
+ try
+ {
+ _expenseCrud.DeleteExpense(id);
+ return NoContent();
+ }
+ catch (System.Exception ex)
+ {
+ return NotFound(ex.Message);
+ }
+ }
+
+ [HttpGet]
+ [ProducesResponseType(200)]
+ [ProducesResponseType(400)]
+ public IActionResult GetAllExpenses()
+ {
+ try
+ {
+ var expenses = _expenseCrud.GetAllExpenses();
+ return Ok(expenses);
+ }
+ catch (System.Exception ex)
+ {
+ return BadRequest(ex.Message);
+ }
+ }
+ }
+
+}
diff --git a/Controllers/ProductController.cs b/Controllers/ProductController.cs
index 91056fc..1d5546f 100644
--- a/Controllers/ProductController.cs
+++ b/Controllers/ProductController.cs
@@ -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]")]
@@ -16,7 +14,12 @@ namespace FirmTracker_Server.Controllers
}
// POST: api/Products
+ ///
+ /// Creates a new product.
+ ///
[HttpPost]
+ [ProducesResponseType(200)] // Created
+ [ProducesResponseType(400)] // Bad Request
public IActionResult CreateProduct([FromBody] Product product)
{
try
@@ -32,6 +35,8 @@ namespace FirmTracker_Server.Controllers
// GET: api/Products/5
[HttpGet("{id}")]
+ [ProducesResponseType(200)] // Created
+ [ProducesResponseType(400)] // Bad Request
public IActionResult GetProduct(int id)
{
var product = _productCrud.GetProduct(id);
@@ -42,6 +47,8 @@ namespace FirmTracker_Server.Controllers
// PUT: api/Products/5
[HttpPut("{id}")]
+ [ProducesResponseType(200)] // Created
+ [ProducesResponseType(400)] // Bad Request
public IActionResult UpdateProduct(int id, [FromBody] Product product)
{
if (id != product.Id)
@@ -60,6 +67,8 @@ namespace FirmTracker_Server.Controllers
// DELETE: api/Products/5
[HttpDelete("{id}")]
+ [ProducesResponseType(200)] // Created
+ [ProducesResponseType(400)] // Bad Request
public IActionResult DeleteProduct(int id)
{
try
@@ -75,10 +84,44 @@ namespace FirmTracker_Server.Controllers
// GET: api/Products
[HttpGet]
+ [ProducesResponseType(200)] // Created
+ [ProducesResponseType(400)] // Bad Request
public IActionResult GetAllProducts()
{
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; }
+ }
}
}
\ No newline at end of file
diff --git a/Controllers/TransactionController.cs b/Controllers/TransactionController.cs
new file mode 100644
index 0000000..b4f80d5
--- /dev/null
+++ b/Controllers/TransactionController.cs
@@ -0,0 +1,160 @@
+using Microsoft.AspNetCore.Mvc;
+using FirmTracker_Server.nHibernate.Transactions;
+using System;
+using System.Text.Json.Serialization;
+using System.Text.Json;
+using System.Transactions;
+using FirmTracker_Server.nHibernate.Products;
+
+namespace FirmTracker_Server.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class TransactionController : ControllerBase
+ {
+ private readonly TransactionCRUD _transactionCRUD;
+ private readonly ProductCRUD _productCRUD;
+
+ public TransactionController()
+ {
+ _transactionCRUD = new TransactionCRUD();
+ _productCRUD = new ProductCRUD();
+ }
+
+
+ // POST: api/Transaction
+ ///
+ /// Creates a new transaction.
+ ///
+ [HttpPost]
+ [ProducesResponseType(StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ public IActionResult CreateTransaction([FromBody] nHibernate.Transactions.Transaction transaction)
+ {
+ 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);
+
+ // 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);
+ }
+ 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] nHibernate.Transactions.Transaction transaction)
+ {
+ if (id != transaction.Id)
+ return BadRequest("Transaction ID mismatch");
+
+ 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);
+
+ // 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();
+ }
+ 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)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public IActionResult 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);
+ }
+
+ }
+}
diff --git a/FirmTracker-Server.csproj b/FirmTracker-Server.csproj
index 727e11d..c4a467b 100644
--- a/FirmTracker-Server.csproj
+++ b/FirmTracker-Server.csproj
@@ -5,15 +5,52 @@
enable
enable
FirmTracker_Server
+ 08986e21-848b-485a-a219-03e2dc6041e4
+
+
+
+
+
+
+
+
+
+
+
+ True
+ True
+ Resources.resx
+
+
+
+
+
+ PreserveNewest
+
+
+
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+
+
+
+ PreserveNewest
+
+
+
diff --git a/Program.cs b/Program.cs
index 9986c4b..676b6dd 100644
--- a/Program.cs
+++ b/Program.cs
@@ -4,43 +4,91 @@ using NHibernate.Dialect;
using NHibernate.Driver;
using FirmTracker_Server.Controllers;
using FirmTracker_Server.nHibernate.Products;
+using FirmTracker_Server.nHibernate;
namespace FirmTracker_Server
{
public class Program
{
+
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
+ string appDirectory = Directory.GetCurrentDirectory();
+ string configFilePath = Path.Combine(appDirectory, "appsettings.json");
+ string connectionString = "";
+ if (File.Exists(configFilePath))
+ {
+ var config = new ConfigurationBuilder()
+ .AddJsonFile(configFilePath)
+ .Build();
+
+ var connectionstringsection = config.GetSection("AppSettings:ConnectionString");
+
+ connectionString = connectionstringsection.Value;
+
+ SessionFactory.Init(connectionString);
+ }
+ else
+ {
+ Console.WriteLine($"The configuration file '{configFilePath}' was not found.");
+ }
- // Add services to the container.
TestClass test = new TestClass();
test.AddTestProduct();
+ builder.Services.AddCors(options =>
+ {
+ options.AddPolicy("AllowSpecificOrigin",
+ policy => policy.WithOrigins("http://localhost:3000")
+ .AllowAnyHeader()
+ .AllowAnyMethod());
+ });
builder.Services.AddControllers();
- // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
+
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
+ var configSwagger = new ConfigurationBuilder()
+ .SetBasePath(Directory.GetCurrentDirectory())
+ .AddJsonFile("appsettings.json")
+ .Build();
- // Configure the HTTP request pipeline.
- if (app.Environment.IsDevelopment())
+
+ var port = configSwagger.GetValue("Port", 5075);
+ var port2 = configSwagger.GetValue("Port", 7039);
+ app.Urls.Add($"http://*:{port}");
+ app.Urls.Add($"https://*:{port2}");
+
+ try
{
app.UseSwagger();
- app.UseSwaggerUI();
+ app.UseSwaggerUI(c =>
+ {
+ c.SwaggerEndpoint($"/swagger/v1/swagger.json", "FirmTracker - TEST");
+ c.RoutePrefix = "swagger";
+ });
+ Console.WriteLine("uruchomiono swaggera");
+ app.UseHttpsRedirection();
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
}
-
app.UseHttpsRedirection();
+ app.UseCors("AllowSpecificOrigin");
+
+
app.UseAuthorization();
-
+
app.MapControllers();
var configuration = new Configuration();
-
+
app.Run();
}
}
-}
\ No newline at end of file
+}
diff --git a/Properties/Resources.Designer.cs b/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..9a0ac44
--- /dev/null
+++ b/Properties/Resources.Designer.cs
@@ -0,0 +1,63 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace FirmTracker_Server.Properties {
+ using System;
+
+
+ ///
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ ///
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources() {
+ }
+
+ ///
+ /// Returns the cached ResourceManager instance used by this class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FirmTracker_Server.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/Properties/Resources.resx b/Properties/Resources.resx
new file mode 100644
index 0000000..4fdb1b6
--- /dev/null
+++ b/Properties/Resources.resx
@@ -0,0 +1,101 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 1.3
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json
index ae02a6f..c7b3353 100644
--- a/Properties/launchSettings.json
+++ b/Properties/launchSettings.json
@@ -1,4 +1,34 @@
-{
+{
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Production"
+ },
+ "dotnetRunMessages": true,
+ "applicationUrl": "http://localhost:5045"
+ },
+ "https": {
+ "commandName": "Project",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Production"
+ },
+ "dotnetRunMessages": true,
+ "applicationUrl": "https://localhost:7039;http://localhost:5045"
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Production"
+ }
+ }
+ },
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
@@ -7,35 +37,5 @@
"applicationUrl": "http://localhost:17940",
"sslPort": 44326
}
- },
- "profiles": {
- "http": {
- "commandName": "Project",
- "dotnetRunMessages": true,
- "launchBrowser": true,
- "launchUrl": "swagger",
- "applicationUrl": "http://localhost:5045",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- },
- "https": {
- "commandName": "Project",
- "dotnetRunMessages": true,
- "launchBrowser": true,
- "launchUrl": "swagger",
- "applicationUrl": "https://localhost:7039;http://localhost:5045",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- },
- "IIS Express": {
- "commandName": "IISExpress",
- "launchBrowser": true,
- "launchUrl": "swagger",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- }
}
-}
+}
\ No newline at end of file
diff --git a/TestClass.cs b/TestClass.cs
index e428bcb..537cc03 100644
--- a/TestClass.cs
+++ b/TestClass.cs
@@ -1,5 +1,8 @@
-using FirmTracker_Server.nHibernate;
+using FirmTracker_Server.Controllers;
+using FirmTracker_Server.nHibernate;
using FirmTracker_Server.nHibernate.Products;
+using FirmTracker_Server.nHibernate.Transactions;
+using FirmTracker_Server.nHibernate.Expenses;
using NHibernate;
namespace FirmTracker_Server
@@ -8,24 +11,134 @@ namespace FirmTracker_Server
{
public void AddTestProduct()
{
- SessionFactory.Init("Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;");
+ // SessionFactory.Init(ConnectionString);
var product = new nHibernate.Products.Product
{
- Name = "Test Product2",
- Description = "This is a test product",
- Price = 11.99m,
- Type = 0, // Goods
- Availability = true
+ Name = "Produkt 1",
+ Description = "testowy produkt",
+ Price = 11.50m,
+ Type = 1,
+ Availability = 5
+ };
+ var product2 = new nHibernate.Products.Product
+ {
+ Name = "Usluga 1",
+ Description = "testowa usluga",
+ Price = 1120.00m,
+ Type = 0,
+ Availability = 0
+ };
+ var product3 = new nHibernate.Products.Product
+ {
+ Name = "Produkt 2",
+ Description = "produkt",
+ Price = 16.50m,
+ Type = 1,
+ Availability = 20
+ };
+ var product4 = new nHibernate.Products.Product
+ {
+ Name = "Produkt 3",
+ Description = "produkt",
+ Price = 25.00m,
+ Type = 1,
+ Availability = 10
+ };
+ var product5 = new nHibernate.Products.Product
+ {
+ Name = "Usługa 2",
+ Description = "usługa",
+ Price = 700.00m,
+ Type = 0,
+ Availability = 0
+ };
+ var transaction1 = new Transaction
+ {
+ Date = DateTime.Now.AddDays(-2),
+ Description = "testowa transakcja",
+ Discount = 10,
+ EmployeeId = 1,
+ PaymentType = "Karta kredytowa",
+ };
+ var transaction2 = new Transaction
+ {
+ Date = DateTime.Now.AddDays(-3),
+ Description = "testowa transakcja",
+ Discount = 30,
+ EmployeeId = 2,
+ PaymentType = "Gotówka",
+ };
+ var transaction3 = new Transaction
+ {
+ Date = DateTime.Now,
+ Description = "testowa transakcja",
+ Discount = 15,
+ EmployeeId = 1,
+ PaymentType = "BLIK",
+ };
+
+ var expense1 = new Expense
+ {
+ Date = DateTime.Now,
+ Value = 1003.9m,
+ Description = "testowy rozchód"
};
try
{
- FirmTracker_Server.nHibernate.Products.ProductCRUD crud = new ProductCRUD();
- crud.AddProduct(product);
+ FirmTracker_Server.nHibernate.Products.ProductCRUD productCrud = new ProductCRUD();
+ FirmTracker_Server.nHibernate.Transactions.TransactionCRUD transactionCrud = new nHibernate.Transactions.TransactionCRUD();
+ ExpenseCRUD expenseCrud = new ExpenseCRUD();
+ productCrud.AddProduct(product);
+ productCrud.AddProduct(product2);
+ productCrud.AddProduct(product3);
+ productCrud.AddProduct(product4);
+ productCrud.AddProduct(product5);
+ transactionCrud.AddTransaction(transaction1);
+ transactionCrud.AddTransaction(transaction2);
+ transactionCrud.AddTransaction(transaction3);
+ expenseCrud.AddExpense(expense1);
+
+
+ List testTransactionProducts = new List {
+ new TransactionProduct { ProductID = 1, Quantity = 2 },
+ new TransactionProduct { ProductID = 2, Quantity = 1 },
+ new TransactionProduct { ProductID = 3, Quantity = 10 }
+ };
+ foreach (var transactionProduct in testTransactionProducts)
+ {
+ transactionCrud.AddTransactionProductToTransaction(transaction1.Id, transactionProduct);
+
+ }
+
+ List testTransactionProducts2 = new List
+ {
+ new TransactionProduct { ProductID = 4, Quantity=5},
+ new TransactionProduct { ProductID = 5, Quantity=1}
+ };
+ foreach (var transactionProduct in testTransactionProducts2)
+ {
+ transactionCrud.AddTransactionProductToTransaction(transaction2.Id, transactionProduct);
+
+ }
+
+ List testTransactionProducts3 = new List
+ {
+ new TransactionProduct { ProductID = 3, Quantity=12},
+ new TransactionProduct { ProductID = 2, Quantity=1}
+ };
+ foreach (var transactionProduct in testTransactionProducts3)
+ {
+ transactionCrud.AddTransactionProductToTransaction(transaction3.Id, transactionProduct);
+
+ }
+
+
}
catch(Exception ex)
{
+ Console.WriteLine(ex.ToString());
throw;
}
}
diff --git a/appsettings.json b/appsettings.json
index 10f68b8..61b3a7a 100644
--- a/appsettings.json
+++ b/appsettings.json
@@ -1,9 +1,29 @@
{
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
- }
+ "AppSettings": {
+ "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;"
},
- "AllowedHosts": "*"
-}
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "applicationUrl": "http://localhost:5045"
+
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "applicationUrl": "https://localhost:7039"
+
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "launchUrl": "swagger"
+
+ }
+ }
+}
\ No newline at end of file
diff --git a/nHIbernate/Expenses/Expense.cs b/nHIbernate/Expenses/Expense.cs
new file mode 100644
index 0000000..f99cc0a
--- /dev/null
+++ b/nHIbernate/Expenses/Expense.cs
@@ -0,0 +1,10 @@
+namespace FirmTracker_Server.nHibernate.Expenses
+{
+ public class Expense
+ {
+ public virtual int Id { get; set; }
+ public virtual DateTime Date { get; set; }
+ public virtual decimal Value { get; set; }
+ public virtual string Description { get; set; }
+ }
+}
diff --git a/nHIbernate/Expenses/ExpenseCRUD.cs b/nHIbernate/Expenses/ExpenseCRUD.cs
new file mode 100644
index 0000000..a7ceeab
--- /dev/null
+++ b/nHIbernate/Expenses/ExpenseCRUD.cs
@@ -0,0 +1,107 @@
+using FirmTracker_Server.nHibernate;
+using FirmTracker_Server.nHibernate.Products;
+
+namespace FirmTracker_Server.nHibernate.Expenses
+{
+ public class ExpenseCRUD
+ {
+ public void AddExpense(Expense expense)
+ {
+ using (var session = SessionFactory.OpenSession())
+ using (var transaction = session.BeginTransaction())
+ {
+ try
+ {
+ session.Save(expense);
+ transaction.Commit();
+ }
+ catch
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+ }
+ public Expense GetExpense(int expenseId) {
+ using (var session = SessionFactory.OpenSession())
+ {
+ /*var query = session.CreateQuery(@"
+ SELECT e
+ FROM Expense e
+ WHERE e.Id = expenseId
+ ");
+ query.SetParameter("expenseId", expenseId);
+ var expense = query.UniqueResult();*/
+ return session.Get(expenseId);
+ }
+ }
+ public DateTime GetExpenseDate(int expenseId)
+ {
+ using(var session = SessionFactory.OpenSession())
+ {
+ var expense = session.Query()
+ .Where(e => e.Id == expenseId)
+ .Select(e => e.Date)
+ .FirstOrDefault();
+ return expense;
+ }
+ }
+ public decimal GetExpenseValue(int expenseId)
+ {
+ using (var session = SessionFactory.OpenSession())
+ {
+ var expense = session.Query()
+ .Where(e => e.Id == expenseId)
+ .Select(e => e.Value)
+ .FirstOrDefault();
+ return expense;
+ }
+ }
+
+ public void UpdateExpense(Expense expense)
+ {
+ using (var session = SessionFactory.OpenSession())
+ using (var transaction = session.BeginTransaction())
+ {
+ try
+ {
+ session.Update(expense);
+ transaction.Commit();
+ }
+ catch
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+ }
+
+ public void DeleteExpense(int expenseId)
+ {
+ using (var session = SessionFactory.OpenSession())
+ using (var transaction = session.BeginTransaction())
+ try
+ {
+ var expense = session.Get(expenseId);
+ if (expense != null)
+ {
+ session.Delete(expense);
+ transaction.Commit();
+ }
+
+ }
+ catch {
+ transaction.Rollback();
+ throw;
+ }
+ }
+
+ public IList GetAllExpenses()
+ {
+ using (var session = SessionFactory.OpenSession())
+ {
+ return session.Query().ToList();
+ }
+ }
+ }
+}
diff --git a/nHIbernate/Expenses/ExpenseMapping.cs b/nHIbernate/Expenses/ExpenseMapping.cs
new file mode 100644
index 0000000..ad2468d
--- /dev/null
+++ b/nHIbernate/Expenses/ExpenseMapping.cs
@@ -0,0 +1,17 @@
+using FluentNHibernate.Mapping;
+
+namespace FirmTracker_Server.nHibernate.Expenses
+{
+ public class ExpenseMapping : ClassMap
+ {
+ public ExpenseMapping()
+ {
+ Table("Expenses");
+ Id(x => x.Id).GeneratedBy.Identity();
+ Map(x => x.Date);
+ Map(x => x.Value);
+ Map(x => x.Description);
+
+ }
+ }
+}
diff --git a/nHIbernate/Products/Product.cs b/nHIbernate/Products/Product.cs
index 2faefa4..f0089b4 100644
--- a/nHIbernate/Products/Product.cs
+++ b/nHIbernate/Products/Product.cs
@@ -1,4 +1,6 @@
-namespace FirmTracker_Server.nHibernate.Products
+using System.Text.Json.Serialization;
+
+namespace FirmTracker_Server.nHibernate.Products
{
public class Product
{
@@ -7,6 +9,6 @@
public virtual string Description { get; set; }
public virtual decimal Price { get; set; }
public virtual int Type { get; set; } // 0 for service, 1 for goods
- public virtual bool Availability { get; set; }
+ public virtual int Availability { get; set; }
}
}
diff --git a/nHIbernate/Products/ProductCRUD.cs b/nHIbernate/Products/ProductCRUD.cs
index 5ec3628..ef05fd5 100644
--- a/nHIbernate/Products/ProductCRUD.cs
+++ b/nHIbernate/Products/ProductCRUD.cs
@@ -4,6 +4,7 @@ using NHibernate;
using System.Collections.Generic;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Http.HttpResults;
+using System.Security.Cryptography.X509Certificates;
namespace FirmTracker_Server.nHibernate.Products
{
@@ -25,8 +26,33 @@ namespace FirmTracker_Server.nHibernate.Products
throw;
}
}
+
}
+ public decimal GetProductPrice(int productId)
+ {
+ using (var session = SessionFactory.OpenSession())
+ {
+ var product = session.Query()
+ .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()
+ .Where(p => p.Id == productId)
+ .Select(p => p.Type)
+ .FirstOrDefault();
+
+ return product;
+ }
+ }
public Product GetProduct(int productId)
{
using (var session = SessionFactory.OpenSession())
diff --git a/nHIbernate/SessionFactory.cs b/nHIbernate/SessionFactory.cs
index 9ab3368..6562a29 100644
--- a/nHIbernate/SessionFactory.cs
+++ b/nHIbernate/SessionFactory.cs
@@ -25,7 +25,16 @@ namespace FirmTracker_Server.nHibernate
.Database(MsSqlConfiguration.MsSql2012
.ConnectionString(c => c.Is(connectionString))
.ShowSql())
- .Mappings(m => m.FluentMappings.AddFromAssemblyOf())
+ .Mappings(m =>
+ {
+ m.FluentMappings
+ .AddFromAssemblyOf()
+ .AddFromAssemblyOf()
+ .AddFromAssemblyOf()
+ .AddFromAssemblyOf()
+ .AddFromAssemblyOf()
+ .AddFromAssemblyOf();
+ })
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update
.BuildSessionFactory();
}
diff --git a/nHibernate/Transactions/Transaction.cs b/nHibernate/Transactions/Transaction.cs
new file mode 100644
index 0000000..879c033
--- /dev/null
+++ b/nHibernate/Transactions/Transaction.cs
@@ -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 Transaction
+ {
+ public virtual int Id { get; set; }
+ public virtual DateTime Date { get; set; }
+ public virtual int EmployeeId { get; set; }
+ public virtual IList TransactionProducts { get; set; } = new List();
+ 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 Transaction()
+ {
+ TransactionProducts = new List();
+ }
+ }
+}
diff --git a/nHibernate/Transactions/Transaction2.cs b/nHibernate/Transactions/Transaction2.cs
new file mode 100644
index 0000000..f6ef4a0
--- /dev/null
+++ b/nHibernate/Transactions/Transaction2.cs
@@ -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 TransactionProducts { get; set; } = new List();
+ 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();
+ }
+ }
+}
diff --git a/nHibernate/Transactions/Transaction2Mapping.cs b/nHibernate/Transactions/Transaction2Mapping.cs
new file mode 100644
index 0000000..931456d
--- /dev/null
+++ b/nHibernate/Transactions/Transaction2Mapping.cs
@@ -0,0 +1,23 @@
+using FluentNHibernate.Mapping;
+
+namespace FirmTracker_Server.nHibernate.Transactions
+{
+ public class Transaction2Mapping : ClassMap
+ {
+ 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
+ }
+ }
+}
diff --git a/nHibernate/Transactions/TransactionCRUD.cs b/nHibernate/Transactions/TransactionCRUD.cs
new file mode 100644
index 0000000..c76d904
--- /dev/null
+++ b/nHibernate/Transactions/TransactionCRUD.cs
@@ -0,0 +1,197 @@
+using FirmTracker_Server.nHibernate.Products;
+using NHibernate;
+using NHibernate.Linq;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Transactions;
+
+namespace FirmTracker_Server.nHibernate.Transactions
+{
+ public class TransactionCRUD
+ {
+ public void AddTransaction(Transaction transaction)
+ {
+ using (var session = SessionFactory.OpenSession())
+ using (var sessionTransaction = session.BeginTransaction())
+ {
+ try
+ {
+ foreach (var transactionProduct in transaction.TransactionProducts)
+ {
+
+ transactionProduct.TransactionId = transaction.Id;
+ session.Save(transactionProduct);
+ }
+ session.Save(transaction);
+
+ // Decrease product quantities based on transaction
+ foreach (var transactionProduct in transaction.TransactionProducts)
+ {
+
+ var product = session.Get(transactionProduct.ProductID);
+ if (product.Type != 0)
+ {
+ product.Availability -= transactionProduct.Quantity;
+ session.Update(product);
+ }
+ }
+
+ sessionTransaction.Commit();
+ }
+ catch
+ {
+ sessionTransaction.Rollback();
+ throw;
+ }
+ }
+ }
+
+ //usage of HQL
+ public Transaction2 GetTransaction(int transactionId)
+ {
+ using (var session = SessionFactory.OpenSession())
+ {
+ var query = session.CreateQuery(@"
+ SELECT t
+ FROM Transaction2 t
+ LEFT JOIN FETCH t.TransactionProducts tp
+ LEFT JOIN FETCH tp.Product
+ WHERE t.Id = :transactionId
+ ");
+ query.SetParameter("transactionId", transactionId);
+
+ var transaction = query.UniqueResult();
+ return 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(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 t = session.BeginTransaction())
+ {
+ try
+ {
+ session.Update(transactionProduct);
+ 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(transactionId);
+ if (transaction != null)
+ {
+ session.Delete(transaction);
+ t.Commit();
+ }
+ }
+ catch
+ {
+ t.Rollback();
+ throw;
+ }
+ }
+ }
+ public void AddTransactionProductToTransaction(int transactionId, TransactionProduct transactionProduct)
+ {
+ using (var session = SessionFactory.OpenSession())
+ using (var transaction = session.BeginTransaction())
+ {
+ try
+ {
+ var transactionToUpdate = session.Get(transactionId);
+ if (transactionToUpdate != null)
+ {
+ transactionProduct.TransactionId= transactionToUpdate.Id;
+ session.Save(transactionProduct);
+ transaction.Commit();
+
+ var product = session.Get(transactionProduct.ProductID);
+ if (product.Type != 0)
+ {
+ product.Availability -= transactionProduct.Quantity;
+ session.Update(product);
+ }
+
+ }
+ else
+ {
+ throw new Exception("Transaction not found.");
+ }
+ }
+ catch (Exception ex)
+ {
+ transaction.Rollback();
+ throw ex;
+ }
+ }
+ }
+
+
+ public IList GetAllTransactions()
+ {
+ using (var session = SessionFactory.OpenSession())
+ {
+ var transactions = session.Query()
+ .FetchMany(t => t.TransactionProducts)
+ .ThenFetch(tp => tp.Product)
+ .ToList();
+
+ return transactions;
+ }
+ }
+
+ }
+}
diff --git a/nHibernate/Transactions/TransactionMapping.cs b/nHibernate/Transactions/TransactionMapping.cs
new file mode 100644
index 0000000..3a24b5b
--- /dev/null
+++ b/nHibernate/Transactions/TransactionMapping.cs
@@ -0,0 +1,23 @@
+using FluentNHibernate.Mapping;
+
+namespace FirmTracker_Server.nHibernate.Transactions
+{
+ public class TransactionMapping : ClassMap
+ {
+ 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);
+
+ HasMany(x => x.TransactionProducts)
+ .KeyColumn("TransactionId")
+ .Cascade.AllDeleteOrphan()
+ .Inverse(); // Ustawienie Inverse() wskazuje, że to `TransactionProduct` jest właścicielem relacji
+ }
+ }
+}
diff --git a/nHibernate/Transactions/TransactionProduct.cs b/nHibernate/Transactions/TransactionProduct.cs
new file mode 100644
index 0000000..943e7a2
--- /dev/null
+++ b/nHibernate/Transactions/TransactionProduct.cs
@@ -0,0 +1,14 @@
+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; }
+ public virtual int TransactionId { get; set; }
+ public virtual int ProductID { get; set; }
+ public virtual int Quantity { get; set; }
+ }
+}
diff --git a/nHibernate/Transactions/TransactionProductMapping.cs b/nHibernate/Transactions/TransactionProductMapping.cs
new file mode 100644
index 0000000..98e7784
--- /dev/null
+++ b/nHibernate/Transactions/TransactionProductMapping.cs
@@ -0,0 +1,19 @@
+using FluentNHibernate.Mapping;
+
+namespace FirmTracker_Server.nHibernate.Transactions
+{
+ public class TransactionProductMapping : ClassMap
+ {
+ public TransactionProductMapping()
+ {
+ Table("TransactionProducts");
+ Id(x => x.Id).GeneratedBy.Identity();
+
+ Map(x => x.TransactionId).Column("TransactionId").Not.Nullable();
+ Map(x => x.ProductID).Column("ProductId").Not.Nullable();
+
+ Map(x => x.Quantity);
+ //Map(x => x.UnitPrice);
+ }
+ }
+}
diff --git a/nHibernate/Transactions/TransactionWithProducts.cs b/nHibernate/Transactions/TransactionWithProducts.cs
new file mode 100644
index 0000000..e46f1d9
--- /dev/null
+++ b/nHibernate/Transactions/TransactionWithProducts.cs
@@ -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; }
+
+ }
+}
diff --git a/nHibernate/Transactions/TransactionWithProductsMapping.cs b/nHibernate/Transactions/TransactionWithProductsMapping.cs
new file mode 100644
index 0000000..5bf1786
--- /dev/null
+++ b/nHibernate/Transactions/TransactionWithProductsMapping.cs
@@ -0,0 +1,19 @@
+using FluentNHibernate.Mapping;
+
+namespace FirmTracker_Server.nHibernate.Transactions
+{
+ public class TransactionWithProductsMapping : ClassMap
+ {
+ 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);
+
+ }
+ }
+}