Compare commits
No commits in common. "master" and "PI2024-23" have entirely different histories.
@ -1,9 +0,0 @@
|
||||
namespace FirmTracker_Server.Authentication
|
||||
{
|
||||
public class AuthenticationSettings
|
||||
{
|
||||
public string JwtSecKey { get; set; }
|
||||
public int JwtExpireDays { get; set; }
|
||||
public string JwtIssuer { get; set; }
|
||||
}
|
||||
}
|
@ -17,13 +17,11 @@
|
||||
|
||||
using FirmTracker_Server.nHibernate.Expenses;
|
||||
using FirmTracker_Server.nHibernate.Products;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class ExpensesController : ControllerBase
|
||||
{
|
||||
private readonly ExpenseCRUD _expenseCrud;
|
||||
@ -36,7 +34,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpPost]
|
||||
[ProducesResponseType(201)] // Created
|
||||
[ProducesResponseType(400)] // Bad Request
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult CreateExpense([FromBody] Expense expense) {
|
||||
try
|
||||
{
|
||||
@ -62,7 +59,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet("{id}")]
|
||||
[ProducesResponseType(200)] // Created
|
||||
[ProducesResponseType(404)] // Bad Request
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult GetExpense(int id)
|
||||
{
|
||||
var expense = _expenseCrud.GetExpense(id);
|
||||
@ -77,7 +73,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpPut("{id}")]
|
||||
[ProducesResponseType(204)]
|
||||
[ProducesResponseType(400)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult UpdateExpense(int id, [FromBody] Expense expense)
|
||||
{
|
||||
try
|
||||
@ -108,7 +103,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpDelete("{id}")]
|
||||
[ProducesResponseType(204)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult DeleteExpense(int id)
|
||||
{
|
||||
try
|
||||
@ -129,7 +123,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(400)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult GetAllExpenses()
|
||||
{
|
||||
try
|
||||
|
@ -1,265 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using FirmTracker_Server.nHibernate;
|
||||
using FirmTracker_Server.nHibernate.Expenses;
|
||||
using FirmTracker_Server.nHibernate.Transactions;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using QuestPDF.Fluent;
|
||||
using QuestPDF.Helpers;
|
||||
using QuestPDF.Infrastructure;
|
||||
|
||||
namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class PdfController : ControllerBase
|
||||
{
|
||||
private readonly IExpenseRepository _expenseRepository;
|
||||
private readonly ITransactionRepository _transactionRepository;
|
||||
private readonly IProductRepository _productRepository;
|
||||
|
||||
public PdfController(IExpenseRepository expenseRepository, ITransactionRepository transactionRepository, IProductRepository productRepository)
|
||||
{
|
||||
_expenseRepository = expenseRepository;
|
||||
_transactionRepository = transactionRepository;
|
||||
_productRepository = productRepository;
|
||||
}
|
||||
|
||||
[HttpGet("download")]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult DownloadReport(
|
||||
[FromQuery] string reportType, // "expenses" or "transactions"
|
||||
[FromQuery] DateTime? startDate,
|
||||
[FromQuery] DateTime? endDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
DateTime start = startDate ?? DateTime.MinValue;
|
||||
DateTime end = endDate ?? DateTime.MaxValue;
|
||||
|
||||
if (string.IsNullOrEmpty(reportType) ||
|
||||
(reportType.ToLower() != "expenses" && reportType.ToLower() != "transactions"))
|
||||
{
|
||||
return BadRequest("Invalid report type. Please specify 'expenses' or 'transactions'.");
|
||||
}
|
||||
|
||||
if (reportType.ToLower() == "expenses")
|
||||
{
|
||||
return GenerateExpenseReport(start, end);
|
||||
}
|
||||
else
|
||||
{
|
||||
return GenerateTransactionReport(start, end);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, $"Internal server error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private IActionResult GenerateExpenseReport(DateTime start, DateTime end)
|
||||
{
|
||||
var expenses = _expenseRepository.GetAllExpenses()
|
||||
.Where(e => e.Date >= start && e.Date <= end)
|
||||
.ToList();
|
||||
|
||||
if (!expenses.Any())
|
||||
{
|
||||
return BadRequest($"No expenses found between {start:yyyy-MM-dd} and {end:yyyy-MM-dd}.");
|
||||
}
|
||||
|
||||
var pdfBytes = GenerateExpensePdf(expenses, start, end);
|
||||
string fileName = $"ExpenseReport_{start:yyyy-MM-dd}_to_{end:yyyy-MM-dd}.pdf";
|
||||
return File(pdfBytes, "application/pdf", fileName);
|
||||
}
|
||||
|
||||
private IActionResult GenerateTransactionReport(DateTime start, DateTime end)
|
||||
{
|
||||
var transactions = _transactionRepository.GetTransactionsByDateRange(start, end);
|
||||
|
||||
if (!transactions.Any())
|
||||
{
|
||||
return BadRequest($"No transactions found between {start:yyyy-MM-dd} and {end:yyyy-MM-dd}.");
|
||||
}
|
||||
|
||||
// Fetch transaction products for all transactions in one query
|
||||
var transactionIds = transactions.Select(t => t.Id).ToList();
|
||||
var transactionProducts = _transactionRepository.GetTransactionProductsForTransactions(transactionIds);
|
||||
|
||||
var pdfBytes = GenerateTransactionPdf(transactions, transactionProducts, start, end);
|
||||
string fileName = $"TransactionReport_{start:yyyy-MM-dd}_to_{end:yyyy-MM-dd}.pdf";
|
||||
return File(pdfBytes, "application/pdf", fileName);
|
||||
}
|
||||
|
||||
private byte[] GenerateTransactionPdf(List<Transaction> transactions, List<TransactionProduct> transactionProducts, DateTime startDate, DateTime endDate)
|
||||
{
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
Document.Create(container =>
|
||||
{
|
||||
container.Page(page =>
|
||||
{
|
||||
page.Size(PageSizes.A4);
|
||||
page.Margin(2, Unit.Centimetre);
|
||||
page.PageColor(Colors.White);
|
||||
page.DefaultTextStyle(x => x.FontSize(12));
|
||||
page.Header()
|
||||
.Text("Raport transakcji")
|
||||
.FontSize(22)
|
||||
.SemiBold()
|
||||
.FontColor(Colors.Blue.Medium)
|
||||
.AlignCenter();
|
||||
|
||||
page.Content().PaddingVertical(1, Unit.Centimetre).Column(column =>
|
||||
{
|
||||
column.Spacing(10);
|
||||
|
||||
column.Item().Text($"Transakcje od ({startDate:yyyy-MM-dd} do {endDate:yyyy-MM-dd})")
|
||||
.FontSize(16)
|
||||
.Underline()
|
||||
.FontColor(Colors.Grey.Medium);
|
||||
|
||||
column.Item().Row(row =>
|
||||
{
|
||||
row.RelativeItem().Text("Data").SemiBold().FontColor(Colors.Blue.Darken1);
|
||||
row.RelativeItem().Text("Typ płatności").SemiBold().FontColor(Colors.Blue.Darken1);
|
||||
row.RelativeItem().Text("Kwota razem").SemiBold().FontColor(Colors.Blue.Darken1);
|
||||
row.RelativeItem().Text("Rabat").SemiBold().FontColor(Colors.Blue.Darken1);
|
||||
row.RelativeItem().Text("Opis").SemiBold().FontColor(Colors.Blue.Darken1);
|
||||
});
|
||||
foreach (var transaction in transactions)
|
||||
{
|
||||
column.Item().Row(row =>
|
||||
{
|
||||
row.RelativeItem().Text(transaction.Date.ToString("yyyy-MM-dd"));
|
||||
row.RelativeItem().Text(transaction.PaymentType);
|
||||
row.RelativeItem().Text(transaction.TotalPrice.ToString("C"));
|
||||
row.RelativeItem().Text(transaction.Discount.ToString("C"));
|
||||
row.RelativeItem().Text(transaction.Description);
|
||||
});
|
||||
var products = transactionProducts
|
||||
.Where(tp => tp.TransactionId == transaction.Id)
|
||||
.ToList();
|
||||
|
||||
if (products.Any())
|
||||
{
|
||||
column.Item().Text("Produkty:").SemiBold().FontColor(Colors.Blue.Medium);
|
||||
foreach (var product in products)
|
||||
{
|
||||
var productQuery = _productRepository.GetProduct(product.Id);
|
||||
column.Item().Row(productRow =>
|
||||
{
|
||||
productRow.RelativeItem().Text($"Nazwa produktu: {productQuery.Name}");
|
||||
productRow.RelativeItem().Text($"Ilość: {product.Quantity}");
|
||||
productRow.RelativeItem().Text($"Cena 1 szt. bez rabatu: {productQuery.Price.ToString("F2")}");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
page.Footer()
|
||||
.AlignCenter()
|
||||
.Text(text =>
|
||||
{
|
||||
text.Span("Wygenerowano przez automat FT: ").FontColor(Colors.Grey.Medium);
|
||||
text.Span(DateTime.Now.ToString("yyyy-MM-dd")).SemiBold().FontColor(Colors.Grey.Medium);
|
||||
});
|
||||
});
|
||||
}).GeneratePdf(ms);
|
||||
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] GenerateExpensePdf(List<Expense> expenses, DateTime startDate, DateTime endDate)
|
||||
{
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
decimal totalExpenses = expenses.Sum(e => e.Value);
|
||||
decimal averageExpense = expenses.Any() ? totalExpenses / expenses.Count : 0;
|
||||
|
||||
Document.Create(container =>
|
||||
{
|
||||
container.Page(page =>
|
||||
{
|
||||
page.Size(PageSizes.A4);
|
||||
page.Margin(2, Unit.Centimetre);
|
||||
page.PageColor(Colors.White);
|
||||
page.DefaultTextStyle(x => x.FontSize(12));
|
||||
page.Header()
|
||||
.Text("Raport wydatków")
|
||||
.FontSize(22)
|
||||
.SemiBold()
|
||||
.FontColor(Colors.Green.Medium)
|
||||
.AlignCenter();
|
||||
page.Content().PaddingVertical(1, Unit.Centimetre).Column(column =>
|
||||
{
|
||||
column.Spacing(10);
|
||||
|
||||
column.Item().Row(row =>
|
||||
{
|
||||
row.RelativeItem().Text($"Łączne wydatki: {totalExpenses:C}").FontSize(14).Bold().FontColor(Colors.Green.Darken1);
|
||||
row.RelativeItem().Text($"Średnie wydatki dzienne: {averageExpense:C}").FontSize(14).Bold().FontColor(Colors.Green.Darken1);
|
||||
});
|
||||
|
||||
column.Item().Text($"Szczegóły wydatków od ({startDate:yyyy-MM-dd} do {endDate:yyyy-MM-dd})")
|
||||
.FontSize(16)
|
||||
.Underline()
|
||||
.FontColor(Colors.Grey.Medium);
|
||||
|
||||
column.Item().Row(row =>
|
||||
{
|
||||
row.RelativeItem().Text("Data").SemiBold().FontColor(Colors.Green.Darken1);
|
||||
row.RelativeItem().Text("Kwota").SemiBold().FontColor(Colors.Green.Darken1);
|
||||
row.RelativeItem().Text("Opis").SemiBold().FontColor(Colors.Green.Darken1);
|
||||
});
|
||||
|
||||
foreach (var expense in expenses)
|
||||
{
|
||||
column.Item().Row(row =>
|
||||
{
|
||||
row.RelativeItem().Text(expense.Date.ToString("yyyy-MM-dd"));
|
||||
row.RelativeItem().Text(expense.Value.ToString("C"));
|
||||
row.RelativeItem().Text(expense.Description);
|
||||
});
|
||||
}
|
||||
});
|
||||
page.Footer()
|
||||
.AlignCenter()
|
||||
.Text(text =>
|
||||
{
|
||||
text.Span("Wygenerowano przez automat FT: ").FontColor(Colors.Grey.Medium);
|
||||
text.Span(DateTime.Now.ToString("yyyy-MM-dd")).SemiBold().FontColor(Colors.Grey.Medium);
|
||||
});
|
||||
});
|
||||
}).GeneratePdf(ms);
|
||||
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -16,8 +16,6 @@
|
||||
*/
|
||||
|
||||
using FirmTracker_Server.nHibernate.Products;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System;
|
||||
|
||||
@ -25,7 +23,6 @@ namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class ProductsController : ControllerBase
|
||||
{
|
||||
private readonly ProductCRUD _productCrud;
|
||||
@ -42,7 +39,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpPost]
|
||||
[ProducesResponseType(200)] // Created
|
||||
[ProducesResponseType(400)] // Bad Request
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult CreateProduct([FromBody] Product product)
|
||||
{
|
||||
try
|
||||
@ -63,11 +59,6 @@ namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
throw new InvalidOperationException("Produkt nie może posiadać ujemnej ceny.");
|
||||
}
|
||||
var productByName = _productCrud.GetProductByName(product.Name);
|
||||
if (productByName != null)
|
||||
{
|
||||
throw new InvalidOperationException("Produkt o podanej nazwie już istnieje.");
|
||||
}
|
||||
|
||||
_productCrud.AddProduct(product);
|
||||
return CreatedAtAction("GetProduct", new { id = product.Id }, product);
|
||||
@ -86,7 +77,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet("{id}")]
|
||||
[ProducesResponseType(200)] // Created
|
||||
[ProducesResponseType(400)] // Bad Request
|
||||
[Authorize(Roles=Roles.Admin+","+Roles.User)]
|
||||
public IActionResult GetProduct(int id)
|
||||
{
|
||||
var product = _productCrud.GetProduct(id);
|
||||
@ -98,7 +88,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet("name/{name}")]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetProductByName(string name)
|
||||
{
|
||||
var product = _productCrud.GetProductByName(name);
|
||||
@ -111,7 +100,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpPut("{id}")]
|
||||
[ProducesResponseType(200)] // Created
|
||||
[ProducesResponseType(400)] // Bad Request
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult UpdateProduct(int id, [FromBody] Product product)
|
||||
{
|
||||
try
|
||||
@ -153,7 +141,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpDelete("{id}")]
|
||||
[ProducesResponseType(200)] // Created
|
||||
[ProducesResponseType(400)] // Bad Request
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult DeleteProduct(int id)
|
||||
{
|
||||
try
|
||||
@ -175,7 +162,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet]
|
||||
[ProducesResponseType(200)] // Created
|
||||
[ProducesResponseType(400)] // Bad Request
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetAllProducts()
|
||||
{
|
||||
var products = _productCrud.GetAllProducts();
|
||||
|
@ -24,14 +24,12 @@ using FirmTracker_Server.nHibernate.Expenses;
|
||||
using FirmTracker_Server.nHibernate.Products;
|
||||
using FirmTracker_Server.nHibernate;
|
||||
using NHibernate.Linq;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
|
||||
namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class ReportController : ControllerBase
|
||||
{
|
||||
private readonly ReportCRUD _reportCRUD;
|
||||
@ -45,7 +43,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpPost]
|
||||
[ProducesResponseType(201)] //Created
|
||||
[ProducesResponseType(400)] //Bad request
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult CreateReport([FromBody] Report.DateRangeDto dateRange)
|
||||
{
|
||||
try
|
||||
@ -121,7 +118,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet("{id}")]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult GetReport(int id)
|
||||
{
|
||||
var report = _reportCRUD.GetReport(id);
|
||||
@ -140,7 +136,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet("{id}/transactions")]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult GetReportTransactions(int id)
|
||||
{
|
||||
var transactions = _reportCRUD.GetReportTransactions(id);
|
||||
@ -154,7 +149,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet("{id}/expenses")]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult GetReportExpenses(int id)
|
||||
{
|
||||
var expenses = _reportCRUD.GetReportExpenses(id);
|
||||
@ -169,7 +163,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet]
|
||||
[ProducesResponseType(200)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult GetAllReports()
|
||||
{
|
||||
var reports = _reportCRUD.GetAllReports();
|
||||
@ -183,7 +176,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[ProducesResponseType(204)]
|
||||
[ProducesResponseType(400)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult UpdateReport(int id, [FromBody] Report.DateRangeDto dateRange)
|
||||
{
|
||||
try
|
||||
@ -252,7 +244,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpDelete("{id}")]
|
||||
[ProducesResponseType(204)]
|
||||
[ProducesResponseType(404)]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public IActionResult DeleteReport(int id)
|
||||
{
|
||||
try
|
||||
|
@ -24,24 +24,20 @@ using System.Transactions;
|
||||
using FirmTracker_Server.nHibernate.Products;
|
||||
using FirmTracker_Server.nHibernate;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using FirmTracker_Server.Services;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class TransactionController : ControllerBase
|
||||
{
|
||||
private readonly TransactionCRUD _transactionCRUD;
|
||||
private readonly ProductCRUD _productCRUD;
|
||||
|
||||
public TransactionController()
|
||||
{
|
||||
_transactionCRUD = new TransactionCRUD();
|
||||
_productCRUD = new ProductCRUD();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -52,27 +48,18 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpPost]
|
||||
[ProducesResponseType(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult CreateTransaction([FromBody] nHibernate.Transactions.Transaction transaction)
|
||||
{
|
||||
try
|
||||
{
|
||||
var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
||||
transaction.EmployeeId = int.Parse(userId);
|
||||
|
||||
foreach (var product in transaction.TransactionProducts)
|
||||
{
|
||||
// Validate if the product quantity is positive
|
||||
if (product.Quantity <= 0)
|
||||
{
|
||||
return BadRequest($"Ilość na produktu {product.ProductName} musi być dodatnia.");
|
||||
}
|
||||
var productByName = _productCRUD.GetProductByName(product.ProductName);
|
||||
if (productByName == null)
|
||||
{
|
||||
throw new InvalidOperationException($"Produkt o nazwie {product.ProductName} nie istnieje.");
|
||||
}
|
||||
|
||||
|
||||
product.ProductID = productByName.Id;
|
||||
product.TransactionId = transaction.Id;
|
||||
|
||||
@ -119,7 +106,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpGet("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetTransaction(int id)
|
||||
{
|
||||
var transaction = _transactionCRUD.GetTransaction(id);
|
||||
@ -132,7 +118,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpPut("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult UpdateTransaction(int id, [FromBody] nHibernate.Transactions.Transaction transaction)
|
||||
{
|
||||
if (id != transaction.Id)
|
||||
@ -142,11 +127,6 @@ namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
foreach (var product in transaction.TransactionProducts)
|
||||
{
|
||||
// Validate if the product quantity is positive
|
||||
if (product.Quantity <= 0)
|
||||
{
|
||||
return BadRequest($"Sprzedawana ilość produktu {product.ProductName} musi być ilością dodatnią.");
|
||||
}
|
||||
var productByName = _productCRUD.GetProductByName(product.ProductName);
|
||||
if (productByName == null)
|
||||
{
|
||||
@ -180,7 +160,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[HttpDelete("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult DeleteTransaction(int id)
|
||||
{
|
||||
try
|
||||
@ -203,7 +182,6 @@ namespace FirmTracker_Server.Controllers
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetAllTransactions()
|
||||
{
|
||||
var transactions = _transactionCRUD.GetAllTransactions();
|
||||
@ -222,27 +200,5 @@ namespace FirmTracker_Server.Controllers
|
||||
return Ok(transactions);
|
||||
}
|
||||
|
||||
// DELETE: api/Transaction/5/product/10
|
||||
[HttpDelete("{transactionId}/product/{productId}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult DeleteTransactionProduct(int transactionId, int productId)
|
||||
{
|
||||
try
|
||||
{
|
||||
_transactionCRUD.DeleteTransactionProduct(transactionId, productId);
|
||||
return NoContent();
|
||||
}
|
||||
catch (InvalidOperationException ioe)
|
||||
{
|
||||
return BadRequest(ioe.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return NotFound(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,165 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using FirmTracker_Server.Models;
|
||||
using FirmTracker_Server.Services;
|
||||
using FirmTracker_Server;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using FirmTracker_Server.Entities;
|
||||
using System.Security.Claims;
|
||||
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
[Route("api/user")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class UserController : ControllerBase
|
||||
{
|
||||
private readonly IUserService UserService;
|
||||
|
||||
public UserController(IUserService userService)
|
||||
{
|
||||
UserService = userService;
|
||||
}
|
||||
|
||||
[HttpPost("create")]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public ActionResult CreateUser([FromBody] CreateUserDto dto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest("Nieprawidłowa wartość pola. /n" + ModelState);
|
||||
}
|
||||
if (!IsValidPassword(dto.Password))
|
||||
{
|
||||
return BadRequest("Hasło musi mieć co najmniej 8 znaków i nie może zawierać spacji, ani tabulatorów.");
|
||||
}
|
||||
|
||||
|
||||
var id = UserService.AddUser(dto);
|
||||
return Created($"/api/user/{id}", "User dodany poprawnie");
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
public ActionResult Login([FromBody] LoginDto dto)
|
||||
{
|
||||
var token = UserService.CreateTokenJwt(dto);
|
||||
return Ok(token);
|
||||
}
|
||||
[HttpGet("role")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public ActionResult<string> GetUserRole()
|
||||
{
|
||||
var roleClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
|
||||
if (roleClaim == null)
|
||||
{
|
||||
return NotFound("Role not found for the logged-in user.");
|
||||
}
|
||||
return Ok(roleClaim);
|
||||
}
|
||||
[HttpGet("UsersList")]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public ActionResult<IList<EmployeeDto>> GetAllUsers()
|
||||
{
|
||||
var users = UserService.GetAllUsers();
|
||||
return Ok(users);
|
||||
}
|
||||
[HttpGet("emails")]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public ActionResult<IEnumerable<string>> GetAllUserEmails()
|
||||
{
|
||||
var emails = UserService.GetAllUserEmails();
|
||||
if (emails == null || !emails.Any())
|
||||
{
|
||||
return NotFound("No users found or unable to retrieve emails.");
|
||||
}
|
||||
|
||||
return Ok(emails);
|
||||
}
|
||||
[HttpPost("ChangeUserPassword")]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
public ActionResult ChangeUserPassword([FromBody] ChangeUserPasswordDto dto)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsValidPassword(dto.password))
|
||||
{
|
||||
return BadRequest("Password must be at least 8 characters long and cannot contain spaces or tabs.");
|
||||
}
|
||||
|
||||
var result = UserService.ChangeUserPassword(dto);
|
||||
|
||||
if (result)
|
||||
{
|
||||
return Ok("Password changed successfully.");
|
||||
}
|
||||
else
|
||||
{
|
||||
return BadRequest("Failed to change the password.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest($"An error occurred: {ex.Message}");
|
||||
}
|
||||
}
|
||||
[HttpPost("changePassword")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public ActionResult ChangePassword([FromBody] UpdatePasswordDto dto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = UserService.UpdatePassword(dto);
|
||||
if (result)
|
||||
{
|
||||
var loginDto = new LoginDto { Email = dto.email, Password = dto.newPassword };
|
||||
var token = UserService.CreateTokenJwt(loginDto);
|
||||
return Ok(new { Token = token });
|
||||
}
|
||||
else
|
||||
{
|
||||
return BadRequest("Failed to change the password.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest($"An error occurred: {ex.Message}");
|
||||
}
|
||||
}
|
||||
private bool IsValidPassword(string password)
|
||||
{
|
||||
if (string.IsNullOrEmpty(password) || password.Length < 8 || password.Contains(" ") || password.Contains("\t"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// New method to get all users
|
||||
/* [HttpGet("all")]
|
||||
[AllowAnonymous]
|
||||
public ActionResult<IList<User>> GetAllUsers()
|
||||
{
|
||||
var users = UserService.GetAllUsers();
|
||||
return Ok(users);
|
||||
}*/
|
||||
}
|
||||
}
|
@ -1,172 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using FirmTracker_Server.Entities;
|
||||
using FirmTracker_Server.Models;
|
||||
using FirmTracker_Server.nHibernate;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace FirmTracker_Server.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class WorkdayController : ControllerBase
|
||||
{
|
||||
private readonly WorkdayRepository _workdayCRUD;
|
||||
|
||||
public WorkdayController()
|
||||
{
|
||||
_workdayCRUD = new WorkdayRepository();
|
||||
}
|
||||
|
||||
// Endpoint to start a workday
|
||||
[HttpPost("start")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult StartWorkday()
|
||||
{
|
||||
try
|
||||
{
|
||||
var userIdString = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
||||
int userId = int.Parse(userIdString);
|
||||
|
||||
_workdayCRUD.StartWorkday(userId);
|
||||
return Ok(new { status = "started", userId });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = "An error occurred while starting the workday.", error = ex.Message });
|
||||
}
|
||||
}
|
||||
// Endpoint to stop a workday
|
||||
[HttpPost("stop")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult StopWorkday()
|
||||
{
|
||||
try
|
||||
{
|
||||
var userIdString = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
||||
int userId = int.Parse(userIdString);
|
||||
|
||||
var result = _workdayCRUD.StopWorkday(userId);
|
||||
return Ok(new { status = result ? "stopped" : "already stopped", userId });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = "An error occurred while stopping the workday.", error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("user/workdays")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetWorkdaysLoggedUser()
|
||||
{
|
||||
try
|
||||
{
|
||||
var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
var workdays = _workdayCRUD.GetWorkdaysByLoggedUser(userId);
|
||||
return Ok(workdays);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = "An error occurred while fetching workdays.", error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
// Endpoint to get all workdays for a user
|
||||
[HttpGet("user/{userMail}/workdays")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetWorkdays(string userMail)
|
||||
{
|
||||
try
|
||||
{
|
||||
var workdays = _workdayCRUD.GetWorkdaysByUser(userMail);
|
||||
return Ok(workdays);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = "An error occurred while fetching workdays.", error = ex.Message });
|
||||
}
|
||||
}
|
||||
[HttpPost("absence/add")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult AddAbsence([FromBody] AddAbsenceDto dto)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(dto.userEmail))
|
||||
{
|
||||
return BadRequest(new { message = "User email must be provided." });
|
||||
}
|
||||
|
||||
int userId;
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
var user = session.Query<User>().FirstOrDefault(u => u.Email == dto.userEmail);
|
||||
if (user == null)
|
||||
{
|
||||
return NotFound(new { message = "User with the given email not found." });
|
||||
}
|
||||
userId = user.UserId;
|
||||
}
|
||||
|
||||
_workdayCRUD.AddAbsence(userId, dto.AbsenceType, dto.StartTime, dto.EndTime);
|
||||
|
||||
return Ok(new { status = "added", userId, dto.userEmail, absenceType = dto.AbsenceType });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = "An error occurred while adding the absence.", error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("user/{userMail}/day/info/{date}")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetUserDayDetailsByMail(string userMail, DateTime date)
|
||||
{
|
||||
try
|
||||
{
|
||||
var dayDetails = _workdayCRUD.GetDayDetails(userMail, date);
|
||||
return Ok(dayDetails);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = "An error occurred while fetching the day's details.", error = ex.Message });
|
||||
}
|
||||
}
|
||||
[HttpGet("user/day/info/{date}")]
|
||||
[Authorize(Roles = Roles.Admin + "," + Roles.User)]
|
||||
public IActionResult GetUserDayDetails(DateTime date)
|
||||
{
|
||||
try
|
||||
{
|
||||
var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
var dayDetails = _workdayCRUD.GetDayDetailsForLoggedUser(int.Parse(userId), date);
|
||||
return Ok(dayDetails);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = "An error occurred while fetching the day's details.", error = ex.Message });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
37
Dockerfile
37
Dockerfile
@ -1,37 +0,0 @@
|
||||
# Step 1: Use the official .NET SDK image to build the app
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Copy the project file and restore dependencies
|
||||
COPY ["FirmTracker-Server.csproj", "FirmTracker-Server/"]
|
||||
RUN dotnet restore "FirmTracker-Server/FirmTracker-Server.csproj"
|
||||
|
||||
# Copy the rest of the application code
|
||||
WORKDIR "/src/FirmTracker-Server"
|
||||
COPY . .
|
||||
|
||||
|
||||
# Copy the szyfrowanie.dll into the build directory (to ensure it's available during the build)
|
||||
#COPY ["szyfrowanie.dll", "./"]
|
||||
|
||||
# Build the app
|
||||
RUN dotnet build "FirmTracker-Server.csproj" -c Release -o /app/build
|
||||
|
||||
# Step 2: Publish the app
|
||||
FROM build AS publish
|
||||
RUN dotnet publish "FirmTracker-Server.csproj" -c Release -o /app/publish
|
||||
|
||||
# Step 3: Create the final image using a runtime-only image
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 80
|
||||
EXPOSE 443
|
||||
|
||||
# Copy the published app from the previous stage
|
||||
COPY --from=publish /app/publish .
|
||||
|
||||
# Copy the szyfrowanie.dll to the final image (if needed at runtime)
|
||||
#COPY ["szyfrowanie.dll", "./"]
|
||||
|
||||
# Set the entry point for the container
|
||||
ENTRYPOINT ["dotnet", "FirmTracker-Server.dll"]
|
@ -1,12 +0,0 @@
|
||||
namespace FirmTracker_Server.Entities
|
||||
{
|
||||
public class User
|
||||
{
|
||||
public virtual int UserId { get; set; }
|
||||
public virtual string Login { get; set; }
|
||||
public virtual string Email { get; set; }
|
||||
public virtual string Role { get; set; } = "User";
|
||||
public virtual string PassHash { get; set; }
|
||||
public virtual bool NewEncryption { get; set; }
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
namespace FirmTracker_Server.Exceptions
|
||||
{
|
||||
public class NoResultsException : Exception
|
||||
{
|
||||
public NoResultsException() : base("Brak wyników") { }
|
||||
|
||||
public NoResultsException(string message) : base(message) { }
|
||||
|
||||
public NoResultsException(string message, Exception innerException) : base(message, innerException) { }
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
namespace FirmTracker_Server.Exceptions
|
||||
{
|
||||
public class PermissionException : Exception
|
||||
{
|
||||
public PermissionException() : base("Brak uprawnień") { }
|
||||
|
||||
public PermissionException(string message) : base(message) { }
|
||||
|
||||
public PermissionException(string message, Exception innerException) : base(message, innerException) { }
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
namespace FirmTracker_Server.Exceptions
|
||||
{
|
||||
public class WrongUserOrPasswordException : Exception
|
||||
{
|
||||
public WrongUserOrPasswordException() : base("Nieprawidłowy użytkownik lub hasło.") { }
|
||||
|
||||
public WrongUserOrPasswordException(string message) : base(message) { }
|
||||
|
||||
public WrongUserOrPasswordException(string message, Exception innerException) : base(message, innerException) { }
|
||||
}
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>FirmTracker_Server</RootNamespace>
|
||||
@ -17,22 +17,13 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
|
||||
<PackageReference Include="FluentNHibernate" Version="3.4.0" />
|
||||
<PackageReference Include="FluentValidation" Version="11.10.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
|
||||
<PackageReference Include="FluentNHibernate" Version="3.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.18" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.1.2" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.12" />
|
||||
<PackageReference Include="NHibernate" Version="5.5.2" />
|
||||
<PackageReference Include="NLog" Version="5.3.4" />
|
||||
<PackageReference Include="NLog.Database" Version="5.3.4" />
|
||||
<PackageReference Include="NHibernate" Version="5.5.1" />
|
||||
<PackageReference Include="NSwag.Annotations" Version="14.0.7" />
|
||||
<PackageReference Include="QuestPDF" Version="2024.10.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@ -1,13 +0,0 @@
|
||||
namespace FirmTracker_Server
|
||||
{
|
||||
public static class RolesHelper
|
||||
{
|
||||
public static IEnumerable<string> GetRoles() => new List<string> { Roles.Admin, Roles.User };
|
||||
}
|
||||
|
||||
public static class Roles
|
||||
{
|
||||
public const string Admin = "Admin";
|
||||
public const string User = "User";
|
||||
}
|
||||
}
|
27
JenkinsFile
27
JenkinsFile
@ -1,27 +0,0 @@
|
||||
pipeline {
|
||||
agent any
|
||||
environment {
|
||||
IMG_NAME = 'firmtracker-server'
|
||||
DOCKER_REPO = 'maciejm0101/firmtracker'
|
||||
}
|
||||
stages {
|
||||
stage('build') {
|
||||
steps {
|
||||
script {
|
||||
sh 'docker build -t ${IMG_NAME} .'
|
||||
sh 'docker tag ${IMG_NAME} ${DOCKER_REPO}:${IMG_NAME}'
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('push') {
|
||||
steps {
|
||||
withCredentials([usernamePassword(credentialsId: 'DockerHub-LG', passwordVariable: 'PSWD', usernameVariable: 'LOGIN')]) {
|
||||
script {
|
||||
sh 'echo ${PSWD} | docker login -u ${LOGIN} --password-stdin'
|
||||
sh 'docker push ${DOCKER_REPO}:${IMG_NAME}'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
75
Logger.cs
75
Logger.cs
@ -1,75 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using NLog;
|
||||
using NLog.Config;
|
||||
using NLog.Targets;
|
||||
|
||||
|
||||
namespace IntegrationWithCzech
|
||||
{
|
||||
public static class Logger
|
||||
{
|
||||
private static NLog.Logger log;
|
||||
|
||||
public static void ConfigLog()
|
||||
{
|
||||
var config = new LoggingConfiguration();
|
||||
|
||||
string appDirectory = Directory.GetCurrentDirectory();
|
||||
string configFilePath = Path.Combine(appDirectory, "appsettings.json");
|
||||
var config1 = new ConfigurationBuilder()
|
||||
.AddJsonFile(configFilePath)
|
||||
.Build();
|
||||
var connectionstringsection = config1.GetSection("AppSettings:ConnectionString");
|
||||
|
||||
string connectionString = connectionstringsection.Value;
|
||||
|
||||
// Czech Database Target
|
||||
var LogDbTarget = new DatabaseTarget("logDBTarget")
|
||||
{
|
||||
ConnectionString = connectionString,
|
||||
CommandText = "INSERT INTO CDN.CzechLogTable(Date, Level, Message, Exception) VALUES(@date, @level, @message, @exception)"
|
||||
};
|
||||
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@date", "${longdate}"));
|
||||
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@level", "${level}"));
|
||||
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@message", "${message}"));
|
||||
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@exception", "${exception}"));
|
||||
|
||||
|
||||
var logconsole = new ConsoleTarget("logconsole")
|
||||
{
|
||||
Layout = "${longdate} ${message} ${exception}"
|
||||
};
|
||||
|
||||
|
||||
|
||||
// Adding Rules for Poland Logging
|
||||
config.AddRuleForOneLevel(NLog.LogLevel.Error, LogDbTarget, "PolandLogger");
|
||||
config.AddRuleForAllLevels(logconsole, "PolandLogger");
|
||||
|
||||
LogManager.Configuration = config;
|
||||
log = LogManager.GetLogger("CzechLogger");
|
||||
|
||||
}
|
||||
|
||||
public static void LogInfo(string message)
|
||||
{
|
||||
log?.Info(message);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void Write2CzechLogError(string message, Exception ex = null)
|
||||
{
|
||||
if (ex is null)
|
||||
{
|
||||
log?.Error(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
log?.Error(ex, message);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
using AutoMapper;
|
||||
using FirmTracker_Server.Entities;
|
||||
using FirmTracker_Server.Models;
|
||||
using NHibernate.Type;
|
||||
using NuGet.Packaging.Licenses;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace FirmTracker_Server.Mappings
|
||||
{
|
||||
public class LicenseMappingProfile : Profile
|
||||
{
|
||||
public LicenseMappingProfile()
|
||||
{
|
||||
// CreateMap<License, LicenseDto>();
|
||||
// CreateMap<LicenseDto, License>();
|
||||
// CreateMap<CreateLicenseDto, License>();
|
||||
// CreateMap<LicType, LicTypeDto>();
|
||||
// CreateMap<LicTypeDto, LicType>();
|
||||
CreateMap<UserDto, User>();
|
||||
CreateMap<User, UserDto>();
|
||||
CreateMap<CreateUserDto, User>().ForSourceMember(x => x.Password, y => y.DoNotValidate());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
using FirmTracker_Server.Exceptions;
|
||||
|
||||
namespace FirmTracker_Server.Middleware
|
||||
{
|
||||
public class ErrorHandling : IMiddleware
|
||||
{
|
||||
private readonly ILogger Logger;
|
||||
|
||||
public ErrorHandling(ILogger<ErrorHandling> logger)
|
||||
{
|
||||
Logger = logger;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
|
||||
{
|
||||
try
|
||||
{
|
||||
await next.Invoke(context);
|
||||
}
|
||||
catch (WrongUserOrPasswordException ex)
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
await context.Response.WriteAsync(ex.Message);
|
||||
}
|
||||
catch (PermissionException ex)
|
||||
{
|
||||
context.Response.StatusCode = 403;
|
||||
await context.Response.WriteAsync(ex.Message);
|
||||
}
|
||||
catch (NoResultsException ex)
|
||||
{
|
||||
context.Response.StatusCode = 404;
|
||||
await context.Response.WriteAsync(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Wystąpił nieoczekiwany błąd.");
|
||||
context.Response.StatusCode = 500;
|
||||
await context.Response.WriteAsJsonAsync("Wystąpił nieoczekiwany błąd.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class AddAbsenceDto
|
||||
{
|
||||
public string userEmail { get; set; }
|
||||
public string AbsenceType { get; set; }
|
||||
public DateTime StartTime { get; set; }
|
||||
public DateTime EndTime { get; set; }
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class ChangeUserPasswordDto
|
||||
{
|
||||
public string email { get; set; }
|
||||
public string password { get; set; }
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class CreateUserDto
|
||||
{
|
||||
public required string Login { get; set; }
|
||||
public required string Password { get; set; }
|
||||
public required string Email { get; set; }
|
||||
public required string Role { get; set; }
|
||||
public bool NewEncryption { get; set; } = true;
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using FirmTracker_Server.nHibernate;
|
||||
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class DayDetailsDto
|
||||
{
|
||||
public required string Email { get; set; }
|
||||
public DateTime Date { get; set; }
|
||||
public required string TotalWorkedHours { get; set; }
|
||||
public required List<Workday> WorkdayDetails { get; set; }
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using FirmTracker_Server.nHibernate;
|
||||
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class DayDetailsLoggedUserDto
|
||||
{
|
||||
public int UserId { get; set; }
|
||||
public DateTime Date { get; set; }
|
||||
public string TotalWorkedHours { get; set; }
|
||||
public List<Workday> WorkdayDetails { get; set; }
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using FirmTracker_Server.Controllers;
|
||||
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class EmployeeDto
|
||||
{
|
||||
public virtual int Id { get; set; }
|
||||
public virtual string email { get; set; }
|
||||
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class LoginDto
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public string Password { get; set; }
|
||||
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class UpdateAbsenceDto
|
||||
{
|
||||
public string NewAbsenceType { get; set; } // e.g., "Sick", "Vacation", etc.
|
||||
public DateTime NewStartTime { get; set; }
|
||||
public DateTime NewEndTime { get; set; }
|
||||
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class UpdatePasswordDto
|
||||
{
|
||||
public string email { get; set; }
|
||||
public string oldPassword { get; set; }
|
||||
public string newPassword { get; set; }
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace FirmTracker_Server.Models
|
||||
{
|
||||
public class UserDto
|
||||
{
|
||||
[Required]
|
||||
[MaxLength(16)]
|
||||
public string Login { get; set; }
|
||||
|
||||
[Required]
|
||||
[EmailAddress]
|
||||
public string Email { get; set; }
|
||||
|
||||
[Required]
|
||||
[MinLength(8, ErrorMessage = "Password must be at least 8 characters long.")]
|
||||
[MaxLength(100, ErrorMessage = "Password cannot be longer than 100 characters.")]
|
||||
[RegularExpression(@"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$", ErrorMessage = "Password must contain at least one uppercase letter, one lowercase letter, one digit, and one special character.")]
|
||||
public string Password { get; set; }
|
||||
|
||||
}
|
||||
}
|
@ -1,31 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using FirmTracker_Server.Entities;
|
||||
using System;
|
||||
|
||||
namespace YourNamespace.Models
|
||||
{
|
||||
public class Workday
|
||||
{
|
||||
public virtual int Id { get; set; }
|
||||
public virtual DateTime? StartTime { get; set; }
|
||||
public virtual DateTime? EndTime { get; set; }
|
||||
public TimeSpan WorkedHours { get; set; }
|
||||
// Many-to-One relationship to the User entity
|
||||
public virtual User User { get; set; }
|
||||
}
|
||||
}
|
94
Program.cs
94
Program.cs
@ -15,26 +15,19 @@
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using NHibernate;
|
||||
using NHibernate.Cfg;
|
||||
using NHibernate.Dialect;
|
||||
using NHibernate.Driver;
|
||||
using FirmTracker_Server.Controllers;
|
||||
using FirmTracker_Server.nHibernate.Products;
|
||||
using FirmTracker_Server.nHibernate;
|
||||
using FirmTracker_Server.Utilities.Converters;
|
||||
using FirmTracker_Server.Utilities.Swagger;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using AutoMapper;
|
||||
using System.Text;
|
||||
using FirmTracker_Server.Entities;
|
||||
using FirmTracker_Server.Middleware;
|
||||
using FirmTracker_Server.Services;
|
||||
using System.Reflection;
|
||||
using FirmTracker_Server.Mappings;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
|
||||
|
||||
|
||||
namespace FirmTracker_Server
|
||||
{
|
||||
internal static class Program
|
||||
public class Program
|
||||
{
|
||||
|
||||
public static void Main(string[] args)
|
||||
@ -52,7 +45,7 @@ namespace FirmTracker_Server
|
||||
var connectionstringsection = config.GetSection("AppSettings:ConnectionString");
|
||||
|
||||
connectionString = connectionstringsection.Value;
|
||||
//Console.WriteLine(connectionString);
|
||||
|
||||
SessionFactory.Init(connectionString);
|
||||
}
|
||||
else
|
||||
@ -60,39 +53,28 @@ namespace FirmTracker_Server
|
||||
Console.WriteLine($"The configuration file '{configFilePath}' was not found.");
|
||||
}
|
||||
|
||||
//TestClass test = new TestClass();
|
||||
// test.AddTestProduct();
|
||||
QuestPDF.Settings.License = QuestPDF.Infrastructure.LicenseType.Community;
|
||||
//builder.Services.AddDataProtection().DisableAutomaticKeyGeneration();
|
||||
TestClass test = new TestClass();
|
||||
test.AddTestProduct();
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowSpecificOrigin",
|
||||
policy => policy.WithOrigins(
|
||||
"http://localhost:3000",
|
||||
"https://firmtracker-server.onrender.com",
|
||||
"https://firmtracker.netlify.app"
|
||||
)
|
||||
policy => policy.WithOrigins("http://localhost:3000")
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod());
|
||||
});
|
||||
builder.Services.ConfigureAutoMapper();
|
||||
builder.Services.ConfigureServiceInjection();
|
||||
builder.Services.AddControllers()
|
||||
.AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
|
||||
});
|
||||
;
|
||||
builder.ConfigureAuthentication();
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SchemaFilter<SwaggerDateTimeSchemaFilter>();
|
||||
});
|
||||
|
||||
|
||||
|
||||
var app = builder.Build();
|
||||
var configSwagger = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
@ -101,9 +83,9 @@ namespace FirmTracker_Server
|
||||
|
||||
|
||||
var port = configSwagger.GetValue<int>("Port", 5075);
|
||||
// var port2 = configSwagger.GetValue<int>("Port", 7039);
|
||||
var port2 = configSwagger.GetValue<int>("Port", 7039);
|
||||
app.Urls.Add($"http://*:{port}");
|
||||
// app.Urls.Add($"https://*:{port2}");
|
||||
app.Urls.Add($"https://*:{port2}");
|
||||
|
||||
try
|
||||
{
|
||||
@ -114,19 +96,17 @@ namespace FirmTracker_Server
|
||||
c.RoutePrefix = "swagger";
|
||||
});
|
||||
Console.WriteLine("uruchomiono swaggera");
|
||||
// app.UseHttpsRedirection();
|
||||
app.UseHttpsRedirection();
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
|
||||
}
|
||||
|
||||
// app.UseHttpsRedirection();
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseCors("AllowSpecificOrigin");
|
||||
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
|
||||
@ -137,47 +117,5 @@ namespace FirmTracker_Server
|
||||
|
||||
app.Run();
|
||||
}
|
||||
private static void ConfigureAuthentication(this WebApplicationBuilder builder)
|
||||
{
|
||||
var authenticationSettings = new Authentication.AuthenticationSettings();
|
||||
builder.Configuration.GetSection("TokenConfig").Bind(authenticationSettings);
|
||||
builder.Services.AddAuthentication(option => {
|
||||
option.DefaultAuthenticateScheme = "Bearer";
|
||||
option.DefaultScheme = "Bearer";
|
||||
option.DefaultChallengeScheme = "Bearer";
|
||||
}).AddJwtBearer(options => {
|
||||
options.RequireHttpsMetadata = false;
|
||||
options.SaveToken = true;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = authenticationSettings.JwtIssuer,
|
||||
ValidAudience = authenticationSettings.JwtIssuer,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationSettings.JwtSecKey)),
|
||||
};
|
||||
});
|
||||
builder.Services.AddSingleton(authenticationSettings);
|
||||
}
|
||||
private static void ConfigureAutoMapper(this IServiceCollection services)
|
||||
{
|
||||
var mapperConfig = new MapperConfiguration(mc => {
|
||||
mc.AddProfile<LicenseMappingProfile>();
|
||||
// mc.AddProfile<PayLinkerMappingProfile>();
|
||||
});
|
||||
var mapper = mapperConfig.CreateMapper();
|
||||
services.AddSingleton(mapper);
|
||||
services.AddAutoMapper(Assembly.GetExecutingAssembly());
|
||||
}
|
||||
private static void ConfigureServiceInjection(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<IUserService, UserService>();
|
||||
services.AddScoped<ErrorHandling>();
|
||||
services.AddScoped<IPasswordHasher<User>, PasswordHasher<User>>();
|
||||
services.AddScoped<IExpenseRepository, ExpenseRepository>();
|
||||
services.AddScoped<ITransactionRepository, TransactionRepository>();
|
||||
services.AddScoped<IProductRepository, ProductRepository>();
|
||||
// services.AddScoped<IWorkdayRepository, WorkdayRepository>();
|
||||
services.AddMvc();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,220 +0,0 @@
|
||||
using AutoMapper;
|
||||
using FirmTracker_Server.Authentication;
|
||||
using FirmTracker_Server.Entities;
|
||||
using FirmTracker_Server.Exceptions;
|
||||
using FirmTracker_Server.Models;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Globalization;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using FirmTracker_Server.nHibernate;
|
||||
using NHibernate;
|
||||
using NHibernate.Criterion;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using NHibernate.Type;
|
||||
|
||||
namespace FirmTracker_Server.Services
|
||||
{
|
||||
public interface IUserService
|
||||
{
|
||||
UserDto GetById(int id);
|
||||
int AddUser(CreateUserDto dto);
|
||||
string CreateTokenJwt(LoginDto dto);
|
||||
IEnumerable<string> GetAllUserEmails();
|
||||
bool UpdatePassword(UpdatePasswordDto dto);
|
||||
bool ChangeUserPassword(ChangeUserPasswordDto dto);
|
||||
IList<EmployeeDto> GetAllUsers();
|
||||
|
||||
}
|
||||
|
||||
public class UserService : IUserService
|
||||
{
|
||||
private readonly IMapper Mapper;
|
||||
private readonly IPasswordHasher<User> PasswordHasher;
|
||||
private readonly AuthenticationSettings AuthenticationSettings;
|
||||
|
||||
public UserService(IMapper mapper, IPasswordHasher<User> passwordHasher, AuthenticationSettings authenticationSettings)
|
||||
{
|
||||
Mapper = mapper;
|
||||
PasswordHasher = passwordHasher;
|
||||
AuthenticationSettings = authenticationSettings;
|
||||
|
||||
}
|
||||
public IList<EmployeeDto> GetAllUsers()
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
var users = session.Query<User>()
|
||||
.Select(u => new EmployeeDto
|
||||
{
|
||||
Id = u.UserId,
|
||||
email = u.Email
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return users;
|
||||
}
|
||||
}
|
||||
public bool ChangeUserPassword(ChangeUserPasswordDto dto)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transaction = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = session.Query<User>().FirstOrDefault(u => u.Email == dto.email);
|
||||
if (user == null)
|
||||
{
|
||||
throw new Exception("User not found.");
|
||||
}
|
||||
|
||||
user.PassHash = PasswordHasher.HashPassword(user, dto.password);
|
||||
session.Update(user);
|
||||
transaction.Commit();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
public bool UpdatePassword(UpdatePasswordDto dto)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transaction = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = session.Query<User>().FirstOrDefault(u => u.Email == dto.email);
|
||||
if (user == null)
|
||||
{
|
||||
throw new Exception("User not found.");
|
||||
}
|
||||
|
||||
var result = PasswordHasher.VerifyHashedPassword(user, user.PassHash, dto.oldPassword);
|
||||
if (result != PasswordVerificationResult.Success)
|
||||
{
|
||||
throw new Exception("Invalid current password.");
|
||||
}
|
||||
|
||||
user.PassHash = PasswordHasher.HashPassword(user, dto.newPassword);
|
||||
session.Update(user);
|
||||
transaction.Commit();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
public IEnumerable<string> GetAllUserEmails()
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
var users = session.Query<User>().Select(u => u.Email).ToList();
|
||||
return users;
|
||||
}
|
||||
}
|
||||
public UserDto GetById(int id)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
var user = session.Get<User>(id);
|
||||
return user == null ? null : Mapper.Map<UserDto>(user);
|
||||
}
|
||||
}
|
||||
|
||||
public int AddUser(CreateUserDto dto)
|
||||
{
|
||||
var user = Mapper.Map<User>(dto);
|
||||
|
||||
user.PassHash = dto.NewEncryption ? PasswordHasher.HashPassword(user, dto.Password) : PasswordHasher.HashPassword(user, dto.Password);
|
||||
user.Role = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dto.Role.ToLower());
|
||||
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transaction = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
session.Save(user);
|
||||
transaction.Commit();
|
||||
return user.UserId;
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string CreateTokenJwt(LoginDto dto)
|
||||
{
|
||||
User user = null;
|
||||
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
if (!string.IsNullOrEmpty(dto.Email))
|
||||
{
|
||||
user = session.Query<User>().FirstOrDefault(x => x.Email == dto.Email);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
|
||||
}
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
|
||||
}
|
||||
|
||||
if (user.NewEncryption)
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.WriteLine(PasswordHasher.HashPassword(user, user.PassHash));
|
||||
var ready = PasswordHasher.VerifyHashedPassword(user, user.PassHash, dto.Password);
|
||||
if (ready == 0)
|
||||
{
|
||||
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw new WrongUserOrPasswordException("Wystąpił błąd podczas logowania");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var ready = PasswordVerificationResult.Failed;
|
||||
if (PasswordHasher.VerifyHashedPassword(user, user.PassHash, dto.Password) == PasswordVerificationResult.Success) { ready = PasswordVerificationResult.Success; } //PasswordHasher.VerifyHashedPassword(user, user.PassHash, dto.Password);
|
||||
if (ready == PasswordVerificationResult.Failed)
|
||||
{
|
||||
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var claims = new List<Claim>() {
|
||||
new(ClaimTypes.NameIdentifier, user.UserId.ToString()),
|
||||
new(ClaimTypes.Role, user.Role)
|
||||
};
|
||||
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AuthenticationSettings.JwtSecKey));
|
||||
var credential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
var expires = DateTime.Now.AddDays(AuthenticationSettings.JwtExpireDays);
|
||||
var token = new JwtSecurityToken(AuthenticationSettings.JwtIssuer, AuthenticationSettings.JwtIssuer, claims, expires: expires, signingCredentials: credential);
|
||||
var finalToken = new JwtSecurityTokenHandler();
|
||||
return finalToken.WriteToken(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
236
TestClass.cs
Normal file
236
TestClass.cs
Normal file
@ -0,0 +1,236 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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
|
||||
{
|
||||
public class TestClass
|
||||
{
|
||||
public static Product CreateProduct(string name, string description, decimal price, int type, int availability)
|
||||
{
|
||||
return new Product
|
||||
{
|
||||
Name = name,
|
||||
Description = description,
|
||||
Price = price,
|
||||
Type = type,
|
||||
Availability = availability
|
||||
};
|
||||
}
|
||||
public void AddTestProduct()
|
||||
{
|
||||
// SessionFactory.Init(ConnectionString);
|
||||
|
||||
|
||||
var product2 = new nHibernate.Products.Product
|
||||
{
|
||||
Name = "Dostawa",
|
||||
Description = "usługa dostawy",
|
||||
Price = 7.50m,
|
||||
Type = 0,
|
||||
Availability = 0
|
||||
};
|
||||
|
||||
var products = new List<Product>
|
||||
{
|
||||
CreateProduct("Tarta_truskawka", "produkt", 31.99m, 1, 10),
|
||||
CreateProduct("Tarta_czekolada", "produkt", 30.99m, 1, 10),
|
||||
CreateProduct("Tarta_agrest", "produkt", 32.90m, 1, 8),
|
||||
CreateProduct("Tarta_pistacja", "produkt", 35.99m, 1, 12),
|
||||
CreateProduct("Tarta_karmel", "produkt", 32.00m, 1, 12),
|
||||
CreateProduct("Rolada_beza", "produkt", 21.00m, 1, 5),
|
||||
CreateProduct("Rolada_róża", "produkt", 21.90m, 1, 10),
|
||||
CreateProduct("Kostka_truskawka", "produkt", 12.00m, 1, 11),
|
||||
CreateProduct("Kostka_lemonCurd", "produkt", 13.99m, 1, 13),
|
||||
CreateProduct("Kostka_hiszpańska", "produkt", 11.99m, 1, 8),
|
||||
CreateProduct("Kostka_wiosenna", "produkt", 11.99m, 1, 5),
|
||||
CreateProduct("Kostka_jabłka", "produkt", 12.00m, 1, 5),
|
||||
CreateProduct("Kostka_porzeczka", "produkt", 12.99m, 1, 5),
|
||||
CreateProduct("Kostka_królewska", "produkt", 13.50m, 1, 5),
|
||||
CreateProduct("Kostka_czekolada", "produkt", 14.50m, 1, 10),
|
||||
CreateProduct("Kostka_wiśnia", "produkt", 12.50m, 1, 5),
|
||||
CreateProduct("Kostka_beza", "produkt", 13.50m, 1, 20),
|
||||
CreateProduct("Kostka_leśna", "produkt", 12.00m, 1, 20),
|
||||
CreateProduct("Kostka_kawowa", "produkt", 12.00m, 1, 10),
|
||||
CreateProduct("Kostka_galaretka", "produkt", 12.50m, 1, 25),
|
||||
CreateProduct("Kostka_firmowa", "produkt", 12.50m, 1, 5),
|
||||
CreateProduct("Sernik_wiśnia", "produkt", 33.00m, 1, 6),
|
||||
CreateProduct("Sernik_truskawka", "produkt", 31.00m, 1, 5),
|
||||
CreateProduct("Sernik_pistacja", "produkt", 38.90m, 1, 5),
|
||||
CreateProduct("Sernik_fantazja", "produkt", 33.00m, 1, 7),
|
||||
CreateProduct("Sernik_rafaello", "produkt", 33.00m, 1, 5),
|
||||
CreateProduct("Sernik_nutella", "produkt", 35.50m, 1, 6),
|
||||
CreateProduct("Sernik_mango", "produkt", 33.00m, 1, 5),
|
||||
CreateProduct("Sernik_rabarbar", "produkt", 37.99m, 1, 5),
|
||||
CreateProduct("Sernik_biszkopt", "produkt", 39.00m, 1, 11),
|
||||
CreateProduct("Tartaletka", "produkt", 13.20m, 1, 30),
|
||||
CreateProduct("Strudel_jabłko", "produkt", 29.00m, 1, 20),
|
||||
CreateProduct("Placek_rabarbar", "produkt", 24.00m, 1, 18),
|
||||
CreateProduct("Placek_jogurt", "produkt", 23.00m, 1, 13),
|
||||
CreateProduct("Placek_śliwka", "produkt", 22.00m, 1, 14),
|
||||
CreateProduct("Placek_maślany", "produkt", 18.00m, 1,11),
|
||||
CreateProduct("Keks", "produkt", 22.00m, 1,11),
|
||||
CreateProduct("Babka_drożdżowa", "produkt", 16.00m, 1,11),
|
||||
CreateProduct("Pączek_pistacja", "produkt", 8.00m, 1,11),
|
||||
CreateProduct("Pączek_marmolada", "produkt", 3.00m, 1,11),
|
||||
CreateProduct("Pączek_nutella", "produkt", 4.50m, 1,11),
|
||||
CreateProduct("Pączek_rafaello", "produkt", 4.50m, 1,11),
|
||||
CreateProduct("Pączek_róża", "produkt", 4.00m, 1,11),
|
||||
CreateProduct("Ekler", "produkt", 3.00m, 1,11),
|
||||
CreateProduct("Ekler_słony_karmel", "produkt", 5.00m, 1,11),
|
||||
CreateProduct("Ptyś", "produkt", 4.00m, 1,11),
|
||||
CreateProduct("Drożdżówka_ser", "produkt", 4.00m, 1,11),
|
||||
CreateProduct("Drożdżówka_rabarbar", "produkt", 5.00m, 1,11),
|
||||
CreateProduct("Drożdżówka_żurawina", "produkt", 5.00m, 1,11),
|
||||
CreateProduct("Drożdżówka_kruszonka", "produkt", 4.00m, 1,11),
|
||||
CreateProduct("Drożdżówka_budyń", "produkt", 5.00m, 1,11),
|
||||
CreateProduct("Jagodzianka", "produkt", 6.00m, 1,11),
|
||||
|
||||
|
||||
};
|
||||
|
||||
var transaction1 = new Transaction
|
||||
{
|
||||
Date = DateTime.Now.AddDays(-2),
|
||||
Description = "zamówienie telefon",
|
||||
Discount = 5,
|
||||
EmployeeId = 1,
|
||||
PaymentType = "Karta kredytowa",
|
||||
};
|
||||
var transaction2 = new Transaction
|
||||
{
|
||||
Date = DateTime.Now.AddDays(-3),
|
||||
Description = "sprzedaż - kasa",
|
||||
Discount = 30,
|
||||
EmployeeId = 2,
|
||||
PaymentType = "Gotówka",
|
||||
};
|
||||
var transaction3 = new Transaction
|
||||
{
|
||||
Date = DateTime.Now,
|
||||
Description = "sprzedaż - kasa",
|
||||
Discount = 15,
|
||||
EmployeeId = 1,
|
||||
PaymentType = "BLIK",
|
||||
};
|
||||
var transaction4 = new Transaction
|
||||
{
|
||||
Date = DateTime.Now,
|
||||
Description = "zamówienie",
|
||||
Discount = 15,
|
||||
EmployeeId = 1,
|
||||
PaymentType = "BLIK",
|
||||
};
|
||||
|
||||
var expense1 = new Expense
|
||||
{
|
||||
Date = DateTime.Now,
|
||||
Value = 7999.9m,
|
||||
Description = "zakup maszyny do lodów FZ/2/6/2024"
|
||||
};
|
||||
var expense2 = new Expense
|
||||
{
|
||||
Date = DateTime.Now,
|
||||
Value = 990.99m,
|
||||
Description = "naprawa pieca - 25.05.2024"
|
||||
};
|
||||
var expense3 = new Expense
|
||||
{
|
||||
Date = DateTime.Now,
|
||||
Value = 1800.00m,
|
||||
Description = "zakup składników "
|
||||
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
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);
|
||||
foreach(var clientProduct in products)
|
||||
{
|
||||
productCrud.AddProduct(clientProduct);
|
||||
}
|
||||
transactionCrud.AddTransaction(transaction1);
|
||||
transactionCrud.AddTransaction(transaction2);
|
||||
transactionCrud.AddTransaction(transaction3);
|
||||
transactionCrud.AddTransaction(transaction4);
|
||||
expenseCrud.AddExpense(expense1);
|
||||
expenseCrud.AddExpense(expense2);
|
||||
expenseCrud.AddExpense(expense3);
|
||||
|
||||
List<TransactionProduct> testTransactionProducts = new List<TransactionProduct> {
|
||||
new TransactionProduct { ProductID =17, Quantity = 10 },
|
||||
new TransactionProduct { ProductID = 14, Quantity = 1 },
|
||||
new TransactionProduct { ProductID = 1, Quantity = 0 },
|
||||
};
|
||||
foreach (var transactionProduct in testTransactionProducts)
|
||||
{
|
||||
transactionCrud.AddTransactionProductToTransaction(transaction1.Id, transactionProduct);
|
||||
|
||||
}
|
||||
|
||||
List<TransactionProduct> testTransactionProducts2 = new List<TransactionProduct>
|
||||
{
|
||||
new TransactionProduct { ProductID = 28, Quantity=5},
|
||||
new TransactionProduct { ProductID = 22, Quantity=5}
|
||||
};
|
||||
foreach (var transactionProduct in testTransactionProducts2)
|
||||
{
|
||||
transactionCrud.AddTransactionProductToTransaction(transaction2.Id, transactionProduct);
|
||||
|
||||
}
|
||||
|
||||
List<TransactionProduct> testTransactionProducts3 = new List<TransactionProduct>
|
||||
{
|
||||
new TransactionProduct { ProductID = 3, Quantity=9},
|
||||
new TransactionProduct { ProductID = 2, Quantity=1}
|
||||
};
|
||||
foreach (var transactionProduct in testTransactionProducts3)
|
||||
{
|
||||
transactionCrud.AddTransactionProductToTransaction(transaction3.Id, transactionProduct);
|
||||
|
||||
}
|
||||
List<TransactionProduct> testTransactionProducts4 = new List<TransactionProduct>
|
||||
{
|
||||
new TransactionProduct { ProductID = 33, Quantity=12},
|
||||
new TransactionProduct { ProductID = 12, Quantity=1}
|
||||
};
|
||||
foreach (var transactionProduct in testTransactionProducts4)
|
||||
{
|
||||
transactionCrud.AddTransactionProductToTransaction(transaction4.Id, transactionProduct);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
29
appsettings.json
Normal file
29
appsettings.json
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"AppSettings": {
|
||||
"ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;"
|
||||
},
|
||||
"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"
|
||||
|
||||
}
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
/*
|
||||
* This file is part of FirmTracker - Server.
|
||||
*
|
||||
* FirmTracker - Server is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* FirmTracker - Server is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace FirmTracker_Server.nHibernate
|
||||
{
|
||||
public class LogsMapping
|
||||
{
|
||||
public virtual int Id { get; set; }
|
||||
public virtual DateTime Date { get; set; }
|
||||
public virtual string Level { get; set; }
|
||||
public virtual string Message { get; set; }
|
||||
public virtual string Exception { get; set; }
|
||||
}
|
||||
}
|
@ -1,239 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Transactions;
|
||||
using FirmTracker_Server.nHibernate.Expenses;
|
||||
using FirmTracker_Server.nHibernate.Products;
|
||||
using FirmTracker_Server.nHibernate.Transactions;
|
||||
using NHibernate;
|
||||
using Transaction = FirmTracker_Server.nHibernate.Transactions.Transaction;
|
||||
|
||||
namespace FirmTracker_Server.nHibernate
|
||||
{
|
||||
public interface IProductRepository
|
||||
{
|
||||
Product GetProduct(int id);
|
||||
}
|
||||
|
||||
public interface IExpenseRepository
|
||||
{
|
||||
List<Expense> GetAllExpenses();
|
||||
Expense GetExpense(int expenseId);
|
||||
void AddExpense(Expense expense);
|
||||
void UpdateExpense(Expense expense);
|
||||
void DeleteExpense(int expenseId);
|
||||
}
|
||||
public interface ITransactionRepository
|
||||
{
|
||||
List<Transaction> GetAllTransactions();
|
||||
Transaction GetTransaction(int transactionId);
|
||||
List<Transaction> GetTransactionsByDateRange(DateTime startDate, DateTime endDate);
|
||||
List<TransactionProduct> GetTransactionProducts(int transactionId);
|
||||
void AddTransaction(Transaction transaction);
|
||||
void UpdateTransaction(Transaction transaction);
|
||||
void DeleteTransaction(int transactionId);
|
||||
List<TransactionProduct> GetTransactionProductsForTransactions(List<int> transactionIds);
|
||||
}
|
||||
public class ProductRepository : IProductRepository
|
||||
{
|
||||
public Product GetProduct(int id)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Get<Product>(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class TransactionRepository : ITransactionRepository
|
||||
{
|
||||
// Retrieve all transactions
|
||||
public List<Transaction> GetAllTransactions()
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Query<Transaction>().ToList();
|
||||
}
|
||||
}
|
||||
public List<TransactionProduct> GetTransactionProductsForTransactions(List<int> transactionIds)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Query<TransactionProduct>()
|
||||
.Where(tp => transactionIds.Contains(tp.TransactionId))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public Transaction GetTransaction(int transactionId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Get<Transaction>(transactionId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public List<Transaction> GetTransactionsByDateRange(DateTime startDate, DateTime endDate)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Query<Transaction>()
|
||||
.Where(t => t.Date >= startDate && t.Date <= endDate)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public List<TransactionProduct> GetTransactionProducts(int transactionId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Query<TransactionProduct>()
|
||||
.Where(tp => tp.TransactionId == transactionId)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void AddTransaction(Transaction transaction)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transactionScope = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
session.Save(transaction);
|
||||
transactionScope.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transactionScope.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update an existing transaction
|
||||
public void UpdateTransaction(Transaction transaction)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transactionScope = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
session.Update(transaction);
|
||||
transactionScope.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transactionScope.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void DeleteTransaction(int transactionId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transactionScope = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
var transaction = session.Get<Transaction>(transactionId);
|
||||
if (transaction != null)
|
||||
{
|
||||
session.Delete(transaction);
|
||||
}
|
||||
transactionScope.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transactionScope.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public class ExpenseRepository : IExpenseRepository
|
||||
{
|
||||
// Retrieve all expenses
|
||||
public List<Expense> GetAllExpenses()
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Query<Expense>().ToList();
|
||||
}
|
||||
}
|
||||
|
||||
// Retrieve a specific expense by ID
|
||||
public Expense GetExpense(int expenseId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
return session.Get<Expense>(expenseId);
|
||||
}
|
||||
}
|
||||
|
||||
// Add a new expense
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update an existing 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete an expense by ID
|
||||
public void DeleteExpense(int expenseId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transaction = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
var expense = session.Get<Expense>(expenseId);
|
||||
if (expense != null)
|
||||
{
|
||||
session.Delete(expense);
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -53,13 +53,9 @@ namespace FirmTracker_Server.nHibernate
|
||||
.AddFromAssemblyOf<Expenses.ExpenseMapping>()
|
||||
.AddFromAssemblyOf<Reports.ReportMapping>()
|
||||
.AddFromAssemblyOf<Reports.ReportTransactionMapping>()
|
||||
.AddFromAssemblyOf<Reports.ReportExpenseMapping>()
|
||||
.AddFromAssemblyOf<LogsMapping>()
|
||||
.AddFromAssemblyOf<UserMapping>()
|
||||
.AddFromAssemblyOf<WorkdayMapping>();
|
||||
|
||||
}) //SchemaExport .Create //żeby tworzyło za każdym razem
|
||||
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true)) //SchemaUpdate . Execute dla only update
|
||||
.AddFromAssemblyOf<Reports.ReportExpenseMapping>();
|
||||
})
|
||||
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update
|
||||
.BuildSessionFactory();
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +0,0 @@
|
||||
using FluentNHibernate.Mapping;
|
||||
using FirmTracker_Server.Entities;
|
||||
|
||||
public class UserMapping : ClassMap<User>
|
||||
{
|
||||
public UserMapping()
|
||||
{
|
||||
Table("Users");
|
||||
|
||||
Id(x => x.UserId);
|
||||
Map(x => x.Email);
|
||||
Map(x => x.PassHash);
|
||||
Map(x => x.Role);
|
||||
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
using FirmTracker_Server.Entities;
|
||||
|
||||
namespace FirmTracker_Server.nHibernate
|
||||
{
|
||||
public class Workday
|
||||
{
|
||||
public virtual int Id { get; set; }
|
||||
public virtual DateTime StartTime { get; set; }
|
||||
public virtual DateTime? EndTime { get; set; } // Nullable EndTime, if not finished
|
||||
public virtual TimeSpan WorkedHours
|
||||
{
|
||||
get
|
||||
{
|
||||
// Calculate the worked hours, using 5 PM as the fallback for the EndTime
|
||||
return (EndTime ?? DateTime.Today.AddHours(24)) - StartTime;
|
||||
}
|
||||
set
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
public virtual User User { get; set; }
|
||||
public virtual string Absence { get; set; }
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
using FluentNHibernate.Mapping;
|
||||
namespace FirmTracker_Server.nHibernate
|
||||
{
|
||||
public class WorkdayMapping : ClassMap<Workday>
|
||||
{
|
||||
public WorkdayMapping()
|
||||
{
|
||||
Table("Workdays"); // Make sure the table name matches the one in the database
|
||||
Id(x => x.Id).GeneratedBy.Identity();
|
||||
Map(x => x.StartTime);
|
||||
Map(x => x.EndTime);
|
||||
References(x => x.User).Column("UserId"); // Assuming Workday is related to a User
|
||||
Map(x => x.Absence);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,263 +0,0 @@
|
||||
using FirmTracker_Server.Entities;
|
||||
using FirmTracker_Server.nHibernate;
|
||||
using static NHibernate.Engine.Query.CallableParser;
|
||||
using FirmTracker_Server.Models;
|
||||
|
||||
public class WorkdayRepository
|
||||
{
|
||||
public void StartWorkday(int userId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transaction = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check if there is an existing workday that hasn't been stopped yet
|
||||
var ongoingWorkday = session.Query<Workday>()
|
||||
.Where(w => w.User.UserId == userId && w.EndTime == null)
|
||||
.OrderByDescending(w => w.StartTime)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (ongoingWorkday != null)
|
||||
{
|
||||
// If there is an ongoing workday, throw an exception or return a specific message
|
||||
throw new Exception("Previous workday wasn't stopped yet.");
|
||||
}
|
||||
|
||||
// Fetch the user entity
|
||||
var user = session.Get<User>(userId);
|
||||
if (user == null) throw new Exception("User not found");
|
||||
|
||||
// Create a new workday if there is no ongoing one
|
||||
var workday = new Workday
|
||||
{
|
||||
StartTime = DateTime.Now,
|
||||
User = user,
|
||||
Absence = ""
|
||||
};
|
||||
|
||||
session.Save(workday);
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw new Exception("An error occurred while starting the workday", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AddAbsence(int userId, string absenceType, DateTime startTime, DateTime endTime)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transaction = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = session.Get<User>(userId);
|
||||
if (user == null) throw new Exception("User not found");
|
||||
|
||||
// Create a new workday entry for the absence
|
||||
var workday = new Workday
|
||||
{
|
||||
User = user,
|
||||
StartTime = startTime,
|
||||
EndTime = endTime,
|
||||
Absence = absenceType // Store the absence type as a string
|
||||
};
|
||||
|
||||
session.Save(workday);
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw new Exception("An error occurred while adding the absence", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool StopWorkday(int userId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var transaction = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
var workday = session.Query<Workday>()
|
||||
.Where(w => w.User.UserId == userId && w.EndTime == null)
|
||||
.OrderByDescending(w => w.StartTime)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (workday == null)
|
||||
{
|
||||
return false; // No ongoing workday found
|
||||
}
|
||||
|
||||
workday.EndTime = DateTime.Now;
|
||||
|
||||
session.Update(workday);
|
||||
transaction.Commit();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw new Exception("An error occurred while stopping the workday", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<Workday> GetWorkdaysByUser(string email)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
try
|
||||
{
|
||||
var workdays = session.Query<Workday>()
|
||||
.Where(w => w.User.Email == email)
|
||||
.Select(w => new Workday
|
||||
{
|
||||
Id = w.Id,
|
||||
StartTime = w.StartTime,
|
||||
EndTime = w.EndTime ?? DateTime.Today.AddHours(17),
|
||||
WorkedHours = (w.EndTime ?? DateTime.Today.AddHours(17)) - w.StartTime,
|
||||
Absence = w.Absence,
|
||||
})
|
||||
.ToList();
|
||||
|
||||
foreach (var workday in workdays)
|
||||
{
|
||||
if(workday.Absence!="")
|
||||
{
|
||||
workday.WorkedHours = TimeSpan.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
return workdays;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("An error occurred while fetching workdays", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
public DayDetailsDto GetDayDetails(string mail, DateTime date)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
try
|
||||
{
|
||||
// Fetch workdays for the specified user on the given date
|
||||
var startOfDay = date.Date;
|
||||
var endOfDay = startOfDay.AddDays(1);
|
||||
|
||||
var workdays = session.Query<Workday>()
|
||||
.Where(w => w.User.Email == mail && w.StartTime >= startOfDay && w.StartTime < endOfDay)
|
||||
.Select(w => new Workday
|
||||
{
|
||||
StartTime = w.StartTime,
|
||||
EndTime = w.EndTime ?? DateTime.Today.AddHours(17),
|
||||
Absence = w.Absence,
|
||||
})
|
||||
.ToList();
|
||||
|
||||
TimeSpan totalWorkedHours = TimeSpan.Zero;
|
||||
|
||||
// Calculate total worked hours and adjust if there's an absence
|
||||
foreach (var workday in workdays)
|
||||
{
|
||||
if (string.IsNullOrEmpty(workday.Absence))
|
||||
{
|
||||
totalWorkedHours += workday.WorkedHours;
|
||||
}
|
||||
}
|
||||
|
||||
return new DayDetailsDto
|
||||
{
|
||||
Email = mail,
|
||||
Date = date,
|
||||
TotalWorkedHours = totalWorkedHours.ToString(@"hh\:mm\:ss"),
|
||||
WorkdayDetails = workdays
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("An error occurred while fetching the day's details", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
public DayDetailsLoggedUserDto GetDayDetailsForLoggedUser(int userId, DateTime date)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
try
|
||||
{
|
||||
// Fetch workdays for the specified user on the given date
|
||||
var startOfDay = date.Date;
|
||||
var endOfDay = startOfDay.AddDays(1);
|
||||
|
||||
var workdays = session.Query<Workday>()
|
||||
.Where(w => w.User.UserId == userId && w.StartTime >= startOfDay && w.StartTime < endOfDay)
|
||||
.Select(w => new Workday
|
||||
{
|
||||
StartTime = w.StartTime,
|
||||
EndTime = w.EndTime ?? DateTime.Today.AddHours(17),
|
||||
Absence = w.Absence,
|
||||
})
|
||||
.ToList();
|
||||
|
||||
TimeSpan totalWorkedHours = TimeSpan.Zero;
|
||||
|
||||
// Calculate total worked hours and adjust if there's an absence
|
||||
foreach (var workday in workdays)
|
||||
{
|
||||
if (string.IsNullOrEmpty(workday.Absence))
|
||||
{
|
||||
totalWorkedHours += workday.WorkedHours;
|
||||
}
|
||||
}
|
||||
|
||||
return new DayDetailsLoggedUserDto
|
||||
{
|
||||
UserId = userId,
|
||||
Date = date,
|
||||
TotalWorkedHours = totalWorkedHours.ToString(@"hh\:mm\:ss"),
|
||||
WorkdayDetails = workdays
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("An error occurred while fetching the day's details", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
public List<Workday> GetWorkdaysByLoggedUser(string userId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
{
|
||||
try
|
||||
{
|
||||
int parsedUserId = Int32.Parse(userId);
|
||||
var workdays = session.Query<Workday>()
|
||||
.Where(w => w.User.UserId == parsedUserId)
|
||||
.Select(w => new Workday
|
||||
{
|
||||
Id = w.Id,
|
||||
StartTime = w.StartTime,
|
||||
EndTime = w.EndTime ?? DateTime.Today.AddHours(17),
|
||||
WorkedHours = (w.EndTime ?? DateTime.Today.AddHours(17)) - w.StartTime,
|
||||
Absence = w.Absence,
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return workdays;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("An error occurred while fetching workdays", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -94,10 +94,6 @@ namespace FirmTracker_Server.nHibernate.Transactions
|
||||
{
|
||||
var product = session.Get<Product>(tp.ProductID);
|
||||
|
||||
if(tp.Quantity < 0)
|
||||
{
|
||||
|
||||
}
|
||||
if (product.Type != 0)
|
||||
{
|
||||
product.Availability += tp.Quantity;
|
||||
@ -253,64 +249,7 @@ namespace FirmTracker_Server.nHibernate.Transactions
|
||||
catch (Exception ex)
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
public void DeleteTransactionProduct(int transactionId, int productId)
|
||||
{
|
||||
using (var session = SessionFactory.OpenSession())
|
||||
using (var t = session.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
// Get the transaction to update
|
||||
var transaction = session.Get<Transaction>(transactionId);
|
||||
if (transaction == null)
|
||||
{
|
||||
throw new InvalidOperationException($"Transaction with ID {transactionId} not found.");
|
||||
}
|
||||
|
||||
// Find the transaction product to remove
|
||||
var transactionProduct = transaction.TransactionProducts.FirstOrDefault(tp => tp.ProductID == productId);
|
||||
if (transactionProduct == null)
|
||||
{
|
||||
throw new InvalidOperationException($"Product with ID {productId} not found in the transaction.");
|
||||
}
|
||||
|
||||
// Get the product to update availability
|
||||
var product = session.Get<Product>(productId);
|
||||
if (product == null)
|
||||
{
|
||||
throw new InvalidOperationException($"Product with ID {productId} not found.");
|
||||
}
|
||||
|
||||
// Revert the product availability
|
||||
if (product.Type != 0)
|
||||
{
|
||||
product.Availability += transactionProduct.Quantity;
|
||||
session.Update(product);
|
||||
}
|
||||
|
||||
// Remove the product from the transaction
|
||||
transaction.TotalPrice = (transaction.TotalPrice * (1 + (transaction.Discount / 100))) - (transactionProduct.Quantity * product.Price );
|
||||
transaction.TotalPrice = Math.Round(transaction.TotalPrice, 2, MidpointRounding.AwayFromZero);
|
||||
|
||||
// Remove the product from the Transaction's Product list
|
||||
transaction.TransactionProducts.Remove(transactionProduct);
|
||||
|
||||
// Now delete the transaction product
|
||||
session.Delete(transactionProduct);
|
||||
|
||||
// Update the transaction total price
|
||||
session.Update(transaction);
|
||||
|
||||
t.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
t.Rollback();
|
||||
throw new InvalidOperationException($"Error while deleting product from transaction: {ex.Message}");
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
BIN
szyfrowanie.dll
BIN
szyfrowanie.dll
Binary file not shown.
Loading…
Reference in New Issue
Block a user