Skip to content

Commit

Permalink
fix(api): bulkwrite unset undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
achorein committed Jan 24, 2025
1 parent 77addde commit 2375fde
Show file tree
Hide file tree
Showing 7 changed files with 262 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { YOUNG_STATUS, YOUNG_STATUS_PHASE1 } from "snu-lib";
import { HistoryType } from "@admin/core/history/History";
import { HistoryMapper } from "@admin/infra/history/repository/HistoryMapper";
import { HistoryGateway } from "@admin/core/history/History.gateway";
import { getEntityUpdateSetUnset } from "@shared/infra/RepositoryHelper";

@Injectable()
export class JeuneRepository implements JeuneGateway {
Expand Down Expand Up @@ -102,7 +103,7 @@ export class JeuneRepository implements JeuneGateway {
jeunesEntity.map((jeune) => ({
updateOne: {
filter: { _id: jeune.updated._id },
update: { $set: jeune.updated },
update: getEntityUpdateSetUnset(jeune.updated),
upsert: false,
},
})),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { LigneDeBusMapper } from "../LigneDeBus.mapper";
import { HistoryGateway } from "@admin/core/history/History.gateway";
import { HistoryType } from "@admin/core/history/History";
import { HistoryMapper } from "@admin/infra/history/repository/HistoryMapper";
import { getEntityUpdateSetUnset } from "@shared/infra/RepositoryHelper";

@Injectable()
export class LigneDeBusRepository implements LigneDeBusGateway {
Expand Down Expand Up @@ -86,7 +87,7 @@ export class LigneDeBusRepository implements LigneDeBusGateway {
lignesEntity.map((ligne) => ({
updateOne: {
filter: { _id: ligne.updated._id },
update: { $set: ligne.updated },
update: getEntityUpdateSetUnset(ligne.updated),
upsert: false,
},
})),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { PlanDeTransportMapper } from "../PlanDeTransport.mapper";
import { HistoryType } from "@admin/core/history/History";
import { HistoryMapper } from "@admin/infra/history/repository/HistoryMapper";
import { HistoryGateway } from "@admin/core/history/History.gateway";
import { getEntityUpdateSetUnset } from "@shared/infra/RepositoryHelper";

@Injectable()
export class PlanDeTransportRepository implements PlanDeTransportGateway {
Expand Down Expand Up @@ -88,7 +89,7 @@ export class PlanDeTransportRepository implements PlanDeTransportGateway {
pdtsEntity.map((pdt) => ({
updateOne: {
filter: { _id: pdt.updated._id },
update: { $set: pdt.updated },
update: getEntityUpdateSetUnset(pdt.updated),
upsert: false,
},
})),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { SejourMapper } from "../Sejour.mapper";
import { HistoryGateway } from "@admin/core/history/History.gateway";
import { HistoryType } from "@admin/core/history/History";
import { HistoryMapper } from "@admin/infra/history/repository/HistoryMapper";
import { getEntityUpdateSetUnset } from "@shared/infra/RepositoryHelper";

@Injectable()
export class SejourRepository implements SejourGateway {
Expand Down Expand Up @@ -88,7 +89,7 @@ export class SejourRepository implements SejourGateway {
sejoursEntity.map((sejour) => ({
updateOne: {
filter: { _id: sejour.updated._id },
update: { $set: sejour.updated },
update: getEntityUpdateSetUnset(sejour.updated),
upsert: false,
},
})),
Expand Down
15 changes: 15 additions & 0 deletions apiv2/src/shared/infra/RepositoryHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function getEntityUpdateSetUnset(entity: Record<string, any>) {
const { set, unset } = Object.keys(entity).reduce(
(acc, key) => {
const value = entity[key];
if (value === undefined) {
acc.unset[key] = 1;
} else {
acc.set[key] = value;
}
return acc;
},
{ set: {}, unset: {} },
);
return { $set: set, $unset: unset };
}
37 changes: 25 additions & 12 deletions apiv2/test/admin/sejour/phase1/Phase1.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import mongoose from "mongoose";
import { INestApplication } from "@nestjs/common";
import { TestingModule } from "@nestjs/testing";

import { TaskGateway } from "@task/core/Task.gateway";
import { YOUNG_STATUS, YOUNG_STATUS_PHASE1 } from "snu-lib";

import { Phase1Controller } from "@admin/infra/sejours/phase1/api/Phase1.controller";
import { JeuneGateway } from "@admin/core/sejours/jeune/Jeune.gateway";

import { setupAdminTest } from "../../setUpAdminTest";
import { createSession } from "./helper/SessionHelper";
Expand All @@ -14,6 +16,7 @@ import { createSejour } from "./helper/SejourHelper";
import { createPointDeRassemblement } from "./helper/PointDeRassemblementHelper";
import { createPlanDeTransport } from "./helper/PlanDeTransportHelper";
import { ClsService } from "nestjs-cls";
import { createJeune } from "./helper/JeuneHelper";

jest.mock("@nestjs-cls/transactional", () => ({
Transactional: () => jest.fn(),
Expand All @@ -25,7 +28,7 @@ describe("Phase1Controller", () => {
let phase1Controller: Phase1Controller;
let mockedAddUserToRequestMiddleware;
let module: TestingModule;
let taskGateway: TaskGateway;
let jeuneGateway: JeuneGateway;
beforeAll(async () => {
const appSetup = await setupAdminTest();
app = appSetup.app;
Expand All @@ -42,11 +45,9 @@ describe("Phase1Controller", () => {

app.use(mockedAddUserToRequestMiddleware);

taskGateway = module.get<TaskGateway>(TaskGateway);
jeuneGateway = module.get<JeuneGateway>(JeuneGateway);
cls = module.get<ClsService>(ClsService);
await app.init();
const tasks = await taskGateway.findAll();
taskGateway.deleteMany(tasks.map((task) => task.id));
});

it("should be defined", () => {
Expand All @@ -56,29 +57,41 @@ describe("Phase1Controller", () => {
describe("DELETE /phase1/:id/plan-de-transport", () => {
it("should return 200", async () => {
const session = await createSession();
console.log("createPointDeRassemblement");
const pdr = await createPointDeRassemblement();
console.log("createSejour");
await createSejour({ sessionId: session.id });
console.log("createLigneDeBus");
await createLigneDeBus({
sessionNom: session.nom,
const sejour = await createSejour({ sessionId: session.id });
const ligne = await createLigneDeBus({
sessionId: session.id,
sessionNom: session.nom,
pointDeRassemblementIds: [pdr.id],
});
await createPlanDeTransport({
sessionNom: session.nom,
sessionId: session.id,
});

console.log("api");
const jeuneBefore = await createJeune({
statut: YOUNG_STATUS.VALIDATED,
statutPhase1: YOUNG_STATUS_PHASE1.AFFECTED,
sessionId: session.id,
sessionNom: session.nom,
sejourId: sejour.id,
ligneDeBusId: ligne.id,
pointDeRassemblementId: pdr.id,
});
const response = await cls.runWith(
// @ts-ignore
{ user: null },
() => request(app.getHttpServer()).delete(`/phase1/${session.id}/plan-de-transport`),
);

expect(response.status).toBe(200);

const jeuneAfter = await jeuneGateway.findById(jeuneBefore.id);
expect(jeuneAfter.statutPhase1).toBe(YOUNG_STATUS_PHASE1.WAITING_AFFECTATION);
expect(jeuneAfter.youngPhase1Agreement).toBe("false");
expect(jeuneAfter.centreId).toBeUndefined();
expect(jeuneAfter.pointDeRassemblementId).toBeUndefined();
expect(jeuneAfter.ligneDeBusId).toBeUndefined();
});
});

Expand Down
214 changes: 214 additions & 0 deletions apiv2/test/admin/sejour/phase1/helper/JeuneHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import mongoose from "mongoose";
import { fakerFR as faker } from "@faker-js/faker";

import { getAdminTestModuleRef } from "../../../setUpAdminTest";
import { JeuneModel } from "@admin/core/sejours/jeune/Jeune.model";
import { JeuneGateway } from "@admin/core/sejours/jeune/Jeune.gateway";
import { addYears } from "date-fns";
import { departmentList, regionList } from "snu-lib";

export const createJeune = async (jeune?: Partial<JeuneModel>) => {
const adminTestModule = getAdminTestModuleRef();
const jeuneGateway = adminTestModule.get<JeuneGateway>(JeuneGateway);

return await jeuneGateway.create({
prenom: faker.person.firstName(),
nom: faker.person.lastName(),
// frenchNationality: "true",
// birthCountry: faker.location.country(),
// birthCity: faker.location.city(),
// birthCityZip: faker.location.zipCode(),
email: faker.internet
.email({ firstName: faker.person.firstName(), lastName: faker.string.uuid() })
.toLowerCase(),
telephone: faker.phone.number(),
// phoneZone: "FRANCE",
genre: faker.person.gender(),
dateNaissance: faker.date.past({ years: 3, refDate: addYears(new Date(), -15) }),
sessionId: new mongoose.Types.ObjectId().toString(),
sessionNom: "Juillet 2023",
// acceptCGU: "true",
// phase: "CONTINUE",
statut: "REFUSED",
statutPhase1: "AFFECTED",
// statutPhase2: "IN_PROGRESS",
// statutPhase3: "VALIDATED",
// statusPhase2UpdatedAt: faker.date.past(),
// statusPhase2ValidatedAt: faker.date.past(),
// statusPhase3UpdatedAt: faker.date.past(),
// statusPhase3ValidatedAt: faker.date.past(),
// lastStatusAt: faker.date.past(),
// withdrawnReason: "",
// withdrawnMessage: "",
// inscriptionStep: "PROFIL",
// cohesion2020Step: "JDC",
// historic: [],
// password: faker.internet.password(),
// cniFiles: [],
cohesionStayPresence: "true",
presenceJDM: "true",
departSejourAt: faker.date.past().toISOString(),
departSejourMotif: "blabla",
departSejourMotifComment: "blabla details",
// cohesionStayMedicalFileReceived: "false",
centreId: "",
// cohesionCenterName: "",
// cohesionCenterZip: "",
// cohesionCenterCity: "",
// autoAffectationPhase1ExpiresAt: faker.date.past(),
// phase2ApplicationStatus: [],
// phase3StructureName: "",
// phase3MissionDomain: "",
// phase3MissionDescription: "",
// phase3MissionStartAt: faker.date.past(),
// phase3MissionEndAt: faker.date.past(),
// phase3TutorFirstName: "",
// phase3TutorLastName: "",
// phase3TutorEmail: "",
// phase3TutorPhone: "",
// phase3TutorNote: "",
// phase3Token: "3",
// address: "",
// complementAddress: "",
// zip: faker.location.zipCode(),
// city: faker.location.city(),
// cityCode: faker.location.zipCode(),
departement: faker.helpers.arrayElement(departmentList),
region: faker.helpers.arrayElement(regionList),
// country: "France",
localisation: {
lat: Number(faker.location.latitude()),
lon: Number(faker.location.longitude()),
},
// hostLastName: faker.person.lastName(),
// hostFirstName: faker.person.firstName(),
// hostRelationship: "Parent",
// foreignCountry: faker.location.country(),
// foreignCity: faker.location.city(),
// foreignZip: faker.location.zipCode(),
// foreignAddress: "Une super adresse",
// populationDensity: "DENSE",
qpv: "false",
// situation: "Etudiant",
// grade: "2ndeGT",
// schoolCertification: "false",
// schooled: "true",
// schoolName: faker.location.city(),
// schoolType: "Lycée",
// schoolAddress: faker.location.street(),
// schoolComplementAdresse: "",
// schoolZip: faker.location.zipCode(),
// schoolCity: faker.location.city(),
departementScolarite: faker.helpers.arrayElement(departmentList),
regionScolarite: faker.helpers.arrayElement(regionList),
// schoolLocation: {
// lat: Number(faker.location.latitude()),
// lon: Number(faker.location.longitude()),
// },
// schoolId: String(faker.number.int()),
// academy: "Strasbourg",
// parent1Status: "",
parent1Prenom: faker.person.firstName(),
parent1Nom: faker.person.lastName(),
parent1Email: faker.internet.email(),
parent1Telephone: faker.phone.number(),
// parent1OwnAddress: "true",
// parent1Address: faker.location.streetAddress(),
// parent1ComplementAddress: "",
// parent1Zip: faker.location.zipCode(),
// parent1City: faker.location.city(),
// parent1Department: faker.helpers.arrayElement(departmentList),
// parent1Region: faker.helpers.arrayElement(regionList),
// parent1Location: {
// lat: Number(faker.location.latitude()),
// lon: Number(faker.location.longitude()),
// },
// parent1FromFranceConnect: "true",
// parent2Status: "",
parent2Prenom: faker.person.firstName(),
parent2Nom: faker.person.lastName(),
parent2Email: faker.internet.email(),
parent2Telephone: faker.phone.number(),
// parent2OwnAddress: "true",
// parent2Address: faker.location.streetAddress(),
// parent2ComplementAddress: "",
// parent2Zip: faker.location.zipCode(),
// parent2City: faker.location.city(),
// parent2Department: faker.helpers.arrayElement(departmentList),
// parent2Region: faker.helpers.arrayElement(regionList),
// parent2Location: {
// lat: Number(faker.location.latitude()),
// lon: Number(faker.location.longitude()),
// },
// parent2FromFranceConnect: "false",
// handicap: "true",
// ppsBeneficiary: "false",
// paiBeneficiary: "false",
// medicosocialStructure: "true",
// medicosocialStructureName: faker.location.country(),
// medicosocialStructureAddress: faker.location.streetAddress(),
// medicosocialStructureComplementAddress: "",
// medicosocialStructureZip: faker.location.zipCode(),
// medicosocialStructureCity: faker.location.city(),
// medicosocialStructureDepartment: faker.helpers.arrayElement(departmentList),
// medicosocialStructureRegion: faker.helpers.arrayElement(regionList),
// medicosocialStructureLocation: {
// lat: Number(faker.location.latitude()),
// lon: Number(faker.location.longitude()),
// },
// engagedStructure: "Maison",
// specificAmenagment: "false",
// specificAmenagmentType: "Aucun",
// highSkilledActivity: "true",
// highSkilledActivityType: "Sport",
// highSkilledActivityProofFiles: [],
// parentConsentment: "true",
// parentConsentmentFiles: [],
// parentConsentmentFilesCompliant: "false",
// parentConsentmentFilesCompliantInfo: "",
// consentment: "false",
// imageRight: "false",
// imageRightFiles: [],
// autoTestPCR: "true",
// autoTestPCRFiles: [],
// rulesYoung: "true",
// rulesParent1: "true",
// rulesParent2: "true",
// rulesFiles: [],
// jdc: "false",
// motivations: "SNU",
// domains: [""],
// professionnalProject: "UNIFORM",
// professionnalProjectPrecision: "",
// period: "DURING_SCHOOL",
// periodRanking: [""],
// mobilityNearSchool: "false",
// mobilityNearHome: "false",
// mobilityNearRelative: "true",
// mobilityNearRelativeName: "",
// mobilityNearRelativeAddress: "",
// mobilityNearRelativeZip: faker.location.zipCode(),
// mobilityTransport: [faker.vehicle.vehicle()],
// mobilityTransportOther: faker.lorem.sentences(),
// missionFormat: "CONTINUOUS",
// engaged: "true",
// engagedDescription: faker.lorem.sentences(),
// desiredLocation: faker.lorem.sentences(),
// defenseInterest: faker.lorem.sentences(),
// defenseTypeInterest: faker.lorem.sentences(),
// defenseDomainInterest: faker.lorem.sentences(),
// defenseMotivationInterest: faker.lorem.sentences(),
// securityInterest: faker.lorem.sentences(),
// securityDomainInterest: faker.lorem.sentences(),
// solidarityInterest: faker.lorem.sentences(),
// healthInterest: faker.lorem.sentences(),
// educationInterest: faker.lorem.sentences(),
// cultureInterest: faker.lorem.sentences(),
// sportInterest: faker.lorem.sentences(),
// environmentInterest: faker.lorem.sentences(),
// citizenshipInterest: faker.lorem.sentences(),
// originalCohortId: new mongoose.Types.ObjectId().toString(),
youngPhase1Agreement: "true",
...jeune,
});
};

0 comments on commit 2375fde

Please sign in to comment.