Compare commits

..

1 Commits

21 changed files with 166 additions and 878 deletions

View File

@ -1,253 +0,0 @@
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;
public PdfController(IExpenseRepository expenseRepository, ITransactionRepository transactionRepository)
{
_expenseRepository = expenseRepository;
_transactionRepository = transactionRepository;
}
[HttpGet("download")]
[Authorize(Roles = Roles.Admin)]
public IActionResult DownloadReport(
[FromQuery] string reportType, // "expenses" or "transactions"
[FromQuery] DateTime? startDate,
[FromQuery] DateTime? endDate)
{
try
{
// Validate date inputs and set default values
DateTime start = startDate ?? DateTime.MinValue;
DateTime end = endDate ?? DateTime.MaxValue;
// Validate report type
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));
// Main header
page.Header()
.Text("Raport transakcji")
.FontSize(20)
.SemiBold()
.AlignCenter();
// Summary section
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();
// Add table header
column.Item().Row(row =>
{
row.RelativeItem().Text("Data").SemiBold();
row.RelativeItem().Text("Typ płatności").SemiBold();
row.RelativeItem().Text("Kwota razem").SemiBold();
row.RelativeItem().Text("Rabat").SemiBold();
row.RelativeItem().Text("Opis").SemiBold();
});
// Populate table rows with transaction data
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);
});
// Fetch and display transaction products for this transaction
var products = transactionProducts
.Where(tp => tp.TransactionId == transaction.Id)
.ToList();
if (products.Any())
{
column.Item().Text("Produkty:").SemiBold();
foreach (var product in products)
{
column.Item().Row(productRow =>
{
productRow.RelativeItem().Text($"Nazwa produktu: {product.ProductName}");
productRow.RelativeItem().Text($"Ilość: {product.Quantity}");
});
}
}
}
});
// Footer with generation date
page.Footer()
.AlignCenter()
.Text(text =>
{
text.Span("Wygenerowano przez automat FT: ");
text.Span(DateTime.Now.ToString("yyyy-MM-dd")).SemiBold();
});
});
}).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));
// Main header
page.Header()
.Text("Raport wydatków")
.FontSize(20)
.SemiBold()
.AlignCenter();
// Summary section
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();
row.RelativeItem().Text($"Średnie wydatki dzienne: {averageExpense:C}").FontSize(14).Bold();
});
column.Item().Text($"Szczegóły wydatków od ({startDate:yyyy-MM-dd} do {endDate:yyyy-MM-dd})")
.FontSize(16).Underline();
column.Item().Row(row =>
{
row.RelativeItem().Text("Data").SemiBold();
row.RelativeItem().Text("Kwota").SemiBold();
row.RelativeItem().Text("Opis").SemiBold();
});
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: ");
text.Span(DateTime.Now.ToString("yyyy-MM-dd")).SemiBold();
});
});
}).GeneratePdf(ms);
return ms.ToArray();
}
}
}
}

View File

@ -58,18 +58,11 @@ namespace FirmTracker_Server.Controllers
foreach (var product in transaction.TransactionProducts) 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); var productByName = _productCRUD.GetProductByName(product.ProductName);
if (productByName == null) if (productByName == null)
{ {
throw new InvalidOperationException($"Produkt o nazwie {product.ProductName} nie istnieje."); throw new InvalidOperationException($"Produkt o nazwie {product.ProductName} nie istnieje.");
} }
product.ProductID = productByName.Id; product.ProductID = productByName.Id;
product.TransactionId = transaction.Id; product.TransactionId = transaction.Id;
@ -139,11 +132,6 @@ namespace FirmTracker_Server.Controllers
{ {
foreach (var product in transaction.TransactionProducts) 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); var productByName = _productCRUD.GetProductByName(product.ProductName);
if (productByName == null) if (productByName == null)
{ {
@ -219,27 +207,5 @@ namespace FirmTracker_Server.Controllers
return Ok(transactions); 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(); // Successfully removed the product
}
catch (InvalidOperationException ioe)
{
return BadRequest(ioe.Message); // If the transaction or product isn't found
}
catch (Exception ex)
{
return NotFound(ex.Message); // Other general errors
}
}
} }
} }

View File

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server.Entities; using FirmTracker_Server.Entities;
using System.Security.Claims; using System.Security.Claims;
using FirmTracker_Server.Exceptions;
namespace FirmTracker_Server.Controllers namespace FirmTracker_Server.Controllers
{ {
@ -50,6 +51,69 @@ namespace FirmTracker_Server.Controllers
} }
return Ok(roleClaim); return Ok(roleClaim);
} }
[HttpPost("change-password")]
[Authorize(Roles = Roles.User + "," + Roles.Admin)]
public ActionResult ChangePassword([FromBody] ChangePasswordDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid data.");
}
// Get the user ID from the claims of the authenticated user
var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out var userId))
{
return Unauthorized("User ID not found.");
}
try
{
// Pass the userId to the service to find the user
var success = UserService.ChangePassword(userId, dto);
if (!success)
{
return BadRequest("Password change failed.");
}
return Ok("Password changed successfully.");
}
catch (WrongUserOrPasswordException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
return StatusCode(500, "An error occurred: " + ex.Message);
}
}
[HttpPost("reset-password")]
[Authorize(Roles = Roles.Admin)]
public ActionResult ResetPassword([FromBody] ResetPasswordDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid data.");
}
try
{
// Reset password for the user
var success = UserService.ResetPassword(dto.UserMail, dto.NewPassword);
if (!success)
{
return BadRequest("Password reset failed.");
}
return Ok("Password has been successfully reset.");
}
catch (Exception ex)
{
return StatusCode(500, "An error occurred: " + ex.Message);
}
}
// New method to get all users // New method to get all users
/* [HttpGet("all")] /* [HttpGet("all")]
[AllowAnonymous] [AllowAnonymous]

View File

@ -1,95 +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;
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);
// Attempt to start a new workday
_workdayCRUD.StartWorkday(userId);
return Ok(new { status = "started", userId });
}
catch (Exception ex)
{
// If there's an error (like previous workday not stopped), handle it
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 });
}
}
// 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 });
}
}
}
}

View File

@ -2,7 +2,7 @@
{ {
public class User public class User
{ {
public virtual int UserId { get; set; } public virtual int Id { get; set; }
public virtual string Login { get; set; } public virtual string Login { get; set; }
public virtual string Email { get; set; } public virtual string Email { get; set; }
public virtual string Role { get; set; } = "User"; public virtual string Role { get; set; } = "User";

View File

@ -29,7 +29,6 @@
<PackageReference Include="NLog" Version="5.3.4" /> <PackageReference Include="NLog" Version="5.3.4" />
<PackageReference Include="NLog.Database" Version="5.3.4" /> <PackageReference Include="NLog.Database" Version="5.3.4" />
<PackageReference Include="NSwag.Annotations" Version="14.0.7" /> <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="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" /> <PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.2" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.2" />

View File

@ -1,24 +0,0 @@
pipeline {
agent any
stages {
stage('Restore Dependencies') {
steps {
echo 'Restoring dependencies...'
sh 'dotnet restore'
}
}
stage('Build') {
steps {
echo 'Building the project...'
sh 'dotnet build --configuration Release'
}
}
stage('Publish') {
steps {
echo 'Publishing the project...'
sh 'dotnet publish --configuration Release --output ./publish'
}
}
}
}

View File

@ -0,0 +1,8 @@
namespace FirmTracker_Server.Models
{
public class ChangePasswordDto
{
public string OldPassword { get; set; }
public string NewPassword { get; set; }
}
}

View File

@ -1,11 +0,0 @@
using FirmTracker_Server.Controllers;
namespace FirmTracker_Server.Models
{
public class EmployeeDto
{
public virtual int Id { get; set; }
public virtual string email { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace FirmTracker_Server.Models
{
public class ResetPasswordDto
{
public string UserMail { get; set; }
public string NewPassword { get; set; }
}
}

View File

@ -1,15 +0,0 @@
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; }
}
}

View File

@ -37,8 +37,6 @@ using FirmTracker_Server.Middleware;
using FirmTracker_Server.Services; using FirmTracker_Server.Services;
using System.Reflection; using System.Reflection;
using FirmTracker_Server.Mappings; using FirmTracker_Server.Mappings;
using NuGet.Packaging;
namespace FirmTracker_Server namespace FirmTracker_Server
@ -71,14 +69,14 @@ namespace FirmTracker_Server
TestClass test = new TestClass(); TestClass test = new TestClass();
test.AddTestProduct(); test.AddTestProduct();
QuestPDF.Settings.License = QuestPDF.Infrastructure.LicenseType.Community;
builder.Services.AddCors(options => builder.Services.AddCors(options =>
{ {
options.AddPolicy("AllowSpecificOrigin", options.AddPolicy("AllowSpecificOrigin",
policy => policy.WithOrigins("http://localhost:3000") policy => policy.WithOrigins("http://localhost:3000", "https://localhost:7039", "https://localhost:5075", "https://localhost:3000")
.AllowAnyHeader() .AllowAnyHeader()
.AllowAnyMethod()); .AllowAnyMethod()
.AllowCredentials());
}); });
builder.Services.ConfigureAutoMapper(); builder.Services.ConfigureAutoMapper();
builder.Services.ConfigureServiceInjection(); builder.Services.ConfigureServiceInjection();
@ -125,8 +123,8 @@ namespace FirmTracker_Server
{ {
Console.WriteLine("Nie uda³o siê uruchomiæ swaggera"); Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
} }
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowSpecificOrigin"); app.UseCors("AllowSpecificOrigin");
@ -176,9 +174,6 @@ namespace FirmTracker_Server
services.AddScoped<IUserService, UserService>(); services.AddScoped<IUserService, UserService>();
services.AddScoped<ErrorHandling>(); services.AddScoped<ErrorHandling>();
services.AddScoped<IPasswordHasher<User>, PasswordHasher<User>>(); services.AddScoped<IPasswordHasher<User>, PasswordHasher<User>>();
services.AddScoped<IExpenseRepository, ExpenseRepository>();
services.AddScoped<ITransactionRepository, TransactionRepository>();
// services.AddScoped<IWorkdayRepository, WorkdayRepository>();
services.AddMvc(); services.AddMvc();
} }

View File

@ -23,6 +23,8 @@ namespace FirmTracker_Server.Services
UserDto GetById(int id); UserDto GetById(int id);
int AddUser(CreateUserDto dto); int AddUser(CreateUserDto dto);
string CreateTokenJwt(LoginDto dto); string CreateTokenJwt(LoginDto dto);
bool ChangePassword(int userMail, ChangePasswordDto dto);
bool ResetPassword(string userId, string newPassword);
} }
@ -54,12 +56,13 @@ namespace FirmTracker_Server.Services
} }
} }
public int AddUser(CreateUserDto dto) public int AddUser(CreateUserDto dto)
{ {
var user = Mapper.Map<User>(dto); var user = Mapper.Map<User>(dto);
// Encrypt or hash the password based on NewEncryption flag // Encrypt or hash the password based on NewEncryption flag
user.PassHash = dto.NewEncryption ? SimplerAES.Encrypt(dto.Password) : PasswordHasher.HashPassword(user, dto.Password); user.PassHash = SimplerAES.Encrypt(dto.Password); //: PasswordHasher.HashPassword(user, dto.Password);
user.Role = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dto.Role.ToLower()); user.Role = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dto.Role.ToLower());
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
@ -69,7 +72,7 @@ namespace FirmTracker_Server.Services
{ {
session.Save(user); session.Save(user);
transaction.Commit(); transaction.Commit();
return user.UserId; return user.Id;
} }
catch catch
{ {
@ -78,7 +81,75 @@ namespace FirmTracker_Server.Services
} }
} }
} }
public bool ChangePassword(int userId, ChangePasswordDto dto)
{
using (var session = SessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
// Find user by ID
var user = session.Get<User>(userId);
if (user == null)
{
throw new WrongUserOrPasswordException("User not found.");
}
// Verify old password
var oldPasswordCorrect = false;
if (user.NewEncryption)
{
oldPasswordCorrect = SimplerAES.Decrypt(user.PassHash) == SimplerAES.Decrypt(dto.OldPassword);
}
else
{
oldPasswordCorrect = SimplerAES.Decrypt(user.PassHash) == SimplerAES.Decrypt(dto.OldPassword);
}
if (!oldPasswordCorrect)
{
throw new WrongUserOrPasswordException("The old password is incorrect.");
}
if (user.NewEncryption)
{
user.PassHash = SimplerAES.Encrypt(dto.NewPassword);
}
else
{
user.PassHash = SimplerAES.Encrypt(dto.NewPassword);
}
session.Update(user);
transaction.Commit();
return true;
}
}
public bool ResetPassword(string userMail, string newPassword)
{
using (var session = SessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
var user = session.Get<User>(userMail);
if (user == null)
{
throw new Exception("User not found");
}
// Encrypt or hash the new password
if (user.NewEncryption)
{
user.PassHash = SimplerAES.Encrypt(newPassword); // Or apply hashing if needed
}
else
{
user.PassHash = SimplerAES.Encrypt(newPassword);
}
session.Update(user);
transaction.Commit();
return true;
}
}
public string CreateTokenJwt(LoginDto dto) public string CreateTokenJwt(LoginDto dto)
{ {
User user = null; User user = null;
@ -128,7 +199,7 @@ namespace FirmTracker_Server.Services
// Generate JWT token // Generate JWT token
var claims = new List<Claim>() { var claims = new List<Claim>() {
new(ClaimTypes.NameIdentifier, user.UserId.ToString()), new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Role, user.Role) new(ClaimTypes.Role, user.Role)
}; };

View File

@ -157,7 +157,7 @@ namespace FirmTracker_Server
}; };
var expense2 = new Expense var expense2 = new Expense
{ {
Date = DateTime.Parse("2024-09-10 16:11:17.6232408"), Date = DateTime.Now,
Value = 990.99m, Value = 990.99m,
Description = "naprawa pieca - 25.05.2024" Description = "naprawa pieca - 25.05.2024"
}; };
@ -239,9 +239,9 @@ namespace FirmTracker_Server
expenseCrud.AddExpense(expense3); expenseCrud.AddExpense(expense3);
List<TransactionProduct> testTransactionProducts = new List<TransactionProduct> { List<TransactionProduct> testTransactionProducts = new List<TransactionProduct> {
new TransactionProduct { ProductID =17, Quantity = 3 }, new TransactionProduct { ProductID =17, Quantity = 10 },
new TransactionProduct { ProductID = 14, Quantity = 1 }, new TransactionProduct { ProductID = 14, Quantity = 1 },
new TransactionProduct { ProductID = 1, Quantity = 1 }, new TransactionProduct { ProductID = 1, Quantity = 0 },
}; };
foreach (var transactionProduct in testTransactionProducts) foreach (var transactionProduct in testTransactionProducts)
{ {

View File

@ -1,220 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using FirmTracker_Server.nHibernate.Expenses;
using FirmTracker_Server.nHibernate.Transactions;
using NHibernate;
namespace FirmTracker_Server.nHibernate
{
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 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;
}
}
}
}
}

View File

@ -55,8 +55,7 @@ namespace FirmTracker_Server.nHibernate
.AddFromAssemblyOf<Reports.ReportTransactionMapping>() .AddFromAssemblyOf<Reports.ReportTransactionMapping>()
.AddFromAssemblyOf<Reports.ReportExpenseMapping>() .AddFromAssemblyOf<Reports.ReportExpenseMapping>()
.AddFromAssemblyOf<LogsMapping>() .AddFromAssemblyOf<LogsMapping>()
.AddFromAssemblyOf<UserMapping>() .AddFromAssemblyOf<UserMapping>();
.AddFromAssemblyOf<WorkdayMapping>();
}) })
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update

View File

@ -7,7 +7,7 @@ public class UserMapping : ClassMap<User>
{ {
Table("Users"); // The name of your table in the database Table("Users"); // The name of your table in the database
Id(x => x.UserId); // Mapping the Id property Id(x => x.Id); // Mapping the Id property
Map(x => x.Email); // Mapping other properties Map(x => x.Email); // Mapping other properties
Map(x => x.PassHash); Map(x => x.PassHash);
Map(x => x.Role); Map(x => x.Role);

View File

@ -1,24 +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; }
}
}

View File

@ -1,15 +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
}
}
}

View File

@ -1,104 +0,0 @@
using FirmTracker_Server.Entities;
using FirmTracker_Server.nHibernate;
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
};
session.Save(workday);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw new Exception("An error occurred while starting the workday", 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,
})
.ToList();
return workdays;
}
catch (Exception ex)
{
throw new Exception("An error occurred while fetching workdays", ex);
}
}
}
}

View File

@ -94,10 +94,6 @@ namespace FirmTracker_Server.nHibernate.Transactions
{ {
var product = session.Get<Product>(tp.ProductID); var product = session.Get<Product>(tp.ProductID);
if(tp.Quantity < 0)
{
}
if (product.Type != 0) if (product.Type != 0)
{ {
product.Availability += tp.Quantity; product.Availability += tp.Quantity;
@ -257,63 +253,6 @@ namespace FirmTracker_Server.nHibernate.Transactions
} }
} }
} }
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 -= (transactionProduct.Quantity * product.Price * (1 - (transaction.Discount / 100)));
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}");
}
}
}
public IList<Transaction2> GetAllTransactions() public IList<Transaction2> GetAllTransactions()