Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help Center: add image upload for chats #96105

Open
wants to merge 7 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/data-stores/src/help-center/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ export const setIsChatLoaded = ( isChatLoaded: boolean ) =>
isChatLoaded,
} ) as const;

export const setZendeskClientId = ( zendeskClientId: string ) =>
( {
type: 'HELP_CENTER_SET_ZENDESK_CLIENT_ID',
zendeskClientId,
} ) as const;

export const setShowMessagingLauncher = ( show: boolean ) =>
( {
type: 'HELP_CENTER_SET_SHOW_MESSAGING_LAUNCHER',
Expand Down Expand Up @@ -168,6 +174,7 @@ export type HelpCenterAction =
| typeof setUnreadCount
| typeof setIsMinimized
| typeof setIsChatLoaded
| typeof setZendeskClientId
| typeof setNavigateToRoute
| typeof setOdieInitialPromptText
| typeof setOdieBotNameSlug
Expand Down
9 changes: 9 additions & 0 deletions packages/data-stores/src/help-center/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ const isChatLoaded: Reducer< boolean, HelpCenterAction > = ( state = false, acti
return state;
};

const zendeskClientId: Reducer< string, HelpCenterAction > = ( state = '', action ) => {
switch ( action.type ) {
case 'HELP_CENTER_SET_ZENDESK_CLIENT_ID':
return action.zendeskClientId;
}
return state;
};

const subject: Reducer< string | undefined, HelpCenterAction > = ( state, action ) => {
if ( action.type === 'HELP_CENTER_RESET_STORE' ) {
return undefined;
Expand Down Expand Up @@ -152,6 +160,7 @@ const reducer = combineReducers( {
hasSeenWhatsNewModal,
isMinimized,
isChatLoaded,
zendeskClientId,
unreadCount,
navigateToRoute,
odieInitialPromptText,
Expand Down
1 change: 1 addition & 0 deletions packages/data-stores/src/help-center/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const getUserDeclaredSite = ( state: State ) => state.userDeclaredSite;
export const getUnreadCount = ( state: State ) => state.unreadCount;
export const getIsMinimized = ( state: State ) => state.isMinimized;
export const getIsChatLoaded = ( state: State ) => state.isChatLoaded;
export const getZendeskClientId = ( state: State ) => state.zendeskClientId;
export const getHasSeenWhatsNewModal = ( state: State ) => state.hasSeenWhatsNewModal;
export const getNavigateToRoute = ( state: State ) => state.navigateToRoute;
export const getOdieInitialPromptText = ( state: State ) => state.odieInitialPromptText;
Expand Down
11 changes: 6 additions & 5 deletions packages/help-center/src/components/help-center-smooch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { useSelect, useDispatch as useDataStoreDispatch } from '@wordpress/data'
import { useEffect, useRef } from '@wordpress/element';
import { useChatStatus } from '../hooks';
import { HELP_CENTER_STORE } from '../stores';
import { calculateUnread } from './utils';
import { calculateUnread, getClientId } from './utils';

const HelpCenterSmooch: React.FC = () => {
const { data: authData } = useAuthenticateZendeskMessaging( true, 'messenger' );
Expand All @@ -29,7 +29,8 @@ const HelpCenterSmooch: React.FC = () => {
isHelpCenterShown && isEligibleForChat,
isEligibleForChat
);
const { setIsChatLoaded, setUnreadCount } = useDataStoreDispatch( HELP_CENTER_STORE );
const { setIsChatLoaded, setUnreadCount, setZendeskClientId } =
useDataStoreDispatch( HELP_CENTER_STORE );
const { initSmooch, destroy, getConversations, renderSmooch } = useSmooch();

// Initialize Smooch which communicates with Zendesk
Expand Down Expand Up @@ -64,10 +65,10 @@ const HelpCenterSmooch: React.FC = () => {

useEffect( () => {
if ( isChatLoaded && getConversations ) {
const { unreadConversations } = calculateUnread(
getConversations() as ZendeskConversation[]
);
const conversations = getConversations() as ZendeskConversation[];
const { unreadConversations } = calculateUnread( conversations );
setUnreadCount( unreadConversations );
setZendeskClientId( getClientId( conversations ) );
}
}, [ isChatLoaded, getConversations, setUnreadCount ] );

Expand Down
12 changes: 12 additions & 0 deletions packages/help-center/src/components/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,15 @@ export const calculateUnread = ( conversations: ZendeskConversation[] ) => {

return { unreadConversations, unreadMessages };
};

export const getClientId = ( conversations: ZendeskConversation[] ) => {
for ( const conversation of conversations ) {
const msg = conversation.messages.find(
( message ) => message.source.type === 'web' && message.source.id
);
if ( msg ) {
return msg.source.id;
}
}
return '';
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// protocols in the future, but for now, this is enough. That would REALLY simplify things for
// us, because adding a new protocol would be as simple as adding it to the array above,
// and extending the component custom-a-link.tsx to handle it. That's it.
const protocols = [ 'http', 'https', 'mailto', 'tel', 'prompt' ];
const protocols = [ 'http', 'https', 'mailto', 'tel', 'prompt', 'blob' ];

const referralCodes: { [ key: string ]: string } = {
https: 'odie',
Expand Down Expand Up @@ -34,9 +34,11 @@ export function uriTransformer( uri: string ) {
const protocol = protocols[ index ];

if ( colon === protocol.length && url.slice( 0, protocol.length ).toLowerCase() === protocol ) {
// Add referral code to the URL
const urlObj = new URL( url );
urlObj.searchParams.set( 'ref', referralCodes[ protocol ] );
// Add referral code to the URL
if ( protocol !== 'blob' ) {
urlObj.searchParams.set( 'ref', referralCodes[ protocol ] );
}
return urlObj.toString();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { HelpCenterSelect } from '@automattic/data-stores';
import { HELP_CENTER_STORE } from '@automattic/help-center/src/stores';
import {
useAttachFileToConversation,
useAuthenticateZendeskMessaging,
} from '@automattic/zendesk-client';
import { FormFileUpload, Spinner } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useCallback } from '@wordpress/element';
import { Icon, image } from '@wordpress/icons';
import React from 'react';
import { useOdieAssistantContext } from '../../context';
import { zendeskMessageConverter } from '../../utils';

const getFileType = ( file: File ) => {
if ( file.type.includes( 'image' ) ) {
return 'image';
}

return 'text';
};

const getPlaceholderAttachmentMessage = ( file: File ) => {
return zendeskMessageConverter( {
role: 'user',
type: getFileType( file ),
displayName: '',
text: '',
id: String( new Date().getTime() ),
received: new Date().getTime(),
source: { type: 'web', id: '', integrationId: '' },
mediaUrl: URL.createObjectURL( file ),
} );
};

export const AttachmentButton: React.FC = () => {
const { chat, shouldUseHelpCenterExperience, addMessage } = useOdieAssistantContext();
const { data: authData } = useAuthenticateZendeskMessaging( true, 'messenger' );
const { isPending: isAttachingFile, mutateAsync: attachFileToConversation } =
useAttachFileToConversation();
const { zendeskClientId } = useSelect( ( select ) => {
const helpCenterSelect: HelpCenterSelect = select( HELP_CENTER_STORE );
return {
zendeskClientId: helpCenterSelect.getZendeskClientId(),
};
}, [] );

const inferredClientId = chat.clientId ? chat.clientId : zendeskClientId;
const onFileUpload = useCallback(
async ( event: React.ChangeEvent< HTMLInputElement > ) => {
if (
authData &&
chat.conversationId &&
inferredClientId &&
event.currentTarget.files?.length
) {
const file = event.currentTarget.files[ 0 ];
attachFileToConversation( {
authData,
file,
conversationId: chat.conversationId,
clientId: inferredClientId,
} ).then( () => {
addMessage( getPlaceholderAttachmentMessage( file ) );
} );
}
},
[ chat.conversationId, authData ]
);

if ( ! chat.conversationId || ! inferredClientId || ! shouldUseHelpCenterExperience ) {
return null;
}

return (
<FormFileUpload accept="image/*" onChange={ onFileUpload } disabled={ isAttachingFile }>
{ isAttachingFile && <Spinner style={ { margin: 0 } } /> }
{ ! isAttachingFile && <Icon icon={ image } /> }
</FormFileUpload>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { SendMessageIcon } from '../../assets/send-message-icon';
import { useOdieAssistantContext } from '../../context';
import { useSendChatMessage } from '../../query/use-send-chat-message';
import { Message } from '../../types/';
import { AttachmentButton } from './attachment-button';
import { ResizableTextarea } from './resizable-textarea';

import './style.scss';
Expand Down Expand Up @@ -61,6 +62,7 @@ export const OdieSendMessageButton = () => {
} );
}
}, [ sendMessage, shouldBeDisabled, shouldUseHelpCenterExperience, trackEvent ] );

const classes = clsx(
'odie-send-message-inner-button',
shouldUseHelpCenterExperience && 'odie-send-message-inner-button__flag'
Expand All @@ -87,6 +89,7 @@ export const OdieSendMessageButton = () => {
keyUpHandle={ onKeyUp }
/>
{ shouldBeDisabled && <Spinner className="odie-send-message-input-spinner" /> }
<AttachmentButton />
<button type="submit" className={ classes } disabled={ shouldBeDisabled }>
{ shouldUseHelpCenterExperience ? (
<SendMessageIcon />
Expand Down
2 changes: 1 addition & 1 deletion packages/odie-client/src/context/use-load-previous-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ export const useLoadPreviousChat = ( {
chat_id: conversation.metadata[ 'odieChatId' ]
? Number( conversation.metadata[ 'odieChatId' ] )
: null,
...existingChat,
conversationId: conversation.id,
clientId: conversation.clientId,
messages: [ ...messages, ...( conversation.messages as Message[] ) ],
} );
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import { zendeskMessageConverter } from '../utils';
import type { ZendeskMessage } from '../types/';

const parseResponse = ( conversation: Conversation ) => {
let clientId;

const messages = conversation?.messages.map( ( message: ZendeskMessage ) => {
if ( message.source?.id ) {
clientId = message.source?.id;
}
return zendeskMessageConverter( message );
} );

return { ...conversation, messages };
return { ...conversation, clientId, messages };
};
/**
* Get the conversation for the Zendesk conversation.
Expand Down
1 change: 1 addition & 0 deletions packages/odie-client/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export type Message = {

export type Chat = {
conversationId?: string;
clientId?: string;
chat_id?: number | null;
wpcom_user_id?: number | null;
messages: Message[];
Expand Down
4 changes: 4 additions & 0 deletions packages/zendesk-client/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
export const SMOOCH_INTEGRATION_ID = '6453b7fc45cea5c267e60fed';
export const SMOOCH_INTEGRATION_ID_STAGING = '63d2ab28dc6b88010e60f38c';
export const SMOOCH_APP_ID = '624dbbd4e6b51f00f3e3864a';
export const SMOOCH_APP_ID_STAGING = '633dcb21690c2c00f4ca2eb8';
export const WIDGET_URL = 'https://wpcomsupport.zendesk.com';
export const WIDGET_URL_STAGING = 'https://woothemes1654197491support.zendesk.com';
export const ZENDESK_SOURCE_URL_TICKET_FIELD_ID = 23752099174548;
export const ZENDESK_SCRIPT_ID = 'ze-snippet';
export const ZENDESK_SUPPORT_CHAT_KEY = 'cec07bc9-4da6-4dd2-afa7-c7e01ae73584';
Expand Down
1 change: 1 addition & 0 deletions packages/zendesk-client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export { useSmooch } from './use-smooch';
export { useOpenZendeskMessaging } from './use-open-zendesk-messaging';
export { useZendeskMessagingAvailability } from './use-zendesk-messaging-availability';
export { useUpdateZendeskUserFields } from './use-update-zendesk-user-fields';
export { useAttachFileToConversation } from './use-attach-file';
export {
ZENDESK_SOURCE_URL_TICKET_FIELD_ID,
ZENDESK_STAGING_SUPPORT_CHAT_KEY,
Expand Down
64 changes: 64 additions & 0 deletions packages/zendesk-client/src/use-attach-file.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import config from '@automattic/calypso-config';
import { useMutation } from '@tanstack/react-query';
import apiFetch, { APIFetchOptions } from '@wordpress/api-fetch';
import {
SMOOCH_APP_ID,
SMOOCH_APP_ID_STAGING,
SMOOCH_INTEGRATION_ID,
SMOOCH_INTEGRATION_ID_STAGING,
WIDGET_URL,
WIDGET_URL_STAGING,
} from './constants';

export const useAttachFileToConversation = () => {
return useMutation( {
mutationFn: ( {
authData,
clientId,
conversationId,
file,
}: {
authData: { isLoggedIn: boolean; jwt: string; externalId: string | undefined };
clientId: string;
conversationId: string;
file: File;
} ) => {
const currentEnvironment = config( 'env_id' );
const isTestMode = currentEnvironment !== 'production';

const integrationId = isTestMode ? SMOOCH_INTEGRATION_ID_STAGING : SMOOCH_INTEGRATION_ID;
const url = isTestMode ? WIDGET_URL_STAGING : WIDGET_URL;
const appId = isTestMode ? SMOOCH_APP_ID_STAGING : SMOOCH_APP_ID;

const formData = new FormData();

formData.append(
'author',
JSON.stringify( {
role: 'appUser',
appUserId: authData.externalId,
client: {
platform: 'web',
id: clientId,
integrationId: integrationId,
},
} )
);
formData.append( 'message', JSON.stringify( {} ) );
formData.append( 'source', file );

return apiFetch( {
path: `${ url }/sc/sdk/v2/apps/${ appId }/conversations/${ conversationId }/files`,
method: 'POST',
body: formData,
credentials: 'include',
headers: {
Authorization: `Bearer ${ authData.jwt }`,
'x-smooch-appid': appId,
'x-smooch-clientid': clientId,
'x-smooch-sdk': 'web/zendesk/0.1',
},
} as APIFetchOptions );
},
} );
};
Loading