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 8d092cf
Show file tree
Hide file tree
Showing 21 changed files with 238 additions and 198 deletions.
3 changes: 2 additions & 1 deletion apiv2/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ RUN apk update
WORKDIR /app
RUN npm install --global turbo@^2.0.0
COPY . .
RUN turbo prune $APP_NAME --docker
RUN turbo prune $APP_NAME --docker && cp -fr patches out/full/

# Add lockfile and package.json's of isolated subworkspace
FROM base AS installer
Expand All @@ -22,6 +22,7 @@ WORKDIR /app
COPY .gitignore .gitignore
COPY --from=builder /app/out/json/ .
COPY --from=builder /app/out/full/packages/ ./packages/
COPY --from=builder /app/out/full/patches/ ./patches/
RUN npm install

# Build the project and its dependencies
Expand Down
2 changes: 1 addition & 1 deletion apiv2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"class-validator": "^0.14.1",
"date-fns": "^3.6.0",
"mongoose": "^8.9.1",
"mongoose-patch-history": "^2.0.0",
"mongoose-patch-history": "^2.0",
"nestjs-cls": "^4.4.1",
"nodemailer": "^6.9.16",
"reflect-metadata": "^0.2.0",
Expand Down
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 Expand Up @@ -146,8 +139,6 @@ describe("SimulationAffectationHTS", () => {
dateAffectation: new Date(),
});

console.log(result);

expect(result.analytics.errors).toEqual(0);
expect(result.analytics.jeunesAffected).toEqual(1);
expect(result.rapportData[0]).toEqual({
Expand Down Expand Up @@ -176,8 +167,8 @@ describe("SimulationAffectationHTS", () => {
region: undefined,
sessionId: "6597e6acb86afb08146e8f86",
sessionNom: "Avril 2024 - C",
statut: undefined,
statutPhase1: undefined,
statut: "VALIDATED",
statutPhase1: "AFFECTED",
telephone: undefined,
});
});
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,18 +168,19 @@ 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, {
...(affecterPDR
? {
pointDeRassemblementId: pdr!.id,
ligneDeBusId: ligneDeBus!.id,
hasPDR: "true",
}
: {}),
transportInfoGivenByLocal: undefined, // Metropole
}),
);
const jeuneUpdated = this.affectationService.mapAffectationJeune(jeune, sejour, {
...(affecterPDR
? {
pointDeRassemblementId: pdr!.id,
ligneDeBusId: ligneDeBus!.id,
hasPDR: "true",
}
: {}),
transportInfoGivenByLocal: undefined, // Metropole
});

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

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

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: "young",
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
@@ -1,6 +1,6 @@
import { DATABASE_CONNECTION } from "@infra/Database.provider";
import mongoose, { Connection, HydratedDocument } from "mongoose";
import { PatchSchema, PatchType } from "snu-lib";
import { PatchOperationSchema, PatchSchema, PatchType, PatchUserSchema } from "snu-lib";
import { ReferentName } from "../../../iam/provider/ReferentMongo.provider";
import { JeuneName } from "../../../sejours/jeune/provider/JeuneMongo.provider";
import { SessionName } from "../../../sejours/phase1/session/provider/SessionMongo.provider";
Expand All @@ -11,7 +11,17 @@ export type HistoryDocument = HydratedDocument<PatchType>;
const PatchName = "patche";
const PATCH_MONGOOSE_ENTITY = "PATCH_MONGOOSE_ENTITY";

const PatchSchemaRef = new mongoose.Schema(PatchSchema);
const PatchSchemaRef = new mongoose.Schema({
...PatchSchema,
user: {
...PatchSchema.user,
type: new mongoose.Schema(PatchUserSchema),
},
ops: {
...PatchSchema.ops,
type: [new mongoose.Schema(PatchOperationSchema)],
},
});

const collectionWithPatches = [JeuneName, ReferentName, ClasseName, SessionName];

Expand Down
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 @@ -6,7 +6,7 @@ import { YoungSchema, YoungSchemaCorrectionRequest, YoungSchemaFile, YoungSchema
import { DATABASE_CONNECTION } from "@infra/Database.provider";

export type JeuneDocument = HydratedDocument<YoungType>;
export const JeuneName = "youngs";
export const JeuneName = "young";
export const JEUNE_MONGOOSE_ENTITY = "JEUNE_MONGOOSE_ENTITY";

const JeuneSchemaRef = new mongoose.Schema({
Expand Down 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 8d092cf

Please sign in to comment.