2018-08-22 17:54:48 +00:00
|
|
|
/** @format */
|
|
|
|
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import apiFetch from '@wordpress/api-fetch';
|
|
|
|
import { dispatch } from '@wordpress/data';
|
|
|
|
|
2018-11-05 21:02:04 +00:00
|
|
|
/**
|
|
|
|
* WooCommerce dependencies
|
|
|
|
*/
|
|
|
|
import { stringifyQuery } from '@woocommerce/navigation';
|
|
|
|
|
2018-08-22 17:54:48 +00:00
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
2018-11-14 21:04:59 +00:00
|
|
|
import { NAMESPACE, SWAGGERNAMESPACE } from 'store/constants';
|
2018-08-22 17:54:48 +00:00
|
|
|
|
|
|
|
export default {
|
2018-11-05 23:30:32 +00:00
|
|
|
// TODO: Use controls data plugin or fresh-data instead of async
|
|
|
|
async getReportStats( ...args ) {
|
|
|
|
// This is interim code to work with either 2.x or 3.x version of @wordpress/data
|
|
|
|
// TODO: Change to just `getNotes( endpoint, query )`
|
|
|
|
// after Gutenberg plugin uses @wordpress/data 3+
|
|
|
|
const [ endpoint, query ] = args.length === 2 ? args : args.slice( 1, 3 );
|
2018-12-18 02:26:46 +00:00
|
|
|
const statEndpoints = [ 'orders', 'revenue', 'products', 'taxes' ];
|
2018-11-05 23:30:32 +00:00
|
|
|
|
2018-08-29 15:55:56 +00:00
|
|
|
let apiPath = endpoint + stringifyQuery( query );
|
2018-08-22 17:54:48 +00:00
|
|
|
|
2018-11-14 21:04:59 +00:00
|
|
|
// TODO: Remove once swagger endpoints are phased out.
|
2018-12-21 02:13:57 +00:00
|
|
|
const swaggerEndpoints = [ 'categories' ];
|
2018-11-14 21:04:59 +00:00
|
|
|
if ( swaggerEndpoints.indexOf( endpoint ) >= 0 ) {
|
|
|
|
apiPath = SWAGGERNAMESPACE + 'reports/' + endpoint + '/stats' + stringifyQuery( query );
|
|
|
|
try {
|
|
|
|
const response = await fetch( apiPath );
|
|
|
|
|
|
|
|
const report = await response.json();
|
|
|
|
dispatch( 'wc-admin' ).setReportStats( endpoint, report, query );
|
|
|
|
} catch ( error ) {
|
|
|
|
dispatch( 'wc-admin' ).setReportStatsError( endpoint, query );
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-08-22 17:54:48 +00:00
|
|
|
if ( statEndpoints.indexOf( endpoint ) >= 0 ) {
|
|
|
|
apiPath = NAMESPACE + 'reports/' + endpoint + '/stats' + stringifyQuery( query );
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2018-09-03 15:25:38 +00:00
|
|
|
const response = await apiFetch( {
|
2018-08-22 17:54:48 +00:00
|
|
|
path: apiPath,
|
2018-09-03 15:25:38 +00:00
|
|
|
parse: false,
|
2018-08-22 17:54:48 +00:00
|
|
|
} );
|
2018-09-03 15:25:38 +00:00
|
|
|
|
|
|
|
const report = await response.json();
|
|
|
|
const totalResults = parseInt( response.headers.get( 'x-wp-total' ) );
|
|
|
|
const totalPages = parseInt( response.headers.get( 'x-wp-totalpages' ) );
|
|
|
|
dispatch( 'wc-admin' ).setReportStats( endpoint, report, query, totalResults, totalPages );
|
2018-08-22 17:54:48 +00:00
|
|
|
} catch ( error ) {
|
|
|
|
dispatch( 'wc-admin' ).setReportStatsError( endpoint, query );
|
|
|
|
}
|
|
|
|
},
|
|
|
|
};
|