Merge branch 'master' into fix/1035
This commit is contained in:
commit
250c0910a1
|
@ -23,9 +23,18 @@ import './style.scss';
|
|||
|
||||
export class Leaderboard extends Component {
|
||||
render() {
|
||||
const { getHeadersContent, getRowsContent, isRequesting, isError, items, title } = this.props;
|
||||
const {
|
||||
getHeadersContent,
|
||||
getRowsContent,
|
||||
isRequesting,
|
||||
isError,
|
||||
items,
|
||||
tableQuery,
|
||||
title,
|
||||
} = this.props;
|
||||
const data = get( items, [ 'data' ], [] );
|
||||
const rows = getRowsContent( data );
|
||||
const totalRows = tableQuery ? tableQuery.per_page : 5;
|
||||
|
||||
if ( isError ) {
|
||||
return <ReportError className="woocommerce-leaderboard" isError />;
|
||||
|
@ -47,9 +56,9 @@ export class Leaderboard extends Component {
|
|||
headers={ getHeadersContent() }
|
||||
isLoading={ isRequesting }
|
||||
rows={ rows }
|
||||
rowsPerPage={ 5 }
|
||||
rowsPerPage={ totalRows }
|
||||
title={ title }
|
||||
totalRows={ 5 }
|
||||
totalRows={ totalRows }
|
||||
/>
|
||||
);
|
||||
}
|
|
@ -68,7 +68,18 @@ export class ReportChart extends Component {
|
|||
}
|
||||
|
||||
render() {
|
||||
const { query, itemsLabel, mode, path, primaryData, secondaryData, selectedChart } = this.props;
|
||||
const {
|
||||
interactiveLegend,
|
||||
itemsLabel,
|
||||
legendPosition,
|
||||
mode,
|
||||
path,
|
||||
primaryData,
|
||||
query,
|
||||
secondaryData,
|
||||
selectedChart,
|
||||
showHeaderControls,
|
||||
} = this.props;
|
||||
|
||||
if ( primaryData.isError || secondaryData.isError ) {
|
||||
return <ReportError isError />;
|
||||
|
@ -106,23 +117,26 @@ export class ReportChart extends Component {
|
|||
|
||||
return (
|
||||
<Chart
|
||||
allowedIntervals={ allowedIntervals }
|
||||
data={ chartData }
|
||||
dateParser={ '%Y-%m-%dT%H:%M:%S' }
|
||||
interactiveLegend={ interactiveLegend }
|
||||
interval={ currentInterval }
|
||||
isRequesting={ primaryData.isRequesting || secondaryData.isRequesting }
|
||||
itemsLabel={ itemsLabel }
|
||||
legendPosition={ legendPosition }
|
||||
mode={ mode || this.getChartMode() }
|
||||
path={ path }
|
||||
query={ query }
|
||||
data={ chartData }
|
||||
showHeaderControls={ showHeaderControls }
|
||||
title={ selectedChart.label }
|
||||
interval={ currentInterval }
|
||||
type={ getChartTypeForQuery( query ) }
|
||||
allowedIntervals={ allowedIntervals }
|
||||
itemsLabel={ itemsLabel }
|
||||
mode={ mode || this.getChartMode() }
|
||||
tooltipLabelFormat={ formats.tooltipLabelFormat }
|
||||
tooltipValueFormat={ getTooltipValueFormat( selectedChart.type ) }
|
||||
tooltipTitle={ selectedChart.label }
|
||||
tooltipValueFormat={ getTooltipValueFormat( selectedChart.type ) }
|
||||
type={ getChartTypeForQuery( query ) }
|
||||
valueType={ selectedChart.type }
|
||||
xFormat={ formats.xFormat }
|
||||
x2Format={ formats.x2Format }
|
||||
dateParser={ '%Y-%m-%dT%H:%M:%S' }
|
||||
valueType={ selectedChart.type }
|
||||
isRequesting={ primaryData.isRequesting || secondaryData.isRequesting }
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -6,7 +6,7 @@ import { applyFilters } from '@wordpress/hooks';
|
|||
import { Component } from '@wordpress/element';
|
||||
import { compose } from '@wordpress/compose';
|
||||
import { withDispatch } from '@wordpress/data';
|
||||
import { get, orderBy } from 'lodash';
|
||||
import { get } from 'lodash';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
/**
|
||||
|
@ -84,15 +84,13 @@ class ReportTable extends Component {
|
|||
}
|
||||
|
||||
const isRequesting = tableData.isRequesting || primaryData.isRequesting;
|
||||
const orderedItems = orderBy( items.data, query.orderby, query.order );
|
||||
const totals = get( primaryData, [ 'data', 'totals' ], null );
|
||||
const totalResults = items.totalResults || 0;
|
||||
const { headers, ids, rows, summary } = applyFilters( TABLE_FILTER, {
|
||||
endpoint: endpoint,
|
||||
headers: getHeadersContent(),
|
||||
orderedItems: orderedItems,
|
||||
ids: itemIdField ? orderedItems.map( item => item[ itemIdField ] ) : null,
|
||||
rows: getRowsContent( orderedItems ),
|
||||
ids: itemIdField ? items.data.map( item => item[ itemIdField ] ) : null,
|
||||
rows: getRowsContent( items.data ),
|
||||
totals: totals,
|
||||
summary: getSummary ? getSummary( totals, totalResults ) : null,
|
||||
} );
|
||||
|
|
|
@ -18,7 +18,7 @@ export const charts = [
|
|||
},
|
||||
{
|
||||
key: 'net_revenue',
|
||||
label: __( 'Gross Revenue', 'wc-admin' ),
|
||||
label: __( 'Net Revenue', 'wc-admin' ),
|
||||
type: 'currency',
|
||||
},
|
||||
{
|
||||
|
|
|
@ -33,6 +33,7 @@ class CategoriesReportTable extends Component {
|
|||
label: __( 'Category', 'wc-admin' ),
|
||||
key: 'category',
|
||||
required: true,
|
||||
isSortable: true,
|
||||
isLeftAligned: true,
|
||||
},
|
||||
{
|
||||
|
@ -110,7 +111,7 @@ class CategoriesReportTable extends Component {
|
|||
value: numberFormat( totals.items_sold ),
|
||||
},
|
||||
{
|
||||
label: __( 'gross revenue', 'wc-admin' ),
|
||||
label: __( 'net revenue', 'wc-admin' ),
|
||||
value: formatCurrency( totals.net_revenue ),
|
||||
},
|
||||
{
|
||||
|
|
|
@ -10,8 +10,8 @@ import { map } from 'lodash';
|
|||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import { getIntervalForQuery, getDateFormatsForInterval } from '@woocommerce/date';
|
||||
import { Link } from '@woocommerce/components';
|
||||
import { defaultTableDateFormat } from '@woocommerce/date';
|
||||
import { formatCurrency, getCurrencyFormatDecimal } from '@woocommerce/currency';
|
||||
|
||||
/**
|
||||
|
@ -33,9 +33,10 @@ export default class CouponsReportTable extends Component {
|
|||
return [
|
||||
{
|
||||
label: __( 'Coupon Code', 'wc-admin' ),
|
||||
key: 'coupon_id',
|
||||
key: 'code',
|
||||
required: true,
|
||||
isLeftAligned: true,
|
||||
isSortable: true,
|
||||
},
|
||||
{
|
||||
label: __( 'Orders', 'wc-admin' ),
|
||||
|
@ -67,10 +68,6 @@ export default class CouponsReportTable extends Component {
|
|||
}
|
||||
|
||||
getRowsContent( coupons ) {
|
||||
const { query } = this.props;
|
||||
const currentInterval = getIntervalForQuery( query );
|
||||
const { tableFormat } = getDateFormatsForInterval( currentInterval );
|
||||
|
||||
return map( coupons, coupon => {
|
||||
const { amount, coupon_id, extended_info, orders_count } = coupon;
|
||||
const { code, date_created, date_expires, discount_type } = extended_info;
|
||||
|
@ -105,11 +102,13 @@ export default class CouponsReportTable extends Component {
|
|||
value: getCurrencyFormatDecimal( amount ),
|
||||
},
|
||||
{
|
||||
display: formatDate( tableFormat, date_created ),
|
||||
display: formatDate( defaultTableDateFormat, date_created ),
|
||||
value: date_created,
|
||||
},
|
||||
{
|
||||
display: date_expires ? formatDate( tableFormat, date_expires ) : __( 'N/A', 'wc-admin' ),
|
||||
display: date_expires
|
||||
? formatDate( defaultTableDateFormat, date_expires )
|
||||
: __( 'N/A', 'wc-admin' ),
|
||||
value: date_expires,
|
||||
},
|
||||
{
|
||||
|
|
|
@ -18,7 +18,7 @@ export const filters = [
|
|||
param: 'filter',
|
||||
showFilters: () => true,
|
||||
filters: [
|
||||
{ label: __( 'All Registered Customers', 'wc-admin' ), value: 'all' },
|
||||
{ label: __( 'All Customers', 'wc-admin' ), value: 'all' },
|
||||
{ label: __( 'Advanced Filters', 'wc-admin' ), value: 'advanced' },
|
||||
],
|
||||
},
|
||||
|
|
|
@ -19,6 +19,11 @@ import CustomersReportTable from './table';
|
|||
export default class CustomersReport extends Component {
|
||||
render() {
|
||||
const { query, path } = this.props;
|
||||
const tableQuery = {
|
||||
orderby: 'date_registered',
|
||||
order: 'desc',
|
||||
...query,
|
||||
};
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
|
@ -29,7 +34,7 @@ export default class CustomersReport extends Component {
|
|||
showDatePicker={ false }
|
||||
advancedFilters={ advancedFilters }
|
||||
/>
|
||||
<CustomersReportTable query={ query } />
|
||||
<CustomersReportTable query={ tableQuery } />
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -9,7 +9,7 @@ import { format as formatDate } from '@wordpress/date';
|
|||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import { getDateFormatsForInterval, getIntervalForQuery } from '@woocommerce/date';
|
||||
import { defaultTableDateFormat } from '@woocommerce/date';
|
||||
import { formatCurrency, getCurrencyFormatDecimal } from '@woocommerce/currency';
|
||||
import { Link } from '@woocommerce/components';
|
||||
|
||||
|
@ -43,7 +43,7 @@ export default class CustomersReportTable extends Component {
|
|||
},
|
||||
{
|
||||
label: __( 'Sign Up', 'wc-admin' ),
|
||||
key: 'date_sign_up',
|
||||
key: 'date_registered',
|
||||
defaultSort: true,
|
||||
isSortable: true,
|
||||
},
|
||||
|
@ -92,33 +92,34 @@ export default class CustomersReportTable extends Component {
|
|||
}
|
||||
|
||||
getRowsContent( customers ) {
|
||||
const { query } = this.props;
|
||||
const currentInterval = getIntervalForQuery( query );
|
||||
const formats = getDateFormatsForInterval( currentInterval );
|
||||
|
||||
return customers.map( customer => {
|
||||
const {
|
||||
avg_order_value,
|
||||
billing,
|
||||
date_last_active,
|
||||
date_sign_up,
|
||||
date_registered,
|
||||
email,
|
||||
first_name,
|
||||
id,
|
||||
last_name,
|
||||
name,
|
||||
user_id,
|
||||
orders_count,
|
||||
username,
|
||||
total_spend,
|
||||
postcode,
|
||||
city,
|
||||
country,
|
||||
} = customer;
|
||||
const { postcode, city, country } = billing || {};
|
||||
const name = `${ first_name } ${ last_name }`;
|
||||
|
||||
const customerNameLink = (
|
||||
<Link href={ 'user-edit.php?user_id=' + id } type="wp-admin">
|
||||
const customerNameLink = user_id ? (
|
||||
<Link href={ 'user-edit.php?user_id=' + user_id } type="wp-admin">
|
||||
{ name }
|
||||
</Link>
|
||||
) : (
|
||||
name
|
||||
);
|
||||
|
||||
const dateRegistered = date_registered
|
||||
? formatDate( defaultTableDateFormat, date_registered )
|
||||
: '—';
|
||||
|
||||
return [
|
||||
{
|
||||
display: customerNameLink,
|
||||
|
@ -129,8 +130,8 @@ export default class CustomersReportTable extends Component {
|
|||
value: username,
|
||||
},
|
||||
{
|
||||
display: formatDate( formats.tableFormat, date_sign_up ),
|
||||
value: date_sign_up,
|
||||
display: dateRegistered,
|
||||
value: date_registered,
|
||||
},
|
||||
{
|
||||
display: <a href={ 'mailto:' + email }>{ email }</a>,
|
||||
|
@ -149,7 +150,7 @@ export default class CustomersReportTable extends Component {
|
|||
value: getCurrencyFormatDecimal( avg_order_value ),
|
||||
},
|
||||
{
|
||||
display: formatDate( formats.tableFormat, date_last_active ),
|
||||
display: formatDate( defaultTableDateFormat, date_last_active ),
|
||||
value: date_last_active,
|
||||
},
|
||||
{
|
||||
|
@ -186,7 +187,7 @@ export default class CustomersReportTable extends Component {
|
|||
labels={ { placeholder: __( 'Search by customer name', 'wc-admin' ) } }
|
||||
searchBy="customers"
|
||||
searchParam="name_includes"
|
||||
title={ __( 'Registered Customers', 'wc-admin' ) }
|
||||
title={ __( 'Customers', 'wc-admin' ) }
|
||||
columnPrefsKey="customers_report_columns"
|
||||
/>
|
||||
);
|
||||
|
|
|
@ -12,7 +12,7 @@ import { NAMESPACE } from 'store/constants';
|
|||
|
||||
export const charts = [
|
||||
{
|
||||
key: 'downloads_count',
|
||||
key: 'download_count',
|
||||
label: __( 'Downloads', 'wc-admin' ),
|
||||
type: 'number',
|
||||
},
|
||||
|
@ -70,7 +70,7 @@ export const advancedFilters = {
|
|||
} ) ),
|
||||
},
|
||||
},
|
||||
username: {
|
||||
user: {
|
||||
labels: {
|
||||
add: __( 'Username', 'wc-admin' ),
|
||||
placeholder: __( 'Search customer username', 'wc-admin' ),
|
||||
|
@ -132,7 +132,7 @@ export const advancedFilters = {
|
|||
} ) ),
|
||||
},
|
||||
},
|
||||
downloadIp: {
|
||||
ip_address: {
|
||||
labels: {
|
||||
add: __( 'IP Address', 'wc-admin' ),
|
||||
placeholder: __( 'Search IP address', 'wc-admin' ),
|
||||
|
|
|
@ -29,7 +29,6 @@ export default class DownloadsReport extends Component {
|
|||
query={ query }
|
||||
path={ path }
|
||||
filters={ filters }
|
||||
showDatePicker={ false }
|
||||
advancedFilters={ advancedFilters }
|
||||
/>
|
||||
<ReportSummary
|
||||
|
|
|
@ -6,11 +6,12 @@ import { __, _n } from '@wordpress/i18n';
|
|||
import { Component } from '@wordpress/element';
|
||||
import { format as formatDate } from '@wordpress/date';
|
||||
import { map } from 'lodash';
|
||||
import moment from 'moment';
|
||||
|
||||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import { getIntervalForQuery, getDateFormatsForInterval } from '@woocommerce/date';
|
||||
import { defaultTableDateFormat, getCurrentDates } from '@woocommerce/date';
|
||||
import { Link } from '@woocommerce/components';
|
||||
import { getNewPath, getPersistedQuery } from '@woocommerce/navigation';
|
||||
|
||||
|
@ -41,7 +42,8 @@ export default class CouponsReportTable extends Component {
|
|||
},
|
||||
{
|
||||
label: __( 'Product Title', 'wc-admin' ),
|
||||
key: 'product_id',
|
||||
key: 'product',
|
||||
isSortable: true,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
|
@ -66,12 +68,12 @@ export default class CouponsReportTable extends Component {
|
|||
|
||||
getRowsContent( downloads ) {
|
||||
const { query } = this.props;
|
||||
const currentInterval = getIntervalForQuery( query );
|
||||
const { tableFormat } = getDateFormatsForInterval( currentInterval );
|
||||
const persistedQuery = getPersistedQuery( query );
|
||||
|
||||
return map( downloads, download => {
|
||||
const { date, file_name, ip_address, order_id, product_id, user_id } = download;
|
||||
const { _embedded, date, file_name, file_path, ip_address, order_id, product_id } = download;
|
||||
const { name: productName } = _embedded.product[ 0 ];
|
||||
const { name: userName } = _embedded.user[ 0 ];
|
||||
|
||||
const productLink = getNewPath( persistedQuery, 'products', {
|
||||
filter: 'single_product',
|
||||
|
@ -80,19 +82,23 @@ export default class CouponsReportTable extends Component {
|
|||
|
||||
return [
|
||||
{
|
||||
display: formatDate( tableFormat, date ),
|
||||
display: formatDate( defaultTableDateFormat, date ),
|
||||
value: date,
|
||||
},
|
||||
{
|
||||
display: (
|
||||
<Link href={ productLink } type="wc-admin">
|
||||
{ product_id }
|
||||
{ productName }
|
||||
</Link>
|
||||
),
|
||||
value: product_id,
|
||||
value: productName,
|
||||
},
|
||||
{
|
||||
display: file_name,
|
||||
display: (
|
||||
<Link href={ file_path } type="external">
|
||||
{ file_name }
|
||||
</Link>
|
||||
),
|
||||
value: file_name,
|
||||
},
|
||||
{
|
||||
|
@ -104,8 +110,8 @@ export default class CouponsReportTable extends Component {
|
|||
value: order_id,
|
||||
},
|
||||
{
|
||||
display: user_id,
|
||||
value: user_id,
|
||||
display: userName,
|
||||
value: userName,
|
||||
},
|
||||
{
|
||||
display: ip_address,
|
||||
|
@ -119,14 +125,20 @@ export default class CouponsReportTable extends Component {
|
|||
if ( ! totals ) {
|
||||
return [];
|
||||
}
|
||||
const { query } = this.props;
|
||||
const dates = getCurrentDates( query );
|
||||
const after = moment( dates.primary.after );
|
||||
const before = moment( dates.primary.before );
|
||||
const days = before.diff( after, 'days' ) + 1;
|
||||
|
||||
return [
|
||||
{
|
||||
label: _n( 'day', 'days', totals.days, 'wc-admin' ),
|
||||
value: numberFormat( totals.days ), // @TODO it's not defined
|
||||
label: _n( 'day', 'days', days, 'wc-admin' ),
|
||||
value: numberFormat( days ),
|
||||
},
|
||||
{
|
||||
label: _n( 'download', 'downloads', totals.downloads_count, 'wc-admin' ),
|
||||
value: numberFormat( totals.downloads_count ),
|
||||
label: _n( 'download', 'downloads', totals.download_count, 'wc-admin' ),
|
||||
value: numberFormat( totals.download_count ),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
@ -141,6 +153,9 @@ export default class CouponsReportTable extends Component {
|
|||
getRowsContent={ this.getRowsContent }
|
||||
getSummary={ this.getSummary }
|
||||
query={ query }
|
||||
tableQuery={ {
|
||||
_embed: true,
|
||||
} }
|
||||
title={ __( 'Downloads', 'wc-admin' ) }
|
||||
columnPrefsKey="downloads_report_columns"
|
||||
/>
|
||||
|
|
|
@ -11,12 +11,7 @@ import { map } from 'lodash';
|
|||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import {
|
||||
appendTimestamp,
|
||||
getCurrentDates,
|
||||
getIntervalForQuery,
|
||||
getDateFormatsForInterval,
|
||||
} from '@woocommerce/date';
|
||||
import { appendTimestamp, defaultTableDateFormat, getCurrentDates } from '@woocommerce/date';
|
||||
import { Link, OrderStatus, ViewMoreList } from '@woocommerce/components';
|
||||
import { formatCurrency } from '@woocommerce/currency';
|
||||
|
||||
|
@ -102,9 +97,6 @@ class OrdersReportTable extends Component {
|
|||
}
|
||||
|
||||
getRowsContent( tableData ) {
|
||||
const { query } = this.props;
|
||||
const currentInterval = getIntervalForQuery( query );
|
||||
const { tableFormat } = getDateFormatsForInterval( currentInterval );
|
||||
return map( tableData, row => {
|
||||
const {
|
||||
date,
|
||||
|
@ -134,7 +126,7 @@ class OrdersReportTable extends Component {
|
|||
|
||||
return [
|
||||
{
|
||||
display: formatDate( tableFormat, date ),
|
||||
display: formatDate( defaultTableDateFormat, date ),
|
||||
value: date,
|
||||
},
|
||||
{
|
||||
|
|
|
@ -36,14 +36,16 @@ class ProductsReportTable extends Component {
|
|||
return [
|
||||
{
|
||||
label: __( 'Product Title', 'wc-admin' ),
|
||||
key: 'name',
|
||||
key: 'product_name',
|
||||
required: true,
|
||||
isLeftAligned: true,
|
||||
isSortable: true,
|
||||
},
|
||||
{
|
||||
label: __( 'SKU', 'wc-admin' ),
|
||||
key: 'sku',
|
||||
hiddenByDefault: true,
|
||||
isSortable: true,
|
||||
},
|
||||
{
|
||||
label: __( 'Items Sold', 'wc-admin' ),
|
||||
|
@ -118,9 +120,11 @@ class ProductsReportTable extends Component {
|
|||
products: product_id,
|
||||
} );
|
||||
const categories = this.props.categories;
|
||||
const productCategories = category_ids
|
||||
.map( category_id => categories[ category_id ] )
|
||||
.filter( Boolean );
|
||||
|
||||
const productCategories =
|
||||
( category_ids &&
|
||||
category_ids.map( category_id => categories[ category_id ] ).filter( Boolean ) ) ||
|
||||
[];
|
||||
|
||||
return [
|
||||
{
|
||||
|
|
|
@ -11,12 +11,7 @@ import { get } from 'lodash';
|
|||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import {
|
||||
appendTimestamp,
|
||||
getCurrentDates,
|
||||
getDateFormatsForInterval,
|
||||
getIntervalForQuery,
|
||||
} from '@woocommerce/date';
|
||||
import { appendTimestamp, defaultTableDateFormat, getCurrentDates } from '@woocommerce/date';
|
||||
import { Link } from '@woocommerce/components';
|
||||
import { formatCurrency, getCurrencyFormatDecimal } from '@woocommerce/currency';
|
||||
|
||||
|
@ -100,10 +95,6 @@ class RevenueReportTable extends Component {
|
|||
}
|
||||
|
||||
getRowsContent( data = [] ) {
|
||||
const { query } = this.props;
|
||||
const currentInterval = getIntervalForQuery( query );
|
||||
const formats = getDateFormatsForInterval( currentInterval );
|
||||
|
||||
return data.map( row => {
|
||||
const {
|
||||
coupons,
|
||||
|
@ -127,7 +118,7 @@ class RevenueReportTable extends Component {
|
|||
);
|
||||
return [
|
||||
{
|
||||
display: formatDate( formats.tableFormat, row.date_start ),
|
||||
display: formatDate( defaultTableDateFormat, row.date_start ),
|
||||
value: row.date_start,
|
||||
},
|
||||
{
|
||||
|
|
|
@ -30,13 +30,15 @@ export default class StockReportTable extends Component {
|
|||
return [
|
||||
{
|
||||
label: __( 'Product / Variation', 'wc-admin' ),
|
||||
key: 'product_variation',
|
||||
key: 'title',
|
||||
required: true,
|
||||
isLeftAligned: true,
|
||||
isSortable: true,
|
||||
},
|
||||
{
|
||||
label: __( 'SKU', 'wc-admin' ),
|
||||
key: 'sku',
|
||||
isSortable: true,
|
||||
},
|
||||
{
|
||||
label: __( 'Status', 'wc-admin' ),
|
||||
|
|
|
@ -2,13 +2,15 @@
|
|||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { Component, Fragment } from '@wordpress/element';
|
||||
import { Component } from '@wordpress/element';
|
||||
import PropTypes from 'prop-types';
|
||||
import { __, sprintf } from '@wordpress/i18n';
|
||||
|
||||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import { Card } from '@woocommerce/components';
|
||||
import { getAdminLink, history } from '@woocommerce/navigation';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
|
@ -17,6 +19,16 @@ import ReportChart from 'analytics/components/report-chart';
|
|||
import './block.scss';
|
||||
|
||||
class ChartBlock extends Component {
|
||||
handleChartClick = () => {
|
||||
const { charts } = this.props;
|
||||
|
||||
if ( ! charts || ! charts.length ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
history.push( 'analytics/' + charts[ 0 ].endpoint + '?chart=' + charts[ 0 ].key );
|
||||
};
|
||||
|
||||
render() {
|
||||
const { charts, endpoint, path, query } = this.props;
|
||||
|
||||
|
@ -25,18 +37,36 @@ class ChartBlock extends Component {
|
|||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<div
|
||||
role="presentation"
|
||||
className="woocommerce-dashboard__chart-block-wrapper"
|
||||
onClick={ this.handleChartClick }
|
||||
>
|
||||
<Card className="woocommerce-dashboard__chart-block" title={ charts[ 0 ].label }>
|
||||
<a
|
||||
className="screen-reader-text"
|
||||
href={ getAdminLink(
|
||||
'admin.php?page=wc-admin#/analytics/' +
|
||||
charts[ 0 ].endpoint +
|
||||
'?chart=' +
|
||||
charts[ 0 ].key
|
||||
) }
|
||||
>
|
||||
{ /* translators: %s is the chart type */
|
||||
sprintf( __( '%s Report', 'wc-admin' ), charts[ 0 ].label ) }
|
||||
</a>
|
||||
<ReportChart
|
||||
charts={ charts }
|
||||
endpoint={ endpoint }
|
||||
mode="block"
|
||||
path={ path }
|
||||
query={ query }
|
||||
interactiveLegend={ false }
|
||||
legendPosition="bottom"
|
||||
path={ path }
|
||||
selectedChart={ charts[ 0 ] }
|
||||
showHeaderControls={ false }
|
||||
/>
|
||||
</Card>
|
||||
</Fragment>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,31 @@
|
|||
/** @format */
|
||||
|
||||
.woocommerce-dashboard__chart-block-wrapper {
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
.woocommerce-chart,
|
||||
.woocommerce-card__header {
|
||||
background: #f8f9f9;
|
||||
}
|
||||
.woocommerce-legend__item button {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
.woocommerce-chart__footer {
|
||||
position: relative;
|
||||
&:after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
left: 0;
|
||||
top: 0;
|
||||
cursor: pointer;
|
||||
z-index: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.woocommerce-dashboard__chart-block {
|
||||
.woocommerce-card__body {
|
||||
padding: 0;
|
||||
|
@ -34,4 +60,22 @@
|
|||
&:hover {
|
||||
background: $core-grey-light-100;
|
||||
}
|
||||
|
||||
.screen-reader-text:focus {
|
||||
clip: auto;
|
||||
clip-path: none;
|
||||
z-index: 1;
|
||||
left: 6px;
|
||||
top: 7px;
|
||||
height: auto;
|
||||
width: auto;
|
||||
display: block;
|
||||
@include font-size( 14 );
|
||||
font-weight: 600;
|
||||
padding: 15px 23px 14px;
|
||||
background: #f1f1f1;
|
||||
color: #0073aa;
|
||||
text-decoration: none;
|
||||
box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,19 +21,11 @@ const allCharts = ordersCharts
|
|||
);
|
||||
|
||||
// Need to remove duplicate charts, by key, from the configs
|
||||
const uniqCharts = allCharts.reduce( ( a, b ) => {
|
||||
export const uniqCharts = allCharts.reduce( ( a, b ) => {
|
||||
if ( a.findIndex( d => d.key === b.key ) < 0 ) {
|
||||
a.push( b );
|
||||
}
|
||||
return a;
|
||||
}, [] );
|
||||
|
||||
// Default charts.
|
||||
// TODO: Implement user-based toggling/persistence.
|
||||
const defaultCharts = [ 'items_sold', 'gross_revenue' ];
|
||||
|
||||
export const showCharts = uniqCharts.map( d => ( {
|
||||
...d,
|
||||
show: defaultCharts.indexOf( d.key ) >= 0,
|
||||
} ) );
|
||||
export const getChartFromKey = key => allCharts.filter( d => d.key === key );
|
||||
|
|
|
@ -4,59 +4,99 @@
|
|||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import classNames from 'classnames';
|
||||
import Gridicon from 'gridicons';
|
||||
import { ToggleControl, IconButton, NavigableMenu } from '@wordpress/components';
|
||||
import { Component, Fragment } from '@wordpress/element';
|
||||
import { compose } from '@wordpress/compose';
|
||||
import Gridicon from 'gridicons';
|
||||
import { isEqual, xor } from 'lodash';
|
||||
import PropTypes from 'prop-types';
|
||||
import { ToggleControl, IconButton, NavigableMenu, SelectControl } from '@wordpress/components';
|
||||
import { withDispatch } from '@wordpress/data';
|
||||
|
||||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import { EllipsisMenu, MenuItem, SectionHeader } from '@woocommerce/components';
|
||||
import { getAllowedIntervalsForQuery } from '@woocommerce/date';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import ChartBlock from './block';
|
||||
import { getChartFromKey, showCharts } from './config';
|
||||
import { getChartFromKey, uniqCharts } from './config';
|
||||
import withSelect from 'wc-api/with-select';
|
||||
import './style.scss';
|
||||
|
||||
class DashboardCharts extends Component {
|
||||
constructor( props ) {
|
||||
super( ...arguments );
|
||||
this.state = {
|
||||
showCharts,
|
||||
query: props.query,
|
||||
chartType: props.userPrefChartType || 'line',
|
||||
hiddenChartKeys: props.userPrefCharts || [],
|
||||
interval: props.userPrefIntervals || 'day',
|
||||
};
|
||||
|
||||
this.toggle = this.toggle.bind( this );
|
||||
}
|
||||
|
||||
componentDidUpdate( {
|
||||
userPrefCharts: prevUserPrefCharts,
|
||||
userPrefChartType: prevUserPrefChartType,
|
||||
userPrefChartInterval: prevUserPrefChartInterval,
|
||||
} ) {
|
||||
const { userPrefCharts, userPrefChartInterval, userPrefChartType } = this.props;
|
||||
if ( userPrefCharts && ! isEqual( userPrefCharts, prevUserPrefCharts ) ) {
|
||||
/* eslint-disable react/no-did-update-set-state */
|
||||
this.setState( {
|
||||
hiddenChartKeys: userPrefCharts,
|
||||
} );
|
||||
/* eslint-enable react/no-did-update-set-state */
|
||||
}
|
||||
if ( userPrefChartType && userPrefChartType !== prevUserPrefChartType ) {
|
||||
/* eslint-disable react/no-did-update-set-state */
|
||||
this.setState( {
|
||||
chartType: userPrefChartType,
|
||||
} );
|
||||
/* eslint-enable react/no-did-update-set-state */
|
||||
}
|
||||
if ( userPrefChartInterval !== prevUserPrefChartInterval ) {
|
||||
/* eslint-disable react/no-did-update-set-state */
|
||||
this.setState( {
|
||||
interval: userPrefChartInterval,
|
||||
} );
|
||||
/* eslint-enable react/no-did-update-set-state */
|
||||
}
|
||||
}
|
||||
|
||||
toggle( key ) {
|
||||
return () => {
|
||||
this.setState( state => {
|
||||
const foundIndex = state.showCharts.findIndex( x => x.key === key );
|
||||
state.showCharts[ foundIndex ].show = ! state.showCharts[ foundIndex ].show;
|
||||
return state;
|
||||
} );
|
||||
const hiddenChartKeys = xor( this.state.hiddenChartKeys, [ key ] );
|
||||
this.setState( { hiddenChartKeys } );
|
||||
const userDataFields = {
|
||||
[ 'dashboard_charts' ]: hiddenChartKeys,
|
||||
};
|
||||
this.props.updateCurrentUserData( userDataFields );
|
||||
};
|
||||
}
|
||||
|
||||
handleTypeToggle( type ) {
|
||||
return () => {
|
||||
this.setState( state => ( { query: { ...state.query, type } } ) );
|
||||
this.setState( { chartType: type } );
|
||||
const userDataFields = {
|
||||
[ 'dashboard_chart_type' ]: type,
|
||||
};
|
||||
this.props.updateCurrentUserData( userDataFields );
|
||||
};
|
||||
}
|
||||
|
||||
renderMenu() {
|
||||
return (
|
||||
<EllipsisMenu label={ __( 'Choose which charts to display', 'wc-admin' ) }>
|
||||
{ this.state.showCharts.map( chart => {
|
||||
{ uniqCharts.map( chart => {
|
||||
return (
|
||||
<MenuItem onInvoke={ this.toggle( chart.key ) } key={ chart.key }>
|
||||
<ToggleControl
|
||||
label={ __( `${ chart.label }`, 'wc-admin' ) }
|
||||
checked={ chart.show }
|
||||
checked={ ! this.state.hiddenChartKeys.includes( chart.key ) }
|
||||
onChange={ this.toggle( chart.key ) }
|
||||
/>
|
||||
</MenuItem>
|
||||
|
@ -66,13 +106,56 @@ class DashboardCharts extends Component {
|
|||
);
|
||||
}
|
||||
|
||||
renderIntervalSelector() {
|
||||
const allowedIntervals = getAllowedIntervalsForQuery( this.props.query );
|
||||
if ( ! allowedIntervals || allowedIntervals.length < 1 ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const intervalLabels = {
|
||||
hour: __( 'By hour', 'wc-admin' ),
|
||||
day: __( 'By day', 'wc-admin' ),
|
||||
week: __( 'By week', 'wc-admin' ),
|
||||
month: __( 'By month', 'wc-admin' ),
|
||||
quarter: __( 'By quarter', 'wc-admin' ),
|
||||
year: __( 'By year', 'wc-admin' ),
|
||||
};
|
||||
|
||||
return (
|
||||
<SelectControl
|
||||
className="woocommerce-chart__interval-select"
|
||||
value={ this.state.interval }
|
||||
options={ allowedIntervals.map( allowedInterval => ( {
|
||||
value: allowedInterval,
|
||||
label: intervalLabels[ allowedInterval ],
|
||||
} ) ) }
|
||||
onChange={ this.setInterval }
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
setInterval = interval => {
|
||||
this.setState( { interval }, () => {
|
||||
const userDataFields = {
|
||||
[ 'dashboard_chart_interval' ]: this.state.interval,
|
||||
};
|
||||
this.props.updateCurrentUserData( userDataFields );
|
||||
} );
|
||||
};
|
||||
|
||||
render() {
|
||||
const { path } = this.props;
|
||||
const { query } = this.state;
|
||||
const { chartType, hiddenChartKeys, interval } = this.state;
|
||||
const query = { ...this.props.query, type: chartType, interval };
|
||||
return (
|
||||
<Fragment>
|
||||
<div className="woocommerce-dashboard__dashboard-charts">
|
||||
<SectionHeader title={ __( 'Charts', 'wc-admin' ) } menu={ this.renderMenu() }>
|
||||
<SectionHeader
|
||||
title={ __( 'Charts', 'wc-admin' ) }
|
||||
menu={ this.renderMenu() }
|
||||
className={ 'has-interval-select' }
|
||||
>
|
||||
{ this.renderIntervalSelector() }
|
||||
<NavigableMenu
|
||||
className="woocommerce-chart__types"
|
||||
orientation="horizontal"
|
||||
|
@ -103,16 +186,15 @@ class DashboardCharts extends Component {
|
|||
</NavigableMenu>
|
||||
</SectionHeader>
|
||||
<div className="woocommerce-dashboard__columns">
|
||||
{ this.state.showCharts.map( chart => {
|
||||
return ! chart.show ? null : (
|
||||
<div key={ chart.key }>
|
||||
<ChartBlock
|
||||
charts={ getChartFromKey( chart.key ) }
|
||||
endpoint={ chart.endpoint }
|
||||
path={ path }
|
||||
query={ query }
|
||||
/>
|
||||
</div>
|
||||
{ uniqCharts.map( chart => {
|
||||
return hiddenChartKeys.includes( chart.key ) ? null : (
|
||||
<ChartBlock
|
||||
charts={ getChartFromKey( chart.key ) }
|
||||
endpoint={ chart.endpoint }
|
||||
key={ chart.key }
|
||||
path={ path }
|
||||
query={ query }
|
||||
/>
|
||||
);
|
||||
} ) }
|
||||
</div>
|
||||
|
@ -127,4 +209,22 @@ DashboardCharts.propTypes = {
|
|||
query: PropTypes.object.isRequired,
|
||||
};
|
||||
|
||||
export default DashboardCharts;
|
||||
export default compose(
|
||||
withSelect( select => {
|
||||
const { getCurrentUserData } = select( 'wc-api' );
|
||||
const userData = getCurrentUserData();
|
||||
|
||||
return {
|
||||
userPrefCharts: userData.dashboard_charts,
|
||||
userPrefChartType: userData.dashboard_chart_type,
|
||||
userPrefChartInterval: userData.dashboard_chart_interval,
|
||||
};
|
||||
} ),
|
||||
withDispatch( dispatch => {
|
||||
const { updateCurrentUserData } = dispatch( 'wc-api' );
|
||||
|
||||
return {
|
||||
updateCurrentUserData,
|
||||
};
|
||||
} )
|
||||
)( DashboardCharts );
|
||||
|
|
|
@ -9,11 +9,11 @@ import { Component, Fragment } from '@wordpress/element';
|
|||
* Internal dependencies
|
||||
*/
|
||||
import './style.scss';
|
||||
import Header from 'header';
|
||||
import StorePerformance from './store-performance';
|
||||
import TopSellingProducts from './top-selling-products';
|
||||
import DashboardCharts from './dashboard-charts';
|
||||
import Header from 'header';
|
||||
import Leaderboards from './leaderboards';
|
||||
import { ReportFilters } from '@woocommerce/components';
|
||||
import StorePerformance from './store-performance';
|
||||
|
||||
export default class Dashboard extends Component {
|
||||
render() {
|
||||
|
@ -23,11 +23,7 @@ export default class Dashboard extends Component {
|
|||
<Header sections={ [ __( 'Dashboard', 'wc-admin' ) ] } />
|
||||
<ReportFilters query={ query } path={ path } />
|
||||
<StorePerformance />
|
||||
<div className="woocommerce-dashboard__columns">
|
||||
<div>
|
||||
<TopSellingProducts query={ query } />
|
||||
</div>
|
||||
</div>
|
||||
<Leaderboards query={ query } />
|
||||
<DashboardCharts query={ query } path={ path } />
|
||||
</Fragment>
|
||||
);
|
||||
|
|
|
@ -0,0 +1,165 @@
|
|||
/** @format */
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { Component, Fragment } from '@wordpress/element';
|
||||
import { compose } from '@wordpress/compose';
|
||||
import { isEqual, xor } from 'lodash';
|
||||
import PropTypes from 'prop-types';
|
||||
import { SelectControl, ToggleControl } from '@wordpress/components';
|
||||
import { withDispatch } from '@wordpress/data';
|
||||
|
||||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import { EllipsisMenu, MenuItem, MenuTitle, SectionHeader } from '@woocommerce/components';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import withSelect from 'wc-api/with-select';
|
||||
import TopSellingProducts from './top-selling-products';
|
||||
import './style.scss';
|
||||
|
||||
class Leaderboards extends Component {
|
||||
constructor( props ) {
|
||||
super( ...arguments );
|
||||
this.state = {
|
||||
hiddenLeaderboardKeys: props.userPrefLeaderboards || [],
|
||||
rowsPerTable: props.userPrefLeaderboardRows || 5,
|
||||
};
|
||||
|
||||
this.toggle = this.toggle.bind( this );
|
||||
}
|
||||
|
||||
componentDidUpdate( {
|
||||
userPrefLeaderboardRows: prevUserPrefLeaderboardRows,
|
||||
userPrefLeaderboards: prevUserPrefLeaderboards,
|
||||
} ) {
|
||||
const { userPrefLeaderboardRows, userPrefLeaderboards } = this.props;
|
||||
if ( userPrefLeaderboards && ! isEqual( userPrefLeaderboards, prevUserPrefLeaderboards ) ) {
|
||||
/* eslint-disable react/no-did-update-set-state */
|
||||
this.setState( {
|
||||
hiddenLeaderboardKeys: userPrefLeaderboards,
|
||||
} );
|
||||
/* eslint-enable react/no-did-update-set-state */
|
||||
}
|
||||
if (
|
||||
userPrefLeaderboardRows &&
|
||||
parseInt( userPrefLeaderboardRows ) !== parseInt( prevUserPrefLeaderboardRows )
|
||||
) {
|
||||
/* eslint-disable react/no-did-update-set-state */
|
||||
this.setState( {
|
||||
rowsPerTable: parseInt( userPrefLeaderboardRows ),
|
||||
} );
|
||||
/* eslint-enable react/no-did-update-set-state */
|
||||
}
|
||||
}
|
||||
|
||||
toggle( key ) {
|
||||
return () => {
|
||||
const hiddenLeaderboardKeys = xor( this.state.hiddenLeaderboardKeys, [ key ] );
|
||||
this.setState( { hiddenLeaderboardKeys } );
|
||||
const userDataFields = {
|
||||
[ 'dashboard_leaderboards' ]: hiddenLeaderboardKeys,
|
||||
};
|
||||
this.props.updateCurrentUserData( userDataFields );
|
||||
};
|
||||
}
|
||||
|
||||
setRowsPerTable = rows => {
|
||||
this.setState( { rowsPerTable: parseInt( rows ) } );
|
||||
const userDataFields = {
|
||||
[ 'dashboard_leaderboard_rows' ]: parseInt( rows ),
|
||||
};
|
||||
this.props.updateCurrentUserData( userDataFields );
|
||||
};
|
||||
|
||||
renderMenu() {
|
||||
const { hiddenLeaderboardKeys, rowsPerTable } = this.state;
|
||||
const allLeaderboards = [
|
||||
{
|
||||
key: 'top-products',
|
||||
label: __( 'Top Products', 'wc-admin' ),
|
||||
},
|
||||
{
|
||||
key: 'top-categories',
|
||||
label: __( 'Top Categories', 'wc-admin' ),
|
||||
},
|
||||
{
|
||||
key: 'top-coupons',
|
||||
label: __( 'Top Coupons', 'wc-admin' ),
|
||||
},
|
||||
];
|
||||
return (
|
||||
<EllipsisMenu label={ __( 'Choose which leaderboards to display', 'wc-admin' ) }>
|
||||
<Fragment>
|
||||
<MenuTitle>{ __( 'Leaderboards', 'wc-admin' ) }</MenuTitle>
|
||||
{ allLeaderboards.map( leaderboard => {
|
||||
return (
|
||||
<MenuItem onInvoke={ this.toggle( leaderboard.key ) } key={ leaderboard.key }>
|
||||
<ToggleControl
|
||||
label={ leaderboard.label }
|
||||
checked={ ! hiddenLeaderboardKeys.includes( leaderboard.key ) }
|
||||
onChange={ this.toggle( leaderboard.key ) }
|
||||
/>
|
||||
</MenuItem>
|
||||
);
|
||||
} ) }
|
||||
<MenuTitle>{ __( 'Rows Per Table', 'wc-admin' ) }</MenuTitle>
|
||||
<SelectControl
|
||||
className="woocommerce-ellipsis-menu__item"
|
||||
value={ rowsPerTable }
|
||||
options={ Array.from( { length: 20 }, ( v, key ) => ( {
|
||||
v: key + 1,
|
||||
label: key + 1,
|
||||
} ) ) }
|
||||
onChange={ this.setRowsPerTable }
|
||||
/>
|
||||
</Fragment>
|
||||
</EllipsisMenu>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const { hiddenLeaderboardKeys, rowsPerTable } = this.state;
|
||||
return (
|
||||
<Fragment>
|
||||
<div className="woocommerce-dashboard__dashboard-leaderboards">
|
||||
<SectionHeader title={ __( 'Leaderboards', 'wc-admin' ) } menu={ this.renderMenu() } />
|
||||
<div className="woocommerce-dashboard__columns">
|
||||
<div>
|
||||
{ ! hiddenLeaderboardKeys.includes( 'top-products' ) && (
|
||||
<TopSellingProducts query={ this.props.query } totalRows={ rowsPerTable } />
|
||||
) }
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Leaderboards.propTypes = {
|
||||
query: PropTypes.object.isRequired,
|
||||
};
|
||||
|
||||
export default compose(
|
||||
withSelect( select => {
|
||||
const { getCurrentUserData } = select( 'wc-api' );
|
||||
const userData = getCurrentUserData();
|
||||
|
||||
return {
|
||||
userPrefLeaderboards: userData.dashboard_leaderboards,
|
||||
userPrefLeaderboardRows: userData.dashboard_leaderboard_rows,
|
||||
};
|
||||
} ),
|
||||
withDispatch( dispatch => {
|
||||
const { updateCurrentUserData } = dispatch( 'wc-api' );
|
||||
|
||||
return {
|
||||
updateCurrentUserData,
|
||||
};
|
||||
} )
|
||||
)( Leaderboards );
|
|
@ -0,0 +1,11 @@
|
|||
/** @format */
|
||||
|
||||
.woocommerce-dashboard__dashboard-leaderboards {
|
||||
.components-base-control__field {
|
||||
width: 100%;
|
||||
}
|
||||
.components-select-control__input {
|
||||
border: 1px solid $core-grey-light-700;
|
||||
height: 34px;
|
||||
}
|
||||
}
|
|
@ -16,7 +16,7 @@ import { getAdminLink } from '@woocommerce/navigation';
|
|||
* Internal dependencies
|
||||
*/
|
||||
import { numberFormat } from 'lib/number';
|
||||
import Leaderboard from 'dashboard/leaderboard';
|
||||
import Leaderboard from 'analytics/components/leaderboard';
|
||||
|
||||
export class TopSellingProducts extends Component {
|
||||
constructor( props ) {
|
||||
|
@ -88,10 +88,11 @@ export class TopSellingProducts extends Component {
|
|||
}
|
||||
|
||||
render() {
|
||||
const { query, totalRows } = this.props;
|
||||
const tableQuery = {
|
||||
orderby: 'items_sold',
|
||||
order: 'desc',
|
||||
per_page: 5, //TODO replace with user configured leaderboard per page value.
|
||||
per_page: totalRows,
|
||||
extended_info: true,
|
||||
};
|
||||
|
||||
|
@ -100,7 +101,7 @@ export class TopSellingProducts extends Component {
|
|||
endpoint="products"
|
||||
getHeadersContent={ this.getHeadersContent }
|
||||
getRowsContent={ this.getRowsContent }
|
||||
query={ this.props.query }
|
||||
query={ query }
|
||||
tableQuery={ tableQuery }
|
||||
title={ __( 'Top Selling Products', 'wc-admin' ) }
|
||||
/>
|
|
@ -2,11 +2,11 @@
|
|||
|
||||
.woocommerce-dashboard__columns {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-columns: calc(50% - #{$gap-large/2}) calc(50% - #{$gap-large/2});
|
||||
grid-column-gap: $gap-large;
|
||||
|
||||
@include breakpoint( '<960px' ) {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-columns: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
import classnames from 'classnames';
|
||||
import { cloneElement, Component } from '@wordpress/element';
|
||||
import Gridicon from 'gridicons';
|
||||
import { moment } from '@wordpress/date';
|
||||
import moment from 'moment';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
/**
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
import { Button } from '@wordpress/components';
|
||||
import Gridicon from 'gridicons';
|
||||
import { shallow } from 'enzyme';
|
||||
import moment from 'moment';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
|
@ -54,8 +55,7 @@ describe( 'ActivityCard', () => {
|
|||
|
||||
test( 'should render a timestamp on a card', () => {
|
||||
// We're generating this via moment to ensure it's always "3 days ago".
|
||||
const threeDaysAgo = wp.date
|
||||
.moment()
|
||||
const threeDaysAgo = moment()
|
||||
.subtract( 3, 'days' )
|
||||
.format();
|
||||
const card = shallow(
|
||||
|
|
|
@ -327,7 +327,7 @@ describe( 'getSummaryNumbers()', () => {
|
|||
} );
|
||||
|
||||
setGetReportStats( ( endpoint, _query ) => {
|
||||
if ( '2018-10-10T00:00:00' === _query.after ) {
|
||||
if ( '2018-10-10T00:00:00+00:00' === _query.after ) {
|
||||
return {
|
||||
data: {
|
||||
totals: totals.primary,
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
* External dependencies
|
||||
*/
|
||||
import { find, forEach, isNull } from 'lodash';
|
||||
import moment from 'moment';
|
||||
|
||||
/**
|
||||
* WooCommerce dependencies
|
||||
|
@ -18,19 +19,21 @@ import { formatCurrency } from '@woocommerce/currency';
|
|||
import { MAX_PER_PAGE, QUERY_DEFAULTS } from 'store/constants';
|
||||
import * as categoriesConfig from 'analytics/report/categories/config';
|
||||
import * as couponsConfig from 'analytics/report/coupons/config';
|
||||
import * as customersConfig from 'analytics/report/customers/config';
|
||||
import * as downloadsConfig from 'analytics/report/downloads/config';
|
||||
import * as ordersConfig from 'analytics/report/orders/config';
|
||||
import * as productsConfig from 'analytics/report/products/config';
|
||||
import * as taxesConfig from 'analytics/report/taxes/config';
|
||||
import * as customersConfig from 'analytics/report/customers/config';
|
||||
import * as reportsUtils from './utils';
|
||||
|
||||
const reportConfigs = {
|
||||
categories: categoriesConfig,
|
||||
coupons: couponsConfig,
|
||||
customers: customersConfig,
|
||||
downloads: downloadsConfig,
|
||||
orders: ordersConfig,
|
||||
products: productsConfig,
|
||||
taxes: taxesConfig,
|
||||
customers: customersConfig,
|
||||
};
|
||||
|
||||
export function getFilterQuery( endpoint, query ) {
|
||||
|
@ -119,15 +122,18 @@ export function isReportDataEmpty( report ) {
|
|||
* @returns {Object} data request query parameters.
|
||||
*/
|
||||
function getRequestQuery( endpoint, dataType, query ) {
|
||||
const datesFromQuery = getCurrentDates( query, 'YYYY-MM-DDTHH:00:00' );
|
||||
const datesFromQuery = getCurrentDates( query );
|
||||
const interval = getIntervalForQuery( query );
|
||||
const filterQuery = getFilterQuery( endpoint, query );
|
||||
const end = datesFromQuery[ dataType ].before;
|
||||
const endingTimeOfDay = end.isSame( moment(), 'day' ) ? 'now' : 'end';
|
||||
|
||||
return {
|
||||
order: 'asc',
|
||||
interval,
|
||||
per_page: MAX_PER_PAGE,
|
||||
after: datesFromQuery[ dataType ].after,
|
||||
before: datesFromQuery[ dataType ].before,
|
||||
after: appendTimestamp( datesFromQuery[ dataType ].after, 'start' ),
|
||||
before: appendTimestamp( end, endingTimeOfDay ),
|
||||
...filterQuery,
|
||||
};
|
||||
}
|
||||
|
|
|
@ -17,6 +17,7 @@ $gap-smallest: 4px;
|
|||
$spacing: 16px;
|
||||
|
||||
// Gutenberg Button variables. These are temporary until Gutenberg's variables are exposed.
|
||||
$border-width: 1px;
|
||||
$default-font-size: 13px;
|
||||
$blue-medium-200: #bfe7f3;
|
||||
$light-gray-500: $core-grey-light-500;
|
||||
|
|
|
@ -14,10 +14,6 @@ import { stringifyQuery } from '@woocommerce/navigation';
|
|||
*/
|
||||
import { getResourceIdentifier, getResourcePrefix } from '../../utils';
|
||||
import { NAMESPACE } from '../../constants';
|
||||
import { SWAGGERNAMESPACE } from 'store/constants';
|
||||
|
||||
// TODO: Remove once swagger endpoints are phased out.
|
||||
const swaggerEndpoints = [ 'customers', 'downloads' ];
|
||||
|
||||
const typeEndpointMap = {
|
||||
'report-items-query-orders': 'orders',
|
||||
|
@ -42,17 +38,11 @@ function read( resourceNames, fetch = apiFetch ) {
|
|||
const prefix = getResourcePrefix( resourceName );
|
||||
const endpoint = typeEndpointMap[ prefix ];
|
||||
const query = getResourceIdentifier( resourceName );
|
||||
|
||||
const fetchArgs = {
|
||||
parse: false,
|
||||
path: NAMESPACE + '/reports/' + endpoint + stringifyQuery( query ),
|
||||
};
|
||||
|
||||
if ( swaggerEndpoints.indexOf( endpoint ) >= 0 ) {
|
||||
fetchArgs.url = SWAGGERNAMESPACE + 'reports/' + endpoint + stringifyQuery( query );
|
||||
} else {
|
||||
fetchArgs.path = NAMESPACE + '/reports/' + endpoint + stringifyQuery( query );
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch( fetchArgs );
|
||||
const report = await response.json();
|
||||
|
|
|
@ -16,9 +16,9 @@ import { getResourceIdentifier, getResourcePrefix } from '../../utils';
|
|||
import { NAMESPACE } from '../../constants';
|
||||
import { SWAGGERNAMESPACE } from 'store/constants';
|
||||
|
||||
const statEndpoints = [ 'orders', 'revenue', 'products', 'taxes', 'coupons' ];
|
||||
const statEndpoints = [ 'coupons', 'downloads', 'orders', 'products', 'revenue', 'taxes' ];
|
||||
// TODO: Remove once swagger endpoints are phased out.
|
||||
const swaggerEndpoints = [ 'categories', 'downloads' ];
|
||||
const swaggerEndpoints = [ 'categories' ];
|
||||
|
||||
const typeEndpointMap = {
|
||||
'report-stats-query-orders': 'orders',
|
||||
|
|
|
@ -40,6 +40,11 @@ function updateCurrentUserData( resourceNames, data, fetch ) {
|
|||
'revenue_report_columns',
|
||||
'taxes_report_columns',
|
||||
'variations_report_columns',
|
||||
'dashboard_charts',
|
||||
'dashboard_chart_type',
|
||||
'dashboard_chart_interval',
|
||||
'dashboard_leaderboards',
|
||||
'dashboard_leaderboard_rows',
|
||||
];
|
||||
|
||||
if ( resourceNames.includes( resourceName ) ) {
|
||||
|
|
|
@ -20,6 +20,14 @@ Filters available for that report.
|
|||
|
||||
Label describing the legend items.
|
||||
|
||||
### `mode`
|
||||
|
||||
- Type: String
|
||||
- Default: null
|
||||
|
||||
`items-comparison` (default) or `time-comparison`, this is used to generate correct
|
||||
ARIA properties.
|
||||
|
||||
### `path`
|
||||
|
||||
- **Required**
|
||||
|
|
|
@ -20,7 +20,10 @@ Properties of all the charts available for that report.
|
|||
- Type: String
|
||||
- Default: null
|
||||
|
||||
The endpoint to use in API calls.
|
||||
The endpoint to use in API calls to populate the Summary Numbers.
|
||||
For example, if `taxes` is provided, data will be fetched from the report
|
||||
`taxes` endpoint (ie: `/wc/v3/reports/taxes/stats`). If the provided endpoint
|
||||
doesn't exist, an error will be shown to the user with `ReportError`.
|
||||
|
||||
### `query`
|
||||
|
||||
|
|
|
@ -18,7 +18,11 @@ The key for user preferences settings for column visibility.
|
|||
- Type: String
|
||||
- Default: null
|
||||
|
||||
The endpoint to use in API calls.
|
||||
The endpoint to use in API calls to populate the table rows and summary.
|
||||
For example, if `taxes` is provided, data will be fetched from the report
|
||||
`taxes` endpoint (ie: `/wc/v3/reports/taxes` and `/wc/v3/reports/taxes/stats`).
|
||||
If the provided endpoint doesn't exist, an error will be shown to the user
|
||||
with `ReportError`.
|
||||
|
||||
### `extendItemsMethodNames`
|
||||
|
||||
|
|
|
@ -85,7 +85,7 @@ A number formatting string, passed to d3Format.
|
|||
|
||||
### `mode`
|
||||
|
||||
- Type: One of: 'item-comparison', 'time-comparison'
|
||||
- Type: One of: 'block', 'item-comparison', 'time-comparison'
|
||||
- Default: `'time-comparison'`
|
||||
|
||||
`item-comparison` (default) or `time-comparison`, this is used to generate correct
|
||||
|
|
|
@ -24,7 +24,7 @@ Function called when selected results change, passed result list.
|
|||
### `type`
|
||||
|
||||
- **Required**
|
||||
- Type: One of: 'countries', 'coupons', 'customers', 'emails', 'orders', 'products', 'product_cats', 'taxes', 'usernames', 'variations'
|
||||
- Type: One of: 'categories', 'countries', 'coupons', 'customers', 'downloadIps', 'emails', 'orders', 'products', 'taxes', 'usernames', 'variations'
|
||||
- Default: null
|
||||
|
||||
The object type to be used in searching.
|
||||
|
|
|
@ -73,6 +73,10 @@ class WC_Admin_REST_Reports_Controller extends WC_REST_Reports_Controller {
|
|||
public function get_items( $request ) {
|
||||
$data = array();
|
||||
$reports = array(
|
||||
array(
|
||||
'slug' => 'performance-indicators',
|
||||
'description' => __( 'Batch endpoint for getting specific performance indicators from `stats` endpoints.', 'wc-admin' ),
|
||||
),
|
||||
array(
|
||||
'slug' => 'revenue/stats',
|
||||
'description' => __( 'Stats about revenue.', 'wc-admin' ),
|
||||
|
|
|
@ -262,6 +262,7 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
|
|||
'default' => 'coupon_id',
|
||||
'enum' => array(
|
||||
'coupon_id',
|
||||
'code',
|
||||
'amount',
|
||||
'orders_count',
|
||||
),
|
||||
|
|
|
@ -38,26 +38,33 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
* @return array
|
||||
*/
|
||||
protected function prepare_reports_query( $request ) {
|
||||
$args = array();
|
||||
$args['before'] = $request['before'];
|
||||
$args['after'] = $request['after'];
|
||||
$args['page'] = $request['page'];
|
||||
$args['per_page'] = $request['per_page'];
|
||||
$args['name'] = $request['name'];
|
||||
$args['username'] = $request['username'];
|
||||
$args['email'] = $request['email'];
|
||||
$args['country'] = $request['country'];
|
||||
$args['last_active_before'] = $request['last_active_before'];
|
||||
$args['last_active_after'] = $request['last_active_after'];
|
||||
$args['order_count_min'] = $request['order_count_min'];
|
||||
$args['order_count_max'] = $request['order_count_max'];
|
||||
$args['order_count_between'] = $request['order_count_between'];
|
||||
$args['total_spend_min'] = $request['total_spend_min'];
|
||||
$args['total_spend_max'] = $request['total_spend_max'];
|
||||
$args['total_spend_between'] = $request['total_spend_between'];
|
||||
$args['avg_order_value_min'] = $request['avg_order_value_min'];
|
||||
$args['avg_order_value_max'] = $request['avg_order_value_max'];
|
||||
$args['avg_order_value_between'] = $request['avg_order_value_between'];
|
||||
$args = array();
|
||||
$args['registered_before'] = $request['registered_before'];
|
||||
$args['registered_after'] = $request['registered_after'];
|
||||
$args['page'] = $request['page'];
|
||||
$args['per_page'] = $request['per_page'];
|
||||
$args['order'] = $request['order'];
|
||||
$args['orderby'] = $request['orderby'];
|
||||
$args['match'] = $request['match'];
|
||||
$args['name'] = $request['name'];
|
||||
$args['username'] = $request['username'];
|
||||
$args['email'] = $request['email'];
|
||||
$args['country'] = $request['country'];
|
||||
$args['last_active_before'] = $request['last_active_before'];
|
||||
$args['last_active_after'] = $request['last_active_after'];
|
||||
$args['orders_count_min'] = $request['orders_count_min'];
|
||||
$args['orders_count_max'] = $request['orders_count_max'];
|
||||
$args['total_spend_min'] = $request['total_spend_min'];
|
||||
$args['total_spend_max'] = $request['total_spend_max'];
|
||||
$args['avg_order_value_min'] = $request['avg_order_value_min'];
|
||||
$args['avg_order_value_max'] = $request['avg_order_value_max'];
|
||||
$args['last_order_before'] = $request['last_order_before'];
|
||||
$args['last_order_after'] = $request['last_order_after'];
|
||||
|
||||
$between_params = array( 'orders_count', 'total_spend', 'avg_order_value' );
|
||||
$normalized = WC_Admin_Reports_Interval::normalize_between_params( $request, $between_params );
|
||||
$args = array_merge( $args, $normalized );
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
|
@ -69,19 +76,20 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
*/
|
||||
public function get_items( $request ) {
|
||||
$query_args = $this->prepare_reports_query( $request );
|
||||
$customers_query = new WC_Reports_Orders_Stats_Query( $query_args ); // @todo change to correct class.
|
||||
$customers_query = new WC_Admin_Reports_Customers_Query( $query_args );
|
||||
$report_data = $customers_query->get_data();
|
||||
$out_data = array(
|
||||
'totals' => get_object_vars( $report_data->totals ),
|
||||
'customers' => array(),
|
||||
);
|
||||
foreach ( $report_data->customers as $customer_data ) {
|
||||
$item_data = $this->prepare_item_for_response( (object) $customer_data, $request );
|
||||
$out_data['customers'][] = $item_data;
|
||||
|
||||
$data = array();
|
||||
|
||||
foreach ( $report_data->data as $customer_data ) {
|
||||
$item = $this->prepare_item_for_response( $customer_data, $request );
|
||||
$data[] = $this->prepare_response_for_collection( $item );
|
||||
}
|
||||
$response = rest_ensure_response( $out_data );
|
||||
|
||||
$response = rest_ensure_response( $data );
|
||||
$response->header( 'X-WP-Total', (int) $report_data->total );
|
||||
$response->header( 'X-WP-TotalPages', (int) $report_data->pages );
|
||||
|
||||
$page = $report_data->page_no;
|
||||
$max_pages = $report_data->pages;
|
||||
$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
|
||||
|
@ -98,21 +106,26 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
$next_link = add_query_arg( 'page', $next_page, $base );
|
||||
$response->link_header( 'next', $next_link );
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a report object for serialization.
|
||||
*
|
||||
* @param stdClass $report Report data.
|
||||
* @param array $report Report data.
|
||||
* @param WP_REST_Request $request Request object.
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function prepare_item_for_response( $report, $request ) {
|
||||
$data = get_object_vars( $report );
|
||||
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
|
||||
$data = $this->add_additional_fields_to_object( $data, $request );
|
||||
$data = $this->filter_response_by_context( $data, $context );
|
||||
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
|
||||
$data = $this->add_additional_fields_to_object( $report, $request );
|
||||
$data['date_registered_gmt'] = wc_rest_prepare_date_response( $data['date_registered'] );
|
||||
$data['date_registered'] = wc_rest_prepare_date_response( $data['date_registered'], false );
|
||||
$data['date_last_active_gmt'] = wc_rest_prepare_date_response( $data['date_last_active'] );
|
||||
$data['date_last_active'] = wc_rest_prepare_date_response( $data['date_last_active'], false );
|
||||
$data = $this->filter_response_by_context( $data, $context );
|
||||
|
||||
// Wrap the data in a response object.
|
||||
$response = rest_ensure_response( $data );
|
||||
$response->add_links( $this->prepare_links( $report ) );
|
||||
|
@ -131,16 +144,19 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
/**
|
||||
* Prepare links for the request.
|
||||
*
|
||||
* @param WC_Reports_Query $object Object data.
|
||||
* @param array $object Object data.
|
||||
* @return array
|
||||
*/
|
||||
protected function prepare_links( $object ) {
|
||||
$links = array(
|
||||
if ( empty( $object['user_id'] ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array(
|
||||
'customer' => array(
|
||||
'href' => rest_url( sprintf( '/%s/customers/%d', $this->namespace, $object->customer_id ) ),
|
||||
'href' => rest_url( sprintf( '/%s/customers/%d', $this->namespace, $object['user_id'] ) ),
|
||||
),
|
||||
);
|
||||
return $links;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -154,18 +170,60 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
'title' => 'report_customers',
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'id' => array(
|
||||
'description' => __( 'ID.', 'wc-admin' ),
|
||||
'customer_id' => array(
|
||||
'description' => __( 'Customer ID.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'customer_id' => array(
|
||||
'description' => __( 'Customer ID.', 'wc-admin' ),
|
||||
'user_id' => array(
|
||||
'description' => __( 'User ID.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'name' => array(
|
||||
'description' => __( 'Name.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'username' => array(
|
||||
'description' => __( 'Username.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'country' => array(
|
||||
'description' => __( 'Country.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'city' => array(
|
||||
'description' => __( 'City.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'postcode' => array(
|
||||
'description' => __( 'Postal code.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_registered' => array(
|
||||
'description' => __( 'Date registered.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_registered_gmt' => array(
|
||||
'description' => __( 'Date registered GMT.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_last_active' => array(
|
||||
'description' => __( 'Date last active.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
|
@ -209,14 +267,14 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
public function get_collection_params() {
|
||||
$params = array();
|
||||
$params['context'] = $this->get_context_param( array( 'default' => 'view' ) );
|
||||
$params['before'] = array(
|
||||
'description' => __( 'Limit response to resources published before a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
$params['registered_before'] = array(
|
||||
'description' => __( 'Limit response to objects registered before (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['after'] = array(
|
||||
'description' => __( 'Limit response to resources published after a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
$params['registered_after'] = array(
|
||||
'description' => __( 'Limit response to objects registered after (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
|
@ -238,7 +296,42 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['name'] = array(
|
||||
$params['order'] = array(
|
||||
'description' => __( 'Order sort attribute ascending or descending.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'desc',
|
||||
'enum' => array( 'asc', 'desc' ),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['orderby'] = array(
|
||||
'description' => __( 'Sort collection by object attribute.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'date_registered',
|
||||
'enum' => array(
|
||||
'username',
|
||||
'name',
|
||||
'country',
|
||||
'city',
|
||||
'postcode',
|
||||
'date_registered',
|
||||
'date_last_active',
|
||||
'orders_count',
|
||||
'total_spend',
|
||||
'avg_order_value',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['match'] = array(
|
||||
'description' => __( 'Indicates whether all the conditions should be true for the resulting set, or if any one of them is sufficient. Match affects the following parameters: status_is, status_is_not, product_includes, product_excludes, coupon_includes, coupon_excludes, customer, categories', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'all',
|
||||
'enum' => array(
|
||||
'all',
|
||||
'any',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['name'] = array(
|
||||
'description' => __( 'Limit response to objects with a specfic customer name.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
|
@ -270,22 +363,34 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['order_count_min'] = array(
|
||||
$params['registered_before'] = array(
|
||||
'description' => __( 'Limit response to objects registered before (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['registered_after'] = array(
|
||||
'description' => __( 'Limit response to objects registered after (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['orders_count_min'] = array(
|
||||
'description' => __( 'Limit response to objects with an order count greater than or equal to given integer.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['order_count_max'] = array(
|
||||
$params['orders_count_max'] = array(
|
||||
'description' => __( 'Limit response to objects with an order count less than or equal to given integer.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['order_count_between'] = array(
|
||||
$params['orders_count_between'] = array(
|
||||
'description' => __( 'Limit response to objects with an order count between two given integers.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'validate_callback' => array( 'WC_Admin_Reports_Interval', 'rest_validate_between_arg' ),
|
||||
);
|
||||
$params['total_spend_min'] = array(
|
||||
'description' => __( 'Limit response to objects with a total order spend greater than or equal to given number.', 'wc-admin' ),
|
||||
|
@ -300,7 +405,7 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
$params['total_spend_between'] = array(
|
||||
'description' => __( 'Limit response to objects with a total order spend between two given numbers.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'validate_callback' => array( 'WC_Admin_Reports_Interval', 'rest_validate_between_arg' ),
|
||||
);
|
||||
$params['avg_order_value_min'] = array(
|
||||
'description' => __( 'Limit response to objects with an average order spend greater than or equal to given number.', 'wc-admin' ),
|
||||
|
@ -315,6 +420,18 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
$params['avg_order_value_between'] = array(
|
||||
'description' => __( 'Limit response to objects with an average order spend between two given numbers.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'validate_callback' => array( 'WC_Admin_Reports_Interval', 'rest_validate_between_arg' ),
|
||||
);
|
||||
$params['last_order_before'] = array(
|
||||
'description' => __( 'Limit response to objects with last order before (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['last_order_after'] = array(
|
||||
'description' => __( 'Limit response to objects with last order after (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
return $params;
|
||||
|
|
|
@ -107,8 +107,10 @@ class WC_Admin_REST_Reports_Downloads_Controller extends WC_REST_Reports_Control
|
|||
$product_id = intval( $data['product_id'] );
|
||||
$_product = wc_get_product( $product_id );
|
||||
$file_path = $_product->get_file_download_path( $data['download_id'] );
|
||||
|
||||
$filename = basename( $file_path );
|
||||
$response->data['file_name'] = apply_filters( 'woocommerce_file_download_filename', $filename, $product_id );
|
||||
$response->data['file_path'] = $file_path;
|
||||
|
||||
/**
|
||||
* Filter a report returned from the API.
|
||||
|
@ -190,6 +192,12 @@ class WC_Admin_REST_Reports_Downloads_Controller extends WC_REST_Reports_Control
|
|||
'context' => array( 'view', 'edit' ),
|
||||
'description' => __( 'File name.', 'wc-admin' ),
|
||||
),
|
||||
'file_path' => array(
|
||||
'type' => 'string',
|
||||
'readonly' => true,
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'description' => __( 'File URL.', 'wc-admin' ),
|
||||
),
|
||||
'product_id' => array(
|
||||
'type' => 'integer',
|
||||
'readonly' => true,
|
||||
|
@ -270,6 +278,7 @@ class WC_Admin_REST_Reports_Downloads_Controller extends WC_REST_Reports_Control
|
|||
'default' => 'date',
|
||||
'enum' => array(
|
||||
'date',
|
||||
'product',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
|
@ -292,7 +301,6 @@ class WC_Admin_REST_Reports_Downloads_Controller extends WC_REST_Reports_Control
|
|||
'default' => array(),
|
||||
'sanitize_callback' => 'wp_parse_id_list',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
|
||||
);
|
||||
$params['product_excludes'] = array(
|
||||
'description' => __( 'Limit result set to items that don\'t have the specified product(s) assigned.', 'wc-admin' ),
|
||||
|
|
|
@ -30,4 +30,340 @@ class WC_Admin_REST_Reports_Downloads_Stats_Controller extends WC_REST_Reports_C
|
|||
* @var string
|
||||
*/
|
||||
protected $rest_base = 'reports/downloads/stats';
|
||||
|
||||
/**
|
||||
* Maps query arguments from the REST request.
|
||||
*
|
||||
* @param array $request Request array.
|
||||
* @return array
|
||||
*/
|
||||
protected function prepare_reports_query( $request ) {
|
||||
$args = array();
|
||||
$args['before'] = $request['before'];
|
||||
$args['after'] = $request['after'];
|
||||
$args['interval'] = $request['interval'];
|
||||
$args['page'] = $request['page'];
|
||||
$args['per_page'] = $request['per_page'];
|
||||
$args['orderby'] = $request['orderby'];
|
||||
$args['order'] = $request['order'];
|
||||
$args['match'] = $request['match'];
|
||||
$args['product_includes'] = (array) $request['product_includes'];
|
||||
$args['product_excludes'] = (array) $request['product_excludes'];
|
||||
$args['order_includes'] = (array) $request['order_includes'];
|
||||
$args['order_excludes'] = (array) $request['order_excludes'];
|
||||
$args['ip_address_includes'] = (array) $request['ip_address_includes'];
|
||||
$args['ip_address_excludes'] = (array) $request['ip_address_excludes'];
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all reports.
|
||||
*
|
||||
* @param WP_REST_Request $request Request data.
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
public function get_items( $request ) {
|
||||
$query_args = $this->prepare_reports_query( $request );
|
||||
$downloads_query = new WC_Admin_Reports_Downloads_Stats_Query( $query_args );
|
||||
$report_data = $downloads_query->get_data();
|
||||
|
||||
$out_data = array(
|
||||
'totals' => get_object_vars( $report_data->totals ),
|
||||
'intervals' => array(),
|
||||
);
|
||||
|
||||
foreach ( $report_data->intervals as $interval_data ) {
|
||||
$item = $this->prepare_item_for_response( $interval_data, $request );
|
||||
$out_data['intervals'][] = $this->prepare_response_for_collection( $item );
|
||||
}
|
||||
|
||||
$response = rest_ensure_response( $out_data );
|
||||
$response->header( 'X-WP-Total', (int) $report_data->total );
|
||||
$response->header( 'X-WP-TotalPages', (int) $report_data->pages );
|
||||
|
||||
$page = $report_data->page_no;
|
||||
$max_pages = $report_data->pages;
|
||||
$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
|
||||
if ( $page > 1 ) {
|
||||
$prev_page = $page - 1;
|
||||
if ( $prev_page > $max_pages ) {
|
||||
$prev_page = $max_pages;
|
||||
}
|
||||
$prev_link = add_query_arg( 'page', $prev_page, $base );
|
||||
$response->link_header( 'prev', $prev_link );
|
||||
}
|
||||
if ( $max_pages > $page ) {
|
||||
$next_page = $page + 1;
|
||||
$next_link = add_query_arg( 'page', $next_page, $base );
|
||||
$response->link_header( 'next', $next_link );
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a report object for serialization.
|
||||
*
|
||||
* @param Array $report Report data.
|
||||
* @param WP_REST_Request $request Request object.
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function prepare_item_for_response( $report, $request ) {
|
||||
$data = $report;
|
||||
|
||||
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
|
||||
$data = $this->add_additional_fields_to_object( $data, $request );
|
||||
$data = $this->filter_response_by_context( $data, $context );
|
||||
|
||||
// Wrap the data in a response object.
|
||||
$response = rest_ensure_response( $data );
|
||||
|
||||
/**
|
||||
* Filter a report returned from the API.
|
||||
*
|
||||
* Allows modification of the report data right before it is returned.
|
||||
*
|
||||
* @param WP_REST_Response $response The response object.
|
||||
* @param object $report The original report object.
|
||||
* @param WP_REST_Request $request Request used to generate the response.
|
||||
*/
|
||||
return apply_filters( 'woocommerce_rest_prepare_report_downloads_stats', $response, $report, $request );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Report's schema, conforming to JSON Schema.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_item_schema() {
|
||||
$totals = array(
|
||||
'download_count' => array(
|
||||
'description' => __( 'Number of downloads.', 'wc-admin' ),
|
||||
'type' => 'number',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
);
|
||||
|
||||
$schema = array(
|
||||
'$schema' => 'http://json-schema.org/draft-04/schema#',
|
||||
'title' => 'report_orders_stats',
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'totals' => array(
|
||||
'description' => __( 'Totals data.', 'wc-admin' ),
|
||||
'type' => 'object',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
'properties' => $totals,
|
||||
),
|
||||
'intervals' => array(
|
||||
'description' => __( 'Reports data grouped by intervals.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
'items' => array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'interval' => array(
|
||||
'description' => __( 'Type of interval.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
'enum' => array( 'day', 'week', 'month', 'year' ),
|
||||
),
|
||||
'date_start' => array(
|
||||
'description' => __( "The date the report start, in the site's timezone.", 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_start_gmt' => array(
|
||||
'description' => __( 'The date the report start, as GMT.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_end' => array(
|
||||
'description' => __( "The date the report end, in the site's timezone.", 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_end_gmt' => array(
|
||||
'description' => __( 'The date the report end, as GMT.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'subtotals' => array(
|
||||
'description' => __( 'Interval subtotals.', 'wc-admin' ),
|
||||
'type' => 'object',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
'properties' => $totals,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return $this->add_additional_fields_schema( $schema );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the query params for collections.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_collection_params() {
|
||||
$params = array();
|
||||
$params['context'] = $this->get_context_param( array( 'default' => 'view' ) );
|
||||
$params['page'] = array(
|
||||
'description' => __( 'Current page of the collection.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'default' => 1,
|
||||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'minimum' => 1,
|
||||
);
|
||||
$params['per_page'] = array(
|
||||
'description' => __( 'Maximum number of items to be returned in result set.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'default' => 10,
|
||||
'minimum' => 1,
|
||||
'maximum' => 100,
|
||||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['after'] = array(
|
||||
'description' => __( 'Limit response to resources published after a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['before'] = array(
|
||||
'description' => __( 'Limit response to resources published before a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['order'] = array(
|
||||
'description' => __( 'Order sort attribute ascending or descending.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'desc',
|
||||
'enum' => array( 'asc', 'desc' ),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['orderby'] = array(
|
||||
'description' => __( 'Sort collection by object attribute.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'date',
|
||||
'enum' => array(
|
||||
'date',
|
||||
'download_count',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['interval'] = array(
|
||||
'description' => __( 'Time interval to use for buckets in the returned data.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'week',
|
||||
'enum' => array(
|
||||
'hour',
|
||||
'day',
|
||||
'week',
|
||||
'month',
|
||||
'quarter',
|
||||
'year',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['match'] = array(
|
||||
'description' => __( 'Indicates whether all the conditions should be true for the resulting set, or if any one of them is sufficient. Match affects the following parameters: status_is, status_is_not, product_includes, product_excludes, coupon_includes, coupon_excludes, customer, categories', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'all',
|
||||
'enum' => array(
|
||||
'all',
|
||||
'any',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['product_includes'] = array(
|
||||
'description' => __( 'Limit result set to items that have the specified product(s) assigned.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'items' => array(
|
||||
'type' => 'integer',
|
||||
),
|
||||
'default' => array(),
|
||||
'sanitize_callback' => 'wp_parse_id_list',
|
||||
|
||||
);
|
||||
$params['product_excludes'] = array(
|
||||
'description' => __( 'Limit result set to items that don\'t have the specified product(s) assigned.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'items' => array(
|
||||
'type' => 'integer',
|
||||
),
|
||||
'default' => array(),
|
||||
'sanitize_callback' => 'wp_parse_id_list',
|
||||
);
|
||||
$params['order_includes'] = array(
|
||||
'description' => __( 'Limit result set to items that have the specified order ids.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => 'wp_parse_id_list',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'items' => array(
|
||||
'type' => 'integer',
|
||||
),
|
||||
);
|
||||
$params['order_excludes'] = array(
|
||||
'description' => __( 'Limit result set to items that don\'t have the specified order ids.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => 'wp_parse_id_list',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'items' => array(
|
||||
'type' => 'integer',
|
||||
),
|
||||
);
|
||||
$params['user_includes'] = array(
|
||||
'description' => __( 'Limit response to objects that have the specified user ids.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => 'wp_parse_id_list',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'items' => array(
|
||||
'type' => 'integer',
|
||||
),
|
||||
);
|
||||
$params['user_excludes'] = array(
|
||||
'description' => __( 'Limit response to objects that don\'t have the specified user ids.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => 'wp_parse_id_list',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'items' => array(
|
||||
'type' => 'integer',
|
||||
),
|
||||
);
|
||||
$params['ip_address_includes'] = array(
|
||||
'description' => __( 'Limit response to objects that have a specified ip address.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'items' => array(
|
||||
'type' => 'string',
|
||||
),
|
||||
);
|
||||
|
||||
$params['ip_address_excludes'] = array(
|
||||
'description' => __( 'Limit response to objects that don\'t have a specified ip address.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'items' => array(
|
||||
'type' => 'string',
|
||||
),
|
||||
);
|
||||
|
||||
return $params;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,287 @@
|
|||
<?php
|
||||
/**
|
||||
* REST API Performance indicators controller
|
||||
*
|
||||
* Handles requests to the /reports/store-performance endpoint.
|
||||
*
|
||||
* @package WooCommerce Admin/API
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* REST API Reports Performance indicators controller class.
|
||||
*
|
||||
* @package WooCommerce/API
|
||||
* @extends WC_REST_Reports_Controller
|
||||
*/
|
||||
class WC_Admin_REST_Reports_Performance_Indicators_Controller extends WC_REST_Reports_Controller {
|
||||
|
||||
/**
|
||||
* Endpoint namespace.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $namespace = 'wc/v3';
|
||||
|
||||
/**
|
||||
* Route base.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $rest_base = 'reports/performance-indicators';
|
||||
|
||||
/**
|
||||
* Maps query arguments from the REST request.
|
||||
*
|
||||
* @param array $request Request array.
|
||||
* @return array
|
||||
*/
|
||||
protected function prepare_reports_query( $request ) {
|
||||
$args = array();
|
||||
$args['before'] = $request['before'];
|
||||
$args['after'] = $request['after'];
|
||||
$args['stats'] = $request['stats'];
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all allowed stats that can be returned from this endpoint.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_allowed_stats() {
|
||||
global $wp_rest_server;
|
||||
|
||||
$request = new WP_REST_Request( 'GET', '/wc/v3/reports' );
|
||||
$response = rest_do_request( $request );
|
||||
$endpoints = $response->get_data();
|
||||
$allowed_stats = array();
|
||||
if ( 200 !== $response->get_status() ) {
|
||||
return new WP_Error( 'woocommerce_reports_performance_indicators_result_failed', __( 'Sorry, fetching performance indicators failed.', 'wc-admin' ) );
|
||||
}
|
||||
|
||||
foreach ( $endpoints as $endpoint ) {
|
||||
if ( '/stats' === substr( $endpoint['slug'], -6 ) ) {
|
||||
$request = new WP_REST_Request( 'OPTIONS', '/wc/v3/reports/' . $endpoint['slug'] );
|
||||
$response = rest_do_request( $request );
|
||||
$data = $response->get_data();
|
||||
$prefix = substr( $endpoint['slug'], 0, -6 );
|
||||
|
||||
if ( empty( $data['schema']['properties']['totals']['properties'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ( $data['schema']['properties']['totals']['properties'] as $property_key => $schema_info ) {
|
||||
$allowed_stats[] = $prefix . '/' . $property_key;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the list of allowed stats that can be returned via the performance indiciator endpoint.
|
||||
*
|
||||
* @param array $allowed_stats The list of allowed stats.
|
||||
*/
|
||||
return apply_filters( 'woocommerce_admin_performance_indicators_allowed_stats', $allowed_stats );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all reports.
|
||||
*
|
||||
* @param WP_REST_Request $request Request data.
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
public function get_items( $request ) {
|
||||
$allowed_stats = $this->get_allowed_stats();
|
||||
|
||||
if ( is_wp_error( $allowed_stats ) ) {
|
||||
return $allowed_stats;
|
||||
}
|
||||
|
||||
$query_args = $this->prepare_reports_query( $request );
|
||||
if ( empty( $query_args['stats'] ) ) {
|
||||
return new WP_Error( 'woocommerce_reports_performance_indicators_empty_query', __( 'A list of stats to query must be provided.', 'wc-admin' ), 400 );
|
||||
}
|
||||
|
||||
$stats = array();
|
||||
foreach ( $query_args['stats'] as $stat_request ) {
|
||||
$is_error = false;
|
||||
|
||||
$pieces = explode( '/', $stat_request );
|
||||
$endpoint = $pieces[0];
|
||||
$stat = $pieces[1];
|
||||
|
||||
if ( ! in_array( $stat_request, $allowed_stats ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the list of allowed endpoints, so that data can be loaded from extensions rather than core.
|
||||
* These should be in the format of slug => path. Example: `bookings` => `/wc-bookings/v1/reports/bookings/stats`.
|
||||
*
|
||||
* @param array $endpoints The list of allowed endpoints.
|
||||
*/
|
||||
$stats_endpoints = apply_filters( 'woocommerce_admin_performance_indicators_stats_endpoints', array() );
|
||||
if ( ! empty( $stats_endpoints [ $endpoint ] ) ) {
|
||||
$request_url = $stats_endpoints [ $endpoint ];
|
||||
} else {
|
||||
$request_url = '/wc/v3/reports/' . $endpoint . '/stats';
|
||||
}
|
||||
|
||||
$request = new WP_REST_Request( 'GET', $request_url );
|
||||
$request->set_param( 'before', $query_args['before'] );
|
||||
$request->set_param( 'after', $query_args['after'] );
|
||||
|
||||
$response = rest_do_request( $request );
|
||||
$data = $response->get_data();
|
||||
|
||||
if ( 200 !== $response->get_status() || empty( $data['totals'][ $stat ] ) ) {
|
||||
$stats[] = (object) array(
|
||||
'stat' => $stat_request,
|
||||
'value' => null,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
$stats[] = (object) array(
|
||||
'stat' => $stat_request,
|
||||
'value' => $data['totals'][ $stat ],
|
||||
);
|
||||
}
|
||||
|
||||
$objects = array();
|
||||
foreach ( $stats as $stat ) {
|
||||
$data = $this->prepare_item_for_response( $stat, $request );
|
||||
$objects[] = $this->prepare_response_for_collection( $data );
|
||||
}
|
||||
|
||||
$response = rest_ensure_response( $objects );
|
||||
$response->header( 'X-WP-Total', count( $stats ) );
|
||||
$response->header( 'X-WP-TotalPages', 1 );
|
||||
|
||||
$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a report object for serialization.
|
||||
*
|
||||
* @param stdClass $stat_data Report data.
|
||||
* @param WP_REST_Request $request Request object.
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function prepare_item_for_response( $stat_data, $request ) {
|
||||
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
|
||||
$data = $this->add_additional_fields_to_object( $stat_data, $request );
|
||||
$data = $this->filter_response_by_context( $data, $context );
|
||||
|
||||
// Wrap the data in a response object.
|
||||
$response = rest_ensure_response( $data );
|
||||
|
||||
$response->add_links( $this->prepare_links( $data ) );
|
||||
|
||||
/**
|
||||
* Filter a report returned from the API.
|
||||
*
|
||||
* Allows modification of the report data right before it is returned.
|
||||
*
|
||||
* @param WP_REST_Response $response The response object.
|
||||
* @param object $report The original report object.
|
||||
* @param WP_REST_Request $request Request used to generate the response.
|
||||
*/
|
||||
return apply_filters( 'woocommerce_rest_prepare_report_performance_indicators', $response, $stat_data, $request );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare links for the request.
|
||||
*
|
||||
* @param WC_Admin_Reports_Query $object Object data.
|
||||
* @return array
|
||||
*/
|
||||
protected function prepare_links( $object ) {
|
||||
$pieces = explode( '/', $object->stat );
|
||||
$endpoint = $pieces[0];
|
||||
$stat = $pieces[1];
|
||||
|
||||
$links = array(
|
||||
'report' => array(
|
||||
'href' => rest_url( sprintf( '/%s/reports/%s/stats', $this->namespace, $endpoint ) ),
|
||||
),
|
||||
);
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Report's schema, conforming to JSON Schema.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_item_schema() {
|
||||
$schema = array(
|
||||
'$schema' => 'http://json-schema.org/draft-04/schema#',
|
||||
'title' => 'report_performance_indicator',
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'stat' => array(
|
||||
'description' => __( 'Unique identifier for the resource.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'value' => array(
|
||||
'description' => __( 'Value of the stat. Returns null if the stat does not exist or cannot be loaded.', 'wc-admin' ),
|
||||
'type' => 'number',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return $this->add_additional_fields_schema( $schema );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the query params for collections.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_collection_params() {
|
||||
$allowed_stats = $this->get_allowed_stats();
|
||||
if ( is_wp_error( $allowed_stats ) ) {
|
||||
$allowed_stats = __( 'There was an issue loading the report endpoints', 'wc-admin' );
|
||||
} else {
|
||||
$allowed_stats = implode( ', ', $allowed_stats );
|
||||
}
|
||||
|
||||
$params = array();
|
||||
$params['context'] = $this->get_context_param( array( 'default' => 'view' ) );
|
||||
$params['stats'] = array(
|
||||
'description' => sprintf(
|
||||
/* translators: Allowed values is a list of stat endpoints. */
|
||||
__( 'Limit response to specific report stats. Allowed values: %s.', 'wc-admin' ),
|
||||
$allowed_stats
|
||||
),
|
||||
'type' => 'array',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
'items' => array(
|
||||
'type' => 'string',
|
||||
),
|
||||
);
|
||||
$params['after'] = array(
|
||||
'description' => __( 'Limit response to resources published after a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['before'] = array(
|
||||
'description' => __( 'Limit response to resources published before a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
return $params;
|
||||
}
|
||||
}
|
|
@ -291,6 +291,7 @@ class WC_Admin_REST_Reports_Products_Controller extends WC_REST_Reports_Controll
|
|||
'orders_count',
|
||||
'items_sold',
|
||||
'product_name',
|
||||
'sku',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
|
|
|
@ -58,8 +58,9 @@ class WC_Admin_REST_Reports_Stock_Controller extends WC_REST_Reports_Controller
|
|||
$args['orderby'] = 'post__in';
|
||||
} elseif ( 'id' === $args['orderby'] ) {
|
||||
$args['orderby'] = 'ID'; // ID must be capitalized.
|
||||
} elseif ( 'slug' === $args['orderby'] ) {
|
||||
$args['orderby'] = 'name';
|
||||
} elseif ( 'sku' === $args['orderby'] ) {
|
||||
$args['meta_key'] = '_sku'; // WPCS: slow query ok.
|
||||
$args['orderby'] = 'meta_value';
|
||||
}
|
||||
|
||||
$args['post_type'] = array( 'product', 'product_variation' );
|
||||
|
@ -359,7 +360,7 @@ class WC_Admin_REST_Reports_Stock_Controller extends WC_REST_Reports_Controller
|
|||
'id',
|
||||
'include',
|
||||
'title',
|
||||
'slug',
|
||||
'sku',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
|
|
|
@ -29,6 +29,10 @@ class WC_Admin_Api_Init {
|
|||
|
||||
// Initialize Orders data store class's static vars.
|
||||
add_action( 'woocommerce_after_register_post_type', array( 'WC_Admin_Api_Init', 'orders_data_store_init' ), 20 );
|
||||
// Initialize Customers Report data store sync hooks.
|
||||
// Note: we need to hook into 'wp' before `wc_current_user_is_active`.
|
||||
// See: https://github.com/woocommerce/woocommerce/blob/942615101ba00c939c107c3a4820c3d466864872/includes/wc-user-functions.php#L749.
|
||||
add_action( 'wp', array( 'WC_Admin_Api_Init', 'customers_report_data_store_init' ), 9 );
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -54,6 +58,8 @@ class WC_Admin_Api_Init {
|
|||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-coupons-query.php';
|
||||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-coupons-stats-query.php';
|
||||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-downloads-query.php';
|
||||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-downloads-stats-query.php';
|
||||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-customers-query.php';
|
||||
|
||||
// Data stores.
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-data-store.php';
|
||||
|
@ -67,6 +73,8 @@ class WC_Admin_Api_Init {
|
|||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-coupons-data-store.php';
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-coupons-stats-data-store.php';
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-downloads-data-store.php';
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-downloads-stats-data-store.php';
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-customers-data-store.php';
|
||||
|
||||
// Data triggers.
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-notes-data-store.php';
|
||||
|
@ -100,36 +108,44 @@ class WC_Admin_Api_Init {
|
|||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-products-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-variations-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-products-stats-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-performance-indicators-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-revenue-stats-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-taxes-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-taxes-stats-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-stock-controller.php';
|
||||
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-downloads-controller.php';
|
||||
|
||||
$controllers = array(
|
||||
'WC_Admin_REST_Admin_Notes_Controller',
|
||||
'WC_Admin_REST_Customers_Controller',
|
||||
'WC_Admin_REST_Data_Controller',
|
||||
'WC_Admin_REST_Data_Download_Ips_Controller',
|
||||
'WC_Admin_REST_Orders_Controller',
|
||||
'WC_Admin_REST_Products_Controller',
|
||||
'WC_Admin_REST_Product_Reviews_Controller',
|
||||
'WC_Admin_REST_Reports_Controller',
|
||||
'WC_Admin_REST_System_Status_Tools_Controller',
|
||||
'WC_Admin_REST_Reports_Products_Controller',
|
||||
'WC_Admin_REST_Reports_Variations_Controller',
|
||||
'WC_Admin_REST_Reports_Products_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Revenue_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Orders_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Categories_Controller',
|
||||
'WC_Admin_REST_Reports_Taxes_Controller',
|
||||
'WC_Admin_REST_Reports_Taxes_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Coupons_Controller',
|
||||
'WC_Admin_REST_Reports_Coupons_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Stock_Controller',
|
||||
'WC_Admin_REST_Reports_Downloads_Controller',
|
||||
$controllers = apply_filters(
|
||||
'woocommerce_admin_rest_controllers',
|
||||
array(
|
||||
'WC_Admin_REST_Admin_Notes_Controller',
|
||||
'WC_Admin_REST_Customers_Controller',
|
||||
'WC_Admin_REST_Data_Controller',
|
||||
'WC_Admin_REST_Data_Download_Ips_Controller',
|
||||
'WC_Admin_REST_Orders_Controller',
|
||||
'WC_Admin_REST_Products_Controller',
|
||||
'WC_Admin_REST_Product_Reviews_Controller',
|
||||
'WC_Admin_REST_Reports_Controller',
|
||||
'WC_Admin_REST_System_Status_Tools_Controller',
|
||||
'WC_Admin_REST_Reports_Products_Controller',
|
||||
'WC_Admin_REST_Reports_Variations_Controller',
|
||||
'WC_Admin_REST_Reports_Products_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Revenue_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Orders_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Categories_Controller',
|
||||
'WC_Admin_REST_Reports_Taxes_Controller',
|
||||
'WC_Admin_REST_Reports_Taxes_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Coupons_Controller',
|
||||
'WC_Admin_REST_Reports_Coupons_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Stock_Controller',
|
||||
'WC_Admin_REST_Reports_Downloads_Controller',
|
||||
'WC_Admin_REST_Reports_Downloads_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Customers_Controller',
|
||||
)
|
||||
);
|
||||
|
||||
// The performance indicators controller must be registered last, after other /stats endpoints have been registered.
|
||||
$controllers[] = 'WC_Admin_REST_Reports_Performance_Indicators_Controller';
|
||||
|
||||
foreach ( $controllers as $controller ) {
|
||||
$this->$controller = new $controller();
|
||||
$this->$controller->register_routes();
|
||||
|
@ -258,6 +274,9 @@ class WC_Admin_Api_Init {
|
|||
* Regenerate data for reports.
|
||||
*/
|
||||
public static function regenerate_report_data() {
|
||||
// Add registered customers to the lookup table before updating order stats
|
||||
// so that the orders can be associated with the `customer_id` column.
|
||||
self::customer_lookup_store_init();
|
||||
WC_Admin_Reports_Orders_Data_Store::queue_order_stats_repopulate_database();
|
||||
self::order_product_lookup_store_init();
|
||||
}
|
||||
|
@ -328,6 +347,59 @@ class WC_Admin_Api_Init {
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Init customers report data store.
|
||||
*/
|
||||
public static function customers_report_data_store_init() {
|
||||
WC_Admin_Reports_Customers_Data_Store::init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Init customer lookup store.
|
||||
*
|
||||
* @param WC_Background_Updater|null $updater Updater instance.
|
||||
* @return bool
|
||||
*/
|
||||
public static function customer_lookup_store_init( $updater = null ) {
|
||||
// TODO: this needs to be updated a bit, as it no longer runs as a part of WC_Install, there is no bg updater.
|
||||
global $wpdb;
|
||||
|
||||
// Backfill customer lookup table with registered customers.
|
||||
$customer_ids = get_transient( 'wc_update_350_all_customers' );
|
||||
|
||||
if ( false === $customer_ids ) {
|
||||
$customer_query = new WP_User_Query(
|
||||
array(
|
||||
'fields' => 'ID',
|
||||
'role' => 'customer',
|
||||
'number' => -1,
|
||||
)
|
||||
);
|
||||
|
||||
$customer_ids = $customer_query->get_results();
|
||||
|
||||
set_transient( 'wc_update_350_all_customers', $customer_ids, DAY_IN_SECONDS );
|
||||
}
|
||||
|
||||
// Process customers until close to running out of memory timeouts on large sites then requeue.
|
||||
foreach ( $customer_ids as $customer_id ) {
|
||||
$result = WC_Admin_Reports_Customers_Data_Store::update_registered_customer( $customer_id );
|
||||
|
||||
if ( $result ) {
|
||||
// Pop the customer ID from the array for updating the transient later should we near memory exhaustion.
|
||||
unset( $customer_ids[ $customer_id ] );
|
||||
}
|
||||
|
||||
if ( $updater instanceof WC_Background_Updater && $updater->is_memory_exceeded() ) {
|
||||
// Update the transient for the next run to avoid processing the same orders again.
|
||||
set_transient( 'wc_update_350_all_customers', $customer_ids, DAY_IN_SECONDS );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds data stores.
|
||||
*
|
||||
|
@ -338,18 +410,20 @@ class WC_Admin_Api_Init {
|
|||
return array_merge(
|
||||
$data_stores,
|
||||
array(
|
||||
'report-revenue-stats' => 'WC_Admin_Reports_Orders_Data_Store',
|
||||
'report-orders-stats' => 'WC_Admin_Reports_Orders_Data_Store',
|
||||
'report-products' => 'WC_Admin_Reports_Products_Data_Store',
|
||||
'report-variations' => 'WC_Admin_Reports_Variations_Data_Store',
|
||||
'report-products-stats' => 'WC_Admin_Reports_Products_Stats_Data_Store',
|
||||
'report-categories' => 'WC_Admin_Reports_Categories_Data_Store',
|
||||
'report-taxes' => 'WC_Admin_Reports_Taxes_Data_Store',
|
||||
'report-taxes-stats' => 'WC_Admin_Reports_Taxes_Stats_Data_Store',
|
||||
'report-coupons' => 'WC_Admin_Reports_Coupons_Data_Store',
|
||||
'report-coupons-stats' => 'WC_Admin_Reports_Coupons_Stats_Data_Store',
|
||||
'report-downloads' => 'WC_Admin_Reports_Downloads_Data_Store',
|
||||
'admin-note' => 'WC_Admin_Notes_Data_Store',
|
||||
'report-revenue-stats' => 'WC_Admin_Reports_Orders_Data_Store',
|
||||
'report-orders-stats' => 'WC_Admin_Reports_Orders_Data_Store',
|
||||
'report-products' => 'WC_Admin_Reports_Products_Data_Store',
|
||||
'report-variations' => 'WC_Admin_Reports_Variations_Data_Store',
|
||||
'report-products-stats' => 'WC_Admin_Reports_Products_Stats_Data_Store',
|
||||
'report-categories' => 'WC_Admin_Reports_Categories_Data_Store',
|
||||
'report-taxes' => 'WC_Admin_Reports_Taxes_Data_Store',
|
||||
'report-taxes-stats' => 'WC_Admin_Reports_Taxes_Stats_Data_Store',
|
||||
'report-coupons' => 'WC_Admin_Reports_Coupons_Data_Store',
|
||||
'report-coupons-stats' => 'WC_Admin_Reports_Coupons_Stats_Data_Store',
|
||||
'report-downloads' => 'WC_Admin_Reports_Downloads_Data_Store',
|
||||
'report-downloads-stats' => 'WC_Admin_Reports_Downloads_Stats_Data_Store',
|
||||
'admin-note' => 'WC_Admin_Notes_Data_Store',
|
||||
'report-customers' => 'WC_Admin_Reports_Customers_Data_Store',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -373,6 +447,7 @@ class WC_Admin_Api_Init {
|
|||
"{$wpdb->prefix}wc_order_coupon_lookup",
|
||||
"{$wpdb->prefix}woocommerce_admin_notes",
|
||||
"{$wpdb->prefix}woocommerce_admin_note_actions",
|
||||
"{$wpdb->prefix}wc_customer_lookup",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -401,6 +476,8 @@ class WC_Admin_Api_Init {
|
|||
shipping_total double DEFAULT 0 NOT NULL,
|
||||
net_total double DEFAULT 0 NOT NULL,
|
||||
returning_customer boolean DEFAULT 0 NOT NULL,
|
||||
status varchar(200) NOT NULL,
|
||||
customer_id BIGINT UNSIGNED NOT NULL,
|
||||
PRIMARY KEY (order_id),
|
||||
KEY date_created (date_created)
|
||||
) $collate;
|
||||
|
@ -469,6 +546,22 @@ class WC_Admin_Api_Init {
|
|||
PRIMARY KEY (action_id),
|
||||
KEY note_id (note_id)
|
||||
) $collate;
|
||||
CREATE TABLE {$wpdb->prefix}wc_customer_lookup (
|
||||
customer_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
user_id BIGINT UNSIGNED DEFAULT NULL,
|
||||
username varchar(60) DEFAULT '' NOT NULL,
|
||||
first_name varchar(255) NOT NULL,
|
||||
last_name varchar(255) NOT NULL,
|
||||
email varchar(100) NOT NULL,
|
||||
date_last_active timestamp DEFAULT '0000-00-00 00:00:00' NOT NULL,
|
||||
date_registered timestamp NULL default null,
|
||||
country char(2) DEFAULT '' NOT NULL,
|
||||
postcode varchar(20) DEFAULT '' NOT NULL,
|
||||
city varchar(100) DEFAULT '' NOT NULL,
|
||||
PRIMARY KEY (customer_id),
|
||||
UNIQUE KEY user_id (user_id),
|
||||
KEY email (email)
|
||||
) $collate;
|
||||
";
|
||||
|
||||
return $tables;
|
||||
|
@ -492,17 +585,7 @@ class WC_Admin_Api_Init {
|
|||
|
||||
// Initialize report tables.
|
||||
add_action( 'woocommerce_after_register_post_type', array( 'WC_Admin_Api_Init', 'order_product_lookup_store_init' ), 20 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the WP REST API for product categories
|
||||
*
|
||||
* @param array $args Default arguments for product_cat taxonomy.
|
||||
* @return array
|
||||
*/
|
||||
public static function show_product_categories_in_rest( $args ) {
|
||||
$args['show_in_rest'] = true;
|
||||
return $args;
|
||||
add_action( 'woocommerce_after_register_post_type', array( 'WC_Admin_Api_Init', 'customer_lookup_store_init' ), 20 );
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
/**
|
||||
* Class for parameter-based Customers Report querying
|
||||
*
|
||||
* Example usage:
|
||||
* $args = array(
|
||||
* 'registered_before' => '2018-07-19 00:00:00',
|
||||
* 'registered_after' => '2018-07-05 00:00:00',
|
||||
* 'page' => 2,
|
||||
* 'avg_order_value_min' => 100,
|
||||
* 'country' => 'GB',
|
||||
* );
|
||||
* $report = new WC_Admin_Reports_Customers_Query( $args );
|
||||
* $mydata = $report->get_data();
|
||||
*
|
||||
* @package WooCommerce Admin/Classes
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* WC_Admin_Reports_Customers_Query
|
||||
*/
|
||||
class WC_Admin_Reports_Customers_Query extends WC_Admin_Reports_Query {
|
||||
|
||||
/**
|
||||
* Valid fields for Customers report.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_default_query_vars() {
|
||||
return array(
|
||||
'per_page' => get_option( 'posts_per_page' ), // not sure if this should be the default.
|
||||
'page' => 1,
|
||||
'order' => 'DESC',
|
||||
'orderby' => 'date_registered',
|
||||
'fields' => '*',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get product data based on the current query vars.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_data() {
|
||||
$args = apply_filters( 'woocommerce_reports_customers_query_args', $this->get_query_vars() );
|
||||
|
||||
$data_store = WC_Data_Store::load( 'report-customers' );
|
||||
$results = $data_store->get_data( $args );
|
||||
return apply_filters( 'woocommerce_reports_customers_select_query', $results, $args );
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
/**
|
||||
* Class for parameter-based downloads Reports querying
|
||||
*
|
||||
* @package WooCommerce Admin/Classes
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* WC_Admin_Reports_Downloads_Stats_Query
|
||||
*/
|
||||
class WC_Admin_Reports_Downloads_Stats_Query extends WC_Admin_Reports_Query {
|
||||
|
||||
/**
|
||||
* Valid fields for Orders report.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_default_query_vars() {
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get revenue data based on the current query vars.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_data() {
|
||||
$args = apply_filters( 'woocommerce_reports_downloads_stats_query_args', $this->get_query_vars() );
|
||||
|
||||
$data_store = WC_Data_Store::load( 'report-downloads-stats' );
|
||||
$results = $data_store->get_data( $args );
|
||||
return apply_filters( 'woocommerce_reports_downloads_stats_select_query', $results, $args );
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
<?php
|
||||
/**
|
||||
* Class for time interval handling for reports
|
||||
* Class for time interval and numeric range handling for reports.
|
||||
*
|
||||
* @package WooCommerce Admin/Classes
|
||||
*/
|
||||
|
@ -8,7 +8,7 @@
|
|||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Date & time interval handling class for Reporting API.
|
||||
* Date & time interval and numeric range handling class for Reporting API.
|
||||
*/
|
||||
class WC_Admin_Reports_Interval {
|
||||
|
||||
|
@ -475,4 +475,72 @@ class WC_Admin_Reports_Interval {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize "*_between" parameters to "*_min" and "*_max".
|
||||
*
|
||||
* @param array $request Query params from REST API request.
|
||||
* @param string|array $param_names One or more param names to handle. Should not include "_between" suffix.
|
||||
* @return array Normalized query values.
|
||||
*/
|
||||
public static function normalize_between_params( $request, $param_names ) {
|
||||
if ( ! is_array( $param_names ) ) {
|
||||
$param_names = array( $param_names );
|
||||
}
|
||||
|
||||
$normalized = array();
|
||||
|
||||
foreach ( $param_names as $param_name ) {
|
||||
if ( ! is_array( $request[ $param_name . '_between' ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$range = $request[ $param_name . '_between' ];
|
||||
|
||||
if ( 2 !== count( $range ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( $range[0] < $range[1] ) {
|
||||
$normalized[ $param_name . '_min' ] = $range[0];
|
||||
$normalized[ $param_name . '_max' ] = $range[1];
|
||||
} else {
|
||||
$normalized[ $param_name . '_min' ] = $range[1];
|
||||
$normalized[ $param_name . '_max' ] = $range[0];
|
||||
}
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a "*_between" range argument (an array with 2 numeric items).
|
||||
*
|
||||
* @param mixed $value Parameter value.
|
||||
* @param WP_REST_Request $request REST Request.
|
||||
* @param string $param Parameter name.
|
||||
* @return WP_Error|boolean
|
||||
*/
|
||||
public static function rest_validate_between_arg( $value, $request, $param ) {
|
||||
if ( ! wp_is_numeric_array( $value ) ) {
|
||||
return new WP_Error(
|
||||
'rest_invalid_param',
|
||||
/* translators: 1: parameter name */
|
||||
sprintf( __( '%1$s is not a numerically indexed array.', 'wc-admin' ), $param )
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
2 !== count( $value ) ||
|
||||
! is_numeric( $value[0] ) ||
|
||||
! is_numeric( $value[1] )
|
||||
) {
|
||||
return new WP_Error(
|
||||
'rest_invalid_param',
|
||||
/* translators: %s: parameter name */
|
||||
sprintf( __( '%s must contain 2 numbers.', 'wc-admin' ), $param )
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -70,14 +70,16 @@ class WC_Admin_Reports_Categories_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
$order_product_lookup_table = $wpdb->prefix . self::TABLE_NAME;
|
||||
|
||||
$sql_query_params = $this->get_time_period_sql_params( $query_args, $order_product_lookup_table );
|
||||
// Limit is left out here so that the grouping in code by PHP can be applied correctly.
|
||||
$sql_query_params = array_merge( $sql_query_params, $this->get_order_by_sql_params( $query_args ) );
|
||||
|
||||
// join wp_order_product_lookup_table with relationships and taxonomies
|
||||
// @TODO: How to handle custom product tables?
|
||||
$sql_query_params['from_clause'] .= " LEFT JOIN {$wpdb->prefix}term_relationships ON {$order_product_lookup_table}.product_id = {$wpdb->prefix}term_relationships.object_id";
|
||||
$sql_query_params['from_clause'] .= " LEFT JOIN {$wpdb->prefix}term_taxonomy ON {$wpdb->prefix}term_relationships.term_taxonomy_id = {$wpdb->prefix}term_taxonomy.term_taxonomy_id";
|
||||
|
||||
// Limit is left out here so that the grouping in code by PHP can be applied correctly.
|
||||
// This also needs to be put after the term_taxonomy JOIN so that we can match the correct term name.
|
||||
$sql_query_params = $this->get_order_by_params( $query_args, $sql_query_params );
|
||||
|
||||
$included_categories = $this->get_included_categories( $query_args );
|
||||
if ( $included_categories ) {
|
||||
$sql_query_params['where_clause'] .= " AND {$wpdb->prefix}term_taxonomy.term_id IN ({$included_categories})";
|
||||
|
@ -100,6 +102,52 @@ class WC_Admin_Reports_Categories_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
return $sql_query_params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills ORDER BY clause of SQL request based on user supplied parameters.
|
||||
*
|
||||
* @param array $query_args Parameters supplied by the user.
|
||||
* @param array $sql_query Current SQL query array.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_order_by_params( $query_args, $sql_query ) {
|
||||
global $wpdb;
|
||||
$lookup_table = $wpdb->prefix . self::TABLE_NAME;
|
||||
|
||||
$sql_query['order_by_clause'] = '';
|
||||
if ( isset( $query_args['orderby'] ) ) {
|
||||
$sql_query['order_by_clause'] = $this->normalize_order_by( $query_args['orderby'] );
|
||||
}
|
||||
|
||||
if ( false !== strpos( $sql_query['order_by_clause'], '_terms' ) ) {
|
||||
$sql_query['from_clause'] .= " JOIN {$wpdb->prefix}terms AS _terms ON {$wpdb->prefix}term_taxonomy.term_id = _terms.term_id";
|
||||
}
|
||||
|
||||
if ( isset( $query_args['order'] ) ) {
|
||||
$sql_query['order_by_clause'] .= ' ' . $query_args['order'];
|
||||
} else {
|
||||
$sql_query['order_by_clause'] .= ' DESC';
|
||||
}
|
||||
|
||||
return $sql_query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps ordering specified by the user to columns in the database/fields in the data.
|
||||
*
|
||||
* @param string $order_by Sorting criterion.
|
||||
* @return string
|
||||
*/
|
||||
protected function normalize_order_by( $order_by ) {
|
||||
if ( 'date' === $order_by ) {
|
||||
return 'time_interval';
|
||||
}
|
||||
if ( 'category' === $order_by ) {
|
||||
return '_terms.name';
|
||||
}
|
||||
return $order_by;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns comma separated ids of included categories, based on query arguments from the user.
|
||||
*
|
||||
|
@ -115,39 +163,6 @@ class WC_Admin_Reports_Categories_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
return $included_categories_str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares values in 2 arrays based on criterion specified when called via sort_records.
|
||||
*
|
||||
* @param array $a Array 1 to compare.
|
||||
* @param array $b Array 2 to compare.
|
||||
* @return integer|WP_Error
|
||||
*/
|
||||
private function sort_callback( $a, $b ) {
|
||||
if ( '' === $this->order_by || '' === $this->order ) {
|
||||
return new WP_Error( 'woocommerce_reports_categories_sort_failed', __( 'Sorry, fetching categories data failed.', 'wc-admin' ) );
|
||||
}
|
||||
if ( $a[ $this->order_by ] === $b[ $this->order_by ] ) {
|
||||
return 0;
|
||||
} elseif ( $a[ $this->order_by ] > $b[ $this->order_by ] ) {
|
||||
return strtolower( $this->order ) === 'desc' ? -1 : 1;
|
||||
} elseif ( $a[ $this->order_by ] < $b[ $this->order_by ] ) {
|
||||
return strtolower( $this->order ) === 'desc' ? 1 : -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the data based on given sorting criterion and order.
|
||||
*
|
||||
* @param array $data Data to sort.
|
||||
* @param string $sort_by Sorting criterion, any of the column_types keys.
|
||||
* @param string $direction Sorting direction: asc/desc.
|
||||
*/
|
||||
protected function sort_records( &$data, $sort_by, $direction ) {
|
||||
$this->order_by = $this->normalize_order_by( $sort_by );
|
||||
$this->order = $direction;
|
||||
usort( $data, array( $this, 'sort_callback' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the page of data according to page number and items per page.
|
||||
*
|
||||
|
@ -223,7 +238,7 @@ class WC_Admin_Reports_Categories_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
|
||||
$categories_data = $wpdb->get_results(
|
||||
"SELECT
|
||||
term_id as category_id,
|
||||
{$wpdb->prefix}term_taxonomy.term_id as category_id,
|
||||
{$selections}
|
||||
FROM
|
||||
{$table_name}
|
||||
|
@ -234,6 +249,8 @@ class WC_Admin_Reports_Categories_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
{$sql_query_params['where_clause']}
|
||||
GROUP BY
|
||||
category_id
|
||||
ORDER BY
|
||||
{$sql_query_params['order_by_clause']}
|
||||
",
|
||||
ARRAY_A
|
||||
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
|
||||
|
@ -248,11 +265,8 @@ class WC_Admin_Reports_Categories_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
return $data;
|
||||
}
|
||||
|
||||
$this->sort_records( $categories_data, $query_args['orderby'], $query_args['order'] );
|
||||
$categories_data = $this->page_records( $categories_data, $query_args['page'], $query_args['per_page'] );
|
||||
|
||||
$this->include_extended_info( $categories_data, $query_args );
|
||||
|
||||
$categories_data = array_map( array( $this, 'cast_numbers' ), $categories_data );
|
||||
$data = (object) array(
|
||||
'data' => $categories_data,
|
||||
|
|
|
@ -94,6 +94,52 @@ class WC_Admin_Reports_Coupons_Data_Store extends WC_Admin_Reports_Data_Store im
|
|||
return $sql_query_params;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fills ORDER BY clause of SQL request based on user supplied parameters.
|
||||
*
|
||||
* @param array $query_args Parameters supplied by the user.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_order_by_sql_params( $query_args ) {
|
||||
global $wpdb;
|
||||
$lookup_table = $wpdb->prefix . self::TABLE_NAME;
|
||||
$sql_query = array();
|
||||
$sql_query['from_clause'] = '';
|
||||
$sql_query['order_by_clause'] = '';
|
||||
if ( isset( $query_args['orderby'] ) ) {
|
||||
$sql_query['order_by_clause'] = $this->normalize_order_by( $query_args['orderby'] );
|
||||
}
|
||||
|
||||
if ( false !== strpos( $sql_query['order_by_clause'], '_coupons' ) ) {
|
||||
$sql_query['from_clause'] .= " JOIN {$wpdb->prefix}posts AS _coupons ON {$lookup_table}.coupon_id = _coupons.ID";
|
||||
}
|
||||
|
||||
if ( isset( $query_args['order'] ) ) {
|
||||
$sql_query['order_by_clause'] .= ' ' . $query_args['order'];
|
||||
} else {
|
||||
$sql_query['order_by_clause'] .= ' DESC';
|
||||
}
|
||||
|
||||
return $sql_query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps ordering specified by the user to columns in the database/fields in the data.
|
||||
*
|
||||
* @param string $order_by Sorting criterion.
|
||||
* @return string
|
||||
*/
|
||||
protected function normalize_order_by( $order_by ) {
|
||||
if ( 'date' === $order_by ) {
|
||||
return 'time_interval';
|
||||
}
|
||||
if ( 'code' === $order_by ) {
|
||||
return '_coupons.post_title';
|
||||
}
|
||||
return $order_by;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enriches the coupon data with extra attributes.
|
||||
*
|
||||
|
|
|
@ -0,0 +1,572 @@
|
|||
<?php
|
||||
/**
|
||||
* WC_Admin_Reports_Customers_Data_Store class file.
|
||||
*
|
||||
* @package WooCommerce Admin/Classes
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* WC_Admin_Reports_Customers_Data_Store.
|
||||
*/
|
||||
class WC_Admin_Reports_Customers_Data_Store extends WC_Admin_Reports_Data_Store implements WC_Admin_Reports_Data_Store_Interface {
|
||||
|
||||
/**
|
||||
* Table used to get the data.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const TABLE_NAME = 'wc_customer_lookup';
|
||||
|
||||
/**
|
||||
* Mapping columns to data type to return correct response types.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $column_types = array(
|
||||
'customer_id' => 'intval',
|
||||
'user_id' => 'intval',
|
||||
'orders_count' => 'intval',
|
||||
'total_spend' => 'floatval',
|
||||
'avg_order_value' => 'floatval',
|
||||
);
|
||||
|
||||
/**
|
||||
* SQL columns to select in the db query and their mapping to SQL code.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $report_columns = array(
|
||||
'customer_id' => 'customer_id',
|
||||
'user_id' => 'user_id',
|
||||
'username' => 'username',
|
||||
'name' => "CONCAT_WS( ' ', first_name, last_name ) as name", // TODO: what does this mean for RTL?
|
||||
'email' => 'email',
|
||||
'country' => 'country',
|
||||
'city' => 'city',
|
||||
'postcode' => 'postcode',
|
||||
'date_registered' => 'date_registered',
|
||||
'date_last_active' => 'date_last_active',
|
||||
'orders_count' => 'COUNT( order_id ) as orders_count',
|
||||
'total_spend' => 'SUM( gross_total ) as total_spend',
|
||||
'avg_order_value' => '( SUM( gross_total ) / COUNT( order_id ) ) as avg_order_value',
|
||||
);
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
global $wpdb;
|
||||
|
||||
// Initialize some report columns that need disambiguation.
|
||||
$this->report_columns['customer_id'] = $wpdb->prefix . self::TABLE_NAME . '.customer_id';
|
||||
$this->report_columns['date_last_order'] = "MAX( {$wpdb->prefix}wc_order_stats.date_created ) as date_last_order";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up all the hooks for maintaining and populating table data.
|
||||
*/
|
||||
public static function init() {
|
||||
add_action( 'woocommerce_new_customer', array( __CLASS__, 'update_registered_customer' ) );
|
||||
add_action( 'woocommerce_update_customer', array( __CLASS__, 'update_registered_customer' ) );
|
||||
add_action( 'edit_user_profile_update', array( __CLASS__, 'update_registered_customer' ) );
|
||||
add_action( 'updated_user_meta', array( __CLASS__, 'update_registered_customer_via_last_active' ), 10, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a customer update if their "last active" meta value was changed.
|
||||
* Function expects to be hooked into the `updated_user_meta` action.
|
||||
*
|
||||
* @param int $meta_id ID of updated metadata entry.
|
||||
* @param int $user_id ID of the user being updated.
|
||||
* @param string $meta_key Meta key being updated.
|
||||
*/
|
||||
public static function update_registered_customer_via_last_active( $meta_id, $user_id, $meta_key ) {
|
||||
if ( 'wc_last_active' === $meta_key ) {
|
||||
self::update_registered_customer( $user_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps ordering specified by the user to columns in the database/fields in the data.
|
||||
*
|
||||
* @param string $order_by Sorting criterion.
|
||||
* @return string
|
||||
*/
|
||||
protected function normalize_order_by( $order_by ) {
|
||||
if ( 'name' === $order_by ) {
|
||||
return "CONCAT_WS( ' ', first_name, last_name )";
|
||||
}
|
||||
|
||||
return $order_by;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills ORDER BY clause of SQL request based on user supplied parameters.
|
||||
*
|
||||
* @param array $query_args Parameters supplied by the user.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_order_by_sql_params( $query_args ) {
|
||||
$sql_query['order_by_clause'] = '';
|
||||
|
||||
if ( isset( $query_args['orderby'] ) ) {
|
||||
$sql_query['order_by_clause'] = $this->normalize_order_by( $query_args['orderby'] );
|
||||
}
|
||||
|
||||
if ( isset( $query_args['order'] ) ) {
|
||||
$sql_query['order_by_clause'] .= ' ' . $query_args['order'];
|
||||
} else {
|
||||
$sql_query['order_by_clause'] .= ' DESC';
|
||||
}
|
||||
|
||||
return $sql_query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills WHERE clause of SQL request with date-related constraints.
|
||||
*
|
||||
* @param array $query_args Parameters supplied by the user.
|
||||
* @param string $table_name Name of the db table relevant for the date constraint.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_time_period_sql_params( $query_args, $table_name ) {
|
||||
global $wpdb;
|
||||
|
||||
$sql_query = array(
|
||||
'where_time_clause' => '',
|
||||
'where_clause' => '',
|
||||
'having_clause' => '',
|
||||
);
|
||||
$date_param_mapping = array(
|
||||
'registered' => array(
|
||||
'clause' => 'where',
|
||||
'column' => $table_name . '.date_registered',
|
||||
),
|
||||
'last_active' => array(
|
||||
'clause' => 'where',
|
||||
'column' => $table_name . '.date_last_active',
|
||||
),
|
||||
'last_order' => array(
|
||||
'clause' => 'having',
|
||||
'column' => "MAX( {$wpdb->prefix}wc_order_stats.date_created )",
|
||||
),
|
||||
);
|
||||
$match_operator = $this->get_match_operator( $query_args );
|
||||
$where_time_clauses = array();
|
||||
$having_time_clauses = array();
|
||||
|
||||
foreach ( $date_param_mapping as $query_param => $param_info ) {
|
||||
$subclauses = array();
|
||||
$before_arg = $query_param . '_before';
|
||||
$after_arg = $query_param . '_after';
|
||||
$column_name = $param_info['column'];
|
||||
|
||||
if ( ! empty( $query_args[ $before_arg ] ) ) {
|
||||
$datetime = new DateTime( $query_args[ $before_arg ] );
|
||||
$datetime_str = $datetime->format( WC_Admin_Reports_Interval::$sql_datetime_format );
|
||||
$subclauses[] = "{$column_name} <= '$datetime_str'";
|
||||
}
|
||||
|
||||
if ( ! empty( $query_args[ $after_arg ] ) ) {
|
||||
$datetime = new DateTime( $query_args[ $after_arg ] );
|
||||
$datetime_str = $datetime->format( WC_Admin_Reports_Interval::$sql_datetime_format );
|
||||
$subclauses[] = "{$column_name} >= '$datetime_str'";
|
||||
}
|
||||
|
||||
if ( $subclauses && ( 'where' === $param_info['clause'] ) ) {
|
||||
$where_time_clauses[] = '(' . implode( ' AND ', $subclauses ) . ')';
|
||||
}
|
||||
|
||||
if ( $subclauses && ( 'having' === $param_info['clause'] ) ) {
|
||||
$having_time_clauses[] = '(' . implode( ' AND ', $subclauses ) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
if ( $where_time_clauses ) {
|
||||
$sql_query['where_time_clause'] = ' AND ' . implode( " {$match_operator} ", $where_time_clauses );
|
||||
}
|
||||
|
||||
if ( $having_time_clauses ) {
|
||||
$sql_query['having_clause'] = ' AND ' . implode( " {$match_operator} ", $having_time_clauses );
|
||||
}
|
||||
|
||||
return $sql_query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the database query with parameters used for Customers report: categories and order status.
|
||||
*
|
||||
* @param array $query_args Query arguments supplied by the user.
|
||||
* @return array Array of parameters used for SQL query.
|
||||
*/
|
||||
protected function get_sql_query_params( $query_args ) {
|
||||
global $wpdb;
|
||||
$customer_lookup_table = $wpdb->prefix . self::TABLE_NAME;
|
||||
|
||||
$sql_query_params = $this->get_time_period_sql_params( $query_args, $customer_lookup_table );
|
||||
$sql_query_params = array_merge( $sql_query_params, $this->get_limit_sql_params( $query_args ) );
|
||||
$sql_query_params = array_merge( $sql_query_params, $this->get_order_by_sql_params( $query_args ) );
|
||||
|
||||
$match_operator = $this->get_match_operator( $query_args );
|
||||
$where_clauses = array();
|
||||
$having_clauses = array();
|
||||
|
||||
$exact_match_params = array(
|
||||
'username',
|
||||
'email',
|
||||
'country',
|
||||
);
|
||||
|
||||
foreach ( $exact_match_params as $exact_match_param ) {
|
||||
if ( ! empty( $query_args[ $exact_match_param ] ) ) {
|
||||
$where_clauses[] = $wpdb->prepare(
|
||||
"{$customer_lookup_table}.{$exact_match_param} = %s",
|
||||
$query_args[ $exact_match_param ]
|
||||
); // WPCS: unprepared SQL ok.
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $query_args['name'] ) ) {
|
||||
$where_clauses[] = $wpdb->prepare( "CONCAT_WS( ' ', first_name, last_name ) = %s", $query_args['name'] );
|
||||
}
|
||||
|
||||
$numeric_params = array(
|
||||
'orders_count' => array(
|
||||
'column' => 'COUNT( order_id )',
|
||||
'format' => '%d',
|
||||
),
|
||||
'total_spend' => array(
|
||||
'column' => 'SUM( gross_total )',
|
||||
'format' => '%f',
|
||||
),
|
||||
'avg_order_value' => array(
|
||||
'column' => '( SUM( gross_total ) / COUNT( order_id ) )',
|
||||
'format' => '%f',
|
||||
),
|
||||
);
|
||||
|
||||
foreach ( $numeric_params as $numeric_param => $param_info ) {
|
||||
$subclauses = array();
|
||||
$min_param = $numeric_param . '_min';
|
||||
$max_param = $numeric_param . '_max';
|
||||
|
||||
if ( isset( $query_args[ $min_param ] ) ) {
|
||||
$subclauses[] = $wpdb->prepare(
|
||||
"{$param_info['column']} >= {$param_info['format']}",
|
||||
$query_args[ $min_param ]
|
||||
); // WPCS: unprepared SQL ok.
|
||||
}
|
||||
|
||||
if ( isset( $query_args[ $max_param ] ) ) {
|
||||
$subclauses[] = $wpdb->prepare(
|
||||
"{$param_info['column']} <= {$param_info['format']}",
|
||||
$query_args[ $max_param ]
|
||||
); // WPCS: unprepared SQL ok.
|
||||
}
|
||||
|
||||
if ( $subclauses ) {
|
||||
$having_clauses[] = '(' . implode( ' AND ', $subclauses ) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
if ( $where_clauses ) {
|
||||
$preceding_match = empty( $sql_query_params['where_time_clause'] ) ? ' AND ' : " {$match_operator} ";
|
||||
$sql_query_params['where_clause'] = $preceding_match . implode( " {$match_operator} ", $where_clauses );
|
||||
}
|
||||
|
||||
if ( $having_clauses ) {
|
||||
$preceding_match = empty( $sql_query_params['having_clause'] ) ? ' AND ' : " {$match_operator} ";
|
||||
$sql_query_params['having_clause'] .= $preceding_match . implode( " {$match_operator} ", $having_clauses );
|
||||
}
|
||||
|
||||
return $sql_query_params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the report data based on parameters supplied by the user.
|
||||
*
|
||||
* @param array $query_args Query parameters.
|
||||
* @return stdClass|WP_Error Data.
|
||||
*/
|
||||
public function get_data( $query_args ) {
|
||||
global $wpdb;
|
||||
|
||||
$customers_table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$order_stats_table_name = $wpdb->prefix . 'wc_order_stats';
|
||||
|
||||
// These defaults are only partially applied when used via REST API, as that has its own defaults.
|
||||
$defaults = array(
|
||||
'per_page' => get_option( 'posts_per_page' ),
|
||||
'page' => 1,
|
||||
'order' => 'DESC',
|
||||
'orderby' => 'date_registered',
|
||||
'fields' => '*',
|
||||
);
|
||||
$query_args = wp_parse_args( $query_args, $defaults );
|
||||
|
||||
$cache_key = $this->get_cache_key( $query_args );
|
||||
$data = wp_cache_get( $cache_key, $this->cache_group );
|
||||
|
||||
if ( false === $data ) {
|
||||
$data = (object) array(
|
||||
'data' => array(),
|
||||
'total' => 0,
|
||||
'pages' => 0,
|
||||
'page_no' => 0,
|
||||
);
|
||||
|
||||
$selections = $this->selected_columns( $query_args );
|
||||
$sql_query_params = $this->get_sql_query_params( $query_args );
|
||||
|
||||
$db_records_count = (int) $wpdb->get_var(
|
||||
"SELECT COUNT(*) FROM (
|
||||
SELECT {$customers_table_name}.customer_id
|
||||
FROM
|
||||
{$customers_table_name}
|
||||
LEFT JOIN
|
||||
{$order_stats_table_name}
|
||||
ON
|
||||
{$customers_table_name}.customer_id = {$order_stats_table_name}.customer_id
|
||||
WHERE
|
||||
1=1
|
||||
{$sql_query_params['where_time_clause']}
|
||||
{$sql_query_params['where_clause']}
|
||||
GROUP BY
|
||||
{$customers_table_name}.customer_id
|
||||
HAVING
|
||||
1=1
|
||||
{$sql_query_params['having_clause']}
|
||||
) as tt
|
||||
"
|
||||
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
|
||||
|
||||
$total_pages = (int) ceil( $db_records_count / $sql_query_params['per_page'] );
|
||||
if ( $query_args['page'] < 1 || $query_args['page'] > $total_pages ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$customer_data = $wpdb->get_results(
|
||||
"SELECT
|
||||
{$selections}
|
||||
FROM
|
||||
{$customers_table_name}
|
||||
LEFT JOIN
|
||||
{$order_stats_table_name}
|
||||
ON
|
||||
{$customers_table_name}.customer_id = {$order_stats_table_name}.customer_id
|
||||
WHERE
|
||||
1=1
|
||||
{$sql_query_params['where_time_clause']}
|
||||
{$sql_query_params['where_clause']}
|
||||
GROUP BY
|
||||
{$customers_table_name}.customer_id
|
||||
HAVING
|
||||
1=1
|
||||
{$sql_query_params['having_clause']}
|
||||
ORDER BY
|
||||
{$sql_query_params['order_by_clause']}
|
||||
{$sql_query_params['limit']}
|
||||
",
|
||||
ARRAY_A
|
||||
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
|
||||
|
||||
if ( null === $customer_data ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$customer_data = array_map( array( $this, 'cast_numbers' ), $customer_data );
|
||||
$data = (object) array(
|
||||
'data' => $customer_data,
|
||||
'total' => $db_records_count,
|
||||
'pages' => $total_pages,
|
||||
'page_no' => (int) $query_args['page'],
|
||||
);
|
||||
|
||||
wp_cache_set( $cache_key, $data, $this->cache_group );
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the guest (no user_id) customer ID or creates a new one for
|
||||
* the corresponding billing email in the provided WC_Order
|
||||
*
|
||||
* @param WC_Order $order Order to get/create guest customer data with.
|
||||
* @return int|false The ID of the retrieved/created customer, or false on error.
|
||||
*/
|
||||
public function get_or_create_guest_customer_from_order( $order ) {
|
||||
global $wpdb;
|
||||
|
||||
$email = $order->get_billing_email( 'edit' );
|
||||
|
||||
if ( empty( $email ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$existing_guest = $this->get_guest_by_email( $email );
|
||||
|
||||
if ( $existing_guest ) {
|
||||
return $existing_guest['customer_id'];
|
||||
}
|
||||
|
||||
$result = $wpdb->insert(
|
||||
$wpdb->prefix . self::TABLE_NAME,
|
||||
array(
|
||||
'first_name' => $order->get_billing_first_name( 'edit' ),
|
||||
'last_name' => $order->get_billing_last_name( 'edit' ),
|
||||
'email' => $email,
|
||||
'city' => $order->get_billing_city( 'edit' ),
|
||||
'postcode' => $order->get_billing_postcode( 'edit' ),
|
||||
'country' => $order->get_billing_country( 'edit' ),
|
||||
'date_last_active' => date( 'Y-m-d H:i:s', $order->get_date_created( 'edit' )->getTimestamp() ),
|
||||
),
|
||||
array(
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
)
|
||||
);
|
||||
|
||||
return $result ? $wpdb->insert_id : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a guest (no user_id) customer row by email.
|
||||
*
|
||||
* @param string $email Email address.
|
||||
* @returns false|array Customer array if found, boolean false if not.
|
||||
*/
|
||||
public function get_guest_by_email( $email ) {
|
||||
global $wpdb;
|
||||
|
||||
$table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$guest_row = $wpdb->get_row(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM {$table_name} WHERE email = %s AND user_id IS NULL LIMIT 1",
|
||||
$email
|
||||
),
|
||||
ARRAY_A
|
||||
); // WPCS: unprepared SQL ok.
|
||||
|
||||
if ( $guest_row ) {
|
||||
return $this->cast_numbers( $guest_row );
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a registered customer row by user_id.
|
||||
*
|
||||
* @param string|int $user_id User ID.
|
||||
* @returns false|array Customer array if found, boolean false if not.
|
||||
*/
|
||||
public function get_customer_by_user_id( $user_id ) {
|
||||
global $wpdb;
|
||||
|
||||
$table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$customer = $wpdb->get_row(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM {$table_name} WHERE user_id = %d LIMIT 1",
|
||||
$user_id
|
||||
),
|
||||
ARRAY_A
|
||||
); // WPCS: unprepared SQL ok.
|
||||
|
||||
if ( $customer ) {
|
||||
return $this->cast_numbers( $customer );
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a registered customer row id by user_id.
|
||||
*
|
||||
* @param string|int $user_id User ID.
|
||||
* @returns false|int Customer ID if found, boolean false if not.
|
||||
*/
|
||||
public static function get_customer_id_by_user_id( $user_id ) {
|
||||
global $wpdb;
|
||||
|
||||
$table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$customer_id = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT customer_id FROM {$table_name} WHERE user_id = %d LIMIT 1",
|
||||
$user_id
|
||||
)
|
||||
); // WPCS: unprepared SQL ok.
|
||||
|
||||
return $customer_id ? (int) $customer_id : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the database with customer data.
|
||||
*
|
||||
* @param int $user_id WP User ID to update customer data for.
|
||||
* @return int|bool|null Number or rows modified or false on failure.
|
||||
*/
|
||||
public static function update_registered_customer( $user_id ) {
|
||||
global $wpdb;
|
||||
|
||||
$customer = new WC_Customer( $user_id );
|
||||
|
||||
if ( $customer->get_id() != $user_id ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$last_active = $customer->get_meta( 'wc_last_active', true, 'edit' );
|
||||
$data = array(
|
||||
'user_id' => $user_id,
|
||||
'username' => $customer->get_username( 'edit' ),
|
||||
'first_name' => $customer->get_first_name( 'edit' ),
|
||||
'last_name' => $customer->get_last_name( 'edit' ),
|
||||
'email' => $customer->get_email( 'edit' ),
|
||||
'city' => $customer->get_billing_city( 'edit' ),
|
||||
'postcode' => $customer->get_billing_postcode( 'edit' ),
|
||||
'country' => $customer->get_billing_country( 'edit' ),
|
||||
'date_registered' => date( 'Y-m-d H:i:s', $customer->get_date_created( 'edit' )->getTimestamp() ),
|
||||
'date_last_active' => $last_active ? date( 'Y-m-d H:i:s', $last_active ) : '',
|
||||
);
|
||||
$format = array(
|
||||
'%d',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
);
|
||||
|
||||
$customer_id = self::get_customer_id_by_user_id( $user_id );
|
||||
|
||||
if ( $customer_id ) {
|
||||
// Preserve customer_id for existing user_id.
|
||||
$data['customer_id'] = $customer_id;
|
||||
$format[] = '%d';
|
||||
}
|
||||
|
||||
return $wpdb->replace( $wpdb->prefix . self::TABLE_NAME, $data, $format );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns string to be used as cache key for the data.
|
||||
*
|
||||
* @param array $params Query parameters.
|
||||
* @return string
|
||||
*/
|
||||
protected function get_cache_key( $params ) {
|
||||
return 'woocommerce_' . self::TABLE_NAME . '_' . md5( wp_json_encode( $params ) );
|
||||
}
|
||||
|
||||
}
|
|
@ -180,6 +180,71 @@ class WC_Admin_Reports_Data_Store {
|
|||
$data->intervals = array_slice( $data->intervals, $offset, $count );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns expected number of items on the page in case of date ordering.
|
||||
*
|
||||
* @param int $expected_interval_count Expected number of intervals in total.
|
||||
* @param int $items_per_page Number of items per page.
|
||||
* @param int $page_no Page number.
|
||||
*
|
||||
* @return float|int
|
||||
*/
|
||||
protected function expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no ) {
|
||||
$total_pages = (int) ceil( $expected_interval_count / $items_per_page );
|
||||
if ( $page_no < $total_pages ) {
|
||||
return $items_per_page;
|
||||
} elseif ( $page_no === $total_pages ) {
|
||||
return $expected_interval_count - ( $page_no - 1 ) * $items_per_page;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if there are any intervals that need to be filled in the response.
|
||||
*
|
||||
* @param int $expected_interval_count Expected number of intervals in total.
|
||||
* @param int $db_records Total number of records for given period in the database.
|
||||
* @param int $items_per_page Number of items per page.
|
||||
* @param int $page_no Page number.
|
||||
* @param string $order asc or desc.
|
||||
* @param string $order_by Column by which the result will be sorted.
|
||||
* @param int $intervals_count Number of records for given (possibly shortened) time interval.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function intervals_missing( $expected_interval_count, $db_records, $items_per_page, $page_no, $order, $order_by, $intervals_count ) {
|
||||
if ( $expected_interval_count > $db_records ) {
|
||||
if ( 'date' === $order_by ) {
|
||||
$expected_intervals_on_page = $this->expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no );
|
||||
if ( $intervals_count < $expected_intervals_on_page ) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if ( 'desc' === $order ) {
|
||||
if ( $page_no > floor( $db_records / $items_per_page ) ) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} elseif ( 'asc' === $order ) {
|
||||
if ( $page_no <= ceil( ( $expected_interval_count - $db_records ) / $items_per_page ) ) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Invalid ordering.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the LIMIT query part for Intervals query of the report.
|
||||
*
|
||||
|
@ -346,7 +411,7 @@ class WC_Admin_Reports_Data_Store {
|
|||
* @param string $status Order status.
|
||||
* @return string
|
||||
*/
|
||||
protected function normalize_order_status( $status ) {
|
||||
protected static function normalize_order_status( $status ) {
|
||||
$status = trim( $status );
|
||||
return 'wc-' . $status;
|
||||
}
|
||||
|
@ -709,14 +774,14 @@ class WC_Admin_Reports_Data_Store {
|
|||
if ( isset( $query_args['status_is'] ) && is_array( $query_args['status_is'] ) && count( $query_args['status_is'] ) > 0 ) {
|
||||
$allowed_statuses = array_map( array( $this, 'normalize_order_status' ), $query_args['status_is'] );
|
||||
if ( $allowed_statuses ) {
|
||||
$subqueries[] = "{$wpdb->prefix}posts.post_status IN ( '" . implode( "','", $allowed_statuses ) . "' )";
|
||||
$subqueries[] = "{$wpdb->prefix}wc_order_stats.status IN ( '" . implode( "','", $allowed_statuses ) . "' )";
|
||||
}
|
||||
}
|
||||
|
||||
if ( isset( $query_args['status_is_not'] ) && is_array( $query_args['status_is_not'] ) && count( $query_args['status_is_not'] ) > 0 ) {
|
||||
$forbidden_statuses = array_map( array( $this, 'normalize_order_status' ), $query_args['status_is_not'] );
|
||||
if ( $forbidden_statuses ) {
|
||||
$subqueries[] = "{$wpdb->prefix}posts.post_status NOT IN ( '" . implode( "','", $forbidden_statuses ) . "' )";
|
||||
$subqueries[] = "{$wpdb->prefix}wc_order_stats.status NOT IN ( '" . implode( "','", $forbidden_statuses ) . "' )";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -73,7 +73,6 @@ class WC_Admin_Reports_Downloads_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
|
||||
$sql_query_params = $this->get_time_period_sql_params( $query_args, $lookup_table );
|
||||
$sql_query_params = array_merge( $sql_query_params, $this->get_limit_sql_params( $query_args ) );
|
||||
$sql_query_params = array_merge( $sql_query_params, $this->get_order_by_sql_params( $query_args ) );
|
||||
|
||||
$included_products = $this->get_included_products( $query_args );
|
||||
$excluded_products = $this->get_excluded_products( $query_args );
|
||||
|
@ -163,6 +162,7 @@ class WC_Admin_Reports_Downloads_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
}
|
||||
|
||||
$sql_query_params['from_clause'] .= " JOIN {$wpdb->prefix}woocommerce_downloadable_product_permissions as product_permissions ON {$lookup_table}.permission_id = product_permissions.permission_id";
|
||||
$sql_query_params = $this->get_order_by( $query_args, $sql_query_params );
|
||||
|
||||
return $sql_query_params;
|
||||
}
|
||||
|
@ -240,14 +240,20 @@ class WC_Admin_Reports_Downloads_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
* Fills ORDER BY clause of SQL request based on user supplied parameters.
|
||||
*
|
||||
* @param array $query_args Parameters supplied by the user.
|
||||
* @param array $sql_query Current SQL query array.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_order_by_sql_params( $query_args ) {
|
||||
protected function get_order_by( $query_args, $sql_query ) {
|
||||
global $wpdb;
|
||||
$sql_query['order_by_clause'] = '';
|
||||
if ( isset( $query_args['orderby'] ) ) {
|
||||
$sql_query['order_by_clause'] = $this->normalize_order_by( $query_args['orderby'] );
|
||||
}
|
||||
|
||||
if ( false !== strpos( $sql_query['order_by_clause'], '_products' ) ) {
|
||||
$sql_query['from_clause'] .= " JOIN {$wpdb->prefix}posts AS _products ON product_permissions.product_id = _products.ID";
|
||||
}
|
||||
|
||||
if ( isset( $query_args['order'] ) ) {
|
||||
$sql_query['order_by_clause'] .= ' ' . $query_args['order'];
|
||||
} else {
|
||||
|
@ -377,6 +383,10 @@ class WC_Admin_Reports_Downloads_Data_Store extends WC_Admin_Reports_Data_Store
|
|||
return $wpdb->prefix . 'wc_download_log.timestamp';
|
||||
}
|
||||
|
||||
if ( 'product' === $order_by ) {
|
||||
return '_products.post_title';
|
||||
}
|
||||
|
||||
return $order_by;
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,232 @@
|
|||
<?php
|
||||
/**
|
||||
* WC_Admin_Reports_Downloads_Data_Store class file.
|
||||
*
|
||||
* @package WooCommerce Admin/Classes
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* WC_Admin_Reports_Downloads_Data_Store.
|
||||
*/
|
||||
class WC_Admin_Reports_Downloads_Stats_Data_Store extends WC_Admin_Reports_Downloads_Data_Store implements WC_Admin_Reports_Data_Store_Interface {
|
||||
|
||||
/**
|
||||
* Mapping columns to data type to return correct response types.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $column_types = array(
|
||||
'download_count' => 'intval',
|
||||
);
|
||||
|
||||
/**
|
||||
* SQL columns to select in the db query and their mapping to SQL code.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $report_columns = array(
|
||||
'download_count' => 'COUNT(DISTINCT download_log_id) as download_count',
|
||||
);
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function __construct() {
|
||||
global $wpdb;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the report data based on parameters supplied by the user.
|
||||
*
|
||||
* @param array $query_args Query parameters.
|
||||
* @return stdClass|WP_Error Data.
|
||||
*/
|
||||
public function get_data( $query_args ) {
|
||||
global $wpdb;
|
||||
|
||||
$table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$now = time();
|
||||
$week_back = $now - WEEK_IN_SECONDS;
|
||||
|
||||
// These defaults are only partially applied when used via REST API, as that has its own defaults.
|
||||
$defaults = array(
|
||||
'per_page' => get_option( 'posts_per_page' ),
|
||||
'page' => 1,
|
||||
'order' => 'DESC',
|
||||
'orderby' => 'date',
|
||||
'fields' => '*',
|
||||
'interval' => 'week',
|
||||
);
|
||||
$query_args = wp_parse_args( $query_args, $defaults );
|
||||
|
||||
if ( empty( $query_args['before'] ) ) {
|
||||
$query_args['before'] = date( WC_Admin_Reports_Interval::$iso_datetime_format, $now );
|
||||
}
|
||||
if ( empty( $query_args['after'] ) ) {
|
||||
$query_args['after'] = date( WC_Admin_Reports_Interval::$iso_datetime_format, $week_back );
|
||||
}
|
||||
|
||||
$cache_key = $this->get_cache_key( $query_args );
|
||||
$data = wp_cache_get( $cache_key, $this->cache_group );
|
||||
|
||||
if ( false === $data ) {
|
||||
$selections = $this->selected_columns( $query_args );
|
||||
$sql_query_params = $this->get_sql_query_params( $query_args );
|
||||
$totals_query = array_merge( array(), $this->get_time_period_sql_params( $query_args, $table_name ) );
|
||||
$intervals_query = array_merge( array(), $this->get_intervals_sql_params( $query_args, $table_name ) );
|
||||
|
||||
$totals_query['where_clause'] .= $sql_query_params['where_clause'];
|
||||
$totals_query['from_clause'] .= $sql_query_params['from_clause'];
|
||||
$intervals_query['where_clause'] .= $sql_query_params['where_clause'];
|
||||
$intervals_query['from_clause'] .= $sql_query_params['from_clause'];
|
||||
$intervals_query['select_clause'] = str_replace( 'date_created', 'timestamp', $intervals_query['select_clause'] );
|
||||
$intervals_query['where_time_clause'] = str_replace( 'date_created', 'timestamp', $intervals_query['where_time_clause'] );
|
||||
|
||||
$db_intervals = $wpdb->get_col(
|
||||
"SELECT
|
||||
{$intervals_query['select_clause']} AS time_interval
|
||||
FROM
|
||||
{$table_name}
|
||||
{$intervals_query['from_clause']}
|
||||
WHERE
|
||||
1=1
|
||||
{$intervals_query['where_time_clause']}
|
||||
{$intervals_query['where_clause']}
|
||||
GROUP BY
|
||||
time_interval"
|
||||
); // WPCS: cache ok, DB call ok, , unprepared SQL ok.
|
||||
|
||||
$db_records_count = count( $db_intervals );
|
||||
|
||||
$expected_interval_count = WC_Admin_Reports_Interval::intervals_between( $query_args['after'], $query_args['before'], $query_args['interval'] );
|
||||
$total_pages = (int) ceil( $expected_interval_count / $intervals_query['per_page'] );
|
||||
if ( $query_args['page'] < 1 || $query_args['page'] > $total_pages ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$this->update_intervals_sql_params( $intervals_query, $query_args, $db_records_count, $expected_interval_count );
|
||||
$intervals_query['where_time_clause'] = str_replace( 'date_created', 'timestamp', $intervals_query['where_time_clause'] );
|
||||
|
||||
$totals = $wpdb->get_results(
|
||||
"SELECT
|
||||
{$selections}
|
||||
FROM
|
||||
{$table_name}
|
||||
{$totals_query['from_clause']}
|
||||
WHERE
|
||||
1=1
|
||||
{$totals_query['where_time_clause']}
|
||||
{$totals_query['where_clause']}",
|
||||
ARRAY_A
|
||||
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
|
||||
|
||||
if ( null === $totals ) {
|
||||
return new WP_Error( 'woocommerce_reports_downloads_stats_result_failed', __( 'Sorry, fetching downloads data failed.', 'wc-admin' ) );
|
||||
}
|
||||
|
||||
if ( '' !== $selections ) {
|
||||
$selections = ', ' . $selections;
|
||||
}
|
||||
|
||||
$intervals = $wpdb->get_results(
|
||||
"SELECT
|
||||
MAX(timestamp) AS datetime_anchor,
|
||||
{$intervals_query['select_clause']} AS time_interval
|
||||
{$selections}
|
||||
FROM
|
||||
{$table_name}
|
||||
{$intervals_query['from_clause']}
|
||||
WHERE
|
||||
1=1
|
||||
{$intervals_query['where_time_clause']}
|
||||
{$intervals_query['where_clause']}
|
||||
GROUP BY
|
||||
time_interval
|
||||
ORDER BY
|
||||
{$intervals_query['order_by_clause']}
|
||||
{$intervals_query['limit']}",
|
||||
ARRAY_A
|
||||
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
|
||||
|
||||
if ( null === $intervals ) {
|
||||
return new WP_Error( 'woocommerce_reports_downloads_stats_result_failed', __( 'Sorry, fetching downloads data failed.', 'wc-admin' ) );
|
||||
}
|
||||
|
||||
$totals = (object) $this->cast_numbers( $totals[0] );
|
||||
$data = (object) array(
|
||||
'totals' => $totals,
|
||||
'intervals' => $intervals,
|
||||
'total' => $expected_interval_count,
|
||||
'pages' => $total_pages,
|
||||
'page_no' => (int) $query_args['page'],
|
||||
);
|
||||
|
||||
if ( $this->intervals_missing( $expected_interval_count, $db_records_count, $intervals_query['per_page'], $query_args['page'], $query_args['order'], $query_args['orderby'], count( $intervals ) ) ) {
|
||||
$this->fill_in_missing_intervals( $db_intervals, $query_args['adj_after'], $query_args['adj_before'], $query_args['interval'], $data );
|
||||
$this->sort_intervals( $data, $query_args['orderby'], $query_args['order'] );
|
||||
$this->remove_extra_records( $data, $query_args['page'], $intervals_query['per_page'], $db_records_count, $expected_interval_count, $query_args['orderby'] );
|
||||
} else {
|
||||
$this->update_interval_boundary_dates( $query_args['after'], $query_args['before'], $query_args['interval'], $data->intervals );
|
||||
}
|
||||
$this->create_interval_subtotals( $data->intervals );
|
||||
|
||||
wp_cache_set( $cache_key, $data, $this->cache_group );
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns string to be used as cache key for the data.
|
||||
*
|
||||
* @param array $params Query parameters.
|
||||
* @return string
|
||||
*/
|
||||
protected function get_cache_key( $params ) {
|
||||
return 'woocommerce_' . self::TABLE_NAME . '_stats_' . md5( wp_json_encode( $params ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts intervals according to user's request.
|
||||
*
|
||||
* They are pre-sorted in SQL, but after adding gaps, they need to be sorted including the added ones.
|
||||
*
|
||||
* @param stdClass $data Data object, must contain an array under $data->intervals.
|
||||
* @param string $sort_by Ordering property.
|
||||
* @param string $direction DESC/ASC.
|
||||
*/
|
||||
protected function sort_intervals( &$data, $sort_by, $direction ) {
|
||||
if ( 'date' === $sort_by ) {
|
||||
$this->order_by = 'time_interval';
|
||||
} else {
|
||||
$this->order_by = $sort_by;
|
||||
}
|
||||
|
||||
$this->order = $direction;
|
||||
usort( $data->intervals, array( $this, 'interval_cmp' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two report data objects by pre-defined object property and ASC/DESC ordering.
|
||||
*
|
||||
* @param stdClass $a Object a.
|
||||
* @param stdClass $b Object b.
|
||||
* @return string
|
||||
*/
|
||||
protected function interval_cmp( $a, $b ) {
|
||||
if ( '' === $this->order_by || '' === $this->order ) {
|
||||
return 0;
|
||||
}
|
||||
if ( $a[ $this->order_by ] === $b[ $this->order_by ] ) {
|
||||
return 0;
|
||||
} elseif ( $a[ $this->order_by ] > $b[ $this->order_by ] ) {
|
||||
return strtolower( $this->order ) === 'desc' ? -1 : 1;
|
||||
} elseif ( $a[ $this->order_by ] < $b[ $this->order_by ] ) {
|
||||
return strtolower( $this->order ) === 'desc' ? 1 : -1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -171,10 +171,8 @@ class WC_Admin_Reports_Orders_Data_Store extends WC_Admin_Reports_Data_Store imp
|
|||
)";
|
||||
}
|
||||
|
||||
// TODO: move order status to wc_order_stats so that JOIN is not necessary.
|
||||
$order_status_filter = $this->get_status_subquery( $query_args, $operator );
|
||||
if ( $order_status_filter ) {
|
||||
$from_clause .= " JOIN {$wpdb->prefix}posts ON {$orders_stats_table}.order_id = {$wpdb->prefix}posts.ID";
|
||||
$where_filters[] = $order_status_filter;
|
||||
}
|
||||
|
||||
|
@ -1268,7 +1266,7 @@ class WC_Admin_Reports_Orders_Data_Store extends WC_Admin_Reports_Data_Store imp
|
|||
return;
|
||||
}
|
||||
|
||||
$data = array(
|
||||
$data = array(
|
||||
'order_id' => $order->get_id(),
|
||||
'date_created' => $order->get_date_created()->date( 'Y-m-d H:i:s' ),
|
||||
'num_items_sold' => self::get_num_items_sold( $order ),
|
||||
|
@ -1279,24 +1277,48 @@ class WC_Admin_Reports_Orders_Data_Store extends WC_Admin_Reports_Data_Store imp
|
|||
'shipping_total' => $order->get_shipping_total(),
|
||||
'net_total' => (float) $order->get_total() - (float) $order->get_total_tax() - (float) $order->get_shipping_total(),
|
||||
'returning_customer' => self::is_returning_customer( $order ),
|
||||
'status' => self::normalize_order_status( $order->get_status() ),
|
||||
);
|
||||
$format = array(
|
||||
'%d',
|
||||
'%s',
|
||||
'%d',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%d',
|
||||
'%s',
|
||||
);
|
||||
|
||||
// Ensure we're associating this order with a Customer in the lookup table.
|
||||
$order_user_id = $order->get_customer_id();
|
||||
$customers_data_store = new WC_Admin_Reports_Customers_Data_Store();
|
||||
|
||||
if ( 0 === $order_user_id ) {
|
||||
$email = $order->get_billing_email( 'edit' );
|
||||
|
||||
if ( $email ) {
|
||||
$customer_id = $customers_data_store->get_or_create_guest_customer_from_order( $order );
|
||||
|
||||
if ( $customer_id ) {
|
||||
$data['customer_id'] = $customer_id;
|
||||
$format[] = '%d';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$customer = $customers_data_store->get_customer_by_user_id( $order_user_id );
|
||||
|
||||
if ( $customer && $customer['customer_id'] ) {
|
||||
$data['customer_id'] = $customer['customer_id'];
|
||||
$format[] = '%d';
|
||||
}
|
||||
}
|
||||
|
||||
// Update or add the information to the DB.
|
||||
return $wpdb->replace(
|
||||
$table_name,
|
||||
$data,
|
||||
array(
|
||||
'%d',
|
||||
'%s',
|
||||
'%d',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
)
|
||||
);
|
||||
return $wpdb->replace( $table_name, $data, $format );
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -100,6 +100,10 @@ class WC_Admin_Reports_Products_Data_Store extends WC_Admin_Reports_Data_Store i
|
|||
$sql_query['from_clause'] .= " JOIN {$wpdb->prefix}posts AS _products ON {$order_product_lookup_table}.product_id = _products.ID";
|
||||
}
|
||||
|
||||
if ( 'postmeta.meta_value' === $sql_query['order_by_clause'] ) {
|
||||
$sql_query['from_clause'] .= " JOIN {$wpdb->prefix}postmeta AS postmeta ON {$order_product_lookup_table}.product_id = postmeta.post_id AND postmeta.meta_key = '_sku'";
|
||||
}
|
||||
|
||||
if ( isset( $query_args['order'] ) ) {
|
||||
$sql_query['order_by_clause'] .= ' ' . $query_args['order'];
|
||||
} else {
|
||||
|
@ -150,7 +154,9 @@ class WC_Admin_Reports_Products_Data_Store extends WC_Admin_Reports_Data_Store i
|
|||
if ( 'product_name' === $order_by ) {
|
||||
return '_products.post_title';
|
||||
}
|
||||
|
||||
if ( 'sku' === $order_by ) {
|
||||
return 'postmeta.meta_value';
|
||||
}
|
||||
return $order_by;
|
||||
}
|
||||
|
||||
|
|
|
@ -399,6 +399,11 @@ function wc_admin_get_user_data_fields() {
|
|||
'revenue_report_columns',
|
||||
'taxes_report_columns',
|
||||
'variations_report_columns',
|
||||
'dashboard_charts',
|
||||
'dashboard_chart_type',
|
||||
'dashboard_chart_interval',
|
||||
'dashboard_leaderboards',
|
||||
'dashboard_leaderboard_rows',
|
||||
);
|
||||
|
||||
return apply_filters( 'wc_admin_get_user_data_fields', $user_data_fields );
|
||||
|
|
|
@ -180,9 +180,6 @@ function wc_admin_print_script_settings() {
|
|||
'embedBreadcrumbs' => wc_admin_get_embed_breadcrumbs(),
|
||||
'siteLocale' => esc_attr( get_bloginfo( 'language' ) ),
|
||||
'currency' => wc_admin_currency_settings(),
|
||||
'date' => array(
|
||||
'dow' => get_option( 'start_of_week', 0 ),
|
||||
),
|
||||
'orderStatuses' => format_order_statuses( wc_get_order_statuses() ),
|
||||
'stockStatuses' => wc_get_product_stock_status_options(),
|
||||
'siteTitle' => get_bloginfo( 'name' ),
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "wc-admin",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"main": "js/index.js",
|
||||
"author": "Automattic",
|
||||
"license": "GPL-2.0-or-later",
|
||||
|
@ -39,6 +39,7 @@
|
|||
"test": "wp-scripts test-unit-js --config tests/js/jest.config.json",
|
||||
"test:watch": "npm run test -- --watch",
|
||||
"test:update-snapshots": "jest --updateSnapshot --config tests/js/jest.config.json",
|
||||
"jest:update": "jest -u --config=tests/js/jest.config.json",
|
||||
"docs": "node ./bin/generate-docs",
|
||||
"publish:check": "npm run build:packages && lerna updated",
|
||||
"publish:dev": "npm run build:packages && lerna publish from-package --npm-tag next",
|
||||
|
@ -52,10 +53,10 @@
|
|||
"@babel/runtime-corejs2": "7.2.0",
|
||||
"@wordpress/babel-plugin-import-jsx-pragma": "1.1.2",
|
||||
"@wordpress/babel-plugin-makepot": "2.1.2",
|
||||
"@wordpress/babel-preset-default": "2.1.0",
|
||||
"@wordpress/babel-preset-default": "3.0.1",
|
||||
"@wordpress/browserslist-config": "2.2.2",
|
||||
"@wordpress/custom-templated-path-webpack-plugin": "1.1.5",
|
||||
"@wordpress/jest-preset-default": "2.0.6",
|
||||
"@wordpress/jest-preset-default": "3.0.3",
|
||||
"@wordpress/postcss-themes": "1.0.4",
|
||||
"ast-types": "0.11.7",
|
||||
"autoprefixer": "9.4.3",
|
||||
|
@ -83,8 +84,8 @@
|
|||
"grunt": "1.0.3",
|
||||
"grunt-checktextdomain": "1.0.1",
|
||||
"grunt-wp-i18n": "1.0.3",
|
||||
"husky": "1.2.1",
|
||||
"lerna": "3.8.0",
|
||||
"husky": "1.3.1",
|
||||
"lerna": "3.8.4",
|
||||
"node-sass": "4.11.0",
|
||||
"postcss-color-function": "4.0.1",
|
||||
"postcss-loader": "3.0.0",
|
||||
|
@ -101,21 +102,21 @@
|
|||
"style-loader": "0.23.1",
|
||||
"stylelint": "9.9.0",
|
||||
"stylelint-config-wordpress": "13.1.0",
|
||||
"webpack": "4.28.2",
|
||||
"webpack": "4.28.3",
|
||||
"webpack-cli": "3.1.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fresh-data/framework": "^0.5.1",
|
||||
"@wordpress/api-fetch": "2.2.2",
|
||||
"@wordpress/components": "3.0.0",
|
||||
"@wordpress/data": "3.1.0",
|
||||
"@wordpress/date": "2.1.0",
|
||||
"@wordpress/element": "2.1.5",
|
||||
"@wordpress/api-fetch": "2.2.6",
|
||||
"@wordpress/components": "7.0.5",
|
||||
"@wordpress/data": "4.2.0",
|
||||
"@wordpress/date": "3.0.1",
|
||||
"@wordpress/element": "2.1.8",
|
||||
"@wordpress/hooks": "2.0.3",
|
||||
"@wordpress/html-entities": "2.0.2",
|
||||
"@wordpress/i18n": "2.0.0",
|
||||
"@wordpress/keycodes": "2.0.3",
|
||||
"@wordpress/scripts": "2.4.1",
|
||||
"@wordpress/html-entities": "2.0.4",
|
||||
"@wordpress/i18n": "3.1.0",
|
||||
"@wordpress/keycodes": "2.0.5",
|
||||
"@wordpress/scripts": "2.4.4",
|
||||
"@wordpress/viewport": "^2.0.7",
|
||||
"browser-filesaver": "^1.1.1",
|
||||
"classnames": "^2.2.5",
|
||||
|
@ -135,7 +136,7 @@
|
|||
"html-to-react": "1.3.4",
|
||||
"interpolate-components": "1.1.1",
|
||||
"lodash": "^4.17.11",
|
||||
"marked": "0.5.2",
|
||||
"marked": "0.6.0",
|
||||
"prismjs": "^1.15.0",
|
||||
"qs": "^6.5.2",
|
||||
"react-click-outside": "3.0.1",
|
||||
|
|
|
@ -3,7 +3,11 @@
|
|||
- Add order number autocompleter to search component
|
||||
- Add order number, username, and IP address filters to the downloads report.
|
||||
- Added `interactive` prop for `d3chart/legend` to signal if legend items are clickable or not.
|
||||
- Fix for undefined ref in `d3chart/legend`
|
||||
- Fix for undefined ref in `d3chart/legend`.
|
||||
- Added three news props to `<Chart>`:
|
||||
- `interactiveLegend`: whether legend items are clickable or not. Defaults to true.
|
||||
- `legendPosition`: can be `top`, `side` or `bottom`. If not specified, it's calculated based on `mode` and viewport width.
|
||||
- `showHeaderControls`: whether the header controls must be visible. Defaults to true.
|
||||
|
||||
# 1.3.0
|
||||
|
||||
|
|
|
@ -26,13 +26,13 @@
|
|||
"@woocommerce/currency": "^1.0.0",
|
||||
"@woocommerce/date": "^1.0.3",
|
||||
"@woocommerce/navigation": "^1.1.0",
|
||||
"@wordpress/components": "3.0.0",
|
||||
"@wordpress/components": "7.0.5",
|
||||
"@wordpress/compose": "3.0.0",
|
||||
"@wordpress/date": "2.1.0",
|
||||
"@wordpress/element": "2.1.5",
|
||||
"@wordpress/html-entities": "2.0.2",
|
||||
"@wordpress/i18n": "2.0.0",
|
||||
"@wordpress/keycodes": "2.0.2",
|
||||
"@wordpress/date": "3.0.1",
|
||||
"@wordpress/element": "2.1.8",
|
||||
"@wordpress/html-entities": "2.0.4",
|
||||
"@wordpress/i18n": "3.1.0",
|
||||
"@wordpress/keycodes": "2.0.5",
|
||||
"@wordpress/viewport": "^2.0.7",
|
||||
"classnames": "^2.2.5",
|
||||
"core-js": "2.6.1",
|
||||
|
|
|
@ -118,6 +118,7 @@ class DateRange extends Component {
|
|||
),
|
||||
shortDateFormat
|
||||
) }
|
||||
onFocus={ () => this.onFocusChange( 'startDate' ) }
|
||||
/>
|
||||
<div className="woocommerce-calendar__inputs-to">{ __( 'to', 'wc-admin' ) }</div>
|
||||
<DateInput
|
||||
|
@ -133,6 +134,7 @@ class DateRange extends Component {
|
|||
),
|
||||
shortDateFormat
|
||||
) }
|
||||
onFocus={ () => this.onFocusChange( 'endDate' ) }
|
||||
/>
|
||||
</div>
|
||||
<div className="woocommerce-calendar__react-dates">
|
||||
|
@ -150,7 +152,6 @@ class DateRange extends Component {
|
|||
noBorder
|
||||
initialVisibleMonth={ this.setTnitialVisibleMonth( isDoubleCalendar, before ) }
|
||||
phrases={ phrases }
|
||||
firstDayOfWeek={ Number( wcSettings.date.dow ) }
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -8,31 +8,31 @@ import { Component, createRef } from '@wordpress/element';
|
|||
import PropTypes from 'prop-types';
|
||||
import classNames from 'classnames';
|
||||
import { timeFormat as d3TimeFormat, utcParse as d3UTCParse } from 'd3-time-format';
|
||||
import { select as d3Select } from 'd3-selection';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import D3Base from './d3base';
|
||||
import {
|
||||
drawAxis,
|
||||
drawBars,
|
||||
drawLines,
|
||||
getDateSpaces,
|
||||
getOrderedKeys,
|
||||
getLine,
|
||||
getLineData,
|
||||
getXTicks,
|
||||
getUniqueKeys,
|
||||
getUniqueDates,
|
||||
getFormatter,
|
||||
} from './utils';
|
||||
import {
|
||||
getXScale,
|
||||
getXGroupScale,
|
||||
getXLineScale,
|
||||
getYMax,
|
||||
getYScale,
|
||||
getYTickOffset,
|
||||
getFormatter,
|
||||
} from './utils';
|
||||
} from './utils/scales';
|
||||
import { drawAxis, getXTicks } from './utils/axis';
|
||||
import { drawBars } from './utils/bar-chart';
|
||||
import { drawLines } from './utils/line-chart';
|
||||
|
||||
/**
|
||||
* A simple D3 line and bar chart component for timeseries data in React.
|
||||
|
@ -70,23 +70,48 @@ class D3Chart extends Component {
|
|||
}
|
||||
|
||||
drawChart( node ) {
|
||||
const { data, margin, type } = this.props;
|
||||
const params = this.getParams();
|
||||
const adjParams = Object.assign( {}, params, {
|
||||
height: params.adjHeight,
|
||||
width: params.adjWidth,
|
||||
tooltip: d3Select( this.tooltipRef.current ),
|
||||
valueType: params.valueType,
|
||||
setTimeout( () => {
|
||||
const { data, margin, type } = this.props;
|
||||
const params = this.getParams();
|
||||
const adjParams = Object.assign( {}, params, {
|
||||
height: params.adjHeight,
|
||||
width: params.adjWidth,
|
||||
tooltip: this.tooltipRef.current,
|
||||
valueType: params.valueType,
|
||||
} );
|
||||
|
||||
const g = node
|
||||
.attr( 'id', 'chart' )
|
||||
.append( 'g' )
|
||||
.attr( 'transform', `translate(${ margin.left },${ margin.top })` );
|
||||
|
||||
drawAxis( g, adjParams );
|
||||
type === 'line' && drawLines( g, data, adjParams );
|
||||
type === 'bar' && drawBars( g, data, adjParams );
|
||||
} );
|
||||
}
|
||||
|
||||
const g = node
|
||||
.attr( 'id', 'chart' )
|
||||
.append( 'g' )
|
||||
.attr( 'transform', `translate(${ margin.left },${ margin.top })` );
|
||||
shouldBeCompact() {
|
||||
const { data, margin, type, width } = this.props;
|
||||
if ( type !== 'bar' ) {
|
||||
return false;
|
||||
}
|
||||
const widthWithoutMargins = width - margin.left - margin.right;
|
||||
const columnsPerDate = data && data.length ? Object.keys( data[ 0 ] ).length - 1 : 0;
|
||||
const minimumWideWidth = data.length * ( columnsPerDate + 1 );
|
||||
|
||||
drawAxis( g, adjParams );
|
||||
type === 'line' && drawLines( g, data, adjParams );
|
||||
type === 'bar' && drawBars( g, data, adjParams );
|
||||
return widthWithoutMargins < minimumWideWidth;
|
||||
}
|
||||
|
||||
getWidth() {
|
||||
const { data, margin, type, width } = this.props;
|
||||
if ( type !== 'bar' ) {
|
||||
return width;
|
||||
}
|
||||
const columnsPerDate = data && data.length ? Object.keys( data[ 0 ] ).length - 1 : 0;
|
||||
const minimumWidth = this.shouldBeCompact() ? data.length * columnsPerDate : data.length * ( columnsPerDate + 1 );
|
||||
|
||||
return Math.max( width, minimumWidth + margin.left + margin.right );
|
||||
}
|
||||
|
||||
getParams() {
|
||||
|
@ -104,14 +129,14 @@ class D3Chart extends Component {
|
|||
tooltipValueFormat,
|
||||
tooltipTitle,
|
||||
type,
|
||||
width,
|
||||
xFormat,
|
||||
x2Format,
|
||||
yFormat,
|
||||
valueType,
|
||||
} = this.props;
|
||||
const adjHeight = height - margin.top - margin.bottom;
|
||||
const adjWidth = width - margin.left - margin.right;
|
||||
const adjWidth = this.getWidth() - margin.left - margin.right;
|
||||
const compact = this.shouldBeCompact();
|
||||
const uniqueKeys = getUniqueKeys( data );
|
||||
const newOrderedKeys = orderedKeys || getOrderedKeys( data, uniqueKeys );
|
||||
const lineData = getLineData( data, newOrderedKeys );
|
||||
|
@ -120,7 +145,7 @@ class D3Chart extends Component {
|
|||
const parseDate = d3UTCParse( dateParser );
|
||||
const uniqueDates = getUniqueDates( lineData, parseDate );
|
||||
const xLineScale = getXLineScale( uniqueDates, adjWidth );
|
||||
const xScale = getXScale( uniqueDates, adjWidth );
|
||||
const xScale = getXScale( uniqueDates, adjWidth, compact );
|
||||
const xTicks = getXTicks( uniqueDates, adjWidth, mode, interval );
|
||||
return {
|
||||
adjHeight,
|
||||
|
@ -143,7 +168,7 @@ class D3Chart extends Component {
|
|||
uniqueKeys,
|
||||
xFormat: getFormatter( xFormat, d3TimeFormat ),
|
||||
x2Format: getFormatter( x2Format, d3TimeFormat ),
|
||||
xGroupScale: getXGroupScale( orderedKeys, xScale ),
|
||||
xGroupScale: getXGroupScale( orderedKeys, xScale, compact ),
|
||||
xLineScale,
|
||||
xTicks,
|
||||
xScale,
|
||||
|
@ -156,21 +181,24 @@ class D3Chart extends Component {
|
|||
}
|
||||
|
||||
render() {
|
||||
if ( isEmpty( this.props.data ) ) {
|
||||
const { className, data, height } = this.props;
|
||||
if ( isEmpty( data ) ) {
|
||||
return null; // TODO: improve messaging
|
||||
}
|
||||
const computedWidth = this.getWidth();
|
||||
return (
|
||||
<div
|
||||
className={ classNames( 'd3-chart__container', this.props.className ) }
|
||||
style={ { height: this.props.height } }
|
||||
className={ classNames( 'd3-chart__container', className ) }
|
||||
style={ { height } }
|
||||
>
|
||||
<D3Base
|
||||
className={ classNames( this.props.className ) }
|
||||
data={ this.state.allData }
|
||||
drawChart={ this.drawChart }
|
||||
height={ this.props.height }
|
||||
height={ height }
|
||||
tooltipRef={ this.tooltipRef }
|
||||
type={ this.state.type }
|
||||
width={ this.props.width }
|
||||
width={ computedWidth }
|
||||
/>
|
||||
<div className="d3-chart__tooltip" ref={ this.tooltipRef } />
|
||||
</div>
|
||||
|
|
|
@ -6,9 +6,14 @@
|
|||
import classNames from 'classnames';
|
||||
import PropTypes from 'prop-types';
|
||||
import { Component, createRef } from '@wordpress/element';
|
||||
import { isEqual } from 'lodash';
|
||||
import { isEqual, throttle } from 'lodash';
|
||||
import { select as d3Select } from 'd3-selection';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { hideTooltip } from '../utils/tooltip';
|
||||
|
||||
/**
|
||||
* Provides foundation to use D3 within React.
|
||||
*
|
||||
|
@ -25,6 +30,10 @@ export default class D3Base extends Component {
|
|||
super( props );
|
||||
|
||||
this.chartRef = createRef();
|
||||
|
||||
this.delayedScroll = throttle( () => {
|
||||
hideTooltip( this.chartRef.current, props.tooltipRef.current );
|
||||
}, 300 );
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
|
@ -86,7 +95,7 @@ export default class D3Base extends Component {
|
|||
|
||||
render() {
|
||||
return (
|
||||
<div className={ classNames( 'd3-base', this.props.className ) } ref={ this.chartRef } />
|
||||
<div className={ classNames( 'd3-base', this.props.className ) } ref={ this.chartRef } onScroll={ this.delayedScroll } />
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
.d3-base {
|
||||
background: transparent;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
|
|
@ -9,7 +9,8 @@ import PropTypes from 'prop-types';
|
|||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { getColor, getFormatter } from './utils';
|
||||
import { getFormatter } from './utils';
|
||||
import { getColor } from './utils/color';
|
||||
|
||||
/**
|
||||
* A legend specifically designed for the WooCommerce admin charts.
|
||||
|
|
|
@ -1,25 +0,0 @@
|
|||
/** @format */
|
||||
|
||||
// /**
|
||||
// * /* eslint-disable quote-props
|
||||
// *
|
||||
// * @format
|
||||
// */
|
||||
|
||||
export default [
|
||||
{
|
||||
date: '2018-08-01T00:00:00',
|
||||
'Custom (Aug 1, 2018)': { label: '2018-08-01 00:00', value: 58929.99 },
|
||||
'Previous Period (Jul 31, 2018)': { label: '2018-07-31 00:00', value: 160130.74000000002 },
|
||||
},
|
||||
{
|
||||
date: '2018-08-01T01:00:00',
|
||||
'Custom (Aug 1, 2018)': { label: '2018-08-01 01:00', value: 3805.56 },
|
||||
'Previous Period (Jul 31, 2018)': { label: '2018-07-31 01:00', value: 0 },
|
||||
},
|
||||
{
|
||||
date: '2018-08-01T02:00:00',
|
||||
'Custom (Aug 1, 2018)': { label: '2018-08-01 02:00', value: 3805.56 },
|
||||
'Previous Period (Jul 31, 2018)': { label: '2018-07-31 02:00', value: 0 },
|
||||
},
|
||||
];
|
|
@ -144,25 +144,29 @@ export const getColor = ( key, params ) => {
|
|||
* Describes getXScale
|
||||
* @param {array} uniqueDates - from `getUniqueDates`
|
||||
* @param {number} width - calculated width of the charting space
|
||||
* @param {boolean} compact - whether the chart must be compact (without padding
|
||||
between days)
|
||||
* @returns {function} a D3 scale of the dates
|
||||
*/
|
||||
export const getXScale = ( uniqueDates, width ) =>
|
||||
export const getXScale = ( uniqueDates, width, compact = false ) =>
|
||||
d3ScaleBand()
|
||||
.domain( uniqueDates )
|
||||
.rangeRound( [ 0, width ] )
|
||||
.paddingInner( 0.1 );
|
||||
.paddingInner( compact ? 0 : 0.1 );
|
||||
|
||||
/**
|
||||
* Describes getXGroupScale
|
||||
* @param {array} orderedKeys - from `getOrderedKeys`
|
||||
* @param {function} xScale - from `getXScale`
|
||||
* @param {boolean} compact - whether the chart must be compact (without padding
|
||||
between days)
|
||||
* @returns {function} a D3 scale for each category within the xScale range
|
||||
*/
|
||||
export const getXGroupScale = ( orderedKeys, xScale ) =>
|
||||
export const getXGroupScale = ( orderedKeys, xScale, compact = false ) =>
|
||||
d3ScaleBand()
|
||||
.domain( orderedKeys.filter( d => d.visible ).map( d => d.key ) )
|
||||
.rangeRound( [ 0, xScale.bandwidth() ] )
|
||||
.padding( 0.07 );
|
||||
.padding( compact ? 0 : 0.07 );
|
||||
|
||||
/**
|
||||
* Describes getXLineScale
|
||||
|
@ -568,27 +572,30 @@ const calculateTooltipXPosition = (
|
|||
elementWidthRatio,
|
||||
tooltipPosition
|
||||
) => {
|
||||
const xPosition =
|
||||
elementCoords.left + elementCoords.width * elementWidthRatio + tooltipMargin - chartCoords.left;
|
||||
const d3BaseCoords = d3Select( '.d3-base' ).node().getBoundingClientRect();
|
||||
const leftMargin = Math.max( d3BaseCoords.left, chartCoords.left );
|
||||
|
||||
if ( tooltipPosition === 'below' ) {
|
||||
return Math.max(
|
||||
tooltipMargin,
|
||||
Math.min(
|
||||
xPosition - tooltipSize.width / 2,
|
||||
chartCoords.width - tooltipSize.width - tooltipMargin
|
||||
elementCoords.left + elementCoords.width * 0.5 - tooltipSize.width / 2 - leftMargin,
|
||||
d3BaseCoords.width - tooltipSize.width - tooltipMargin
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( xPosition + tooltipSize.width + tooltipMargin > chartCoords.width ) {
|
||||
const xPosition =
|
||||
elementCoords.left + elementCoords.width * elementWidthRatio + tooltipMargin - leftMargin;
|
||||
|
||||
if ( xPosition + tooltipSize.width + tooltipMargin > d3BaseCoords.width ) {
|
||||
return Math.max(
|
||||
tooltipMargin,
|
||||
elementCoords.left +
|
||||
elementCoords.width * ( 1 - elementWidthRatio ) -
|
||||
tooltipSize.width -
|
||||
tooltipMargin -
|
||||
chartCoords.left
|
||||
leftMargin
|
||||
);
|
||||
}
|
||||
|
||||
|
|
266
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/axis.js
vendored
Normal file
266
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/axis.js
vendored
Normal file
|
@ -0,0 +1,266 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { axisBottom as d3AxisBottom, axisLeft as d3AxisLeft } from 'd3-axis';
|
||||
import { smallBreak, wideBreak } from './breakpoints';
|
||||
|
||||
const dayTicksThreshold = 63;
|
||||
const weekTicksThreshold = 9;
|
||||
const mediumBreak = 1130;
|
||||
const smallPoints = 7;
|
||||
const mediumPoints = 12;
|
||||
const largePoints = 16;
|
||||
const mostPoints = 31;
|
||||
|
||||
/**
|
||||
* Describes `smallestFactor`
|
||||
* @param {number} inputNum - any double or integer
|
||||
* @returns {integer} smallest factor of num
|
||||
*/
|
||||
const getFactors = inputNum => {
|
||||
const numFactors = [];
|
||||
for ( let i = 1; i <= Math.floor( Math.sqrt( inputNum ) ); i += 1 ) {
|
||||
if ( inputNum % i === 0 ) {
|
||||
numFactors.push( i );
|
||||
inputNum / i !== i && numFactors.push( inputNum / i );
|
||||
}
|
||||
}
|
||||
numFactors.sort( ( x, y ) => x - y ); // numeric sort
|
||||
|
||||
return numFactors;
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculate the maximum number of ticks allowed in the x-axis based on the width and mode of the chart
|
||||
* @param {integer} width - calculated page width
|
||||
* @param {string} mode - item-comparison or time-comparison
|
||||
* @returns {integer} number of x-axis ticks based on width and chart mode
|
||||
*/
|
||||
const calculateMaxXTicks = ( width, mode ) => {
|
||||
if ( width < smallBreak ) {
|
||||
return smallPoints;
|
||||
} else if ( width >= smallBreak && width <= mediumBreak ) {
|
||||
return mediumPoints;
|
||||
} else if ( width > mediumBreak && width <= wideBreak ) {
|
||||
if ( mode === 'time-comparison' ) {
|
||||
return largePoints;
|
||||
} else if ( mode === 'item-comparison' ) {
|
||||
return mediumPoints;
|
||||
}
|
||||
} else if ( width > wideBreak ) {
|
||||
if ( mode === 'time-comparison' ) {
|
||||
return mostPoints;
|
||||
} else if ( mode === 'item-comparison' ) {
|
||||
return largePoints;
|
||||
}
|
||||
}
|
||||
|
||||
return largePoints;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get x-axis ticks given the unique dates and the increment factor.
|
||||
* @param {array} uniqueDates - all the unique dates from the input data for the chart
|
||||
* @param {integer} incrementFactor - increment factor for the visible ticks.
|
||||
* @returns {array} Ticks for the x-axis.
|
||||
*/
|
||||
const getXTicksFromIncrementFactor = ( uniqueDates, incrementFactor ) => {
|
||||
const ticks = [];
|
||||
|
||||
for ( let idx = 0; idx < uniqueDates.length; idx = idx + incrementFactor ) {
|
||||
ticks.push( uniqueDates[ idx ] );
|
||||
}
|
||||
|
||||
// If the first date is missing from the ticks array, add it back in.
|
||||
if ( ticks[ 0 ] !== uniqueDates[ 0 ] ) {
|
||||
ticks.unshift( uniqueDates[ 0 ] );
|
||||
}
|
||||
|
||||
return ticks;
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculates the increment factor between ticks so there aren't more than maxTicks.
|
||||
* @param {array} uniqueDates - all the unique dates from the input data for the chart
|
||||
* @param {integer} maxTicks - maximum number of ticks that can be displayed in the x-axis
|
||||
* @returns {integer} x-axis ticks increment factor
|
||||
*/
|
||||
const calculateXTicksIncrementFactor = ( uniqueDates, maxTicks ) => {
|
||||
let factors = [];
|
||||
let i = 1;
|
||||
// First we get all the factors of the length of the uniqueDates array
|
||||
// if the number is a prime number or near prime (with 3 factors) then we
|
||||
// step down by 1 integer and try again.
|
||||
while ( factors.length <= 3 ) {
|
||||
factors = getFactors( uniqueDates.length - i );
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return factors.find( f => uniqueDates.length / f < maxTicks );
|
||||
};
|
||||
|
||||
/**
|
||||
* Given an array of dates, returns true if the first and last one belong to the same day.
|
||||
* @param {array} dates - an array of dates
|
||||
* @returns {boolean} whether the first and last date are different hours from the same date.
|
||||
*/
|
||||
const areDatesInTheSameDay = dates => {
|
||||
const firstDate = new Date( dates [ 0 ] );
|
||||
const lastDate = new Date( dates [ dates.length - 1 ] );
|
||||
return (
|
||||
firstDate.getDate() === lastDate.getDate() &&
|
||||
firstDate.getMonth() === lastDate.getMonth() &&
|
||||
firstDate.getFullYear() === lastDate.getFullYear()
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Filter out irrelevant dates so only the first date of each month is kept.
|
||||
* @param {array} dates - string dates.
|
||||
* @returns {array} Filtered dates.
|
||||
*/
|
||||
const getFirstDatePerMonth = dates => {
|
||||
return dates.filter(
|
||||
( date, i ) => i === 0 || new Date( date ).getMonth() !== new Date( dates[ i - 1 ] ).getMonth()
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns ticks for the x-axis.
|
||||
* @param {array} uniqueDates - all the unique dates from the input data for the chart
|
||||
* @param {integer} width - calculated page width
|
||||
* @param {string} mode - item-comparison or time-comparison
|
||||
* @param {string} interval - string of the interval used in the graph (hour, day, week...)
|
||||
* @returns {integer} number of x-axis ticks based on width and chart mode
|
||||
*/
|
||||
export const getXTicks = ( uniqueDates, width, mode, interval ) => {
|
||||
const maxTicks = calculateMaxXTicks( width, mode );
|
||||
|
||||
if (
|
||||
( uniqueDates.length >= dayTicksThreshold && interval === 'day' ) ||
|
||||
( uniqueDates.length >= weekTicksThreshold && interval === 'week' )
|
||||
) {
|
||||
uniqueDates = getFirstDatePerMonth( uniqueDates );
|
||||
}
|
||||
if ( uniqueDates.length <= maxTicks ||
|
||||
( interval === 'hour' && areDatesInTheSameDay( uniqueDates ) && width > smallBreak ) ) {
|
||||
return uniqueDates;
|
||||
}
|
||||
|
||||
const incrementFactor = calculateXTicksIncrementFactor( uniqueDates, maxTicks );
|
||||
|
||||
return getXTicksFromIncrementFactor( uniqueDates, incrementFactor );
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares 2 strings and returns a list of words that are unique from s2
|
||||
* @param {string} s1 - base string to compare against
|
||||
* @param {string} s2 - string to compare against the base string
|
||||
* @param {string|Object} splitChar - character or RegExp to use to deliminate words
|
||||
* @returns {array} of unique words that appear in s2 but not in s1, the base string
|
||||
*/
|
||||
export const compareStrings = ( s1, s2, splitChar = new RegExp( [ ' |,' ], 'g' ) ) => {
|
||||
const string1 = s1.split( splitChar );
|
||||
const string2 = s2.split( splitChar );
|
||||
const diff = new Array();
|
||||
const long = s1.length > s2.length ? string1 : string2;
|
||||
for ( let x = 0; x < long.length; x++ ) {
|
||||
string1[ x ] !== string2[ x ] && diff.push( string2[ x ] );
|
||||
}
|
||||
return diff;
|
||||
};
|
||||
|
||||
export const drawAxis = ( node, params ) => {
|
||||
const xScale = params.type === 'line' ? params.xLineScale : params.xScale;
|
||||
const removeDuplicateDates = ( d, i, ticks, formatter ) => {
|
||||
const monthDate = d instanceof Date ? d : new Date( d );
|
||||
let prevMonth = i !== 0 ? ticks[ i - 1 ] : ticks[ i ];
|
||||
prevMonth = prevMonth instanceof Date ? prevMonth : new Date( prevMonth );
|
||||
return i === 0
|
||||
? formatter( monthDate )
|
||||
: compareStrings( formatter( prevMonth ), formatter( monthDate ) ).join( ' ' );
|
||||
};
|
||||
|
||||
const yGrids = [];
|
||||
for ( let i = 0; i < 4; i++ ) {
|
||||
if ( params.yMax > 1 ) {
|
||||
const roundedValue = Math.round( i / 3 * params.yMax );
|
||||
if ( yGrids[ yGrids.length - 1 ] !== roundedValue ) {
|
||||
yGrids.push( roundedValue );
|
||||
}
|
||||
} else {
|
||||
yGrids.push( i / 3 * params.yMax );
|
||||
}
|
||||
}
|
||||
|
||||
const ticks = params.xTicks.map( d => ( params.type === 'line' ? new Date( d ) : d ) );
|
||||
|
||||
node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'axis' )
|
||||
.attr( 'aria-hidden', 'true' )
|
||||
.attr( 'transform', `translate(0, ${ params.height })` )
|
||||
.call(
|
||||
d3AxisBottom( xScale )
|
||||
.tickValues( ticks )
|
||||
.tickFormat( ( d, i ) => params.interval === 'hour'
|
||||
? params.xFormat( d )
|
||||
: removeDuplicateDates( d, i, ticks, params.xFormat ) )
|
||||
);
|
||||
|
||||
node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'axis axis-month' )
|
||||
.attr( 'aria-hidden', 'true' )
|
||||
.attr( 'transform', `translate(0, ${ params.height + 20 })` )
|
||||
.call(
|
||||
d3AxisBottom( xScale )
|
||||
.tickValues( ticks )
|
||||
.tickFormat( ( d, i ) => removeDuplicateDates( d, i, ticks, params.x2Format ) )
|
||||
)
|
||||
.call( g => g.select( '.domain' ).remove() );
|
||||
|
||||
node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'pipes' )
|
||||
.attr( 'transform', `translate(0, ${ params.height })` )
|
||||
.call(
|
||||
d3AxisBottom( xScale )
|
||||
.tickValues( ticks )
|
||||
.tickSize( 5 )
|
||||
.tickFormat( '' )
|
||||
);
|
||||
|
||||
node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'grid' )
|
||||
.attr( 'transform', `translate(-${ params.margin.left },0)` )
|
||||
.call(
|
||||
d3AxisLeft( params.yScale )
|
||||
.tickValues( yGrids )
|
||||
.tickSize( -params.width - params.margin.left - params.margin.right )
|
||||
.tickFormat( '' )
|
||||
)
|
||||
.call( g => g.select( '.domain' ).remove() );
|
||||
|
||||
node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'axis y-axis' )
|
||||
.attr( 'aria-hidden', 'true' )
|
||||
.attr( 'transform', 'translate(-50, 0)' )
|
||||
.attr( 'text-anchor', 'start' )
|
||||
.call(
|
||||
d3AxisLeft( params.yTickOffset )
|
||||
.tickValues( yGrids )
|
||||
.tickFormat( d => params.yFormat( d !== 0 ? d : 0 ) )
|
||||
);
|
||||
|
||||
node.selectAll( '.domain' ).remove();
|
||||
node
|
||||
.selectAll( '.axis' )
|
||||
.selectAll( '.tick' )
|
||||
.select( 'line' )
|
||||
.remove();
|
||||
};
|
103
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/bar-chart.js
vendored
Normal file
103
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/bar-chart.js
vendored
Normal file
|
@ -0,0 +1,103 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { get } from 'lodash';
|
||||
import { event as d3Event, select as d3Select } from 'd3-selection';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { getColor } from './color';
|
||||
import { calculateTooltipPosition, hideTooltip, showTooltip } from './tooltip';
|
||||
|
||||
const handleMouseOverBarChart = ( date, parentNode, node, data, params, position ) => {
|
||||
d3Select( parentNode )
|
||||
.select( '.barfocus' )
|
||||
.attr( 'opacity', '0.1' );
|
||||
showTooltip( params, data.find( e => e.date === date ), position );
|
||||
};
|
||||
|
||||
export const drawBars = ( node, data, params ) => {
|
||||
const barGroup = node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'bars' )
|
||||
.selectAll( 'g' )
|
||||
.data( data )
|
||||
.enter()
|
||||
.append( 'g' )
|
||||
.attr( 'transform', d => `translate(${ params.xScale( d.date ) },0)` )
|
||||
.attr( 'class', 'bargroup' )
|
||||
.attr( 'role', 'region' )
|
||||
.attr(
|
||||
'aria-label',
|
||||
d =>
|
||||
params.mode === 'item-comparison'
|
||||
? params.tooltipLabelFormat( d.date instanceof Date ? d.date : new Date( d.date ) )
|
||||
: null
|
||||
);
|
||||
|
||||
barGroup
|
||||
.append( 'rect' )
|
||||
.attr( 'class', 'barfocus' )
|
||||
.attr( 'x', 0 )
|
||||
.attr( 'y', 0 )
|
||||
.attr( 'width', params.xGroupScale.range()[ 1 ] )
|
||||
.attr( 'height', params.height )
|
||||
.attr( 'opacity', '0' );
|
||||
|
||||
barGroup
|
||||
.selectAll( '.bar' )
|
||||
.data( d =>
|
||||
params.orderedKeys.filter( row => row.visible ).map( row => ( {
|
||||
key: row.key,
|
||||
focus: row.focus,
|
||||
value: get( d, [ row.key, 'value' ], 0 ),
|
||||
label: get( d, [ row.key, 'label' ], '' ),
|
||||
visible: row.visible,
|
||||
date: d.date,
|
||||
} ) )
|
||||
)
|
||||
.enter()
|
||||
.append( 'rect' )
|
||||
.attr( 'class', 'bar' )
|
||||
.attr( 'x', d => params.xGroupScale( d.key ) )
|
||||
.attr( 'y', d => params.yScale( d.value ) )
|
||||
.attr( 'width', params.xGroupScale.bandwidth() )
|
||||
.attr( 'height', d => params.height - params.yScale( d.value ) )
|
||||
.attr( 'fill', d => getColor( d.key, params ) )
|
||||
.attr( 'tabindex', '0' )
|
||||
.attr( 'aria-label', d => {
|
||||
const label = params.mode === 'time-comparison' && d.label ? d.label : d.key;
|
||||
return `${ label } ${ params.tooltipValueFormat( d.value ) }`;
|
||||
} )
|
||||
.style( 'opacity', d => {
|
||||
const opacity = d.focus ? 1 : 0.1;
|
||||
return d.visible ? opacity : 0;
|
||||
} )
|
||||
.on( 'focus', ( d, i, nodes ) => {
|
||||
const targetNode = d.value > 0 ? d3Event.target : d3Event.target.parentNode;
|
||||
const position = calculateTooltipPosition( targetNode, node.node(), params.tooltipPosition );
|
||||
handleMouseOverBarChart( d.date, nodes[ i ].parentNode, node, data, params, position );
|
||||
} )
|
||||
.on( 'blur', ( d, i, nodes ) => hideTooltip( nodes[ i ].parentNode, params.tooltip ) );
|
||||
|
||||
barGroup
|
||||
.append( 'rect' )
|
||||
.attr( 'class', 'barmouse' )
|
||||
.attr( 'x', 0 )
|
||||
.attr( 'y', 0 )
|
||||
.attr( 'width', params.xGroupScale.range()[ 1 ] )
|
||||
.attr( 'height', params.height )
|
||||
.attr( 'opacity', '0' )
|
||||
.on( 'mouseover', ( d, i, nodes ) => {
|
||||
const position = calculateTooltipPosition(
|
||||
d3Event.target,
|
||||
node.node(),
|
||||
params.tooltipPosition
|
||||
);
|
||||
handleMouseOverBarChart( d.date, nodes[ i ].parentNode, node, data, params, position );
|
||||
} )
|
||||
.on( 'mouseout', ( d, i, nodes ) => hideTooltip( nodes[ i ].parentNode, params.tooltip ) );
|
||||
};
|
3
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/breakpoints.js
vendored
Normal file
3
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/breakpoints.js
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
/** @format */
|
||||
export const smallBreak = 783;
|
||||
export const wideBreak = 1365;
|
25
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/color.js
vendored
Normal file
25
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/color.js
vendored
Normal file
|
@ -0,0 +1,25 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { findIndex } from 'lodash';
|
||||
|
||||
export const getColor = ( key, params ) => {
|
||||
const smallColorScales = [
|
||||
[],
|
||||
[ 0.5 ],
|
||||
[ 0.333, 0.667 ],
|
||||
[ 0.2, 0.5, 0.8 ],
|
||||
[ 0.12, 0.375, 0.625, 0.88 ],
|
||||
];
|
||||
let keyValue = 0;
|
||||
const len = params.orderedKeys.length;
|
||||
const idx = findIndex( params.orderedKeys, d => d.key === key );
|
||||
if ( len < 5 ) {
|
||||
keyValue = smallColorScales[ len ][ idx ];
|
||||
} else {
|
||||
keyValue = idx / ( params.orderedKeys.length - 1 );
|
||||
}
|
||||
return params.colorScheme( keyValue );
|
||||
};
|
136
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/index.js
vendored
Normal file
136
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/index.js
vendored
Normal file
|
@ -0,0 +1,136 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { find, get } from 'lodash';
|
||||
import { format as d3Format } from 'd3-format';
|
||||
import { line as d3Line } from 'd3-shape';
|
||||
|
||||
/**
|
||||
* Allows an overriding formatter or defaults to d3Format or d3TimeFormat
|
||||
* @param {string|function} format - either a format string for the D3 formatters or an overriding fomatting method
|
||||
* @param {function} formatter - default d3Format or another formatting method, which accepts the string `format`
|
||||
* @returns {function} to be used to format an input given the format and formatter
|
||||
*/
|
||||
export const getFormatter = ( format, formatter = d3Format ) =>
|
||||
typeof format === 'function' ? format : formatter( format );
|
||||
|
||||
/**
|
||||
* Describes `getUniqueKeys`
|
||||
* @param {array} data - The chart component's `data` prop.
|
||||
* @returns {array} of unique category keys
|
||||
*/
|
||||
export const getUniqueKeys = data => {
|
||||
return [
|
||||
...new Set(
|
||||
data.reduce( ( accum, curr ) => {
|
||||
Object.keys( curr ).forEach( key => key !== 'date' && accum.push( key ) );
|
||||
return accum;
|
||||
}, [] )
|
||||
),
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Describes `getOrderedKeys`
|
||||
* @param {array} data - The chart component's `data` prop.
|
||||
* @param {array} uniqueKeys - from `getUniqueKeys`.
|
||||
* @returns {array} of unique category keys ordered by cumulative total value
|
||||
*/
|
||||
export const getOrderedKeys = ( data, uniqueKeys ) =>
|
||||
uniqueKeys
|
||||
.map( key => ( {
|
||||
key,
|
||||
focus: true,
|
||||
total: data.reduce( ( a, c ) => a + c[ key ].value, 0 ),
|
||||
visible: true,
|
||||
} ) )
|
||||
.sort( ( a, b ) => b.total - a.total );
|
||||
|
||||
/**
|
||||
* Describes `getLineData`
|
||||
* @param {array} data - The chart component's `data` prop.
|
||||
* @param {array} orderedKeys - from `getOrderedKeys`.
|
||||
* @returns {array} an array objects with a category `key` and an array of `values` with `date` and `value` properties
|
||||
*/
|
||||
export const getLineData = ( data, orderedKeys ) =>
|
||||
orderedKeys.map( row => ( {
|
||||
key: row.key,
|
||||
focus: row.focus,
|
||||
visible: row.visible,
|
||||
values: data.map( d => ( {
|
||||
date: d.date,
|
||||
focus: row.focus,
|
||||
label: get( d, [ row.key, 'label' ], '' ),
|
||||
value: get( d, [ row.key, 'value' ], 0 ),
|
||||
visible: row.visible,
|
||||
} ) ),
|
||||
} ) );
|
||||
|
||||
/**
|
||||
* Describes `getUniqueDates`
|
||||
* @param {array} lineData - from `GetLineData`
|
||||
* @param {function} parseDate - D3 time format parser
|
||||
* @returns {array} an array of unique date values sorted from earliest to latest
|
||||
*/
|
||||
export const getUniqueDates = ( lineData, parseDate ) => {
|
||||
return [
|
||||
...new Set(
|
||||
lineData.reduce( ( accum, { values } ) => {
|
||||
values.forEach( ( { date } ) => accum.push( date ) );
|
||||
return accum;
|
||||
}, [] )
|
||||
),
|
||||
].sort( ( a, b ) => parseDate( a ) - parseDate( b ) );
|
||||
};
|
||||
|
||||
/**
|
||||
* Describes getLine
|
||||
* @param {function} xLineScale - from `getXLineScale`.
|
||||
* @param {function} yScale - from `getYScale`.
|
||||
* @returns {function} the D3 line function for plotting all category values
|
||||
*/
|
||||
export const getLine = ( xLineScale, yScale ) =>
|
||||
d3Line()
|
||||
.x( d => xLineScale( new Date( d.date ) ) )
|
||||
.y( d => yScale( d.value ) );
|
||||
|
||||
/**
|
||||
* Describes getDateSpaces
|
||||
* @param {array} data - The chart component's `data` prop.
|
||||
* @param {array} uniqueDates - from `getUniqueDates`
|
||||
* @param {number} width - calculated width of the charting space
|
||||
* @param {function} xLineScale - from `getXLineScale`
|
||||
* @returns {array} that icnludes the date, start (x position) and width to mode the mouseover rectangles
|
||||
*/
|
||||
export const getDateSpaces = ( data, uniqueDates, width, xLineScale ) =>
|
||||
uniqueDates.map( ( d, i ) => {
|
||||
const datapoints = find( data, { date: d } );
|
||||
const xNow = xLineScale( new Date( d ) );
|
||||
const xPrev =
|
||||
i >= 1
|
||||
? xLineScale( new Date( uniqueDates[ i - 1 ] ) )
|
||||
: xLineScale( new Date( uniqueDates[ 0 ] ) );
|
||||
const xNext =
|
||||
i < uniqueDates.length - 1
|
||||
? xLineScale( new Date( uniqueDates[ i + 1 ] ) )
|
||||
: xLineScale( new Date( uniqueDates[ uniqueDates.length - 1 ] ) );
|
||||
let xWidth = i === 0 ? xNext - xNow : xNow - xPrev;
|
||||
const xStart = i === 0 ? 0 : xNow - xWidth / 2;
|
||||
xWidth = i === 0 || i === uniqueDates.length - 1 ? xWidth / 2 : xWidth;
|
||||
return {
|
||||
date: d,
|
||||
start: uniqueDates.length > 1 ? xStart : 0,
|
||||
width: uniqueDates.length > 1 ? xWidth : width,
|
||||
values: Object.keys( datapoints )
|
||||
.filter( key => key !== 'date' )
|
||||
.map( key => {
|
||||
return {
|
||||
key,
|
||||
value: datapoints[ key ].value,
|
||||
date: d,
|
||||
};
|
||||
} ),
|
||||
};
|
||||
} );
|
138
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/line-chart.js
vendored
Normal file
138
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/line-chart.js
vendored
Normal file
|
@ -0,0 +1,138 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { event as d3Event, select as d3Select } from 'd3-selection';
|
||||
import { smallBreak, wideBreak } from './breakpoints';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { getColor } from './color';
|
||||
import { calculateTooltipPosition, hideTooltip, showTooltip } from './tooltip';
|
||||
|
||||
const handleMouseOverLineChart = ( date, parentNode, node, data, params, position ) => {
|
||||
d3Select( parentNode )
|
||||
.select( '.focus-grid' )
|
||||
.attr( 'opacity', '1' );
|
||||
showTooltip( params, data.find( e => e.date === date ), position );
|
||||
};
|
||||
|
||||
export const drawLines = ( node, data, params ) => {
|
||||
const series = node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'lines' )
|
||||
.selectAll( '.line-g' )
|
||||
.data( params.lineData.filter( d => d.visible ).reverse() )
|
||||
.enter()
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'line-g' )
|
||||
.attr( 'role', 'region' )
|
||||
.attr( 'aria-label', d => d.key );
|
||||
|
||||
let lineStroke = params.width <= wideBreak || params.uniqueDates.length > 50 ? 2 : 3;
|
||||
lineStroke = params.width <= smallBreak ? 1.25 : lineStroke;
|
||||
const dotRadius = params.width <= wideBreak ? 4 : 6;
|
||||
|
||||
series
|
||||
.append( 'path' )
|
||||
.attr( 'fill', 'none' )
|
||||
.attr( 'stroke-width', lineStroke )
|
||||
.attr( 'stroke-linejoin', 'round' )
|
||||
.attr( 'stroke-linecap', 'round' )
|
||||
.attr( 'stroke', d => getColor( d.key, params ) )
|
||||
.style( 'opacity', d => {
|
||||
const opacity = d.focus ? 1 : 0.1;
|
||||
return d.visible ? opacity : 0;
|
||||
} )
|
||||
.attr( 'd', d => params.line( d.values ) );
|
||||
|
||||
const minDataPointSpacing = 36;
|
||||
|
||||
params.width / params.uniqueDates.length > minDataPointSpacing &&
|
||||
series
|
||||
.selectAll( 'circle' )
|
||||
.data( ( d, i ) => d.values.map( row => ( { ...row, i, visible: d.visible, key: d.key } ) ) )
|
||||
.enter()
|
||||
.append( 'circle' )
|
||||
.attr( 'r', dotRadius )
|
||||
.attr( 'fill', d => getColor( d.key, params ) )
|
||||
.attr( 'stroke', '#fff' )
|
||||
.attr( 'stroke-width', lineStroke + 1 )
|
||||
.style( 'opacity', d => {
|
||||
const opacity = d.focus ? 1 : 0.1;
|
||||
return d.visible ? opacity : 0;
|
||||
} )
|
||||
.attr( 'cx', d => params.xLineScale( new Date( d.date ) ) )
|
||||
.attr( 'cy', d => params.yScale( d.value ) )
|
||||
.attr( 'tabindex', '0' )
|
||||
.attr( 'aria-label', d => {
|
||||
const label = d.label
|
||||
? d.label
|
||||
: params.tooltipLabelFormat( d.date instanceof Date ? d.date : new Date( d.date ) );
|
||||
return `${ label } ${ params.tooltipValueFormat( d.value ) }`;
|
||||
} )
|
||||
.on( 'focus', ( d, i, nodes ) => {
|
||||
const position = calculateTooltipPosition(
|
||||
d3Event.target,
|
||||
node.node(),
|
||||
params.tooltipPosition
|
||||
);
|
||||
handleMouseOverLineChart( d.date, nodes[ i ].parentNode, node, data, params, position );
|
||||
} )
|
||||
.on( 'blur', ( d, i, nodes ) => hideTooltip( nodes[ i ].parentNode, params.tooltip ) );
|
||||
|
||||
const focus = node
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'focusspaces' )
|
||||
.selectAll( '.focus' )
|
||||
.data( params.dateSpaces )
|
||||
.enter()
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'focus' );
|
||||
|
||||
const focusGrid = focus
|
||||
.append( 'g' )
|
||||
.attr( 'class', 'focus-grid' )
|
||||
.attr( 'opacity', '0' );
|
||||
|
||||
focusGrid
|
||||
.append( 'line' )
|
||||
.attr( 'x1', d => params.xLineScale( new Date( d.date ) ) )
|
||||
.attr( 'y1', 0 )
|
||||
.attr( 'x2', d => params.xLineScale( new Date( d.date ) ) )
|
||||
.attr( 'y2', params.height );
|
||||
|
||||
focusGrid
|
||||
.selectAll( 'circle' )
|
||||
.data( d => d.values.reverse() )
|
||||
.enter()
|
||||
.append( 'circle' )
|
||||
.attr( 'r', dotRadius + 2 )
|
||||
.attr( 'fill', d => getColor( d.key, params ) )
|
||||
.attr( 'stroke', '#fff' )
|
||||
.attr( 'stroke-width', lineStroke + 2 )
|
||||
.attr( 'cx', d => params.xLineScale( new Date( d.date ) ) )
|
||||
.attr( 'cy', d => params.yScale( d.value ) );
|
||||
|
||||
focus
|
||||
.append( 'rect' )
|
||||
.attr( 'class', 'focus-g' )
|
||||
.attr( 'x', d => d.start )
|
||||
.attr( 'y', 0 )
|
||||
.attr( 'width', d => d.width )
|
||||
.attr( 'height', params.height )
|
||||
.attr( 'opacity', 0 )
|
||||
.on( 'mouseover', ( d, i, nodes ) => {
|
||||
const elementWidthRatio = i === 0 || i === params.dateSpaces.length - 1 ? 0 : 0.5;
|
||||
const position = calculateTooltipPosition(
|
||||
d3Event.target,
|
||||
node.node(),
|
||||
params.tooltipPosition,
|
||||
elementWidthRatio
|
||||
);
|
||||
handleMouseOverLineChart( d.date, nodes[ i ].parentNode, node, data, params, position );
|
||||
} )
|
||||
.on( 'mouseout', ( d, i, nodes ) => hideTooltip( nodes[ i ].parentNode, params.tooltip ) );
|
||||
};
|
83
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/scales.js
vendored
Normal file
83
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/scales.js
vendored
Normal file
|
@ -0,0 +1,83 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { max as d3Max } from 'd3-array';
|
||||
import {
|
||||
scaleBand as d3ScaleBand,
|
||||
scaleLinear as d3ScaleLinear,
|
||||
scaleTime as d3ScaleTime,
|
||||
} from 'd3-scale';
|
||||
|
||||
/**
|
||||
* Describes and rounds the maximum y value to the nearest thousand, ten-thousand, million etc. In case it is a decimal number, ceils it.
|
||||
* @param {array} lineData - from `getLineData`
|
||||
* @returns {number} the maximum value in the timeseries multiplied by 4/3
|
||||
*/
|
||||
export const getYMax = lineData => {
|
||||
const yMax = 4 / 3 * d3Max( lineData, d => d3Max( d.values.map( date => date.value ) ) );
|
||||
const pow3Y = Math.pow( 10, ( ( Math.log( yMax ) * Math.LOG10E + 1 ) | 0 ) - 2 ) * 3;
|
||||
return Math.ceil( Math.ceil( yMax / pow3Y ) * pow3Y );
|
||||
};
|
||||
|
||||
/**
|
||||
* Describes getXScale
|
||||
* @param {array} uniqueDates - from `getUniqueDates`
|
||||
* @param {number} width - calculated width of the charting space
|
||||
* @param {boolean} compact - whether the chart must be compact (without padding
|
||||
between days)
|
||||
* @returns {function} a D3 scale of the dates
|
||||
*/
|
||||
export const getXScale = ( uniqueDates, width, compact = false ) =>
|
||||
d3ScaleBand()
|
||||
.domain( uniqueDates )
|
||||
.rangeRound( [ 0, width ] )
|
||||
.paddingInner( compact ? 0 : 0.1 );
|
||||
|
||||
/**
|
||||
* Describes getXGroupScale
|
||||
* @param {array} orderedKeys - from `getOrderedKeys`
|
||||
* @param {function} xScale - from `getXScale`
|
||||
* @param {boolean} compact - whether the chart must be compact (without padding
|
||||
between days)
|
||||
* @returns {function} a D3 scale for each category within the xScale range
|
||||
*/
|
||||
export const getXGroupScale = ( orderedKeys, xScale, compact = false ) =>
|
||||
d3ScaleBand()
|
||||
.domain( orderedKeys.filter( d => d.visible ).map( d => d.key ) )
|
||||
.rangeRound( [ 0, xScale.bandwidth() ] )
|
||||
.padding( compact ? 0 : 0.07 );
|
||||
|
||||
/**
|
||||
* Describes getXLineScale
|
||||
* @param {array} uniqueDates - from `getUniqueDates`
|
||||
* @param {number} width - calculated width of the charting space
|
||||
* @returns {function} a D3 scaletime for each date
|
||||
*/
|
||||
export const getXLineScale = ( uniqueDates, width ) =>
|
||||
d3ScaleTime()
|
||||
.domain( [ new Date( uniqueDates[ 0 ] ), new Date( uniqueDates[ uniqueDates.length - 1 ] ) ] )
|
||||
.rangeRound( [ 0, width ] );
|
||||
|
||||
/**
|
||||
* Describes getYScale
|
||||
* @param {number} height - calculated height of the charting space
|
||||
* @param {number} yMax - from `getYMax`
|
||||
* @returns {function} the D3 linear scale from 0 to the value from `getYMax`
|
||||
*/
|
||||
export const getYScale = ( height, yMax ) =>
|
||||
d3ScaleLinear()
|
||||
.domain( [ 0, yMax ] )
|
||||
.rangeRound( [ height, 0 ] );
|
||||
|
||||
/**
|
||||
* Describes getyTickOffset
|
||||
* @param {number} height - calculated height of the charting space
|
||||
* @param {number} yMax - from `getYMax`
|
||||
* @returns {function} the D3 linear scale from 0 to the value from `getYMax`, offset by 12 pixels down
|
||||
*/
|
||||
export const getYTickOffset = ( height, yMax ) =>
|
||||
d3ScaleLinear()
|
||||
.domain( [ 0, yMax ] )
|
||||
.rangeRound( [ height + 12, 12 ] );
|
|
@ -1,162 +1,12 @@
|
|||
/** @format */
|
||||
/**
|
||||
* External dependencies
|
||||
*
|
||||
* @format
|
||||
*/
|
||||
// import { noop } from 'lodash';
|
||||
import { utcParse as d3UTCParse } from 'd3-time-format';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import dummyOrders from './fixtures/dummy';
|
||||
import {
|
||||
compareStrings,
|
||||
getDateSpaces,
|
||||
getOrderedKeys,
|
||||
getLineData,
|
||||
getUniqueKeys,
|
||||
getUniqueDates,
|
||||
getXScale,
|
||||
getXGroupScale,
|
||||
getXLineScale,
|
||||
getXTicks,
|
||||
getYMax,
|
||||
getYScale,
|
||||
getYTickOffset,
|
||||
} from '../utils';
|
||||
|
||||
const orderedKeys = [
|
||||
{
|
||||
key: 'Cap',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 34513697,
|
||||
},
|
||||
{
|
||||
key: 'T-Shirt',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 14762281,
|
||||
},
|
||||
{
|
||||
key: 'Sunglasses',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 12430349,
|
||||
},
|
||||
{
|
||||
key: 'Polo',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 8712807,
|
||||
},
|
||||
{
|
||||
key: 'Hoodie',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 6968764,
|
||||
},
|
||||
];
|
||||
const orderedDates = [
|
||||
'2018-05-30T00:00:00',
|
||||
'2018-05-31T00:00:00',
|
||||
'2018-06-01T00:00:00',
|
||||
'2018-06-02T00:00:00',
|
||||
'2018-06-03T00:00:00',
|
||||
'2018-06-04T00:00:00',
|
||||
];
|
||||
const parseDate = d3UTCParse( '%Y-%m-%dT%H:%M:%S' );
|
||||
const testUniqueKeys = getUniqueKeys( dummyOrders );
|
||||
const testOrderedKeys = getOrderedKeys( dummyOrders, testUniqueKeys );
|
||||
const testLineData = getLineData( dummyOrders, testOrderedKeys );
|
||||
const testUniqueDates = getUniqueDates( testLineData, parseDate );
|
||||
const testXScale = getXScale( testUniqueDates, 100 );
|
||||
const testXLineScale = getXLineScale( testUniqueDates, 100 );
|
||||
const testYMax = getYMax( testLineData );
|
||||
const testYScale = getYScale( 100, testYMax );
|
||||
|
||||
describe( 'parseDate', () => {
|
||||
it( 'correctly parse date in the expected format', () => {
|
||||
const testDate = parseDate( '2018-06-30T00:00:00' );
|
||||
const expectedDate = new Date( Date.UTC( 2018, 5, 30 ) );
|
||||
expect( testDate.getTime() ).toEqual( expectedDate.getTime() );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getUniqueKeys', () => {
|
||||
it( 'returns an array of keys excluding date', () => {
|
||||
// sort is a mutating action so we need a copy
|
||||
const testUniqueKeysClone = testUniqueKeys.slice();
|
||||
const sortedAZKeys = orderedKeys.map( d => d.key ).slice();
|
||||
expect( testUniqueKeysClone.sort() ).toEqual( sortedAZKeys.sort() );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getOrderedKeys', () => {
|
||||
it( 'returns an array of keys order by value from largest to smallest', () => {
|
||||
expect( testOrderedKeys ).toEqual( orderedKeys );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getLineData', () => {
|
||||
it( 'returns a sorted array of objects with category key', () => {
|
||||
expect( testLineData ).toBeInstanceOf( Array );
|
||||
expect( testLineData ).toHaveLength( 5 );
|
||||
expect( testLineData.map( d => d.key ) ).toEqual( orderedKeys.map( d => d.key ) );
|
||||
} );
|
||||
|
||||
testLineData.forEach( d => {
|
||||
it( 'ensure a key and that the values property is an array', () => {
|
||||
expect( d ).toHaveProperty( 'key' );
|
||||
expect( d ).toHaveProperty( 'values' );
|
||||
expect( d.values ).toBeInstanceOf( Array );
|
||||
} );
|
||||
|
||||
it( 'ensure all unique dates exist in values array', () => {
|
||||
const rowDates = d.values.map( row => row.date );
|
||||
expect( rowDates ).toEqual( orderedDates );
|
||||
} );
|
||||
|
||||
d.values.forEach( row => {
|
||||
it( 'ensure a date property and that the values property is an array with date (parseable) and value properties', () => {
|
||||
expect( row ).toHaveProperty( 'date' );
|
||||
expect( row ).toHaveProperty( 'value' );
|
||||
expect( parseDate( row.date ) ).not.toBeNull();
|
||||
expect( typeof row.date ).toBe( 'string' );
|
||||
expect( typeof row.value ).toBe( 'number' );
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getXScale', () => {
|
||||
it( 'properly scale inputs to the provided domain and range', () => {
|
||||
expect( testXScale( orderedDates[ 0 ] ) ).toEqual( 3 );
|
||||
expect( testXScale( orderedDates[ 2 ] ) ).toEqual( 35 );
|
||||
expect( testXScale( orderedDates[ orderedDates.length - 1 ] ) ).toEqual( 83 );
|
||||
} );
|
||||
it( 'properly scale inputs and test the bandwidth', () => {
|
||||
expect( testXScale.bandwidth() ).toEqual( 14 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getXGroupScale', () => {
|
||||
it( 'properly scale inputs based on the getXScale', () => {
|
||||
const testXGroupScale = getXGroupScale( testOrderedKeys, testXScale );
|
||||
expect( testXGroupScale( orderedKeys[ 0 ].key ) ).toEqual( 2 );
|
||||
expect( testXGroupScale( orderedKeys[ 2 ].key ) ).toEqual( 6 );
|
||||
expect( testXGroupScale( orderedKeys[ orderedKeys.length - 1 ].key ) ).toEqual( 10 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getXLineScale', () => {
|
||||
it( 'properly scale inputs for the line', () => {
|
||||
expect( testXLineScale( new Date( orderedDates[ 0 ] ) ) ).toEqual( 0 );
|
||||
expect( testXLineScale( new Date( orderedDates[ 2 ] ) ) ).toEqual( 40 );
|
||||
expect( testXLineScale( new Date( orderedDates[ orderedDates.length - 1 ] ) ) ).toEqual( 100 );
|
||||
} );
|
||||
} );
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { compareStrings, getXTicks } from '../axis';
|
||||
|
||||
describe( 'getXTicks', () => {
|
||||
describe( 'interval=day', () => {
|
||||
|
@ -380,42 +230,6 @@ describe( 'getXTicks', () => {
|
|||
} );
|
||||
} );
|
||||
|
||||
describe( 'getYMax', () => {
|
||||
it( 'calculate the correct maximum y value', () => {
|
||||
expect( testYMax ).toEqual( 15000000 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getYScale', () => {
|
||||
it( 'properly scale the y values given the height and maximum y value', () => {
|
||||
expect( testYScale( 0 ) ).toEqual( 100 );
|
||||
expect( testYScale( testYMax ) ).toEqual( 0 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getYTickOffset', () => {
|
||||
it( 'properly scale the y values for the y-axis ticks given the height and maximum y value', () => {
|
||||
const testYTickOffset1 = getYTickOffset( 100, testYMax );
|
||||
expect( testYTickOffset1( 0 ) ).toEqual( 112 );
|
||||
expect( testYTickOffset1( testYMax ) ).toEqual( 12 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getDateSpaces', () => {
|
||||
it( 'return an array used to space out the mouseover rectangles, used for tooltips', () => {
|
||||
const testDateSpaces = getDateSpaces( dummyOrders, testUniqueDates, 100, testXLineScale );
|
||||
expect( testDateSpaces[ 0 ].date ).toEqual( '2018-05-30T00:00:00' );
|
||||
expect( testDateSpaces[ 0 ].start ).toEqual( 0 );
|
||||
expect( testDateSpaces[ 0 ].width ).toEqual( 10 );
|
||||
expect( testDateSpaces[ 3 ].date ).toEqual( '2018-06-02T00:00:00' );
|
||||
expect( testDateSpaces[ 3 ].start ).toEqual( 50 );
|
||||
expect( testDateSpaces[ 3 ].width ).toEqual( 20 );
|
||||
expect( testDateSpaces[ testDateSpaces.length - 1 ].date ).toEqual( '2018-06-04T00:00:00' );
|
||||
expect( testDateSpaces[ testDateSpaces.length - 1 ].start ).toEqual( 90 );
|
||||
expect( testDateSpaces[ testDateSpaces.length - 1 ].width ).toEqual( 10 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'compareStrings', () => {
|
||||
it( 'return an array of unique words from s2 that dont appear in base string', () => {
|
||||
expect( compareStrings( 'Jul 2018', 'Aug 2018' ).join( ' ' ) ).toEqual( 'Aug' );
|
|
@ -0,0 +1,9 @@
|
|||
/** @format */
|
||||
export default [
|
||||
'2018-05-30T00:00:00',
|
||||
'2018-05-31T00:00:00',
|
||||
'2018-06-01T00:00:00',
|
||||
'2018-06-02T00:00:00',
|
||||
'2018-06-03T00:00:00',
|
||||
'2018-06-04T00:00:00',
|
||||
];
|
|
@ -0,0 +1,33 @@
|
|||
/** @format */
|
||||
export default [
|
||||
{
|
||||
key: 'Cap',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 34513697,
|
||||
},
|
||||
{
|
||||
key: 'T-Shirt',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 14762281,
|
||||
},
|
||||
{
|
||||
key: 'Sunglasses',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 12430349,
|
||||
},
|
||||
{
|
||||
key: 'Polo',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 8712807,
|
||||
},
|
||||
{
|
||||
key: 'Hoodie',
|
||||
focus: true,
|
||||
visible: true,
|
||||
total: 6968764,
|
||||
},
|
||||
];
|
|
@ -1,11 +1,4 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* /* eslint-disable quote-props
|
||||
*
|
||||
* @format
|
||||
*/
|
||||
|
||||
export default [
|
||||
{
|
||||
date: '2018-05-30T00:00:00',
|
96
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/test/index.js
vendored
Normal file
96
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/test/index.js
vendored
Normal file
|
@ -0,0 +1,96 @@
|
|||
/** @format */
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { utcParse as d3UTCParse } from 'd3-time-format';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import dummyOrders from './fixtures/dummy-orders';
|
||||
import orderedDates from './fixtures/dummy-ordered-dates';
|
||||
import orderedKeys from './fixtures/dummy-ordered-keys';
|
||||
import {
|
||||
getDateSpaces,
|
||||
getOrderedKeys,
|
||||
getLineData,
|
||||
getUniqueKeys,
|
||||
getUniqueDates,
|
||||
} from '../index';
|
||||
import { getXLineScale } from '../scales';
|
||||
|
||||
const parseDate = d3UTCParse( '%Y-%m-%dT%H:%M:%S' );
|
||||
const testUniqueKeys = getUniqueKeys( dummyOrders );
|
||||
const testOrderedKeys = getOrderedKeys( dummyOrders, testUniqueKeys );
|
||||
const testLineData = getLineData( dummyOrders, testOrderedKeys );
|
||||
const testUniqueDates = getUniqueDates( testLineData, parseDate );
|
||||
const testXLineScale = getXLineScale( testUniqueDates, 100 );
|
||||
|
||||
describe( 'parseDate', () => {
|
||||
it( 'correctly parse date in the expected format', () => {
|
||||
const testDate = parseDate( '2018-06-30T00:00:00' );
|
||||
const expectedDate = new Date( Date.UTC( 2018, 5, 30 ) );
|
||||
expect( testDate.getTime() ).toEqual( expectedDate.getTime() );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getUniqueKeys', () => {
|
||||
it( 'returns an array of keys excluding date', () => {
|
||||
// sort is a mutating action so we need a copy
|
||||
const testUniqueKeysClone = testUniqueKeys.slice();
|
||||
const sortedAZKeys = orderedKeys.map( d => d.key ).slice();
|
||||
expect( testUniqueKeysClone.sort() ).toEqual( sortedAZKeys.sort() );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getOrderedKeys', () => {
|
||||
it( 'returns an array of keys order by value from largest to smallest', () => {
|
||||
expect( testOrderedKeys ).toEqual( orderedKeys );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getLineData', () => {
|
||||
it( 'returns a sorted array of objects with category key', () => {
|
||||
expect( testLineData ).toBeInstanceOf( Array );
|
||||
expect( testLineData ).toHaveLength( 5 );
|
||||
expect( testLineData.map( d => d.key ) ).toEqual( orderedKeys.map( d => d.key ) );
|
||||
} );
|
||||
|
||||
testLineData.forEach( d => {
|
||||
it( 'ensure a key and that the values property is an array', () => {
|
||||
expect( d ).toHaveProperty( 'key' );
|
||||
expect( d ).toHaveProperty( 'values' );
|
||||
expect( d.values ).toBeInstanceOf( Array );
|
||||
} );
|
||||
|
||||
it( 'ensure all unique dates exist in values array', () => {
|
||||
const rowDates = d.values.map( row => row.date );
|
||||
expect( rowDates ).toEqual( orderedDates );
|
||||
} );
|
||||
|
||||
d.values.forEach( row => {
|
||||
it( 'ensure a date property and that the values property is an array with date (parseable) and value properties', () => {
|
||||
expect( row ).toHaveProperty( 'date' );
|
||||
expect( row ).toHaveProperty( 'value' );
|
||||
expect( parseDate( row.date ) ).not.toBeNull();
|
||||
expect( typeof row.date ).toBe( 'string' );
|
||||
expect( typeof row.value ).toBe( 'number' );
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getDateSpaces', () => {
|
||||
it( 'return an array used to space out the mouseover rectangles, used for tooltips', () => {
|
||||
const testDateSpaces = getDateSpaces( dummyOrders, testUniqueDates, 100, testXLineScale );
|
||||
expect( testDateSpaces[ 0 ].date ).toEqual( '2018-05-30T00:00:00' );
|
||||
expect( testDateSpaces[ 0 ].start ).toEqual( 0 );
|
||||
expect( testDateSpaces[ 0 ].width ).toEqual( 10 );
|
||||
expect( testDateSpaces[ 3 ].date ).toEqual( '2018-06-02T00:00:00' );
|
||||
expect( testDateSpaces[ 3 ].start ).toEqual( 50 );
|
||||
expect( testDateSpaces[ 3 ].width ).toEqual( 20 );
|
||||
expect( testDateSpaces[ testDateSpaces.length - 1 ].date ).toEqual( '2018-06-04T00:00:00' );
|
||||
expect( testDateSpaces[ testDateSpaces.length - 1 ].start ).toEqual( 90 );
|
||||
expect( testDateSpaces[ testDateSpaces.length - 1 ].width ).toEqual( 10 );
|
||||
} );
|
||||
} );
|
78
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/test/scales.js
vendored
Normal file
78
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/test/scales.js
vendored
Normal file
|
@ -0,0 +1,78 @@
|
|||
/** @format */
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { utcParse as d3UTCParse } from 'd3-time-format';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import dummyOrders from './fixtures/dummy-orders';
|
||||
import orderedDates from './fixtures/dummy-ordered-dates';
|
||||
import orderedKeys from './fixtures/dummy-ordered-keys';
|
||||
import {
|
||||
getOrderedKeys,
|
||||
getLineData,
|
||||
getUniqueKeys,
|
||||
getUniqueDates,
|
||||
} from '../index';
|
||||
import { getXGroupScale, getXScale, getXLineScale, getYMax, getYScale, getYTickOffset } from '../scales';
|
||||
|
||||
const parseDate = d3UTCParse( '%Y-%m-%dT%H:%M:%S' );
|
||||
const testUniqueKeys = getUniqueKeys( dummyOrders );
|
||||
const testOrderedKeys = getOrderedKeys( dummyOrders, testUniqueKeys );
|
||||
const testLineData = getLineData( dummyOrders, testOrderedKeys );
|
||||
const testUniqueDates = getUniqueDates( testLineData, parseDate );
|
||||
const testXScale = getXScale( testUniqueDates, 100 );
|
||||
const testXLineScale = getXLineScale( testUniqueDates, 100 );
|
||||
const testYMax = getYMax( testLineData );
|
||||
const testYScale = getYScale( 100, testYMax );
|
||||
|
||||
describe( 'getXScale', () => {
|
||||
it( 'properly scale inputs to the provided domain and range', () => {
|
||||
expect( testXScale( orderedDates[ 0 ] ) ).toEqual( 3 );
|
||||
expect( testXScale( orderedDates[ 2 ] ) ).toEqual( 35 );
|
||||
expect( testXScale( orderedDates[ orderedDates.length - 1 ] ) ).toEqual( 83 );
|
||||
} );
|
||||
it( 'properly scale inputs and test the bandwidth', () => {
|
||||
expect( testXScale.bandwidth() ).toEqual( 14 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getXGroupScale', () => {
|
||||
it( 'properly scale inputs based on the getXScale', () => {
|
||||
const testXGroupScale = getXGroupScale( testOrderedKeys, testXScale );
|
||||
expect( testXGroupScale( orderedKeys[ 0 ].key ) ).toEqual( 2 );
|
||||
expect( testXGroupScale( orderedKeys[ 2 ].key ) ).toEqual( 6 );
|
||||
expect( testXGroupScale( orderedKeys[ orderedKeys.length - 1 ].key ) ).toEqual( 10 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getXLineScale', () => {
|
||||
it( 'properly scale inputs for the line', () => {
|
||||
expect( testXLineScale( new Date( orderedDates[ 0 ] ) ) ).toEqual( 0 );
|
||||
expect( testXLineScale( new Date( orderedDates[ 2 ] ) ) ).toEqual( 40 );
|
||||
expect( testXLineScale( new Date( orderedDates[ orderedDates.length - 1 ] ) ) ).toEqual( 100 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getYMax', () => {
|
||||
it( 'calculate the correct maximum y value', () => {
|
||||
expect( testYMax ).toEqual( 15000000 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getYScale', () => {
|
||||
it( 'properly scale the y values given the height and maximum y value', () => {
|
||||
expect( testYScale( 0 ) ).toEqual( 100 );
|
||||
expect( testYScale( testYMax ) ).toEqual( 0 );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'getYTickOffset', () => {
|
||||
it( 'properly scale the y values for the y-axis ticks given the height and maximum y value', () => {
|
||||
const testYTickOffset1 = getYTickOffset( 100, testYMax );
|
||||
expect( testYTickOffset1( 0 ) ).toEqual( 112 );
|
||||
expect( testYTickOffset1( testYMax ) ).toEqual( 12 );
|
||||
} );
|
||||
} );
|
148
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/tooltip.js
vendored
Normal file
148
plugins/woocommerce-admin/packages/components/src/chart/d3chart/utils/tooltip.js
vendored
Normal file
|
@ -0,0 +1,148 @@
|
|||
/** @format */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { select as d3Select } from 'd3-selection';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { getColor } from './color';
|
||||
|
||||
export const hideTooltip = ( parentNode, tooltipNode ) => {
|
||||
d3Select( parentNode )
|
||||
.selectAll( '.barfocus, .focus-grid' )
|
||||
.attr( 'opacity', '0' );
|
||||
d3Select( tooltipNode )
|
||||
.style( 'visibility', 'hidden' );
|
||||
};
|
||||
|
||||
const calculateTooltipXPosition = (
|
||||
elementCoords,
|
||||
chartCoords,
|
||||
tooltipSize,
|
||||
tooltipMargin,
|
||||
elementWidthRatio,
|
||||
tooltipPosition
|
||||
) => {
|
||||
const d3BaseCoords = d3Select( '.d3-base' ).node().getBoundingClientRect();
|
||||
const leftMargin = Math.max( d3BaseCoords.left, chartCoords.left );
|
||||
|
||||
if ( tooltipPosition === 'below' ) {
|
||||
return Math.max(
|
||||
tooltipMargin,
|
||||
Math.min(
|
||||
elementCoords.left + elementCoords.width * 0.5 - tooltipSize.width / 2 - leftMargin,
|
||||
d3BaseCoords.width - tooltipSize.width - tooltipMargin
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const xPosition =
|
||||
elementCoords.left + elementCoords.width * elementWidthRatio + tooltipMargin - leftMargin;
|
||||
|
||||
if ( xPosition + tooltipSize.width + tooltipMargin > d3BaseCoords.width ) {
|
||||
return Math.max(
|
||||
tooltipMargin,
|
||||
elementCoords.left +
|
||||
elementCoords.width * ( 1 - elementWidthRatio ) -
|
||||
tooltipSize.width -
|
||||
tooltipMargin -
|
||||
leftMargin
|
||||
);
|
||||
}
|
||||
|
||||
return xPosition;
|
||||
};
|
||||
|
||||
const calculateTooltipYPosition = (
|
||||
elementCoords,
|
||||
chartCoords,
|
||||
tooltipSize,
|
||||
tooltipMargin,
|
||||
tooltipPosition
|
||||
) => {
|
||||
if ( tooltipPosition === 'below' ) {
|
||||
return chartCoords.height;
|
||||
}
|
||||
|
||||
const yPosition = elementCoords.top + tooltipMargin - chartCoords.top;
|
||||
if ( yPosition + tooltipSize.height + tooltipMargin > chartCoords.height ) {
|
||||
return Math.max( 0, elementCoords.top - tooltipSize.height - tooltipMargin - chartCoords.top );
|
||||
}
|
||||
|
||||
return yPosition;
|
||||
};
|
||||
|
||||
export const calculateTooltipPosition = ( element, chart, tooltipPosition, elementWidthRatio = 1 ) => {
|
||||
const elementCoords = element.getBoundingClientRect();
|
||||
const chartCoords = chart.getBoundingClientRect();
|
||||
const tooltipSize = d3Select( '.d3-chart__tooltip' )
|
||||
.node()
|
||||
.getBoundingClientRect();
|
||||
const tooltipMargin = 24;
|
||||
|
||||
if ( tooltipPosition === 'below' ) {
|
||||
elementWidthRatio = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
x: calculateTooltipXPosition(
|
||||
elementCoords,
|
||||
chartCoords,
|
||||
tooltipSize,
|
||||
tooltipMargin,
|
||||
elementWidthRatio,
|
||||
tooltipPosition
|
||||
),
|
||||
y: calculateTooltipYPosition(
|
||||
elementCoords,
|
||||
chartCoords,
|
||||
tooltipSize,
|
||||
tooltipMargin,
|
||||
tooltipPosition
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const getTooltipRowLabel = ( d, row, params ) => {
|
||||
if ( d[ row.key ].labelDate ) {
|
||||
return params.tooltipLabelFormat(
|
||||
d[ row.key ].labelDate instanceof Date
|
||||
? d[ row.key ].labelDate
|
||||
: new Date( d[ row.key ].labelDate )
|
||||
);
|
||||
}
|
||||
return row.key;
|
||||
};
|
||||
|
||||
export const showTooltip = ( params, d, position ) => {
|
||||
const keys = params.orderedKeys.filter( row => row.visible ).map(
|
||||
row => `
|
||||
<li class="key-row">
|
||||
<div class="key-container">
|
||||
<span class="key-color" style="background-color:${ getColor( row.key, params ) }"></span>
|
||||
<span class="key-key">${ getTooltipRowLabel( d, row, params ) }</span>
|
||||
</div>
|
||||
<span class="key-value">${ params.tooltipValueFormat( d[ row.key ].value ) }</span>
|
||||
</li>
|
||||
`
|
||||
);
|
||||
|
||||
const tooltipTitle = params.tooltipTitle
|
||||
? params.tooltipTitle
|
||||
: params.tooltipLabelFormat( d.date instanceof Date ? d.date : new Date( d.date ) );
|
||||
|
||||
d3Select( params.tooltip )
|
||||
.style( 'left', position.x + 'px' )
|
||||
.style( 'top', position.y + 'px' )
|
||||
.style( 'visibility', 'visible' ).html( `
|
||||
<div>
|
||||
<h4>${ tooltipTitle }</h4>
|
||||
<ul>
|
||||
${ keys.join( '' ) }
|
||||
</ul>
|
||||
</div>
|
||||
` );
|
||||
};
|
|
@ -113,8 +113,8 @@ class Chart extends Component {
|
|||
}
|
||||
|
||||
handleLegendToggle( event ) {
|
||||
const { data, mode } = this.props;
|
||||
if ( mode ) {
|
||||
const { data, interactiveLegend } = this.props;
|
||||
if ( ! interactiveLegend ) {
|
||||
return;
|
||||
}
|
||||
const orderedKeys = this.state.orderedKeys.map( d => ( {
|
||||
|
@ -211,28 +211,44 @@ class Chart extends Component {
|
|||
return 220;
|
||||
}
|
||||
|
||||
getLegendPosition() {
|
||||
const { legendPosition, mode, isViewportWide } = this.props;
|
||||
if ( legendPosition ) {
|
||||
return legendPosition;
|
||||
}
|
||||
if ( isViewportWide && mode === 'time-comparison' ) {
|
||||
return 'top';
|
||||
}
|
||||
if ( isViewportWide && mode === 'item-comparison' ) {
|
||||
return 'side';
|
||||
}
|
||||
return 'bottom';
|
||||
}
|
||||
|
||||
render() {
|
||||
const { orderedKeys, visibleData, width } = this.state;
|
||||
const { interactiveLegend, orderedKeys, visibleData, width } = this.state;
|
||||
const {
|
||||
dateParser,
|
||||
interval,
|
||||
isRequesting,
|
||||
isViewportLarge,
|
||||
itemsLabel,
|
||||
mode,
|
||||
isViewportLarge,
|
||||
isViewportWide,
|
||||
showHeaderControls,
|
||||
title,
|
||||
tooltipLabelFormat,
|
||||
tooltipValueFormat,
|
||||
tooltipTitle,
|
||||
type,
|
||||
valueType,
|
||||
xFormat,
|
||||
x2Format,
|
||||
interval,
|
||||
valueType,
|
||||
type,
|
||||
isRequesting,
|
||||
} = this.props;
|
||||
let { yFormat } = this.props;
|
||||
const legendDirection = mode === 'time-comparison' && isViewportWide ? 'row' : 'column';
|
||||
const chartDirection = ( mode === 'item-comparison' ) && isViewportWide ? 'row' : 'column';
|
||||
|
||||
const legendPosition = this.getLegendPosition();
|
||||
const legendDirection = legendPosition === 'top' ? 'row' : 'column';
|
||||
const chartDirection = legendPosition === 'side' ? 'row' : 'column';
|
||||
|
||||
const chartHeight = this.getChartHeight();
|
||||
const legend = (
|
||||
|
@ -241,7 +257,7 @@ class Chart extends Component {
|
|||
data={ orderedKeys }
|
||||
handleLegendHover={ this.handleLegendHover }
|
||||
handleLegendToggle={ this.handleLegendToggle }
|
||||
interactive={ mode !== 'block' }
|
||||
interactive={ interactiveLegend }
|
||||
legendDirection={ legendDirection }
|
||||
legendValueFormat={ tooltipValueFormat }
|
||||
totalLabel={ sprintf( itemsLabel, orderedKeys.length ) }
|
||||
|
@ -267,10 +283,10 @@ class Chart extends Component {
|
|||
}
|
||||
return (
|
||||
<div className="woocommerce-chart">
|
||||
{ mode !== 'block' &&
|
||||
{ showHeaderControls && (
|
||||
<div className="woocommerce-chart__header">
|
||||
<H className="woocommerce-chart__title">{ title }</H>
|
||||
{ isViewportWide && legendDirection === 'row' && legend }
|
||||
{ legendPosition === 'top' && legend }
|
||||
{ this.renderIntervalSelector() }
|
||||
<NavigableMenu
|
||||
className="woocommerce-chart__types"
|
||||
|
@ -301,7 +317,7 @@ class Chart extends Component {
|
|||
/>
|
||||
</NavigableMenu>
|
||||
</div>
|
||||
}
|
||||
) }
|
||||
<Section component={ false }>
|
||||
<div
|
||||
className={ classNames(
|
||||
|
@ -310,7 +326,7 @@ class Chart extends Component {
|
|||
) }
|
||||
ref={ this.chartBodyRef }
|
||||
>
|
||||
{ isViewportWide && legendDirection === 'column' && mode !== 'block' && legend }
|
||||
{ legendPosition === 'side' && legend }
|
||||
{ isRequesting && (
|
||||
<Fragment>
|
||||
<span className="screen-reader-text">
|
||||
|
@ -328,7 +344,7 @@ class Chart extends Component {
|
|||
height={ chartHeight }
|
||||
interval={ interval }
|
||||
margin={ margin }
|
||||
mode={ mode === 'block' ? 'item-comparison' : mode }
|
||||
mode={ mode }
|
||||
orderedKeys={ orderedKeys }
|
||||
tooltipLabelFormat={ tooltipLabelFormat }
|
||||
tooltipValueFormat={ tooltipValueFormat }
|
||||
|
@ -343,7 +359,9 @@ class Chart extends Component {
|
|||
/>
|
||||
) }
|
||||
</div>
|
||||
{ ( ! isViewportWide || mode === 'block' ) && <div className="woocommerce-chart__footer">{ legend }</div> }
|
||||
{ ( legendPosition === 'bottom' ) && (
|
||||
<div className="woocommerce-chart__footer">{ legend }</div>
|
||||
) }
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
|
@ -351,6 +369,10 @@ class Chart extends Component {
|
|||
}
|
||||
|
||||
Chart.propTypes = {
|
||||
/**
|
||||
* Allowed intervals to show in a dropdown.
|
||||
*/
|
||||
allowedIntervals: PropTypes.array,
|
||||
/**
|
||||
* An array of data.
|
||||
*/
|
||||
|
@ -363,6 +385,11 @@ Chart.propTypes = {
|
|||
* Label describing the legend items.
|
||||
*/
|
||||
itemsLabel: PropTypes.string,
|
||||
/**
|
||||
* `item-comparison` (default) or `time-comparison`, this is used to generate correct
|
||||
* ARIA properties.
|
||||
*/
|
||||
mode: PropTypes.oneOf( [ 'item-comparison', 'time-comparison' ] ),
|
||||
/**
|
||||
* Current path
|
||||
*/
|
||||
|
@ -371,6 +398,35 @@ Chart.propTypes = {
|
|||
* The query string represented in object form
|
||||
*/
|
||||
query: PropTypes.object,
|
||||
/**
|
||||
* Whether the legend items can be activated/deactivated.
|
||||
*/
|
||||
interactiveLegend: PropTypes.bool,
|
||||
/**
|
||||
* Interval specification (hourly, daily, weekly etc).
|
||||
*/
|
||||
interval: PropTypes.oneOf( [ 'hour', 'day', 'week', 'month', 'quarter', 'year' ] ),
|
||||
/**
|
||||
* Information about the currently selected interval, and set of allowed intervals for the chart. See `getIntervalsForQuery`.
|
||||
*/
|
||||
intervalData: PropTypes.object,
|
||||
/**
|
||||
* Render a chart placeholder to signify an in-flight data request.
|
||||
*/
|
||||
isRequesting: PropTypes.bool,
|
||||
/**
|
||||
* Position the legend must be displayed in. If it's not defined, it's calculated
|
||||
* depending on the viewport width and the mode.
|
||||
*/
|
||||
legendPosition: PropTypes.oneOf( [ 'bottom', 'side', 'top' ] ),
|
||||
/**
|
||||
* Wether header UI controls must be displayed.
|
||||
*/
|
||||
showHeaderControls: PropTypes.bool,
|
||||
/**
|
||||
* A title describing this chart.
|
||||
*/
|
||||
title: PropTypes.string,
|
||||
/**
|
||||
* A datetime formatting string or overriding function to format the tooltip label.
|
||||
*/
|
||||
|
@ -383,6 +439,14 @@ Chart.propTypes = {
|
|||
* A string to use as a title for the tooltip. Takes preference over `tooltipLabelFormat`.
|
||||
*/
|
||||
tooltipTitle: PropTypes.string,
|
||||
/**
|
||||
* Chart type of either `line` or `bar`.
|
||||
*/
|
||||
type: PropTypes.oneOf( [ 'bar', 'line' ] ),
|
||||
/**
|
||||
* What type of data is to be displayed? Number, Average, String?
|
||||
*/
|
||||
valueType: PropTypes.string,
|
||||
/**
|
||||
* A datetime formatting string, passed to d3TimeFormat.
|
||||
*/
|
||||
|
@ -395,53 +459,22 @@ Chart.propTypes = {
|
|||
* A number formatting string, passed to d3Format.
|
||||
*/
|
||||
yFormat: PropTypes.string,
|
||||
/**
|
||||
* `item-comparison` (default) or `time-comparison`, this is used to generate correct
|
||||
* ARIA properties.
|
||||
*/
|
||||
mode: PropTypes.oneOf( [ 'block', 'item-comparison', 'time-comparison' ] ),
|
||||
/**
|
||||
* A title describing this chart.
|
||||
*/
|
||||
title: PropTypes.string,
|
||||
/**
|
||||
* Chart type of either `line` or `bar`.
|
||||
*/
|
||||
type: PropTypes.oneOf( [ 'bar', 'line' ] ),
|
||||
/**
|
||||
* Information about the currently selected interval, and set of allowed intervals for the chart. See `getIntervalsForQuery`.
|
||||
*/
|
||||
intervalData: PropTypes.object,
|
||||
/**
|
||||
* Interval specification (hourly, daily, weekly etc).
|
||||
*/
|
||||
interval: PropTypes.oneOf( [ 'hour', 'day', 'week', 'month', 'quarter', 'year' ] ),
|
||||
/**
|
||||
* Allowed intervals to show in a dropdown.
|
||||
*/
|
||||
allowedIntervals: PropTypes.array,
|
||||
/**
|
||||
* What type of data is to be displayed? Number, Average, String?
|
||||
*/
|
||||
valueType: PropTypes.string,
|
||||
/**
|
||||
* Render a chart placeholder to signify an in-flight data request.
|
||||
*/
|
||||
isRequesting: PropTypes.bool,
|
||||
};
|
||||
|
||||
Chart.defaultProps = {
|
||||
data: [],
|
||||
dateParser: '%Y-%m-%dT%H:%M:%S',
|
||||
interactiveLegend: true,
|
||||
interval: 'day',
|
||||
isRequesting: false,
|
||||
mode: 'time-comparison',
|
||||
showHeaderControls: true,
|
||||
tooltipLabelFormat: '%B %d, %Y',
|
||||
tooltipValueFormat: ',',
|
||||
type: 'line',
|
||||
xFormat: '%d',
|
||||
x2Format: '%b %Y',
|
||||
yFormat: '$.3s',
|
||||
mode: 'time-comparison',
|
||||
type: 'line',
|
||||
interval: 'day',
|
||||
isRequesting: false,
|
||||
};
|
||||
|
||||
export default withViewportMatch( {
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
*/
|
||||
import { Component } from '@wordpress/element';
|
||||
import PropTypes from 'prop-types';
|
||||
import { Spinner } from '@wordpress/components';
|
||||
|
||||
/**
|
||||
* `ChartPlaceholder` displays a large loading indiciator for use in place of a `Chart` while data is loading.
|
||||
|
@ -13,7 +14,9 @@ class ChartPlaceholder extends Component {
|
|||
const { height } = this.props;
|
||||
|
||||
return (
|
||||
<div aria-hidden="true" className="woocommerce-chart-placeholder" style={ { height } } />
|
||||
<div aria-hidden="true" className="woocommerce-chart-placeholder" style={ { height } }>
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -56,6 +56,12 @@
|
|||
@include placeholder();
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
.components-spinner {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.woocommerce-chart__interval-select {
|
||||
|
|
|
@ -4,30 +4,43 @@
|
|||
*/
|
||||
import { Component, Fragment } from '@wordpress/element';
|
||||
import { SelectControl, TextControl } from '@wordpress/components';
|
||||
import { get, find, partial } from 'lodash';
|
||||
import { get, find, partial, isArray } from 'lodash';
|
||||
import interpolateComponents from 'interpolate-components';
|
||||
import classnames from 'classnames';
|
||||
import { _x } from '@wordpress/i18n';
|
||||
import { sprintf, __, _x } from '@wordpress/i18n';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import TextControlWithAffixes from '../../text-control-with-affixes';
|
||||
import { textContent } from './utils';
|
||||
|
||||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
import { formatCurrency } from '@woocommerce/currency';
|
||||
|
||||
class NumberFilter extends Component {
|
||||
getBetweenString() {
|
||||
return _x(
|
||||
'{{rangeStart /}}{{span}}and{{/span}}{{rangeEnd /}}',
|
||||
'{{rangeStart /}}{{span}} and {{/span}}{{rangeEnd /}}',
|
||||
'Numerical range inputs arranged on a single line',
|
||||
'wc-admin'
|
||||
);
|
||||
}
|
||||
|
||||
getLegend( filter, config ) {
|
||||
getScreenReaderText( filter, config ) {
|
||||
const inputType = get( config, [ 'input', 'type' ], 'number' );
|
||||
const rule = find( config.rules, { value: filter.rule } ) || {};
|
||||
let [ rangeStart, rangeEnd ] = ( filter.value || '' ).split( ',' );
|
||||
let [ rangeStart, rangeEnd ] = isArray( filter.value ) ? filter.value : [ filter.value ];
|
||||
|
||||
// Return nothing if we're missing input(s)
|
||||
if (
|
||||
! rangeStart ||
|
||||
( 'between' === rule.value && ! rangeEnd )
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ( 'currency' === inputType ) {
|
||||
rangeStart = formatCurrency( rangeStart );
|
||||
|
@ -47,16 +60,16 @@ class NumberFilter extends Component {
|
|||
} );
|
||||
}
|
||||
|
||||
return interpolateComponents( {
|
||||
return textContent( interpolateComponents( {
|
||||
mixedString: config.labels.title,
|
||||
components: {
|
||||
filter: <span>{ filterStr }</span>,
|
||||
rule: <span>{ rule.label }</span>,
|
||||
filter: <Fragment>{ filterStr }</Fragment>,
|
||||
rule: <Fragment>{ rule.label }</Fragment>,
|
||||
},
|
||||
} );
|
||||
} ) );
|
||||
}
|
||||
|
||||
getFormControl( type, value, onChange ) {
|
||||
getFormControl( { type, value, label, onChange } ) {
|
||||
if ( 'currency' === type ) {
|
||||
const currencySymbol = get( wcSettings, [ 'currency', 'symbol' ] );
|
||||
const symbolPosition = get( wcSettings, [ 'currency', 'position' ] );
|
||||
|
@ -68,6 +81,7 @@ class NumberFilter extends Component {
|
|||
className="woocommerce-filters-advanced__input"
|
||||
type="number"
|
||||
value={ value || '' }
|
||||
aria-label={ label }
|
||||
onChange={ onChange }
|
||||
/>
|
||||
: <TextControlWithAffixes
|
||||
|
@ -75,6 +89,7 @@ class NumberFilter extends Component {
|
|||
className="woocommerce-filters-advanced__input"
|
||||
type="number"
|
||||
value={ value || '' }
|
||||
aria-label={ label }
|
||||
onChange={ onChange }
|
||||
/>
|
||||
);
|
||||
|
@ -85,6 +100,7 @@ class NumberFilter extends Component {
|
|||
className="woocommerce-filters-advanced__input"
|
||||
type="number"
|
||||
value={ value || '' }
|
||||
aria-label={ label }
|
||||
onChange={ onChange }
|
||||
/>
|
||||
);
|
||||
|
@ -98,40 +114,71 @@ class NumberFilter extends Component {
|
|||
return this.getRangeInput();
|
||||
}
|
||||
|
||||
const [ rangeStart, rangeEnd ] = ( filter.value || '' ).split( ',' );
|
||||
const [ rangeStart, rangeEnd ] = isArray( filter.value ) ? filter.value : [ filter.value ];
|
||||
if ( Boolean( rangeEnd ) ) {
|
||||
// If there's a value for rangeEnd, we've just changed from "between"
|
||||
// to "less than" or "more than" and need to transition the value
|
||||
onFilterChange( filter.key, 'value', rangeStart || rangeEnd );
|
||||
}
|
||||
|
||||
return this.getFormControl(
|
||||
inputType,
|
||||
rangeStart || rangeEnd,
|
||||
partial( onFilterChange, filter.key, 'value' )
|
||||
);
|
||||
let labelFormat = '';
|
||||
|
||||
if ( 'lessthan' === filter.rule ) {
|
||||
/* eslint-disable-next-line max-len */
|
||||
/* translators: Sentence fragment, "maximum amount" refers to a numeric value the field must be less than. Screenshot for context: https://cloudup.com/cmv5CLyMPNQ */
|
||||
labelFormat = _x( '%(field)s maximum amount', 'maximum value input', 'wc-admin' );
|
||||
} else {
|
||||
/* eslint-disable-next-line max-len */
|
||||
/* translators: Sentence fragment, "minimum amount" refers to a numeric value the field must be more than. Screenshot for context: https://cloudup.com/cmv5CLyMPNQ */
|
||||
labelFormat = _x( '%(field)s minimum amount', 'minimum value input', 'wc-admin' );
|
||||
}
|
||||
|
||||
return this.getFormControl( {
|
||||
type: inputType,
|
||||
value: rangeStart || rangeEnd,
|
||||
label: sprintf( labelFormat, { field: get( config, [ 'labels', 'add' ] ) } ),
|
||||
onChange: partial( onFilterChange, filter.key, 'value' ),
|
||||
} );
|
||||
}
|
||||
|
||||
getRangeInput() {
|
||||
const { config, filter, onFilterChange } = this.props;
|
||||
const inputType = get( config, [ 'input', 'type' ], 'number' );
|
||||
const [ rangeStart, rangeEnd ] = ( filter.value || '' ).split( ',' );
|
||||
const [ rangeStart, rangeEnd ] = isArray( filter.value ) ? filter.value : [ filter.value ];
|
||||
|
||||
const rangeStartOnChange = ( newRangeStart ) => {
|
||||
const newValue = [ newRangeStart, rangeEnd ].join( ',' );
|
||||
onFilterChange( filter.key, 'value', newValue );
|
||||
onFilterChange( filter.key, 'value', [ newRangeStart, rangeEnd ] );
|
||||
};
|
||||
|
||||
const rangeEndOnChange = ( newRangeEnd ) => {
|
||||
const newValue = [ rangeStart, newRangeEnd ].join( ',' );
|
||||
onFilterChange( filter.key, 'value', newValue );
|
||||
onFilterChange( filter.key, 'value', [ rangeStart, newRangeEnd ] );
|
||||
};
|
||||
|
||||
return interpolateComponents( {
|
||||
mixedString: this.getBetweenString(),
|
||||
components: {
|
||||
rangeStart: this.getFormControl( inputType, rangeStart, rangeStartOnChange ),
|
||||
rangeEnd: this.getFormControl( inputType, rangeEnd, rangeEndOnChange ),
|
||||
rangeStart: this.getFormControl( {
|
||||
type: inputType,
|
||||
value: rangeStart || '',
|
||||
label: sprintf(
|
||||
/* eslint-disable-next-line max-len */
|
||||
/* translators: Sentence fragment, "range start" refers to the first of two numeric values the field must be between. Screenshot for context: https://cloudup.com/cmv5CLyMPNQ */
|
||||
__( '%(field)s range start', 'wc-admin' ),
|
||||
{ field: get( config, [ 'labels', 'add' ] ) }
|
||||
),
|
||||
onChange: rangeStartOnChange,
|
||||
} ),
|
||||
rangeEnd: this.getFormControl( {
|
||||
type: inputType,
|
||||
value: rangeEnd || '',
|
||||
label: sprintf(
|
||||
/* eslint-disable-next-line max-len */
|
||||
/* translators: Sentence fragment, "range end" refers to the second of two numeric values the field must be between. Screenshot for context: https://cloudup.com/cmv5CLyMPNQ */
|
||||
__( '%(field)s range end', 'wc-admin' ),
|
||||
{ field: get( config, [ 'labels', 'add' ] ) }
|
||||
),
|
||||
onChange: rangeEndOnChange,
|
||||
} ),
|
||||
span: <span className="separator" />,
|
||||
},
|
||||
} );
|
||||
|
@ -165,11 +212,14 @@ class NumberFilter extends Component {
|
|||
),
|
||||
},
|
||||
} );
|
||||
|
||||
const screenReaderText = this.getScreenReaderText( filter, config );
|
||||
|
||||
/*eslint-disable jsx-a11y/no-noninteractive-tabindex*/
|
||||
return (
|
||||
<fieldset tabIndex="0">
|
||||
<legend className="screen-reader-text">
|
||||
{ this.getLegend( filter, config ) }
|
||||
{ labels.add || '' }
|
||||
</legend>
|
||||
<div
|
||||
className={ classnames( 'woocommerce-filters-advanced__fieldset', {
|
||||
|
@ -178,6 +228,11 @@ class NumberFilter extends Component {
|
|||
>
|
||||
{ children }
|
||||
</div>
|
||||
{ screenReaderText && (
|
||||
<span className="screen-reader-text">
|
||||
{ screenReaderText }
|
||||
</span>
|
||||
) }
|
||||
</fieldset>
|
||||
);
|
||||
/*eslint-enable jsx-a11y/no-noninteractive-tabindex*/
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { Component } from '@wordpress/element';
|
||||
import { Component, Fragment } from '@wordpress/element';
|
||||
import { SelectControl } from '@wordpress/components';
|
||||
import { find, isEqual, partial } from 'lodash';
|
||||
import PropTypes from 'prop-types';
|
||||
|
@ -13,6 +13,7 @@ import classnames from 'classnames';
|
|||
* Internal dependencies
|
||||
*/
|
||||
import Search from '../../search';
|
||||
import { textContent } from './utils';
|
||||
|
||||
class SearchFilter extends Component {
|
||||
constructor( { filter, config, query } ) {
|
||||
|
@ -51,18 +52,23 @@ class SearchFilter extends Component {
|
|||
onFilterChange( filter.key, 'value', idList );
|
||||
}
|
||||
|
||||
getLegend( filter, config ) {
|
||||
getScreenReaderText( filter, config ) {
|
||||
const { selected } = this.state;
|
||||
|
||||
if ( 0 === selected.length ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const rule = find( config.rules, { value: filter.rule } ) || {};
|
||||
const filterStr = selected.map( item => item.label ).join( ', ' );
|
||||
|
||||
return interpolateComponents( {
|
||||
return textContent( interpolateComponents( {
|
||||
mixedString: config.labels.title,
|
||||
components: {
|
||||
filter: <span>{ filterStr }</span>,
|
||||
rule: <span>{ rule.label }</span>,
|
||||
filter: <Fragment>{ filterStr }</Fragment>,
|
||||
rule: <Fragment>{ rule.label }</Fragment>,
|
||||
},
|
||||
} );
|
||||
} ) );
|
||||
}
|
||||
|
||||
render() {
|
||||
|
@ -95,11 +101,14 @@ class SearchFilter extends Component {
|
|||
),
|
||||
},
|
||||
} );
|
||||
|
||||
const screenReaderText = this.getScreenReaderText( filter, config );
|
||||
|
||||
/*eslint-disable jsx-a11y/no-noninteractive-tabindex*/
|
||||
return (
|
||||
<fieldset tabIndex="0">
|
||||
<legend className="screen-reader-text">
|
||||
{ this.getLegend( filter, config, selected ) }
|
||||
{ labels.add || '' }
|
||||
</legend>
|
||||
<div
|
||||
className={ classnames( 'woocommerce-filters-advanced__fieldset', {
|
||||
|
@ -108,6 +117,11 @@ class SearchFilter extends Component {
|
|||
>
|
||||
{ children }
|
||||
</div>
|
||||
{ screenReaderText && (
|
||||
<span className="screen-reader-text">
|
||||
{ screenReaderText }
|
||||
</span>
|
||||
) }
|
||||
</fieldset>
|
||||
);
|
||||
/*eslint-enable jsx-a11y/no-noninteractive-tabindex*/
|
||||
|
|
|
@ -2,13 +2,18 @@
|
|||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { Component } from '@wordpress/element';
|
||||
import { Component, Fragment } from '@wordpress/element';
|
||||
import { SelectControl, Spinner } from '@wordpress/components';
|
||||
import { find, partial } from 'lodash';
|
||||
import PropTypes from 'prop-types';
|
||||
import interpolateComponents from 'interpolate-components';
|
||||
import classnames from 'classnames';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { textContent } from './utils';
|
||||
|
||||
/**
|
||||
* WooCommerce dependencies
|
||||
*/
|
||||
|
@ -41,16 +46,21 @@ class SelectFilter extends Component {
|
|||
return options;
|
||||
}
|
||||
|
||||
getLegend( filter, config ) {
|
||||
getScreenReaderText( filter, config ) {
|
||||
if ( '' === filter.value ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const rule = find( config.rules, { value: filter.rule } ) || {};
|
||||
const value = find( config.input.options, { value: filter.value } ) || {};
|
||||
return interpolateComponents( {
|
||||
|
||||
return textContent( interpolateComponents( {
|
||||
mixedString: config.labels.title,
|
||||
components: {
|
||||
filter: <span>{ value.label }</span>,
|
||||
rule: <span>{ rule.label }</span>,
|
||||
filter: <Fragment>{ value.label }</Fragment>,
|
||||
rule: <Fragment>{ rule.label }</Fragment>,
|
||||
},
|
||||
} );
|
||||
} ) );
|
||||
}
|
||||
|
||||
render() {
|
||||
|
@ -83,10 +93,15 @@ class SelectFilter extends Component {
|
|||
),
|
||||
},
|
||||
} );
|
||||
|
||||
const screenReaderText = this.getScreenReaderText( filter, config );
|
||||
|
||||
/*eslint-disable jsx-a11y/no-noninteractive-tabindex*/
|
||||
return (
|
||||
<fieldset tabIndex="0">
|
||||
<legend className="screen-reader-text">{ this.getLegend( filter, config ) }</legend>
|
||||
<legend className="screen-reader-text">
|
||||
{ labels.add || '' }
|
||||
</legend>
|
||||
<div
|
||||
className={ classnames( 'woocommerce-filters-advanced__fieldset', {
|
||||
'is-english': isEnglish,
|
||||
|
@ -94,6 +109,11 @@ class SelectFilter extends Component {
|
|||
>
|
||||
{ children }
|
||||
</div>
|
||||
{ screenReaderText && (
|
||||
<span className="screen-reader-text">
|
||||
{ screenReaderText }
|
||||
</span>
|
||||
) }
|
||||
</fieldset>
|
||||
);
|
||||
/*eslint-enable jsx-a11y/no-noninteractive-tabindex*/
|
||||
|
|
|
@ -0,0 +1,83 @@
|
|||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { textContent } from '../utils';
|
||||
|
||||
describe( 'textContent()', () => {
|
||||
test( 'should get text `Hello World`', () => {
|
||||
const component = (
|
||||
<div>
|
||||
<h1>Hello</h1> World
|
||||
</div>
|
||||
);
|
||||
|
||||
expect( textContent( component ) ).toBe( 'Hello World' );
|
||||
} );
|
||||
|
||||
test( 'render variable', () => {
|
||||
const component = (
|
||||
<div>
|
||||
<h1>Hello</h1> { 'World' + '2' }
|
||||
</div>
|
||||
);
|
||||
|
||||
expect( textContent( component ) ).toBe( 'Hello World2' );
|
||||
} );
|
||||
|
||||
test( 'render variable2', () => {
|
||||
const component = (
|
||||
<div>
|
||||
<h1>Hello</h1> { 1 + 1 }
|
||||
</div>
|
||||
);
|
||||
|
||||
expect( textContent( component ) ).toBe( 'Hello 2' );
|
||||
} );
|
||||
|
||||
test( 'should output empty string', () => {
|
||||
const component = ( <div /> );
|
||||
|
||||
expect( textContent( component ) ).toBe( '' );
|
||||
} );
|
||||
|
||||
test( 'array children', () => {
|
||||
const component = (
|
||||
<div>
|
||||
<h1>Hello</h1> World
|
||||
{
|
||||
[ 'a', <h2 key="b">b</h2> ]
|
||||
}
|
||||
</div>
|
||||
);
|
||||
|
||||
expect( textContent( component ) ).toBe( 'Hello Worldab' );
|
||||
} );
|
||||
|
||||
test( 'array children with null', () => {
|
||||
const component = (
|
||||
<div>
|
||||
<h1>Hello</h1> World
|
||||
{
|
||||
[ 'a', null ]
|
||||
}
|
||||
</div>
|
||||
);
|
||||
|
||||
expect( textContent( component ) ).toBe( 'Hello Worlda' );
|
||||
} );
|
||||
|
||||
test( 'array component', () => {
|
||||
const component = ( [
|
||||
<h1>a</h1>,
|
||||
'b',
|
||||
'c',
|
||||
(
|
||||
<div>
|
||||
<h2>x</h2>y
|
||||
</div>
|
||||
),
|
||||
] );
|
||||
|
||||
expect( textContent( component ) ).toBe( 'abcxy' );
|
||||
} );
|
||||
} );
|
|
@ -0,0 +1,36 @@
|
|||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { isArray, isNumber, isString } from 'lodash';
|
||||
|
||||
/**
|
||||
* DOM Node.textContent for React components
|
||||
* See: https://github.com/rwu823/react-addons-text-content/blob/master/src/index.js
|
||||
*
|
||||
* @param {Array<string|ReactNode>} components array of components
|
||||
*
|
||||
* @returns {string} concatenated text content of all nodes
|
||||
*/
|
||||
export function textContent( components ) {
|
||||
let text = '';
|
||||
|
||||
const toText = ( component ) => {
|
||||
if ( isString( component ) || isNumber( component ) ) {
|
||||
text += component;
|
||||
} else if ( isArray( component ) ) {
|
||||
component.forEach( toText );
|
||||
} else if ( component && component.props ) {
|
||||
const { children } = component.props;
|
||||
|
||||
if ( isArray( children ) ) {
|
||||
children.forEach( toText );
|
||||
} else {
|
||||
toText( children );
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
toText( components );
|
||||
|
||||
return text;
|
||||
}
|
|
@ -10,8 +10,10 @@
|
|||
fill: $core-grey-light-900;
|
||||
}
|
||||
|
||||
.woocommerce-tag {
|
||||
margin: 8px 6px 0 0;
|
||||
&:not(.has-inline-tags) {
|
||||
.woocommerce-tag {
|
||||
margin: 8px 6px 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
&.has-inline-tags {
|
||||
|
@ -19,10 +21,6 @@
|
|||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.woocommerce-tag {
|
||||
margin: initial;
|
||||
}
|
||||
}
|
||||
|
||||
.woocommerce-search__inline-container {
|
||||
|
|
|
@ -21,6 +21,19 @@
|
|||
height: 1px;
|
||||
margin: 0 10px;
|
||||
}
|
||||
|
||||
@include breakpoint( '<782px' ) {
|
||||
&.has-interval-select {
|
||||
position: relative;
|
||||
padding-bottom: 30px;
|
||||
.woocommerce-chart__interval-select {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
padding-left: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.woocommerce-section-header__actions,
|
||||
|
@ -31,6 +44,18 @@
|
|||
display: flex;
|
||||
flex-grow: 1;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
|
||||
.components-base-control {
|
||||
padding-top: 0;
|
||||
min-height: 34px;
|
||||
}
|
||||
.components-base-control__field {
|
||||
margin-bottom: 0;
|
||||
select {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.woocommerce-ellipsis-menu__toggle {
|
||||
|
@ -48,7 +73,7 @@
|
|||
// EllipsisMenu is 24px, so to match we add 6px padding around the
|
||||
// heading text, which we know is 18px from line-height.
|
||||
padding: 3px 0;
|
||||
@include font-size( 15 );
|
||||
@include font-size( 18 );
|
||||
line-height: 2.2;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
|
|
@ -20,7 +20,7 @@ exports[`SplitButton it should render a simple split button 1`] = `
|
|||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden={true}
|
||||
aria-hidden="true"
|
||||
className="dashicon dashicons-arrow-down"
|
||||
focusable="false"
|
||||
height={20}
|
||||
|
@ -60,7 +60,7 @@ exports[`SplitButton it should render a split button with Foo as main label 1`]
|
|||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden={true}
|
||||
aria-hidden="true"
|
||||
className="dashicon dashicons-arrow-down"
|
||||
focusable="false"
|
||||
height={20}
|
||||
|
@ -103,7 +103,7 @@ exports[`SplitButton it should render a split button with a menu label 1`] = `
|
|||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden={true}
|
||||
aria-hidden="true"
|
||||
className="dashicon dashicons-arrow-down"
|
||||
focusable="false"
|
||||
height={20}
|
||||
|
@ -141,7 +141,7 @@ exports[`SplitButton it should render a split button with isPrimary theme 1`] =
|
|||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden={true}
|
||||
aria-hidden="true"
|
||||
className="dashicon dashicons-arrow-down"
|
||||
focusable="false"
|
||||
height={20}
|
||||
|
@ -193,7 +193,7 @@ exports[`SplitButton it should render a split button with pencil as main button
|
|||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden={true}
|
||||
aria-hidden="true"
|
||||
className="dashicon dashicons-arrow-down"
|
||||
focusable="false"
|
||||
height={20}
|
||||
|
|
|
@ -77,7 +77,7 @@ exports[`Tag <Tag label="foo" remove={ noop } /> should render a tag with a clos
|
|||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden={true}
|
||||
aria-hidden="true"
|
||||
className="dashicon dashicons-dismiss"
|
||||
focusable="false"
|
||||
height={20}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue