dodawanie nieobecności pracownika

This commit is contained in:
Maciej Maciejewski 2024-12-04 23:35:36 +01:00
parent 19e1a43996
commit d28a692fdd
14 changed files with 170 additions and 26 deletions

View File

@ -50,6 +50,18 @@ namespace FirmTracker_Server.Controllers
} }
return Ok(roleClaim); return Ok(roleClaim);
} }
[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);
}
// New method to get all users // New method to get all users
/* [HttpGet("all")] /* [HttpGet("all")]
[AllowAnonymous] [AllowAnonymous]

View File

@ -15,6 +15,8 @@
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>. * 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 FirmTracker_Server.nHibernate;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -74,6 +76,8 @@ namespace FirmTracker_Server.Controllers
} }
} }
// Endpoint to get all workdays for a user // Endpoint to get all workdays for a user
[HttpGet("user/{userMail}/workdays")] [HttpGet("user/{userMail}/workdays")]
[Authorize(Roles = Roles.Admin + "," + Roles.User)] [Authorize(Roles = Roles.Admin + "," + Roles.User)]
@ -89,6 +93,39 @@ namespace FirmTracker_Server.Controllers
return BadRequest(new { message = "An error occurred while fetching workdays.", error = ex.Message }); 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." });
}
// Fetch the userId based on the provided email
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;
}
// Add the absence for the retrieved 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 });
}
}
} }

37
Dockerfile Normal file
View File

@ -0,0 +1,37 @@
# 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"]

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>FirmTracker_Server</RootNamespace> <RootNamespace>FirmTracker_Server</RootNamespace>
@ -37,7 +37,7 @@
<ItemGroup> <ItemGroup>
<Reference Include="szyfrowanie"> <Reference Include="szyfrowanie">
<HintPath>..\..\..\Desktop\szyfrowanie.dll</HintPath> <HintPath>./szyfrowanie.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>

12
Models/AddAbsenceDtocs.cs Normal file
View File

@ -0,0 +1,12 @@
namespace FirmTracker_Server.Models
{
public class AddAbsenceDto
{
public string userEmail { get; set; }
public string AbsenceType { get; set; } // e.g., "Sick", "Vacation", etc.
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
}

View File

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

View File

@ -46,7 +46,7 @@ namespace FirmTracker_Server
internal static class Program internal static class Program
{ {
public static async Task Main(string[] args) public static void Main(string[] args)
{ {
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
string appDirectory = Directory.GetCurrentDirectory(); string appDirectory = Directory.GetCurrentDirectory();
@ -61,7 +61,7 @@ namespace FirmTracker_Server
var connectionstringsection = config.GetSection("AppSettings:ConnectionString"); var connectionstringsection = config.GetSection("AppSettings:ConnectionString");
connectionString = connectionstringsection.Value; connectionString = connectionstringsection.Value;
//Console.WriteLine(connectionString);
SessionFactory.Init(connectionString); SessionFactory.Init(connectionString);
} }
else else
@ -87,7 +87,7 @@ namespace FirmTracker_Server
{ {
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
}); });
; ;
builder.ConfigureAuthentication(); builder.ConfigureAuthentication();
builder.Services.AddAuthorization(); builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
@ -108,7 +108,7 @@ namespace FirmTracker_Server
var port = configSwagger.GetValue<int>("Port", 5075); 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($"http://*:{port}");
app.Urls.Add($"https://*:{port2}"); app.Urls.Add($"https://*:{port2}");
try try
{ {
@ -125,6 +125,7 @@ namespace FirmTracker_Server
{ {
Console.WriteLine("Nie uda³o siê uruchomiæ swaggera"); Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseCors("AllowSpecificOrigin"); app.UseCors("AllowSpecificOrigin");

View File

@ -23,7 +23,7 @@ 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);
IEnumerable<string> GetAllUserEmails();
} }
public class UserService : IUserService public class UserService : IUserService
@ -44,7 +44,15 @@ namespace FirmTracker_Server.Services
SimplerAES = new SimplerAES(); SimplerAES = new SimplerAES();
//SessionFactory = sessionFactory; //SessionFactory = sessionFactory;
} }
public IEnumerable<string> GetAllUserEmails()
{
using (var session = SessionFactory.OpenSession())
{
// Query the users and return a list of emails
var users = session.Query<User>().Select(u => u.Email).ToList();
return users;
}
}
public UserDto GetById(int id) public UserDto GetById(int id)
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())

View File

@ -1,6 +1,6 @@
{ {
"AppSettings": { "AppSettings": {
"ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;" "ConnectionString": "Server=localhost,1433;Initial Catalog=master;User Id=sa;Password=Rap45tro2;"
}, },
"TokenConfig": { "TokenConfig": {
@ -17,14 +17,7 @@
"applicationUrl": "http://localhost:5045" "applicationUrl": "http://localhost:5045"
}, },
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7039"
},
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,

View File

@ -20,5 +20,6 @@ namespace FirmTracker_Server.nHibernate
} }
} }
public virtual User User { get; set; } public virtual User User { get; set; }
public virtual string Absence { get; set; }
} }
} }

View File

@ -10,6 +10,7 @@ namespace FirmTracker_Server.nHibernate
Map(x => x.StartTime); Map(x => x.StartTime);
Map(x => x.EndTime); Map(x => x.EndTime);
References(x => x.User).Column("UserId"); // Assuming Workday is related to a User References(x => x.User).Column("UserId"); // Assuming Workday is related to a User
Map(x => x.Absence);
} }
} }
} }

View File

@ -30,7 +30,8 @@ public class WorkdayRepository
var workday = new Workday var workday = new Workday
{ {
StartTime = DateTime.Now, StartTime = DateTime.Now,
User = user User = user,
Absence = ""
}; };
session.Save(workday); session.Save(workday);
@ -44,6 +45,36 @@ public class WorkdayRepository
} }
} }
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) public bool StopWorkday(int userId)
{ {
using (var session = SessionFactory.OpenSession()) using (var session = SessionFactory.OpenSession())
@ -90,6 +121,7 @@ public class WorkdayRepository
StartTime = w.StartTime, StartTime = w.StartTime,
EndTime = w.EndTime ?? DateTime.Today.AddHours(17), EndTime = w.EndTime ?? DateTime.Today.AddHours(17),
WorkedHours = (w.EndTime ?? DateTime.Today.AddHours(17)) - w.StartTime, WorkedHours = (w.EndTime ?? DateTime.Today.AddHours(17)) - w.StartTime,
Absence = w.Absence,
}) })
.ToList(); .ToList();

View File

@ -293,7 +293,7 @@ namespace FirmTracker_Server.nHibernate.Transactions
} }
// Remove the product from the transaction // Remove the product from the transaction
transaction.TotalPrice -= (transactionProduct.Quantity * product.Price * (1 - (transaction.Discount / 100))); transaction.TotalPrice = (transaction.TotalPrice * (1 + (transaction.Discount / 100))) - (transactionProduct.Quantity * product.Price );
transaction.TotalPrice = Math.Round(transaction.TotalPrice, 2, MidpointRounding.AwayFromZero); transaction.TotalPrice = Math.Round(transaction.TotalPrice, 2, MidpointRounding.AwayFromZero);
// Remove the product from the Transaction's Product list // Remove the product from the Transaction's Product list

BIN
szyfrowanie.dll Normal file

Binary file not shown.