snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
71
apps/meteor/server/services/nps/getAndCreateNpsSurvey.ts
Normal file
71
apps/meteor/server/services/nps/getAndCreateNpsSurvey.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { Banner } from '@rocket.chat/core-services';
|
||||
import type { IBanner, BannerPlatform } from '@rocket.chat/core-typings';
|
||||
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
|
||||
import type * as UiKit from '@rocket.chat/ui-kit';
|
||||
|
||||
import { getWorkspaceAccessToken } from '../../lib/cloud';
|
||||
import { SystemLogger } from '../../lib/logger/system';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
type NpsSurveyData = {
|
||||
id: string;
|
||||
platform: BannerPlatform[];
|
||||
roles: string[];
|
||||
survey: UiKit.BannerView;
|
||||
createdAt: Date;
|
||||
startAt: Date;
|
||||
expireAt: Date;
|
||||
};
|
||||
|
||||
export const getAndCreateNpsSurvey = async function getNpsSurvey(npsId: string) {
|
||||
const token = await getWorkspaceAccessToken();
|
||||
if (!token) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const npsEnabled = settings.get('NPS_survey_enabled');
|
||||
|
||||
if (!npsEnabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const npsUrl = settings.get('Nps_Url');
|
||||
|
||||
try {
|
||||
const result = await fetch(`${npsUrl}/v1/surveys/${npsId}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
// SECURITY: URL can only be configured by users with enough privileges. It's ok to disable this check here.
|
||||
ignoreSsrfValidation: true,
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
SystemLogger.error({ msg: 'invalid response from the nps service:', result });
|
||||
return;
|
||||
}
|
||||
|
||||
const surveyData = (await result.json()) as NpsSurveyData;
|
||||
|
||||
const banner: IBanner = {
|
||||
_id: npsId,
|
||||
platform: surveyData.platform,
|
||||
createdAt: new Date(surveyData.createdAt),
|
||||
expireAt: new Date(surveyData.expireAt),
|
||||
startAt: new Date(surveyData.startAt),
|
||||
_updatedAt: new Date(), // Needed by the IRocketChatRecord interface
|
||||
roles: surveyData.roles,
|
||||
createdBy: {
|
||||
_id: 'rocket.cat',
|
||||
username: 'rocket.cat',
|
||||
},
|
||||
view: surveyData.survey,
|
||||
surface: 'banner',
|
||||
};
|
||||
|
||||
await Banner.create(banner);
|
||||
} catch (err) {
|
||||
SystemLogger.error({ err });
|
||||
return false;
|
||||
}
|
||||
};
|
||||
54
apps/meteor/server/services/nps/notification.ts
Normal file
54
apps/meteor/server/services/nps/notification.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { IBanner } from '@rocket.chat/core-typings';
|
||||
import { BannerPlatform } from '@rocket.chat/core-typings';
|
||||
import { Random } from '@rocket.chat/random';
|
||||
import moment from 'moment';
|
||||
|
||||
import { i18n } from '../../lib/i18n';
|
||||
import { sendMessagesToAdmins } from '../../lib/sendMessagesToAdmins';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
export const getBannerForAdmins = (expireAt: Date): Omit<IBanner, '_id'> => {
|
||||
const lng = settings.get<string>('Language') || 'en';
|
||||
|
||||
return {
|
||||
platform: [BannerPlatform.Web],
|
||||
createdAt: new Date(),
|
||||
expireAt,
|
||||
startAt: new Date(),
|
||||
roles: ['admin'],
|
||||
createdBy: {
|
||||
_id: 'rocket.cat',
|
||||
username: 'rocket.cat',
|
||||
},
|
||||
_updatedAt: new Date(),
|
||||
surface: 'banner',
|
||||
view: {
|
||||
viewId: Random.id(),
|
||||
appId: '',
|
||||
blocks: [
|
||||
{
|
||||
type: 'section',
|
||||
blockId: 'attention',
|
||||
text: {
|
||||
type: 'plain_text',
|
||||
text: i18n.t('NPS_survey_is_scheduled_to-run-at__date__for_all_users', {
|
||||
date: moment(expireAt).format('YYYY-MM-DD'),
|
||||
lng,
|
||||
}),
|
||||
emoji: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const notifyAdmins = (expireAt: Date) =>
|
||||
sendMessagesToAdmins({
|
||||
msgs: async ({ adminUser }: { adminUser: any }): Promise<any> => ({
|
||||
msg: i18n.t('NPS_survey_is_scheduled_to-run-at__date__for_all_users', {
|
||||
date: moment(expireAt).format('YYYY-MM-DD'),
|
||||
lng: adminUser.language,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
37
apps/meteor/server/services/nps/sendNpsResults.ts
Normal file
37
apps/meteor/server/services/nps/sendNpsResults.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { INpsVote } from '@rocket.chat/core-typings';
|
||||
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
|
||||
|
||||
import { getWorkspaceAccessToken } from '../../lib/cloud';
|
||||
import { SystemLogger } from '../../lib/logger/system';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
type NPSResultPayload = {
|
||||
total: number;
|
||||
votes: Pick<INpsVote, 'identifier' | 'roles' | 'score' | 'comment'>[];
|
||||
};
|
||||
|
||||
export const sendNpsResults = async function sendNpsResults(npsId: string, data: NPSResultPayload) {
|
||||
const token = await getWorkspaceAccessToken();
|
||||
if (!token) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const npsUrl = settings.get('Nps_Url');
|
||||
|
||||
try {
|
||||
return (
|
||||
await fetch(`${npsUrl}/v1/surveys/${npsId}/results`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: data,
|
||||
// SECURITY: URL can only be configured by users with enough privileges. It's ok to disable this check here.
|
||||
ignoreSsrfValidation: true,
|
||||
})
|
||||
).json();
|
||||
} catch (err) {
|
||||
SystemLogger.error({ err });
|
||||
return false;
|
||||
}
|
||||
};
|
||||
192
apps/meteor/server/services/nps/service.ts
Normal file
192
apps/meteor/server/services/nps/service.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import type { INPSService, NPSVotePayload, NPSCreatePayload } from '@rocket.chat/core-services';
|
||||
import { ServiceClassInternal, Banner, NPS, Settings } from '@rocket.chat/core-services';
|
||||
import type { INpsVote, INps } from '@rocket.chat/core-typings';
|
||||
import { NPSStatus, INpsVoteStatus } from '@rocket.chat/core-typings';
|
||||
import { Nps, NpsVote } from '@rocket.chat/models';
|
||||
|
||||
import { getBannerForAdmins, notifyAdmins } from './notification';
|
||||
import { sendNpsResults } from './sendNpsResults';
|
||||
import { SystemLogger } from '../../lib/logger/system';
|
||||
|
||||
export class NPSService extends ServiceClassInternal implements INPSService {
|
||||
protected name = 'nps';
|
||||
|
||||
async create(nps: NPSCreatePayload): Promise<boolean> {
|
||||
const npsEnabled = await Settings.get<boolean>('NPS_survey_enabled');
|
||||
if (!npsEnabled) {
|
||||
throw new Error('Server opted-out for NPS surveys');
|
||||
}
|
||||
|
||||
const any = await Nps.findOne({}, { projection: { _id: 1 } });
|
||||
if (!any) {
|
||||
if (nps.expireAt < nps.startAt || nps.expireAt < new Date()) {
|
||||
throw new Error('NPS already expired');
|
||||
}
|
||||
await Banner.create(getBannerForAdmins(nps.expireAt));
|
||||
|
||||
await notifyAdmins(nps.startAt);
|
||||
}
|
||||
|
||||
const { npsId, startAt, expireAt, createdBy } = nps;
|
||||
|
||||
try {
|
||||
await Nps.save({
|
||||
_id: npsId,
|
||||
startAt,
|
||||
expireAt,
|
||||
createdBy,
|
||||
status: NPSStatus.OPEN,
|
||||
});
|
||||
} catch (err) {
|
||||
SystemLogger.error({ msg: 'Error creating NPS', err });
|
||||
throw new Error('Error creating NPS');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async sendResults(): Promise<void> {
|
||||
const npsEnabled = await Settings.get<boolean>('NPS_survey_enabled');
|
||||
if (!npsEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const npsSending = await Nps.getOpenExpiredAlreadySending();
|
||||
|
||||
const nps = npsSending || (await Nps.getOpenExpiredAndStartSending());
|
||||
if (!nps) {
|
||||
return;
|
||||
}
|
||||
|
||||
const total = await NpsVote.countByNpsId(nps._id);
|
||||
|
||||
const votesToSend = await NpsVote.findNotSentByNpsId(nps._id).toArray();
|
||||
|
||||
// if there is nothing to sent, check if something gone wrong
|
||||
if (votesToSend.length === 0) {
|
||||
// check if still has votes left to send
|
||||
const totalSent = await NpsVote.countByNpsIdAndStatus(nps._id, INpsVoteStatus.SENT);
|
||||
if (totalSent === total) {
|
||||
await Nps.updateStatusById(nps._id, NPSStatus.SENT);
|
||||
return;
|
||||
}
|
||||
|
||||
// update old votes (sent 5 minutes ago or more) in 'sending' status back to 'new'
|
||||
await NpsVote.updateOldSendingToNewByNpsId(nps._id);
|
||||
|
||||
// try again in 5 minutes
|
||||
setTimeout(() => NPS.sendResults(), 5 * 60 * 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
const today = new Date();
|
||||
|
||||
const sending = await Promise.all(
|
||||
votesToSend.map(async (vote) => {
|
||||
const value = await NpsVote.findOneAndUpdate(
|
||||
{
|
||||
_id: vote._id,
|
||||
status: INpsVoteStatus.NEW,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
status: INpsVoteStatus.SENDING,
|
||||
sentAt: today,
|
||||
},
|
||||
},
|
||||
{
|
||||
projection: {
|
||||
identifier: 1,
|
||||
roles: 1,
|
||||
score: 1,
|
||||
comment: 1,
|
||||
},
|
||||
},
|
||||
);
|
||||
return value;
|
||||
}),
|
||||
);
|
||||
|
||||
const votes = sending.filter(Boolean) as Pick<INpsVote, '_id' | 'identifier' | 'roles' | 'score' | 'comment'>[];
|
||||
if (votes.length > 0) {
|
||||
const voteIds = votes.map(({ _id }) => _id);
|
||||
|
||||
const votesWithoutIds = votes.map(({ identifier, roles, score, comment }) => ({
|
||||
identifier,
|
||||
roles,
|
||||
score,
|
||||
comment,
|
||||
}));
|
||||
|
||||
const payload = {
|
||||
total,
|
||||
votes: votesWithoutIds,
|
||||
};
|
||||
|
||||
await sendNpsResults(nps._id, payload);
|
||||
|
||||
await NpsVote.updateVotesToSent(voteIds);
|
||||
}
|
||||
|
||||
const totalSent = await NpsVote.countByNpsIdAndStatus(nps._id, INpsVoteStatus.SENT);
|
||||
if (totalSent < total) {
|
||||
// send more in five minutes
|
||||
setTimeout(() => NPS.sendResults(), 5 * 60 * 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
await Nps.updateStatusById(nps._id, NPSStatus.SENT);
|
||||
}
|
||||
|
||||
async vote({ userId, npsId, roles, score, comment }: NPSVotePayload): Promise<void> {
|
||||
const npsEnabled = await Settings.get<boolean>('NPS_survey_enabled');
|
||||
if (!npsEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!npsId || typeof npsId !== 'string') {
|
||||
throw new Error('Invalid NPS id');
|
||||
}
|
||||
|
||||
const nps = await Nps.findOneById<Pick<INps, 'status' | 'startAt' | 'expireAt'>>(npsId, {
|
||||
projection: { status: 1, startAt: 1, expireAt: 1 },
|
||||
});
|
||||
if (!nps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nps.status !== NPSStatus.OPEN) {
|
||||
throw new Error('NPS not open for votes');
|
||||
}
|
||||
|
||||
const today = new Date();
|
||||
if (today > nps.expireAt) {
|
||||
throw new Error('NPS expired');
|
||||
}
|
||||
|
||||
if (today < nps.startAt) {
|
||||
throw new Error('NPS survey not started');
|
||||
}
|
||||
|
||||
const identifier = createHash('sha256').update(`${userId}${npsId}`).digest('hex');
|
||||
|
||||
const result = await NpsVote.save({
|
||||
ts: new Date(),
|
||||
npsId,
|
||||
identifier,
|
||||
roles,
|
||||
score,
|
||||
comment,
|
||||
status: INpsVoteStatus.NEW,
|
||||
});
|
||||
if (!result) {
|
||||
throw new Error('Error saving NPS vote');
|
||||
}
|
||||
}
|
||||
|
||||
async closeOpenSurveys(): Promise<void> {
|
||||
await Nps.closeAllByStatus(NPSStatus.OPEN);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user