Added backend functionality

This commit is contained in:
2025-03-01 16:57:18 +01:00
parent 55be2f1e88
commit a1ba2f9571
19 changed files with 427 additions and 11 deletions

View File

@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc;
using WorkTime.Api.Models;
using WorkTime.Api.Services;
namespace WorkTime.Api.Controller;
[ApiController, Route("entries")]
public class EntryController(ITimeEntryService entryService) : ControllerBase {
[HttpGet("{id:guid}")]
public async Task<IResult> GetEntries(Guid id) {
var result = await entryService.GetTimeEntries(id);
return result.HttpResult;
}
[HttpPost("{id:guid}")]
public async Task<IResult> AddEntry(Guid id, TimeEntryDto entry) {
var result = await entryService.AddTimeEntry(id, entry);
return result.HttpResult;
}
[HttpDelete("{id:int}")]
public async Task<IResult> DeleteEntry(int id) {
var result = await entryService.RemoveTimeEntry(id);
return result.HttpResult;
}
}

View File

@@ -0,0 +1,10 @@
using Microsoft.EntityFrameworkCore;
using WorkTime.Api.Models;
namespace WorkTime.Api;
public class DatabaseContext(DbContextOptions<DatabaseContext> options) : DbContext(options) {
public DbSet<TimeEntry> Entries { get; set; }
}

View File

@@ -1,7 +1,15 @@
namespace WorkTime.Api.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class TimeEntry {
namespace WorkTime.Api.Models;
public class TimeEntry : TimeEntryDto {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EntryId { get; set; }
public Guid Owner { get; set; }
}
public class TimeEntryDto {
public DateTime RegisteredAt { get; set; }
public EntryType Type { get; set; }
public bool IsMoba { get; set; }

View File

@@ -1,15 +1,35 @@
using Scalar.AspNetCore;
using WorkTime.Api;
using WorkTime.Api.Services;
using WorkTime.Api.Services.Implementation;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.AddServiceDefaults();
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddNpgsql<DatabaseContext>(builder.Configuration.GetConnectionString("data"));
builder.Services.AddScoped<ITimeEntryService, TimeEntryService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.MapOpenApi();
app.MapScalarApiReference(options => {
options.Servers = [];
});
await app.Services
.CreateAsyncScope().ServiceProvider
.GetRequiredService<DatabaseContext>()
.Database.EnsureCreatedAsync();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

View File

@@ -0,0 +1,14 @@
using WorkTime.Api.Models;
using WorkTime.Defaults;
namespace WorkTime.Api.Services;
public interface ITimeEntryService {
public Task<DataResult<IEnumerable<TimeEntry>>> GetTimeEntries(Guid owner);
public Task<DataResult> AddTimeEntry(Guid owner, TimeEntryDto entry);
public Task<DataResult<bool, IResult>> RemoveTimeEntry(int id);
}

View File

@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore;
using WorkTime.Api.Models;
using WorkTime.Defaults;
namespace WorkTime.Api.Services.Implementation;
public class TimeEntryService(DatabaseContext context) : ITimeEntryService {
public async Task<DataResult<IEnumerable<TimeEntry>>> GetTimeEntries(Guid owner) {
return await context.Entries
.Where(entry => entry.Owner == owner)
.ToArrayAsync();
}
public async Task<DataResult> AddTimeEntry(Guid owner, TimeEntryDto entry) {
var dbEntry = new TimeEntry {
Owner = owner,
RegisteredAt = entry.RegisteredAt,
Type = entry.Type,
IsMoba = entry.IsMoba
};
await context.Entries.AddAsync(dbEntry);
await context.SaveChangesAsync();
return true;
}
public async Task<DataResult<bool, IResult>> RemoveTimeEntry(int id) {
var entry = await context.Entries.FindAsync(id);
if (entry is null)
return TypedResults.NotFound();
context.Entries.Remove(entry);
await context.SaveChangesAsync();
return true;
}
}

View File

@@ -8,7 +8,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.1.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0"/>
<PackageReference Include="Scalar.AspNetCore" Version="2.0.20" />
</ItemGroup>
<ItemGroup>
@@ -17,4 +19,8 @@
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\WorkTime.Defaults\WorkTime.Defaults.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,3 +1,14 @@
var builder = DistributedApplication.CreateBuilder(args);
var db = builder.AddPostgres("db")
.WithDataVolume()
.AddDatabase("data");
builder.AddProject<Projects.WorkTime_Api>("api")
.WithReference(db)
.WaitFor(db);
builder.AddNpmApp("mobile", "../WorkTime.Mobile")
.WithHttpEndpoint(4200, isProxied: false);
builder.Build().Run();

View File

@@ -4,7 +4,7 @@
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:17121;http://localhost:15199",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
@@ -16,7 +16,7 @@
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:15199",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",

View File

@@ -12,7 +12,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.0.0"/>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.1.0" />
<PackageReference Include="Aspire.Hosting.NodeJs" Version="9.1.0" />
<PackageReference Include="Aspire.Hosting.PostgreSQL" Version="9.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WorkTime.Api\WorkTime.Api.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,3 +1,6 @@
export const environment = {
production: true
import {Environment} from "../models/environment";
export const environment: Environment = {
production: true,
backendUrl: "time.leon-hoppe.de/api/"
};

View File

@@ -2,8 +2,11 @@
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
import {Environment} from "../models/environment";
export const environment: Environment = {
production: false,
backendUrl: "http://localhost:5295/"
};
/*

View File

@@ -0,0 +1,4 @@
export interface Environment {
production: boolean;
backendUrl: string;
}

View File

@@ -0,0 +1,43 @@
import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {environment} from "../environments/environment";
import {firstValueFrom} from "rxjs";
export type RequestVerb = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export interface BackendResult<TResult> {
content?: TResult;
error?: any;
isSuccessful: boolean;
statusCode: number;
}
@Injectable({
providedIn: 'root'
})
export class BackendService {
constructor(private http: HttpClient) { }
public async request<TResult>(verb: RequestVerb, url: string, body?: any): Promise<BackendResult<TResult>> {
try {
const response = await firstValueFrom(this.http.request<TResult>(verb, environment.backendUrl + url, {
body: body != undefined ? JSON.stringify(body) : undefined
}));
return {
content: response,
isSuccessful: true,
statusCode: 200
}
}catch (e) {
const error = e as HttpErrorResponse;
return {
error: error,
isSuccessful: false,
statusCode: error.status
}
}
}
}

View File

@@ -1,12 +1,13 @@
import { Injectable } from '@angular/core';
import {TimeEntry} from "../models/timeEntry";
import {BackendTimeEntry, TimeEntry} from "../models/timeEntry";
import {BackendService} from "./backend.service";
@Injectable({
providedIn: 'root'
})
export class TimeService {
constructor() { }
constructor(private backend: BackendService) { }
public calculateTimespanInMinutes(start: TimeEntry, end: TimeEntry): number {
const startSeconds: number = (start.registeredAt.getHours() * 3600) + (start.registeredAt.getMinutes() * 60) + start.registeredAt.getSeconds();