Skip to content
Snippets Groups Projects
Commit ac2e87da authored by ALGLAVE Ivan's avatar ALGLAVE Ivan
Browse files

Added the ability to import multiple people at once using JSON format.

parent 25badb99
No related branches found
No related tags found
1 merge request!14Added the ability to import multiple people at once using JSON format.
...@@ -107,6 +107,53 @@ export class GroupsDao { ...@@ -107,6 +107,53 @@ export class GroupsDao {
); );
}); });
findByIdAndUpdateManyByRole = (
id: string,
role: string,
peopleIds: string[],
action: string,
): Promise<Group | void> =>
new Promise((resolve, reject) => {
let query = {};
if (action === 'post') {
switch (role) {
case Roles.ROLE_RESPONSIBLE:
query = { $addToSet: { responsibles: { $each: peopleIds } } };
break;
case Roles.ROLE_SECRETARY:
query = { $addToSet: { secretaries: { $each: peopleIds } } };
break;
case Roles.ROLE_STUDENT:
query = { $addToSet: { students: { $each: peopleIds } } };
break;
default:
reject(new BadRequestException('Bad role'));
}
} else if (action === 'delete') {
switch (role) {
case Roles.ROLE_RESPONSIBLE:
query = { $pull: { responsibles: { $in: peopleIds } } };
break;
case Roles.ROLE_SECRETARY:
query = { $pull: { secretaries: { $in: peopleIds } } };
break;
case Roles.ROLE_STUDENT:
query = { $pull: { students: { $in: peopleIds } } };
break;
default:
reject(new BadRequestException('Bad role'));
}
} else reject(new BadRequestException('Unknown action'));
this._groupModel.findByIdAndUpdate(
id,
query,
{ new: true },
(err, value) => {
if (err) reject(err.message);
resolve(value);
});
});
findByIdAndRemove = (id: string): Promise<Group | void> => findByIdAndRemove = (id: string): Promise<Group | void> =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
this._groupModel.findByIdAndDelete(id, {}, (err) => { this._groupModel.findByIdAndDelete(id, {}, (err) => {
......
...@@ -13,11 +13,17 @@ import { CreateGroupDto } from './dto/create-group.dto'; ...@@ -13,11 +13,17 @@ import { CreateGroupDto } from './dto/create-group.dto';
import { UpdateGroupDto } from './dto/update-group.dto'; import { UpdateGroupDto } from './dto/update-group.dto';
import { GroupEntity } from './entities/group.entity'; import { GroupEntity } from './entities/group.entity';
import { GroupsService } from './groups.service'; import { GroupsService } from './groups.service';
import { CreatePeopleDto } from 'src/people/dto/create-people.dto';
import { PeopleService } from 'src/people/people.service';
import { roleValue } from 'src/shared/Roles';
@Controller('groups') @Controller('groups')
@UseInterceptors(HttpInterceptor) @UseInterceptors(HttpInterceptor)
export class GroupsController { export class GroupsController {
constructor(private readonly _groupsService: GroupsService) {} constructor(
private readonly _groupsService: GroupsService,
private readonly _peopleService: PeopleService,
) {}
@Get() @Get()
findAll(): Promise<GroupEntity[] | void> { findAll(): Promise<GroupEntity[] | void> {
...@@ -34,6 +40,26 @@ export class GroupsController { ...@@ -34,6 +40,26 @@ export class GroupsController {
return this._groupsService.create(createGroupDto); return this._groupsService.create(createGroupDto);
} }
@Post(':id/import/:role')
async importAsFile(
@Param() params: { id: string; role: string },
@Body() people: CreatePeopleDto[],
): Promise<GroupEntity | void> {
const peopleEntities = await this._peopleService.createMany(
people.map((person) => {
person.role = roleValue(params.role);
return person;
}),
);
const peopleIds = peopleEntities.map((person) => person._id);
return this._groupsService.updateManyByRole(
params.id,
params.role,
peopleIds,
'post',
);
}
@Put(':id') @Put(':id')
update( update(
@Param() params: { id: string }, @Param() params: { id: string },
......
import { Module, Logger } from '@nestjs/common'; import { Module, Logger } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { PeopleDao } from 'src/people/dao/people.dao';
import { PeopleService } from 'src/people/people.service';
import { People, PeopleSchema } from 'src/people/schemas/people.schema';
import { GroupsDao } from './dao/groups.dao'; import { GroupsDao } from './dao/groups.dao';
import { GroupsController } from './groups.controller'; import { GroupsController } from './groups.controller';
import { GroupsService } from './groups.service'; import { GroupsService } from './groups.service';
...@@ -8,8 +11,9 @@ import { Group, GroupSchema } from './schemas/group.schema'; ...@@ -8,8 +11,9 @@ import { Group, GroupSchema } from './schemas/group.schema';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([{ name: Group.name, schema: GroupSchema }]), MongooseModule.forFeature([{ name: Group.name, schema: GroupSchema }]),
MongooseModule.forFeature([{ name: People.name, schema: PeopleSchema }]),
], ],
controllers: [GroupsController], controllers: [GroupsController],
providers: [GroupsService, GroupsDao, Logger], providers: [GroupsService, GroupsDao, Logger, PeopleService, PeopleDao],
}) })
export class GroupsModule {} export class GroupsModule {}
...@@ -27,6 +27,14 @@ export class GroupsService { ...@@ -27,6 +27,14 @@ export class GroupsService {
): Promise<GroupEntity | void> => ): Promise<GroupEntity | void> =>
this._groupsDao.findByIdAndUpdateRole(id, role, personId, action); this._groupsDao.findByIdAndUpdateRole(id, role, personId, action);
updateManyByRole = (
id: string,
role: string,
peopleIds: string[],
action: string,
): Promise<GroupEntity | void> =>
this._groupsDao.findByIdAndUpdateManyByRole(id, role, peopleIds, action);
delete(id: string): Promise<GroupEntity | void> { delete(id: string): Promise<GroupEntity | void> {
return this._groupsDao.findById(id).then((res) => { return this._groupsDao.findById(id).then((res) => {
if (res) { if (res) {
......
...@@ -120,9 +120,7 @@ export class InternshipDao { ...@@ -120,9 +120,7 @@ export class InternshipDao {
content: string | boolean, content: string | boolean,
): Promise<Internship | void> => ): Promise<Internship | void> =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
console.log('%s/%s: {%s}', studentId, state, content);
if (!isStateValid(state)) reject(BAD_REQUEST); if (!isStateValid(state)) reject(BAD_REQUEST);
console.log(content);
let nextState: string, contentHolder: string; let nextState: string, contentHolder: string;
let valid = false; let valid = false;
switch (state) { switch (state) {
......
...@@ -12,6 +12,8 @@ import { People } from '../schemas/people.schema'; ...@@ -12,6 +12,8 @@ import { People } from '../schemas/people.schema';
import * as Mailgun from 'mailgun-js'; import * as Mailgun from 'mailgun-js';
import config from 'src/config'; import config from 'src/config';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
import { PeopleEntity } from '../entities/people.entity';
import { CONFLICT } from 'src/shared/HttpError';
@Injectable() @Injectable()
export class PeopleDao { export class PeopleDao {
...@@ -73,6 +75,41 @@ export class PeopleDao { ...@@ -73,6 +75,41 @@ export class PeopleDao {
}); });
}; };
saveMany = async (people: CreatePeopleDto[]): Promise<PeopleEntity[]> =>
Promise.all(
people.map(
(person): Promise<PeopleEntity> =>
new Promise((resolve, reject) => {
this._peopleModel.findOne(
{ email: person.email },
{},
{},
(err, value) => {
if (err) {
reject(err.message);
} else if (!value) {
// Person does not exist -> create password + add to database
this.secret().then((value) => {
person.passwordHash = value;
new this._peopleModel(person).save((err, value) => {
if (err) reject(err.message);
if (!value) reject(new InternalServerErrorException());
this.sendPassword(person.email, person.passwordHash);
resolve(value);
});
});
} else {
resolve(value);
}
},
);
}),
),
);
// Check for existing people in database based on email
// Add missing people
// Get all added people as PeopleEntity to have access to IDs
findByIdAndUpdate = ( findByIdAndUpdate = (
id: string, id: string,
people: UpdatePeopleDto, people: UpdatePeopleDto,
......
import { IsBoolean, IsString, IsNotEmpty, IsOptional } from 'class-validator'; import { IsString, IsNotEmpty, IsOptional } from 'class-validator';
export class CreatePeopleDto { export class CreatePeopleDto {
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
firstname: string; firstname: string;
...@@ -16,8 +15,7 @@ export class CreatePeopleDto { ...@@ -16,8 +15,7 @@ export class CreatePeopleDto {
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
email: string; email: string;
@IsNotEmpty()
role: number;
} @IsOptional()
\ No newline at end of file role: number;
}
...@@ -11,4 +11,4 @@ export class PeopleEntity { ...@@ -11,4 +11,4 @@ export class PeopleEntity {
constructor(partial: Partial<People>) { constructor(partial: Partial<People>) {
Object.assign(this, partial); Object.assign(this, partial);
} }
} }
\ No newline at end of file
...@@ -29,7 +29,7 @@ export class PeopleController { ...@@ -29,7 +29,7 @@ export class PeopleController {
constructor(private readonly _peopleService: PeopleService) {} constructor(private readonly _peopleService: PeopleService) {}
@UseGuards(AuthGuard('jwt')) //@UseGuards(AuthGuard('jwt'))
@Get() @Get()
findAll(): Promise<PeopleEntity[] | void> { findAll(): Promise<PeopleEntity[] | void> {
return this._peopleService.findAll(); return this._peopleService.findAll();
......
...@@ -24,6 +24,10 @@ export class PeopleService { ...@@ -24,6 +24,10 @@ export class PeopleService {
return this._peopleDao.save(people); return this._peopleDao.save(people);
} }
createMany = (people: CreatePeopleDto[]): Promise<PeopleEntity[]> => {
return this._peopleDao.saveMany(people);
};
update = ( update = (
id: string, id: string,
people: UpdatePeopleDto, people: UpdatePeopleDto,
......
...@@ -12,3 +12,18 @@ export const ROLES = [ ...@@ -12,3 +12,18 @@ export const ROLES = [
export const isRoleValid = (potentialRole: string): boolean => export const isRoleValid = (potentialRole: string): boolean =>
ROLES.includes(potentialRole); ROLES.includes(potentialRole);
export const roleValue = (role: string): number => {
switch (role) {
case ROLE_STUDENT:
return 0;
case ROLE_SECRETARY:
return 1;
case ROLE_RESPONSIBLE:
return 2;
case ROLE_ADMIN:
return 9999;
default:
return -1;
}
};
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment