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

#19 Catalog - Edit Tag #24

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

namespace Catalog.Application.Tags.Commands;

public static class EditTag
{
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("edit-tag-validation");

var tag = await tagRepository.GetByIdAsync(id);

tag.Name = name;

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);
}
}
}
2 changes: 1 addition & 1 deletion backend/src/Catalog.Domain/Tags/Entities/Tag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
public sealed class Tag
{
public required Guid Id { get; init; }
public required string Name { get; init; }
public required string Name { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ public interface ITagRepository
Task<List<Tag>> GetTagsAsync(List<Guid> ids);
Task AddAsync(Tag tag);
void Delete(List<Tag> tags);
Task<Tag> GetByIdAsync(Guid id);
}
9 changes: 9 additions & 0 deletions backend/src/Host.WebApi/Routes/TagRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ internal static void MapTagRoutes(this IEndpointRouteBuilder api)
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status500InternalServerError);

group.MapPut("", async ([FromServices] ICommandHandler<EditTag.Command> handler, [FromBody] EditTag.Command command) =>
{
var result = await handler.HandleAsync(command);
return result.ToHttp();
})
.Produces(StatusCodes.Status204NoContent)
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status500InternalServerError);

group.MapDelete("", async ([FromServices] ICommandHandler<DeleteTags.Command> handler, [FromBody] DeleteTags.Command command) =>
{
var result = await handler.HandleAsync(command);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,9 @@ public void Delete(List<Tag> tags)
{
context.Set<Tag>().RemoveRange(tags);
}

public Task<Tag> GetByIdAsync(Guid id)
{
return context.Set<Tag>().FirstAsync(t => t.Id == id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public async Task EditProduct_Should_BeSuccessful()
Price = 10
};

await dbContext.AddAsync(product);
await dbContext.Set<Product>().AddAsync(product);
await dbContext.SaveChangesAsync();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
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 EditTagTest(IntegrationFixture integrationFixture)
{
[Fact]
public async Task EditTag_Should_BeSuccessful()
{
// Arrange
await integrationFixture.ResetDatabaseAsync();
using var client = integrationFixture.Factory.CreateClient();

var tagId = Guid.NewGuid();

await using (var dbContext = integrationFixture.CreateDbContext())
{
var tag = new Tag
{
Id = tagId,
Name = "Name"
};

await dbContext.Set<Tag>().AddAsync(tag);
await dbContext.SaveChangesAsync();
}

var command = new EditTag.Command(tagId, "NewName");

// Act
var response = await client.PutAsJsonAsync("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 == tagId);
tag.Should().NotBeNull();
tag.Should().BeEquivalentTo(new Tag { Id = tagId, Name = command.Name });
}
}
}
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 EditTagValidatorTests
{
private readonly EditTag.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 EditTag.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 CatalogTagsEditTagCommand {
id: string;
name: string;
}

export interface CatalogTagsDeleteTagsCommand {
tagIds: string[];
}
Expand Down Expand Up @@ -660,6 +665,80 @@ export const usePostApiV1Tags = <
return useMutation(mutationOptions);
};

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

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

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

return putApiV1Tags(data, requestOptions);
};

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

export type PutApiV1TagsMutationResult = NonNullable<
Awaited<ReturnType<typeof putApiV1Tags>>
>;
export type PutApiV1TagsMutationBody = BodyType<CatalogTagsEditTagCommand>;
export type PutApiV1TagsMutationError = ErrorType<ProblemDetails>;

export const usePutApiV1Tags = <
TError = ErrorType<ProblemDetails>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putApiV1Tags>>,
TError,
{ data: BodyType<CatalogTagsEditTagCommand> },
TContext
>;
request?: SecondParameter<typeof customInstance>;
}): UseMutationResult<
Awaited<ReturnType<typeof putApiV1Tags>>,
TError,
{ data: BodyType<CatalogTagsEditTagCommand> },
TContext
> => {
const mutationOptions = getPutApiV1TagsMutationOptions(options);

return useMutation(mutationOptions);
};

export const deleteApiV1Tags = (
catalogTagsDeleteTagsCommand: BodyType<CatalogTagsDeleteTagsCommand>,
options?: SecondParameter<typeof customInstance>,
Expand Down
76 changes: 76 additions & 0 deletions frontend/admin/src/routes/tags/-components/edit-tag.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { useForm } from "@mantine/form";
import { zodResolver } from "mantine-form-zod-resolver";
import {
CatalogTagsQueriesGetTagsDto,
usePutApiV1Tags,
} from "../../../api/types";
import { z } from "zod";
import { Button, Flex, Modal, TextInput } from "@mantine/core";
import { handleProblemDetailsError } from "../../../utils/error-utils.ts";

interface EditTagProps {
readonly tag: CatalogTagsQueriesGetTagsDto;
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 EditTag = ({ tag, opened, onClose, onSave }: EditTagProps) => {
const form = useForm<Schema>({
mode: "uncontrolled",
initialValues: {
name: tag.name,
},
validate: zodResolver(schema),
});

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

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

return (
<Modal opened={opened} onClose={onClose} title={"Edit 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">Save</Button>
<Button type="button" variant="default" onClick={onClose}>
Cancel
</Button>
</Flex>
</Flex>
</form>
</Modal>
);
};

export default EditTag;
Loading