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

refactor(geo-features): remove unused code #565

Merged
merged 3 commits into from
Oct 14, 2021
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
182 changes: 2 additions & 180 deletions api/apps/api/src/modules/geo-features/geo-feature-set.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,13 @@ import {
JSONAPISerializerConfig,
PaginationMeta,
} from '@marxan-api/utils/app-base.service';
import { Inject, Injectable, Logger } from '@nestjs/common';
import {
GeoFeatureSetSpecification,
SpecForGeofeature,
SpecForGeoFeatureWithGeoprocessing,
SpecForPlainGeoFeature,
} from './dto/geo-feature-set-specification.dto';
import { Injectable } from '@nestjs/common';
import { GeoFeatureSetSpecification } from './dto/geo-feature-set-specification.dto';
import * as JSONAPISerializer from 'jsonapi-serializer';
import { GeoFeatureSetResult } from './geo-feature-set.api.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Scenario } from '../scenarios/scenario.api.entity';
import { EntityManager, Repository } from 'typeorm';
import { GeoFeaturePropertySetService } from './geo-feature-property-sets.service';
import { ScenarioFeaturesData } from '@marxan/features';
import { flattenDeep } from 'lodash';
import { GeoprocessingOpSplitV1 } from './types/geo-feature.geoprocessing-operations.type';
import { RemoteFeaturesData } from '../scenarios-features/entities/remote-features-data.geo.entity';
import { plainToClass } from 'class-transformer';

export const EntityManagerToken = Symbol();

export const MarxanFeaturesMetadata = {
defaults: {
fpf: 1,
},
};

@Injectable()
export class GeoFeatureSetService {
constructor(
@InjectRepository(Scenario)
private readonly scenarioRepository: Repository<Scenario>,
private readonly geoFeaturePropertySetService: GeoFeaturePropertySetService,
@Inject(EntityManagerToken)
private readonly entityManager: EntityManager,
) {}

get serializerConfig(): JSONAPISerializerConfig<GeoFeatureSetSpecification> {
return {
attributes: ['status', 'features'],
Expand All @@ -60,152 +30,4 @@ export class GeoFeatureSetService {

return serializer.serialize(entities);
}

/**
* Create or replace the set of features linked to a scenario.
*/
async createOrReplaceFeatureSet(
id: string,
dto: GeoFeatureSetSpecification,
): Promise<GeoFeatureSetSpecification | undefined> {
const scenario = await this.scenarioRepository.findOneOrFail(id);
await this.scenarioRepository.update(id, { featureSet: dto });
// @todo: move to async job - this was just for simple tests
await this.createFeaturesForScenario(id, dto.features);
return await this.geoFeaturePropertySetService.extendGeoFeatureProcessingSpecification(
dto,
scenario,
);
}

/**
* Given a specification for features to be linked to a scenario, compute
* features defined via geoprocessing operations and link plain features
* and features from geoprocessing to the scenario.
*/
async createFeaturesForScenario(
scenarioId: string,
featureSpecification: SpecForGeofeature[],
): Promise<void> {
await this.entityManager.transaction(async (transactionalEntityManager) => {
const repository = transactionalEntityManager.getRepository(
ScenarioFeaturesData,
);
await repository.delete({ scenarioId });
// First process features which can be used as they are (plain)
await this.createPlainFeaturesForScenario(
transactionalEntityManager,
scenarioId,
featureSpecification,
);
// Then process features from geoprocessing operations of kind `split/v1`
// TODO
// Then process features from geoprocessing operations of kind `stratification/v1`
// TODO
});
}

/**
* Given a specification for features to be linked to a scenario, select plain
* features (i.e. no geoprocessing required) and link them to the scenario as
* part of an ongoing db transaction.
*
* @todo fix typing
*/
async createPlainFeaturesForScenario(
transactionalEntityManager: EntityManager,
scenarioId: string,
featureSpecification: SpecForGeofeature[],
): Promise<
{
scenarioId: string;
featuresDataId: string;
fpf?: number;
prop?: number;
}[][]
> {
const scenarioFeaturesData = Promise.all(
featureSpecification
.filter(
(feature): feature is SpecForPlainGeoFeature =>
!('geoprocessingOperations' in feature),
)
.map(async (feature) => {
const featuresData: Partial<ScenarioFeaturesData>[] = await transactionalEntityManager
.find(RemoteFeaturesData, { featureId: feature.featureId })
.then((result) =>
result.map((fd) => ({
scenarioId,
featuresDataId: fd.id,
fpf:
feature.marxanSettings?.fpf ??
MarxanFeaturesMetadata.defaults.fpf,
prop: feature.marxanSettings?.prop,
})),
);

return transactionalEntityManager.save(
plainToClass(ScenarioFeaturesData, featuresData),
);
}),
);
return scenarioFeaturesData;
}

/**
* Given a specification for features to be linked to a scenario, select plain
* features (i.e. no geoprocessing required) and link them to the scenario as
* part of an ongoing db transaction.
*
* @todo fix typing
*/
async createGeoprocessedFeaturesForScenarioWithSplitV1(
transactionalEntityManager: EntityManager,
scenarioId: string,
featureSpecification: SpecForGeofeature[],
): Promise<any> {
// ({
// scenarioId: string;
// featuresDataId: string;
// fpf: number;
// prop: number | undefined;
// } & RemoteScenarioFeaturesData)[]
const _repository = transactionalEntityManager.getRepository(
ScenarioFeaturesData,
);
return Promise.all(
featureSpecification
.filter(
(feature): feature is SpecForGeoFeatureWithGeoprocessing =>
'geoprocessingOperations' in feature,
)
.map((feature) => {
const splitOperations = flattenDeep(
feature.geoprocessingOperations
?.filter(
(operation): operation is GeoprocessingOpSplitV1 =>
operation.kind === 'split/v1',
)
.map((operation) =>
operation.splits.map((split) => ({
featureId: feature.featureId,
splitByProperty: operation.splitByProperty,
value: split.value,
marxanSettings: split.marxanSettings,
})),
),
);

Logger.debug(splitOperations);
// return repository.save({
// scenarioId,
// featuresDataId: feature.featureId,
// fpf:
// feature.marxanSettings?.fpf ??
// MarxanFeaturesMetadata.defaults.fpf,
// prop: feature.marxanSettings?.prop,
// });
}),
);
}
}
11 changes: 2 additions & 9 deletions api/apps/api/src/modules/geo-features/geo-features.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common';
import { getEntityManagerToken, TypeOrmModule } from '@nestjs/typeorm';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Project } from '@marxan-api/modules/projects/project.api.entity';
import { GeoFeature } from './geo-feature.api.entity';
import {
Expand All @@ -12,10 +12,7 @@ import { GeoFeaturesService } from './geo-features.service';
import { ProxyService } from '@marxan-api/modules/proxy/proxy.service';
import { Scenario } from '../scenarios/scenario.api.entity';
import { GeoFeatureSetSerializer } from './geo-feature-set.serializer';
import {
EntityManagerToken,
GeoFeatureSetService,
} from './geo-feature-set.service';
import { GeoFeatureSetService } from './geo-feature-set.service';
import { ScenarioFeaturesData } from '@marxan/features';
import { GeoFeaturePropertySetService } from './geo-feature-property-sets.service';
import { ProcessingModule } from './processing';
Expand All @@ -36,10 +33,6 @@ import { DbConnections } from '@marxan-api/ormconfig.connections';
GeoFeatureSetService,
GeoFeaturePropertySetService,
ProxyService,
{
provide: EntityManagerToken,
useExisting: getEntityManagerToken(DbConnections.geoprocessingDB),
},
],
controllers: [GeoFeaturesController],
exports: [
Expand Down
33 changes: 1 addition & 32 deletions api/apps/api/src/modules/scenarios/scenarios.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ import { ProxyService } from '@marxan-api/modules/proxy/proxy.service';
import { ZipFilesSerializer } from './dto/zip-files.serializer';
import { ScenarioPlanningUnitSerializer } from './dto/scenario-planning-unit.serializer';
import { GeoFeatureSetSerializer } from '../geo-features/geo-feature-set.serializer';
import { UpdateGeoFeatureSetDTO } from '../geo-features/dto/update.geo-feature-set.dto';
import { CreateGeoFeatureSetDTO } from '../geo-features/dto/create.geo-feature-set.dto';
import { GeoFeatureSetService } from '../geo-features/geo-feature-set.service';
import { ScenarioPlanningUnitDto } from './dto/scenario-planning-unit.dto';
import { isLeft } from 'fp-ts/Either';
import { ScenarioFeaturesGapDataService } from '../scenarios-features/scenario-features-gap-data.service';
Expand Down Expand Up @@ -104,7 +102,6 @@ export class ScenariosController {
private readonly scenarioFeaturesGapDataService: ScenarioFeaturesGapDataService,
private readonly scenarioFeaturesOutputGapDataService: ScenarioFeaturesOutputGapDataService,
private readonly geoFeatureSetSerializer: GeoFeatureSetSerializer,
private readonly geoFeatureSetService: GeoFeatureSetService,
private readonly scenarioSerializer: ScenarioSerializer,
private readonly scenarioFeaturesGapData: ScenarioFeaturesGapDataSerializer,
private readonly scenarioFeaturesOutputGapData: ScenarioFeaturesOutputGapDataSerializer,
Expand Down Expand Up @@ -234,7 +231,7 @@ export class ScenariosController {

@ApiOperation({ description: 'Create feature set for scenario' })
@ApiTags(asyncJobTag)
@Post(':id/features/specification/v2')
@Post(':id/features/specification')
async createSpecification(
@Body(new ValidationPipe()) dto: CreateGeoFeatureSetDTO,
@Param('id', ParseUUIDPipe) id: string,
Expand All @@ -250,34 +247,6 @@ export class ScenariosController {
);
}

@ApiOperation({ description: 'Create feature set for scenario' })
@ApiCreatedResponse({ type: GeoFeatureSetResult })
@Post(':id/features/specification')
async createFeatureSetFor(
@Body(new ValidationPipe()) dto: CreateGeoFeatureSetDTO,
@Param('id', ParseUUIDPipe) id: string,
): Promise<GeoFeatureSetResult> {
// TODO once `copy` is in place, replace with implementation as in
// id/features/specification/v2
return await this.geoFeatureSetSerializer.serialize(
await this.geoFeatureSetService.createOrReplaceFeatureSet(id, dto),
);
}

@ApiOperation({ description: 'Update feature set for scenario' })
@ApiOkResponse({ type: GeoFeatureSetResult })
@Put(':id/features/specification')
async updateFeatureSetFor(
@Body(new ValidationPipe()) dto: UpdateGeoFeatureSetDTO,
@Param('id', ParseUUIDPipe) id: string,
): Promise<GeoFeatureSetResult> {
// TODO once `copy` is in place, replace with implementation as in
// id/features/specification/v2
return await this.geoFeatureSetSerializer.serialize(
await this.geoFeatureSetService.createOrReplaceFeatureSet(id, dto),
);
}

@ApiOperation({ description: 'Get feature set for scenario' })
@ApiOkResponse({ type: GeoFeatureSetResult })
@Get(':id/features/specification')
Expand Down
2 changes: 1 addition & 1 deletion app/hooks/features/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ export function useSaveSelectedFeatures({

const saveFeature = ({ id, data }: SaveSelectedFeaturesProps) => {
return SCENARIOS.request({
url: `/${id}/features/specification/v2`,
url: `/${id}/features/specification`,
data,
headers: {
Authorization: `Bearer ${session.accessToken}`,
Expand Down