Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 42 additions & 9 deletions src/Domain/Entities/Companies/Company.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,12 @@ public void ApproveReview(
}

review.Approve();
var relevantReviews = GetRelevantReviews();
var newRating = RecalculateRating();

Rating = relevantReviews
.Select(x => x.TotalRating)
.DefaultIfEmpty(0)
.Average();

ReviewsCount = relevantReviews.Count;
RatingHistory.Add(new CompanyRatingHistory(Rating, this));
RatingHistory.Add(
new CompanyRatingHistory(
newRating,
this));
}

public void MarkReviewAsOutdated(
Expand All @@ -136,6 +133,16 @@ public void MarkReviewAsOutdated(
}

review.MarkAsOutdated();
var newRating = RecalculateRating();

RatingHistory.Add(
new CompanyRatingHistory(
newRating,
this));
}

public double RecalculateRating()
{
var relevantReviews = GetRelevantReviews();

Rating = relevantReviews
Expand All @@ -144,7 +151,7 @@ public void MarkReviewAsOutdated(
.Average();

ReviewsCount = relevantReviews.Count;
RatingHistory.Add(new CompanyRatingHistory(Rating, this));
return Rating;
}

public void Delete()
Expand All @@ -165,6 +172,32 @@ public void NotDeletedOrFail()
}
}

public void Update(
string name,
string description,
string logoUrl,
List<string> links)
{
name = name?.Trim();
description = description?.Trim();

if (string.IsNullOrWhiteSpace(name))
{
throw new BadRequestException("Company name cannot be empty.");
}

if (string.IsNullOrWhiteSpace(description))
{
throw new BadRequestException("Company description cannot be empty.");
}

Name = name;
NormalizedName = name.ToUpperInvariant();
Description = description;
LogoUrl = logoUrl;
Links = links ?? new List<string>();
}
Comment on lines +175 to +199
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add check for deleted companies in Update method.

The Update method implementation looks good with proper validation and normalization of inputs. However, unlike other methods that modify the entity (AddReview, ApproveReview, MarkReviewAsOutdated), it doesn't check if the company has been deleted.

Consider adding a call to NotDeletedOrFail() at the beginning of the method:

public void Update(
    string name,
    string description,
    string logoUrl,
    List<string> links)
{
+    NotDeletedOrFail();
+
    name = name?.Trim();
    description = description?.Trim();
    
    // rest of the method...
}


protected Company()
{
}
Expand Down
7 changes: 4 additions & 3 deletions src/Domain/Validation/Exceptions/EntityInvalidException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,17 @@ public EntityInvalidException(string message)
{
}

public static EntityInvalidException FromInstance<T>(ICollection<string> errors)
public static EntityInvalidException FromInstance<T>(
ICollection<string> errors)
{
errors.ThrowIfNull(nameof(errors));
if (!errors.Any())
if (errors.Count == 0)
{
throw new InvalidOperationException("Collection of errors could not be empty");
}

var message = $"Instance of {typeof(T).Name} is invalid";
if (errors.Any())
if (errors.Count != 0)
{
message += "\r\n" + errors.Aggregate((result, item) => result + item + "\r\n");
}
Expand Down
18 changes: 17 additions & 1 deletion src/Web.Api/Features/Companies/CompaniesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Web.Api.Features.Companies.SearchCompanies;
using Web.Api.Features.Companies.SearchReviewsToBeApproved;
using Web.Api.Features.Companies.SoftDeleteCompany;
using Web.Api.Features.Companies.UpdateCompany;
using Web.Api.Setup.Attributes;

namespace Web.Api.Features.Companies;
Expand Down Expand Up @@ -44,7 +45,7 @@ await _mediator.Send(
[HttpPost("")]
[HasAnyRole(Role.Admin)]
public async Task<IActionResult> CreateCompany(
[FromBody] CreateCompanyBodyRequest request,
[FromBody] EditCompanyBodyRequest request,
CancellationToken cancellationToken)
{
return Ok(
Expand All @@ -53,6 +54,21 @@ await _mediator.Send(
cancellationToken));
}

[HttpPost("{companyId:guid}")]
[HasAnyRole(Role.Admin)]
public async Task<IActionResult> UpdateCompany(
[FromRoute] Guid companyId,
[FromBody] EditCompanyBodyRequest request,
CancellationToken cancellationToken)
{
return Ok(
await _mediator.Send(
new UpdateCompanyCommand(
companyId,
request),
cancellationToken));
}

[HttpGet("{companyId:guid}")]
public async Task<IActionResult> GetCompany(
Guid companyId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@

namespace Web.Api.Features.Companies.CreateCompany;

public record CreateCompanyCommand : CreateCompanyBodyRequest, IRequest<CompanyDto>
public record CreateCompanyCommand : EditCompanyBodyRequest, IRequest<CompanyDto>
{
public CreateCompanyCommand(
CreateCompanyBodyRequest request)
EditCompanyBodyRequest request)
{
request.ThrowIfInvalid();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace Web.Api.Features.Companies.CreateCompany;

public record CreateCompanyBodyRequest
public record EditCompanyBodyRequest
{
[Required]
public string Name { get; init; }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using MediatR;
using Web.Api.Features.Companies.CreateCompany;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Using the same request model for create and update operations.

The reuse of EditCompanyBodyRequest from the CreateCompany namespace for update operations promotes consistency and reduces duplication. This suggests the model has been renamed from its original CreateCompanyBodyRequest to better reflect its dual purpose.


🏁 Script executed:

#!/bin/bash
# Check if EditCompanyBodyRequest was renamed from CreateCompanyBodyRequest
git log -p -- "src/Web.Api/Features/Companies/CreateCompany/EditCompanyBodyRequest.cs" | grep -A 10 -B 10 "CreateCompanyBodyRequest"

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Locate the file that defines EditCompanyBodyRequest
file=$(rg -l "class EditCompanyBodyRequest" -n .)
echo "Found file: $file"

# Check its Git history (including renames) for occurrences of CreateCompanyBodyRequest
git log --follow --name-status -- "$file" | grep -E "^(R[0-9]+|[AMDR]\s)" | sed -n '1,20p'
git log --follow -p -- "$file" | grep -C 5 "CreateCompanyBodyRequest"

Length of output: 87


🏁 Script executed:

#!/bin/bash
# 1. List all BodyRequest classes in the repository
echo "=== All BodyRequest class definitions ==="
rg --ignore-case -n "class .*BodyRequest" -t cs || true

echo
# 2. List files in the CreateCompany feature folder
echo "=== Files in src/Web.Api/Features/Companies/CreateCompany ==="
find src/Web.Api/Features/Companies/CreateCompany -maxdepth 1 -type f -name "*.cs" -printf '%f\n' || true

echo
# 3. Show the top of UpdateCompanyCommand.cs to inspect its usings
echo "=== UpdateCompanyCommand.cs imports ==="
update_file=$(rg -l "class UpdateCompanyCommand" -n .)
if [ -n "$update_file" ]; then
  sed -n '1,20p' "$update_file"
else
  echo "UpdateCompanyCommand.cs not found"
fi

Length of output: 712


Standardize the shared request model and clarify its intent

The EditCompanyBodyRequest type is currently defined under the CreateCompany feature but is being reused by UpdateCompany. To avoid confusion and better reflect its dual role:

  • Consolidate this DTO into a neutral name (for example, CompanyBodyRequest)
  • Move it to a shared namespace/folder, e.g. src/Web.Api/Features/Companies/Models/CompanyBodyRequest.cs
  • Update both CreateCompanyCommand.cs and UpdateCompanyCommand.cs to import the new namespace:
- using Web.Api.Features.Companies.CreateCompany;
+ using Web.Api.Features.Companies.Models;

This will make its purpose clear, reduce coupling between feature folders, and improve maintainability.

Committable suggestion skipped: line range outside the PR's diff.


namespace Web.Api.Features.Companies.UpdateCompany;

public record UpdateCompanyCommand : IRequest<Unit>
{
public UpdateCompanyCommand(
Guid companyId,
EditCompanyBodyRequest body)
{
CompanyId = companyId;
Body = body;
}

public Guid CompanyId { get; }

public EditCompanyBodyRequest Body { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Domain.Entities.Companies;
using Domain.Validation;
using Domain.Validation.Exceptions;
using Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Web.Api.Features.Companies.UpdateCompany;

public record UpdateCompanyHandler : IRequestHandler<UpdateCompanyCommand, Unit>
{
private readonly DatabaseContext _context;

public UpdateCompanyHandler(
DatabaseContext context)
{
_context = context;
}

public async Task<Unit> Handle(
UpdateCompanyCommand request,
CancellationToken cancellationToken)
{
request.Body.ThrowIfInvalid();

var company = await _context.Companies.FirstOrDefaultAsync(
c => c.Id == request.CompanyId,
cancellationToken)
?? throw NotFoundException.CreateFromEntity<Company>(request.CompanyId);

company.Update(
request.Body.Name,
request.Body.Description,
request.Body.LogoUrl,
request.Body.Links);

await _context.TrySaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace Web.Api.Features.Telegram.GetTelegramInlineUsageStats;

public class TelegramInlineUsageChatDataItem
public record TelegramInlineUsageChatDataItem
{
public TelegramInlineUsageChatDataItem(
long? chatId,
Expand Down
11 changes: 9 additions & 2 deletions src/Web.Api/Middlewares/LoggingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ public class LoggingMiddleware
{
typeof(AuthenticationException),
typeof(BadRequestException),
typeof(EntityInvalidException),
typeof(NotFoundException),
};

public LoggingMiddleware(ILoggerFactory loggerFactory, RequestDelegate next)
public LoggingMiddleware(
ILoggerFactory loggerFactory,
RequestDelegate next)
{
_next = next;
_logger = loggerFactory.CreateLogger<LoggingMiddleware>();
Expand All @@ -37,7 +41,10 @@ public async Task InvokeAsync(HttpContext context)
{
if (!Ignore(exception))
{
_logger.LogError(exception, exception.Message);
_logger.LogError(
exception,
"Unhandled error occured. Message {Message}",
exception.Message);
}

throw;
Expand Down