Skip to content

Commit

Permalink
Merge pull request #83 from ti-broish/protocols-data-v2
Browse files Browse the repository at this point in the history
  • Loading branch information
hkdobrev authored Jul 10, 2021
2 parents 6d39391 + a64e924 commit 2d9be8c
Show file tree
Hide file tree
Showing 28 changed files with 399 additions and 899 deletions.
7 changes: 2 additions & 5 deletions src/casl/casl-ability.factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Broadcast } from 'src/broadcasts/entities/broadcast.entity';
import { Party } from 'src/parties/entities/party.entity';
import { Picture } from 'src/pictures/entities/picture.entity';
import { Post } from 'src/posts/entities/post.entity';
import { ProtocolData } from 'src/protocols/entities/protocol-data.entity';
import { ProtocolResult } from 'src/protocols/entities/protocol-result.entity';
import { Protocol } from 'src/protocols/entities/protocol.entity';
import {
Expand Down Expand Up @@ -40,10 +39,8 @@ type Subjects =
| typeof Stream
| Stream
| typeof Protocol
| typeof ProtocolData
| typeof ProtocolResult
| Protocol
| ProtocolData
| ProtocolResult
| typeof Section
| typeof CityRegion
Expand Down Expand Up @@ -132,8 +129,8 @@ export class CaslAbilityFactory {
}

if (user.hasRole(Role.Validator) || user.hasRole(Role.Admin)) {
can(Action.Read, [Protocol, ProtocolResult, ProtocolData]);
can(Action.Create, [ProtocolResult, ProtocolData]);
can(Action.Read, [Protocol, ProtocolResult]);
can(Action.Create, [ProtocolResult]);
can(Action.Update, Protocol, ['status']);
// Can see the organization of the user submitted the protocol
can(Action.Read, User, ['organization']);
Expand Down
43 changes: 43 additions & 0 deletions src/migrations/1625769115216-AddProtocolDataResultsV2Columns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddProtocolDataResultsV2Columns1625769115216
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "protocol_results" add column "machine_votes" jsonb default null;
`);
await queryRunner.query(`
update "protocol_results"
set "machine_votes" = ('[' || "machine_votes_count" || ']')::jsonb
where "machine_votes_count" > 0;
`);
await queryRunner.query(`
alter table "protocols" add column "metadata" jsonb default null;
`);
await queryRunner.query(`
update "protocols" set "metadata" = json_build_object(
'validVotesCount', "protocol_data"."valid_votes_count",
'invalidVotesCount', "protocol_data"."invalid_votes_count",
'machineVotesCount', "protocol_data"."machine_votes_count",
'votersCount', "protocol_data"."voters_count"
)
from "protocol_data" where protocol_data.protocol_id = protocols.id;
`);
await queryRunner.query(`
alter table "protocol_results" drop column "invalid_votes_count";
`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
alter table "protocol_results" add column "invalid_votes_count" integer default null;
`);
await queryRunner.query(`
alter table "protocols" drop column "metadata";
`);
await queryRunner.query(`
alter table "protocol_results" drop column "machine_votes";
`);
}
}
54 changes: 1 addition & 53 deletions src/protocols/api/protocol-assignees.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ import {
UsePipes,
Inject,
UseGuards,
Put,
ParseArrayPipe,
Delete,
NotFoundException,
BadRequestException,
ForbiddenException,
} from '@nestjs/common';
import { Action } from '../../casl/action.enum';
Expand All @@ -31,7 +27,6 @@ import { User } from '../../users/entities';
import { Protocol } from '../entities/protocol.entity';
import { ProtocolsRepository } from '../entities/protocols.repository';
import { CaslAbilityFactory } from 'src/casl/casl-ability.factory';
import { ApiTags } from '@nestjs/swagger';
import { WorkQueue } from './work-queue.service';

@Controller('protocols')
Expand All @@ -56,52 +51,10 @@ export class ProtocolAssigneesController {
return protocol.assignees.map((user: User) => UserDto.fromEntity(user));
}

/**
* @deprecated No need to manage multiple assignees at once
*/
@Put(':protocol/assignees')
@ApiTags('Deprecated')
@HttpCode(200)
@UseGuards(PoliciesGuard)
@CheckPolicies((ability: Ability) => ability.can(Action.Update, Protocol))
@UsePipes(
new ValidationPipe({
transform: true,
transformOptions: { groups: ['assignee'] },
groups: ['assignee'],
}),
)
async putAssignees(
@Param('protocol') protocolId: string,
@Body(
new ParseArrayPipe({
items: UserDto,
transformOptions: { groups: ['assignee'] },
groups: ['assignee'],
}),
)
assigneeDtos: UserDto[],
@InjectUser() user: User,
): Promise<AcceptedResponse> {
if (assigneeDtos.length > 1) {
throw new BadRequestException(
'CANNOT_ASSIGN_MORE_THAN_ONE_PERSON_TO_PROTOCOL',
);
}
const protocol = await this.protocolsRepo.findOneOrFail(protocolId);
protocol.assign(
user,
assigneeDtos.map((userDto: UserDto) => userDto.toEntity()),
);
await this.protocolsRepo.save(protocol);

return { status: ACCEPTED_RESPONSE_STATUS };
}

@Post(':protocol/assignees')
@HttpCode(201)
@UseGuards(PoliciesGuard)
@CheckPolicies((ability: Ability) => ability.can(Action.Update, Protocol))
@CheckPolicies((ability: Ability) => ability.can(Action.Manage, Protocol))
@UsePipes(
new ValidationPipe({
transform: true,
Expand All @@ -116,11 +69,6 @@ export class ProtocolAssigneesController {
): Promise<AcceptedResponse> {
this.checkIfCanEditAssignees(actor, assigneeDto.id);
const protocol = await this.protocolsRepo.findOneOrFail(protocolId);
if (protocol.assignees.length > 0) {
throw new BadRequestException(
'CANNOT_ASSIGN_MORE_THAN_ONE_PERSON_TO_PROTOCOL',
);
}
protocol.assign(actor, [...protocol.assignees, assigneeDto.toEntity()]);
await this.protocolsRepo.save(protocol);

Expand Down
77 changes: 77 additions & 0 deletions src/protocols/api/protocol-result.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { Expose, plainToClass, Transform, Type } from 'class-transformer';
import {
ArrayNotEmpty,
IsArray,
IsInt,
IsNotEmpty,
IsNumber,
IsOptional,
Min,
ValidateNested,
} from 'class-validator';
import { PartyDto } from '../../parties/api/party.dto';
import { ProtocolResult } from '../entities/protocol-result.entity';
import { Protocol } from '../entities/protocol.entity';

export class ProtocolResultDto {
@Transform(
({ value: id }) => plainToClass(PartyDto, { id }, { groups: ['create'] }),
{ groups: ['create', 'replace'] },
)
@ValidateNested({
groups: ['create', 'replace'],
})
@Type(() => PartyDto)
@Expose({ groups: ['read', 'create', 'replace'] })
party: PartyDto;

@Expose({ groups: ['read'] })
validVotesCount: number;

@IsOptional({ groups: ['read', 'replace'] })
@IsNumber({}, { each: true, groups: ['replace'] })
@IsNotEmpty({ groups: ['replace'] })
@Min(0, { each: true, groups: ['replace'] })
@IsInt({ each: true, groups: ['replace'] })
@Expose({ groups: ['read', 'replace'] })
@IsArray({ groups: ['replace'] })
@ArrayNotEmpty({ groups: ['replace'] })
machineVotes?: number[];

@IsOptional({ groups: ['read', 'replace'] })
@IsNumber({}, { groups: ['replace'] })
@IsNotEmpty({ groups: ['replace'] })
@Min(0, { groups: ['replace'] })
@IsInt({ groups: ['replace'] })
@Expose({ groups: ['read', 'replace'] })
nonMachineVotesCount?: number;

public toEntity(): ProtocolResult {
const protocolResult = plainToClass<
ProtocolResult,
Partial<ProtocolResultDto>
>(ProtocolResult, this, {
groups: ['create', 'replace'],
});
const validVotes = (protocolResult.machineVotes || []).concat([
protocolResult.nonMachineVotesCount || 0,
]);

protocolResult.validVotesCount = validVotes.reduce(
(sum: number, votes: number): number => sum + votes,
);

return protocolResult;
}

public static fromEntity(entity: ProtocolResult): ProtocolResultDto {
return plainToClass<ProtocolResultDto, Partial<Protocol>>(
ProtocolResultDto,
entity,
{
excludeExtraneousValues: true,
groups: ['read'],
},
);
}
}
157 changes: 0 additions & 157 deletions src/protocols/api/protocol-results.dto.ts

This file was deleted.

Loading

0 comments on commit 2d9be8c

Please sign in to comment.