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
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import * as ejs from 'ejs';
import { Model, Query, Types } from 'mongoose';
import * as mongodb from 'mongodb';
import { Model, Types } from 'mongoose';
import { MergeEmployerDto } from '../../admin/dto/merge-employer.dto';
import { MailerService } from '../../mailer/mailer.service';
import { CreateEmployerDto } from '../dto/create-employer.dto';
......@@ -28,7 +29,7 @@ export class EmployerService {
public async findOne(idParam: string): Promise<EmployerDocument> {
this.logger.debug('findOne');
return this.employerModel.findById(Types.ObjectId(idParam));
return this.employerModel.findById(new Types.ObjectId(idParam));
}
public async findAllUnvalidated(): Promise<Employer[]> {
......@@ -81,7 +82,7 @@ export class EmployerService {
public async validate(employerId: string): Promise<Employer> {
this.logger.debug(`validateEmployer: ${employerId}`);
const employer = await this.employerModel.findById(Types.ObjectId(employerId));
const employer = await this.employerModel.findById(new Types.ObjectId(employerId));
if (employer) {
employer.validated = true;
employer.save();
......@@ -93,7 +94,7 @@ export class EmployerService {
public async update(employerId: string, newEmployer: CreateEmployerDto): Promise<Employer> {
this.logger.debug(`editEmployer: ${employerId}`);
const employer = await this.employerModel.findById(Types.ObjectId(employerId));
const employer = await this.employerModel.findById(new Types.ObjectId(employerId));
if (employer) {
employer.name = newEmployer.name;
employer.save();
......@@ -108,8 +109,8 @@ export class EmployerService {
targetEmployerId,
}: MergeEmployerDto): Promise<Employer | HttpException> {
this.logger.debug(`mergeEmployer: ${sourceEmployerId} into ${targetEmployerId}`);
const sourceEmployer = await this.employerModel.findById(Types.ObjectId(sourceEmployerId));
const targetEmployer = await this.employerModel.findById(Types.ObjectId(targetEmployerId));
const sourceEmployer = await this.employerModel.findById(new Types.ObjectId(sourceEmployerId));
const targetEmployer = await this.employerModel.findById(new Types.ObjectId(targetEmployerId));
if (targetEmployer && sourceEmployer) {
this.userService.replaceEmployers(sourceEmployer, targetEmployer);
if (!sourceEmployer.validated) {
......@@ -121,17 +122,9 @@ export class EmployerService {
}
}
public async deleteInvalidEmployer(
id: string
): Promise<
Query<{
ok?: number;
n?: number;
deletedCount?: number;
}>
> {
public async deleteInvalidEmployer(id: string): Promise<mongodb.DeleteResult> {
this.logger.debug(`deleteInvalidEmployer: ${id}`);
const document = await this.employerModel.findById(Types.ObjectId(id));
const document = await this.employerModel.findById(new Types.ObjectId(id));
this.employerSearchService.deleteIndex(document, document._id);
return this.employerModel.deleteOne({ _id: id });
}
......@@ -144,15 +137,7 @@ export class EmployerService {
return employer.deleteOne();
}
public async deleteByName(
name: string
): Promise<
Query<{
ok?: number;
n?: number;
deletedCount?: number;
}>
> {
public async deleteByName(name: string): Promise<mongodb.DeleteResult> {
this.logger.debug(`deleteByname: ${name}`);
const document = await this.findByName(name);
this.employerSearchService.deleteIndex(document, document._id);
......
......@@ -68,7 +68,7 @@ describe('JobsService', () => {
it('should findAll validated jobs', async () => {
mockJobModel.find.mockResolvedValue([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFS',
validated: true,
hasPersonalOffer: true,
......@@ -80,7 +80,7 @@ describe('JobsService', () => {
it('should findAll all jobs', async () => {
mockJobModel.find.mockResolvedValue([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFSssss',
validated: false,
hasPersonalOffer: true,
......@@ -94,7 +94,7 @@ describe('JobsService', () => {
it('findUnvalidated', async () => {
mockJobModel.find.mockResolvedValue([
{
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFS',
validated: false,
hasPersonalOffer: true,
......@@ -106,7 +106,7 @@ describe('JobsService', () => {
it('findByName', async () => {
mockJobModel.findOne.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFS',
validated: true,
hasPersonalOffer: true,
......@@ -116,7 +116,7 @@ describe('JobsService', () => {
});
it('findOne', async () => {
mockJobModel.findById.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFS',
validated: true,
hasPersonalOffer: true,
......@@ -128,7 +128,7 @@ describe('JobsService', () => {
describe('createJob', () => {
it('create', async () => {
mockJobModel.create.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Dev',
validated: false,
hasPersonalOffer: false,
......@@ -163,7 +163,7 @@ describe('JobsService', () => {
it('createFromAdmin', async () => {
mockJobModel.create.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Dev',
validated: true,
hasPersonalOffer: false,
......@@ -179,7 +179,7 @@ describe('JobsService', () => {
describe('sendAdminCreateNotification', () => {
it('should sendAdminCreateNotification', async () => {
const job = {
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'Metro',
validated: true,
};
......@@ -220,7 +220,7 @@ describe('JobsService', () => {
describe('validate', () => {
it('should validate job', async () => {
mockJobModel.findById.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Dev',
validated: false,
save: jest.fn().mockResolvedValueOnce(null),
......@@ -243,14 +243,14 @@ describe('JobsService', () => {
describe('mergeJob', () => {
it('should delete source job', async () => {
const reply = {
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e61'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e61'),
name: 'Dev 2',
validated: true,
hasPersonalOffer: false,
};
mockJobModel.findById
.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Dev',
validated: false,
hasPersonalOffer: false,
......@@ -265,7 +265,7 @@ describe('JobsService', () => {
it('should throw error if target job is not validated', async () => {
mockJobModel.findById
.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Dev',
validated: false,
hasPersonalOffer: false,
......@@ -281,7 +281,7 @@ describe('JobsService', () => {
});
it('should throw error if no source or target job', async () => {
mockJobModel.findById.mockResolvedValueOnce(null).mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Dev',
validated: false,
hasPersonalOffer: false,
......@@ -306,7 +306,7 @@ describe('JobsService', () => {
describe('deleteOneId', () => {
it('should delete ', async () => {
mockJobModel.findOne.mockResolvedValueOnce({
_id: Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
_id: new Types.ObjectId('623aed68c5d45b6fbbaa7e60'),
name: 'Dev',
validated: false,
deleteOne: jest.fn().mockResolvedValueOnce('toto'),
......@@ -333,13 +333,13 @@ describe('JobsService', () => {
hasPersonalOffer: true,
};
const newJob = {
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFS',
validated: true,
hasPersonalOffer: true,
};
mockJobModel.findById.mockResolvedValue({
_id: Types.ObjectId('6231aefe76598527c8d0b5bc'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5bc'),
name: 'CNFS old',
validated: true,
hasPersonalOffer: false,
......
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import * as ejs from 'ejs';
import { Model, Query, Types } from 'mongoose';
import * as mongodb from 'mongodb';
import { Model, Types } from 'mongoose';
import { MergeJobDto } from '../../admin/dto/merge-job.dto';
import { MailerService } from '../../mailer/mailer.service';
import { CreateJobDto } from '../dto/create-job.dto';
......@@ -35,7 +36,7 @@ export class JobsService {
public async findOne(idParam: string): Promise<JobDocument> {
this.logger.debug('findOne');
return this.jobModel.findById(Types.ObjectId(idParam));
return this.jobModel.findById(new Types.ObjectId(idParam));
}
public async findAllUnvalidated(): Promise<IJob[]> {
......@@ -84,7 +85,7 @@ export class JobsService {
public async validate(jobId: string): Promise<Job> {
this.logger.debug(`validateJob: ${jobId}`);
const job = await this.jobModel.findById(Types.ObjectId(jobId));
const job = await this.jobModel.findById(new Types.ObjectId(jobId));
if (job) {
job.validated = true;
job.save();
......@@ -96,8 +97,8 @@ export class JobsService {
public async mergeJob({ sourceJobId, targetJobId }: MergeJobDto): Promise<Job | HttpException> {
this.logger.debug(`mergeJob: ${sourceJobId} into ${targetJobId}`);
const sourceJob = await this.jobModel.findById(Types.ObjectId(sourceJobId));
const targetJob = await this.jobModel.findById(Types.ObjectId(targetJobId));
const sourceJob = await this.jobModel.findById(new Types.ObjectId(sourceJobId));
const targetJob = await this.jobModel.findById(new Types.ObjectId(targetJobId));
if (targetJob && sourceJob) {
this.logger.debug(`Both jobs : ${sourceJob}, ${targetJob}`);
this.userService.replaceJobs(sourceJob, targetJob);
......@@ -110,15 +111,7 @@ export class JobsService {
}
}
public async deleteInvalidJob(
id: string
): Promise<
Query<{
ok?: number;
n?: number;
deletedCount?: number;
}>
> {
public async deleteInvalidJob(id: string): Promise<mongodb.DeleteResult> {
this.logger.debug(`deleteInvalidJob: ${id}`);
return this.jobModel.deleteOne({ _id: id });
}
......@@ -133,7 +126,7 @@ export class JobsService {
public async update(jobId: string, newJob: CreateJobDto): Promise<Job> {
this.logger.debug(`editJob: ${jobId}`);
const job = await this.jobModel.findById(Types.ObjectId(jobId));
const job = await this.jobModel.findById(new Types.ObjectId(jobId));
if (job) {
job.name = newJob.name;
job.hasPersonalOffer = newJob.hasPersonalOffer;
......
import { IndicesCreateResponse, 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 { UserRegistrySearchBody } from '../interfaces/userRegistry-search-body.interface';
import { UserRegistrySearchResult } from '../interfaces/userRegistry-search-response.interface';
import { IUserRegistry } from '../interfaces/userRegistry.interface';
@Injectable()
......@@ -14,10 +14,10 @@ export class UserRegistrySearchService {
public async indexUserRegistry(user: IUserRegistry): Promise<IUserRegistry> {
this.logger.debug(`indexUser ${user.name} ${user.surname}`);
this.elasticsearchService.index<UserRegistrySearchResult, UserRegistrySearchBody>({
this.elasticsearchService.index<UserRegistrySearchBody>({
index: this.index,
id: user._id,
body: {
document: {
name: user.name,
id: user._id,
surname: user.surname,
......@@ -28,37 +28,33 @@ export class UserRegistrySearchService {
return user;
}
public async createUserRegistryIndex(): Promise<any> {
public async createUserRegistryIndex(): Promise<IndicesCreateResponse> {
this.logger.debug('createUserRegistryIndex');
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');
const foundIndexes = (
await this.elasticsearchService.indices.exists({
index: this.index,
})
).body;
const foundIndexes = await this.elasticsearchService.indices.exists({
index: this.index,
});
if (foundIndexes) {
return this.elasticsearchService.indices.delete({
index: this.index,
......@@ -68,56 +64,52 @@ export class UserRegistrySearchService {
public async deleteIndex(user: IUserRegistry): Promise<IUserRegistry> {
this.logger.debug('deleteIndex');
this.elasticsearchService.delete<UserRegistrySearchResult, IUserRegistry>({
this.elasticsearchService.delete({
index: this.index,
id: user._id,
});
return user;
}
public async refreshIndexUserRegistry(): Promise<any> {
public async refreshIndexUserRegistry(): Promise<IndicesRefreshResponse> {
this.logger.debug('refreshIndexUserRegistry');
return this.elasticsearchService.indices.refresh({
index: this.index,
});
}
public async search(searchString: string): Promise<any[]> {
public async search(searchString: string): Promise<UserRegistrySearchBody[]> {
this.logger.debug(`search user with query: ${searchString}`);
searchString = searchString ? searchString + '*' : '*';
const { body } = await this.elasticsearchService.search<UserRegistrySearchResult>({
const { hits } = await this.elasticsearchService.search<UserRegistrySearchBody>({
index: this.index,
body: {
from: 0,
size: 200,
query: {
query_string: {
analyze_wildcard: 'true',
query: searchString,
fields: ['name', 'surname'],
fuzziness: 'AUTO',
},
from: 0,
size: 200,
query: {
query_string: {
analyze_wildcard: true,
query: searchString,
fields: ['name', 'surname'],
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(user: IUserRegistry): Promise<any> {
public async update(user: IUserRegistry): Promise<UpdateResponse<any>> {
this.logger.debug(`Updates user : ${user._id} `);
return this.elasticsearchService.update({
return this.elasticsearchService.update<UserRegistrySearchBody>({
index: this.index,
id: user._id,
body: {
doc: {
name: user.name,
surname: user.surname,
job: user.job,
employer: user.employer,
},
doc: {
name: user.name,
surname: user.surname,
job: user.job,
employer: user.employer,
},
});
}
......
......@@ -71,7 +71,7 @@ describe('userRegistryService', () => {
describe('findAll', () => {
const result: IUserRegistry[] = [
{
_id: Types.ObjectId('6319dfa79672971e1f8fe1b7'),
_id: new Types.ObjectId('6319dfa79672971e1f8fe1b7'),
surname: 'ADMIN',
name: 'Admin',
employer: {
......@@ -105,7 +105,7 @@ describe('userRegistryService', () => {
describe('find with filter', () => {
const result: IUserRegistry[] = [
{
_id: Types.ObjectId('6319dfa79672971e1f8fe1b7'),
_id: new Types.ObjectId('6319dfa79672971e1f8fe1b7'),
surname: 'ADMIN',
name: 'Admin',
employer: {
......@@ -124,7 +124,7 @@ describe('userRegistryService', () => {
count: 1,
docs: [
{
_id: Types.ObjectId('6319dfa79672971e1f8fe1b7'),
_id: new Types.ObjectId('6319dfa79672971e1f8fe1b7'),
surname: 'ADMIN',
name: 'Admin',
employer: {
......
......@@ -533,12 +533,12 @@ describe('UsersService', () => {
describe('updateUserProfile', () => {
const employer = {
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Metro',
validated: true,
} as EmployerDocument;
const job = {
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Developer',
validated: true,
} as JobDocument;
......@@ -546,15 +546,15 @@ describe('UsersService', () => {
it('should updateUserProfile', async () => {
const spyer = jest.spyOn(mockUserRegistrySearchService, 'update');
mockUserModel.findOne.mockReturnThis();
mockUserModel.updateOne.mockResolvedValueOnce(usersMockData[0]);
const result = await service.updateUserProfile(Types.ObjectId('627b85aea0466f0f132e1599'), employer, job);
mockUserModel.findByIdAndUpdate.mockResolvedValueOnce(usersMockData[0]);
const result = await service.updateUserProfile(new Types.ObjectId('627b85aea0466f0f132e1599'), employer, job);
expect(spyer).toBeCalledTimes(1);
expect(result).toEqual(usersMockData[0]);
});
it('should not updateUserProfile', async () => {
const spyer = jest.spyOn(mockUserRegistrySearchService, 'update');
mockUserModel.updateOne.mockResolvedValueOnce(null);
const result = await service.updateUserProfile(Types.ObjectId('627b85aea0466f0f132e1599'), employer, job);
mockUserModel.findByIdAndUpdate.mockResolvedValueOnce(null);
const result = await service.updateUserProfile(new Types.ObjectId('627b85aea0466f0f132e1599'), employer, job);
expect(spyer).toBeCalledTimes(0);
expect(result).toEqual(null);
});
......@@ -562,22 +562,22 @@ describe('UsersService', () => {
describe('updateUserJob', () => {
const job = {
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Developer',
validated: true,
} as JobDocument;
it('should updateUserJob', async () => {
const spyer = jest.spyOn(mockUserRegistrySearchService, 'update');
mockUserModel.updateOne.mockResolvedValueOnce(usersMockData[0]);
mockUserModel.findByIdAndUpdate.mockResolvedValueOnce(usersMockData[0]);
mockUserModel.findOne.mockReturnThis();
const result = await service.updateUserJob(Types.ObjectId('627b85aea0466f0f132e1599'), job);
const result = await service.updateUserJob(new Types.ObjectId('627b85aea0466f0f132e1599'), job);
expect(spyer).toBeCalledTimes(1);
expect(result).toEqual(usersMockData[0]);
});
it('should not updateUserJob', async () => {
const spyer = jest.spyOn(mockUserRegistrySearchService, 'update');
mockUserModel.updateOne.mockResolvedValueOnce(null);
const result = await service.updateUserJob(Types.ObjectId('627b85aea0466f0f132e1599'), job);
mockUserModel.findByIdAndUpdate.mockResolvedValueOnce(null);
const result = await service.updateUserJob(new Types.ObjectId('627b85aea0466f0f132e1599'), job);
expect(spyer).toBeCalledTimes(0);
expect(result).toEqual(null);
});
......@@ -585,21 +585,21 @@ describe('UsersService', () => {
describe('updateUserEmployer', () => {
const employer = {
_id: Types.ObjectId('6231aefe76598527c8d0b5ba'),
_id: new Types.ObjectId('6231aefe76598527c8d0b5ba'),
name: 'Metro',
validated: true,
} as EmployerDocument;
it('should updateUserEmployer', async () => {
const spyer = jest.spyOn(mockUserRegistrySearchService, 'update');
mockUserModel.updateOne.mockResolvedValueOnce(usersMockData[0]);
const result = await service.updateUserEmployer(Types.ObjectId('627b85aea0466f0f132e1599'), employer);
mockUserModel.findByIdAndUpdate.mockResolvedValueOnce(usersMockData[0]);
const result = await service.updateUserEmployer(new Types.ObjectId('627b85aea0466f0f132e1599'), employer);
expect(spyer).toBeCalledTimes(1);
expect(result).toEqual(usersMockData[0]);
});
it('should not updateUserEmployer', async () => {
const spyer = jest.spyOn(mockUserRegistrySearchService, 'update');
mockUserModel.updateOne.mockResolvedValueOnce(null);
const result = await service.updateUserEmployer(Types.ObjectId('627b85aea0466f0f132e1599'), employer);
mockUserModel.findByIdAndUpdate.mockResolvedValueOnce(null);
const result = await service.updateUserEmployer(new Types.ObjectId('627b85aea0466f0f132e1599'), employer);
expect(spyer).toBeCalledTimes(0);
expect(result).toEqual(null);
});
......
......@@ -4,6 +4,7 @@ import * as bcrypt from 'bcrypt';
import * as crypto from 'crypto';
import * as ejs from 'ejs';
import { DateTime } from 'luxon';
import { UpdateResult } from 'mongodb';
import { Model, Types } from 'mongoose';
import { PendingStructureDto } from '../../admin/dto/pending-structure.dto';
import { LoginDto } from '../../auth/login-dto';
......@@ -51,7 +52,7 @@ export class UsersService {
createUser.structuresLink = [];
if (createUserDto.structuresLink) {
createUserDto.structuresLink.forEach((structureId) => {
createUser.structuresLink.push(Types.ObjectId(structureId));
createUser.structuresLink.push(new Types.ObjectId(structureId));
});
}
createUser.password = await this.hashPassword(createUser.password);
......@@ -153,13 +154,13 @@ export class UsersService {
public async replaceEmployers(
sourceEmployer: EmployerDocument,
targetEmployer: EmployerDocument
): Promise<IUser[] | undefined> {
): Promise<UpdateResult> {
return this.userModel
.updateMany({ employer: sourceEmployer._id }, { $set: { employer: targetEmployer._id } })
.exec();
}
public async replaceJobs(sourceJob: JobDocument, targetJob: JobDocument): Promise<IUser[] | undefined> {
public async replaceJobs(sourceJob: JobDocument, targetJob: JobDocument): Promise<UpdateResult> {
return this.userModel.updateMany({ job: sourceJob._id }, { $set: { job: targetJob._id } }).exec();
}
......@@ -301,7 +302,7 @@ export class UsersService {
config,
token: token,
});
this.mailerService.send(user.email, jsonConfig.subject, html);
this.mailerService.send(emailDto.newEmail, jsonConfig.subject, html);
user.changeEmailToken = token;
user.newEmail = emailDto.newEmail;
user.save();
......@@ -394,7 +395,7 @@ export class UsersService {
}
public async isStructureClaimed(structureId: string): Promise<IUser> {
return this.userModel.findOne({ structuresLink: Types.ObjectId(structureId) }).exec();
return this.userModel.findOne({ structuresLink: new Types.ObjectId(structureId) }).exec();
}
public async isEmployerLinkedtoUser(id: string): Promise<boolean> {
......@@ -455,13 +456,13 @@ export class UsersService {
}
public getStructureOwners(structureId: string): Promise<IUser[]> {
return this.userModel.find({ structuresLink: Types.ObjectId(structureId) }).exec();
return this.userModel.find({ structuresLink: new Types.ObjectId(structureId) }).exec();
}
public async isUserAlreadyClaimedStructure(structureId: string, userEmail: string): Promise<boolean> {
const user = await this.findOne(userEmail, true);
if (user) {
return user.pendingStructuresLink.includes(Types.ObjectId(structureId));
return user.pendingStructuresLink.includes(new Types.ObjectId(structureId));
}
return false;
}
......@@ -505,8 +506,8 @@ export class UsersService {
public async updatePendingStructureLinked(userEmail: string, idStructure: string): Promise<Types.ObjectId[]> {
const user = await this.findOne(userEmail, true);
if (user) {
if (!user.pendingStructuresLink.includes(Types.ObjectId(idStructure))) {
user.pendingStructuresLink.push(Types.ObjectId(idStructure));
if (!user.pendingStructuresLink.includes(new Types.ObjectId(idStructure))) {
user.pendingStructuresLink.push(new Types.ObjectId(idStructure));
await user.save();
return user.pendingStructuresLink;
}
......@@ -518,9 +519,9 @@ export class UsersService {
public async removeFromPendingStructureLinked(userEmail: string, idStructure: string): Promise<Types.ObjectId[]> {
const user = await this.findOne(userEmail, true);
if (user) {
if (user.pendingStructuresLink.includes(Types.ObjectId(idStructure))) {
if (user.pendingStructuresLink.includes(new Types.ObjectId(idStructure))) {
user.pendingStructuresLink = user.pendingStructuresLink.filter((structureId) => {
return structureId === Types.ObjectId(idStructure);
return structureId === new Types.ObjectId(idStructure);
});
await user.save();
return user.pendingStructuresLink;
......@@ -533,8 +534,8 @@ export class UsersService {
public async updateStructureLinked(userEmail: string, idStructure: string): Promise<Types.ObjectId[]> {
const user = await this.findOne(userEmail, true);
if (user) {
if (!user.structuresLink.includes(Types.ObjectId(idStructure))) {
user.structuresLink.push(Types.ObjectId(idStructure));
if (!user.structuresLink.includes(new Types.ObjectId(idStructure))) {
user.structuresLink.push(new Types.ObjectId(idStructure));
user.unattachedSince = null;
await user.save();
return user.structuresLink;
......@@ -548,7 +549,7 @@ export class UsersService {
if (!user) {
throw new HttpException('Invalid user', HttpStatus.NOT_FOUND);
}
if (!user.structuresLink.includes(Types.ObjectId(idStructure))) {
if (!user.structuresLink.includes(new Types.ObjectId(idStructure))) {
throw new HttpException("User doesn't belong to this structure", HttpStatus.NOT_FOUND);
}
user.structuresLink = user.structuresLink.filter((structureId) => {
......@@ -591,20 +592,20 @@ export class UsersService {
const user = await this.findOne(userEmail);
// Get other users who have made the demand on the same structure
const otherUsers = await this.userModel
.find({ pendingStructuresLink: Types.ObjectId(structureId), email: { $ne: userEmail } })
.find({ pendingStructuresLink: new Types.ObjectId(structureId), email: { $ne: userEmail } })
.exec();
let status = false;
if (!user) {
throw new HttpException('User not found', HttpStatus.NOT_FOUND);
}
if (user.pendingStructuresLink.includes(Types.ObjectId(structureId))) {
if (user.pendingStructuresLink.includes(new Types.ObjectId(structureId))) {
user.pendingStructuresLink = user.pendingStructuresLink.filter((item) => {
return !Types.ObjectId(structureId).equals(item);
return !new Types.ObjectId(structureId).equals(item);
});
// If it's a validation case, push structureId into validated user structures
if (validate) {
user.structuresLink.push(Types.ObjectId(structureId));
user.structuresLink.push(new Types.ObjectId(structureId));
// Send validation email
status = true;
// For other users who have made the demand on the same structure
......@@ -612,7 +613,7 @@ export class UsersService {
otherUsers.forEach((otherUser) => {
// Remove the structure id from their demand
otherUser.pendingStructuresLink = otherUser.pendingStructuresLink.filter((item) => {
return !Types.ObjectId(structureId).equals(item);
return !new Types.ObjectId(structureId).equals(item);
});
// Send a rejection email
this.sendStructureClaimApproval(otherUser.email, structureName, false);
......@@ -633,10 +634,10 @@ export class UsersService {
public async removeOutdatedStructureFromArray(structureId: string): Promise<void> {
this.logger.debug(`removeOutdatedStructureFromArray for structure : ${structureId}`);
const users = await this.userModel.find({ structureOutdatedMailSent: Types.ObjectId(structureId) }).exec();
const users = await this.userModel.find({ structureOutdatedMailSent: new Types.ObjectId(structureId) }).exec();
users.forEach((user) => {
user.structureOutdatedMailSent = user.structureOutdatedMailSent.filter(
(item) => !Types.ObjectId(structureId).equals(item)
(item) => !new Types.ObjectId(structureId).equals(item)
);
user.save();
});
......@@ -667,7 +668,7 @@ export class UsersService {
public async getStructureOwnersDetails(structureId: string, emailUser: string): Promise<IUser[]> {
return this.userModel
.find({ structuresLink: Types.ObjectId(structureId), email: { $ne: emailUser } })
.find({ structuresLink: new Types.ObjectId(structureId), email: { $ne: emailUser } })
.populate('job')
.populate('employer')
.select('name surname job employer email')
......@@ -709,7 +710,7 @@ export class UsersService {
throw new HttpException('Invalid user', HttpStatus.NOT_FOUND);
}
user.personalOffers = user.personalOffers.filter(
(personalOffer) => !personalOffer._id.equals(Types.ObjectId(offerId))
(personalOffer) => !personalOffer._id.equals(new Types.ObjectId(offerId))
);
await user.save();
return user.personalOffers;
......@@ -724,7 +725,10 @@ export class UsersService {
*/
public async updateUserProfile(userId: Types.ObjectId, employer: EmployerDocument, job: JobDocument): Promise<any> {
this.logger.debug(`updateUserProfile | ${userId}`);
const updated = await this.userModel.updateOne({ _id: userId }, { $set: { employer: employer._id, job: job._id } });
const updated = await this.userModel.findByIdAndUpdate(
{ _id: userId },
{ $set: { employer: employer._id, job: job._id } }
);
if (updated) this.userRegistrySearchService.update(updated);
return updated;
}
......@@ -736,7 +740,7 @@ export class UsersService {
*/
public async updateUserJob(userId: Types.ObjectId, job: JobDocument): Promise<any> {
this.logger.debug(`updateUserProfile - Job | ${userId}`);
const updated = await this.userModel.updateOne({ _id: userId }, { $set: { job: job._id } });
const updated = await this.userModel.findByIdAndUpdate({ _id: userId }, { $set: { job: job._id } });
if (updated) {
const populatedResult = await this.findPopulatedUserRegistryById(updated._id);
this.userRegistrySearchService.update(populatedResult);
......@@ -751,7 +755,7 @@ export class UsersService {
*/
public async updateUserEmployer(userId: Types.ObjectId, employer: EmployerDocument): Promise<any> {
this.logger.debug(`updateUserProfile - Employer | ${userId}`);
const updated = await this.userModel.updateOne({ _id: userId }, { $set: { employer: employer._id } });
const updated = await this.userModel.findByIdAndUpdate({ _id: userId }, { $set: { employer: employer._id } });
if (updated) {
const populatedResult = await this.findPopulatedUserRegistryById(updated._id);
this.userRegistrySearchService.update(populatedResult);
......@@ -803,7 +807,7 @@ export class UsersService {
this.logger.debug('findByPersonalOfferId');
return this.userModel
.findOne({
personalOffers: { $all: [Types.ObjectId(id)] },
personalOffers: { $all: [new Types.ObjectId(id)] },
})
.populate('personalOffers')
.exec();
......
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "../src",
"testEnvironment": "node",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"reporters": ["default", "jest-junit"],
"collectCoverage": true
}
import { HttpException, HttpStatus } from '@nestjs/common';
import { PersonalOffer, PersonalOfferDocument } from '../../../src/personal-offers/schemas/personal-offer.schema';
import { PersonalOfferDocument } from '../../../src/personal-offers/schemas/personal-offer.schema';
import { CNFSStructure } from '../../../src/structures/interfaces/cnfs-structure.interface';
import { Structure, StructureDocument } from '../../../src/structures/schemas/structure.schema';
......@@ -1117,9 +1117,7 @@ export class StructuresServiceMock {
personalOfferDocument: PersonalOfferDocument
): Promise<StructureDocument> {
if (structureId === '6093ba0e2ab5775cfc01ed3e') {
const personalOffer: PersonalOffer = { ...personalOfferDocument } as PersonalOffer;
return {
_id: '6093ba0e2ab5775cfc01ed3e',
return new Structure({
coord: [4.8498155, 45.7514817],
categories: {
accessModality: ['accesLibre'],
......@@ -1214,11 +1212,14 @@ export class StructuresServiceMock {
nbScanners: 1,
freeWorkShop: false,
accountVerified: true,
personalOffers: [personalOffer],
personalOffers: [personalOfferDocument],
createdAt: new Date('2021-05-06T09:42:38.000Z'),
updatedAt: new Date('2021-05-06T09:42:50.000Z'),
__v: 0,
} as StructureDocument;
numero: '0606060606',
remoteAccompaniment: true,
deletedAt: null,
dataShareConsentDate: null,
}) as StructureDocument;
}
if (personalOfferDocument._id === 'unIdQuiExisteDeja') {
throw new HttpException('Personal offer already exist in the structure', HttpStatus.BAD_REQUEST);
......
......@@ -82,7 +82,7 @@ export class UsersServiceMock {
name: 'DUPONT',
surname: 'Pauline',
personalOffers: [],
structuresLink: [Types.ObjectId('6093ba0e2ab5775cfc01ed3e')],
structuresLink: [new Types.ObjectId('6093ba0e2ab5775cfc01ed3e')],
};
} else {
return null;
......
......@@ -6,11 +6,13 @@
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
}
"incremental": true,
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": ["src/**/*"]
}