Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/marxan 1345 export scenario selection #924

Merged
merged 4 commits into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,49 +14,57 @@ beforeEach(async () => {
fixtures = await getFixtures();
});

it('should return project pieces when resolving for a project', async () => {
it('resolves project pieces', async () => {
const projectId = fixtures.GivenAProjectExport();
const result = await fixtures.WhenRequestingExportPieces(
projectId,
ResourceKind.Project,
[],
);
fixtures.ThenProjectPiecesShouldBeIncluded({ components: result });
});

it(`should return ${ClonePiece.PlanningAreaCustom} when resolving for a project with a custom planning area`, async () => {
it(`resolves ${ClonePiece.PlanningAreaCustom} piece when invoked with a custom planning area project`, async () => {
const projectId = fixtures.GivenAProjectExportWithCustomPlanningArea();
const result = await fixtures.WhenRequestingExportPieces(
projectId,
ResourceKind.Project,
[],
);
fixtures.ThenProjectPiecesShouldBeIncluded({
components: result,
projectWithCustomPlanningArea: true,
});
});

it('should return scenario pieces when resolving for a scenario', async () => {
it('resolves scenario pieces', async () => {
const scenarioId = fixtures.GivenAScenarioExport();
const result = await fixtures.WhenRequestingExportPieces(
scenarioId,
ResourceKind.Scenario,
[],
);
fixtures.ThenScenarioPiecesShouldBeIncluded({
components: result,
});
});

it('should return project and scenario pieces when resolving for a project if the project has scenarios', async () => {
const scenariosCount = 2;
const projectId = fixtures.GivenAProjectExportWithScenarios(scenariosCount);
it('resolves project and specific scenario pieces when invoked specifying an array of scenarios ids', async () => {
const projectScenariosCount = 5;
const [projectId, scenariosIds] = fixtures.GivenAProjectExportWithScenarios(
projectScenariosCount,
);
const scenariosToBeExportedCount = 2;

const result = await fixtures.WhenRequestingExportPieces(
projectId,
ResourceKind.Project,
scenariosIds.slice(0, scenariosToBeExportedCount),
);
fixtures.ThenProjectAndScenarioPiecesShouldBeIncluded({
components: result,
projectWithCustomPlanningArea: false,
scenariosCount,
scenariosCount: scenariosToBeExportedCount,
});
});

Expand Down Expand Up @@ -106,33 +114,50 @@ const getFixtures = async () => {
return {
GivenAProjectExport: () => {
const projectId = ResourceId.create();
repo.mockProject(projectId.value, {});

return projectId;
},
GivenAProjectExportWithARegularPlanningArea: () => {
const projectId = ResourceId.create();
repo.mockProject(projectId.value, {});

return projectId;
},
GivenAProjectExportWithCustomPlanningArea: () => {
const projectId = ResourceId.create();

repo.mockProject(projectId.value, { planningAreaGeometryId: v4() });

return projectId;
},
GivenAProjectExportWithScenarios: (scenariosCount: number) => {
GivenAProjectExportWithScenarios: (
scenariosCount: number,
): [ResourceId, string[]] => {
const projectId = ResourceId.create();
const scenarios = Array(scenariosCount).fill({ id: v4() });
const scenarios: { id: string }[] = Array(scenariosCount)
.fill(0)
.map(() => ({
id: v4(),
}));

repo.mockProject(projectId.value, {
scenarios,
});

return projectId;
return [projectId, scenarios.map((scenario) => scenario.id)];
},
GivenAScenarioExport: () => {
return ResourceId.create();
},
WhenRequestingExportPieces: (id: ResourceId, kind: ResourceKind) => {
return sut.resolveFor(id, kind);
WhenRequestingExportPieces: (
id: ResourceId,
kind: ResourceKind,
scenarioIds: string[],
) => {
if (kind === ResourceKind.Project)
return sut.resolveForProject(id, scenarioIds);

return sut.resolveForScenario(id, kind);
},
ThenProjectPiecesShouldBeIncluded: ({
components,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,41 +8,34 @@ import { ExportComponent } from '../domain';

@Injectable()
export class ExportResourcePiecesAdapter implements ExportResourcePieces {
private resolverMapping: Record<
ResourceKind,
(id: ResourceId, kind: ResourceKind) => Promise<ExportComponent[]>
> = {
project: this.resolveForProject.bind(this),
scenario: this.resolveForScenario.bind(this),
};

constructor(
@InjectRepository(Project)
private readonly projectRepository: Repository<Project>,
) {}

resolveFor(id: ResourceId, kind: ResourceKind): Promise<ExportComponent[]> {
return this.resolverMapping[kind](id, kind);
}

private async resolveForProject(
async resolveForProject(
id: ResourceId,
kind: ResourceKind,
scenarioIds: string[],
): Promise<ExportComponent[]> {
const project = await this.projectRepository.findOneOrFail(id.value, {
relations: ['scenarios'],
});
const { scenarios } = project;

const scenarioPieces: ExportComponent[][] = [];
const scenarioPieces: ExportComponent[] = [];

if (scenarios) {
scenarioPieces.push(
...(await Promise.all(
scenarios.map((scenario) =>
this.resolveForScenario(new ResourceId(scenario.id), kind),
...scenarios
.filter(
(scenario) => !scenarioIds || scenarioIds.includes(scenario.id),
)
.flatMap((scenario) =>
this.resolveForScenario(
new ResourceId(scenario.id),
ResourceKind.Project,
),
),
)),
);
}

Expand All @@ -62,16 +55,13 @@ export class ExportResourcePiecesAdapter implements ExportResourcePieces {
ExportComponent.newOne(id, ClonePiece.PlanningUnitsGrid),
ExportComponent.newOne(id, ClonePiece.PlanningUnitsGridGeojson),
ExportComponent.newOne(id, ClonePiece.ProjectCustomProtectedAreas),
...scenarioPieces.flat(),
...scenarioPieces,
];

return components;
}

private async resolveForScenario(
id: ResourceId,
kind: ResourceKind,
): Promise<ExportComponent[]> {
resolveForScenario(id: ResourceId, kind: ResourceKind): ExportComponent[] {
const pieces: ExportComponent[] = [
ExportComponent.newOne(id, ClonePiece.ScenarioMetadata),
ExportComponent.newOne(id, ClonePiece.ScenarioProtectedAreas),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { ResourceId } from '@marxan/cloning/domain';
import { ExportId } from '../domain';

export class ExportProject extends Command<ExportId> {
constructor(public readonly id: ResourceId) {
constructor(
public readonly id: ResourceId,
public readonly scenarioIds: string[],
) {
super();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const getFixtures = async () => {
return { projectId };
},
WhenExportIsRequested: async (projectId: ResourceId) =>
sut.execute(new ExportProject(projectId)),
sut.execute(new ExportProject(projectId, [])),
ThenExportRequestIsSaved: async (exportId: ExportId) => {
expect((await repo.find(exportId))?.toSnapshot()).toBeDefined();
},
Expand Down Expand Up @@ -115,13 +115,17 @@ const getFixtures = async () => {
@Injectable()
class FakePiecesProvider implements ExportResourcePieces {
resolveMock: jest.MockedFunction<
ExportResourcePieces['resolveFor']
ExportResourcePieces['resolveForProject']
> = jest.fn();

async resolveFor(
async resolveForProject(
id: ResourceId,
kind: ResourceKind,
scenarioIds: string[],
): Promise<ExportComponent[]> {
return this.resolveMock(id, kind);
return this.resolveMock(id, scenarioIds);
}

resolveForScenario(id: ResourceId, kind: ResourceKind): ExportComponent[] {
return [];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export class ExportProjectHandler
private readonly eventPublisher: EventPublisher,
) {}

async execute({ id }: ExportProject): Promise<ExportId> {
async execute({ id, scenarioIds }: ExportProject): Promise<ExportId> {
const kind = ResourceKind.Project;
const pieces = await this.resourcePieces.resolveFor(id, kind);
const pieces = await this.resourcePieces.resolveForProject(id, scenarioIds);
const exportRequest = this.eventPublisher.mergeObjectContext(
Export.newOne(id, kind, pieces),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ import { ResourceId, ResourceKind } from '@marxan/cloning/domain';
import { ExportComponent } from '../domain';

export abstract class ExportResourcePieces {
abstract resolveFor(
abstract resolveForProject(
id: ResourceId,
kind: ResourceKind,
scenarioIds: string[],
): Promise<ExportComponent[]>;

abstract resolveForScenario(
id: ResourceId,
kind: ResourceKind,
): ExportComponent[];
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class ExportScenarioHandler

async execute({ scenarioId, projectId }: ExportScenario): Promise<ExportId> {
const kind = ResourceKind.Scenario;
const pieces = await this.resourcePieces.resolveFor(scenarioId, kind);
const pieces = this.resourcePieces.resolveForScenario(scenarioId, kind);
const exportRequest = this.eventPublisher.mergeObjectContext(
Export.newOne(projectId, kind, pieces),
);
Expand Down
24 changes: 24 additions & 0 deletions api/apps/api/src/modules/projects/dto/export.project.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsUUID } from 'class-validator';

export class RequestProjectExportBodyDto {
@ApiProperty({
description: 'Array of ids of scenarios to be exported',
isArray: true,
type: 'string',
example: [
'c214c6b9-1683-4b95-9221-8e378932fad1',
'873c952c-86e7-4fee-b2d8-500c3f72ad80',
],
})
@IsUUID(4, { each: true })
scenarioIds!: string[];
}

export class RequestProjectExportResponseDto {
@ApiProperty({
description: 'ID of the project',
example: '6fbec34e-04a7-4131-be14-c245f2435a6c',
})
id!: string;
}

This file was deleted.

19 changes: 14 additions & 5 deletions api/apps/api/src/modules/projects/projects.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@ import {
IsMissingAclImplementation,
} from '@marxan-api/decorators/acl.decorator';
import { locationNotFound } from '@marxan-api/modules/clone/export/application/get-archive.query';
import { RequestProjectExportResponseDto } from './dto/export.project.response.dto';
import {
RequestProjectExportResponseDto,
RequestProjectExportBodyDto,
} from './dto/export.project.dto';
import { ScenarioLockResultPlural } from '@marxan-api/modules/access-control/scenarios-acl/locks/dto/scenario.lock.dto';
import { RequestProjectImportResponseDto } from './dto/import.project.response.dto';
import { unknownError as fileRepositoryUnknownError } from '@marxan/files-repository';
Expand Down Expand Up @@ -417,7 +420,10 @@ export class ProjectsController {
throw new ForbiddenException();
}
req.url = req.url.replace(result.right.from, result.right.to);
req.originalUrl = req.originalUrl.replace(result.right.from, result.right.to);
req.originalUrl = req.originalUrl.replace(
result.right.from,
result.right.to,
);

return await this.proxyService.proxyTileRequest(req, response);
}
Expand Down Expand Up @@ -463,10 +469,11 @@ export class ProjectsController {
throw new ForbiddenException();
}



req.url = req.url.replace(result.right.from, result.right.to);
req.originalUrl = req.originalUrl.replace(result.right.from, result.right.to);
req.originalUrl = req.originalUrl.replace(
result.right.from,
result.right.to,
);

req.query = result.right.query;

Expand Down Expand Up @@ -590,10 +597,12 @@ export class ProjectsController {
async requestProjectExport(
@Param('projectId') projectId: string,
@Req() req: RequestWithAuthenticatedUser,
@Body() dto: RequestProjectExportBodyDto,
) {
const result = await this.projectsService.requestExport(
projectId,
req.user.id,
dto.scenarioIds,
);

if (isLeft(result)) {
Expand Down
Loading