Skip to content

Commit

Permalink
Split TableStatistic into simple Statistic and Summary
Browse files Browse the repository at this point in the history
  • Loading branch information
juneszh committed Sep 19, 2022
1 parent 124cca2 commit 3355c7b
Show file tree
Hide file tree
Showing 7 changed files with 208 additions and 123 deletions.
137 changes: 104 additions & 33 deletions npm/src/components/Table.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ const Table = props => {
const actionRef = useRef();
const modelRef = useRef();

const [statJustify, setStatJustify] = useState('space-evenly');
const [requestStatistic, setRequestStatistic] = useState({});
const [statisticJustify, setStatisticJustify] = useState('space-evenly');

const statSize = useResizeDetector({
handleWidth: false,
Expand Down Expand Up @@ -178,12 +179,13 @@ const Table = props => {
danger={buttonValue.danger ?? undefined}
size='small'
onClick={(e) => { e.preventDefault(); buttonAction(buttonValue, record); }}
>{buttonValue.locale ? localeValue(buttonValue.title) : buttonValue.title}</Button>
children={buttonValue.locale ? localeValue(buttonValue.title) : buttonValue.title}
/>
);
}
}
}
return buttons ? <Space wrap>{buttons}</Space> : null;
return buttons ? <Space wrap children={buttons} /> : null;
};
}

Expand Down Expand Up @@ -275,16 +277,17 @@ const Table = props => {
href={buttonHref(buttonValue)}
danger={buttonValue.danger ?? undefined}
onClick={(e) => { e.preventDefault(); buttonAction(buttonValue); }}
>{buttonValue.locale ? localeValue(buttonValue.title) : buttonValue.title}</Button>);
children={buttonValue.locale ? localeValue(buttonValue.title) : buttonValue.title}
/>);
}
}

useEffect(() => {
if (statSize.height) {
if (statSize.height > 100) {
setStatJustify('space-between');
setStatisticJustify('start');
} else {
setStatJustify('space-evenly');
setStatisticJustify('space-evenly');
}
}
}, [statSize.height]);
Expand All @@ -303,12 +306,23 @@ const Table = props => {
params._sort = sort[params._order];
}
const result = await ajax(window.location.pathname + '?' + new URLSearchParams(params).toString());
return (result && result.error === 0) ? {
success: true,
data: result.data.list,
total: result.data.count,
} : false;
if (result && result.error === 0) {
setRequestStatistic(result.data.statistic ?? {});
return {
success: true,
data: result.data.list,
total: result.data.count,
};
} else {
setRequestStatistic({});
return {
success: false,
data: [],
total: 0,
};
}
}}
revalidateOnFocus={false}
rowKey='id'
search={tableSearch ? { labelWidth: 'auto' } : false}
pagination={{
Expand All @@ -332,45 +346,102 @@ const Table = props => {
href={buttonHref(buttonValue, selectedRowKeys)}
danger={buttonValue.danger ?? undefined}
onClick={(e) => { e.preventDefault(); buttonAction(buttonValue, selectedRowKeys); }}
>{buttonValue.locale ? localeValue(buttonValue.title) : buttonValue.title}</Button>
children={buttonValue.locale ? localeValue(buttonValue.title) : buttonValue.title}
/>
);
}
}
return <Space wrap>{buttons}</Space>;
return <Space wrap children={buttons} />;
}}
columnsState={{
persistenceKey: window.location.pathname,
persistenceType: 'sessionStorage',
options={{
setting: false
}}
summary={notEmpty(global.config.summary) ? pageData => {
let sumVisible = false;
let avgVisible = false;
let sumCells = [];
let avgCells = [];

if (notEmpty(columns) && notEmpty(pageData)) {
let titleIndex = '0';
let summaryColumns = [];

if (notEmpty(global.config.batch.button)) {
titleIndex = '1';
summaryColumns.push('_batch')
}
for (const column of Object.values(columns)) {
summaryColumns.push(column.dataIndex)
}

for (const [index, key] of Object.entries(summaryColumns)) {
if (global.config.summary[key]) {
let precision = global.config.summary[key].precision ?? 2;
let sum = pageData.reduce((pre, cur) => +cur[key] + pre, 0);
let result = sum.toFixed(precision);
sumVisible = true;
sumCells.push(
<ProTable.Summary.Cell className='ant-table-column-sort' index={index} >
{index === titleIndex ? <><span style={{ float: 'left' }} children={localeValue(':sum')} />{result}</> : result}
</ProTable.Summary.Cell>
);
if (global.config.summary[key].type === 'sum') {
avgCells.push(
<ProTable.Summary.Cell className='ant-table-column-sort' index={index} >
{index === titleIndex ? <span style={{ float: 'left' }} children={localeValue(':avg')} /> : undefined}
</ProTable.Summary.Cell>
);
} else {
avgVisible = true;
result = (sum / pageData.length).toFixed(precision);
avgCells.push(
<ProTable.Summary.Cell className='ant-table-column-sort' index={index} >
{index === titleIndex ? <><span style={{ float: 'left' }} children={localeValue(':avg')} />{result}</> : result}
</ProTable.Summary.Cell>
);
}
} else {
sumCells.push(
<ProTable.Summary.Cell className='ant-table-column-sort' index={index} >
{index === titleIndex ? <span style={{ float: 'left' }} children={localeValue(':sum')} /> : undefined}
</ProTable.Summary.Cell>
);
avgCells.push(
<ProTable.Summary.Cell className='ant-table-column-sort' index={index} >
{index === titleIndex ? <span style={{ float: 'left' }} children={localeValue(':avg')} /> : undefined}
</ProTable.Summary.Cell>
);
}
}
}

return sumVisible || avgVisible ? (
<ProTable.Summary>
{sumVisible ? (<ProTable.Summary.Row style={{ textAlign: 'right' }} children={sumCells} />) : undefined}
{avgVisible ? (<ProTable.Summary.Row style={{ textAlign: 'right' }} children={avgCells} />) : undefined}
</ProTable.Summary>
) : undefined;
} : undefined}
tableExtraRender={notEmpty(global.config.statistic) ? (_, pageData) => {
const statistic = [];
for (const value of Object.values(global.config.statistic)) {
let result = pageData.reduce((pre, cur) => +cur[value.key] + pre, 0);
if (value.type === 'avg') {
result = result / pageData.length;
for (const [key, value] of Object.entries(global.config.statistic)) {
let statValue = value.value ?? undefined;
if (notEmpty(requestStatistic)) {
statValue = requestStatistic[key] ?? statValue;
}
let columnTitle = localeValue(global.config.column[value.key].title);
let statisticTitle = localeValue(value.title).replace('{{field}}', columnTitle);
statistic.push(
<Col>
<Statistic
valueStyle={{ textAlign: 'center' }}
title={statisticTitle}
value={result}
precision={(value.precision && value.precision > -1) ? value.precision : undefined}
prefix={(value.prefix) ?? undefined}
suffix={(value.suffix) ?? undefined}
groupSeparator={(value.thousandsSeparator) ?? undefined}
decimalSeparator={(value.decimalSeparator) ?? undefined}
style={{ textAlign: 'center' }}
title={value.title}
value={statValue}
/>
</Col>
);
}
return (
<Card>
<Row gutter={[16, 16]} justify={statJustify} ref={statSize.ref}>
{statistic}
</Row>
<Row gutter={[16, 16]} justify={statisticJustify} ref={statSize.ref} children={statistic} />
</Card>
);
} : undefined}
Expand Down
4 changes: 2 additions & 2 deletions npm/src/locale/en_US.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ const i18n = {
':success': 'Success',
':confirm_password': 'Confirm password',
':confirm_field': 'Different from {{field}}',
':sum': 'Sum of {{field}}',
':avg': 'Avg of {{field}}',
':sum': 'Sum',
':avg': 'Avg',
':upload_failed': 'Upload failed',
};

Expand Down
4 changes: 2 additions & 2 deletions npm/src/locale/zh_CN.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ const i18n = {
':success': '操作成功',
':confirm_password': '确认密码',
':confirm_field': '与{{field}}不一致',
':sum': '{{field}}合计',
':avg': '{{field}}平均',
':sum': '合计',
':avg': '平均',
':upload_failed': '上传失败',
};

Expand Down
2 changes: 1 addition & 1 deletion src/Admin/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public static function render(string $table, ?callable $middleware = null)
$cache->delete($table . '_enum_list');

if (is_callable($middleware)) {
$middleware('return', $rsId);
$middleware('api', $rsId);
}

Model::userLog($userId, true);
Expand Down
60 changes: 36 additions & 24 deletions src/Admin/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ class Table
{
public static array $config = [];
private static int $buttonIndex = 0;
private static int $statisticIndex = 0;

/**
* Create a colum
Expand Down Expand Up @@ -68,22 +67,35 @@ public static function button(string $form): TableButton
return new TableButton(self::$buttonIndex);
}

/**
* Create a column summary
*
* @param string $key
* @return TableSummary
*/
public static function summary(string $key): TableSummary
{
self::$config[__FUNCTION__][$key] = [
'type' => 'sum',
];

return new TableSummary($key);
}

/**
* Create a statistic
*
* @param string $key
* @return TableStatistic
* @return TableStatistic
*/
public static function statistic(string $key): TableStatistic
{
++self::$statisticIndex;
self::$config[__FUNCTION__][self::$statisticIndex] = [
self::$config[__FUNCTION__][$key] = [
'key' => $key,
'title' => ':sum',
'type' => 'sum',
'title' => $key,
];

return new TableStatistic(self::$statisticIndex);
return new TableStatistic($key);
}

/**
Expand All @@ -100,16 +112,6 @@ public static function statistic(string $key): TableStatistic
*/
public static function render(string $table, ?callable $middleware = null)
{

$page = (int) (Request::$data['current'] ?? 1);
$limit = (int) (Request::$data['pageSize'] ?? 20);
$limit = $limit < 100 ? $limit : 100;
$order = trim(Request::$data['_order'] ?? '') ?: 'id';
$sort = trim(Request::$data['_sort'] ?? '') ?: 'asc';

$sortLimit = ['ascend' => 'asc', 'descend' => 'desc'];
$sort = $sortLimit[$sort] ?? 'asc';

$userId = Auth::getUserId();
$userInfo = Model::getUserInfo($userId);

Expand Down Expand Up @@ -156,11 +158,11 @@ public static function render(string $table, ?callable $middleware = null)
}
}

$statistic = [];
if (isset(Table::$config['statistic'])) {
foreach (Table::$config['statistic'] as $v) {
if (isset($column[$v['key']])) {
$statistic[] = $v;
$summary = [];
if (isset(Table::$config['summary'])) {
foreach (Table::$config['summary'] as $k => $v) {
if (isset($column[$k])) {
$summary[$k] = $v;
}
}
}
Expand All @@ -169,7 +171,8 @@ public static function render(string $table, ?callable $middleware = null)
'column' => $column,
'toolbar' => $toolbar,
'batch' => $batch,
'statistic' => $statistic,
'summary' => $summary,
'statistic' => Table::$config['statistic'] ?? [],
];

if (is_callable($middleware)) {
Expand All @@ -180,6 +183,15 @@ public static function render(string $table, ?callable $middleware = null)

Response::render('public/alight-admin/index.html', ['title' => Request::$data['_title'] ?? '', 'script' => Admin::globalScript('Table', $renderData)]);
} else {
$page = (int) (Request::$data['current'] ?? 1);
$limit = (int) (Request::$data['pageSize'] ?? 20);
$limit = $limit < 100 ? $limit : 100;
$order = trim(Request::$data['_order'] ?? '') ?: 'id';
$sort = trim(Request::$data['_sort'] ?? '') ?: 'asc';

$sortLimit = ['ascend' => 'asc', 'descend' => 'desc'];
$sort = $sortLimit[$sort] ?? 'asc';

$column = [];
if (isset(Table::$config['column'])) {
foreach (Table::$config['column'] as $k => $v) {
Expand Down Expand Up @@ -210,7 +222,7 @@ public static function render(string $table, ?callable $middleware = null)
];

if (is_callable($middleware)) {
$middleware('return', $resData);
$middleware('api', $resData);
}

Response::api(0, $resData);
Expand Down
Loading

0 comments on commit 3355c7b

Please sign in to comment.