Skip to content

Commit

Permalink
manual patch creation
Browse files Browse the repository at this point in the history
  • Loading branch information
achorein committed Dec 20, 2024
1 parent 65ea855 commit 2ccf639
Show file tree
Hide file tree
Showing 15 changed files with 192 additions and 169 deletions.
6 changes: 2 additions & 4 deletions apiv2/src/admin/AdminJob.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { planDeTransportMongoProviders } from "./infra/sejours/phase1/planDeTran
import { DATABASE_CONNECTION } from "@infra/Database.provider";
import { ClsPluginTransactional } from "@nestjs-cls/transactional";
import { TransactionalAdapterMongoose } from "@infra/TransactionalAdatpterMongoose";
import { historyProvider } from "./infra/history/historyProvider";

@Module({
imports: [
Expand All @@ -37,10 +38,6 @@ import { TransactionalAdapterMongoose } from "@infra/TransactionalAdatpterMongoo
imports: [DatabaseModule],
adapter: new TransactionalAdapterMongoose({
mongooseConnectionToken: DATABASE_CONNECTION,
defaultTxOptions: {
// https://www.mongodb.com/docs/manual/core/transactions-sharded-clusters/#time-limit
maxTimeMS: 1000 * 60 * 15, // 10 minutes
},
}),
}),
],
Expand All @@ -63,6 +60,7 @@ import { TransactionalAdapterMongoose } from "@infra/TransactionalAdatpterMongoo
...taskMongoProviders,
...phase1GatewayProviders,
...jeuneGatewayProviders,
...historyProvider,
{ provide: FileGateway, useClass: FileProvider },
{ provide: TaskGateway, useClass: AdminTaskRepository },
// add use case here
Expand Down
1 change: 1 addition & 0 deletions apiv2/src/admin/core/history/History.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { PatchType } from "snu-lib";

export interface HistoryGateway {
findByReferenceId(history: HistoryType, referenceId: string): Promise<PatchType[]>;
bulkCreate(history: HistoryType, patches: PatchType[]): Promise<number>;
}

export const HistoryGateway = Symbol("HistoryGateway");
3 changes: 2 additions & 1 deletion apiv2/src/admin/core/sejours/jeune/Jeune.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ export interface JeuneGateway {
): Promise<JeuneModel[]>;
findBySessionId(sessionId: string): Promise<JeuneModel[]>;
update(jeune: JeuneModel, updateOriginName?: string): Promise<JeuneModel>;
bulkUpdate(jeunes: { original: JeuneModel; updated: JeuneModel }[], updateOriginName?: string): Promise<number>;
create(jeune: CreateJeuneModel): Promise<JeuneModel>;
countAffectedByLigneDeBus(ligneDeBusId: string): Promise<number>;
countAffectedByLigneDeBus(ligneDeBusId: string);
}

export const JeuneGateway = Symbol("JeuneGateway");
47 changes: 1 addition & 46 deletions apiv2/src/admin/core/sejours/jeune/Jeune.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,52 +46,7 @@ export type JeuneModel = {
parent2Nom?: string;
parent2Email?: string;
parent2Telephone?: string;
// mandatory
cniFiles: any;
highSkilledActivityProofFiles: any;
parentConsentmentFiles: any;
autoTestPCRFiles: any;
imageRightFiles: any;
dataProcessingConsentmentFiles: any;
rulesFiles: any;
militaryPreparationFilesIdentity: any;
militaryPreparationFilesCensus: any;
militaryPreparationFilesAuthorization: any;
militaryPreparationFilesCertificate: any;
domains: any;
periodRanking: any;
mobilityTransport: any;
notes: any;
statusPhase2Contract: any;
historic: any;
phase2ApplicationStatus: any;
phase2ApplicationFilesType: any;
missionsInMail: any;
loginAttempts: any;
token2FA: any;
attempts2FA: any;
lastLoginAt: any;
forgotPasswordResetToken: any;
acceptCGU: any;
invitationToken: any;
phase: any;
statusPhase2: any;
statusPhase3: any;
lastStatusAt: any;
hasStartedReinscription: any;
cohesion2020Step: any;
tokenEmailValidation: any;
attemptsEmailValidation: any;
cohesionStayMedicalFileDownload: any;
convocationFileDownload: any;
source: any;
phase3Token: any;
parent1FromFranceConnect: any;
parent2FromFranceConnect: any;
imageRightFilesStatus: any;
autoTestPCRFilesStatus: any;
youngPhase1Agreement: any;
hasNotes: any;
youngPhase1Agreement: string;
};

export type CreateJeuneModel = Omit<JeuneModel, "id" | "createdAt" | "updatedAt">;
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jest.mock("@nestjs-cls/transactional", () => ({
Transactional: () => jest.fn(),
}));

describe("SimulationAffectationHTS", () => {
describe("ValiderAffectationHTS", () => {
let validerAffectationHTS: ValiderAffectationHTS;

beforeEach(async () => {
Expand Down Expand Up @@ -66,14 +66,7 @@ describe("SimulationAffectationHTS", () => {
sessionNom: "Avril 2024 - C",
},
]),
update: jest.fn().mockResolvedValue({
id: "jeune1",
sessionNom: "Avril 2024 - C",
ligneDeBusId: "65f9c8bb735e0e12a4213c18",
sejourId: "6597e6acb86afb08146e8f86",
pointDeRassemblementId: "6398797d3bc18708cc3981f6",
hasPDR: "true",
}),
bulkUpdate: jest.fn().mockResolvedValue(1),
countAffectedByLigneDeBus: jest.fn().mockResolvedValue(1),
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export class ValiderAffectationHTS implements UseCase<ValiderAffectationHTSResul
jeunesAffected: 0,
errors: 0,
};
const updateQueries: { original: JeuneModel; updated: JeuneModel }[] = [];
const rapportData: Array<ReturnType<typeof this.formatJeuneRapport>> = [];

// Traitement des jeunes
Expand Down Expand Up @@ -167,8 +168,7 @@ export class ValiderAffectationHTS implements UseCase<ValiderAffectationHTSResul
// Affectation du jeune
sejour.placesRestantes = sejour.placesRestantes - 1;

const jeuneUpdated = await this.jeuneGateway.update(
this.affectationService.mapAffectationJeune(jeune, sejour, {
const jeuneUpdated = this.affectationService.mapAffectationJeune(jeune, sejour, {
...(affecterPDR
? {
pointDeRassemblementId: pdr!.id,
Expand All @@ -177,8 +177,10 @@ export class ValiderAffectationHTS implements UseCase<ValiderAffectationHTSResul
}
: {}),
transportInfoGivenByLocal: undefined, // Metropole
}),
);
});

updateQueries.push({ original: jeune, updated: jeuneUpdated });

this.logger.log(
`🚀 Jeune affecté: ${jeune.id}, centre: ${jeuneUpdated.centreId}, sejour: ${
jeuneUpdated.sejourId
Expand All @@ -189,8 +191,11 @@ export class ValiderAffectationHTS implements UseCase<ValiderAffectationHTSResul

rapportData.push(this.formatJeuneRapport(jeuneUpdated, sejour));
analytics.jeunesAffected += 1;
break;
}

await this.jeuneGateway.bulkUpdate(updateQueries, `Affectation ${session.nom}`);

this.logger.log(`Mise à jour des places dans les séjours`);
// mise à jour des placesRestantes dans les centres
for (const sejour of sejoursList) {
Expand Down
31 changes: 31 additions & 0 deletions apiv2/src/admin/infra/history/repository/HistoryMapper.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { JEUNE_PATCHHISTORY_OPTIONS } from "@admin/infra/sejours/jeune/provider/JeuneMongo.provider";
import { HistoryMapper } from "./HistoryMapper";

describe("HistoryMapper", () => {
describe("toUpdateHistory", () => {
it("should return a PatchType object with user firstname", () => {
const original = { _id: "id", statusPhase1: "WAITING_AFFECTATION", otherField: 2 };
const updated = { _id: "id", statusPhase1: "AFFECTED", otherField: 2 };
const options = JEUNE_PATCHHISTORY_OPTIONS;
const user = { firstName: "firstName" };

const result = HistoryMapper.toUpdateHistory(original, updated, options, user);

expect(result).toEqual({
modelName: "youngs",
ops: [
{
op: "replace",
originalValue: "WAITING_AFFECTATION",
path: "/statusPhase1",
value: "AFFECTED",
},
],
ref: "id",
user: {
firstName: "firstName",
},
});
});
});
});
19 changes: 19 additions & 0 deletions apiv2/src/admin/infra/history/repository/HistoryMapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { createPatch } from "mongoose-patch-history";
import { PatchType } from "snu-lib";

export class HistoryMapper {
static toUpdateHistory(original: object & { _id: string }, updated: object, options: any, user: object): PatchType {
const doc = {
data: () => updated,
_original: original,
_user: user,
_id: original._id,
modelName: options.includes?.modelName?.default,
patches: {
create: (patch) => patch,
},
};
const history = createPatch(doc, options);
return history;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,17 @@ export class HistoryRepository implements HistoryGateway {
const instance = this.getInstance(history);
return instance.find({ ref: referenceId });
}

async bulkCreate(history: HistoryType, patches: PatchType[]): Promise<number> {
const instance = this.getInstance(history);

const updatePatches = await instance.bulkWrite(
patches.map((patch) => ({
insertOne: {
document: patch,
},
})),
);
return updatePatches.insertedCount;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,17 @@ JeuneSchemaRef.pre("save", function (next, params) {
next();
});

JeuneSchemaRef.plugin(patchHistory, {
mongoose,
export const JEUNE_PATCHHISTORY_OPTIONS = {
name: `${JeuneName}Patches`,
trackOriginalValue: true,
includes: {
modelName: { type: String, required: true, default: JeuneName },
user: { type: Object, required: false, from: "_user" },
},
excludes: ["/updatedAt"],
});
};

JeuneSchemaRef.plugin(patchHistory, { mongoose, ...JEUNE_PATCHHISTORY_OPTIONS });

export const jeuneMongoProviders = [
{
Expand Down
Loading

0 comments on commit 2ccf639

Please sign in to comment.