Skip to content

Commit

Permalink
Merge branch 'develop' into fix/omni-removed-room-msg
Browse files Browse the repository at this point in the history
  • Loading branch information
kodiakhq[bot] authored Jun 22, 2023
2 parents 1b33b61 + f23e4f6 commit 88de4f8
Show file tree
Hide file tree
Showing 25 changed files with 206 additions and 86 deletions.
5 changes: 5 additions & 0 deletions .changeset/friendly-terms-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@rocket.chat/meteor": patch
---

fix: self dm is not found with `im.messages`
6 changes: 6 additions & 0 deletions .changeset/little-ligers-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@rocket.chat/meteor": patch
"@rocket.chat/model-typings": patch
---

fix: Dept w/o any BH config do not adhere to the default BH rules.
5 changes: 5 additions & 0 deletions .changeset/rare-goats-promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rocket.chat/meteor': minor
---

Fix dates translations
5 changes: 5 additions & 0 deletions .changeset/two-wasps-develop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@rocket.chat/meteor": patch
---

Fixed Business Hours behavior so they now Take seconds in consideration to assess if BH is open/closed
2 changes: 1 addition & 1 deletion apps/meteor/app/emoji/client/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const createEmojiList = (
if (!image) {
continue;
}
emojiList.push({ emoji: current, image, emojiHandle: emojiToRender });
emojiList.push({ emoji: current, image });
}
});

Expand Down
1 change: 0 additions & 1 deletion apps/meteor/app/emoji/client/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type { TranslationKey } from '@rocket.chat/ui-contexts';
export type EmojiItem = {
emoji: string;
image: string;
emojiHandle: string;
};

export type EmojiCategory = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ export const getRoomByNameOrIdWithOptionToJoin = async ({
});
}

const rid = isObject(roomUser) ? [user._id, roomUser._id].sort().join('') : nameOrId;
room = await Rooms.findOneById(rid);
room = isObject(roomUser)
? await Rooms.findOneDirectRoomContainingAllUserIDs([...new Set([user._id, roomUser._id])])
: await Rooms.findOneById(nameOrId);

// If the room hasn't been found yet, let's try some more
if (!isObject(room)) {
Expand All @@ -55,7 +56,7 @@ export const getRoomByNameOrIdWithOptionToJoin = async ({
}
}

await createDirectMessage([roomUser.username], user._id);
const { rid } = await createDirectMessage([roomUser.username], user._id);

return Rooms.findOneById(rid);
}
Expand Down
8 changes: 4 additions & 4 deletions apps/meteor/app/livechat/server/business-hour/Helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { createDefaultBusinessHourRow } from './LivechatBusinessHours';
export const filterBusinessHoursThatMustBeOpened = async (
businessHours: ILivechatBusinessHour[],
): Promise<Pick<ILivechatBusinessHour, '_id' | 'type'>[]> => {
const currentTime = moment(moment().format('dddd:HH:mm'), 'dddd:HH:mm');
const currentTime = moment(moment().format('dddd:HH:mm:ss'), 'dddd:HH:mm:ss');

return businessHours
.filter(
Expand All @@ -17,9 +17,9 @@ export const filterBusinessHoursThatMustBeOpened = async (
businessHour.workHours
.filter((hour) => hour.open)
.some((hour) => {
const localTimeStart = moment(`${hour.start.cron.dayOfWeek}:${hour.start.cron.time}`, 'dddd:HH:mm');
const localTimeFinish = moment(`${hour.finish.cron.dayOfWeek}:${hour.finish.cron.time}`, 'dddd:HH:mm');
return currentTime.isSameOrAfter(localTimeStart) && currentTime.isSameOrBefore(localTimeFinish);
const localTimeStart = moment(`${hour.start.cron.dayOfWeek}:${hour.start.cron.time}:00`, 'dddd:HH:mm:ss');
const localTimeFinish = moment(`${hour.finish.cron.dayOfWeek}:${hour.finish.cron.time}:00`, 'dddd:HH:mm:ss');
return currentTime.isSameOrAfter(localTimeStart) && currentTime.isBefore(localTimeFinish);
}),
)
.map((businessHour) => ({
Expand Down
1 change: 0 additions & 1 deletion apps/meteor/app/slashcommands-inviteall/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ function inviteAll<T extends string>(type: T): SlashCommand<T>['callback'] {
void api.broadcast('notify.ephemeralMessage', userId, message.rid, {
msg: i18n.t('Users_added', { lng }),
});
return;
} catch (e: any) {
const msg = e.error === 'cant-invite-for-direct-room' ? 'Cannot_invite_users_to_direct_rooms' : e.error;
void api.broadcast('notify.ephemeralMessage', userId, message.rid, {
Expand Down
14 changes: 2 additions & 12 deletions apps/meteor/client/components/message/toolbox/Toolbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,8 @@ const Toolbox = ({ message, messageContext, room, subscription }: ToolboxProps):
return (
<MessageToolbox>
{recentList.length > 0 &&
recentList.slice(0, 3).map(({ emoji, image, emojiHandle }) => {
return (
<EmojiElement
small
key={emoji}
title={emoji}
emoji={emoji}
image={image}
emojiHandle={emojiHandle}
onClick={() => handleSetReaction(emoji)}
/>
);
recentList.slice(0, 3).map(({ emoji, image }) => {
return <EmojiElement small key={emoji} title={emoji} emoji={emoji} image={image} onClick={() => handleSetReaction(emoji)} />;
})}
{actionsQueryResult.data?.message.map((action) => (
<MessageToolboxItem
Expand Down
3 changes: 2 additions & 1 deletion apps/meteor/client/providers/LayoutProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ const LayoutProvider: FC = ({ children }) => {
},
size: {
sidebar: '240px',
contextualBar: breakpoints.includes('sm') ? '380px' : '100%',
// eslint-disable-next-line no-nested-ternary
contextualBar: breakpoints.includes('sm') ? (breakpoints.includes('xl') ? '38%' : '380px') : '100%',
},
contextualBarExpanded: breakpoints.includes('sm'),
// eslint-disable-next-line no-nested-ternary
Expand Down
3 changes: 3 additions & 0 deletions apps/meteor/client/providers/TranslationProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ const useI18next = (lng: string): typeof i18next => {
react: {
useSuspense: true,
},
interpolation: {
escapeValue: false,
},
});
}

Expand Down
14 changes: 4 additions & 10 deletions apps/meteor/client/views/composer/EmojiPicker/EmojiCategoryRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,14 @@ const EmojiCategoryRow = ({
<>
{categoryKey === CUSTOM_CATEGORY &&
emojis.list.map(
({ emoji, image, emojiHandle }, index = 1) =>
({ emoji, image }, index = 1) =>
index < customItemsLimit && (
<EmojiElement
key={emoji + categoryKey}
emoji={emoji}
image={image}
emojiHandle={emojiHandle}
onClick={handleSelectEmoji}
/>
<EmojiElement key={emoji + categoryKey} emoji={emoji} image={image} onClick={handleSelectEmoji} />
),
)}
{!(categoryKey === CUSTOM_CATEGORY) &&
emojis.list.map(({ emoji, image, emojiHandle }) => (
<EmojiElement key={emoji + categoryKey} emoji={emoji} image={image} emojiHandle={emojiHandle} onClick={handleSelectEmoji} />
emojis.list.map(({ emoji, image }) => (
<EmojiElement key={emoji + categoryKey} emoji={emoji} image={image} onClick={handleSelectEmoji} />
))}
</>
</EmojiPickerCategoryWrapper>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ import type { MouseEvent, AllHTMLAttributes } from 'react';
import React, { memo } from 'react';

import type { EmojiItem } from '../../../../app/emoji/client';
import Emoji from '../../../components/Emoji';
import { usePreviewEmoji } from '../../../contexts/EmojiPickerContext';

type EmojiElementProps = EmojiItem & { small?: boolean; onClick: (e: MouseEvent<HTMLElement>) => void } & Omit<
AllHTMLAttributes<HTMLButtonElement>,
'is'
>;

const EmojiElement = ({ emoji, image, emojiHandle, onClick, small = false, ...props }: EmojiElementProps) => {
const EmojiElement = ({ emoji, image, onClick, small = false, ...props }: EmojiElementProps) => {
const { handlePreview, handleRemovePreview } = usePreviewEmoji();

if (!image) {
return null;
}

const emojiSmallClass = css`
> .emoji,
.emojione {
Expand All @@ -23,7 +26,7 @@ const EmojiElement = ({ emoji, image, emojiHandle, onClick, small = false, ...pr
}
`;

const emojiElement = <Emoji emojiHandle={emojiHandle} />;
const emojiElement = <div dangerouslySetInnerHTML={{ __html: image }} />;

return (
<IconButton
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ const SearchingResult = ({ searchResults, handleSelectEmoji }: SearchingResultPr
List: SearchingResultWrapper,
}}
itemContent={(index) => {
const { emoji, image, emojiHandle } = searchResults[index] || {};
return <EmojiElement emoji={emoji} image={image} emojiHandle={emojiHandle} onClick={handleSelectEmoji} />;
const { emoji, image } = searchResults[index] || {};
return <EmojiElement emoji={emoji} image={image} onClick={handleSelectEmoji} />;
}}
/>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ export const useMediaPermissions = (name: MediaDevices): [isPermissionDenied: bo
try {
if (!(await navigator.mediaDevices.enumerateDevices()).some(({ kind }) => kind === getDeviceKind(name))) {
setIsPermissionDenied(true);
return;
}
} catch (error) {
console.warn(error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,31 @@ const getAllAgentIdsWithoutDepartment = async (): Promise<string[]> => {
return agentIdsWithoutDepartment;
};

const getAllAgentIdsWithDepartmentNotConnectedToBusinessHour = async (): Promise<string[]> => {
const activeDepartmentsWithoutBusinessHour = (
await LivechatDepartment.findActiveDepartmentsWithoutBusinessHour({
projection: { _id: 1 },
}).toArray()
).map((dept) => dept._id);

const agentIdsWithDepartmentNotConnectedToBusinessHour = await LivechatDepartmentAgents.findAllAgentsConnectedToListOfDepartments(
activeDepartmentsWithoutBusinessHour,
);
return agentIdsWithDepartmentNotConnectedToBusinessHour;
};

const getAllAgentIdsForDefaultBusinessHour = async (): Promise<string[]> => {
const [withoutDepartment, withDepartmentNotConnectedToBusinessHour] = await Promise.all([
getAllAgentIdsWithoutDepartment(),
getAllAgentIdsWithDepartmentNotConnectedToBusinessHour(),
]);

return [...new Set([...withoutDepartment, ...withDepartmentNotConnectedToBusinessHour])];
};

const getAgentIdsToHandle = async (businessHour: Record<string, any>): Promise<string[]> => {
if (businessHour.type === LivechatBusinessHourTypes.DEFAULT) {
return getAllAgentIdsWithoutDepartment();
return getAllAgentIdsForDefaultBusinessHour();
}
const departmentIds = (
await LivechatDepartment.findEnabledByBusinessHourId(businessHour._id, {
Expand Down
16 changes: 8 additions & 8 deletions apps/meteor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@
"email": "[email protected]"
},
"devDependencies": {
"@babel/core": "~7.22.5",
"@babel/eslint-parser": "~7.22.5",
"@babel/plugin-proposal-nullish-coalescing-operator": "~7.18.6",
"@babel/plugin-proposal-optional-chaining": "~7.21.0",
"@babel/preset-env": "~7.22.5",
"@babel/preset-react": "~7.22.5",
"@babel/register": "~7.22.5",
"@babel/core": "^7.20.5",
"@babel/eslint-parser": "^7.19.1",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
"@babel/plugin-proposal-optional-chaining": "^7.18.9",
"@babel/preset-env": "^7.20.2",
"@babel/preset-react": "^7.18.6",
"@babel/register": "^7.18.9",
"@faker-js/faker": "~8.0.2",
"@playwright/test": "^1.22.2",
"@rocket.chat/eslint-config": "workspace:^",
Expand Down Expand Up @@ -164,7 +164,7 @@
"chai-spies": "~1.0.0",
"cross-env": "^7.0.3",
"emojione-assets": "^4.5.0",
"eslint": "~8.38.0",
"eslint": "^8.29.0",
"eslint-config-prettier": "~8.8.0",
"eslint-plugin-import": "~2.26.0",
"eslint-plugin-no-floating-promise": "~1.0.2",
Expand Down
8 changes: 8 additions & 0 deletions apps/meteor/server/models/raw/LivechatDepartment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,14 @@ export class LivechatDepartmentRaw extends BaseRaw<ILivechatDepartment> implemen
return this.find(query, options);
}

findActiveDepartmentsWithoutBusinessHour(options: FindOptions<ILivechatDepartment>): FindCursor<ILivechatDepartment> {
const query = {
enabled: true,
businessHourId: { $exists: false },
};
return this.find(query, options);
}

findEnabledByListOfBusinessHourIdsAndDepartmentIds(
businessHourIds: string[],
departmentIds: string[],
Expand Down
4 changes: 4 additions & 0 deletions apps/meteor/server/models/raw/LivechatDepartmentAgents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,10 @@ export class LivechatDepartmentAgentsRaw extends BaseRaw<ILivechatDepartmentAgen
countByDepartmentId(departmentId: string): Promise<number> {
return this.col.countDocuments({ departmentId });
}

findAllAgentsConnectedToListOfDepartments(departmentIds: string[]): Promise<string[]> {
return this.col.distinct('agentId', { departmentId: { $in: departmentIds } });
}
}

const isStringValue = (value: any): value is string => typeof value === 'string';
1 change: 0 additions & 1 deletion apps/meteor/server/startup/migrations/v273.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ addMigration({
async up() {
try {
await AppsTokens.col.dropIndex('userId_1');
return;
} catch (error: unknown) {
console.warn('Error dropping index for _raix_push_app_tokens, continuing...');
console.warn(error);
Expand Down
18 changes: 18 additions & 0 deletions apps/meteor/tests/end-to-end/api/04-direct-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,24 @@ describe('[Direct Messages]', function () {
await testFileUploads('im.files', directMessage, 'invalid-channel');
});

describe('/im.messages', () => {
it('should return all DM messages that were sent to yourself using your username', (done) => {
request
.get(api('im.messages'))
.set(credentials)
.query({
username: adminUsername,
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('messages').and.to.be.an('array');
})
.end(done);
});
});

describe('/im.messages.others', () => {
it('should fail when the endpoint is disabled', (done) => {
updateSetting('API_Enable_Direct_Message_History_EndPoint', false).then(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,5 @@ export interface ILivechatDepartmentAgentsModel extends IBaseModel<ILivechatDepa
getNextBotForDepartment(departmentId: string, ignoreAgentId?: string): Promise<{ agentId: string; username: string } | undefined>;
replaceUsernameOfAgentByUserId(userId: string, username: string): Promise<UpdateResult | Document>;
countByDepartmentId(departmentId: string): Promise<number>;
findAllAgentsConnectedToListOfDepartments(departmentIds: string[]): Promise<string[]>;
}
2 changes: 2 additions & 0 deletions packages/model-typings/src/models/ILivechatDepartmentModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export interface ILivechatDepartmentModel extends IBaseModel<ILivechatDepartment
options: FindOptions<ILivechatDepartment>,
): FindCursor<ILivechatDepartment>;

findActiveDepartmentsWithoutBusinessHour(options: FindOptions<ILivechatDepartment>): FindCursor<ILivechatDepartment>;

addBusinessHourToDepartmentsByIds(ids: string[], businessHourId: string): Promise<Document | UpdateResult>;

removeBusinessHourFromDepartmentsByIdsAndBusinessHourId(ids: string[], businessHourId: string): Promise<Document | UpdateResult>;
Expand Down
Loading

0 comments on commit 88de4f8

Please sign in to comment.