-
Notifications
You must be signed in to change notification settings - Fork 3
/
gewisdb-service.ts
166 lines (144 loc) · 6.34 KB
/
gewisdb-service.ts
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of gewis-db-service.
*
* @module GEWIS/gewisdb
*/
import GewisUser from '../entity/gewis-user';
import { BasicApi, Configuration, Health, MembersApi } from 'gewisdb-ts-client';
import log4js, { getLogger, Logger } from 'log4js';
import { webResponseToUpdate } from '../helpers/gewis-helper';
import UserService from '../../service/user-service';
import { UserResponse } from '../../controller/response/user-response';
import Mailer from '../../mailer';
import MembershipExpiryNotification from '../../mailer/messages/membership-expiry-notification';
import DineroTransformer from '../../entity/transformer/dinero-transformer';
import { Language } from '../../mailer/mail-message';
import BalanceService from '../../service/balance-service';
const GEWISDB_API_URL = process.env.GEWISDB_API_URL;
const GEWISDB_API_KEY = process.env.GEWISDB_API_KEY;
// Configuration for the API access
const configuration = new Configuration({ basePath: GEWISDB_API_URL, accessToken: () => GEWISDB_API_KEY });
const api = new MembersApi(configuration);
const pinger = new BasicApi(configuration);
// Logger setup
const logger: Logger = log4js.getLogger('GewisDBService');
logger.level = process.env.LOG_LEVEL;
export default class GewisDBService {
public static api = api;
public static pinger = pinger;
/**
* Synchronizes ALL users with GEWIS DB user data.
* This method only returns users that were actually updated during the synchronization process.
* @param {boolean} commit - Whether to commit the changes to the database.
* @returns {Promise<UserResponse[]>} A promise that resolves with an array of UserResponses for users that were updated. Returns null if the API is unhealthy.
*/
public static async syncAll(commit: boolean = true): Promise<UserResponse[]> {
const gewisUsers = await GewisUser.find({ where: { user: { deleted: false } }, relations: ['user'] });
return this.sync(gewisUsers, commit);
}
/**
* Synchronizes users with GEWIS DB user data.
* This method only returns users that were actually updated during the synchronization process.
* @param {GewisUser[]} gewisUsers - Array of users to sync.
* @param {boolean} commit - Whether to commit the changes to the database.
* @returns {Promise<UserResponse[]>} A promise that resolves with an array of UserResponses for users that were updated. Returns null if the API is unhealthy.
*/
public static async sync(gewisUsers: GewisUser[], commit: boolean = true): Promise<UserResponse[]> {
let ping: Health;
try {
ping = await GewisDBService.pinger.healthGet().then(health => health.data);
} catch (error) {
logger.warn('Failed to ping GEWIS DB', error);
return null;
}
if (ping.sync_paused) {
logger.warn('GEWISDB API paused, aborting.');
return null;
}
if (!ping.healthy) {
logger.warn('GEWISDB API unhealthy, aborting.');
return null;
}
logger.info(`Syncing ${gewisUsers.length} users with GEWIS DB`);
const updates: UserResponse[] = [];
const promises = gewisUsers.map(user => GewisDBService.updateUser(user, commit).then((u: UserResponse) => {
if (u) updates.push(u);
}));
await Promise.allSettled(promises);
return updates;
}
/**
* Updates a user in the local database based on the GEWIS DB data.
* @param commit - Whether to commit the changes to the database.
* @param {GewisUser} gewisUser - The user to be updated.
*/
private static async updateUser(gewisUser: GewisUser, commit: boolean = true) {
logger.trace(`Syncing GEWIS User ${gewisUser.gewisId}`);
let dbMember;
try {
dbMember = await GewisDBService.api.membersLidnrGet(gewisUser.gewisId).then(member => member.data.data);
} catch (error) {
logger.error(`Failed to fetch: ${error}`);
return;
}
if (!dbMember) {
logger.trace(`Could not find GEWIS User ${gewisUser.gewisId} in DB.`);
return;
}
const expirationDate = new Date(dbMember.expiration);
const expired = new Date() > expirationDate;
if (expired) {
try {
logger.log(`User ${gewisUser.gewisId} has expired, closing account.`);
if (!commit) return null;
const currentBalance = await new BalanceService().getBalance(gewisUser.user.id);
const isZero = currentBalance.amount.amount === 0;
const user = await UserService.closeUser(gewisUser.user.id, isZero);
Mailer.getInstance().send(gewisUser.user, new MembershipExpiryNotification({
balance: DineroTransformer.Instance.from(currentBalance.amount.amount),
}), Language.ENGLISH, { bcc: process.env.FINANCIAL_RESPONSIBLE }).catch((e) => getLogger('User').error(e));
return user;
} catch (e) {
logger.error(e);
return null;
}
}
const update = webResponseToUpdate(dbMember);
if (GewisDBService.isUpdateNeeded(gewisUser, update)) {
logger.log(`Updated user m${gewisUser.gewisId} (id ${gewisUser.userId}) with `, update);
if (!commit) return null;
return UserService.updateUser(gewisUser.user.id, update);
}
}
/**
* Checks if the user needs an update.
* @param {GewisUser} gewisUser - The local user data.
* @param {any} update - The new data to potentially update.
* @returns {boolean} True if an update is needed, otherwise false.
*/
private static isUpdateNeeded(gewisUser: GewisUser, update: any): boolean {
return gewisUser.user.firstName !== update.firstName ||
gewisUser.user.lastName !== update.lastName ||
gewisUser.user.ofAge !== update.ofAge ||
gewisUser.user.email !== update.email;
}
}