• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

GrottoCenter / grottocenter-api / 25434722276

06 May 2026 12:17PM UTC coverage: 86.372% (+0.01%) from 86.36%
25434722276

push

github

dawoldo
feat(1451): french and english localizations for the message notification email

3036 of 3660 branches covered (82.95%)

Branch coverage included in aggregate %.

6350 of 7207 relevant lines covered (88.11%)

50.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.65
/api/services/NotificationService.js
1
const NameService = require('./NameService');
8✔
2
const CommonService = require('./CommonService');
8✔
3

4
const NOTIFICATION_ENTITIES = {
8✔
5
  CAVE: 'cave',
6
  COMMENT: 'comment',
7
  DESCRIPTION: 'description',
8
  DOCUMENT: 'document',
9
  ENTRANCE: 'entrance',
10
  HISTORY: 'history',
11
  LOCATION: 'location',
12
  MASSIF: 'massif',
13
  ORGANIZATION: 'organization',
14
  RIGGING: 'rigging',
15
};
16

17
const NOTIFICATION_TYPES = {
8✔
18
  CREATE: 'CREATE',
19
  DELETE: 'DELETE',
20
  PERMANENT_DELETE: 'PERMANENT_DELETE',
21
  UPDATE: 'UPDATE',
22
  VALIDATE: 'VALIDATE',
23
  RESTORE: 'RESTORE',
24
};
25

26
async function removeOlderNotifications() {
27
  const query = `DELETE
×
28
                 FROM t_notification
29
                 WHERE date_inscription < current_timestamp - interval '2 month';`;
30
  await CommonService.query(query);
×
31
}
32

33
const safeGetPropId = (prop, data) => {
8✔
34
  if (data && data[prop]) {
661✔
35
    if (data[prop] instanceof Object) {
201✔
36
      return data[prop].id;
145✔
37
    }
38
    return data[prop];
56✔
39
  }
40
  return undefined;
460✔
41
};
42

43
const sendNotificationEmail = async (
8✔
44
  entity,
45
  notificationType,
46
  notificationEntity,
47
  req,
48
  user
49
) => {
50
  // Get entity name (handle all cases)
51
  const getEntityName = (entityData) => {
36✔
52
    if (entityData.name) return entityData.name;
36✔
53
    if (entityData.names) return entityData.names[0]?.name;
28✔
54
    if (entityData.title) return entityData.title;
27✔
55
    if (entityData.titles) return entityData.titles[0]?.text;
15✔
56
    if (entityData.body) return `${entityData.body.slice(0, 50)}...`;
14✔
57
    if (entityData.descriptions) return entityData.descriptions[0].title;
13✔
58
    return '';
12✔
59
  };
60

61
  const entityName = getEntityName(entity);
36✔
62

63
  // Format action verb
64
  const actionVerbMap = {
36✔
65
    [NOTIFICATION_TYPES.CREATE]: 'created',
66
    [NOTIFICATION_TYPES.DELETE]: 'deleted',
67
    [NOTIFICATION_TYPES.PERMANENT_DELETE]: 'permanently deleted',
68
    [NOTIFICATION_TYPES.UPDATE]: 'updated',
69
    [NOTIFICATION_TYPES.VALIDATE]: 'validated',
70
    [NOTIFICATION_TYPES.RESTORE]: 'restored',
71
  };
72

73
  const actionVerb = actionVerbMap[notificationType];
36✔
74
  if (!actionVerb) {
36✔
75
    throw Error(`Unknown notification type: ${notificationType}`);
1✔
76
  }
77

78
  // Format entity Link
79
  const baseUrl = `${sails.config.custom.baseUrl}/ui/`;
35✔
80
  const relatedCaveId = safeGetPropId('cave', entity);
35✔
81
  const relatedEntranceId = safeGetPropId('entrance', entity);
35✔
82
  const relatedMassifId = safeGetPropId('massif', entity);
35✔
83

84
  const getRelatedEntityLink = () => {
35✔
85
    if (relatedCaveId) return `caves/${relatedCaveId}`;
20✔
86
    if (relatedEntranceId) return `entrances/${relatedEntranceId}`;
18✔
87
    if (relatedMassifId) return `massifs/${relatedMassifId}`;
5✔
88
    return null;
4✔
89
  };
90

91
  const directLinkEntities = {
35✔
92
    [NOTIFICATION_ENTITIES.CAVE]: `caves/${entity.id}`,
93
    [NOTIFICATION_ENTITIES.DOCUMENT]: `documents/${entity.id}`,
94
    [NOTIFICATION_ENTITIES.ENTRANCE]: `entrances/${entity.id}`,
95
    [NOTIFICATION_ENTITIES.MASSIF]: `massifs/${entity.id}`,
96
    [NOTIFICATION_ENTITIES.ORGANIZATION]: `organizations/${entity.id}`,
97
  };
98

99
  let entityLink;
100
  if (directLinkEntities[notificationEntity]) {
35✔
101
    entityLink = baseUrl + directLinkEntities[notificationEntity];
15✔
102
  } else {
103
    const relatedLink = getRelatedEntityLink();
20✔
104
    if (!relatedLink) {
20✔
105
      const entityTypeName = notificationEntity.toLowerCase();
4✔
106
      let requiredEntities;
107
      if (notificationEntity === NOTIFICATION_ENTITIES.DESCRIPTION) {
4✔
108
        requiredEntities = 'cave, entrance or massif';
1✔
109
      } else if (notificationEntity === NOTIFICATION_ENTITIES.LOCATION) {
3✔
110
        requiredEntities = 'entrance';
1✔
111
      } else {
112
        requiredEntities = 'cave or entrance';
2✔
113
      }
114
      throw Error(
4✔
115
        `Can't find related entity (${requiredEntities}) of the ${entityTypeName} with id ${entity.id}`
116
      );
117
    }
118
    entityLink = baseUrl + relatedLink;
16✔
119
  }
120

121
  await sails.helpers.sendEmail
31✔
122
    .with({
123
      allowResponse: false,
124
      emailSubject: 'Notification',
125
      i18n: req.i18n,
126
      recipientEmail: user.mail,
127
      viewName: 'notification',
128
      viewValues: {
129
        actionVerb,
130
        entityLink,
131
        entityName,
132
        entityType: notificationEntity,
133
        recipientName: user.nickname,
134
        subscriptionName: user.subscriptionName,
135
        subscriptionType: user.subscriptionType,
136
      },
137
    })
138
    .intercept('sendSESEmailError', () => {
139
      sails.log.error(
×
140
        `The email service has encountered an error while trying to notify user ${user.nickname} (id=${user.id}).`
141
      );
142
      return false;
×
143
    });
144
};
145

146
const getCountryMassifAndRegionSubscribers = async (
8✔
147
  entityCountryId,
148
  entityMassifIds,
149
  entityRegionId
150
) => {
151
  const countrySubscribers = [];
117✔
152
  const massifsSubscribers = [];
117✔
153
  const regionSubscribers = [];
117✔
154
  if (entityCountryId) {
117✔
155
    const country =
156
      await TCountry.findOne(entityCountryId).populate('subscribedCavers');
10✔
157
    if (country) {
10!
158
      countrySubscribers.push(
10✔
159
        ...country.subscribedCavers.map((caver) => ({
10✔
160
          ...caver,
161
          subscriptionName: country.nativeName,
162
          subscriptionType: 'country',
163
        }))
164
      );
165
    }
166
  }
167
  if (entityMassifIds) {
117!
168
    await Promise.all(
117✔
169
      entityMassifIds.map(async (massifId) => {
170
        const massif =
171
          await TMassif.findOne(massifId).populate('subscribedCavers');
69✔
172
        if (massif) {
69✔
173
          await NameService.setNames([massif], 'massif');
67✔
174
          massifsSubscribers.push(
67✔
175
            ...massif.subscribedCavers.map((caver) => ({
58✔
176
              ...caver,
177
              subscriptionType: 'massif',
178
              subscriptionName: massif.names[0]?.name,
179
            }))
180
          );
181
        }
182
      })
183
    );
184
  }
185
  if (entityRegionId) {
117✔
186
    const region =
187
      await TISO31662.findOne(entityRegionId).populate('subscribedCavers');
17✔
188
    if (region) {
17✔
189
      regionSubscribers.push(
3✔
190
        ...region.subscribedCavers.map((caver) => ({
×
191
          ...caver,
192
          subscriptionName: region.name,
193
          subscriptionType: 'region',
194
        }))
195
      );
196
    }
197
  }
198
  return { countrySubscribers, massifsSubscribers, regionSubscribers };
117✔
199
};
200

201
module.exports = {
8✔
202
  NOTIFICATION_ENTITIES,
203
  notifyMessageRecipient: async (req, senderId, conversationId) => {
204
    try {
4✔
205
      const sender = await TCaver.findOne({ id: senderId });
4✔
206
      if (!sender) return;
4!
207
      const query = `SELECT id_caver FROM j_participant WHERE id_conversation = $1 AND id_caver != $2`;
4✔
208
      const result = await CommonService.query(query, [
4✔
209
        conversationId,
210
        senderId,
211
      ]);
212
      if (result.rows.length === 0) return;
4!
213
      await Promise.all(
4✔
214
        result.rows.map(async (row) => {
215
          const recipient = await TCaver.findOne({ id: row.id_caver });
4✔
216
          if (!recipient || !recipient.sendMessageNotificationByEmail) return;
4!
217
          const conversationLink = '';
4✔
218
          await sails.helpers.sendEmail
4✔
219
            .with({
220
              allowResponse: false,
221
              emailSubject: 'New Message',
222
              i18n: req.i18n,
223
              recipientEmail: recipient.mail,
224
              viewName: 'new-message',
225
              viewValues: {
226
                senderNickname: sender.nickname,
227
                conversationLink,
228
                recipientName: recipient.nickname,
229
              },
230
            })
231
            .intercept('sendSESEmailError', () => {
232
              sails.log.error(
×
233
                `The email service error notifying user ${recipient.nickname}.`
234
              );
235
              return false;
×
236
            });
237
        })
238
      );
239
    } catch (error) {
240
      sails.log.error(
×
241
        `An error occurred in notifyMessageRecipient: ${error.message}`
242
      );
243
    }
244
  },
245
  NOTIFICATION_TYPES,
246
  ...(process.env.NODE_ENV === 'test' ? { sendNotificationEmail } : undefined),
8!
247

248
  /**
249
   *
250
   * @param {*} req
251
   * @param {*} entity
252
   * @param {Number} notifierId
253
   * @param {NOTIFICATION_TYPES} notificationType
254
   * @param {NOTIFICATION_ENTITIES} notificationEntity
255
   * @return {Boolean} true if everything went well, else false
256
   */
257
  notifySubscribers: async (
258
    req,
259
    entity,
260
    notifierId,
261
    notificationType,
262
    notificationEntity
263
  ) => {
264
    // Had to require in the function to avoid a circular dependency with notifySubscribers() in CaveService.createCave()
265
    // eslint-disable-next-line global-require
266
    const CaveService = require('./CaveService');
149✔
267

268
    // Check params and silently fail to avoid sending an error to the client
269
    if (!Object.values(NOTIFICATION_ENTITIES).includes(notificationEntity)) {
149✔
270
      throw new Error(`Invalid notification entity: ${notificationEntity}`);
1✔
271
    }
272
    if (!Object.values(NOTIFICATION_TYPES).includes(notificationType)) {
148✔
273
      throw new Error(`Invalid notification type: ${notificationType}`);
1✔
274
    }
275
    if (!notifierId) {
147✔
276
      throw new Error(`Missing notifier id`);
1✔
277
    }
278

279
    try {
146✔
280
      // For the populateEntities() method, must use "grotto" instead of "organization"
281
      const entityKey =
282
        notificationEntity === NOTIFICATION_ENTITIES.ORGANIZATION
146✔
283
          ? 'grotto'
284
          : notificationEntity;
285

286
      // Format notification and populate entity
287
      const notification = await module.exports.populateEntities({
146✔
288
        dateInscription: new Date(),
289
        notificationType: (
290
          await TNotificationType.findOne({
291
            name: notificationType,
292
          })
293
        ).id,
294
        notifier: notifierId,
295
        [entityKey]: entity,
296
      });
297

298
      const populatedEntity = notification[entityKey];
121✔
299

300
      const caveId = safeGetPropId('cave', populatedEntity);
121✔
301
      const entranceId = safeGetPropId('entrance', populatedEntity);
121✔
302
      const massifId = safeGetPropId('massif', populatedEntity);
121✔
303

304
      const getMassifIdsFromCave = async (id) =>
121✔
305
        (await CaveService.getMassifs(id)).map((m) => m.id);
69✔
306
      const getCountryId = (id) => safeGetPropId('country', id);
121✔
307
      const getRegionId = (entityData) => entityData?.iso_3166_2;
121✔
308

309
      const getCountryFromCaveEntrances = (cave) => {
121✔
310
        if (cave?.entrances?.length > 0) {
15✔
311
          return getCountryId(cave.entrances[0]);
5✔
312
        }
313
        return null;
10✔
314
      };
315

316
      const resolveLocationFromCaveOrEntrance = async (
121✔
317
        relatedCaveId,
318
        relatedEntranceId,
319
        entityData
320
      ) => {
321
        if (relatedCaveId) {
45✔
322
          return {
3✔
323
            countryId: getCountryFromCaveEntrances(entityData.cave),
324
            massifIds: await getMassifIdsFromCave(relatedCaveId),
325
            regionId: entityData.cave?.entrances?.[0]
3!
326
              ? getRegionId(entityData.cave.entrances[0])
327
              : null,
328
          };
329
        }
330
        if (relatedEntranceId) {
42✔
331
          return {
15✔
332
            countryId: getCountryId(entityData.entrance),
333
            massifIds: await getMassifIdsFromCave(
334
              safeGetPropId('cave', entityData.entrance)
335
            ),
336
            regionId: getRegionId(entityData.entrance),
337
          };
338
        }
339
        return { countryId: null, massifIds: [], regionId: null };
27✔
340
      };
341

342
      // Entity-specific location resolution
343
      const entityResolvers = {
121✔
344
        [NOTIFICATION_ENTITIES.CAVE]: async () => ({
12✔
345
          countryId: getCountryFromCaveEntrances(populatedEntity),
346
          massifIds: await getMassifIdsFromCave(populatedEntity.id),
347
          regionId: populatedEntity?.entrances?.[0]
12✔
348
            ? getRegionId(populatedEntity.entrances[0])
349
            : null,
350
        }),
351

352
        [NOTIFICATION_ENTITIES.ENTRANCE]: async () => ({
34✔
353
          countryId: getCountryId(populatedEntity),
354
          massifIds: populatedEntity?.cave
34✔
355
            ? await getMassifIdsFromCave(safeGetPropId('cave', populatedEntity))
356
            : [],
357
          regionId: getRegionId(populatedEntity),
358
        }),
359

360
        [NOTIFICATION_ENTITIES.MASSIF]: async () => ({
8✔
361
          countryId: null,
362
          massifIds: [populatedEntity.id],
363
          regionId: null,
364
        }),
365

366
        [NOTIFICATION_ENTITIES.ORGANIZATION]: async () => ({
13✔
367
          countryId: getCountryId(populatedEntity),
368
          massifIds: [],
369
          regionId: getRegionId(populatedEntity),
370
        }),
371

372
        [NOTIFICATION_ENTITIES.LOCATION]: async () => {
373
          if (!entranceId)
9✔
374
            throw new Error(`Can't retrieve related entrance id.`);
1✔
375
          return {
8✔
376
            countryId: getCountryId(populatedEntity.entrance),
377
            massifIds: await getMassifIdsFromCave(
378
              safeGetPropId('cave', populatedEntity.entrance)
379
            ),
380
            regionId: getRegionId(populatedEntity.entrance),
381
          };
382
        },
383
      };
384

385
      // Entities that can relate to cave, entrance, or massif
386
      const multiRelationEntities = [
121✔
387
        NOTIFICATION_ENTITIES.COMMENT,
388
        NOTIFICATION_ENTITIES.DESCRIPTION,
389
        NOTIFICATION_ENTITIES.HISTORY,
390
        NOTIFICATION_ENTITIES.RIGGING,
391
      ];
392

393
      // Find massifs and country concerned about the notification
394
      let result;
395
      if (entityResolvers[notificationEntity]) {
121✔
396
        result = await entityResolvers[notificationEntity]();
76✔
397
      } else if (multiRelationEntities.includes(notificationEntity)) {
45✔
398
        result = await resolveLocationFromCaveOrEntrance(
22✔
399
          caveId,
400
          entranceId,
401
          populatedEntity
402
        );
403

404
        // Handle massif-only case for description and document
405
        if (!result.countryId && !result.massifIds.length && massifId) {
22!
406
          result.massifIds = [safeGetPropId('massif', populatedEntity)];
×
407
        }
408

409
        // Require cave or entrance for most entities
410
        if (
22✔
411
          !caveId &&
45✔
412
          !entranceId &&
413
          ![
414
            NOTIFICATION_ENTITIES.DESCRIPTION,
415
            NOTIFICATION_ENTITIES.DOCUMENT,
416
          ].includes(notificationEntity)
417
        ) {
418
          throw new Error(`Can't retrieve related cave or entrance id.`);
3✔
419
        }
420
      } else if (notificationEntity === NOTIFICATION_ENTITIES.DOCUMENT) {
23!
421
        result = await resolveLocationFromCaveOrEntrance(
23✔
422
          caveId,
423
          entranceId,
424
          populatedEntity
425
        );
426
        if (!result.countryId && !result.massifIds.length && massifId) {
23!
427
          result.massifIds = [safeGetPropId('massif', populatedEntity)];
×
428
        }
429
      } else {
430
        throw new Error(
×
431
          `Can't find what to do with the following notification entity value: ${notificationEntity}`
432
        );
433
      }
434

435
      const entityCountryId = result.countryId;
117✔
436
      const entityMassifIds = result.massifIds;
117✔
437
      const entityRegionId = result.regionId;
117✔
438

439
      // Find subscribers to the entity.
440
      const { countrySubscribers, massifsSubscribers, regionSubscribers } =
441
        await getCountryMassifAndRegionSubscribers(
117✔
442
          entityCountryId,
443
          entityMassifIds,
444
          entityRegionId
445
        );
446
      // Consolidate subscribers by user ID and combine subscription types
447
      const subscriberMap = new Map();
117✔
448

449
      const addSubscribers = (subscribers) => {
117✔
450
        subscribers
351✔
451
          .filter((u) => u.id !== notifierId)
68✔
452
          .forEach((user) => {
453
            if (subscriberMap.has(user.id)) {
68✔
454
              const existing = subscriberMap.get(user.id);
9✔
455
              existing.subscriptionNames.push(user.subscriptionName);
9✔
456
              existing.subscriptionTypes.push(user.subscriptionType);
9✔
457
            } else {
458
              subscriberMap.set(user.id, {
59✔
459
                ...user,
460
                subscriptionNames: [user.subscriptionName],
461
                subscriptionTypes: [user.subscriptionType],
462
              });
463
            }
464
          });
465
      };
466

467
      addSubscribers(countrySubscribers);
117✔
468
      addSubscribers(massifsSubscribers);
117✔
469
      addSubscribers(regionSubscribers);
117✔
470

471
      const uniqueUsers = Array.from(subscriberMap.values()).map((user) => ({
117✔
472
        ...user,
473
        subscriptionName: user.subscriptionNames.join(' and '),
474
        subscriptionType: user.subscriptionTypes.join(', '),
475
      }));
476

477
      // Create notifications & optionally send email
478
      const res = await Promise.all(
117✔
479
        uniqueUsers.map(async (user) => {
480
          try {
59✔
481
            await TNotification.create({
59✔
482
              ...notification,
483
              notified: user.id,
484
              [entityKey]: notification[entityKey].id, // id only for the DB storage
485
            });
486
          } catch (e) {
487
            sails.log.error(
×
488
              `An error occured when trying to create a notification: ${e.message}`
489
            );
490
            return false;
×
491
          }
492

493
          if (user.sendNotificationByEmail) {
59!
494
            await sendNotificationEmail(
×
495
              populatedEntity,
496
              notificationType,
497
              notificationEntity,
498
              req,
499
              user
500
            );
501
          }
502
          return true;
59✔
503
        })
504
      );
505

506
      // 5% chance to also remove older notifications
507
      if (process.env.NODE_ENV !== 'test' && Math.random() < 0.05) {
117!
508
        try {
×
509
          await removeOlderNotifications();
×
510
        } catch (cleanupError) {
511
          sails.log.error(
×
512
            `Error during notification cleanup: ${cleanupError.message}`
513
          );
514
        }
515
      }
516

517
      return res;
117✔
518
    } catch (error) {
519
      // Fail silently to avoid sending an error to the user
520
      sails.log.error(
29✔
521
        `An error occurred when trying to notify subscribers: ${error.message} ${error.stack}`
522
      );
523
      return false;
29✔
524
    }
525
  },
526

527
  populateEntities: async (notification) => {
528
    const populatedNotification = notification;
171✔
529
    if (populatedNotification.cave) {
171✔
530
      await NameService.setNames([populatedNotification.cave], 'cave');
18✔
531
    }
532
    if (populatedNotification.comment) {
171✔
533
      populatedNotification.comment = await TComment.findOne(
10✔
534
        safeGetPropId('comment', notification)
535
      )
536
        .populate('cave')
537
        .populate('entrance');
538
    }
539
    if (populatedNotification.description) {
171✔
540
      populatedNotification.description = await TDescription.findOne(
9✔
541
        safeGetPropId('description', notification)
542
      )
543
        .populate('cave')
544
        .populate('document')
545
        .populate('entrance')
546
        .populate('massif');
547
    }
548
    if (populatedNotification.document) {
171✔
549
      // Had to require in the function to avoid a circular dependency with notifySubscribers() in DocumentService.createDocument()
550
      // eslint-disable-next-line global-require
551
      const DocumentService = require('./DocumentService');
23✔
552
      const populatedDocuments = await DocumentService.getDocuments([
23✔
553
        safeGetPropId('document', notification),
554
      ]);
555
      populatedNotification.document = populatedDocuments[0];
23✔
556
    }
557
    if (populatedNotification.entrance) {
171✔
558
      await NameService.setNames([populatedNotification.entrance], 'entrance');
50✔
559
    }
560
    if (populatedNotification.grotto) {
171✔
561
      await NameService.setNames([populatedNotification.grotto], 'grotto');
13✔
562
    }
563
    if (populatedNotification.history) {
171✔
564
      populatedNotification.history = await THistory.findOne(
5✔
565
        safeGetPropId('history', notification)
566
      )
567
        .populate('cave')
568
        .populate('entrance');
569
    }
570
    if (populatedNotification.location) {
171✔
571
      populatedNotification.location = await TLocation.findOne(
12✔
572
        safeGetPropId('location', notification)
573
      ).populate('entrance');
574
    }
575
    if (populatedNotification.massif) {
171✔
576
      await NameService.setNames([populatedNotification.massif], 'massif');
9✔
577
    }
578
    if (populatedNotification.rigging) {
171✔
579
      populatedNotification.rigging = await TRigging.findOne(
5✔
580
        safeGetPropId('rigging', notification)
581
      )
582
        .populate('entrance')
583
        .populate('cave');
584
    }
585
    return populatedNotification;
171✔
586
  },
587
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc