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(api): allow to get scenarios solutions results #264

Merged
merged 4 commits into from
Jun 17, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
@@ -0,0 +1,40 @@
import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger';
import { ScenariosOutputResultsGeoEntity } from '@marxan/scenarios-planning-unit';

class ScenarioSolutionsDataDto {
@ApiProperty()
type: 'solutions' = 'solutions';

@ApiProperty()
id!: string;

@ApiProperty({
isArray: true,
type: () => ScenariosOutputResultsGeoEntity,
})
attributes!: ScenariosOutputResultsGeoEntity[];
}

class ScenarioSolutionDataDto {
@ApiProperty()
type: 'solution' = 'solution';

@ApiProperty()
id!: string;

@ApiProperty({
type: () => ScenariosOutputResultsGeoEntity,
})
attributes!: ScenariosOutputResultsGeoEntity;
}

@ApiExtraModels(ScenarioSolutionsDataDto, ScenarioSolutionDataDto)
export class ScenarioSolutionResultDto {
@ApiProperty({
oneOf: [
{ $ref: getSchemaPath(ScenarioSolutionsDataDto) },
{ $ref: getSchemaPath(ScenarioSolutionDataDto) },
],
})
data!: ScenarioSolutionsDataDto | ScenarioSolutionDataDto;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Injectable } from '@nestjs/common';
import { PaginationMeta } from '@marxan-api/utils/app-base.service';
import { ScenariosOutputResultsGeoEntity } from '@marxan/scenarios-planning-unit';
import { SolutionResultCrudService } from '../solutions-result/solution-result-crud.service';

@Injectable()
export class ScenarioSolutionSerializer {
constructor(
private readonly scenariosSolutionsCrudService: SolutionResultCrudService,
) {}

async serialize(
entities:
| Partial<ScenariosOutputResultsGeoEntity>
| (Partial<ScenariosOutputResultsGeoEntity> | undefined)[],
paginationMeta?: PaginationMeta,
): Promise<any> {
return this.scenariosSolutionsCrudService.serialize(
entities,
paginationMeta,
);
}
}
56 changes: 56 additions & 0 deletions api/apps/api/src/modules/scenarios/scenarios.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import {
Delete,
Get,
Param,
ParseBoolPipe,
ParseUUIDPipe,
Patch,
Post,
Query,
Req,
UploadedFile,
UseGuards,
Expand All @@ -26,6 +28,7 @@ import {
ApiNoContentResponse,
ApiOkResponse,
ApiOperation,
ApiQuery,
ApiTags,
} from '@nestjs/swagger';
import { apiGlobalPrefixes } from '@marxan-api/api.config';
Expand All @@ -47,6 +50,9 @@ import { FileInterceptor } from '@nestjs/platform-express';
import { ScenariosService } from './scenarios.service';
import { ScenarioSerializer } from './dto/scenario.serializer';
import { ScenarioFeatureSerializer } from './dto/scenario-feature.serializer';
import { ScenarioFeatureResultDto } from './dto/scenario-feature-result.dto';
import { ScenarioSolutionResultDto } from './dto/scenario-solution-result.dto';
import { ScenarioSolutionSerializer } from './dto/scenario-solution.serializer';

@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
Expand All @@ -57,6 +63,7 @@ export class ScenariosController {
private readonly service: ScenariosService,
private readonly scenarioSerializer: ScenarioSerializer,
private readonly scenarioFeatureSerializer: ScenarioFeatureSerializer,
private readonly scenarioSolutionSerializer: ScenarioSolutionSerializer,
) {}

@ApiOperation({
Expand Down Expand Up @@ -170,4 +177,53 @@ export class ScenariosController {
await this.service.getFeatures(id),
);
}

@ApiOkResponse({
type: ScenarioSolutionResultDto,
})
@ApiQuery({
name: 'best',
required: false,
type: Boolean,
})
@ApiQuery({
name: 'most-different',
required: false,
type: Boolean,
})
@JSONAPIQueryParams()
@Get(`:id/marxan/run/:runId/solutions`)
async getScenarioRunSolutions(
@Param('id', ParseUUIDPipe) id: string,
@Param('runId', ParseUUIDPipe) runId: string,
@ProcessFetchSpecification() fetchSpecification: FetchSpecification,
@Query('best', ParseBoolPipe) selectOnlyBest?: boolean,
@Query('most-different', ParseBoolPipe) selectMostDifferent?: boolean,
Comment on lines +203 to +204
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

they seem to be mutually exclusive
maybe it's not a problem, though
also a dto could be used here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, they are exclusive (and returning different DTO). Any idea how to show it in code?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

honestly I'd create another method and route for it, trying to show it in the code with one method is tricky (especially when you'd like to keep it in the openapi spec) and can be not worth the effort

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd go with @Dyostiq 's suggestion

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or make bestSolution and oneOfFiveMostDifferentSolutions (or something like this) column-based props of the entity, which would allow to filter via ?filter[bestSolution]=true or ?filter[oneOfBlaBla]=true.

but semantically I prefer separate endpoints - if we expose these props as part of the entity then API consumers could as well just filter client-side, IMO.

:id/marxan/run/:runId/solutions/best
:id/marxan/run/:runId/solutions/most-different

at the expense of some controller handler boilerplate duplication, though a minor evil here IMO.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kgajowy should we remove in a new PR the best and most-different queries and relative code paths in this controller, or did you want to leave these in to let API clients query for best and most different solutions in either way? (I am fine either way, though I'd prefer to have only one way to query for best and most efficient, via their own endpoint).

): Promise<ScenarioFeatureResultDto> {
if (selectOnlyBest) {
return this.scenarioSolutionSerializer.serialize(
await this.service.getBestSolution(id, runId),
);
}
if (selectMostDifferent) {
const result = await this.service.getMostDifferentSolutions(
id,
runId,
fetchSpecification,
);
return this.scenarioSolutionSerializer.serialize(
result.data,
result.metadata,
);
}
const result = await this.service.findAllSolutionsPaginated(
id,
runId,
fetchSpecification,
);
return this.scenarioSolutionSerializer.serialize(
result.data,
result.metadata,
);
}
}
10 changes: 10 additions & 0 deletions api/apps/api/src/modules/scenarios/scenarios.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,21 @@ import { ScenariosService } from './scenarios.service';
import { ScenarioSerializer } from './dto/scenario.serializer';
import { ScenarioFeatureSerializer } from './dto/scenario-feature.serializer';
import { CostSurfaceTemplateModule } from './cost-surface-template';
import { SolutionResultCrudService } from './solutions-result/solution-result-crud.service';
import { DbConnections } from '@marxan-api/ormconfig.connections';
import { ScenariosOutputResultsGeoEntity } from '@marxan/scenarios-planning-unit';
import { ScenarioSolutionSerializer } from './dto/scenario-solution.serializer';

@Module({
imports: [
CqrsModule,
ProtectedAreasModule,
forwardRef(() => ProjectsModule),
TypeOrmModule.forFeature([Project, Scenario]),
TypeOrmModule.forFeature(
[ScenariosOutputResultsGeoEntity],
DbConnections.geoprocessingDB,
),
UsersModule,
ScenarioFeaturesModule,
AnalysisModule,
Expand All @@ -39,6 +47,8 @@ import { CostSurfaceTemplateModule } from './cost-surface-template';
WdpaAreaCalculationService,
ScenarioSerializer,
ScenarioFeatureSerializer,
SolutionResultCrudService,
ScenarioSolutionSerializer,
],
controllers: [ScenariosController],
exports: [ScenariosCrudService, ScenariosService],
Expand Down
37 changes: 37 additions & 0 deletions api/apps/api/src/modules/scenarios/scenarios.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ScenariosCrudService } from './scenarios-crud.service';
import { CreateScenarioDTO } from './dto/create.scenario.dto';
import { UpdateScenarioDTO } from './dto/update.scenario.dto';
import { UpdateScenarioPlanningUnitLockStatusDto } from './dto/update-scenario-planning-unit-lock-status.dto';
import { SolutionResultCrudService } from './solutions-result/solution-result-crud.service';

@Injectable()
export class ScenariosService {
Expand All @@ -26,6 +27,7 @@ export class ScenariosService {
private readonly updatePlanningUnits: AdjustPlanningUnits,
private readonly costSurface: CostSurfaceFacade,
private readonly httpService: HttpService,
private readonly solutionsCrudService: SolutionResultCrudService,
) {}

async findAllPaginated(fetchSpecification: FetchSpecification) {
Expand Down Expand Up @@ -103,7 +105,42 @@ export class ScenariosService {
return geoJson;
}

async findScenarioResults(
scenarioId: string,
runId: string,
fetchSpecification: FetchSpecification,
) {
await this.assertScenario(scenarioId);
return this.solutionsCrudService.findAll(fetchSpecification);
}

private async assertScenario(scenarioId: string) {
await this.crudService.getById(scenarioId);
}

async getBestSolution(scenarioId: string, runId: string) {
await this.assertScenario(scenarioId);
// TODO correct implementation
return this.solutionsCrudService.getById(runId);
}

async getMostDifferentSolutions(
scenarioId: string,
runId: string,
fetchSpecification: FetchSpecification,
) {
await this.assertScenario(scenarioId);
// TODO correct implementation
return this.solutionsCrudService.findAllPaginated(fetchSpecification);
}

async findAllSolutionsPaginated(
scenarioId: string,
runId: string,
fetchSpecification: FetchSpecification,
) {
await this.assertScenario(scenarioId);
// TODO correct implementation
return this.solutionsCrudService.findAllPaginated(fetchSpecification);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import {
AppBaseService,
JSONAPISerializerConfig,
} from '@marxan-api/utils/app-base.service';

import { AppInfoDTO } from '@marxan-api/dto/info.dto';
import { AppConfig } from '@marxan-api/utils/config.utils';
import { FetchSpecification } from 'nestjs-base-service';
import { ScenariosOutputResultsGeoEntity } from '@marxan/scenarios-planning-unit';
import { DbConnections } from '@marxan-api/ormconfig.connections';

@Injectable()
export class SolutionResultCrudService extends AppBaseService<
ScenariosOutputResultsGeoEntity,
never,
never,
AppInfoDTO
> {
constructor(
@InjectRepository(
ScenariosOutputResultsGeoEntity,
DbConnections.geoprocessingDB,
)
protected readonly repository: Repository<ScenariosOutputResultsGeoEntity>,
) {
super(repository, 'solution', 'solutions', {
logging: { muteAll: AppConfig.get<boolean>('logging.muteAll', false) },
});
}

get serializerConfig(): JSONAPISerializerConfig<ScenariosOutputResultsGeoEntity> {
return {
attributes: [
'id',
'planningUnits',
'missingValues',
'cost',
'score',
'run',
],
keyForAttribute: 'camelCase',
};
}

async extendFindAllResults(
entitiesAndCount: [ScenariosOutputResultsGeoEntity[], number],
_fetchSpecification?: FetchSpecification,
_info?: AppInfoDTO,
): Promise<[ScenariosOutputResultsGeoEntity[], number]> {
const extendedEntities: Promise<ScenariosOutputResultsGeoEntity>[] = entitiesAndCount[0].map(
(entity) => this.extendGetByIdResult(entity),
);
return [await Promise.all(extendedEntities), entitiesAndCount[1]];
}

async extendGetByIdResult(
entity: ScenariosOutputResultsGeoEntity,
_fetchSpecification?: FetchSpecification,
_info?: AppInfoDTO,
): Promise<ScenariosOutputResultsGeoEntity> {
// TODO implement
entity.planningUnits = 17;
entity.missingValues = 13;
entity.cost = 400;
entity.score = 999;
entity.run = 1;
return entity;
}
}
47 changes: 47 additions & 0 deletions api/apps/api/test/scenario-solutions/get-all-solutions.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { PromiseType } from 'utility-types';
import { createWorld } from './world';

let world: PromiseType<ReturnType<typeof createWorld>>;

beforeAll(async () => {
world = await createWorld();
});

describe(`When getting scenario solution results`, () => {
beforeAll(async () => {
await world.GivenScenarioHasSolutionsReady();
});

it(`should resolve solutions`, async () => {
const response = await world.WhenGettingSolutions();
expect(response.body.meta).toMatchInlineSnapshot(`
Object {
"page": 1,
"size": 25,
"totalItems": 1,
"totalPages": 1,
}
`);

expect(response.body.data.length).toEqual(1);
expect(response.body.data[0].attributes).toMatchInlineSnapshot(
{
id: expect.any(String),
},
`
Object {
"cost": 400,
"id": Any<String>,
"missingValues": 13,
"planningUnits": 17,
"run": 1,
"score": 999,
}
`,
);
});
});

afterAll(async () => {
await world?.cleanup();
});
Loading