From c94363b7900a9e8cbc55a9680eecf10550fe2e48 Mon Sep 17 00:00:00 2001 From: Maciej Maciejewski Date: Fri, 26 Apr 2024 21:24:17 +0200 Subject: [PATCH 1/8] =?UTF-8?q?zmiany=20do=20test=C3=B3w=20rest=20api=20-?= =?UTF-8?q?=20swagger?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .config/dotnet-tools.json | 12 ++++ Controllers/ProductController.cs | 13 ++++ FirmTracker-Server.csproj | 32 ++++++++++ Program.cs | 58 +++++++++++++++--- Properties/Resources.Designer.cs | 63 +++++++++++++++++++ Properties/Resources.resx | 101 +++++++++++++++++++++++++++++++ Properties/launchSettings.json | 64 ++++++++++---------- TestClass.cs | 21 +++++-- appsettings.json | 34 ++++++++--- nHIbernate/Products/Product.cs | 6 +- 10 files changed, 349 insertions(+), 55 deletions(-) create mode 100644 .config/dotnet-tools.json create mode 100644 Properties/Resources.Designer.cs create mode 100644 Properties/Resources.resx 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/ProductController.cs b/Controllers/ProductController.cs index 91056fc..5eda21b 100644 --- a/Controllers/ProductController.cs +++ b/Controllers/ProductController.cs @@ -16,7 +16,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 +37,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 +49,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 +69,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,6 +86,8 @@ namespace FirmTracker_Server.Controllers // GET: api/Products [HttpGet] + [ProducesResponseType(200)] // Created + [ProducesResponseType(400)] // Bad Request public IActionResult GetAllProducts() { var products = _productCrud.GetAllProducts(); diff --git a/FirmTracker-Server.csproj b/FirmTracker-Server.csproj index 727e11d..3616e11 100644 --- a/FirmTracker-Server.csproj +++ b/FirmTracker-Server.csproj @@ -5,8 +5,13 @@ enable enable FirmTracker_Server + 08986e21-848b-485a-a219-03e2dc6041e4 + + + + @@ -16,4 +21,31 @@ + + + True + True + Resources.resx + + + + + + PreserveNewest + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + PreserveNewest + + + diff --git a/Program.cs b/Program.cs index 9986c4b..bff4c04 100644 --- a/Program.cs +++ b/Program.cs @@ -4,33 +4,75 @@ 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(); + // Combine the application directory with the relative path to the config file + 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; + + 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.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(); + Console.WriteLine("raz dwa trzy"); app.UseAuthorization(); @@ -38,9 +80,9 @@ namespace FirmTracker_Server 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..f7302d4 100644 --- a/TestClass.cs +++ b/TestClass.cs @@ -8,21 +8,30 @@ 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 }; try { FirmTracker_Server.nHibernate.Products.ProductCRUD crud = new ProductCRUD(); crud.AddProduct(product); + crud.AddProduct(product2); } catch(Exception ex) { diff --git a/appsettings.json b/appsettings.json index 10f68b8..57058bd 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,9 +1,29 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } + "AppSettings": { + "ConnectionString": "Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;", }, - "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/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; } } } -- 2.20.1 From fc8ac5d51d43afb5342735254c4f010d140dbf15 Mon Sep 17 00:00:00 2001 From: Maciej Maciejewski Date: Sun, 5 May 2024 22:08:27 +0200 Subject: [PATCH 2/8] Added transaction object, crud class and controller for transactions --- Controllers/ProductController.cs | 38 ++++++- Controllers/TransactionController.cs | 100 ++++++++++++++++++ Program.cs | 6 +- TestClass.cs | 14 ++- nHIbernate/SessionFactory.cs | 7 +- nHibernate/Transactions/Transaction.cs | 21 ++++ nHibernate/Transactions/TransactionCRUD.cs | 95 +++++++++++++++++ nHibernate/Transactions/TransactionMapping.cs | 24 +++++ 8 files changed, 294 insertions(+), 11 deletions(-) create mode 100644 Controllers/TransactionController.cs create mode 100644 nHibernate/Transactions/Transaction.cs create mode 100644 nHibernate/Transactions/TransactionCRUD.cs create mode 100644 nHibernate/Transactions/TransactionMapping.cs diff --git a/Controllers/ProductController.cs b/Controllers/ProductController.cs index 5eda21b..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]")] @@ -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; } + } } } \ No newline at end of file diff --git a/Controllers/TransactionController.cs b/Controllers/TransactionController.cs new file mode 100644 index 0000000..29dc5e2 --- /dev/null +++ b/Controllers/TransactionController.cs @@ -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 + /// + /// Creates a new transaction. + /// + [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); + } + + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index bff4c04..fe44b9b 100644 --- a/Program.cs +++ b/Program.cs @@ -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(); diff --git a/TestClass.cs b/TestClass.cs index f7302d4..e16dc79 100644 --- a/TestClass.cs +++ b/TestClass.cs @@ -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, 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) { diff --git a/nHIbernate/SessionFactory.cs b/nHIbernate/SessionFactory.cs index 9ab3368..e08bb24 100644 --- a/nHIbernate/SessionFactory.cs +++ b/nHIbernate/SessionFactory.cs @@ -25,7 +25,12 @@ namespace FirmTracker_Server.nHibernate .Database(MsSqlConfiguration.MsSql2012 .ConnectionString(c => c.Is(connectionString)) .ShowSql()) - .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) + .Mappings(m => + { + m.FluentMappings + .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..448f118 --- /dev/null +++ b/nHibernate/Transactions/Transaction.cs @@ -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 Products { get; set; } = new List(); + public virtual string PaymentType { get; set; } + public virtual int Discount { get; set; } + public virtual string Description { get; set; } + + public Transaction() + { + Products = new List(); + } + } +} diff --git a/nHibernate/Transactions/TransactionCRUD.cs b/nHibernate/Transactions/TransactionCRUD.cs new file mode 100644 index 0000000..8fb8e21 --- /dev/null +++ b/nHibernate/Transactions/TransactionCRUD.cs @@ -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() + .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(transactionId); + if (transaction != null) + { + session.Delete(transaction); + t.Commit(); + } + } + catch + { + t.Rollback(); + throw; + } + } + } + + public IList GetAllTransactions() + { + using (var session = SessionFactory.OpenSession()) + { + var transactions = session.Query() + .FetchMany(t => t.Products) + .ToList(); + return transactions; + } + } + } + +} diff --git a/nHibernate/Transactions/TransactionMapping.cs b/nHibernate/Transactions/TransactionMapping.cs new file mode 100644 index 0000000..1c26c10 --- /dev/null +++ b/nHibernate/Transactions/TransactionMapping.cs @@ -0,0 +1,24 @@ +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); + + HasManyToMany(x => x.Products) + .Table("TransactionProducts") + .ParentKeyColumn("TransactionId") + .ChildKeyColumn("ProductId") + .Cascade.All(); + } + } +} -- 2.20.1 From 31f920a0485becf5e74e83532ee62733efe501a2 Mon Sep 17 00:00:00 2001 From: Maciej Maciejewski Date: Mon, 6 May 2024 21:25:10 +0200 Subject: [PATCH 3/8] changes to transaction entity and endpoints --- Controllers/TransactionController.cs | 26 +++++-- FirmTracker-Server.csproj | 1 + TestClass.cs | 17 ++++- nHIbernate/SessionFactory.cs | 3 +- nHibernate/Transactions/Transaction.cs | 13 ++-- nHibernate/Transactions/TransactionCRUD.cs | 76 ++++++++++++++++--- nHibernate/Transactions/TransactionMapping.cs | 13 ++-- nHibernate/Transactions/TransactionProduct.cs | 17 +++++ .../Transactions/TransactionProductMapping.cs | 19 +++++ 9 files changed, 152 insertions(+), 33 deletions(-) create mode 100644 nHibernate/Transactions/TransactionProduct.cs create mode 100644 nHibernate/Transactions/TransactionProductMapping.cs diff --git a/Controllers/TransactionController.cs b/Controllers/TransactionController.cs index 29dc5e2..febb74e 100644 --- a/Controllers/TransactionController.cs +++ b/Controllers/TransactionController.cs @@ -1,8 +1,9 @@ using Microsoft.AspNetCore.Mvc; using FirmTracker_Server.nHibernate.Transactions; -using FirmTracker_Server; -using System.Collections.Generic; - +using System; +using System.Text.Json.Serialization; +using System.Text.Json; +using System.Transactions; namespace FirmTracker_Server.Controllers { @@ -24,7 +25,7 @@ namespace FirmTracker_Server.Controllers [HttpPost] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - public IActionResult CreateTransaction([FromBody] Transaction transaction) + public IActionResult CreateTransaction([FromBody] nHibernate.Transactions.Transaction transaction) { try { @@ -53,7 +54,7 @@ namespace FirmTracker_Server.Controllers [HttpPut("{id}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [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) return BadRequest("Transaction ID mismatch"); @@ -90,11 +91,24 @@ namespace FirmTracker_Server.Controllers [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); } } -} \ No newline at end of file +} diff --git a/FirmTracker-Server.csproj b/FirmTracker-Server.csproj index 3616e11..e6f7bb1 100644 --- a/FirmTracker-Server.csproj +++ b/FirmTracker-Server.csproj @@ -17,6 +17,7 @@ + diff --git a/TestClass.cs b/TestClass.cs index e16dc79..892a4ba 100644 --- a/TestClass.cs +++ b/TestClass.cs @@ -1,6 +1,7 @@ using FirmTracker_Server.Controllers; using FirmTracker_Server.nHibernate; using FirmTracker_Server.nHibernate.Products; +using FirmTracker_Server.nHibernate.Transactions; using NHibernate; namespace FirmTracker_Server @@ -27,14 +28,13 @@ namespace FirmTracker_Server Type = 0, Availability = 0 }; - var transaction1 = new nHibernate.Transactions.Transaction + var transaction1 = new Transaction { Date = DateTime.Now, Description = "testowa transakcja", Discount = 10, EmployeeId = 1, PaymentType = "Karta kredytowa", - Products = new List { product, product2 } }; try @@ -44,9 +44,22 @@ namespace FirmTracker_Server crud.AddProduct(product); crud.AddProduct(product2); transactionCrud.AddTransaction(transaction1); + + List testTransactionProducts = new List { + 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) { + Console.WriteLine(ex.ToString()); throw; } } diff --git a/nHIbernate/SessionFactory.cs b/nHIbernate/SessionFactory.cs index e08bb24..afed35c 100644 --- a/nHIbernate/SessionFactory.cs +++ b/nHIbernate/SessionFactory.cs @@ -29,7 +29,8 @@ namespace FirmTracker_Server.nHibernate { m.FluentMappings .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 index 448f118..995c34d 100644 --- a/nHibernate/Transactions/Transaction.cs +++ b/nHibernate/Transactions/Transaction.cs @@ -1,21 +1,24 @@ using FirmTracker_Server.nHibernate.Products; -using System.Text.Json.Serialization; +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 DateTime Date { get; set; } public virtual int EmployeeId { get; set; } - public virtual IList Products { get; set; } = new List(); + public virtual IList TransactionProducts { get; set; } = new List(); 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 decimal TotalPrice => TransactionProducts.Sum(tp => ((tp.Quantity * tp.UnitPrice)* ((1 - (Discount / 100)))));// (1 - (Discount / 100))); public Transaction() { - Products = new List(); + TransactionProducts = new List(); } } } diff --git a/nHibernate/Transactions/TransactionCRUD.cs b/nHibernate/Transactions/TransactionCRUD.cs index 8fb8e21..4cd65ba 100644 --- a/nHibernate/Transactions/TransactionCRUD.cs +++ b/nHibernate/Transactions/TransactionCRUD.cs @@ -1,11 +1,9 @@ -using FirmTracker_Server.nHibernate; -using FirmTracker_Server.nHibernate.Products; +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; +using System; +using System.Collections.Generic; +using System.Linq; namespace FirmTracker_Server.nHibernate.Transactions { @@ -18,7 +16,24 @@ namespace FirmTracker_Server.nHibernate.Transactions { 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.Product.Id); + if (product.Type != 0) + { + product.Availability -= transactionProduct.Quantity; + session.Update(product); + } + } + sessionTransaction.Commit(); } catch @@ -29,17 +44,25 @@ namespace FirmTracker_Server.nHibernate.Transactions } } + //usage of HQL public Transaction GetTransaction(int transactionId) { using (var session = SessionFactory.OpenSession()) { - var transaction = session.Query() - .Fetch(t => t.Products) - .FirstOrDefault(t => t.Id == transactionId); + var query = session.CreateQuery(@" + SELECT t + 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(); return transaction; } } + public void UpdateTransaction(Transaction transaction) { using (var session = SessionFactory.OpenSession()) @@ -65,7 +88,7 @@ namespace FirmTracker_Server.nHibernate.Transactions { try { - var transaction = session.Get(transactionId); + var transaction = session.Get(transactionId); if (transaction != null) { 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(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 GetAllTransactions() { using (var session = SessionFactory.OpenSession()) { var transactions = session.Query() - .FetchMany(t => t.Products) + .FetchMany(t => t.TransactionProducts) + .ThenFetch(tp => tp.Product) .ToList(); + return transactions; } } - } + } } diff --git a/nHibernate/Transactions/TransactionMapping.cs b/nHibernate/Transactions/TransactionMapping.cs index 1c26c10..3a24b5b 100644 --- a/nHibernate/Transactions/TransactionMapping.cs +++ b/nHibernate/Transactions/TransactionMapping.cs @@ -2,23 +2,22 @@ namespace FirmTracker_Server.nHibernate.Transactions { - public class TransactionMapping:ClassMap + public class TransactionMapping : ClassMap { public TransactionMapping() { Table("Transactions"); - Id(x => x.Id).GeneratedBy.Identity(); + 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(); + 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..1eca3c7 --- /dev/null +++ b/nHibernate/Transactions/TransactionProduct.cs @@ -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; } + } +} diff --git a/nHibernate/Transactions/TransactionProductMapping.cs b/nHibernate/Transactions/TransactionProductMapping.cs new file mode 100644 index 0000000..4f0ff0d --- /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(); + References(x => x.Product).Column("ProductId").Not.Nullable(); + + Map(x => x.Quantity); + Map(x => x.UnitPrice); + } + } +} -- 2.20.1 From 4e023be7ca147629b1ba441e81f708b3f52b7dd6 Mon Sep 17 00:00:00 2001 From: Maciej Maciejewski Date: Thu, 16 May 2024 00:42:06 +0200 Subject: [PATCH 4/8] =?UTF-8?q?zmiany=20zwi=C4=85zane=20z=20poprawkami=20t?= =?UTF-8?q?ransakcji=20(wymagane=20tylko=20ID=20towaru=20oraz=20ilo=C5=9B?= =?UTF-8?q?=C4=87),=20poprawki=20w=20obliczeniach?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/TransactionController.cs | 46 +++++++++++ Program.cs | 12 ++- TestClass.cs | 4 +- appsettings.json | 2 +- nHIbernate/Products/ProductCRUD.cs | 26 +++++++ nHIbernate/SessionFactory.cs | 4 +- nHibernate/Transactions/Transaction.cs | 2 +- nHibernate/Transactions/Transaction2.cs | 24 ++++++ .../Transactions/Transaction2Mapping.cs | 23 ++++++ nHibernate/Transactions/TransactionCRUD.cs | 76 +++++++++++++++---- nHibernate/Transactions/TransactionProduct.cs | 7 +- .../Transactions/TransactionProductMapping.cs | 4 +- .../Transactions/TransactionWithProducts.cs | 16 ++++ .../TransactionWithProductsMapping.cs | 19 +++++ 14 files changed, 239 insertions(+), 26 deletions(-) create mode 100644 nHibernate/Transactions/Transaction2.cs create mode 100644 nHibernate/Transactions/Transaction2Mapping.cs create mode 100644 nHibernate/Transactions/TransactionWithProducts.cs create mode 100644 nHibernate/Transactions/TransactionWithProductsMapping.cs diff --git a/Controllers/TransactionController.cs b/Controllers/TransactionController.cs index febb74e..b4f80d5 100644 --- a/Controllers/TransactionController.cs +++ b/Controllers/TransactionController.cs @@ -4,6 +4,7 @@ using System; using System.Text.Json.Serialization; using System.Text.Json; using System.Transactions; +using FirmTracker_Server.nHibernate.Products; namespace FirmTracker_Server.Controllers { @@ -12,11 +13,14 @@ namespace FirmTracker_Server.Controllers public class TransactionController : ControllerBase { private readonly TransactionCRUD _transactionCRUD; + private readonly ProductCRUD _productCRUD; public TransactionController() { _transactionCRUD = new TransactionCRUD(); + _productCRUD = new ProductCRUD(); } + // POST: api/Transaction /// @@ -29,7 +33,34 @@ namespace FirmTracker_Server.Controllers { 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) @@ -38,6 +69,7 @@ namespace FirmTracker_Server.Controllers } } + // GET: api/Transaction/5 [HttpGet("{id}")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -61,7 +93,21 @@ namespace FirmTracker_Server.Controllers 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) diff --git a/Program.cs b/Program.cs index fe44b9b..676b6dd 100644 --- a/Program.cs +++ b/Program.cs @@ -36,6 +36,13 @@ namespace FirmTracker_Server TestClass test = new TestClass(); test.AddTestProduct(); + builder.Services.AddCors(options => + { + options.AddPolicy("AllowSpecificOrigin", + policy => policy.WithOrigins("http://localhost:3000") + .AllowAnyHeader() + .AllowAnyMethod()); + }); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); @@ -68,11 +75,14 @@ namespace FirmTracker_Server { Console.WriteLine("Nie uda³o siê uruchomiæ swaggera"); } + app.UseHttpsRedirection(); + + app.UseCors("AllowSpecificOrigin"); app.UseAuthorization(); - + app.MapControllers(); var configuration = new Configuration(); diff --git a/TestClass.cs b/TestClass.cs index 892a4ba..3a3df8b 100644 --- a/TestClass.cs +++ b/TestClass.cs @@ -46,8 +46,8 @@ namespace FirmTracker_Server transactionCrud.AddTransaction(transaction1); List testTransactionProducts = new List { - new TransactionProduct { Product = product, Quantity = 2, UnitPrice = product.Price }, - new TransactionProduct { Product = product2, Quantity = 1, UnitPrice = product2.Price } + new TransactionProduct { ProductID = 1, Quantity = 2 }, + new TransactionProduct { ProductID = 2, Quantity = 1 } }; foreach (var transactionProduct in testTransactionProducts) { diff --git a/appsettings.json b/appsettings.json index 57058bd..5859ca6 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,6 +1,6 @@ { "AppSettings": { - "ConnectionString": "Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;", + "ConnectionString": "Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;TrustServerCertificate=True;" }, "profiles": { "http": { 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 afed35c..151c710 100644 --- a/nHIbernate/SessionFactory.cs +++ b/nHIbernate/SessionFactory.cs @@ -30,7 +30,9 @@ namespace FirmTracker_Server.nHibernate 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 index 995c34d..879c033 100644 --- a/nHibernate/Transactions/Transaction.cs +++ b/nHibernate/Transactions/Transaction.cs @@ -14,7 +14,7 @@ namespace FirmTracker_Server.nHibernate.Transactions public virtual string PaymentType { get; set; } public virtual decimal Discount { 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() { 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 index 4cd65ba..c76d904 100644 --- a/nHibernate/Transactions/TransactionCRUD.cs +++ b/nHibernate/Transactions/TransactionCRUD.cs @@ -4,6 +4,7 @@ using NHibernate.Linq; using System; using System.Collections.Generic; using System.Linq; +using System.Transactions; namespace FirmTracker_Server.nHibernate.Transactions { @@ -18,6 +19,7 @@ namespace FirmTracker_Server.nHibernate.Transactions { foreach (var transactionProduct in transaction.TransactionProducts) { + transactionProduct.TransactionId = transaction.Id; session.Save(transactionProduct); } @@ -26,7 +28,8 @@ namespace FirmTracker_Server.nHibernate.Transactions // Decrease product quantities based on transaction foreach (var transactionProduct in transaction.TransactionProducts) { - var product = session.Get(transactionProduct.Product.Id); + + var product = session.Get(transactionProduct.ProductID); if (product.Type != 0) { product.Availability -= transactionProduct.Quantity; @@ -45,32 +48,71 @@ namespace FirmTracker_Server.nHibernate.Transactions } //usage of HQL - public Transaction GetTransaction(int transactionId) + public Transaction2 GetTransaction(int transactionId) { using (var session = SessionFactory.OpenSession()) { var query = session.CreateQuery(@" - SELECT t - FROM Transaction t - LEFT JOIN FETCH t.TransactionProducts tp - LEFT JOIN FETCH tp.Product + 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(); + + 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(transaction); + session.Update(transactionProduct); t.Commit(); } catch @@ -112,9 +154,17 @@ namespace FirmTracker_Server.nHibernate.Transactions var transactionToUpdate = session.Get(transactionId); if (transactionToUpdate != null) { - transactionProduct.TransactionId = transactionToUpdate.Id; + 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 { @@ -130,13 +180,13 @@ namespace FirmTracker_Server.nHibernate.Transactions } - public IList GetAllTransactions() + public IList GetAllTransactions() { using (var session = SessionFactory.OpenSession()) { - var transactions = session.Query() - .FetchMany(t => t.TransactionProducts) - .ThenFetch(tp => tp.Product) + var transactions = session.Query() + .FetchMany(t => t.TransactionProducts) + .ThenFetch(tp => tp.Product) .ToList(); return transactions; diff --git a/nHibernate/Transactions/TransactionProduct.cs b/nHibernate/Transactions/TransactionProduct.cs index 1eca3c7..943e7a2 100644 --- a/nHibernate/Transactions/TransactionProduct.cs +++ b/nHibernate/Transactions/TransactionProduct.cs @@ -7,11 +7,8 @@ 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 TransactionId { get; set; } + public virtual int ProductID { get; set; } public virtual int Quantity { get; set; } - public virtual decimal UnitPrice { get; set; } } } diff --git a/nHibernate/Transactions/TransactionProductMapping.cs b/nHibernate/Transactions/TransactionProductMapping.cs index 4f0ff0d..98e7784 100644 --- a/nHibernate/Transactions/TransactionProductMapping.cs +++ b/nHibernate/Transactions/TransactionProductMapping.cs @@ -10,10 +10,10 @@ namespace FirmTracker_Server.nHibernate.Transactions 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.ProductID).Column("ProductId").Not.Nullable(); Map(x => x.Quantity); - Map(x => x.UnitPrice); + //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); + + } + } +} -- 2.20.1 From 8f3f1e5b1eb0ec21d493842c19b7b2fbdd568316 Mon Sep 17 00:00:00 2001 From: kamil Date: Thu, 16 May 2024 12:19:35 +0200 Subject: [PATCH 5/8] connection string --- appsettings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appsettings.json b/appsettings.json index 5859ca6..61b3a7a 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,6 +1,6 @@ { "AppSettings": { - "ConnectionString": "Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;TrustServerCertificate=True;" + "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;" }, "profiles": { "http": { -- 2.20.1 From 7b54a5d796b33c8940daab2731fcde20bd250bf2 Mon Sep 17 00:00:00 2001 From: kamil Date: Thu, 16 May 2024 18:02:44 +0200 Subject: [PATCH 6/8] added expense object with crud, mapping and controller --- Controllers/ExpenseController.cs | 44 +++++++++++++++++++++++++++ TestClass.cs | 11 +++++++ nHIbernate/Expenses/Expense.cs | 10 ++++++ nHIbernate/Expenses/ExpenseCRUD.cs | 38 +++++++++++++++++++++++ nHIbernate/Expenses/ExpenseMapping.cs | 17 +++++++++++ nHIbernate/SessionFactory.cs | 3 +- 6 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 Controllers/ExpenseController.cs create mode 100644 nHIbernate/Expenses/Expense.cs create mode 100644 nHIbernate/Expenses/ExpenseCRUD.cs create mode 100644 nHIbernate/Expenses/ExpenseMapping.cs diff --git a/Controllers/ExpenseController.cs b/Controllers/ExpenseController.cs new file mode 100644 index 0000000..3e2e1b0 --- /dev/null +++ b/Controllers/ExpenseController.cs @@ -0,0 +1,44 @@ +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); + } + } +} diff --git a/TestClass.cs b/TestClass.cs index 3a3df8b..7188bf4 100644 --- a/TestClass.cs +++ b/TestClass.cs @@ -2,6 +2,7 @@ using FirmTracker_Server.nHibernate; using FirmTracker_Server.nHibernate.Products; using FirmTracker_Server.nHibernate.Transactions; +using FirmTracker_Server.nHibernate.Expenses; using NHibernate; namespace FirmTracker_Server @@ -37,13 +38,23 @@ namespace FirmTracker_Server PaymentType = "Karta kredytowa", }; + var expense1 = new Expense + { + Date = DateTime.Now, + TotalPrice = 10.5m, + Description = "testowy rozchód" + }; + try { FirmTracker_Server.nHibernate.Products.ProductCRUD crud = new ProductCRUD(); FirmTracker_Server.nHibernate.Transactions.TransactionCRUD transactionCrud = new nHibernate.Transactions.TransactionCRUD(); + ExpenseCRUD expenseCrud = new ExpenseCRUD(); crud.AddProduct(product); crud.AddProduct(product2); transactionCrud.AddTransaction(transaction1); + expenseCrud.AddExpense(expense1); + List testTransactionProducts = new List { new TransactionProduct { ProductID = 1, Quantity = 2 }, diff --git a/nHIbernate/Expenses/Expense.cs b/nHIbernate/Expenses/Expense.cs new file mode 100644 index 0000000..106ae9f --- /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 TotalPrice { 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..94c3d5c --- /dev/null +++ b/nHIbernate/Expenses/ExpenseCRUD.cs @@ -0,0 +1,38 @@ +using FirmTracker_Server.nHibernate; + +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); + } + } + } +} diff --git a/nHIbernate/Expenses/ExpenseMapping.cs b/nHIbernate/Expenses/ExpenseMapping.cs new file mode 100644 index 0000000..2eee2c8 --- /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.TotalPrice); + Map(x => x.Description); + + } + } +} diff --git a/nHIbernate/SessionFactory.cs b/nHIbernate/SessionFactory.cs index 151c710..6562a29 100644 --- a/nHIbernate/SessionFactory.cs +++ b/nHIbernate/SessionFactory.cs @@ -32,7 +32,8 @@ namespace FirmTracker_Server.nHibernate .AddFromAssemblyOf() .AddFromAssemblyOf() .AddFromAssemblyOf() - .AddFromAssemblyOf(); + .AddFromAssemblyOf() + .AddFromAssemblyOf(); }) .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update .BuildSessionFactory(); -- 2.20.1 From f09289c101604d20a9e9c2e0b5eb17e2a4e61947 Mon Sep 17 00:00:00 2001 From: kamil Date: Thu, 16 May 2024 21:25:07 +0200 Subject: [PATCH 7/8] poprawki do cruda expenses --- Controllers/ExpenseController.cs | 54 +++++++++++++++++++++ FirmTracker-Server.csproj | 4 ++ TestClass.cs | 42 +++++++++++++--- nHIbernate/Expenses/Expense.cs | 2 +- nHIbernate/Expenses/ExpenseCRUD.cs | 69 +++++++++++++++++++++++++++ nHIbernate/Expenses/ExpenseMapping.cs | 2 +- 6 files changed, 165 insertions(+), 8 deletions(-) diff --git a/Controllers/ExpenseController.cs b/Controllers/ExpenseController.cs index 3e2e1b0..cb6b8e6 100644 --- a/Controllers/ExpenseController.cs +++ b/Controllers/ExpenseController.cs @@ -40,5 +40,59 @@ namespace FirmTracker_Server.Controllers } 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/FirmTracker-Server.csproj b/FirmTracker-Server.csproj index e6f7bb1..c4a467b 100644 --- a/FirmTracker-Server.csproj +++ b/FirmTracker-Server.csproj @@ -8,6 +8,10 @@ 08986e21-848b-485a-a219-03e2dc6041e4 + + + + diff --git a/TestClass.cs b/TestClass.cs index 7188bf4..a79333f 100644 --- a/TestClass.cs +++ b/TestClass.cs @@ -29,6 +29,14 @@ namespace FirmTracker_Server Type = 0, Availability = 0 }; + var product3 = new nHibernate.Products.Product + { + Name = "Produkt 2", + Description = "produkt", + Price = 16.50m, + Type = 1, + Availability = 20 + }; var transaction1 = new Transaction { Date = DateTime.Now, @@ -37,35 +45,57 @@ namespace FirmTracker_Server EmployeeId = 1, PaymentType = "Karta kredytowa", }; + var transaction2 = new Transaction + { + Date = DateTime.Now, + Description = "testowa transakcja", + Discount = 30, + EmployeeId = 2, + PaymentType = "Gotówka", + }; var expense1 = new Expense { Date = DateTime.Now, - TotalPrice = 10.5m, + Value = 1003.9m, Description = "testowy rozchód" }; try { - FirmTracker_Server.nHibernate.Products.ProductCRUD crud = new ProductCRUD(); + FirmTracker_Server.nHibernate.Products.ProductCRUD productCrud = new ProductCRUD(); FirmTracker_Server.nHibernate.Transactions.TransactionCRUD transactionCrud = new nHibernate.Transactions.TransactionCRUD(); ExpenseCRUD expenseCrud = new ExpenseCRUD(); - crud.AddProduct(product); - crud.AddProduct(product2); + productCrud.AddProduct(product); + productCrud.AddProduct(product2); + productCrud.AddProduct(product3); transactionCrud.AddTransaction(transaction1); + transactionCrud.AddTransaction(transaction2); expenseCrud.AddExpense(expense1); List testTransactionProducts = new List { new TransactionProduct { ProductID = 1, Quantity = 2 }, - new TransactionProduct { ProductID = 2, Quantity = 1 } + 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 = 3, Quantity=4}, + new TransactionProduct { ProductID = 1, Quantity=6} + }; + foreach (var transactionProduct in testTransactionProducts2) + { + transactionCrud.AddTransactionProductToTransaction(transaction2.Id, transactionProduct); + + } + } catch(Exception ex) diff --git a/nHIbernate/Expenses/Expense.cs b/nHIbernate/Expenses/Expense.cs index 106ae9f..f99cc0a 100644 --- a/nHIbernate/Expenses/Expense.cs +++ b/nHIbernate/Expenses/Expense.cs @@ -4,7 +4,7 @@ { public virtual int Id { get; set; } public virtual DateTime Date { get; set; } - public virtual decimal TotalPrice { 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 index 94c3d5c..a7ceeab 100644 --- a/nHIbernate/Expenses/ExpenseCRUD.cs +++ b/nHIbernate/Expenses/ExpenseCRUD.cs @@ -1,4 +1,5 @@ using FirmTracker_Server.nHibernate; +using FirmTracker_Server.nHibernate.Products; namespace FirmTracker_Server.nHibernate.Expenses { @@ -34,5 +35,73 @@ namespace FirmTracker_Server.nHibernate.Expenses 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 index 2eee2c8..ad2468d 100644 --- a/nHIbernate/Expenses/ExpenseMapping.cs +++ b/nHIbernate/Expenses/ExpenseMapping.cs @@ -9,7 +9,7 @@ namespace FirmTracker_Server.nHibernate.Expenses Table("Expenses"); Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Date); - Map(x => x.TotalPrice); + Map(x => x.Value); Map(x => x.Description); } -- 2.20.1 From 2c4927aa1dcc058267c5c5000a52927685acd491 Mon Sep 17 00:00:00 2001 From: kamil Date: Thu, 16 May 2024 22:30:57 +0200 Subject: [PATCH 8/8] =?UTF-8?q?wi=C4=99cej=20testowych=20produkt=C3=B3w=20?= =?UTF-8?q?i=20transakcji?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TestClass.cs | 46 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/TestClass.cs b/TestClass.cs index a79333f..537cc03 100644 --- a/TestClass.cs +++ b/TestClass.cs @@ -37,9 +37,25 @@ namespace FirmTracker_Server 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, + Date = DateTime.Now.AddDays(-2), Description = "testowa transakcja", Discount = 10, EmployeeId = 1, @@ -47,12 +63,20 @@ namespace FirmTracker_Server }; var transaction2 = new Transaction { - Date = DateTime.Now, + 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 { @@ -69,8 +93,11 @@ namespace FirmTracker_Server 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); @@ -87,8 +114,8 @@ namespace FirmTracker_Server List testTransactionProducts2 = new List { - new TransactionProduct { ProductID = 3, Quantity=4}, - new TransactionProduct { ProductID = 1, Quantity=6} + new TransactionProduct { ProductID = 4, Quantity=5}, + new TransactionProduct { ProductID = 5, Quantity=1} }; foreach (var transactionProduct in testTransactionProducts2) { @@ -96,6 +123,17 @@ namespace FirmTracker_Server } + 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) -- 2.20.1