Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#18 Catalog - Add Tag #22

Merged
merged 1 commit into from
Oct 17, 2024
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
47 changes: 47 additions & 0 deletions backend/src/Catalog.Application/Tags/Commands/AddTag.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Catalog.Domain.Tags.Entities;
using Catalog.Domain.Tags.Repositories;
using Common.Application.Commands;
using Common.Application.Models;
using FluentValidation;

namespace Catalog.Application.Tags.Commands;

public static class AddTag
{
public sealed record Command(Guid Id, string Name) : ICommand;

public sealed class Handler(IUnitOfWork unitOfWork, ITagRepository tagRepository, IValidator<Command> validator) : ICommandHandler<Command>
{
public async Task<Result> HandleAsync(Command command)
{
var (id, name) = command;

var validationResult = await validator.ValidateAsync(command);
if (!validationResult.IsValid) return Result.Fail("add-tag-validation");

var tag = new Tag
{
Id = id,
Name = name
};

await tagRepository.AddAsync(tag);
await unitOfWork.CommitAsync();

return Result.Ok();
}
}

public sealed class Validator : AbstractValidator<Command>
{
public Validator()
{
RuleFor(x => x.Id)
.NotEmpty();

RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(20);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Catalog.Domain.Tags.Entities;

namespace Catalog.Domain.Tags.Repositories;

public interface ITagRepository
{
Task AddAsync(Tag tag);
}
14 changes: 13 additions & 1 deletion backend/src/Host.WebApi/Routes/TagRoutes.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using Catalog.Application.Tags.Queries;
using Catalog.Application.Tags.Commands;
using Catalog.Application.Tags.Queries;
using Common.Application.Commands;
using Common.Application.Queries;
using Host.WebApi.Extensions;
using Microsoft.AspNetCore.Mvc;

namespace Host.WebApi.Routes;
Expand All @@ -18,5 +21,14 @@ internal static void MapTagRoutes(this IEndpointRouteBuilder api)
})
.Produces<GetTags.Result>()
.ProducesProblem(StatusCodes.Status500InternalServerError);

group.MapPost("", async ([FromServices] ICommandHandler<AddTag.Command> handler, [FromBody] AddTag.Command command) =>
{
var result = await handler.HandleAsync(command);
return result.ToHttp();
})
.Produces(StatusCodes.Status204NoContent)
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status500InternalServerError);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Catalog.Domain.Products.Repositories;
using Catalog.Domain.Tags.Repositories;
using Common.Application.Commands;
using Common.Application.Queries;
using Infrastructure.Data.Common;
Expand All @@ -18,6 +19,7 @@ public static IServiceCollection AddInfrastructureData(this IServiceCollection s
services.AddTransient<IQueryProcessor, EfQueryProcessor>();

services.AddTransient<IProductRepository, EfProductRepository>();
services.AddTransient<ITagRepository, EfTagRepository>();

return services;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public Task<List<Product>> GetProductsAsync(List<Guid> ids)

public Task AddAsync(Product product)
{
return context.Set<Product>().AddRangeAsync(product);
return context.Set<Product>().AddAsync(product).AsTask();
}

public void Delete(List<Product> products)
Expand Down
13 changes: 13 additions & 0 deletions backend/src/Infrastructure.Data/Repositories/EfTagRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Catalog.Domain.Tags.Entities;
using Catalog.Domain.Tags.Repositories;
using Infrastructure.Data.Contexts;

namespace Infrastructure.Data.Repositories;

internal sealed class EfTagRepository(AppDbContext context) : ITagRepository
{
public Task AddAsync(Tag tag)
{
return context.Set<Tag>().AddAsync(tag).AsTask();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Net;
using System.Net.Http.Json;
using Catalog.Application.Tags.Commands;
using Catalog.Domain.Tags.Entities;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Tamaplante.IntegrationTests.Common;

namespace Tamaplante.IntegrationTests.Catalog.Tags.Commands;

[Collection("IntegrationTests")]
public sealed class AddTagTest(IntegrationFixture integrationFixture)
{
[Fact]
public async Task AddTag_Should_BeSuccessful()
{
// Arrange
await integrationFixture.ResetDatabaseAsync();
using var client = integrationFixture.Factory.CreateClient();

var command = new AddTag.Command(Guid.NewGuid(), "Name");

// Act
var response = await client.PostAsJsonAsync("api/v1/tags", command);

// Assert
response.StatusCode.Should().Be(HttpStatusCode.NoContent);

await using var dbContext = integrationFixture.CreateDbContext();
var tag = await dbContext.Set<Tag>().FirstOrDefaultAsync(x => x.Id == command.Id);
tag.Should().NotBeNull();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Catalog.Application.Tags.Commands;
using FluentAssertions;
using FluentValidation.TestHelper;

namespace Tamaplante.Tests.Catalog.Application.Tags.Validators;

public sealed class AddTagValidatorTests
{
private readonly AddTag.Validator _sut = new();

[Theory]
[InlineData("2BE2D805-294B-4EA5-96E0-087431636A0B", "name", true)]
[InlineData("2BE2D805-294B-4EA5-96E0-087431636A0B", "", false)]
public async Task Should_Fail_When_Invalid_Command(string id, string name, bool valid)
{
var command = new AddTag.Command(Guid.Parse(id), name);
var result = await _sut.TestValidateAsync(command);
result.IsValid.Should().Be(valid);
}
}
79 changes: 79 additions & 0 deletions frontend/admin/src/api/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ export interface CatalogTagsQueriesGetTagsResult {
total: number;
}

export interface CatalogTagsAddTagCommand {
id: string;
name: string;
}

export interface CatalogProductsQueriesGetProductsDto {
description: string;
id: string;
Expand Down Expand Up @@ -576,3 +581,77 @@ export function useGetApiV1Tags<

return query;
}

export const postApiV1Tags = (
catalogTagsAddTagCommand: BodyType<CatalogTagsAddTagCommand>,
options?: SecondParameter<typeof customInstance>,
) => {
return customInstance<void>(
{
url: `/api/v1/tags`,
method: "POST",
headers: { "Content-Type": "application/json" },
data: catalogTagsAddTagCommand,
},
options,
);
};

export const getPostApiV1TagsMutationOptions = <
TError = ErrorType<ProblemDetails>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof postApiV1Tags>>,
TError,
{ data: BodyType<CatalogTagsAddTagCommand> },
TContext
>;
request?: SecondParameter<typeof customInstance>;
}): UseMutationOptions<
Awaited<ReturnType<typeof postApiV1Tags>>,
TError,
{ data: BodyType<CatalogTagsAddTagCommand> },
TContext
> => {
const { mutation: mutationOptions, request: requestOptions } = options ?? {};

const mutationFn: MutationFunction<
Awaited<ReturnType<typeof postApiV1Tags>>,
{ data: BodyType<CatalogTagsAddTagCommand> }
> = (props) => {
const { data } = props ?? {};

return postApiV1Tags(data, requestOptions);
};

return { mutationFn, ...mutationOptions };
};

export type PostApiV1TagsMutationResult = NonNullable<
Awaited<ReturnType<typeof postApiV1Tags>>
>;
export type PostApiV1TagsMutationBody = BodyType<CatalogTagsAddTagCommand>;
export type PostApiV1TagsMutationError = ErrorType<ProblemDetails>;

export const usePostApiV1Tags = <
TError = ErrorType<ProblemDetails>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof postApiV1Tags>>,
TError,
{ data: BodyType<CatalogTagsAddTagCommand> },
TContext
>;
request?: SecondParameter<typeof customInstance>;
}): UseMutationResult<
Awaited<ReturnType<typeof postApiV1Tags>>,
TError,
{ data: BodyType<CatalogTagsAddTagCommand> },
TContext
> => {
const mutationOptions = getPostApiV1TagsMutationOptions(options);

return useMutation(mutationOptions);
};
11 changes: 9 additions & 2 deletions frontend/admin/src/routes/products/-components/products-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,14 @@ const ProductsList = () => {

const rows =
productsQuery.data?.products.map((p) => (
<Table.Tr key={p.id}>
<Table.Tr
key={p.id}
bg={
selectedRows.includes(p.id)
? "var(--mantine-color-blue-light)"
: undefined
}
>
<Table.Td>
<Checkbox
checked={selectedRows.includes(p.id)}
Expand Down Expand Up @@ -113,7 +120,7 @@ const ProductsList = () => {
<Table>
<Table.Thead>
<Table.Tr>
<Table.Th></Table.Th>
<Table.Th />
<Table.Th>Name</Table.Th>
<Table.Th>Description</Table.Th>
<Table.Th>Price</Table.Th>
Expand Down
72 changes: 72 additions & 0 deletions frontend/admin/src/routes/tags/-components/add-tag.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { useForm } from "@mantine/form";
import { zodResolver } from "mantine-form-zod-resolver";
import { usePostApiV1Tags } from "../../../api/types";
import { z } from "zod";
import { Button, Flex, Modal, TextInput } from "@mantine/core";
import { handleProblemDetailsError } from "../../../utils/error-utils.ts";

interface AddTagProps {
readonly opened: boolean;
readonly onClose: () => void;
readonly onSave: () => void;
}

const schema = z.object({
name: z.string().min(1).max(20),
});

type Schema = z.infer<typeof schema>;

const AddTag = ({ opened, onClose, onSave }: AddTagProps) => {
const form = useForm<Schema>({
mode: "uncontrolled",
initialValues: {
name: "",
},
validate: zodResolver(schema),
});

const { mutateAsync } = usePostApiV1Tags({
mutation: {
onError: handleProblemDetailsError,
onSuccess: () => {
form.reset();
onSave();
onClose();
},
},
});

const handleSubmit = form.onSubmit(async (values) => {
await mutateAsync({
data: {
...values,
id: crypto.randomUUID(),
},
});
});

return (
<Modal opened={opened} onClose={onClose} title={"Add Tag"}>
<form onSubmit={handleSubmit}>
<Flex direction="column" align="flex-start" gap="sm">
<TextInput
{...form.getInputProps("name")}
key={form.key("name")}
label="Name"
withAsterisk
placeholder="Choose a name"
/>
<Flex gap="xs" justify="flex-end">
<Button type="submit">Add</Button>
<Button type="button" variant="default" onClick={onClose}>
Cancel
</Button>
</Flex>
</Flex>
</form>
</Modal>
);
};

export default AddTag;
Loading