Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • web-et-numerique/factory/pamn_plateforme-des-acteurs-de-la-mediation-numerique/pamn_server
1 result
Show changes
Showing
with 243 additions and 248 deletions
......@@ -6,6 +6,7 @@ import { PersonalOfferDocument } from '../../personal-offers/schemas/personal-of
import { Week } from '../../shared/schemas/week.schema';
import { StructureTypeDocument } from '../structure-type/structure-type.schema';
import { Address } from './address.schema';
import { StructureCategories } from './structureCategories.schema';
export type StructureDocument = Structure & Document;
......@@ -101,12 +102,12 @@ export class Structure {
@IsNotEmpty()
remoteAccompaniment: boolean;
@Prop()
categories: any;
@Prop({ type: StructureCategories })
categories: StructureCategories;
@Prop()
@IsNotEmpty()
freeWorkShop: boolean | string;
freeWorkShop: boolean;
@Prop()
nbComputers: number;
......
export class StructureCategories {
[property: string]: string[];
}
import { IndicesRefreshResponse, UpdateResponse } from '@elastic/elasticsearch/lib/api/types';
import { Injectable, Logger } from '@nestjs/common';
import { ElasticsearchService } from '@nestjs/elasticsearch';
import { es_settings_homemade_french } from '../../shared/utils';
import { StructureSearchBody } from '../interfaces/structure-search-body.interface';
import { StructureSearchResult } from '../interfaces/structure-search-response.interface';
import { StructureDocument } from '../schemas/structure.schema';
@Injectable()
......@@ -14,10 +14,10 @@ export class StructuresSearchService {
public async indexStructure(structure: StructureDocument): Promise<StructureDocument> {
this.logger.debug(`indexStructure`);
this.elasticsearchService.index<StructureSearchResult, StructureSearchBody>({
this.elasticsearchService.index<StructureSearchBody>({
index: this.index,
id: structure._id,
body: this.formatIndexBody(structure),
document: this.formatIndexBody(structure),
});
return structure;
}
......@@ -25,7 +25,7 @@ export class StructuresSearchService {
private formatIndexBody(structure: StructureDocument): StructureSearchBody {
return {
structureName: structure.structureName,
structureType: structure.structureType.value,
structureType: structure.structureType?.value,
structureId: structure._id,
address: structure.address,
description: structure.description,
......@@ -38,41 +38,37 @@ export class StructuresSearchService {
// don't use stopwords (le, la, de, son, etc.) for structureName (to find "maison de la", "le son du clic", etc.)
return this.elasticsearchService.indices.create({
index: this.index,
body: {
mappings: {
dynamic_templates: [
{
strings: {
match_mapping_type: 'string',
mapping: {
type: 'text',
analyzer: 'homemade_french',
search_analyzer: 'homemade_french',
},
mappings: {
dynamic_templates: [
{
strings: {
match_mapping_type: 'string',
mapping: {
type: 'text',
analyzer: 'homemade_french',
search_analyzer: 'homemade_french',
},
},
],
properties: {
structureName: {
type: 'text',
analyzer: 'homemade_french_stopless',
search_analyzer: 'homemade_french_stopless',
},
},
],
properties: {
structureName: {
type: 'text',
analyzer: 'homemade_french_stopless',
search_analyzer: 'homemade_french_stopless',
},
},
settings: es_settings_homemade_french,
},
settings: es_settings_homemade_french,
});
}
public async dropIndex(): Promise<any> {
this.logger.debug(`dropIndex`);
if (
(
await this.elasticsearchService.indices.exists({
index: this.index,
})
).body
await this.elasticsearchService.indices.exists({
index: this.index,
})
) {
return this.elasticsearchService.indices.delete({
index: this.index,
......@@ -82,14 +78,14 @@ export class StructuresSearchService {
public async deleteIndexStructure(structure: StructureDocument): Promise<StructureDocument> {
this.logger.debug(`deleteIndexStructure`);
this.elasticsearchService.delete<StructureSearchResult, StructureSearchBody>({
this.elasticsearchService.delete({
index: this.index,
id: structure._id,
});
return structure;
}
public async refreshIndexStructure(): Promise<any> {
public async refreshIndexStructure(): Promise<IndicesRefreshResponse> {
this.logger.debug(`refreshIndexStructure`);
return this.elasticsearchService.indices.refresh({
index: this.index,
......@@ -99,35 +95,31 @@ export class StructuresSearchService {
public async search(searchString: string, fields?: string[]): Promise<StructureSearchBody[]> {
this.logger.debug(`search ${searchString} | fields : ${fields}`);
searchString = searchString ? searchString + '*' : '*';
const { body } = await this.elasticsearchService.search<StructureSearchResult>({
const { hits } = await this.elasticsearchService.search<StructureSearchBody>({
index: this.index,
body: {
from: 0,
size: 200,
query: {
query_string: {
analyze_wildcard: 'true',
query: searchString,
fields: fields ? fields : ['structureName^5', 'structureType^5', 'address.commune^10', 'description'],
fuzziness: 'AUTO',
},
from: 0,
size: 200,
query: {
query_string: {
analyze_wildcard: true,
query: searchString,
fields: fields ? fields : ['structureName^5', 'structureType^5', 'address.commune^10', 'description'],
fuzziness: 'AUTO',
},
},
});
const sortedHits = body.hits.hits.filter(function (elem) {
return elem._score >= body.hits.max_score / 1.5;
const sortedHits = hits.hits.filter(function (elem) {
return elem._score >= hits.max_score / 1.5;
});
return sortedHits.map((item) => item._source);
}
public async update(structure: StructureDocument, id: string): Promise<any> {
public async update(structure: StructureDocument, id: string): Promise<UpdateResponse<any>> {
this.logger.debug('update');
return this.elasticsearchService.update({
index: this.index,
id: id,
body: {
doc: this.formatIndexBody(structure),
},
doc: this.formatIndexBody(structure),
});
}
}
import { HttpModule } from '@nestjs/axios';
import { HttpModule, HttpService } from '@nestjs/axios';
import { HttpStatus } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { getModelToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import axios from 'axios';
import * as bcrypt from 'bcrypt';
import { Types } from 'mongoose';
import { of } from 'rxjs';
import { personalOffersDataMock } from '../../../test/mock/data/personalOffers.mock.data';
import { structureMockDto, structuresDocumentDataMock } from '../../../test/mock/data/structures.mock.data';
import { userDetails } from '../../../test/mock/data/users.mock.data';
......@@ -228,6 +228,10 @@ const mockCategoriesService = {
__v: 0,
}),
};
const httpServiceMock = {
get: jest.fn(),
};
describe('StructuresService', () => {
let service: StructuresService;
......@@ -238,6 +242,10 @@ describe('StructuresService', () => {
StructuresService,
ConfigurationService,
ParametersService,
{
provide: HttpService,
useValue: httpServiceMock,
},
{
provide: StructuresSearchService,
useValue: structuresSearchServiceMock,
......@@ -440,9 +448,9 @@ describe('StructuresService', () => {
changeEmailToken: '',
resetPasswordToken: null,
structuresLink: [
Types.ObjectId('620e510b7d8f26712c386be7'),
Types.ObjectId('620e51247d8f26712c386be9'),
Types.ObjectId('620e5236f25755550cb86dfd'),
new Types.ObjectId('620e510b7d8f26712c386be7'),
new Types.ObjectId('620e51247d8f26712c386be9'),
new Types.ObjectId('620e5236f25755550cb86dfd'),
],
pendingStructuresLink: [],
structureOutdatedMailSent: [],
......@@ -455,21 +463,21 @@ describe('StructuresService', () => {
jest
.spyOn(service, 'findOne')
.mockResolvedValueOnce({
_id: Types.ObjectId('61e9260b2ac971550065e261'),
_id: new Types.ObjectId('61e9260b2ac971550065e261'),
coord: [4.844309, 45.865288],
createdAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
__v: 0,
} as StructureDocument)
.mockResolvedValueOnce({
_id: Types.ObjectId('61e9260b2ac971550065e261'),
_id: new Types.ObjectId('61e9260b2ac971550065e261'),
coord: [4.844309, 45.865288],
createdAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
dataShareConsentDate: null,
} as StructureDocument)
.mockResolvedValueOnce({
_id: Types.ObjectId('61e9260b2ac971550065e261'),
_id: new Types.ObjectId('61e9260b2ac971550065e261'),
coord: [4.844309, 45.865288],
createdAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
......@@ -491,9 +499,9 @@ describe('StructuresService', () => {
changeEmailToken: '',
resetPasswordToken: null,
structuresLink: [
Types.ObjectId('620e510b7d8f26712c386be7'),
Types.ObjectId('620e51247d8f26712c386be9'),
Types.ObjectId('620e5236f25755550cb86dfd'),
new Types.ObjectId('620e510b7d8f26712c386be7'),
new Types.ObjectId('620e51247d8f26712c386be9'),
new Types.ObjectId('620e5236f25755550cb86dfd'),
],
pendingStructuresLink: [],
structureOutdatedMailSent: [],
......@@ -506,7 +514,7 @@ describe('StructuresService', () => {
jest
.spyOn(service, 'findOne')
.mockResolvedValueOnce({
_id: Types.ObjectId('61e9260b2ac971550065e261'),
_id: new Types.ObjectId('61e9260b2ac971550065e261'),
coord: [4.844309, 45.865288],
createdAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
......@@ -514,14 +522,14 @@ describe('StructuresService', () => {
__v: 0,
} as StructureDocument)
.mockResolvedValueOnce({
_id: Types.ObjectId('61e9260b2ac971550065e261'),
_id: new Types.ObjectId('61e9260b2ac971550065e261'),
coord: [4.844309, 45.865288],
createdAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
dataShareConsentDate: null,
} as StructureDocument)
.mockResolvedValueOnce({
_id: Types.ObjectId('61e9260b2ac971550065e261'),
_id: new Types.ObjectId('61e9260b2ac971550065e261'),
coord: [4.844309, 45.865288],
createdAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'),
......@@ -574,7 +582,7 @@ describe('StructuresService', () => {
describe('CNFS Structures', () => {
beforeEach(() => {
axios.get = jest.fn().mockResolvedValue({ data: mockCNFSStructures });
httpServiceMock.get.mockImplementationOnce(() => of({ data: mockCNFSStructures }));
});
it('getCNFSStructuress(): should return 2 structures from the mock containing 4 structures', async () => {
......
......@@ -2,12 +2,12 @@ import { HttpService } from '@nestjs/axios';
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cron, CronExpression } from '@nestjs/schedule';
import axios, { AxiosResponse } from 'axios';
import { AxiosResponse } from 'axios';
import * as ejs from 'ejs';
import * as _ from 'lodash';
import { DateTime } from 'luxon';
import { DocumentDefinition, FilterQuery, Model, Types } from 'mongoose';
import { Observable } from 'rxjs';
import { map, Observable, tap } from 'rxjs';
import { UnclaimedStructureDto } from '../../admin/dto/unclaimed-structure-dto';
import { Categories } from '../../categories/schemas/categories.schema';
import { Module } from '../../categories/schemas/module.class';
......@@ -128,14 +128,14 @@ export class StructuresService {
// Handle equipments
// Value is forced to true because there is no verification needed now. Cannot be removed because of old data prod
structure.accountVerified = true;
let createdStructure = new this.structureModel(structure);
createdStructure._id = Types.ObjectId();
createdStructure = this.addEquipmentsCategories(createdStructure);
const createdStructure = new this.structureModel(structure);
createdStructure._id = new Types.ObjectId();
createdStructure.categories.selfServiceMaterial = this.getSelfServiceMaterial(createdStructure);
await createdStructure.save();
await this.getStructurePosition(createdStructure).then(async (position: StructureDocument) => {
return this.structuresSearchService.indexStructure(
await this.structureModel
.findByIdAndUpdate(Types.ObjectId(createdStructure._id), {
.findByIdAndUpdate(new Types.ObjectId(createdStructure._id), {
address: position.address,
coord: position.coord,
})
......@@ -194,8 +194,8 @@ export class StructuresService {
* @param structure
* @returns Structure
*/
public addEquipmentsCategories(structure: StructureDocument): StructureDocument {
Logger.debug(`addEquipmentsCategories of ${structure.structureName}`, StructuresService.name);
public getSelfServiceMaterial(structure: StructureDocument): string[] {
Logger.debug(`getSelfServiceMaterial of ${structure.structureName}`, StructuresService.name);
if (!structure.categories.selfServiceMaterial) {
structure.categories.selfServiceMaterial = [];
}
......@@ -209,8 +209,7 @@ export class StructuresService {
structure.categories.selfServiceMaterial.push(EquipmentsServicesEnum.scanner);
}
// // Remove duplicate if exists
structure.categories.selfServiceMaterial = [...new Set(structure.categories.selfServiceMaterial)];
return structure;
return [...new Set(structure.categories.selfServiceMaterial)];
}
/**
......@@ -238,7 +237,10 @@ export class StructuresService {
if (!structure.address || structure.coord.length <= 0) {
return this.getStructurePosition(structure).then((position: StructureDocument) => {
this.structureModel
.findByIdAndUpdate(Types.ObjectId(structure._id), { address: position.address, coord: position.coord })
.findByIdAndUpdate(new Types.ObjectId(structure._id), {
address: position.address,
coord: position.coord,
})
.exec();
});
}
......@@ -303,7 +305,7 @@ export class StructuresService {
if (!structure.address || structure.coord.length <= 0) {
return this.getStructurePosition(structure).then((position: StructureDocument) => {
this.structureModel
.findByIdAndUpdate(Types.ObjectId(structure._id), {
.findByIdAndUpdate(new Types.ObjectId(structure._id), {
address: position.address,
coord: position.coord,
})
......@@ -358,23 +360,25 @@ export class StructuresService {
public async update(idStructure: string, updatedFields: UpdateStructureDto): Promise<Structure> {
this.logger.debug(`Updating structure ${idStructure}`);
const oldStructure = await this.findOne(idStructure);
let deepClone: StructureDocument;
const oldCategories = { ...oldStructure.categories };
// Store updated categories because it will be erased by Object.assign which is a shallow copy
const updatedCategories = { ...updatedFields.categories };
const deepClone: StructureDocument = Object.assign(oldStructure, updatedFields);
// Update structure categories in order to not override it
if (updatedFields.categories) {
Object.keys(updatedFields.categories).forEach((key) => {
oldStructure.categories[key] = updatedFields.categories[key];
if (updatedCategories) {
deepClone.categories = Object.assign(deepClone.categories, oldCategories);
Object.keys(updatedCategories).forEach((key) => {
deepClone.categories[key] = updatedCategories[key];
});
deepClone = oldStructure;
} else {
deepClone = Object.assign(oldStructure, updatedFields);
}
if (updatedFields.address) {
await this.getStructurePosition(deepClone);
}
const parsedStructure = this.addEquipmentsCategories(deepClone);
const parsedStructure = deepClone;
parsedStructure.categories.selfServiceMaterial = this.getSelfServiceMaterial(deepClone);
const result = await this.structureModel.findByIdAndUpdate(Types.ObjectId(idStructure), parsedStructure).exec();
const result = await this.structureModel.findByIdAndUpdate(new Types.ObjectId(idStructure), parsedStructure).exec();
if (!result) {
throw new HttpException('Invalid structure id', HttpStatus.BAD_REQUEST);
}
......@@ -393,7 +397,7 @@ export class StructuresService {
public async findOne(idParam: string): Promise<StructureDocument> {
this.logger.debug('findOne');
return this.structureModel
.findById(Types.ObjectId(idParam))
.findById(new Types.ObjectId(idParam))
.populate('personalOffers')
.populate('structureType')
.exec();
......@@ -919,7 +923,7 @@ export class StructuresService {
users.map(async (user) => {
return {
id: user._id,
createdAt: user.createdAt ? user.createdAt.toLocaleDateString() : '',
createdAt: user.createdAt ? user.createdAt.toLocaleDateString('fr-FR') : '',
surname: user.surname,
name: user.name,
email: user.email,
......@@ -986,18 +990,25 @@ export class StructuresService {
* Fetch espace coop and filter structures in 69XXX and structures with courriel and phone
* @returns CNFSStructure[]
*/
public async getCNFSStructures(): Promise<Array<CNFSStructure>> {
public getCNFSStructures(): Promise<Array<CNFSStructure>> {
this.logger.debug(`get CNFS structures`);
const response: AxiosResponse<Array<CNFSStructure>> = await axios.get(
'https://api.conseiller-numerique.gouv.fr/permanences'
const obs = this.httpService.get('https://api.conseiller-numerique.gouv.fr/permanences').pipe(
map((response: AxiosResponse<Array<CNFSStructure>>) =>
response.data.filter((structure: CNFSStructure) => {
if (structure.code_postal.substring(0, 2) === '69' && (structure.courriel || structure.telephone))
return structure;
})
),
tap((response) => {
this.logger.debug(`${response.length} CNFS rhone structures containing found`);
})
);
const filteredData = response.data.filter((structure) => {
if (structure.code_postal.substring(0, 2) === '69' && (structure.courriel || structure.telephone))
return structure;
return new Promise((resolve) => {
obs.subscribe((data) => {
resolve(data);
});
});
this.logger.debug(`${filteredData.length} CNFS rhone structures containing found`);
return filteredData;
}
/**
......@@ -1069,7 +1080,7 @@ export class StructuresService {
this.logger.debug(`A resin structure '${idStructure}' matched with a CNFS one, updating its idCNFS '${idCNFS}'`);
const oldStructure = await this.findOne(idStructure);
const deepClone = Object.assign(oldStructure, { idCNFS });
return this.structureModel.findByIdAndUpdate(Types.ObjectId(idStructure), deepClone).exec();
return this.structureModel.findByIdAndUpdate(new Types.ObjectId(idStructure), deepClone).exec();
}
/**
......@@ -1080,7 +1091,7 @@ export class StructuresService {
throw new HttpException('Invalid structure', HttpStatus.NOT_FOUND);
}
structure.personalOffers = structure.personalOffers.filter(
(personalOffer) => !personalOffer._id.equals(Types.ObjectId(offerId))
(personalOffer) => !personalOffer._id.equals(new Types.ObjectId(offerId))
);
await structure.save();
return structure.personalOffers;
......@@ -1090,7 +1101,7 @@ export class StructuresService {
this.logger.debug('findByPersonalOfferId');
return this.structureModel
.findOne({
personalOffers: { $all: [Types.ObjectId(id)] },
personalOffers: { $all: [new Types.ObjectId(id)] },
})
.populate('personalOffers')
.exec();
......
......@@ -204,7 +204,7 @@ export class StructuresController {
if (!structure) {
throw new HttpException('Invalid Structure', HttpStatus.NOT_FOUND);
}
user.pendingStructuresLink = [Types.ObjectId(id)];
user.pendingStructuresLink = [new Types.ObjectId(id)];
// If user already exist, use created account
if (await this.userService.verifyUserExist(user.email)) {
this.tempUserService.sendUserMail(user as ITempUser, structure.structureName, true);
......@@ -274,7 +274,7 @@ export class StructuresController {
}
// Get temp user
const userFromDb = await this.tempUserService.findById(userId);
if (!userFromDb || !userFromDb.pendingStructuresLink.includes(Types.ObjectId(id))) {
if (!userFromDb || !userFromDb.pendingStructuresLink.includes(new Types.ObjectId(id))) {
throw new HttpException('Invalid temp user', HttpStatus.NOT_FOUND);
}
this.tempUserService.removeFromStructureLinked(userFromDb.email, id);
......
export interface PgisCoord {
export class PgisCoord {
type: string;
coordinates: [number, number];
}
......@@ -3,7 +3,7 @@ import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { Roles } from '../users/decorators/roles.decorator';
import { RolesGuard } from '../users/guards/roles.guard';
import { PgisCoord } from './interfaces/pgis.coord';
import { PgisCoord } from './schemas/pgisCoord.schema';
import { TclStopPoint } from './tclStopPoint.schema';
import { TclStopPointService } from './tclStopPoint.service';
......
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { PgisCoord } from './schemas/pgisCoord.schema';
export type TclStopPointDocument = TclStopPoint & Document;
......@@ -39,7 +40,7 @@ export class TclStopPoint {
lastUpdateFme?: Date;
@Prop()
pgisCoord?: string | any;
pgisCoord?: PgisCoord;
@Prop()
distance?: number;
......
......@@ -2,7 +2,7 @@ import { HttpService } from '@nestjs/axios';
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { PgisCoord } from './interfaces/pgis.coord';
import { PgisCoord } from './schemas/pgisCoord.schema';
import { TclStopPoint, TclStopPointDocument } from './tclStopPoint.schema';
interface ReceivedStopPoint {
......
......@@ -12,6 +12,7 @@ describe('TempUserService', () => {
create: jest.fn(),
findOne: jest.fn(),
findById: jest.fn(),
findByIdAndUpdate: jest.fn(),
deleteOne: jest.fn(),
find: jest.fn(),
exec: jest.fn(),
......@@ -90,12 +91,13 @@ describe('TempUserService', () => {
const tmpUser = { email: 'test2@test.com', pendingStructuresLink: [] };
tempUserModelMock.find.mockReturnThis();
tempUserModelMock.exec.mockResolvedValueOnce([]).mockResolvedValueOnce(tmpUser);
tempUserModelMock.updateOne.mockReturnThis();
tempUserModelMock.findByIdAndUpdate.mockReturnThis();
expect(await service.updateStructureLinked(tmpUser)).toEqual(tmpUser);
});
it('should not update structure linked: User already linked', async () => {
const tmpUser = { email: 'test2@test.com', pendingStructuresLink: [] };
tempUserModelMock.find.mockReturnThis();
tempUserModelMock.findByIdAndUpdate.mockReturnThis();
tempUserModelMock.exec.mockResolvedValueOnce([tmpUser]);
try {
await service.updateStructureLinked(tmpUser);
......
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import * as ejs from 'ejs';
import { Model, Types } from 'mongoose';
import { MailerService } from '../mailer/mailer.service';
import { CreateTempUserDto } from './dto/create-temp-user.dto';
import { TempUser } from './temp-user.schema';
import * as ejs from 'ejs';
import { ITempUser } from './temp-user.interface';
import { TempUser } from './temp-user.schema';
@Injectable()
export class TempUserService {
......@@ -30,7 +30,7 @@ export class TempUserService {
}
public async findById(id: string): Promise<TempUser> {
return this.tempUserModel.findById(Types.ObjectId(id));
return this.tempUserModel.findById(new Types.ObjectId(id));
}
public async delete(mail: string): Promise<TempUser> {
......@@ -59,7 +59,7 @@ export class TempUserService {
throw new HttpException('User already linked', HttpStatus.UNPROCESSABLE_ENTITY);
}
return this.tempUserModel
.updateOne(
.findByIdAndUpdate(
{ email: createTempUser.email },
{ $push: { pendingStructuresLink: createTempUser.pendingStructuresLink[0] } }
)
......@@ -67,7 +67,7 @@ export class TempUserService {
}
/**
* Send email in order to tell the user that an account is alreday fill with his structure info.
* Send email in order to tell the user that an account is already fill with his structure info.
* @param user User
*/
public async sendUserMail(user: ITempUser, structureName: string, existingUser?: boolean): Promise<any> {
......@@ -89,7 +89,7 @@ export class TempUserService {
public async getStructureTempUsers(structureId: string): Promise<ITempUser[]> {
return this.tempUserModel
.find({ pendingStructuresLink: Types.ObjectId(structureId) })
.find({ pendingStructuresLink: new Types.ObjectId(structureId) })
.select('email updatedAt')
.exec();
}
......@@ -99,7 +99,7 @@ export class TempUserService {
if (!user) {
throw new HttpException('Invalid temp user', HttpStatus.NOT_FOUND);
}
if (!user.pendingStructuresLink.includes(Types.ObjectId(idStructure))) {
if (!user.pendingStructuresLink.includes(new Types.ObjectId(idStructure))) {
throw new HttpException("Temp user doesn't belong to this structure", HttpStatus.NOT_FOUND);
}
user.pendingStructuresLink = user.pendingStructuresLink.filter((structureId) => {
......
......@@ -63,12 +63,12 @@ describe('EmployerController', () => {
it('should return two elements ', async () => {
employerServiceMock.findAll.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CAF',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CARSAT',
validated: true,
},
......@@ -79,12 +79,12 @@ describe('EmployerController', () => {
it('should return searched elements with query `CA`', async () => {
employerServiceMock.searchByName.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CAF',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CARSAT',
validated: true,
},
......@@ -132,12 +132,12 @@ describe('EmployerController', () => {
it('should reset search index', async () => {
employerServiceMock.initEmployerIndex.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CAF',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CARSAT',
validated: true,
},
......@@ -151,7 +151,7 @@ describe('EmployerController', () => {
it('should create a employer', async () => {
employerServiceMock.findByName.mockResolvedValueOnce(null);
employerServiceMock.create.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Sopra',
validated: true,
});
......@@ -161,7 +161,7 @@ describe('EmployerController', () => {
});
it('should not create if employer already exists', async () => {
employerServiceMock.findByName.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Sopra',
validated: true,
});
......@@ -190,7 +190,7 @@ describe('EmployerController', () => {
describe('Validate Employer', () => {
it('should validate an employer', async () => {
employerServiceMock.validate.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Sopra',
validated: true,
});
......@@ -202,12 +202,12 @@ describe('EmployerController', () => {
const spyer = jest.spyOn(userService, 'populateEmployerswithUsers');
employerServiceMock.findAllValidated.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
},
......@@ -221,12 +221,12 @@ describe('EmployerController', () => {
const spyer = jest.spyOn(userService, 'populateEmployerswithUsers');
employerServiceMock.findAllUnvalidated.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: false,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: false,
},
......@@ -239,7 +239,7 @@ describe('EmployerController', () => {
describe('Edit Employer', () => {
it('should update employer', async () => {
employerServiceMock.update.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'SopraMod',
validated: true,
});
......@@ -248,7 +248,7 @@ describe('EmployerController', () => {
it('should delete an unvalidated employer and replace all its occurence with a chosen validated employer', async () => {
employerServiceMock.mergeEmployer.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Sopra',
validated: true,
});
......@@ -274,7 +274,7 @@ describe('EmployerController', () => {
});
employerServiceMock.findOne.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Sopra',
validated: true,
});
......@@ -284,7 +284,7 @@ describe('EmployerController', () => {
it('should not delete employer if a user is linked', async () => {
employerServiceMock.findOne.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
});
......
......@@ -68,13 +68,13 @@ describe('JobsController', () => {
it('should findAll', async () => {
jobServiceMock.findAll.mockResolvedValue([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFS',
validated: true,
hasPersonalOffer: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Formateur',
validated: true,
hasPersonalOffer: true,
......@@ -108,7 +108,7 @@ describe('JobsController', () => {
hasPersonalOffer: false,
};
jobServiceMock.findByName.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'Metro',
validated: false,
hasPersonalOffer: false,
......@@ -128,7 +128,7 @@ describe('JobsController', () => {
it('should create a job', async () => {
jobServiceMock.findByName.mockResolvedValueOnce(null);
jobServiceMock.create.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Dev',
validated: true,
});
......@@ -138,7 +138,7 @@ describe('JobsController', () => {
});
it('should not create if job already exists', async () => {
jobServiceMock.findByName.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Dev',
validated: true,
});
......@@ -153,7 +153,7 @@ describe('JobsController', () => {
it('should call create with send notification to true if admin', async () => {
jobServiceMock.findByName.mockResolvedValueOnce(null);
jobServiceMock.create.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Dev',
validated: true,
});
......@@ -167,7 +167,7 @@ describe('JobsController', () => {
describe('Validate Job', () => {
it('should validate a given job', async () => {
jobServiceMock.validate.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Dev',
validated: true,
});
......@@ -179,12 +179,12 @@ describe('JobsController', () => {
const spyer = jest.spyOn(userServiceMock, 'populateJobswithUsers');
jobServiceMock.findAll.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Dev',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Scrum',
validated: true,
},
......@@ -198,12 +198,12 @@ describe('JobsController', () => {
const spyer = jest.spyOn(userServiceMock, 'populateJobswithUsers');
jobServiceMock.findAllUnvalidated.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Dev',
validated: false,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Scrum',
validated: false,
},
......@@ -216,7 +216,7 @@ describe('JobsController', () => {
describe('Edit Job', () => {
it('should update job', async () => {
jobServiceMock.update.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'DevMod',
validated: true,
});
......@@ -227,7 +227,7 @@ describe('JobsController', () => {
it('should delete an unvalidated job and replace all its occurence with a chosen validated job', async () => {
jobServiceMock.mergeJob.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Dev',
validated: true,
});
......@@ -253,7 +253,7 @@ describe('JobsController', () => {
it('should delete job', async () => {
jobServiceMock.findOne.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Dev',
validated: true,
});
......@@ -264,7 +264,7 @@ describe('JobsController', () => {
it('should not delete job if a user is linked', async () => {
jobServiceMock.findOne.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Dev',
validated: true,
});
......
......@@ -117,13 +117,12 @@ describe('UsersController', () => {
],
controllers: [UsersController],
}).compile();
afterEach(() => {
jest.clearAllMocks();
});
controller = module.get<UsersController>(UsersController);
});
afterEach(() => {
jest.clearAllMocks();
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
......@@ -157,7 +156,7 @@ describe('UsersController', () => {
jobName: 'Dev',
};
employerServiceMock.findByName.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CAF',
validated: true,
});
......@@ -176,21 +175,21 @@ describe('UsersController', () => {
jobName: 'Dev',
};
employerServiceMock.findByName.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5a7'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
name: 'CAF',
validated: true,
});
jobServiceMock.findByName.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5be'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5be'),
name: 'Dev',
validated: false,
hasPersonalOffer: false,
});
userServiceMock.findOne.mockResolvedValueOnce({
_id: Types.ObjectId('620e4ffa72389045b02ac854'),
structuresLink: [Types.ObjectId('620e5236f25755550cb86dfd')],
_id: new Types.ObjectId('620e4ffa72389045b02ac854'),
structuresLink: [new Types.ObjectId('620e5236f25755550cb86dfd')],
structureOutdatedMailSent: [],
pendingStructuresLink: [Types.ObjectId('61e926192ac971550065e275')],
pendingStructuresLink: [new Types.ObjectId('61e926192ac971550065e275')],
phone: '06 06 06 06 06',
newEmail: null,
changeEmailToken: null,
......@@ -203,8 +202,8 @@ describe('UsersController', () => {
email: 'admin@admin.com',
password: '$2a$12$vLQjJ9zAWyUwiXLeQDa6w.XzrlgPBhw.2GWrjog/yuEjIaZnQwmZu',
__v: 11,
employer: Types.ObjectId('6231aefe76598527c8d0b5a7'),
job: Types.ObjectId('6231aefe76598527c8d0b5be'),
employer: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
job: new Types.ObjectId('6231aefe76598527c8d0b5be'),
});
const reply = await controller.setProfile({ user: { _id: '36', email: 'a@a.com' } }, profile);
expect(reply).toBeTruthy();
......@@ -219,10 +218,10 @@ describe('UsersController', () => {
phone: '0605040302',
};
userServiceMock.updateUserDetails.mockResolvedValueOnce({
_id: Types.ObjectId('620e4ffa72389045b02ac854'),
structuresLink: [Types.ObjectId('620e5236f25755550cb86dfd')],
_id: new Types.ObjectId('620e4ffa72389045b02ac854'),
structuresLink: [new Types.ObjectId('620e5236f25755550cb86dfd')],
structureOutdatedMailSent: [],
pendingStructuresLink: [Types.ObjectId('61e926192ac971550065e275')],
pendingStructuresLink: [new Types.ObjectId('61e926192ac971550065e275')],
phone: '06 06 06 06 06',
newEmail: null,
changeEmailToken: null,
......@@ -235,8 +234,8 @@ describe('UsersController', () => {
email: 'admin@admin.com',
password: '$2a$12$vLQjJ9zAWyUwiXLeQDa6w.XzrlgPBhw.2GWrjog/yuEjIaZnQwmZu',
__v: 11,
employer: Types.ObjectId('6231aefe76598527c8d0b5a7'),
job: Types.ObjectId('6231aefe76598527c8d0b5be'),
employer: new Types.ObjectId('6231aefe76598527c8d0b5a7'),
job: new Types.ObjectId('6231aefe76598527c8d0b5be'),
});
const reply = await controller.updateDetails({ user: { _id: '36', email: 'a@a.com' } }, newDetails);
expect(reply).toBeTruthy();
......
export interface EmployerSearchBody {
name: string;
}
import { Employer } from '../schemas/employer.schema';
export interface EmployerSearchResult {
hits: {
total: number;
max_score: number;
hits: Array<{
_score: number;
_source: Employer;
}>;
};
}
......@@ -7,27 +7,27 @@ import { EmployerSearchService } from './employer-search.service';
const employers = [
{
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Metro',
validated: true,
} as EmployerDocument,
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bb'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bb'),
name: 'Sopra',
validated: true,
} as EmployerDocument,
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bd'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bd'),
name: 'CAF',
validated: true,
} as EmployerDocument,
{
_id: Types.ObjectId('6231aefe76598527c8d0b5be'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5be'),
name: 'CARSAT',
validated: true,
} as EmployerDocument,
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bf'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bf'),
name: 'CPAM',
validated: true,
} as EmployerDocument,
......@@ -85,7 +85,7 @@ describe('EmployerSearchService Search cases', () => {
const resCaf = await service.search('CAF');
const res = await service.update(
resCaf[0] as EmployerDocument,
Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString()
new Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString()
);
expect(res).toBeTruthy();
});
......@@ -93,7 +93,7 @@ describe('EmployerSearchService Search cases', () => {
const resCaf = await service.search('CAF');
const res = await service.deleteIndex(
resCaf[0] as EmployerDocument,
Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString()
new Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString()
);
expect(res).toBeTruthy();
});
......
import { IndicesRefreshResponse, UpdateResponse } from '@elastic/elasticsearch/lib/api/types';
import { Injectable, Logger } from '@nestjs/common';
import { ElasticsearchService } from '@nestjs/elasticsearch';
import { es_settings_homemade_french } from '../../shared/utils';
import { EmployerSearchBody } from '../interfaces/employer-search-body.interface';
import { EmployerSearchResult } from '../interfaces/employer-search-response.interface';
import { Employer, EmployerDocument } from '../schemas/employer.schema';
@Injectable()
......@@ -14,10 +13,10 @@ export class EmployerSearchService {
public async indexEmployer(employer: EmployerDocument): Promise<EmployerDocument> {
this.logger.debug(`indexEmployer ${employer.name}`);
this.elasticsearchService.index<EmployerSearchResult, Employer>({
this.elasticsearchService.index<Employer>({
index: this.index,
id: employer._id,
body: {
document: {
name: employer.name,
validated: employer.validated,
},
......@@ -29,34 +28,30 @@ export class EmployerSearchService {
this.logger.debug('createEmployerIndex');
return this.elasticsearchService.indices.create({
index: this.index,
body: {
mappings: {
dynamic_templates: [
{
strings: {
match_mapping_type: 'string',
mapping: {
type: 'text',
analyzer: 'homemade_french',
search_analyzer: 'homemade_french_stopless',
},
mappings: {
dynamic_templates: [
{
strings: {
match_mapping_type: 'string',
mapping: {
type: 'text',
analyzer: 'homemade_french',
search_analyzer: 'homemade_french_stopless',
},
},
],
},
settings: es_settings_homemade_french,
},
],
},
settings: es_settings_homemade_french,
});
}
public async dropIndex(): Promise<any> {
this.logger.debug('dropIndex');
if (
(
await this.elasticsearchService.indices.exists({
index: this.index,
})
).body
await this.elasticsearchService.indices.exists({
index: this.index,
})
) {
return this.elasticsearchService.indices.delete({
index: this.index,
......@@ -66,14 +61,14 @@ export class EmployerSearchService {
public async deleteIndex(employer: EmployerDocument, id: string): Promise<EmployerDocument> {
this.logger.debug('deleteIndex');
this.elasticsearchService.delete<EmployerSearchResult, EmployerSearchBody>({
this.elasticsearchService.delete({
index: this.index,
id: id,
});
return employer;
}
public async refreshIndexStructure(): Promise<any> {
public async refreshIndexStructure(): Promise<IndicesRefreshResponse> {
this.logger.debug('refreshIndexStructure');
return this.elasticsearchService.indices.refresh({
index: this.index,
......@@ -83,28 +78,26 @@ export class EmployerSearchService {
public async search(searchString: string): Promise<Employer[]> {
this.logger.debug(`search ${searchString}`);
searchString = searchString ? searchString + '*' : '*';
const { body } = await this.elasticsearchService.search<EmployerSearchResult>({
const { hits } = await this.elasticsearchService.search<Employer>({
index: this.index,
body: {
from: 0,
size: 200,
query: {
query_string: {
analyze_wildcard: 'true',
query: searchString,
fields: ['name'],
fuzziness: 'AUTO',
},
from: 0,
size: 200,
query: {
query_string: {
analyze_wildcard: true,
query: searchString,
fields: ['name'],
fuzziness: 'AUTO',
},
},
});
const sortedHits = body.hits.hits.filter(function (elem) {
return elem._score >= body.hits.max_score / 1.5;
const sortedHits = hits.hits.filter(function (elem) {
return elem._score >= hits.max_score / 1.5;
});
return sortedHits.map((item) => item._source);
}
public async update(employer: EmployerDocument, id: string): Promise<any> {
public async update(employer: EmployerDocument, id: string): Promise<UpdateResponse<any>> {
this.logger.debug('update');
return this.elasticsearchService.update({
index: this.index,
......
......@@ -71,12 +71,12 @@ describe('EmployerService', () => {
it('findAll', async () => {
mockEmployerModel.sort.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
},
......@@ -86,7 +86,7 @@ describe('EmployerService', () => {
});
it('findOne', async () => {
mockEmployerModel.findById.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
});
......@@ -96,7 +96,7 @@ describe('EmployerService', () => {
it('findAllValidated', async () => {
mockEmployerModel.find.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
},
......@@ -108,7 +108,7 @@ describe('EmployerService', () => {
it('findAllUnvalidated', async () => {
mockEmployerModel.find.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: false,
},
......@@ -120,7 +120,7 @@ describe('EmployerService', () => {
it('finds all unvalidated employers', async () => {
mockEmployerModel.find.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: false,
},
......@@ -132,12 +132,12 @@ describe('EmployerService', () => {
it('finds all validated employers', async () => {
mockEmployerModel.find.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5b2'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5b2'),
name: 'Sopra',
validated: true,
},
......@@ -148,7 +148,7 @@ describe('EmployerService', () => {
it('findByName', async () => {
mockEmployerModel.findOne.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
});
......@@ -159,12 +159,12 @@ describe('EmployerService', () => {
describe('createEmployer', () => {
it('create', async () => {
mockEmployerModel.create.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: false,
});
mockEmployerModel.findOne.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: false,
});
......@@ -179,12 +179,12 @@ describe('EmployerService', () => {
it('should create validated employer and not send email to admins', async () => {
mockEmployerModel.create.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: false,
});
mockEmployerModel.findOne.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: false,
});
......@@ -198,7 +198,7 @@ describe('EmployerService', () => {
it('delete', async () => {
mockEmployerModel.findOne.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
});
......@@ -224,24 +224,24 @@ describe('EmployerService', () => {
mockEmployerSearchService.createEmployerIndex.mockResolvedValueOnce({});
mockEmployerModel.sort.mockResolvedValueOnce([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: true,
},
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
},
]);
mockEmployerSearchService.indexEmployer
.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: true,
} as EmployerDocument)
.mockResolvedValueOnce({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Sopra',
validated: true,
} as EmployerDocument);
......@@ -254,13 +254,13 @@ describe('EmployerService', () => {
describe('mergeEmployer', () => {
it('should delete source employer', async () => {
const reply = {
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e61'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e61'),
name: 'Metro',
validated: true,
};
mockEmployerModel.findById
.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Sopra',
validated: false,
})
......@@ -293,7 +293,7 @@ describe('EmployerService', () => {
describe('sendAdminCreateNotification', () => {
it('should sendAdminCreateNotification', async () => {
const employer = {
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: true,
};
......@@ -338,7 +338,7 @@ describe('EmployerService', () => {
describe('validate', () => {
it('should validate employer', async () => {
mockEmployerModel.findById.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Sopra',
validated: false,
save: jest.fn().mockResolvedValueOnce(null),
......@@ -361,7 +361,7 @@ describe('EmployerService', () => {
describe('update', () => {
it('should update employer', async () => {
mockEmployerModel.findById.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Sopraaa',
validated: false,
save: jest.fn().mockResolvedValueOnce(null),
......@@ -384,14 +384,14 @@ describe('EmployerService', () => {
describe('deleteInvalidEmployer', () => {
it('should delete invalid employer', async () => {
mockEmployerModel.findById.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Sopra',
validated: false,
save: jest.fn().mockResolvedValueOnce(null),
});
mockEmployerSearchService.deleteIndex.mockResolvedValueOnce(null);
mockEmployerModel.deleteOne.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Sopra',
validated: false,
save: jest.fn().mockResolvedValueOnce(null),
......