-
Notifications
You must be signed in to change notification settings - Fork 70
/
survey-cycle.service.ts
96 lines (86 loc) · 2.75 KB
/
survey-cycle.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
import {BindingScope, inject, injectable} from '@loopback/core';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {ILogger, LOGGER} from '@sourceloop/core';
import moment from 'moment';
import {SurveyCycle, SurveyResponder} from '../models';
import {SurveyCycleRepository} from '../repositories';
import {SurveyRepository} from '../repositories/survey.repository';
const sqlDateFormat = 'YYYY-MM-DD';
@injectable({scope: BindingScope.TRANSIENT})
export class SurveyCycleService {
constructor(
@repository(SurveyRepository)
public surveyRepository: SurveyRepository,
@repository(SurveyCycleRepository)
public surveyCycleRepository: SurveyCycleRepository,
@inject(LOGGER.LOGGER_INJECT) public logger: ILogger,
) {}
async createSurveyCycle(
surveyId: string,
surveyCycle: Omit<SurveyCycle, 'id'>,
): Promise<SurveyCycle> {
surveyCycle.surveyId = surveyId;
await this.surveyCycleRepository.create(surveyCycle);
// fetch createdSurveyCycle with id
const orderByCreatedOn = 'created_on DESC';
const createdSurveyCycle = await this.surveyCycleRepository.findOne({
order: [orderByCreatedOn],
where: {
surveyId,
},
});
if (!createdSurveyCycle) {
throw new HttpErrors.NotFound();
}
return createdSurveyCycle;
}
async validateSurveyCycle(surveyCycleId: string, surveyId: string) {
const surveyCycle = await this.surveyCycleRepository.count({
id: surveyCycleId,
surveyId,
});
if (!surveyCycle) {
throw new HttpErrors.BadRequest('Invalid surveyCycle Id');
}
}
public async checkIfResponderAddedInActiveCycle(
surveyResponder: SurveyResponder,
) {
const surveyCycle = await this.surveyCycleRepository.findById(
surveyResponder.surveyCycleId,
{
include: [
{
relation: 'survey',
scope: {
fields: {name: true, id: true, createdBy: true},
},
},
],
},
);
if (!surveyCycle?.isActivated) {
return;
}
}
async createFirstSurveyCycle(surveyId: string) {
const survey = await this.surveyRepository.findById(surveyId);
await this.surveyRepository.surveyCycles(surveyId).create({
startDate: moment(new Date(survey.startDate)).format(sqlDateFormat),
endDate: moment(new Date(survey.endDate)).format(sqlDateFormat),
extId: survey.extId,
surveyId,
isActivated: true,
});
const surveyCycle = await this.surveyCycleRepository.findOne({
where: {surveyId},
order: ['created_on DESC'],
});
return Promise.all([
this.surveyRepository
.surveyResponders(surveyId)
.patch({surveyCycleId: surveyCycle?.id}),
]);
}
}