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

Feat/handle duplicated supplies #Issue 179 #192

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions src/supply-categories/supply-categories.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,19 @@ export class SupplyCategoriesController {
@UseGuards(AdminGuard)
async store(@Body() body) {
try {
const isDuplicate = await this.supplyCategoryServices.isDuplicate(body);

if (isDuplicate) {
return new ServerResponse(400, 'This category already exists')
}

const data = await this.supplyCategoryServices.store(body);
return new ServerResponse(
200,
'Successfully created supply category',
data,
);

} catch (err: any) {
this.logger.error(`Failed to create supply category: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
Expand Down
28 changes: 20 additions & 8 deletions src/supply-categories/supply-categories.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,34 @@ import { SupplyCategoriesService } from './supply-categories.service';

describe('SupplyCategoriesService', () => {
let service: SupplyCategoriesService;
let prisma: PrismaService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SupplyCategoriesService],
})
.useMocker((token) => {
if (token === PrismaService) {
return {};
}
})
.compile();
providers: [SupplyCategoriesService, PrismaService],
}).compile();

service = module.get<SupplyCategoriesService>(SupplyCategoriesService);
prisma = module.get<PrismaService>(PrismaService);
prisma.supplyCategory.findFirst = jest.fn(); // Adicione esta linha
});

it('should be defined', () => {
expect(service).toBeDefined();
});

it('should check for duplicates', async () => {
const body = {
name: 'Test',
};

const mockSupply = {
name: 'Test'
} as any;

jest.spyOn(prisma.supplyCategory, 'findFirst').mockResolvedValue(mockSupply);

const result = await service.isDuplicate(body);
expect(result).toBe(true);
});
});
24 changes: 24 additions & 0 deletions src/supply-categories/supply-categories.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
UpdateSupplyCategorySchema,
} from './types';

import { slugify } from '@/utils/utils';

@Injectable()
export class SupplyCategoriesService {
constructor(private readonly prismaService: PrismaService) {}
Expand Down Expand Up @@ -37,4 +39,26 @@ export class SupplyCategoriesService {
async index() {
return await this.prismaService.supplyCategory.findMany({});
}

async isDuplicate(body: z.infer<typeof CreateSupplyCategorySchema>) : Promise<boolean> {

const payload = CreateSupplyCategorySchema.parse(body);
const existingData = await this.prismaService.supplyCategory.findFirst({
where: {
name: payload.name
},
select: {
name: true,
},
});

const payloadName = slugify(payload.name)
const existingDataName = slugify(existingData?.name)

if (payloadName === existingDataName) {
return true
}

return false
}
}
10 changes: 9 additions & 1 deletion src/supply/supply.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,17 @@ export class SupplyController {

@Post('')
async store(@Body() body) {
try {
try {

const isDuplicate = await this.supplyServices.isDuplicate(body);

if (isDuplicate) {
return new ServerResponse(400, 'This supply already exists')
}

const data = await this.supplyServices.store(body);
return new ServerResponse(200, 'Successfully created supply', data);

} catch (err: any) {
this.logger.error(`Failed to create supply: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
Expand Down
32 changes: 24 additions & 8 deletions src/supply/supply.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,38 @@ import { PrismaService } from 'src/prisma/prisma.service';

describe('SupplyService', () => {
let service: SupplyService;
let prisma: PrismaService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SupplyService],
})
.useMocker((token) => {
if (token === PrismaService) {
return {};
}
})
.compile();
providers: [SupplyService, PrismaService],
}).compile();

service = module.get<SupplyService>(SupplyService);
prisma = module.get<PrismaService>(PrismaService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});

it('should check for duplicates', async () => {
const body = {
name: 'Test',
supplyCategoryId: '1',
};

const mockSupply = {
name: 'Test',
supplyCategory: {
id: '1',
},
} as any;

jest.spyOn(prisma.supply, 'findFirst').mockResolvedValue(mockSupply);

const result = await service.isDuplicate(body);
expect(result).toBe(true);
});

});
32 changes: 32 additions & 0 deletions src/supply/supply.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateSupplySchema, UpdateSupplySchema } from './types';

import { slugify } from '@/utils/utils';

@Injectable()
export class SupplyService {
constructor(private readonly prismaService: PrismaService) {}

async store(body: z.infer<typeof CreateSupplySchema>) {
const payload = CreateSupplySchema.parse(body);

return await this.prismaService.supply.create({
data: {
...payload,
Expand Down Expand Up @@ -53,4 +56,33 @@ export class SupplyService {

return data;
}

async isDuplicate(body: z.infer<typeof CreateSupplySchema>):Promise<boolean> {

const payload = CreateSupplySchema.parse(body);
const payloadName = slugify(payload.name)

const existingData = await this.prismaService.supply.findFirst({
where: {
name: payload.name
},
select: {
name: true,
supplyCategory: {
select: {
id: true,
},
},
},
});
const existingDataName = slugify(existingData?.name)

if (existingDataName === payloadName
&& payload.supplyCategoryId === existingData?.supplyCategory.id) {
return true
}

return false;
}

}
20 changes: 20 additions & 0 deletions src/utils/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { slugify } from './utils';

describe('slugify function', () => {

it('should handle accented characters', () => {
const result = slugify('tést');
expect(result).toBe('test');
});

it('should handle uppercase characters', () => {
const result = slugify('Test');
expect(result).toBe('test');
});

it('should handle double spaces', () => {
const result = slugify('test test');
expect(result).toBe('test-test');
});
});
8 changes: 8 additions & 0 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ function removeEmptyStrings<T>(obj): T {
) as T;
}

function slugify(str:string | void):string {

const slugified = String(str).normalize('NFKD').replace(/[\u0300-\u036f]/g, '').trim().toLowerCase()
.replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-')
return slugified

}
export {
ServerResponse,
calculateGeolocationBounds,
Expand All @@ -125,4 +132,5 @@ export {
getSessionData,
removeNotNumbers,
removeEmptyStrings,
slugify
};