Skip to content

Commit

Permalink
V1 stats area ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentlaine committed Jul 18, 2024
1 parent 6fe2466 commit 8e3fe64
Show file tree
Hide file tree
Showing 8 changed files with 169 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"flatbush": "^4.4.0",
"helmet": "^7.1.0",
"lodash": "^4.17.21",
"moment": "^2.30.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pg": "^8.11.3",
Expand Down
5 changes: 4 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { CronModule } from './cron/cron.module';
import { UsageModule } from './usage/usage.module';
import AuthModule from './auth/auth.module';
import { ArretesRestrictionsModule } from './arretes_restrictions/arretes_restrictions.module';
import { DataModule } from './data/data.module';

@Module({
imports: [
Expand Down Expand Up @@ -69,6 +70,7 @@ import { ArretesRestrictionsModule } from './arretes_restrictions/arretes_restri
CronModule,
UsageModule,
ArretesRestrictionsModule,
DataModule,
],
controllers: [AppController],
providers: [
Expand All @@ -82,4 +84,5 @@ import { ArretesRestrictionsModule } from './arretes_restrictions/arretes_restri
},
],
})
export class AppModule {}
export class AppModule {
}
18 changes: 18 additions & 0 deletions src/data/data.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Controller, Get, Query } from '@nestjs/common';
import { ApiExcludeController, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { DataService } from './data.service';

@Controller('data')
@ApiExcludeController()
export class DataController {
constructor(private readonly dataService: DataService) {}

@Get('area')
@ApiOperation({ summary: "Récupérer les pourcentages de surface couvertes par des restrictions" })
@ApiQuery({ name: 'dateDebut', description: 'Date de recherche (YYYY-MM-DD), si non précisée c\'est la date du jour qui est prise en compte', required: false })
@ApiQuery({ name: 'dateFin', description: 'Date de recherche (YYYY-MM-DD), si non précisée c\'est la date du jour qui est prise en compte', required: false })
findAll(@Query('dateDebut') dateDebut?: string,
@Query('dateFin') dateFin?: string,) {
return this.dataService.findByDate(dateDebut, dateFin);
}
}
14 changes: 14 additions & 0 deletions src/data/data.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { StatisticDepartement } from './entities/statistic_departement.entity';
import { DataController } from './data.controller';
import { DataService } from './data.service';
import { Departement } from '../zones/entities/departement.entity';

@Module({
imports: [TypeOrmModule.forFeature([StatisticDepartement, Departement])],
controllers: [DataController],
providers: [DataService],
})
export class DataModule {
}
90 changes: 90 additions & 0 deletions src/data/data.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { Injectable } from '@nestjs/common';
import { VigieauLogger } from '../logger/vigieau.logger';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { StatisticDepartement } from './entities/statistic_departement.entity';
import { Departement } from '../zones/entities/departement.entity';
import moment from 'moment';

@Injectable()
export class DataService {
private readonly logger = new VigieauLogger('DataService');

data: any;
departements: any[];
metropoleArea: number;
fullArea: number;
releaseDate = '2023-07-11';
beginDate = '2013-01-01';

constructor(@InjectRepository(StatisticDepartement)
private readonly statisticDepartementRepository: Repository<StatisticDepartement>,
@InjectRepository(Departement)
private readonly departementRepository: Repository<Departement>,
) {
this.loadData();
}

findByDate(dateDebut?: string, dateFin?: string) {
const dataFiltered = this.data.filter(d =>
moment(d.date).isSameOrAfter(moment(this.beginDate, 'YYYY-MM-DD'), 'day')
&& moment(d.date, 'YYYY-MM-DD').isSameOrBefore(moment(), 'day')
&& (dateDebut ? moment(d.date, 'YYYY-MM-DD').isSameOrAfter(moment(dateDebut, 'YYYY-MM-DD'), 'day') : true)
&& (dateFin ? moment(d.date, 'YYYY-MM-DD').isSameOrBefore(moment(dateFin, 'YYYY-MM-DD'), 'day') : true),
);
return dataFiltered.map(d => {
return {
date: d.date,
ESO: this.filterRestrictions(d.restrictions, 'SOU', this.fullArea),
ESU: this.filterRestrictions(d.restrictions, 'SUP', this.fullArea),
AEP: this.filterRestrictions(d.restrictions, 'AEP', this.fullArea),
};
});
}

filterRestrictions(restrictions: any, zoneType: string, areaPercentage: number) {
return {
vigilance: (restrictions.reduce((acc, r) => acc + Number(r[zoneType] ? r[zoneType].vigilance : 0), 0) * 100 / areaPercentage).toFixed(2),
alerte: (restrictions.reduce((acc, r) => acc + Number(r[zoneType] ? r[zoneType].alerte : 0), 0) * 100 / areaPercentage).toFixed(2),
alerte_renforcee: (restrictions.reduce((acc, r) => acc + Number(r[zoneType] ? r[zoneType].alerte_renforcee : 0), 0) * 100 / areaPercentage).toFixed(2),
crise: (restrictions.reduce((acc, r) => acc + Number(r[zoneType] ? r[zoneType].crise : 0), 0) * 100 / areaPercentage).toFixed(2),
};
}

async loadData() {
this.logger.log('LOAD DATA');
const statisticsDepartement = await this.statisticDepartementRepository.find({
relations: ['departement'],
});
this.departements = await this.departementRepository
.createQueryBuilder('departement')
.select('departement.id', 'id')
.addSelect('departement.code', 'code')
.addSelect('departement.nom', 'nom')
.addSelect(
'ST_Area(departement.geom::geography)/1000000',
'area')
.getRawMany();
this.fullArea = this.departements.reduce((acc, d) => acc + d.area, 0);
this.metropoleArea = this.departements.filter(d => d.code.length < 3).reduce((acc, d) => acc + d.area, 0);

const endDate = moment();
this.data = [];
for (let m = moment(this.beginDate, 'YYYY-MM-DD'); m.diff(endDate, 'days', true) <= 0; m.add(1, 'days')) {
const d = {
date: m.format('YYYY-MM-DD'),
restrictions: [],
};
statisticsDepartement.forEach((statisticDepartement) => {
const restriction = statisticDepartement.restrictions.find(r => r.date === m.format('YYYY-MM-DD'));
if (restriction) {
d.restrictions.push({
...{ departement: statisticDepartement.departement.code },
...restriction,
});
}
});
this.data.push(d);
}
}
}
33 changes: 33 additions & 0 deletions src/data/entities/statistic_departement.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { BaseEntity, Column, Entity, ManyToOne, PrimaryGeneratedColumn, Unique } from 'typeorm';
import { Departement } from '../../zones/entities/departement.entity';

@Entity()
@Unique(['departement'])
export class StatisticDepartement extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;

@ManyToOne(() => Departement, (departement) => departement.statisticDepartement)
departement: Departement;

@Column('jsonb',{ nullable: true })
visits: any[];

@Column('jsonb',{ nullable: true })
restrictions: any[];

@Column({ nullable: false })
totalVisits: number;

@Column({ nullable: false })
weekVisits: number;

@Column({ nullable: false })
monthVisits: number;

@Column({ nullable: false })
yearVisits: number;

@Column({ nullable: false })
subscriptions: number;
}
4 changes: 4 additions & 0 deletions src/zones/entities/departement.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from 'typeorm';
import { ArreteRestriction } from './arrete_restriction.entity';
import { Region } from './region.entity';
import { StatisticDepartement } from '../../data/entities/statistic_departement.entity';

@Entity()
export class Departement extends BaseEntity {
Expand Down Expand Up @@ -56,4 +57,7 @@ export class Departement extends BaseEntity {

// @OneToOne(() => Parametres, (parametres) => parametres.departement)
// parametres: Parametres;

@OneToMany(() => StatisticDepartement, (statisticDepartement) => statisticDepartement.departement)
statisticDepartement: StatisticDepartement[];
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4402,6 +4402,11 @@ mkdirp@^2.1.3:
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-2.1.6.tgz#964fbcb12b2d8c5d6fbc62a963ac95a273e2cc19"
integrity sha512-+hEnITedc8LAtIP9u3HJDFIdcLV2vXP33sqLLIzkv1Db1zO/1OxbvYf0Y1OC/S/Qo5dxHXepofhmxL02PsKe+A==

moment@^2.30.1:
version "2.30.1"
resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae"
integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==

[email protected]:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
Expand Down

0 comments on commit 8e3fe64

Please sign in to comment.