Compare commits

47 Commits

Author SHA1 Message Date
d4ae137115 Merge pull request 'Use current datetime for validation' (#17) from main into production
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #17
2025-10-16 18:27:37 +02:00
9f51f508ce Merge pull request 'Always use current datetime for validation' (#16) from fix/stale-datetime-validation into main
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
Reviewed-on: #16
2025-10-16 18:23:44 +02:00
62824549fc Always use current datetime for validation
Some checks failed
continuous-integration/drone/push Build was killed
continuous-integration/drone/pr Build is passing
2025-10-16 18:21:14 +02:00
0cb5e44f7a Merge pull request 'main' (#15) from main into production
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #15
2025-10-16 17:54:03 +02:00
7d7f5750e3 Merge pull request 'Fix bash syntax for creating a variable' (#14) from fix/pipeline into main
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
Reviewed-on: #14
2025-10-16 17:51:33 +02:00
789ba35c60 Fix bash syntax for creating a variable
Some checks failed
continuous-integration/drone/push Build was killed
continuous-integration/drone/pr Build is passing
2025-10-16 17:48:05 +02:00
1226c42f19 Merge pull request 'Echo docker image with tag in pipeline' (#13) from feature/docker-image-echoed-in-pipeline into main
Some checks failed
continuous-integration/drone/push Build is failing
Reviewed-on: #13
2025-10-16 17:41:32 +02:00
5e083aeaf6 Echo docker image with tag in pipeline
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-10-16 17:36:15 +02:00
31efd6b4ad Merge pull request 'Prod: Better debug create consumption error due to datetime' (#12) from main into production
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #12
2025-10-16 17:33:53 +02:00
69bb19e4eb Merge pull request 'Better debug date time error when creating a consumptions' (#11) from fix/bad-request-due-to-date into main
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
Reviewed-on: #11
2025-10-16 17:28:43 +02:00
db791a1183 Add endpoint to query the system's current time
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2025-10-16 17:23:47 +02:00
ad77c2fe2b Fix logs showing non enumerated enumerable as error messages
All checks were successful
continuous-integration/drone/push Build is passing
2025-10-16 17:15:11 +02:00
87a0241f11 Update packages 2025-10-16 17:14:49 +02:00
f248be4e1f Merge pull request 'Seq API Key support and package updates' (#10) from prepare-for-prod into production
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #10
2025-09-21 11:52:08 +02:00
67d29333d9 Merge branch 'production' into prepare-for-prod
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
# Conflicts:
#	.drone.yml
2025-09-21 11:48:42 +02:00
5956f27646 Merge pull request 'feature/add-seq-api-key-support' (#8) from feature/add-seq-api-key-support into main
Some checks failed
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is failing
Reviewed-on: #8
2025-09-21 11:14:06 +02:00
69901a295c Do not build and push docker image for pull requests
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-09-21 11:07:26 +02:00
527759eb7b Fix fluent assertions version
Some checks failed
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is failing
2025-09-21 10:56:56 +02:00
d4fff6741c Update packages
Some checks failed
continuous-integration/drone/pr Build is failing
2025-09-21 10:50:33 +02:00
a10070b9c7 Add seq api key support 2025-09-21 10:50:08 +02:00
d10d1a6fdb Docker push and build for production branch as well
All checks were successful
continuous-integration/drone/push Build is passing
2025-08-19 19:01:27 +02:00
c57972d9a6 Docker push and build for production branch as well
All checks were successful
continuous-integration/drone/push Build is passing
2025-08-19 18:59:01 +02:00
ea019ebfa6 Merge pull request '[PROD] Add seq support' (#7) from main into production
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #7
2025-08-19 18:56:10 +02:00
97a275478d Update configuration documentation in README
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-07-22 21:13:26 +02:00
731eab3898 Prevent using seq if no seq host is set 2025-07-22 21:13:18 +02:00
f018e62163 Fix Docker build
node:lts seems to be bugged, npm binary does not work right
2025-07-22 21:12:50 +02:00
10e02b5e9b Merge pull request 'Add Seq support' (#6) from feature/traces into main
Some checks failed
continuous-integration/drone/push Build is failing
Reviewed-on: #6
2025-07-22 20:20:24 +02:00
c365af1d42 Add Seq support
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2025-07-22 20:19:57 +02:00
66c23ffb4f Merge pull request 'Use full type as log category' (#5) from main into production
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #5
2025-07-21 21:42:57 +02:00
7ddc346e88 Use full type as log category
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2025-07-21 21:41:16 +02:00
00e0869a13 Merge pull request '[Prod] More logging' (#4) from main into production
Some checks failed
continuous-integration/drone/push Build is failing
Reviewed-on: #4
2025-07-21 21:25:21 +02:00
925293d626 Merge pull request 'Add docker build intructions' (#3) from feature/readme into main
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
Reviewed-on: #3
2025-07-21 21:22:18 +02:00
9b024967e6 Add docker build intructions
Some checks failed
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is failing
2025-07-21 21:22:05 +02:00
288d470c1b Merge pull request 'Add more logging and trace parameters' (#2) from feature/better-observability into main
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #2
2025-07-21 21:14:07 +02:00
84a72a8557 Add more logging and trace parameters
Some checks failed
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is failing
2025-07-21 20:58:45 +02:00
d4223ed38f Use port proxying
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-29 12:02:16 +02:00
9f2c5db825 Install npm dependencies as .NET build target 2025-06-29 12:02:16 +02:00
18cbc2225f Remove upload project after both qa and prod have been deployed and migrated
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-28 18:39:33 +02:00
267c4165dd Fix line endings in docker image
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is passing
2025-06-28 17:48:16 +02:00
ef1c1d8ba1 Fix resolver by always using local resolver 2025-06-28 17:46:14 +02:00
8d4ae30224 Just go with one environment variable
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-28 16:54:14 +02:00
02e7ed7030 Fix support for https and http endpoints
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-27 20:23:29 +02:00
9595bedd8e Add support for https and http api url environment variable
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-27 19:50:42 +02:00
af661632cc Add docker dns resolver 2025-06-27 19:50:27 +02:00
5062887010 Add console project to create data to migrate
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-27 19:14:50 +02:00
b41d5c5d33 Ensure correct sorting and thus also correct liter per 100km calculation
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-24 20:35:49 +02:00
4b377ce9f4 Fix resource name to be a valid Aspire resource name 2025-06-24 20:35:26 +02:00
32 changed files with 299 additions and 93 deletions

View File

@@ -42,9 +42,11 @@ steps:
- name: docker build and push
image: docker:24.0.7
commands:
- docker build . -t $docker_registry$docker_repo:$DRONE_BRANCH
- dockerImageWithTag="$docker_registry$docker_repo:$DRONE_BRANCH"
- docker build . -t $dockerImageWithTag
- echo $docker_password | docker login --username $docker_username --password-stdin $docker_registry
- docker push $docker_registry$docker_repo:$DRONE_BRANCH
- docker push $dockerImageWithTag
- echo "Built and pushed $dockerImageWithTag"
environment:
docker_username:
from_secret: docker_username
@@ -60,6 +62,10 @@ steps:
when:
branch:
- main
- production
event:
exclude:
- pull_request
depends_on:
- compile (.NET)
- test

View File

@@ -2,18 +2,20 @@
Vegasco (**VE**hicle **GAS** **CO**nsumption) application.
Includes the backend (`src/Vegasco.Server.Api`) and the frontend (`src/Vegasco-Web`). Utilizes [Aspire](https://learn.microsoft.com/en-us/dotnet/aspire/get-started/aspire-overview).
Includes the backend (`src/Vegasco.Server.Api`) and the frontend (`src/Vegasco-Web`). Uses [Aspire](https://learn.microsoft.com/en-us/dotnet/aspire/get-started/aspire-overview).
## Getting Started
### Configuration
| Configuration | Description | Default | Required |
|--------------------------|---------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|----------|
| JWT:MetadataUrl | The oidc meta data url | - | true |
| JWT:ValidAudience | The valid audience of the JWT token. | - | true |
| JWT:NameClaimType | The claim type of the user's name claim. For keycloak, using `preferred_username` is often the better choice. | http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name | false |
| JWT:AllowHttpMetadataUrl | Whether to allow the meta data url to have http as protocol. Always true when `ASPNETCORE_ENVIRONMENT=true` | false | false |
| Configuration | Description | Default | Required |
|------------------------------------|---------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|----------|
| JWT:MetadataUrl | The oidc meta data url | - | true |
| JWT:ValidAudience | The valid audience of the JWT token. | - | true |
| JWT:NameClaimType | The claim type of the user's name claim. For keycloak, using `preferred_username` is often the better choice. | http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name | false |
| JWT:AllowHttpMetadataUrl | Whether to allow the meta data url to have http as protocol. Always true when `ASPNETCORE_ENVIRONMENT=true` | false | false |
| ConnectionStrings:seq | The seq http endpoint to send the logs and traces to. If not set, logs and traces will not be sent to seq. | - | false |
| ConnectionStrings:vegasco-database | The connection string to the postgres database. | - | true |
The application uses the prefix `Vegasco_` for environment variable names. The prefix is removed when the application reads the environment variables and duplicate entries are overwritten by the environment variables.
@@ -67,3 +69,17 @@ creates a Postgres database as a docker container, and starts the Api with the c
Ensure you have an identity provider set up, for example Keycloak, and configured the relevant options described above.
Then, to run the application, ensure you have Docker running, then run either the `http` or `https` launch profile of the `Vegasco.Server.AppHost` project.
## Deployment
Build server by running in project root:
```shell
docker build . -t docker.nuyken.dev/vegasco/api:main
```
Builder web client by running in `src/Vegasco-Web`:
```shell
docker build -t docker.nuyken.dev/vegasco/web:main --build-arg CONFIGURATION=production .
```

View File

@@ -14,7 +14,7 @@
"options": {
"env": {
"PORT": "44200",
"services__Vegasco-Server-Api__https__0": "https://localhost:7098",
"services__Api__https__0": "https://localhost:7098",
"NODE_ENV": "development"
}
},

View File

@@ -1,4 +1,4 @@
FROM node:lts AS build
FROM node:latest AS build
RUN npm install -g pnpm
ARG CONFIGURATION=development
WORKDIR /usr/local/app
@@ -8,11 +8,12 @@ RUN pnpm "build:$CONFIGURATION"
FROM nginx:alpine
RUN rm /etc/nginx/conf.d/*
RUN apk add --update dos2unix
ENV DOLLAR=$
WORKDIR /usr/share/nginx/html
COPY --from=build /usr/local/app/dist/Vegasco-Web/browser .
COPY nginx.conf /etc/nginx/nginx.conf
RUN dos2unix /etc/nginx/nginx.conf
COPY webserver.conf.template /etc/nginx/templates/webserver.conf.template
RUN dos2unix /etc/nginx/templates/webserver.conf.template
EXPOSE 80

View File

@@ -16,7 +16,7 @@ Once the server is running, open your browser and navigate to `http://localhost:
Because the solution utilizes Aspire which injects endpoint references for the API as environment variables, this application uses a proxy to access the API. The proxy is configured in the `proxy.config.js` file which is used in the `serve` section of the `angular.json` file. This makes the dev server provide a proxy when serving the application.
The environment variables for the API endpoint are named `services__Vegasco-Server-Api__https__0` and `services__Vegasco-Server-Api__http__0` for the https and the http endpoints respectively. If the https endpoint is not configured, the http endpoint is used. At least one of them has to be configured.
The environment variables for the API endpoint are named `services__Api__https__0` and `services__Api__http__0` for the https and the http endpoints respectively. If the https endpoint is not configured, the http endpoint is used. At least one of them has to be configured.
To allow the dev proxy to accept otherwise untrusted server certificates, set `NODE_ENV` to `development`. Otherwise the dev proxy rejects untrusted certificates.

View File

@@ -2,7 +2,7 @@ events { }
http {
include mime.types;
resolver 8.8.8.8 8.8.4.4 1.1.1.1;
resolver 127.0.0.11;
include /etc/nginx/conf.d/webserver.conf;
}

View File

@@ -3,7 +3,6 @@
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start:withInstall": "pnpm install && pnpm run start",
"start": "run-script-os",
"start:win32": "ng serve --port %PORT% --configuration development",
"start:default": "ng serve --port $PORT --configuration development",

View File

@@ -1,8 +1,8 @@
module.exports = {
"/api": {
target:
process.env["services__Vegasco-Server-Api__https__0"] ||
process.env["services__Vegasco-Server-Api__http__0"],
process.env["services__Api__https__0"] ||
process.env["services__Api__http__0"],
secure: process.env["NODE_ENV"] !== "development",
pathRewrite: {
"^/api": "",

View File

@@ -73,7 +73,7 @@ export class EntriesComponent implements OnInit {
const entries = this.consumptionClient.getAll()
.pipe(
takeUntilDestroyed(),
map(response => response.consumptions),
map(response => response.consumptions.sort((a, b) => b.dateTime.localeCompare(a.dateTime))),
catchError((error) => this.handleGetEntriesError(error))
);

View File

@@ -2,7 +2,7 @@ server {
listen 80;
location ~ ^/api/(.*) {
proxy_pass ${services__Vegasco_Server_Api__https__0}/$1;
proxy_pass ${apiUrl}/${DOLLAR}1;
}
location / {

View File

@@ -11,6 +11,7 @@ namespace Vegasco.Server.Api.Cars;
public static class CreateCar
{
public record Request(string Name);
public record Response(Guid Id, string Name);
public static RouteHandlerBuilder MapEndpoint(IEndpointRouteBuilder builder)
@@ -39,44 +40,57 @@ public static class CreateCar
IEnumerable<IValidator<Request>> validators,
ApplicationDbContext dbContext,
UserAccessor userAccessor,
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
List<ValidationResult> failedValidations = await validators.ValidateAllAsync(request, cancellationToken: cancellationToken);
ILogger logger = loggerFactory.CreateLogger(typeof(CreateCar));
List<ValidationResult> failedValidations =
await validators.ValidateAllAsync(request, cancellationToken: cancellationToken);
if (failedValidations.Count > 0)
{
string[] errors = failedValidations
.Where(x => !x.IsValid)
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage)
.ToArray();
logger.LogDebug(
"Validation failed for request {@Request} with errors {@Errors}",
request,
errors);
return TypedResults.BadRequest(new HttpValidationProblemDetails(failedValidations.ToCombinedDictionary()));
}
bool isDuplicate = await dbContext.Cars
.AnyAsync(x => x.Name.ToUpper() == request.Name.ToUpper(), cancellationToken);
if (isDuplicate)
{
logger.LogDebug("Car with name '{CarName}' (case insensitive) already exists", request.Name);
return TypedResults.Conflict();
}
string userId = userAccessor.GetUserId();
User? user = await dbContext.Users.FindAsync([userId], cancellationToken: cancellationToken);
if (user is null)
{
user = new User
{
Id = userId
};
logger.LogDebug("User with ID '{UserId}' not found, creating new user", userId);
user = new User { Id = userId };
await dbContext.Users.AddAsync(user, cancellationToken);
}
Car car = new()
{
Name = request.Name.Trim(),
UserId = userId
};
bool isDuplicate = await dbContext.Cars
.AnyAsync(x => x.Name.ToUpper() == request.Name.ToUpper(), cancellationToken);
if (isDuplicate)
{
return TypedResults.Conflict();
}
Car car = new() { Name = request.Name.Trim(), UserId = userId };
await dbContext.Cars.AddAsync(car, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
logger.LogTrace("Created new car: {@Car}", car);
Response response = new(car.Id.Value, car.Name);
return TypedResults.Created($"/v1/cars/{car.Id}", response);
}
}
}

View File

@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using Vegasco.Server.Api.Persistence;
namespace Vegasco.Server.Api.Cars;
@@ -21,6 +22,9 @@ public static class DeleteCar
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
Activity? activity = Activity.Current;
activity?.SetTag("id", id);
int rows = await dbContext.Cars
.Where(x => x.Id == new CarId(id))
.ExecuteDeleteAsync(cancellationToken);
@@ -32,7 +36,7 @@ public static class DeleteCar
if (rows > 1)
{
ILogger logger = loggerFactory.CreateLogger(nameof(DeleteCar));
ILogger logger = loggerFactory.CreateLogger(typeof(DeleteCar));
logger.LogWarning("Deleted '{DeletedRowCount}' rows for id '{CarId}'", rows, id);
}

View File

@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using Vegasco.Server.Api.Persistence;
namespace Vegasco.Server.Api.Cars;
@@ -34,11 +35,15 @@ public static class GetCars
ApplicationDbContext dbContext,
CancellationToken cancellationToken)
{
Activity? activity = Activity.Current;
List<ResponseDto> cars = await dbContext.Cars
.Select(x => new ResponseDto(x.Id.Value, x.Name))
.ToListAsync(cancellationToken);
ApiResponse response = new ApiResponse
activity?.SetTag("carCount", cars.Count);
ApiResponse response = new()
{
Cars = cars
};

View File

@@ -10,6 +10,7 @@ namespace Vegasco.Server.Api.Cars;
public static class UpdateCar
{
public record Request(string Name);
public record Response(Guid Id, string Name);
public static RouteHandlerBuilder MapEndpoint(IEndpointRouteBuilder builder)
@@ -40,11 +41,25 @@ public static class UpdateCar
IEnumerable<IValidator<Request>> validators,
ApplicationDbContext dbContext,
UserAccessor userAccessor,
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
ILogger logger = loggerFactory.CreateLogger(typeof(UpdateCar));
List<ValidationResult> failedValidations = await validators.ValidateAllAsync(request, cancellationToken);
if (failedValidations.Count > 0)
{
string[] errors = failedValidations
.Where(x => !x.IsValid)
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage)
.ToArray();
logger.LogDebug(
"Validation failed for request {@Request} with errors {@Errors}",
request,
errors);
return TypedResults.BadRequest(new HttpValidationProblemDetails(failedValidations.ToCombinedDictionary()));
}
@@ -60,13 +75,16 @@ public static class UpdateCar
if (isDuplicate)
{
logger.LogDebug("Car with name '{CarName}' (case insensitive) already exists", request.Name);
return TypedResults.Conflict();
}
car.Name = request.Name.Trim();
await dbContext.SaveChangesAsync(cancellationToken);
logger.LogTrace("Updated car: {@Car}", car);
Response response = new(car.Id.Value, car.Name);
return TypedResults.Ok(response);
}
}
}

View File

@@ -18,6 +18,8 @@ public static class DependencyInjectionExtensions
/// <param name="builder"></param>
public static void AddApiServices(this IHostApplicationBuilder builder)
{
builder.AddBuilderServices();
builder.Services
.AddMiscellaneousServices()
.AddCustomOpenApi()
@@ -27,6 +29,24 @@ public static class DependencyInjectionExtensions
builder.AddDbContext();
}
private static IHostApplicationBuilder AddBuilderServices(this IHostApplicationBuilder builder)
{
string? seqHost = builder.Configuration.GetConnectionString("seq");
if (!string.IsNullOrEmpty(seqHost))
{
builder.AddSeqEndpoint("seq", o =>
{
var apiKey = builder.Configuration.GetValue<string>("seq-api-key");
if (!string.IsNullOrEmpty(apiKey))
{
o.ApiKey = apiKey;
}
});
}
return builder;
}
private static IServiceCollection AddMiscellaneousServices(this IServiceCollection services)
{
services.AddSingleton(() =>

View File

@@ -1,5 +1,6 @@
using FluentValidation;
using FluentValidation.Results;
using System.Diagnostics;
using Vegasco.Server.Api.Cars;
using Vegasco.Server.Api.Common;
using Vegasco.Server.Api.Persistence;
@@ -25,13 +26,13 @@ public static class CreateConsumption
{
public Validator(TimeProvider timeProvider)
{
DateTime todayEndOfDay = timeProvider.GetUtcNow()
Func<DateTimeOffset> getTodayEndOfDay = () => timeProvider.GetUtcNow()
.Date
.AddDays(1)
.AddTicks(-1);
RuleFor(x => x.DateTime.ToUniversalTime())
.LessThanOrEqualTo(todayEndOfDay)
.LessThanOrEqualTo(_ => getTodayEndOfDay())
.WithName(nameof(Request.DateTime));
RuleFor(x => x.Distance)
@@ -49,11 +50,25 @@ public static class CreateConsumption
ApplicationDbContext dbContext,
Request request,
IEnumerable<IValidator<Request>> validators,
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
ILogger logger = loggerFactory.CreateLogger(typeof(CreateConsumption));
List<ValidationResult> failedValidations = await validators.ValidateAllAsync(request, cancellationToken);
if (failedValidations.Count > 0)
{
string[] errors = failedValidations
.Where(x => !x.IsValid)
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage)
.ToArray();
logger.LogDebug(
"Validation failed for request {@Request} with errors {@Errors}",
request,
errors);
return TypedResults.BadRequest(new HttpValidationProblemDetails(failedValidations.ToCombinedDictionary()));
}
@@ -74,6 +89,8 @@ public static class CreateConsumption
dbContext.Consumptions.Add(consumption);
await dbContext.SaveChangesAsync(cancellationToken);
logger.LogTrace("Created new consumption: {@Consumption}", consumption);
return TypedResults.Created($"consumptions/{consumption.Id.Value}",
new Response(consumption.Id.Value, consumption.DateTime, consumption.Distance, consumption.Amount,
consumption.CarId.Value));

View File

@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using Vegasco.Server.Api.Persistence;
namespace Vegasco.Server.Api.Consumptions;
@@ -21,6 +22,9 @@ public static class DeleteConsumption
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
Activity? activity = Activity.Current;
activity?.SetTag("id", id);
int rows = await dbContext.Consumptions
.Where(x => x.Id == new ConsumptionId(id))
.ExecuteDeleteAsync(cancellationToken);
@@ -32,7 +36,7 @@ public static class DeleteConsumption
if (rows > 1)
{
ILogger logger = loggerFactory.CreateLogger(nameof(DeleteConsumption));
ILogger logger = loggerFactory.CreateLogger(typeof(DeleteConsumption));
logger.LogWarning("Deleted '{DeletedRowCount}' rows for id '{ConsumptionId}'", rows, id);
}

View File

@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using Vegasco.Server.Api.Cars;
using Vegasco.Server.Api.Persistence;
@@ -49,13 +50,18 @@ public static class GetConsumptions
private static async Task<Ok<ApiResponse>> Endpoint(
[AsParameters] Request request,
ApplicationDbContext dbContext,
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
ILogger logger = loggerFactory.CreateLogger(typeof(GetConsumptions));
logger.LogTrace("Received request to get consumptions with parameters: {@Request}", request);
Activity? activity = Activity.Current;
Dictionary<CarId, List<Consumption>> consumptionsByCar = await dbContext.Consumptions
.OrderByDescending(x => x.DateTime)
.Include(x => x.Car)
.GroupBy(x => x.CarId)
.ToDictionaryAsync(x => x.Key, x => x.ToList(), cancellationToken);
.ToDictionaryAsync(x => x.Key, x => x.OrderByDescending(x => x.DateTime).ToList(), cancellationToken);
List<ResponseDto> responses = [];
@@ -84,8 +90,13 @@ public static class GetConsumptions
literPer100Km));
}
}
activity?.SetTag("consumptionCount", responses.Count);
ApiResponse apiResponse = new() { Consumptions = responses };
ApiResponse apiResponse = new()
{
Consumptions = responses
};
return TypedResults.Ok(apiResponse);
}
}

View File

@@ -26,13 +26,13 @@ public static class UpdateConsumption
{
public Validator(TimeProvider timeProvider)
{
DateTime todayEndOfDay = timeProvider.GetUtcNow()
Func<DateTimeOffset> getTodayEndOfDay = () => timeProvider.GetUtcNow()
.Date
.AddDays(1)
.AddTicks(-1);
RuleFor(x => x.DateTime.ToUniversalTime())
.LessThanOrEqualTo(todayEndOfDay)
.LessThanOrEqualTo(_ => getTodayEndOfDay())
.WithName(nameof(Request.DateTime));
RuleFor(x => x.Distance)
@@ -48,11 +48,25 @@ public static class UpdateConsumption
Guid id,
Request request,
IEnumerable<IValidator<Request>> validators,
ILoggerFactory loggerFactory,
CancellationToken cancellationToken)
{
ILogger logger = loggerFactory.CreateLogger(typeof(UpdateConsumption));
List<ValidationResult> failedValidations = await validators.ValidateAllAsync(request, cancellationToken);
if (failedValidations.Count > 0)
{
string[] errors = failedValidations
.Where(x => !x.IsValid)
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage)
.ToArray();
logger.LogDebug(
"Validation failed for request {@Request} with errors {@Errors}",
request,
errors);
return TypedResults.BadRequest(new HttpValidationProblemDetails(failedValidations.ToCombinedDictionary()));
}
@@ -68,6 +82,9 @@ public static class UpdateConsumption
await dbContext.SaveChangesAsync(cancellationToken);
return TypedResults.Ok(new Response(consumption.Id.Value, consumption.DateTime, consumption.Distance, consumption.Amount, consumption.CarId.Value));
logger.LogTrace("Updated consumption: {@Consumption}", consumption);
return TypedResults.Ok(new Response(consumption.Id.Value, consumption.DateTime, consumption.Distance,
consumption.Amount, consumption.CarId.Value));
}
}

View File

@@ -41,5 +41,6 @@ public static class EndpointExtensions
.RequireAuthorization(Constants.Authorization.RequireAuthenticatedUserPolicy);
GetServerInfo.MapEndpoint(versionedApis);
GetCurrentTime.MapEndpoint(versionedApis);
}
}

View File

@@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Http.HttpResults;
namespace Vegasco.Server.Api.Info;
public static class GetCurrentTime
{
public record Response(DateTimeOffset CurrentTime);
public static RouteHandlerBuilder MapEndpoint(IEndpointRouteBuilder builder)
{
return builder
.MapGet("info/time", Endpoint)
.WithTags("Info");
}
private static Ok<Response> Endpoint(
TimeProvider timeProvider)
{
return TypedResults.Ok(new Response(timeProvider.GetUtcNow()));
}
}

View File

@@ -2,7 +2,7 @@
namespace Vegasco.Server.Api.Info;
public class GetServerInfo
public static class GetServerInfo
{
public record Response(
string FullVersion,

View File

@@ -13,23 +13,24 @@
<ItemGroup>
<PackageReference Include="Asp.Versioning.Http" Version="8.1.0" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.3.0" />
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.5.1" />
<PackageReference Include="Aspire.Seq" Version="9.5.1" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.5" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.5">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.2" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="OpenTelemetry" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.12.0" />
<PackageReference Include="OpenTelemetry" Version="1.13.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.13.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.13.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.12.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.4.16" />
<PackageReference Include="Scalar.AspNetCore" Version="2.9.0" />
<PackageReference Include="StronglyTypedId" Version="1.0.0-beta08" PrivateAssets="all" ExcludeAssets="runtime" />
<PackageReference Include="StronglyTypedId.Templates" Version="1.0.0-beta08" />
</ItemGroup>
@@ -40,7 +41,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Update="Nerdbank.GitVersioning" Version="3.7.115" />
<PackageReference Update="Nerdbank.GitVersioning" Version="3.8.118" />
</ItemGroup>
</Project>

View File

@@ -4,7 +4,7 @@ public static class Constants
{
public static class Projects
{
public const string Api = "Vegasco_Server_Api";
public const string Api = "Api";
}
public static class Database

View File

@@ -8,7 +8,7 @@
<ItemGroup>
<PackageReference Update="Nerdbank.GitVersioning">
<Version>3.7.115</Version>
<Version>3.8.118</Version>
</PackageReference>
</ItemGroup>

View File

@@ -14,19 +14,27 @@ if (builder.Environment.IsDevelopment())
.WithPgAdmin();
}
IResourceBuilder<SeqResource> seq = builder.AddSeq("seq")
.WithLifetime(ContainerLifetime.Persistent)
.WithDataVolume()
.WithExternalHttpEndpoints()
.WithImageTag("latest");
IResourceBuilder<PostgresDatabaseResource> postgres = postgresBuilder
.AddDatabase(Constants.Database.Name);
IResourceBuilder<ProjectResource> api = builder
.AddProject<Projects.Vegasco_Server_Api>(Constants.Projects.Api)
.WithReference(postgres)
.WaitFor(postgres);
.WaitFor(postgres)
.WithReference(seq)
.WaitFor(seq);
builder
.AddNpmApp("Vegasco-Web", "../Vegasco-Web", scriptName: "start:withInstall")
.AddNpmApp("Vegasco-Web", "../Vegasco-Web")
.WithReference(api)
.WaitFor(api)
.WithHttpEndpoint(port: 44200, env: "PORT", isProxied: false)
.WithHttpEndpoint(port: 44200, env: "PORT")
.WithExternalHttpEndpoints()
.WithHttpHealthCheck("/", 200);

View File

@@ -12,12 +12,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.3.0" />
<PackageReference Include="Aspire.Hosting.NodeJs" Version="9.3.1" />
<PackageReference Include="Aspire.Hosting.PostgreSQL" Version="9.3.0" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.5.1" />
<PackageReference Include="Aspire.Hosting.NodeJs" Version="9.5.1" />
<PackageReference Include="Aspire.Hosting.PostgreSQL" Version="9.5.1" />
<PackageReference Update="Nerdbank.GitVersioning">
<Version>3.7.115</Version>
<Version>3.8.118</Version>
</PackageReference>
<PackageReference Include="Aspire.Hosting.Seq" Version="9.5.1" />
</ItemGroup>
<ItemGroup>
@@ -25,4 +26,14 @@
<ProjectReference Include="..\Vegasco.Server.Api\Vegasco.Server.Api.csproj" />
</ItemGroup>
<Target Name="RestoreNpm" BeforeTargets="Build" Condition=" '$(DesignTimeBuild)' != 'true' ">
<ItemGroup>
<PackageJsons Include="..\*\package.json" />
</ItemGroup>
<!-- Install npm packages if node_modules is missing -->
<Message Importance="Normal" Text="Installing npm packages for %(PackageJsons.RelativeDir)" Condition="!Exists('%(PackageJsons.RootDir)%(PackageJsons.Directory)/node_modules')" />
<Exec Command="pnpm install" WorkingDirectory="%(PackageJsons.RootDir)%(PackageJsons.Directory)" Condition="!Exists('%(PackageJsons.RootDir)%(PackageJsons.Directory)/node_modules')" />
</Target>
</Project>

View File

@@ -10,15 +10,15 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.5.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.3.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.12.0" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.10.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.5.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.13.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.13.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.12.0" />
<PackageReference Update="Nerdbank.GitVersioning">
<Version>3.7.115</Version>
<Version>3.8.118</Version>
</PackageReference>
</ItemGroup>

View File

@@ -0,0 +1,32 @@
using FluentAssertions;
using FluentAssertions.Extensions;
using System.Net.Http.Json;
using Vegasco.Server.Api.Info;
namespace Vegasco.Server.Api.Tests.Integration.Info;
[Collection(SharedTestCollection.Name)]
public sealed class GetCurrentTimeTests
{
private readonly WebAppFactory _factory;
public GetCurrentTimeTests(WebAppFactory factory)
{
_factory = factory;
}
[Fact]
public async Task GetServerInfo_ShouldReturnServerInfo_WhenCalled()
{
// Arrange
// Act
using HttpResponseMessage response = await _factory.HttpClient.GetAsync("/v1/info/time");
// Assert
response.IsSuccessStatusCode.Should().BeTrue();
GetCurrentTime.Response? timeInfo = await response.Content.ReadFromJsonAsync<GetCurrentTime.Response>();
timeInfo.Should().NotBeNull();
timeInfo.CurrentTime.Should().BeCloseTo(DateTimeOffset.UtcNow, TimeSpan.FromSeconds(10));
}
}

View File

@@ -10,21 +10,21 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.14.0" />
<PackageReference Include="Bogus" Version="35.6.3" />
<PackageReference Include="Azure.Identity" Version="1.17.0" />
<PackageReference Include="Bogus" Version="35.6.4" />
<PackageReference Include="coverlet.collector" Version="6.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="[7.2.0,8.0.0)" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.5" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.10" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.0" />
<PackageReference Include="Respawn" Version="6.2.1" />
<PackageReference Include="System.Formats.Asn1" Version="9.0.5" />
<PackageReference Include="Testcontainers.PostgreSql" Version="4.5.0" />
<PackageReference Include="System.Formats.Asn1" Version="9.0.10" />
<PackageReference Include="Testcontainers.PostgreSql" Version="4.7.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1">
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
@@ -40,7 +40,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Update="Nerdbank.GitVersioning" Version="3.7.115" />
<PackageReference Update="Nerdbank.GitVersioning" Version="3.8.118" />
</ItemGroup>
</Project>

View File

@@ -14,12 +14,12 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.5" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="FluentAssertions" Version="8.7.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.10" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.0" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1">
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
@@ -34,7 +34,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Update="Nerdbank.GitVersioning" Version="3.7.115" />
<PackageReference Update="Nerdbank.GitVersioning" Version="3.8.118" />
</ItemGroup>
</Project>

View File

@@ -6,10 +6,10 @@
<File Path="version.json" />
</Folder>
<Folder Name="/src/">
<Project Path="src/Vegasco.Server.Api/Vegasco.Server.Api.csproj" />
<Project Path="src/Vegasco.Server.AppHost.Shared/Vegasco.Server.AppHost.Shared.csproj" />
<Project Path="src/Vegasco.Server.AppHost/Vegasco.Server.AppHost.csproj" />
<Project Path="src/Vegasco.Server.ServiceDefaults/Vegasco.Server.ServiceDefaults.csproj" />
<Project Path="src/Vegasco.Server.Api/Vegasco.Server.Api.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Vegasco.Server.Api.Tests.Integration/Vegasco.Server.Api.Tests.Integration.csproj" />