Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { registerDecorator, ValidationOptions } from "class-validator";

// The date must be between now - maxPastMs and now + maxFutureMs
export function IsDateTimeWithin(
{ maxPastMs, maxFutureMs }: { maxPastMs: number; maxFutureMs: number },
validationOptions?: ValidationOptions
) {
return function (object: object, propertyName: string) {
registerDecorator({
name: "isDateTimeWithin",
target: object.constructor,
propertyName,
options: validationOptions,
validator: {
validate(value: unknown) {
if (typeof value !== "string") {
return false;
}
const time = new Date(value).getTime();
if (Number.isNaN(time)) {
return false;
}
const now = Date.now();
return time >= now - maxPastMs && time <= now + maxFutureMs;
},
defaultMessage() {
return "DATE_OUT_OF_RANGE";
},
},
});
};
}
1 change: 1 addition & 0 deletions packages/backend/src/_common/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//@index('./*', f => `export * from '${f.path}'`, { ignore: ['**/tests/**'] })
export * from "../../modules/portail-admin/decorators/isValidGeographicDecorator";
export * from "./IsDateTimeWithinDecorator";
export * from "./IsValidPasswordDecorator";
export * from "./IsValidPhoneDecorator";
export * from "./MatchFieldDecorator";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import {
Usager,
UsagerDecision,
CriteriaSearchField,
getUsagerDeadlines,
ETAPE_ENTRETIEN,
Expand Down Expand Up @@ -32,7 +30,14 @@ import {
joinSelectFields,
} from "../../database";

import { SearchUsagerDto } from "../dto";
import { SearchUsagerDto, UpdateManageDto } from "../dto";
import { applyUsagerNameSearch, filterUsagerHistorique } from "../utils";

const RADIES_PREVIEW_LIMIT = 1600;
const RADIES_SEARCH_WITHOUT_CRITERIA_LIMIT = 100;
const UPDATE_MANAGE_DEFAULT_WINDOW_MINUTES = 5;
// Rows committed after the previous poll can carry an older updatedAt (transaction start time)
const UPDATE_MANAGE_OVERLAP_MINUTES = 1;

@Controller("search-usagers")
@UseGuards(AuthGuard("jwt"), AppUserGuard)
Expand All @@ -53,6 +58,8 @@ export class SearchUsagersController {
if (typeof chargerTousRadies !== "boolean") {
throw new BadRequestException("BAD_REQUEST");
}
// Taken before reading, so that nothing written during the load is skipped by update-manage
const syncedAt = new Date();
const usagersNonRadies = await usagerRepository.find({
where: {
statut: Not("RADIE"),
Expand All @@ -67,7 +74,10 @@ export class SearchUsagersController {
structureId: user.structureId,
},
select: USAGER_LIGHT_ATTRIBUTES,
take: chargerTousRadies ? undefined : 1600,
// Without an order, the window changes between two calls
...(chargerTousRadies
? {}
: { order: { ref: "DESC" }, take: RADIES_PREVIEW_LIMIT }),
});

const usagersRadiesTotalCount = chargerTousRadies
Expand All @@ -79,41 +89,36 @@ export class SearchUsagersController {
},
});

const filterHistorique = (usager: Usager) => {
if (usager.historique && Array.isArray(usager.historique)) {
usager.historique = usager.historique.map((item: UsagerDecision) => ({
statut: item.statut,
dateDecision: item.dateDecision,
dateDebut: item.dateDebut,
dateFin: item.dateFin,
})) as UsagerDecision[];
}
return usager;
};

const usagersMerges = [...usagersNonRadies, ...usagersRadiesFirsts].map(
filterHistorique
filterUsagerHistorique
);

return {
usagersRadiesTotalCount,
usagers: usagersMerges,
syncedAt,
};
}

@Get("update-manage")
public async updateManage(@CurrentUser() user: UserStructureAuthenticated) {
return await usagerRepository
public async updateManage(
@Query() query: UpdateManageDto,
@CurrentUser() user: UserStructureAuthenticated
) {
const since = query.since
? subMinutes(new Date(query.since), UPDATE_MANAGE_OVERLAP_MINUTES)
: subMinutes(new Date(), UPDATE_MANAGE_DEFAULT_WINDOW_MINUTES);

const usagers = await usagerRepository
.createQueryBuilder()
.select(joinSelectFields(USAGER_LIGHT_ATTRIBUTES))
.where(
`"structureId" = :structureId AND "updatedAt" >= :fiveMinutesAgo`,
{
structureId: user.structureId,
fiveMinutesAgo: subMinutes(new Date(), 5),
}
)
.select(joinSelectFields([...USAGER_LIGHT_ATTRIBUTES, "updatedAt"]))
.where(`"structureId" = :structureId AND "updatedAt" >= :since`, {
structureId: user.structureId,
since,
})
.getRawMany();

return usagers.map(filterUsagerHistorique);
}

@Get("count")
Expand All @@ -137,9 +142,7 @@ export class SearchUsagersController {

if (search.searchString?.length > 0) {
if (search.searchStringField === CriteriaSearchField.DEFAULT) {
query.andWhere("nom_prenom_surnom_ref ILIKE :str", {
str: `%${search.searchString}%`,
});
applyUsagerNameSearch(query, search.searchString);
} else if (search.searchStringField === CriteriaSearchField.BIRTH_DATE) {
const formattedDate = format(
parse(search.searchString, "ddMMyyyy", new Date()),
Expand Down Expand Up @@ -213,9 +216,12 @@ export class SearchUsagersController {
typeof search?.referrerId === "undefined" &&
!search?.lastInteractionDate
) {
query.take(100);
query
.orderBy(`usager."ref"`, "DESC")
.take(RADIES_SEARCH_WITHOUT_CRITERIA_LIMIT);
}

return await query.getRawMany();
const usagers = await query.getRawMany();
return usagers.map(filterUsagerHistorique);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,68 @@ export const UsagersControllerSecurityTests: AppTestHttpClientSecurityTestDef[]
),
}),
},
// Unknown usagerRef: allowed roles stop at UsagerAccessGuard (400), nothing is written
{
label: `${CONTROLLER}.patchMailAndPhone`,
query: async (context: AppTestContext) => ({
response: await AppTestHttpClient.patch(
"/usagers/contact-details/999999",
{ context, body: {} }
),
expectedStatus: expectedResponseStatusBuilder.allowStructureOnly(
context.user,
{
validExpectedResponseStatus: HttpStatus.BAD_REQUEST,
roles: ["simple", "responsable", "admin"],
}
),
}),
},
{
label: `${CONTROLLER}.nextStep`,
query: async (context: AppTestContext) => ({
response: await AppTestHttpClient.get("/usagers/next-step/999999/3", {
context,
}),
expectedStatus: expectedResponseStatusBuilder.allowStructureOnly(
context.user,
{
validExpectedResponseStatus: HttpStatus.BAD_REQUEST,
roles: ["simple", "responsable", "admin"],
}
),
}),
},
{
label: `${CONTROLLER}.stopCourrier`,
query: async (context: AppTestContext) => ({
response: await AppTestHttpClient.post(
"/usagers/stop-courrier/999999",
{ context, body: {} }
),
expectedStatus: expectedResponseStatusBuilder.allowStructureOnly(
context.user,
{
validExpectedResponseStatus: HttpStatus.BAD_REQUEST,
roles: ["simple", "responsable", "admin", "facteur", "agent"],
}
),
}),
},
{
label: `${CONTROLLER}.assignReferrersToAnotherUser`,
query: async (context: AppTestContext) => ({
response: await AppTestHttpClient.post("/usagers/assign-referrers", {
context,
body: { usagersRefs: [999999], newReferrerId: null },
}),
expectedStatus: expectedResponseStatusBuilder.allowStructureOnly(
context.user,
{
validExpectedResponseStatus: HttpStatus.BAD_REQUEST,
roles: ["simple", "responsable", "admin"],
}
),
}),
},
];
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "../../../util/test";
import { UsagersModule } from "../../usagers.module";
import { CriteriaSearchField } from "@domifa/common";
import { usagerRepository } from "../../../database";

describe("SearchUsagersController", () => {
let controller: SearchUsagersController;
Expand Down Expand Up @@ -119,6 +120,88 @@ describe("SearchUsagersController", () => {
}).expect(400);
});

it("should find a radie whatever the order of the words", async () => {
const response = await AppTestHttpClient.post(
"/search-usagers/search-radies",
{
context,
body: {
searchString: "lisa loumiel",
searchStringField: CriteriaSearchField.DEFAULT,
},
}
).expect(201);
expect(response.body.map((usager) => usager.nom)).toEqual(["Loumiel"]);
});

it("should return the server time with the full load", async () => {
const response = await AppTestHttpClient.get(
"/search-usagers?chargerTousRadies=false",
{ context }
).expect(200);
expect(Number.isNaN(Date.parse(response.body.syncedAt))).toBe(false);
});

it("should return every usager updated since lastSync", async () => {
const lastSync = new Date().toISOString();
await usagerRepository.update(
{ ref: 4, structureId: 1 },
{ updatedAt: new Date() }
);

const response = await AppTestHttpClient.get(
`/search-usagers/update-manage?since=${lastSync}`,
{ context }
).expect(200);
expect(response.body.map((usager) => usager.ref)).toContain(4);
for (const usager of response.body) {
expect(usager.updatedAt).toBeDefined();
for (const decision of usager.historique ?? []) {
expect(
Object.keys(decision).every((key) =>
["statut", "dateDecision", "dateDebut", "dateFin"].includes(key)
)
).toBe(true);
}
}
});

it.each([
"hier",
"2026-10-27",
"2026-10-27T10:00",
"2026-10-27T10:00:00",
"20261027T100000Z",
"2026-02-30T10:00:00Z",
])("should reject lastSync %s", async (since) => {
await AppTestHttpClient.get(
`/search-usagers/update-manage?since=${encodeURIComponent(since)}`,
{ context }
).expect(400);
});

it.each([
["more than one day old", -25 * 60 * 60 * 1000],
["in the future", 2 * 60 * 60 * 1000],
])("should reject a lastSync %s", async (_label, offsetMs) => {
const since = new Date(Date.now() + offsetMs).toISOString();
await AppTestHttpClient.get(
`/search-usagers/update-manage?since=${encodeURIComponent(since)}`,
{ context }
).expect(400);
});

it("should accept a recent lastSync with a time zone offset", async () => {
// 1 hour ago, written in UTC-03:00 (Cayenne)
const since = new Date(Date.now() - 4 * 60 * 60 * 1000)
.toISOString()
.replace("Z", "-03:00");
await AppTestHttpClient.get(
`/search-usagers/update-manage?since=${encodeURIComponent(since)}`,
{ context }
).expect(200);
});

it("should reject invalid echeance value", async () => {
await AppTestHttpClient.post("/search-usagers/search-radies", {
context,
Expand Down
Loading
Loading