34 Commits

Author SHA1 Message Date
Romain Thouvenin
d48d01f051 Implement distributed event handler to propagate ad deletion 2024-04-25 16:06:59 +02:00
Romain Thouvenin
1701fbbeb1 Implement a DeleteAdCommand 2024-04-25 16:06:59 +02:00
Romain Thouvenin
a7c281d740 fix retrieval of DB records not including schedule or waypoints 2024-04-25 15:14:35 +02:00
Romain Thouvenin
01ebac7e74 DRY the pax/driver schedule adjustment logic 2024-04-12 11:33:17 +02:00
Romain Thouvenin
104559d03d Add a test for punctual search matching a recurrent driver schedule 2024-04-05 11:44:10 +02:00
Romain Thouvenin
173e5ebba5 Rename schedule fixtures for better readability of tests 2024-04-05 11:43:30 +02:00
Romain Thouvenin
0dc01da2b0 Combine journey creation and filtering to avoid missing results 2024-04-04 17:24:23 +02:00
Sylvain Briat
945ce80840 improve documentation 2024-04-03 13:39:09 +02:00
Sylvain Briat
16ebe8d543 handle excluded ad in query and selector 2024-04-03 13:02:31 +02:00
Sylvain Briat
0c29e522ed add excludedAdId to proto and dto 2024-04-03 13:01:12 +02:00
Romain Thouvenin
c51c368d83 Remove the controller-level cache from MatchGrpcController 2024-04-03 07:52:37 +00:00
Sylvain Briat
0446d267ef improve creation of schedules 2024-04-02 11:14:05 +00:00
Sylvain Briat
100fb3487d add possibility to have more than one driver target in carpool path item (eg. when a user adds 2 same waypoints with a different target) 2024-04-02 11:14:05 +00:00
Romain Thouvenin
e501bef249 Move test job to a common template 2024-04-02 12:23:03 +02:00
Sylvain Briat
71ac97410a return frequency in match response 2024-04-02 10:06:34 +00:00
Romain Thouvenin
5696ac57bd Generic test job that also runs on release merge requests 2024-04-02 12:01:38 +02:00
Romain Thouvenin
f759581157 Move build job to a common template 2024-04-02 11:42:54 +02:00
Romain Thouvenin
08b5af7511 Update CI script for release-branch workflow 2024-04-02 11:23:34 +02:00
Romain Thouvenin
4581af5e9f Define an exception filter to log the cause of exceptions 2024-04-02 10:27:53 +02:00
Romain Thouvenin
7f7a51d19b Let Nest exception filter handle unexpected exceptions 2024-04-02 10:27:53 +02:00
Sylvain Briat
739d05b095 improve candidate entity for empty driver or passenger schedule 2024-03-29 15:10:10 +01:00
Sylvain Briat
212b609e26 add array min size check on schedule property 2024-03-29 15:10:10 +01:00
Romain Thouvenin
bd6fc1576b Apply 1 suggestion(s) to 1 file(s) 2024-03-29 14:04:57 +00:00
Sylvain Briat
53df6183bd fix driverTime in journey item 2024-03-29 11:56:42 +01:00
Sylvain Briat
ffeb009497 fix readme for optional schedule 2024-03-28 17:12:30 +00:00
Sylvain Briat
3786fcc2c2 improve TODO explanation in journey value object 2024-03-28 17:12:30 +00:00
Sylvain Briat
e53c12ba74 fix readme for optional schedule 2024-03-28 17:12:30 +00:00
Sylvain Briat
c5a5e33256 update readme for optional schedule 2024-03-28 17:12:30 +00:00
Sylvain Briat
924547c316 update mtching mapper to handle empty schedules 2024-03-28 17:12:30 +00:00
Sylvain Briat
5f8dd8b4a0 handle empty schedule in candidates 2024-03-28 17:12:30 +00:00
Sylvain Briat
90ae3cf9cb update passenger oriented selector to handle empty schedule; improve punctual where part 2024-03-28 17:12:30 +00:00
Sylvain Briat
6b9bf53b4a set schedule to optional in match query and query handler 2024-03-28 17:12:30 +00:00
Sylvain Briat
4fd2950027 set schedule to optional in match request 2024-03-28 17:12:30 +00:00
Romain Thouvenin
2ce2a46c95 Allow remote debugging of dev container 2024-03-28 16:59:28 +01:00
44 changed files with 876 additions and 491 deletions

View File

@@ -7,52 +7,7 @@ stages:
include: include:
- template: Security/SAST.gitlab-ci.yml - template: Security/SAST.gitlab-ci.yml
- template: Security/Secret-Detection.gitlab-ci.yml - template: Security/Secret-Detection.gitlab-ci.yml
- project: mobicoop/v3/gitlab-templates
############## file:
# TEST STAGE # - /ci/release.build-job.yml
############## - /ci/service.test-job.yml
test:
stage: test
image: docker/compose:latest
variables:
DOCKER_TLS_CERTDIR: ''
services:
- docker:dind
script:
- docker-compose -f docker-compose.ci.tools.yml -p matcher-tools --env-file ci/.env.ci up -d
- sh ci/wait-up.sh
- docker-compose -f docker-compose.ci.service.yml -p matcher-service --env-file ci/.env.ci up -d
- docker exec -t v3-matcher-api sh -c "npm run test:integration:ci"
coverage: /All files[^|]*\|[^|]*\s+([\d\.]+)/
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH || $CI_COMMIT_MESSAGE =~ /--check/ || $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
when: always
###############
# BUILD STAGE #
###############
build:
stage: build
image: docker:20.10.22
variables:
DOCKER_TLS_CERTDIR: ''
services:
- docker:dind
before_script:
- echo -n $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY
script:
- export VERSION=$(docker run --rm -v "$PWD":/usr/src/app:ro -w /usr/src/app node:slim node -p "require('./package.json').version")
- docker pull $CI_REGISTRY_IMAGE:latest || true
- >
docker build
--pull
--cache-from $CI_REGISTRY_IMAGE:latest
--tag $CI_REGISTRY_IMAGE:$VERSION
--tag $CI_REGISTRY_IMAGE:latest
.
- docker push $CI_REGISTRY_IMAGE:$VERSION
- docker push $CI_REGISTRY_IMAGE:latest
only:
- main

View File

@@ -156,13 +156,18 @@ The app exposes the following [gRPC](https://grpc.io/) services :
- **strict** (boolean, optional): if set to true, allow matching only with similar frequency ads (_default : false_) - **strict** (boolean, optional): if set to true, allow matching only with similar frequency ads (_default : false_)
- **fromDate**: start date for recurrent ad, carpool date for punctual ad - **fromDate**: start date for recurrent ad, carpool date for punctual ad
- **toDate**: end date for recurrent ad, same as fromDate for punctual ad - **toDate**: end date for recurrent ad, same as fromDate for punctual ad
- **schedule**: an array of schedule items, a schedule item containing : - **schedule**: an optional array of schedule items, a schedule item containing :
- the week day as a number, from 0 (sunday) to 6 (saturday) if the ad is recurrent (default to fromDate day for punctual search) - the week day as a number, from 0 (sunday) to 6 (saturday) if the ad is recurrent (default to fromDate day for punctual search)
- the departure time (as HH:MM) - the departure time (as HH:MM)
- the margin around the departure time in seconds (optional) (_default : 900_) - the margin around the departure time in seconds (optional) (_default : 900_)
_If the schedule is not set, the driver departure time is guessed to be the ideal departure time to reach the passenger, and the passenger departure time is guessed to be the ideal pick up time for the driver_
- **seatsProposed** (integer, optional): number of seats proposed as driver (_default : 3_) - **seatsProposed** (integer, optional): number of seats proposed as driver (_default : 3_)
- **seatsRequested** (integer, optional): number of seats requested as passenger (_default : 1_) - **seatsRequested** (integer, optional): number of seats requested as passenger (_default : 1_)
- **waypoints**: an array of addresses that represent the waypoints of the journey (only first and last waypoints are used for passenger ads). Note that positions are **required** and **must** be consecutives - **waypoints**: an array of addresses that represent the waypoints of the journey (only first and last waypoints are used for passenger ads). Note that positions are **required** and **must** be consecutives
- **excludedAdId** (optional): the id of an ad to be excluded from the results (useful to avoid self-matchings)
- **algorithmType** (optional): the type of algorithm to use (as of 2023-09-28, only the default `PASSENGER_ORIENTED` is accepted) - **algorithmType** (optional): the type of algorithm to use (as of 2023-09-28, only the default `PASSENGER_ORIENTED` is accepted)
- **remoteness** (integer, optional): an integer to indicate the maximum flying distance (in metres) between the driver route and the passenger pick-up / drop-off points (_default : 15000_) - **remoteness** (integer, optional): an integer to indicate the maximum flying distance (in metres) between the driver route and the passenger pick-up / drop-off points (_default : 15000_)
- **useProportion** (boolean, optional): a boolean to indicate if the matching algorithm will compare the distance of the passenger route against the distance of the driver route (_default : 1_). Works in combination with **proportion** parameter - **useProportion** (boolean, optional): a boolean to indicate if the matching algorithm will compare the distance of the passenger route against the distance of the driver route (_default : 1_). Works in combination with **proportion** parameter
@@ -214,10 +219,6 @@ If the matching is successful, you will get a result, containing :
Matching is a time-consuming process, so the results of a matching request are stored in cache before being paginated and returned to the requester. Matching is a time-consuming process, so the results of a matching request are stored in cache before being paginated and returned to the requester.
An id is attributed to the overall results of a request : on further requests (for example to query for different pages of results), the requester can provide this id and get in return the cached data, avoiding another longer process of computing the results from scratch. Obviously, new computing must be done periodically to get fresh new results ! An id is attributed to the overall results of a request : on further requests (for example to query for different pages of results), the requester can provide this id and get in return the cached data, avoiding another longer process of computing the results from scratch. Obviously, new computing must be done periodically to get fresh new results !
There's also a basic cache to store the results of the _same_ request sent multiple times successively.
Cache TTLs are customizable in the `.env` file.
## Tests / ESLint / Prettier ## Tests / ESLint / Prettier
Tests are run outside the container for ease of use (switching between different environments inside containers using prisma is complicated and error prone). Tests are run outside the container for ease of use (switching between different environments inside containers using prisma is complicated and error prone).

View File

@@ -11,10 +11,11 @@ services:
- .:/usr/src/app - .:/usr/src/app
env_file: env_file:
- .env - .env
command: npm run start:dev command: npm run start:debug
ports: ports:
- ${SERVICE_PORT:-5005}:${SERVICE_PORT:-5005} - ${SERVICE_PORT:-5005}:${SERVICE_PORT:-5005}
- ${HEALTH_SERVICE_PORT:-6005}:${HEALTH_SERVICE_PORT:-6005} - ${HEALTH_SERVICE_PORT:-6005}:${HEALTH_SERVICE_PORT:-6005}
- 9225:9229
networks: networks:
v3-network: v3-network:
aliases: aliases:

View File

@@ -1,6 +1,6 @@
{ {
"name": "@mobicoop/matcher", "name": "@mobicoop/matcher",
"version": "1.5.5", "version": "1.6.0",
"description": "Mobicoop V3 Matcher", "description": "Mobicoop V3 Matcher",
"author": "sbriat", "author": "sbriat",
"private": true, "private": true,
@@ -11,7 +11,7 @@
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start", "start": "nest start",
"start:dev": "nest start --watch", "start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch", "start:debug": "nest start --debug 0.0.0.0:9229 --watch",
"start:prod": "node dist/main", "start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"lint:check": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix-dry-run --ignore-path .gitignore", "lint:check": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix-dry-run --ignore-path .gitignore",

View File

@@ -15,6 +15,9 @@ export const MATCHER_AD_CREATION_FAILED_ROUTING_KEY =
export const AD_CREATED_MESSAGE_HANDLER = 'adCreated'; export const AD_CREATED_MESSAGE_HANDLER = 'adCreated';
export const AD_CREATED_ROUTING_KEY = 'ad.created'; export const AD_CREATED_ROUTING_KEY = 'ad.created';
export const AD_CREATED_QUEUE = 'matcher.ad.created'; export const AD_CREATED_QUEUE = 'matcher.ad.created';
export const AD_DELETED_MESSAGE_HANDLER = 'adDeleted';
export const AD_DELETED_ROUTING_KEY = 'ad.deleted';
export const AD_DELETED_QUEUE = 'matcher.ad.deleted';
// health // health
export const GRPC_HEALTH_PACKAGE_NAME = 'health'; export const GRPC_HEALTH_PACKAGE_NAME = 'health';

View File

@@ -0,0 +1,24 @@
import { ArgumentsHost, Catch, Logger } from '@nestjs/common';
import { BaseRpcExceptionFilter } from '@nestjs/microservices';
import { Observable } from 'rxjs';
@Catch()
export class LogCauseExceptionFilter extends BaseRpcExceptionFilter {
private static readonly causeLogger = new Logger('RpcExceptionsHandler');
catch(exception: any, host: ArgumentsHost): Observable<any> {
const response = super.catch(exception, host);
const cause = exception.cause;
if (cause) {
if (this.isError(cause)) {
LogCauseExceptionFilter.causeLogger.error(
'Caused by: ' + cause.message,
cause.stack,
);
} else {
LogCauseExceptionFilter.causeLogger.error('Caused by: ' + cause);
}
}
return response;
}
}

View File

@@ -19,4 +19,3 @@ export const AD_CONFIGURATION_REPOSITORY = Symbol(
'AD_CONFIGURATION_REPOSITORY', 'AD_CONFIGURATION_REPOSITORY',
); );
export const GEOGRAPHY_PACKAGE = Symbol('GEOGRAPHY_PACKAGE'); export const GEOGRAPHY_PACKAGE = Symbol('GEOGRAPHY_PACKAGE');
export const GEOGRAPHY_SERVICE = Symbol('GEOGRAPHY_SERVICE');

View File

@@ -1,19 +1,19 @@
import { ExtendedMapper } from '@mobicoop/ddd-library';
import { DirectionEncoderPort } from '@modules/geography/core/application/ports/direction-encoder.port';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { AdEntity } from './core/domain/ad.entity';
import {
AdWriteModel,
AdReadModel,
ScheduleItemModel,
AdWriteExtraModel,
} from './infrastructure/ad.repository';
import { v4 } from 'uuid'; import { v4 } from 'uuid';
import { AD_DIRECTION_ENCODER } from './ad.di-tokens';
import { AdEntity } from './core/domain/ad.entity';
import { import {
ScheduleItem, ScheduleItem,
ScheduleItemProps, ScheduleItemProps,
} from './core/domain/value-objects/schedule-item.value-object'; } from './core/domain/value-objects/schedule-item.value-object';
import { DirectionEncoderPort } from '@modules/geography/core/application/ports/direction-encoder.port'; import {
import { AD_DIRECTION_ENCODER } from './ad.di-tokens'; AdReadModel,
import { ExtendedMapper } from '@mobicoop/ddd-library'; AdWriteExtraModel,
AdWriteModel,
ScheduleItemModel,
} from './infrastructure/ad.repository';
/** /**
* Mapper constructs objects that are used in different layers: * Mapper constructs objects that are used in different layers:
@@ -97,7 +97,7 @@ export class AdMapper
frequency: record.frequency, frequency: record.frequency,
fromDate: record.fromDate.toISOString().split('T')[0], fromDate: record.fromDate.toISOString().split('T')[0],
toDate: record.toDate.toISOString().split('T')[0], toDate: record.toDate.toISOString().split('T')[0],
schedule: record.schedule.map( schedule: record.schedule?.map(
(scheduleItem: ScheduleItemModel) => (scheduleItem: ScheduleItemModel) =>
new ScheduleItem({ new ScheduleItem({
day: scheduleItem.day, day: scheduleItem.day,
@@ -111,12 +111,14 @@ export class AdMapper
margin: scheduleItem.margin, margin: scheduleItem.margin,
}), }),
), ),
waypoints: this.directionEncoder waypoints: record.waypoints
? this.directionEncoder
.decode(record.waypoints) .decode(record.waypoints)
.map((coordinates, index) => ({ .map((coordinates, index) => ({
position: index, position: index,
...coordinates, ...coordinates,
})), }))
: [],
fwdAzimuth: record.fwdAzimuth, fwdAzimuth: record.fwdAzimuth,
backAzimuth: record.backAzimuth, backAzimuth: record.backAzimuth,
points: [], points: [],

View File

@@ -1,50 +1,51 @@
import { Module, Provider } from '@nestjs/common'; import { ConfigurationRepository } from '@mobicoop/configuration-module';
import { CqrsModule } from '@nestjs/cqrs';
import {
AD_MESSAGE_PUBLISHER,
AD_REPOSITORY,
AD_DIRECTION_ENCODER,
AD_ROUTE_PROVIDER,
TIMEZONE_FINDER,
TIME_CONVERTER,
INPUT_DATETIME_TRANSFORMER,
OUTPUT_DATETIME_TRANSFORMER,
MATCHING_REPOSITORY,
AD_CONFIGURATION_REPOSITORY,
GEOGRAPHY_PACKAGE,
GEOGRAPHY_SERVICE,
} from './ad.di-tokens';
import { MessageBrokerPublisher } from '@mobicoop/message-broker-module'; import { MessageBrokerPublisher } from '@mobicoop/message-broker-module';
import { AdRepository } from './infrastructure/ad.repository';
import { PrismaService } from './infrastructure/prisma.service';
import { AdMapper } from './ad.mapper';
import { AdCreatedMessageHandler } from './interface/message-handlers/ad-created.message-handler';
import { PostgresDirectionEncoder } from '@modules/geography/infrastructure/postgres-direction-encoder';
import { GeographyModule } from '@modules/geography/geography.module'; import { GeographyModule } from '@modules/geography/geography.module';
import { CreateAdService } from './core/application/commands/create-ad/create-ad.service'; import { PostgresDirectionEncoder } from '@modules/geography/infrastructure/postgres-direction-encoder';
import { MatchGrpcController } from './interface/grpc-controllers/match.grpc-controller';
import { MatchQueryHandler } from './core/application/queries/match/match.query-handler';
import { TimezoneFinder } from './infrastructure/timezone-finder';
import { TimeConverter } from './infrastructure/time-converter';
import { InputDateTimeTransformer } from './infrastructure/input-datetime-transformer';
import { MatchMapper } from './match.mapper';
import { OutputDateTimeTransformer } from './infrastructure/output-datetime-transformer';
import { MatchingRepository } from './infrastructure/matching.repository';
import { MatchingMapper } from './matching.mapper';
import { CacheModule } from '@nestjs/cache-manager'; import { CacheModule } from '@nestjs/cache-manager';
import { Module, Provider } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config'; import { ConfigModule, ConfigService } from '@nestjs/config';
import { redisStore } from 'cache-manager-ioredis-yet'; import { CqrsModule } from '@nestjs/cqrs';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { import {
RedisClientOptions, RedisClientOptions,
RedisModule, RedisModule,
RedisModuleOptions, RedisModuleOptions,
} from '@songkeys/nestjs-redis'; } from '@songkeys/nestjs-redis';
import { ConfigurationRepository } from '@mobicoop/configuration-module';
import { PublishMessageWhenMatcherAdIsCreatedDomainEventHandler } from './core/application/event-handlers/publish-message-when-matcher-ad-is-created.domain-event-handler';
import { Georouter } from './infrastructure/georouter';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { GRPC_GEOGRAPHY_PACKAGE_NAME } from '@src/app.constants'; import { GRPC_GEOGRAPHY_PACKAGE_NAME } from '@src/app.constants';
import { redisStore } from 'cache-manager-ioredis-yet';
import { join } from 'path'; import { join } from 'path';
import {
AD_CONFIGURATION_REPOSITORY,
AD_DIRECTION_ENCODER,
AD_MESSAGE_PUBLISHER,
AD_REPOSITORY,
AD_ROUTE_PROVIDER,
GEOGRAPHY_PACKAGE,
INPUT_DATETIME_TRANSFORMER,
MATCHING_REPOSITORY,
OUTPUT_DATETIME_TRANSFORMER,
TIMEZONE_FINDER,
TIME_CONVERTER,
} from './ad.di-tokens';
import { AdMapper } from './ad.mapper';
import { CreateAdService } from './core/application/commands/create-ad/create-ad.service';
import { DeleteAdService } from './core/application/commands/delete-ad/delete-ad.service';
import { PublishMessageWhenMatcherAdIsCreatedDomainEventHandler } from './core/application/event-handlers/publish-message-when-matcher-ad-is-created.domain-event-handler';
import { MatchQueryHandler } from './core/application/queries/match/match.query-handler';
import { AdRepository } from './infrastructure/ad.repository';
import { Georouter } from './infrastructure/georouter';
import { InputDateTimeTransformer } from './infrastructure/input-datetime-transformer';
import { MatchingRepository } from './infrastructure/matching.repository';
import { OutputDateTimeTransformer } from './infrastructure/output-datetime-transformer';
import { PrismaService } from './infrastructure/prisma.service';
import { TimeConverter } from './infrastructure/time-converter';
import { TimezoneFinder } from './infrastructure/timezone-finder';
import { MatchGrpcController } from './interface/grpc-controllers/match.grpc-controller';
import { AdCreatedMessageHandler } from './interface/message-handlers/ad-created.message-handler';
import { AdDeletedMessageHandler } from './interface/message-handlers/ad-deleted.message-handler';
import { MatchMapper } from './match.mapper';
import { MatchingMapper } from './matching.mapper';
const imports = [ const imports = [
CqrsModule, CqrsModule,
@@ -65,20 +66,6 @@ const imports = [
}), }),
}, },
]), ]),
ClientsModule.register([
{
name: GEOGRAPHY_SERVICE,
transport: Transport.RMQ,
options: {
//TODO read from config
urls: [`${process.env.MESSAGE_BROKER_URI}`],
queue: 'geography',
queueOptions: {
durable: true,
},
},
},
]),
CacheModule.registerAsync<RedisClientOptions>({ CacheModule.registerAsync<RedisClientOptions>({
imports: [ConfigModule], imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({ useFactory: async (configService: ConfigService) => ({
@@ -111,13 +98,13 @@ const imports = [
const grpcControllers = [MatchGrpcController]; const grpcControllers = [MatchGrpcController];
const messageHandlers = [AdCreatedMessageHandler]; const messageHandlers = [AdCreatedMessageHandler, AdDeletedMessageHandler];
const eventHandlers: Provider[] = [ const eventHandlers: Provider[] = [
PublishMessageWhenMatcherAdIsCreatedDomainEventHandler, PublishMessageWhenMatcherAdIsCreatedDomainEventHandler,
]; ];
const commandHandlers: Provider[] = [CreateAdService]; const commandHandlers: Provider[] = [CreateAdService, DeleteAdService];
const queryHandlers: Provider[] = [MatchQueryHandler]; const queryHandlers: Provider[] = [MatchQueryHandler];

View File

@@ -0,0 +1,7 @@
import { Command, CommandProps } from '@mobicoop/ddd-library';
export class DeleteAdCommand extends Command {
constructor(props: CommandProps<DeleteAdCommand>) {
super(props);
}
}

View File

@@ -0,0 +1,18 @@
import { AD_REPOSITORY } from '@modules/ad/ad.di-tokens';
import { Inject } from '@nestjs/common';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { AdRepositoryPort } from '../../ports/ad.repository.port';
import { DeleteAdCommand } from './delete-ad.command';
@CommandHandler(DeleteAdCommand)
export class DeleteAdService implements ICommandHandler {
constructor(
@Inject(AD_REPOSITORY) private readonly adRepository: AdRepositoryPort,
) {}
async execute(command: DeleteAdCommand): Promise<boolean> {
const ad = await this.adRepository.findOneById(command.id);
ad.delete();
return this.adRepository.delete(ad);
}
}

View File

@@ -1,9 +1,9 @@
import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity'; import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity';
import { Completer } from './completer.abstract';
import { MatchQuery } from '../match.query';
import { Step } from '../../../types/step.type';
import { CarpoolPathItem } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object'; import { CarpoolPathItem } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object';
import { RouteResponse } from '../../../ports/georouter.port'; import { RouteResponse } from '../../../ports/georouter.port';
import { Step } from '../../../types/step.type';
import { MatchQuery } from '../match.query';
import { Completer } from './completer.abstract';
export class RouteCompleter extends Completer { export class RouteCompleter extends Completer {
protected readonly type: RouteCompleterType; protected readonly type: RouteCompleterType;
@@ -48,10 +48,7 @@ export class RouteCompleter extends Completer {
): Promise<RouteResponse> => ): Promise<RouteResponse> =>
this.query.routeProvider.getRoute({ this.query.routeProvider.getRoute({
waypoints: (candidate.getProps().carpoolPath as CarpoolPathItem[]).map( waypoints: (candidate.getProps().carpoolPath as CarpoolPathItem[]).map(
(carpoolPathItem: CarpoolPathItem) => ({ (carpoolPathItem: CarpoolPathItem) => carpoolPathItem,
lon: carpoolPathItem.lon,
lat: carpoolPathItem.lat,
}),
), ),
detailsSettings: detailsSettings, detailsSettings: detailsSettings,
}); });

View File

@@ -165,7 +165,7 @@ export class MatchQueryHandler implements IQueryHandler {
frequency: query.frequency, frequency: query.frequency,
fromDate: query.fromDate, fromDate: query.fromDate,
toDate: query.toDate, toDate: query.toDate,
schedule: query.schedule.map((scheduleItem: ScheduleItem) => ({ schedule: query.schedule?.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day as number, day: scheduleItem.day as number,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin as number, margin: scheduleItem.margin as number,

View File

@@ -21,11 +21,12 @@ export class MatchQuery extends QueryBase {
readonly frequency: Frequency; readonly frequency: Frequency;
fromDate: string; fromDate: string;
toDate: string; toDate: string;
schedule: ScheduleItem[]; schedule?: ScheduleItem[];
seatsProposed?: number; seatsProposed?: number;
seatsRequested?: number; seatsRequested?: number;
strict?: boolean; strict?: boolean;
readonly waypoints: Waypoint[]; readonly waypoints: Waypoint[];
excludedAdId?: string;
algorithmType?: AlgorithmType; algorithmType?: AlgorithmType;
remoteness?: number; remoteness?: number;
useProportion?: boolean; useProportion?: boolean;
@@ -56,6 +57,7 @@ export class MatchQuery extends QueryBase {
this.seatsRequested = props.seatsRequested; this.seatsRequested = props.seatsRequested;
this.strict = props.strict; this.strict = props.strict;
this.waypoints = props.waypoints; this.waypoints = props.waypoints;
this.excludedAdId = props.excludedAdId;
this.algorithmType = props.algorithmType; this.algorithmType = props.algorithmType;
this.remoteness = props.remoteness; this.remoteness = props.remoteness;
this.useProportion = props.useProportion; this.useProportion = props.useProportion;
@@ -73,7 +75,7 @@ export class MatchQuery extends QueryBase {
} }
setMissingMarginDurations = (defaultMarginDuration: number): MatchQuery => { setMissingMarginDurations = (defaultMarginDuration: number): MatchQuery => {
this.schedule.forEach((day: ScheduleItem) => { this.schedule?.forEach((day: ScheduleItem) => {
if (day.margin === undefined) day.margin = defaultMarginDuration; if (day.margin === undefined) day.margin = defaultMarginDuration;
}); });
return this; return this;
@@ -136,6 +138,8 @@ export class MatchQuery extends QueryBase {
setDatesAndSchedule = ( setDatesAndSchedule = (
datetimeTransformer: DateTimeTransformerPort, datetimeTransformer: DateTimeTransformerPort,
): MatchQuery => { ): MatchQuery => {
// no transformation if schedule is not set
if (this.schedule === undefined) return this;
const initialFromDate: string = this.fromDate; const initialFromDate: string = this.fromDate;
this.fromDate = datetimeTransformer.fromDate( this.fromDate = datetimeTransformer.fromDate(
{ {
@@ -209,10 +213,7 @@ export class MatchQuery extends QueryBase {
pathCreator.getBasePaths().map(async (path: Path) => ({ pathCreator.getBasePaths().map(async (path: Path) => ({
type: path.type, type: path.type,
route: await this.routeProvider.getRoute({ route: await this.routeProvider.getRoute({
waypoints: path.waypoints.map((p) => ({ waypoints: path.waypoints,
lon: p.lon,
lat: p.lat,
})),
}), }),
})), })),
) )
@@ -228,8 +229,9 @@ export class MatchQuery extends QueryBase {
} }
}); });
} catch (e: any) { } catch (e: any) {
console.log(e.stack || e); throw new Error('Unable to find a route for given waypoints', {
throw new Error('Unable to find a route for given waypoints'); cause: e,
});
} }
return this; return this;
}; };

View File

@@ -19,7 +19,6 @@ export class PassengerOrientedSelector extends Selector {
query: this._createQueryString(Role.PASSENGER), query: this._createQueryString(Role.PASSENGER),
role: Role.PASSENGER, role: Role.PASSENGER,
}); });
return ( return (
await Promise.all( await Promise.all(
queryStringRoles.map<Promise<AdsRole>>( queryStringRoles.map<Promise<AdsRole>>(
@@ -74,7 +73,7 @@ export class PassengerOrientedSelector extends Selector {
driverSchedule: driverSchedule:
adsRole.role == Role.PASSENGER adsRole.role == Role.PASSENGER
? adEntity.getProps().schedule ? adEntity.getProps().schedule
: this.query.schedule.map((scheduleItem: ScheduleItem) => ({ : this.query.schedule?.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day as number, day: scheduleItem.day as number,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin as number, margin: scheduleItem.margin as number,
@@ -82,7 +81,7 @@ export class PassengerOrientedSelector extends Selector {
passengerSchedule: passengerSchedule:
adsRole.role == Role.DRIVER adsRole.role == Role.DRIVER
? adEntity.getProps().schedule ? adEntity.getProps().schedule
: this.query.schedule.map((scheduleItem: ScheduleItem) => ({ : this.query.schedule?.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day as number, day: scheduleItem.day as number,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin as number, margin: scheduleItem.margin as number,
@@ -137,6 +136,7 @@ export class PassengerOrientedSelector extends Selector {
this._whereStrict(), this._whereStrict(),
this._whereDate(), this._whereDate(),
this._whereSchedule(role), this._whereSchedule(role),
this._whereExcludedAd(),
this._whereAzimuth(), this._whereAzimuth(),
this._whereProportion(role), this._whereProportion(role),
this._whereRemoteness(role), this._whereRemoteness(role),
@@ -155,7 +155,9 @@ export class PassengerOrientedSelector extends Selector {
: ''; : '';
private _whereDate = (): string => private _whereDate = (): string =>
`(\ this.query.frequency == Frequency.PUNCTUAL
? `("fromDate" <= '${this.query.fromDate}' AND "toDate" >= '${this.query.fromDate}')`
: `(\
(\ (\
"fromDate" <= '${this.query.fromDate}' AND "fromDate" <= '${this.query.toDate}' AND\ "fromDate" <= '${this.query.fromDate}' AND "fromDate" <= '${this.query.toDate}' AND\
"toDate" >= '${this.query.toDate}' AND "toDate" >= '${this.query.fromDate}'\ "toDate" >= '${this.query.toDate}' AND "toDate" >= '${this.query.fromDate}'\
@@ -172,6 +174,8 @@ export class PassengerOrientedSelector extends Selector {
)`; )`;
private _whereSchedule = (role: Role): string => { private _whereSchedule = (role: Role): string => {
// no schedule filtering if schedule is not set
if (this.query.schedule === undefined) return '';
const schedule: string[] = []; const schedule: string[] = [];
// we need full dates to compare times, because margins can lead to compare on previous or next day // we need full dates to compare times, because margins can lead to compare on previous or next day
// - first we establish a base calendar (up to a week) // - first we establish a base calendar (up to a week)
@@ -182,7 +186,7 @@ export class PassengerOrientedSelector extends Selector {
// - then we compare each resulting day of the schedule with each day of calendar, // - then we compare each resulting day of the schedule with each day of calendar,
// adding / removing margin depending on the role // adding / removing margin depending on the role
scheduleDates.map((date: Date) => { scheduleDates.map((date: Date) => {
this.query.schedule (this.query.schedule as ScheduleItem[])
.filter( .filter(
(scheduleItem: ScheduleItem) => date.getUTCDay() == scheduleItem.day, (scheduleItem: ScheduleItem) => date.getUTCDay() == scheduleItem.day,
) )
@@ -203,6 +207,9 @@ export class PassengerOrientedSelector extends Selector {
return ''; return '';
}; };
private _whereExcludedAd = (): string =>
this.query.excludedAdId ? `ad.uuid <> '${this.query.excludedAdId}'` : '';
private _wherePassengerSchedule = ( private _wherePassengerSchedule = (
date: Date, date: Date,
scheduleItem: ScheduleItem, scheduleItem: ScheduleItem,
@@ -310,6 +317,11 @@ export class PassengerOrientedSelector extends Selector {
} }
}; };
/**
* Returns an array of dates containing all the dates (limited to 7 by default) between 2 boundary dates.
*
* The array length can be limited to a _max_ number of dates (default: 7)
*/
private _datesBetweenBoundaries = ( private _datesBetweenBoundaries = (
firstDate: string, firstDate: string,
lastDate: string, lastDate: string,

View File

@@ -1,5 +1,6 @@
import { AggregateRoot, AggregateID } from '@mobicoop/ddd-library'; import { AggregateID, AggregateRoot } from '@mobicoop/ddd-library';
import { AdProps, CreateAdProps } from './ad.types'; import { AdProps, CreateAdProps } from './ad.types';
import { AdDeletedDomainEvent } from './events/ad-delete.domain-event';
import { MatcherAdCreatedDomainEvent } from './events/matcher-ad-created.domain-event'; import { MatcherAdCreatedDomainEvent } from './events/matcher-ad-created.domain-event';
export class AdEntity extends AggregateRoot<AdProps> { export class AdEntity extends AggregateRoot<AdProps> {
@@ -26,6 +27,14 @@ export class AdEntity extends AggregateRoot<AdProps> {
return ad; return ad;
}; };
delete(): void {
this.addEvent(
new AdDeletedDomainEvent({
aggregateId: this.id,
}),
);
}
validate(): void { validate(): void {
// entity business rules validation to protect it's invariant before saving entity to a database // entity business rules validation to protect it's invariant before saving entity to a database
} }

View File

@@ -1,21 +1,30 @@
import { AggregateRoot, AggregateID } from '@mobicoop/ddd-library'; import {
AggregateID,
AggregateRoot,
ArgumentInvalidException,
ValueObject,
} from '@mobicoop/ddd-library';
import { Role } from './ad.types';
import { CalendarTools } from './calendar-tools.service';
import { import {
CandidateProps, CandidateProps,
CreateCandidateProps, CreateCandidateProps,
DateInterval,
Target, Target,
} from './candidate.types'; } from './candidate.types';
import { ActorTime } from './value-objects/actor-time.value-object';
import { Actor } from './value-objects/actor.value-object';
import { import {
CarpoolPathItem, CarpoolPathItem,
CarpoolPathItemProps, CarpoolPathItemProps,
} from './value-objects/carpool-path-item.value-object'; } from './value-objects/carpool-path-item.value-object';
import { Step, StepProps } from './value-objects/step.value-object';
import { ScheduleItem } from './value-objects/schedule-item.value-object';
import { Journey } from './value-objects/journey.value-object';
import { CalendarTools } from './calendar-tools.service';
import { JourneyItem } from './value-objects/journey-item.value-object'; import { JourneyItem } from './value-objects/journey-item.value-object';
import { Actor } from './value-objects/actor.value-object'; import { Journey, JourneyProps } from './value-objects/journey.value-object';
import { ActorTime } from './value-objects/actor-time.value-object'; import {
import { Role } from './ad.types'; ScheduleItem,
ScheduleItemProps,
} from './value-objects/schedule-item.value-object';
import { Step, StepProps } from './value-objects/step.value-object';
export class CandidateEntity extends AggregateRoot<CandidateProps> { export class CandidateEntity extends AggregateRoot<CandidateProps> {
protected readonly _id: AggregateID; protected readonly _id: AggregateID;
@@ -53,18 +62,26 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
* This is a tedious process : additional information can be found in deeper methods ! * This is a tedious process : additional information can be found in deeper methods !
*/ */
createJourneys = (): CandidateEntity => { createJourneys = (): CandidateEntity => {
// driver and passenger schedules are eventually mandatory
if (!this.props.driverSchedule) this._createDriverSchedule();
if (!this.props.passengerSchedule) this._createPassengerSchedule();
this.props.journeys = this.props.driverSchedule!.reduce(
(accJourneys: JourneyProps[], driverScheduleItem: ScheduleItem) => {
try { try {
this.props.journeys = this.props.driverSchedule
// first we create the journeys // first we create the journeys
.map((driverScheduleItem: ScheduleItem) => const journey = this._createJourney(driverScheduleItem);
this._createJourney(driverScheduleItem),
)
// then we filter the ones with invalid pickups // then we filter the ones with invalid pickups
.filter((journey: Journey) => journey.hasValidPickUp()); if (journey.hasValidPickUp()) {
accJourneys.push(journey);
}
} catch (e) { } catch (e) {
// irrelevant journeys fall here // irrelevant journeys fall here
// eg. no available day for the given date range // eg. no available day for the given date range
} }
return accJourneys;
},
new Array<JourneyProps>(),
);
return this; return this;
}; };
@@ -82,6 +99,49 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
(1 + this.props.spacetimeDetourRatio.maxDistanceDetourRatio) (1 + this.props.spacetimeDetourRatio.maxDistanceDetourRatio)
: false; : false;
/**
* Create the driver schedule based on the passenger schedule
*/
private _createDriverSchedule = (): void => {
const passengerSchedule = new Schedule(
this.props.passengerSchedule!,
this.props.dateInterval,
);
this.props.driverSchedule = passengerSchedule
.adjust(-this._passengerStartDuration())
.unpack().items;
};
/**
* Return the duration to reach the passenger starting point from the driver starting point
*/
private _passengerStartDuration = (): number => {
let passengerStartStepIndex = 0;
this.props.carpoolPath?.forEach(
(carpoolPathItem: CarpoolPathItem, index: number) => {
carpoolPathItem.actors.forEach((actor: Actor) => {
if (actor.role == Role.PASSENGER && actor.target == Target.START)
passengerStartStepIndex = index;
});
},
);
return this.props.steps![passengerStartStepIndex].duration;
};
/**
* Create the passenger schedule based on the driver schedule
*/
private _createPassengerSchedule = (): void => {
const driverSchedule = new Schedule(
this.props.driverSchedule!,
this.props.dateInterval,
);
this.props.passengerSchedule = driverSchedule
.adjust(this._passengerStartDuration())
.unpack().items;
};
private _createJourney = (driverScheduleItem: ScheduleItem): Journey => private _createJourney = (driverScheduleItem: ScheduleItem): Journey =>
new Journey({ new Journey({
firstDate: CalendarTools.firstDate( firstDate: CalendarTools.firstDate(
@@ -216,7 +276,7 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
* Find the passenger schedule item with the minimum duration between a given date and the dates of the passenger schedule * Find the passenger schedule item with the minimum duration between a given date and the dates of the passenger schedule
*/ */
private _minPassengerScheduleItemGapForDate = (date: Date): ScheduleItemGap => private _minPassengerScheduleItemGapForDate = (date: Date): ScheduleItemGap =>
this.props.passengerSchedule (this.props.passengerSchedule as ScheduleItemProps[])
// first map the passenger schedule to "real" dates (we use unix epoch date as base) // first map the passenger schedule to "real" dates (we use unix epoch date as base)
.map( .map(
(scheduleItem: ScheduleItem) => (scheduleItem: ScheduleItem) =>
@@ -255,6 +315,64 @@ export class CandidateEntity extends AggregateRoot<CandidateProps> {
validate(): void { validate(): void {
// entity business rules validation to protect it's invariant before saving entity to a database // entity business rules validation to protect it's invariant before saving entity to a database
if (!this.props.driverSchedule && !this.props.passengerSchedule)
throw new ArgumentInvalidException(
'at least the driver or the passenger schedule is required',
);
}
}
//TODO Use this class as part of the CandidateEntity aggregate
class Schedule extends ValueObject<{
items: ScheduleItemProps[];
dateInterval: DateInterval;
}> {
constructor(items: ScheduleItemProps[], dateInterval: DateInterval) {
super({ items, dateInterval });
}
protected validate(): void {}
/**
* Add the given duration to each schedule item
* unless the expected new datetime is not possible,
* in which case the item is removed from the adjusted schedule
* @param duration time increment in seconds (can be negative)
* @returns the new adjusted schedule
*/
adjust(duration: number): Schedule {
const newItems = this.props.items.reduce((acc, scheduleItemProps) => {
try {
const itemDate: Date = CalendarTools.firstDate(
scheduleItemProps.day,
this.props.dateInterval,
);
const driverStartDatetime: Date = CalendarTools.datetimeWithSeconds(
itemDate,
scheduleItemProps.time,
duration,
);
acc.push({
day: itemDate.getUTCDay(),
margin: scheduleItemProps.margin,
time: this._formatTime(driverStartDatetime),
});
} catch (e) {
// no possible driver date or time
// TODO : find a test case !
}
return acc;
}, new Array<ScheduleItemProps>());
return new Schedule(newItems, this.props.dateInterval);
}
private _formatTime(dateTime: Date) {
return (
dateTime.getUTCHours().toString().padStart(2, '0') +
':' +
dateTime.getUTCMinutes().toString().padStart(2, '0')
);
} }
} }

View File

@@ -11,8 +11,8 @@ export interface CandidateProps {
frequency: Frequency; frequency: Frequency;
driverWaypoints: PointProps[]; driverWaypoints: PointProps[];
passengerWaypoints: PointProps[]; passengerWaypoints: PointProps[];
driverSchedule: ScheduleItemProps[]; driverSchedule?: ScheduleItemProps[];
passengerSchedule: ScheduleItemProps[]; passengerSchedule?: ScheduleItemProps[];
driverDistance: number; driverDistance: number;
driverDuration: number; driverDuration: number;
dateInterval: DateInterval; dateInterval: DateInterval;
@@ -33,8 +33,8 @@ export interface CreateCandidateProps {
driverDuration: number; driverDuration: number;
driverWaypoints: PointProps[]; driverWaypoints: PointProps[];
passengerWaypoints: PointProps[]; passengerWaypoints: PointProps[];
driverSchedule: ScheduleItemProps[]; driverSchedule?: ScheduleItemProps[];
passengerSchedule: ScheduleItemProps[]; passengerSchedule?: ScheduleItemProps[];
spacetimeDetourRatio: SpacetimeDetourRatio; spacetimeDetourRatio: SpacetimeDetourRatio;
dateInterval: DateInterval; dateInterval: DateInterval;
} }

View File

@@ -0,0 +1,7 @@
import { DomainEvent, DomainEventProps } from '@mobicoop/ddd-library';
export class AdDeletedDomainEvent extends DomainEvent {
constructor(props: DomainEventProps<AdDeletedDomainEvent>) {
super(props);
}
}

View File

@@ -1,7 +1,7 @@
import { Route } from '../application/types/route.type';
import { Role } from './ad.types'; import { Role } from './ad.types';
import { PathCreatorException } from './match.errors';
import { Point } from './value-objects/point.value-object'; import { Point } from './value-objects/point.value-object';
import { PathCreatorException } from './match.errors';
import { Route } from '../application/types/route.type';
export class PathCreator { export class PathCreator {
constructor( constructor(

View File

@@ -2,8 +2,7 @@ import {
ArgumentOutOfRangeException, ArgumentOutOfRangeException,
ValueObject, ValueObject,
} from '@mobicoop/ddd-library'; } from '@mobicoop/ddd-library';
import { Actor, ActorProps } from './actor.value-object'; import { ActorProps } from './actor.value-object';
import { Role } from '../ad.types';
import { Point, PointProps } from './point.value-object'; import { Point, PointProps } from './point.value-object';
/** Note: /** Note:
@@ -36,12 +35,5 @@ export class CarpoolPathItem extends ValueObject<CarpoolPathItemProps> {
}); });
if (props.actors.length <= 0) if (props.actors.length <= 0)
throw new ArgumentOutOfRangeException('at least one actor is required'); throw new ArgumentOutOfRangeException('at least one actor is required');
if (
props.actors.filter((actor: Actor) => actor.role == Role.DRIVER).length >
1
)
throw new ArgumentOutOfRangeException(
'a carpoolStep can contain only one driver',
);
} }
} }

View File

@@ -42,8 +42,8 @@ export class JourneyItem extends ValueObject<JourneyItemProps> {
(actorTime: ActorTime) => actorTime.role == Role.DRIVER, (actorTime: ActorTime) => actorTime.role == Role.DRIVER,
) as ActorTime ) as ActorTime
).firstDatetime; ).firstDatetime;
return `${driverTime.getHours().toString().padStart(2, '0')}:${driverTime return `${driverTime.getUTCHours().toString().padStart(2, '0')}:${driverTime
.getMinutes() .getUTCMinutes()
.toString() .toString()
.padStart(2, '0')}`; .padStart(2, '0')}`;
}; };

View File

@@ -46,6 +46,29 @@ export class Journey extends ValueObject<JourneyProps> {
const driverActorTime = passengerDepartureJourneyItem.actorTimes.find( const driverActorTime = passengerDepartureJourneyItem.actorTimes.find(
(actorTime: ActorTime) => actorTime.role == Role.DRIVER, (actorTime: ActorTime) => actorTime.role == Role.DRIVER,
) as ActorTime; ) as ActorTime;
// TODO : check if the following conditions are even to the ones used in the return
// 4 possibilities to be valid :
// - 1 : the driver time boundaries are within the passenger time boundaries
// - 2 : the max driver time boundary is within the passenger time boundaries
// - 3 : the min driver time boundary is within the passenger time boundaries
// - 4 : the passenger time boundaries are within the driver time boundaries
// return (
// // 1
// (driverActorTime.firstMinDatetime >=
// passengerDepartureActorTime.firstMinDatetime &&
// driverActorTime.firstMaxDatetime <=
// passengerDepartureActorTime.firstMaxDatetime) ||
// // 2 & 4
// (driverActorTime.firstMinDatetime <=
// passengerDepartureActorTime.firstMinDatetime &&
// driverActorTime.firstMaxDatetime >=
// passengerDepartureActorTime.firstMinDatetime) ||
// // 3
// (driverActorTime.firstMinDatetime >=
// passengerDepartureActorTime.firstMinDatetime &&
// driverActorTime.firstMinDatetime <=
// passengerDepartureActorTime.firstMaxDatetime)
// );
return ( return (
(passengerDepartureActorTime.firstMinDatetime <= (passengerDepartureActorTime.firstMinDatetime <=
driverActorTime.firstMaxDatetime && driverActorTime.firstMaxDatetime &&

View File

@@ -14,7 +14,7 @@ export interface MatchQueryProps {
frequency: Frequency; frequency: Frequency;
fromDate: string; fromDate: string;
toDate: string; toDate: string;
schedule: ScheduleItemProps[]; schedule?: ScheduleItemProps[];
seatsProposed: number; seatsProposed: number;
seatsRequested: number; seatsRequested: number;
strict: boolean; strict: boolean;
@@ -50,7 +50,7 @@ export class MatchQuery extends ValueObject<MatchQueryProps> {
return this.props.toDate; return this.props.toDate;
} }
get schedule(): ScheduleItemProps[] { get schedule(): ScheduleItemProps[] | undefined {
return this.props.schedule; return this.props.schedule;
} }

View File

@@ -1,26 +1,35 @@
import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { Observable, lastValueFrom } from 'rxjs'; import { Observable, lastValueFrom } from 'rxjs';
import { GEOGRAPHY_SERVICE } from '../ad.di-tokens'; import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { ClientGrpc } from '@nestjs/microservices';
import { GRPC_GEOROUTER_SERVICE_NAME } from '@src/app.constants';
import { import {
GeorouterPort, GeorouterPort,
RouteRequest, RouteRequest,
RouteResponse, RouteResponse,
} from '../core/application/ports/georouter.port'; } from '../core/application/ports/georouter.port';
import { GEOGRAPHY_PACKAGE } from '../ad.di-tokens';
interface GeorouterService { interface GeorouterService {
getRoute(request: RouteRequest): Observable<RouteResponse>; getRoute(request: RouteRequest): Observable<RouteResponse>;
} }
@Injectable() @Injectable()
export class Georouter implements GeorouterPort { export class Georouter implements GeorouterPort, OnModuleInit {
private georouterService: GeorouterService; private georouterService: GeorouterService;
constructor( constructor(@Inject(GEOGRAPHY_PACKAGE) private readonly client: ClientGrpc) {}
@Inject(GEOGRAPHY_SERVICE) private readonly client: ClientProxy,
) {} onModuleInit() {
this.georouterService = this.client.getService<GeorouterService>(
GRPC_GEOROUTER_SERVICE_NAME,
);
}
getRoute = async (request: RouteRequest): Promise<RouteResponse> => { getRoute = async (request: RouteRequest): Promise<RouteResponse> => {
return lastValueFrom(this.client.send('getRoute', request)); try {
return await lastValueFrom(this.georouterService.getRoute(request));
} catch (error: any) {
throw error;
}
}; };
} }

View File

@@ -1,10 +1,11 @@
import { ResponseBase } from '@mobicoop/ddd-library'; import { ResponseBase } from '@mobicoop/ddd-library';
import { JourneyResponseDto } from './journey.response.dto'; import { JourneyResponseDto } from './journey.response.dto';
import { Frequency } from '@modules/ad/core/domain/ad.types';
export class MatchResponseDto extends ResponseBase { export class MatchResponseDto extends ResponseBase {
adId: string; adId: string;
role: string; role: string;
frequency: string; frequency: Frequency;
distance: number; distance: number;
duration: number; duration: number;
initialDistance: number; initialDistance: number;

View File

@@ -58,8 +58,9 @@ export class MatchRequestDto {
@Type(() => ScheduleItemDto) @Type(() => ScheduleItemDto)
@IsArray() @IsArray()
@ArrayMinSize(1) @ArrayMinSize(1)
@IsOptional()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
schedule: ScheduleItemDto[]; schedule?: ScheduleItemDto[];
@IsOptional() @IsOptional()
@IsInt() @IsInt()
@@ -80,6 +81,10 @@ export class MatchRequestDto {
@ValidateNested({ each: true }) @ValidateNested({ each: true })
waypoints: WaypointDto[]; waypoints: WaypointDto[];
@IsUUID()
@IsOptional()
excludedAdId?: string;
@IsOptional() @IsOptional()
@IsEnum(AlgorithmType) @IsEnum(AlgorithmType)
algorithmType?: AlgorithmType; algorithmType?: AlgorithmType;

View File

@@ -1,18 +1,18 @@
import { Controller, Inject, UseInterceptors, UsePipes } from '@nestjs/common';
import { GrpcMethod, RpcException } from '@nestjs/microservices';
import { RpcValidationPipe } from '@mobicoop/ddd-library'; import { RpcValidationPipe } from '@mobicoop/ddd-library';
import { RpcExceptionCode } from '@mobicoop/ddd-library';
import { MatchingPaginatedResponseDto } from '../dtos/matching.paginated.response.dto';
import { QueryBus } from '@nestjs/cqrs';
import { MatchRequestDto } from './dtos/match.request.dto';
import { MatchQuery } from '@modules/ad/core/application/queries/match/match.query';
import { MatchEntity } from '@modules/ad/core/domain/match.entity';
import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens'; import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens';
import { MatchMapper } from '@modules/ad/match.mapper';
import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler';
import { CacheInterceptor, CacheKey } from '@nestjs/cache-manager';
import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port'; import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port';
import { MatchQuery } from '@modules/ad/core/application/queries/match/match.query';
import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler';
import { MatchEntity } from '@modules/ad/core/domain/match.entity';
import { MatchMapper } from '@modules/ad/match.mapper';
import { Controller, Inject, UseFilters, UsePipes } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs';
import { GrpcMethod } from '@nestjs/microservices';
import { LogCauseExceptionFilter } from '@src/log-cause.exception-filter';
import { MatchingPaginatedResponseDto } from '../dtos/matching.paginated.response.dto';
import { MatchRequestDto } from './dtos/match.request.dto';
@UseFilters(LogCauseExceptionFilter)
@UsePipes( @UsePipes(
new RpcValidationPipe({ new RpcValidationPipe({
whitelist: false, whitelist: false,
@@ -28,11 +28,8 @@ export class MatchGrpcController {
private readonly matchMapper: MatchMapper, private readonly matchMapper: MatchMapper,
) {} ) {}
@CacheKey('MatcherServiceMatch')
@UseInterceptors(CacheInterceptor)
@GrpcMethod('MatcherService', 'Match') @GrpcMethod('MatcherService', 'Match')
async match(data: MatchRequestDto): Promise<MatchingPaginatedResponseDto> { async match(data: MatchRequestDto): Promise<MatchingPaginatedResponseDto> {
try {
const matchingResult: MatchingResult = await this.queryBus.execute( const matchingResult: MatchingResult = await this.queryBus.execute(
new MatchQuery(data, this.routeProvider), new MatchQuery(data, this.routeProvider),
); );
@@ -45,11 +42,5 @@ export class MatchGrpcController {
perPage: matchingResult.perPage, perPage: matchingResult.perPage,
total: matchingResult.total, total: matchingResult.total,
}); });
} catch (e) {
throw new RpcException({
code: RpcExceptionCode.UNKNOWN,
message: e.message,
});
}
} }
} }

View File

@@ -16,16 +16,17 @@ message MatchRequest {
repeated ScheduleItem schedule = 7; repeated ScheduleItem schedule = 7;
bool strict = 8; bool strict = 8;
repeated Waypoint waypoints = 9; repeated Waypoint waypoints = 9;
AlgorithmType algorithmType = 10; string excludedAdId = 10;
int32 remoteness = 11; AlgorithmType algorithmType = 11;
bool useProportion = 12; int32 remoteness = 12;
float proportion = 13; bool useProportion = 13;
bool useAzimuth = 14; float proportion = 14;
int32 azimuthMargin = 15; bool useAzimuth = 15;
float maxDetourDistanceRatio = 16; int32 azimuthMargin = 16;
float maxDetourDurationRatio = 17; float maxDetourDistanceRatio = 17;
optional int32 page = 18; float maxDetourDurationRatio = 18;
optional int32 perPage = 19; optional int32 page = 19;
optional int32 perPage = 20;
} }
message ScheduleItem { message ScheduleItem {
@@ -58,15 +59,16 @@ enum AlgorithmType {
message Match { message Match {
string adId = 1; string adId = 1;
string role = 2; string role = 2;
int32 distance = 3; Frequency frequency = 3;
int32 duration = 4; int32 distance = 4;
int32 initialDistance = 5; int32 duration = 5;
int32 initialDuration = 6; int32 initialDistance = 6;
int32 distanceDetour = 7; int32 initialDuration = 7;
int32 durationDetour = 8; int32 distanceDetour = 8;
double distanceDetourPercentage = 9; int32 durationDetour = 9;
double durationDetourPercentage = 10; double distanceDetourPercentage = 10;
repeated Journey journeys = 11; double durationDetourPercentage = 11;
repeated Journey journeys = 12;
} }
message Journey { message Journey {

View File

@@ -0,0 +1,32 @@
import { RabbitSubscribe } from '@mobicoop/message-broker-module';
import { DeleteAdCommand } from '@modules/ad/core/application/commands/delete-ad/delete-ad.command';
import { Injectable } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import {
AD_DELETED_MESSAGE_HANDLER,
AD_DELETED_ROUTING_KEY,
} from '@src/app.constants';
import { AdReference } from './ad.types';
@Injectable()
export class AdDeletedMessageHandler {
constructor(private readonly commandBus: CommandBus) {}
@RabbitSubscribe({
name: AD_DELETED_MESSAGE_HANDLER,
routingKey: AD_DELETED_ROUTING_KEY,
})
public async adDeleted(message: string): Promise<void> {
try {
const deletedAd: AdReference = JSON.parse(message);
await this.commandBus.execute(
new DeleteAdCommand({
id: deletedAd.aggregateId,
}),
);
} catch (error: any) {
// do not throw error to acknowledge incoming message
// error handling should be done in the command handler, if relevant
}
}
}

View File

@@ -1,7 +1,10 @@
import { Frequency } from '@modules/ad/core/domain/ad.types'; import { Frequency } from '@modules/ad/core/domain/ad.types';
export type Ad = { export type AdReference = {
aggregateId: string; aggregateId: string;
};
export type Ad = AdReference & {
driver: boolean; driver: boolean;
passenger: boolean; passenger: boolean;
frequency: Frequency; frequency: Frequency;

View File

@@ -64,7 +64,7 @@ export class MatchingMapper
toDate: entity.getProps().query.toDate, toDate: entity.getProps().query.toDate,
schedule: entity schedule: entity
.getProps() .getProps()
.query.schedule.map((scheduleItem: ScheduleItem) => ({ .query.schedule?.map((scheduleItem: ScheduleItem) => ({
day: scheduleItem.day, day: scheduleItem.day,
time: scheduleItem.time, time: scheduleItem.time,
margin: scheduleItem.margin, margin: scheduleItem.margin,

View File

@@ -1,46 +1,10 @@
import { AdEntity } from '@modules/ad/core/domain/ad.entity'; import { AdEntity } from '@modules/ad/core/domain/ad.entity';
import { CreateAdProps, Frequency } from '@modules/ad/core/domain/ad.types'; import { createAdProps } from './ad.fixtures';
import { PointProps } from '@modules/ad/core/domain/value-objects/point.value-object';
const originPointProps: PointProps = {
lat: 48.689445,
lon: 6.17651,
};
const destinationPointProps: PointProps = {
lat: 48.8566,
lon: 2.3522,
};
const createAdProps: CreateAdProps = {
id: 'e8fe64b1-4c33-49e1-9f69-4db48b21df36',
driver: true,
passenger: true,
fromDate: '2023-06-21',
toDate: '2023-06-21',
schedule: [
{
day: 3,
time: '08:30',
margin: 900,
},
],
frequency: Frequency.PUNCTUAL,
seatsProposed: 3,
seatsRequested: 1,
strict: false,
waypoints: [originPointProps, destinationPointProps],
driverDistance: 23000,
driverDuration: 900,
passengerDistance: 23000,
passengerDuration: 900,
fwdAzimuth: 283,
backAzimuth: 93,
points: [],
};
describe('Ad entity create', () => { describe('Ad entity create', () => {
describe('create', () => {
it('should create a new entity', async () => { it('should create a new entity', async () => {
const ad: AdEntity = AdEntity.create(createAdProps); const ad: AdEntity = AdEntity.create(createAdProps());
expect(ad.id.length).toBe(36); expect(ad.id.length).toBe(36);
expect(ad.getProps().schedule.length).toBe(1); expect(ad.getProps().schedule.length).toBe(1);
expect(ad.getProps().schedule[0].day).toBe(3); expect(ad.getProps().schedule[0].day).toBe(3);
@@ -50,3 +14,4 @@ describe('Ad entity create', () => {
expect(ad.getProps().driverDistance).toBe(23000); expect(ad.getProps().driverDistance).toBe(23000);
}); });
}); });
});

View File

@@ -0,0 +1,40 @@
import { CreateAdProps, Frequency } from '@modules/ad/core/domain/ad.types';
import { PointProps } from '@modules/ad/core/domain/value-objects/point.value-object';
const originPointProps: PointProps = {
lat: 48.689445,
lon: 6.17651,
};
const destinationPointProps: PointProps = {
lat: 48.8566,
lon: 2.3522,
};
export function createAdProps(): CreateAdProps {
return {
id: 'e8fe64b1-4c33-49e1-9f69-4db48b21df36',
driver: true,
passenger: true,
fromDate: '2023-06-21',
toDate: '2023-06-21',
schedule: [
{
day: 3,
time: '08:30',
margin: 900,
},
],
frequency: Frequency.PUNCTUAL,
seatsProposed: 3,
seatsRequested: 1,
strict: false,
waypoints: [originPointProps, destinationPointProps],
driverDistance: 23000,
driverDuration: 900,
passengerDistance: 23000,
passengerDuration: 900,
fwdAzimuth: 283,
backAzimuth: 93,
points: [],
};
}

View File

@@ -1,3 +1,4 @@
import { ArgumentInvalidException } from '@mobicoop/ddd-library';
import { Frequency, Role } from '@modules/ad/core/domain/ad.types'; import { Frequency, Role } from '@modules/ad/core/domain/ad.types';
import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity'; import { CandidateEntity } from '@modules/ad/core/domain/candidate.entity';
import { import {
@@ -6,7 +7,10 @@ import {
} from '@modules/ad/core/domain/candidate.types'; } from '@modules/ad/core/domain/candidate.types';
import { Actor } from '@modules/ad/core/domain/value-objects/actor.value-object'; import { Actor } from '@modules/ad/core/domain/value-objects/actor.value-object';
import { CarpoolPathItemProps } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object'; import { CarpoolPathItemProps } from '@modules/ad/core/domain/value-objects/carpool-path-item.value-object';
import { Journey } from '@modules/ad/core/domain/value-objects/journey.value-object'; import {
Journey,
JourneyProps,
} from '@modules/ad/core/domain/value-objects/journey.value-object';
import { PointProps } from '@modules/ad/core/domain/value-objects/point.value-object'; import { PointProps } from '@modules/ad/core/domain/value-objects/point.value-object';
import { ScheduleItemProps } from '@modules/ad/core/domain/value-objects/schedule-item.value-object'; import { ScheduleItemProps } from '@modules/ad/core/domain/value-objects/schedule-item.value-object';
import { StepProps } from '@modules/ad/core/domain/value-objects/step.value-object'; import { StepProps } from '@modules/ad/core/domain/value-objects/step.value-object';
@@ -33,7 +37,7 @@ const waypointsSet2: PointProps[] = [
}, },
]; ];
const schedule1: ScheduleItemProps[] = [ const mondayAt7: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '07:00', time: '07:00',
@@ -41,7 +45,7 @@ const schedule1: ScheduleItemProps[] = [
}, },
]; ];
const schedule2: ScheduleItemProps[] = [ const mondayAt710: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '07:10', time: '07:10',
@@ -49,7 +53,7 @@ const schedule2: ScheduleItemProps[] = [
}, },
]; ];
const schedule3: ScheduleItemProps[] = [ const weekdayMornings: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '06:30', time: '06:30',
@@ -77,7 +81,7 @@ const schedule3: ScheduleItemProps[] = [
}, },
]; ];
const schedule4: ScheduleItemProps[] = [ const schooldayMornings: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '06:50', time: '06:50',
@@ -100,7 +104,7 @@ const schedule4: ScheduleItemProps[] = [
}, },
]; ];
const schedule5: ScheduleItemProps[] = [ const saturdayNightAndMondayMorning: ScheduleItemProps[] = [
{ {
day: 0, day: 0,
time: '00:02', time: '00:02',
@@ -113,7 +117,7 @@ const schedule5: ScheduleItemProps[] = [
}, },
]; ];
const schedule6: ScheduleItemProps[] = [ const mondayAndSaturdayNights: ScheduleItemProps[] = [
{ {
day: 1, day: 1,
time: '23:10', time: '23:10',
@@ -126,7 +130,7 @@ const schedule6: ScheduleItemProps[] = [
}, },
]; ];
const schedule7: ScheduleItemProps[] = [ const thursdayEvening: ScheduleItemProps[] = [
{ {
day: 4, day: 4,
time: '19:00', time: '19:00',
@@ -262,8 +266,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule2, passengerSchedule: mondayAt710,
spacetimeDetourRatio, spacetimeDetourRatio,
}); });
expect(candidateEntity.id.length).toBe(36); expect(candidateEntity.id.length).toBe(36);
@@ -282,8 +286,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule2, passengerSchedule: mondayAt710,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setCarpoolPath(carpoolPath1); }).setCarpoolPath(carpoolPath1);
expect(candidateEntity.getProps().carpoolPath).toHaveLength(2); expect(candidateEntity.getProps().carpoolPath).toHaveLength(2);
@@ -302,8 +306,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule2, passengerSchedule: mondayAt710,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setMetrics(352688, 14587); }).setMetrics(352688, 14587);
expect(candidateEntity.getProps().distance).toBe(352688); expect(candidateEntity.getProps().distance).toBe(352688);
@@ -324,8 +328,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule2, passengerSchedule: mondayAt710,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setMetrics(458690, 13980); }).setMetrics(458690, 13980);
expect(candidateEntity.isDetourValid()).toBeFalsy(); expect(candidateEntity.isDetourValid()).toBeFalsy();
@@ -343,8 +347,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule2, passengerSchedule: mondayAt710,
spacetimeDetourRatio, spacetimeDetourRatio,
}).setMetrics(352368, 18314); }).setMetrics(352368, 18314);
expect(candidateEntity.isDetourValid()).toBeFalsy(); expect(candidateEntity.isDetourValid()).toBeFalsy();
@@ -365,8 +369,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule2, passengerSchedule: mondayAt710,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -374,6 +378,95 @@ describe('Candidate entity', () => {
.createJourneys(); .createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1); expect(candidateEntity.getProps().journeys).toHaveLength(1);
}); });
it('should create journeys for a single date without driver schedule', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2023-08-28',
higherDate: '2023-08-28',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: undefined,
passengerSchedule: mondayAt710,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1);
// computed driver start time should be 06:49
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[0].actorTimes[0].firstDatetime.getUTCMinutes(),
).toBe(49);
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[0].actorTimes[0].firstDatetime.getUTCHours(),
).toBe(6);
});
it('should create journeys for a single date without passenger schedule', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2023-08-28',
higherDate: '2023-08-28',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: mondayAt7,
passengerSchedule: undefined,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1);
// computed passenger start time should be 07:20
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[1].actorTimes[0].firstDatetime.getUTCMinutes(),
).toBe(20);
expect(
(
candidateEntity.getProps().journeys as JourneyProps[]
)[0].journeyItems[1].actorTimes[0].firstDatetime.getUTCHours(),
).toBe(7);
});
it('should throw without driver and passenger schedule', () => {
expect(() =>
CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2023-08-28',
higherDate: '2023-08-28',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: undefined,
passengerSchedule: undefined,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys(),
).toThrow(ArgumentInvalidException);
});
it('should create journeys for multiple dates', () => { it('should create journeys for multiple dates', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({ const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0', id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
@@ -387,8 +480,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule3, driverSchedule: weekdayMornings,
passengerSchedule: schedule4, passengerSchedule: schooldayMornings,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -424,8 +517,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule5, driverSchedule: saturdayNightAndMondayMorning,
passengerSchedule: schedule6, passengerSchedule: mondayAndSaturdayNights,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -457,6 +550,33 @@ describe('Candidate entity', () => {
)[0].journeyItems[1].actorTimes[1].firstMinDatetime.getUTCMinutes(), )[0].journeyItems[1].actorTimes[1].firstMinDatetime.getUTCMinutes(),
).toBe(42); ).toBe(42);
}); });
it('should create a journey for a punctual search from a recurrent driver schedule', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({
id: '5600ccfb-ab69-4d03-aa30-0fbe84fcedc0',
role: Role.PASSENGER,
frequency: Frequency.PUNCTUAL,
dateInterval: {
lowerDate: '2024-04-01', //This is a Monday
higherDate: '2024-04-01',
},
driverWaypoints: waypointsSet1,
passengerWaypoints: waypointsSet2,
driverDistance: 350145,
driverDuration: 13548,
driverSchedule: weekdayMornings,
passengerSchedule: mondayAt7,
spacetimeDetourRatio,
})
.setCarpoolPath(carpoolPath2)
.setSteps(steps)
.createJourneys();
expect(candidateEntity.getProps().journeys).toHaveLength(1);
expect(
(
candidateEntity.getProps().journeys as Journey[]
)[0].firstDate.getDate(),
).toBe(1);
});
it('should not create journeys if dates does not match', () => { it('should not create journeys if dates does not match', () => {
const candidateEntity: CandidateEntity = CandidateEntity.create({ const candidateEntity: CandidateEntity = CandidateEntity.create({
@@ -471,8 +591,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule7, passengerSchedule: thursdayEvening,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)
@@ -495,8 +615,8 @@ describe('Candidate entity', () => {
passengerWaypoints: waypointsSet2, passengerWaypoints: waypointsSet2,
driverDistance: 350145, driverDistance: 350145,
driverDuration: 13548, driverDuration: 13548,
driverSchedule: schedule1, driverSchedule: mondayAt7,
passengerSchedule: schedule7, passengerSchedule: thursdayEvening,
spacetimeDetourRatio, spacetimeDetourRatio,
}) })
.setCarpoolPath(carpoolPath2) .setCarpoolPath(carpoolPath2)

View File

@@ -33,22 +33,4 @@ describe('Carpool Path Item value object', () => {
}); });
}).toThrow(ArgumentOutOfRangeException); }).toThrow(ArgumentOutOfRangeException);
}); });
it('should throw an exception if actors contains more than one driver', () => {
expect(() => {
new CarpoolPathItem({
lat: 48.689445,
lon: 6.17651,
actors: [
new Actor({
role: Role.DRIVER,
target: Target.NEUTRAL,
}),
new Actor({
role: Role.DRIVER,
target: Target.START,
}),
],
});
}).toThrow(ArgumentOutOfRangeException);
});
}); });

View File

@@ -0,0 +1,41 @@
import { AD_REPOSITORY } from '@modules/ad/ad.di-tokens';
import { DeleteAdCommand } from '@modules/ad/core/application/commands/delete-ad/delete-ad.command';
import { DeleteAdService } from '@modules/ad/core/application/commands/delete-ad/delete-ad.service';
import { AdEntity } from '@modules/ad/core/domain/ad.entity';
import { Test, TestingModule } from '@nestjs/testing';
import { createAdProps } from './ad.fixtures';
const ad: AdEntity = AdEntity.create(createAdProps());
const mockAdRepository = {
findOneById: jest.fn().mockImplementation(() => ad),
delete: jest.fn(),
};
describe('DeleteAdService', () => {
let deleteAdService: DeleteAdService;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: AD_REPOSITORY,
useValue: mockAdRepository,
},
DeleteAdService,
],
}).compile();
deleteAdService = module.get<DeleteAdService>(DeleteAdService);
});
it('should be defined', () => {
expect(deleteAdService).toBeDefined();
});
it('should execute the delete logic and delete the ad from the repository', async () => {
jest.spyOn(ad, 'delete');
await deleteAdService.execute(new DeleteAdCommand(ad.id));
expect(ad.delete).toHaveBeenCalled();
expect(mockAdRepository.delete).toHaveBeenCalledWith(ad);
});
});

View File

@@ -44,7 +44,7 @@ describe('Match Query value object', () => {
expect(matchQueryVO.frequency).toBe(Frequency.PUNCTUAL); expect(matchQueryVO.frequency).toBe(Frequency.PUNCTUAL);
expect(matchQueryVO.fromDate).toBe('2023-09-01'); expect(matchQueryVO.fromDate).toBe('2023-09-01');
expect(matchQueryVO.toDate).toBe('2023-09-01'); expect(matchQueryVO.toDate).toBe('2023-09-01');
expect(matchQueryVO.schedule.length).toBe(1); expect(matchQueryVO.schedule?.length).toBe(1);
expect(matchQueryVO.seatsProposed).toBe(3); expect(matchQueryVO.seatsProposed).toBe(3);
expect(matchQueryVO.seatsRequested).toBe(1); expect(matchQueryVO.seatsRequested).toBe(1);
expect(matchQueryVO.strict).toBe(false); expect(matchQueryVO.strict).toBe(false);

View File

@@ -1,6 +1,9 @@
import { DateTimeTransformerPort } from '@modules/ad/core/application/ports/datetime-transformer.port'; import { DateTimeTransformerPort } from '@modules/ad/core/application/ports/datetime-transformer.port';
import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port'; import { GeorouterPort } from '@modules/ad/core/application/ports/georouter.port';
import { MatchQuery } from '@modules/ad/core/application/queries/match/match.query'; import {
MatchQuery,
ScheduleItem,
} from '@modules/ad/core/application/queries/match/match.query';
import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types'; import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types';
import { Waypoint } from '@modules/ad/core/application/types/waypoint.type'; import { Waypoint } from '@modules/ad/core/application/types/waypoint.type';
import { Frequency } from '@modules/ad/core/domain/ad.types'; import { Frequency } from '@modules/ad/core/domain/ad.types';
@@ -135,9 +138,9 @@ describe('Match Query', () => {
expect(matchQuery.maxDetourDurationRatio).toBe(0.3); expect(matchQuery.maxDetourDurationRatio).toBe(0.3);
expect(matchQuery.fromDate).toBe('2023-08-27'); expect(matchQuery.fromDate).toBe('2023-08-27');
expect(matchQuery.toDate).toBe('2023-08-27'); expect(matchQuery.toDate).toBe('2023-08-27');
expect(matchQuery.schedule[0].day).toBe(0); expect((matchQuery.schedule as ScheduleItem[])[0].day).toBe(0);
expect(matchQuery.schedule[0].time).toBe('23:05'); expect((matchQuery.schedule as ScheduleItem[])[0].time).toBe('23:05');
expect(matchQuery.schedule[0].margin).toBe(900); expect((matchQuery.schedule as ScheduleItem[])[0].margin).toBe(900);
}); });
it('should set good values for seats', async () => { it('should set good values for seats', async () => {

View File

@@ -47,6 +47,7 @@ const matchQuery = new MatchQuery(
], ],
strict: false, strict: false,
waypoints: [originWaypoint, destinationWaypoint], waypoints: [originWaypoint, destinationWaypoint],
excludedAdId: '758618c6-dd82-4199-a548-0205161b04d7',
}, },
bareMockGeorouter, bareMockGeorouter,
); );

View File

@@ -0,0 +1,44 @@
import { AdDeletedMessageHandler } from '@modules/ad/interface/message-handlers/ad-deleted.message-handler';
import { CommandBus } from '@nestjs/cqrs';
import { Test, TestingModule } from '@nestjs/testing';
const adDeletedMessage =
'{"aggregateId":"4eb6a6af-ecfd-41c3-9118-473a507014d4"}';
const mockCommandBus = {
execute: jest.fn(),
};
describe('Ad Deleted Message Handler', () => {
let adDeletedMessageHandler: AdDeletedMessageHandler;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: CommandBus,
useValue: mockCommandBus,
},
AdDeletedMessageHandler,
],
}).compile();
adDeletedMessageHandler = module.get<AdDeletedMessageHandler>(
AdDeletedMessageHandler,
);
});
afterEach(async () => {
jest.clearAllMocks();
});
it('should be defined', () => {
expect(adDeletedMessageHandler).toBeDefined();
});
it('should call the delete command', async () => {
jest.spyOn(mockCommandBus, 'execute');
await adDeletedMessageHandler.adDeleted(adDeletedMessage);
expect(mockCommandBus.execute).toHaveBeenCalledTimes(1);
});
});

View File

@@ -1,4 +1,3 @@
import { RpcExceptionCode } from '@mobicoop/ddd-library';
import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens'; import { AD_ROUTE_PROVIDER } from '@modules/ad/ad.di-tokens';
import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler'; import { MatchingResult } from '@modules/ad/core/application/queries/match/match.query-handler';
import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types'; import { AlgorithmType } from '@modules/ad/core/application/types/algorithm.types';
@@ -14,7 +13,6 @@ import { MatchGrpcController } from '@modules/ad/interface/grpc-controllers/matc
import { MatchMapper } from '@modules/ad/match.mapper'; import { MatchMapper } from '@modules/ad/match.mapper';
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { QueryBus } from '@nestjs/cqrs'; import { QueryBus } from '@nestjs/cqrs';
import { RpcException } from '@nestjs/microservices';
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from '@nestjs/testing';
import { bareMockGeorouter } from '../georouter.mock'; import { bareMockGeorouter } from '../georouter.mock';
@@ -56,9 +54,7 @@ const recurrentMatchRequestDto: MatchRequestDto = {
}; };
const mockQueryBus = { const mockQueryBus = {
execute: jest execute: jest.fn().mockImplementationOnce(
.fn()
.mockImplementationOnce(
() => () =>
<MatchingResult>{ <MatchingResult>{
id: '43c83ae2-f4b0-4ac6-b8bf-8071801924d4', id: '43c83ae2-f4b0-4ac6-b8bf-8071801924d4',
@@ -177,10 +173,7 @@ const mockQueryBus = {
], ],
total: 1, total: 1,
}, },
) ),
.mockImplementationOnce(() => {
throw new Error();
}),
}; };
const mockMatchMapper = { const mockMatchMapper = {
@@ -317,16 +310,4 @@ describe('Match Grpc Controller', () => {
expect(matchingPaginatedResponseDto.perPage).toBe(10); expect(matchingPaginatedResponseDto.perPage).toBe(10);
expect(mockQueryBus.execute).toHaveBeenCalledTimes(1); expect(mockQueryBus.execute).toHaveBeenCalledTimes(1);
}); });
it('should throw a generic RpcException', async () => {
jest.spyOn(mockQueryBus, 'execute');
expect.assertions(3);
try {
await matchGrpcController.match(recurrentMatchRequestDto);
} catch (e: any) {
expect(e).toBeInstanceOf(RpcException);
expect(e.error.code).toBe(RpcExceptionCode.UNKNOWN);
}
expect(mockQueryBus.execute).toHaveBeenCalledTimes(1);
});
}); });

View File

@@ -1,17 +1,20 @@
import { Module, Provider } from '@nestjs/common';
import { MESSAGE_PUBLISHER } from './messager.di-tokens';
import { import {
MessageBrokerModule, MessageBrokerModule,
MessageBrokerModuleOptions, MessageBrokerModuleOptions,
MessageBrokerPublisher, MessageBrokerPublisher,
} from '@mobicoop/message-broker-module'; } from '@mobicoop/message-broker-module';
import { Module, Provider } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config'; import { ConfigModule, ConfigService } from '@nestjs/config';
import { import {
AD_CREATED_MESSAGE_HANDLER, AD_CREATED_MESSAGE_HANDLER,
AD_CREATED_QUEUE, AD_CREATED_QUEUE,
AD_CREATED_ROUTING_KEY, AD_CREATED_ROUTING_KEY,
AD_DELETED_MESSAGE_HANDLER,
AD_DELETED_QUEUE,
AD_DELETED_ROUTING_KEY,
SERVICE_NAME, SERVICE_NAME,
} from '@src/app.constants'; } from '@src/app.constants';
import { MESSAGE_PUBLISHER } from './messager.di-tokens';
const imports = [ const imports = [
MessageBrokerModule.forRootAsync({ MessageBrokerModule.forRootAsync({
@@ -33,6 +36,10 @@ const imports = [
routingKey: AD_CREATED_ROUTING_KEY, routingKey: AD_CREATED_ROUTING_KEY,
queue: AD_CREATED_QUEUE, queue: AD_CREATED_QUEUE,
}, },
[AD_DELETED_MESSAGE_HANDLER]: {
routingKey: AD_DELETED_ROUTING_KEY,
queue: AD_DELETED_QUEUE,
},
}, },
}), }),
}), }),

View File

@@ -7,6 +7,7 @@
"experimentalDecorators": true, "experimentalDecorators": true,
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"target": "es2017", "target": "es2017",
"lib": ["es2022"],
"sourceMap": true, "sourceMap": true,
"outDir": "./dist", "outDir": "./dist",
"baseUrl": "./", "baseUrl": "./",