-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRemoveUserFromAgency.ts
More file actions
66 lines (56 loc) · 2.14 KB
/
Copy pathRemoveUserFromAgency.ts
File metadata and controls
66 lines (56 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {
type ConnectedUser,
errors,
type WithAgencyIdAndUserId,
withAgencyIdAndUserIdSchema,
} from "shared";
import {
rejectIfEditionOfValidatorsOfAgencyWithRefersTo,
validateAgencyRights,
} from "../../connected-users/helpers/agencyRights.helper";
import { throwIfNotAgencyAdminOrBackofficeAdmin } from "../../connected-users/helpers/authorization.helper";
import type { CreateNewEvent } from "../../core/events/ports/EventBus";
import { useCaseBuilder } from "../../core/useCaseBuilder";
export type RemoveUserFromAgency = ReturnType<typeof makeRemoveUserFromAgency>;
export const makeRemoveUserFromAgency = useCaseBuilder("RemoveUserFromAgency")
.withInput<WithAgencyIdAndUserId>(withAgencyIdAndUserIdSchema)
.withCurrentUser<ConnectedUser>()
.withDeps<{ createNewEvent: CreateNewEvent }>()
.build(
async ({ currentUser, uow, inputParams: { agencyId, userId }, deps }) => {
const isUserHimself = currentUser.id === userId;
if (!isUserHimself)
throwIfNotAgencyAdminOrBackofficeAdmin(agencyId, currentUser);
const user = await uow.userRepository.getById(userId);
if (!user) throw errors.user.notFound({ userId });
const agency = await uow.agencyRepository.getById(agencyId);
if (!agency) throw errors.agency.notFound({ agencyId });
const userRight = agency.usersRights[userId];
if (!userRight)
throw errors.user.expectedRightsOnAgency({
agencyId,
userId: user.id,
});
rejectIfEditionOfValidatorsOfAgencyWithRefersTo(agency, userRight.roles);
const { [user.id]: _, ...usersRights } = agency.usersRights;
validateAgencyRights(agency.id, usersRights, agency.refersToAgencyId);
await uow.agencyRepository.update({
id: agency.id,
status: agency.status,
usersRights,
});
await uow.outboxRepository.save(
deps.createNewEvent({
topic: "ConnectedUserAgencyRightChanged",
payload: {
userId,
agencyId,
triggeredBy: {
kind: "connected-user",
userId: currentUser.id,
},
},
}),
);
},
);