woocommerce/plugins/woocommerce-admin/client/marketing/hooks/useRegisteredChannels.ts

81 lines
2.1 KiB
TypeScript
Raw Normal View History

/**
* External dependencies
*/
import { useDispatch, useSelect } from '@wordpress/data';
import { __, sprintf } from '@wordpress/i18n';
2023-01-20 18:14:36 +00:00
import { useCallback } from '@wordpress/element';
2022-12-23 13:21:52 +00:00
/**
* Internal dependencies
*/
import { InstalledChannel, SyncStatusType } from '~/marketing/types';
import { STORE_KEY } from '~/marketing/data-multichannel/constants';
import {
ApiFetchError,
Channel,
2023-01-20 18:14:36 +00:00
ChannelsState,
} from '~/marketing/data-multichannel/types';
2022-12-23 13:21:52 +00:00
type UseRegisteredChannels = {
loading: boolean;
data?: Array< InstalledChannel >;
error?: ApiFetchError;
refetch: () => void;
2022-12-23 13:21:52 +00:00
};
/**
* A object that maps the product listings status in
* plugins/woocommerce/src/Admin/Marketing/MarketingChannelInterface.php backend
* to SyncStatusType frontend.
*/
const statusMap: Record< string, SyncStatusType > = {
'sync-in-progress': 'syncing',
'sync-failed': 'failed',
synced: 'synced',
};
const convert = ( data: Channel ): InstalledChannel => {
const issueType = data.errors_count >= 1 ? 'error' : 'none';
const issueText =
data.errors_count >= 1
? sprintf(
// translators: %d: The number of issues to resolve.
__( '%d issues to resolve', 'woocommerce' ),
data.errors_count
)
: __( 'No issues to resolve', 'woocommerce' );
2022-12-08 15:53:36 +00:00
return {
slug: data.slug,
title: data.name,
description: data.description,
icon: data.icon,
isSetupCompleted: data.is_setup_completed,
setupUrl: data.settings_url,
manageUrl: data.settings_url,
syncStatus: statusMap[ data.product_listings_status ],
issueType,
issueText,
2022-12-08 15:53:36 +00:00
};
};
export const useRegisteredChannels = (): UseRegisteredChannels => {
const { invalidateResolution } = useDispatch( STORE_KEY );
const refetch = useCallback( () => {
invalidateResolution( 'getChannels' );
}, [ invalidateResolution ] );
return useSelect( ( select ) => {
const { hasFinishedResolution, getChannels } = select( STORE_KEY );
2023-01-20 18:14:36 +00:00
const channels = getChannels< ChannelsState >();
return {
loading: ! hasFinishedResolution( 'getChannels' ),
data: channels.data?.map( convert ),
error: channels.error,
refetch,
};
} );
};