每月统计

This commit is contained in:
2026-06-08 17:18:45 +08:00
parent 007ced596d
commit dd4cfab01a
4 changed files with 382 additions and 1 deletions

View File

@@ -9,7 +9,6 @@ use app\common\controller\Backend;
use app\admin\model\Bank; use app\admin\model\Bank;
use think\exception\ValidateException; use think\exception\ValidateException;
use think\facade\Db; use think\facade\Db;
use think\facade\Request;
use Throwable; use Throwable;
class Dashboard extends Backend class Dashboard extends Backend

View File

@@ -7,6 +7,7 @@ use Throwable;
use app\admin\model\User; use app\admin\model\User;
use app\admin\model\UserMoneyLog; use app\admin\model\UserMoneyLog;
use app\common\controller\Backend; use app\common\controller\Backend;
use think\facade\Db;
class MoneyLog extends Backend class MoneyLog extends Backend
{ {
@@ -173,4 +174,95 @@ class MoneyLog extends Backend
} }
$this->success('', $history); $this->success('', $history);
} }
public function annualReport()
{
$year = $this->request->param('year/d', date('Y'));
$timeExpression = "create_time";
$list = Db::table('ba_user_money_log')
->whereRaw("FROM_UNIXTIME({$timeExpression}, '%Y') = ?", [$year])
->fieldRaw("
FROM_UNIXTIME({$timeExpression}, '%c') as month,
-- 1. DEPOSIT (分转元保留2位小数)
ROUND(SUM(CASE WHEN type IN (1, 3) THEN money / 100 ELSE 0 END), 2) as deposit_amount,
-- 2. WITHDRAW (从变更记录看提现通常存正数,这里直接累加,分转元)
ROUND(SUM(CASE WHEN type IN (2, 4) THEN money / 100 ELSE 0 END), 2) as withdraw_amount,
-- 3. TRANSACTION (DEPOSIT)
COUNT(CASE WHEN type IN (1, 3) THEN id END) as deposit_count,
-- 4. TRANSACTION (WITHDRAW)
COUNT(CASE WHEN type IN (2, 4) THEN id END) as withdraw_count,
-- 5. ACTIVE PLAYER (每月去重活跃用户)
COUNT(DISTINCT user_id) as active_player,
-- 6. FIRST DEPOSIT (首充去重人数)
COUNT(DISTINCT CASE WHEN type = 1 AND label = 1 THEN user_id END) as first_deposit_count,
-- 7. UNCLAIM RECEIPT (未领单数)
COUNT(CASE WHEN type = 1 AND label = 2 THEN id END) as unclaim_count,
-- 8. UNCLAIM AMOUNT (未领金额)
ROUND(SUM(CASE WHEN type = 1 AND label = 2 THEN money / 100 ELSE 0 END), 2) as unclaim_amount
")
->group("month")
->select()
->toArray();
$monthsData = [];
foreach ($list as $row) {
$monthsData[intval($row['month'])] = $row;
}
$rowsSkeleton = [
'deposit' => ['name' => 'DEPOSIT', 'is_price' => true],
'withdraw' => ['name' => 'WITHDRAW', 'is_price' => true],
'trans_deposit' => ['name' => 'TRANSACTION (DEPOSIT)', 'is_price' => false],
'trans_withdraw' => ['name' => 'TRANSACTION (WITHDRAW)', 'is_price' => false],
'active_player' => ['name' => 'ACTIVE PLAYER', 'is_price' => false],
'first_deposit' => ['name' => 'FIRST DEPOSIT', 'is_price' => false],
'unclaim_receipt' => ['name' => 'UNCLAIM RECEIPT', 'is_price' => false],
'unclaim_amount' => ['name' => 'UNCLAIM AMOUNT', 'is_price' => true],
];
$finalReport = [];
foreach ($rowsSkeleton as $key => $meta) {
$rowData = [
'title' => $meta['name']
];
$yearTotal = 0;
for ($m = 1; $m <= 12; $m++) {
$monthValue = 0;
if (isset($monthsData[$m])) {
$monthValue = match ($key) {
'deposit' => (float)$monthsData[$m]['deposit_amount'],
'withdraw' => (float)$monthsData[$m]['withdraw_amount'],
'trans_deposit' => (int)$monthsData[$m]['deposit_count'],
'trans_withdraw' => (int)$monthsData[$m]['withdraw_count'],
'active_player' => (int)$monthsData[$m]['active_player'],
'first_deposit' => (int)$monthsData[$m]['first_deposit_count'],
'unclaim_receipt' => (int)$monthsData[$m]['unclaim_count'],
'unclaim_amount' => (float)$monthsData[$m]['unclaim_amount'],
};
}
$rowData['month_' . $m] = $meta['is_price'] ? number_format($monthValue, 2, '.', '') : $monthValue;
$yearTotal += $monthValue;
}
$rowData['year_total'] = $meta['is_price'] ? number_format($yearTotal, 2, '.', '') : $yearTotal;
$finalReport[] = $rowData;
}
$this->success('', [
'year' => $year,
'report_table' => $finalReport
]);
}
} }

View File

@@ -19,3 +19,11 @@ export function logHistory(params: { id: number | string }) {
params, params,
}) })
} }
export function annualReport(params: { id: number | string }) {
return createAxios({
url: url + 'annualReport',
method: 'get',
params,
})
}

View File

@@ -0,0 +1,282 @@
<template>
<div class="default-main ba-table-box">
<el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
<TableHeader
:buttons="['refresh', 'add', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="
t('Quick search placeholder', { fields: t('user.moneyLog.User name') + '/' + t('user.moneyLog.User nickname') })
"
>
<el-button v-if="!isEmpty(state.userInfo)" v-blur class="table-header-operate">
<span class="table-header-operate-text">
{{ state.userInfo.username + '(ID:' + state.userInfo.id + ') ' + t('user.moneyLog.balance') + ':' + state.userInfo.money }}
</span>
</el-button>
</TableHeader>
<Table />
<PopupForm />
<el-dialog v-model="historyDialog.visible" title="Transaction Edit History" width="720px">
<p class="dialog-note">Transaction edit history is only kept for the most recent 12 months.</p>
<p class="dialog-note">Transaction 的编辑历史记录仅保存最近 12 个月</p>
<el-table v-loading="historyDialog.loading" :data="historyDialog.rows" border size="small" empty-text="No Record">
<el-table-column prop="id" label="Tx ID" width="100" />
<el-table-column prop="editedBy" label="Edit By" width="120" />
<el-table-column prop="editedTime" label="Edit Time" width="170" />
<el-table-column prop="changes" label="Changes (Old → New)" />
</el-table>
<template #footer>
<el-button @click="historyDialog.visible = false">CANCEL</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { debounce, isEmpty, parseInt } from 'lodash-es'
import { provide, reactive, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import PopupForm from './popupForm.vue'
import { add, annualReport, url } from '/@/api/backend/user/moneyLog' // 🌟 已修复:移除了别名前面的绝对斜杠
import { baTableApi } from '/@/api/common'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import scoreLog from '/@/lang/backend/zh-cn/user/scoreLog'
import { defaultOptButtons } from '/@/components/table'
defineOptions({
name: 'user/moneyLog',
})
const { t, tm } = useI18n()
const route = useRoute()
const defalutUser = (route.query.user_id ?? '') as string
const state = reactive({
userInfo: {} as anyObj,
})
interface HistoryRow {
id: number | string
editedBy: string
editedTime: string
changes: string
}
const historyDialog = reactive({
visible: false,
loading: false,
rows: [] as HistoryRow[],
})
const gameTypeMap = scoreLog.game_type as Record<string, string>
const optButtons: OptButton[] = [
{
render: 'tipButton',
name: 'history',
title: 'History',
text: '',
type: 'primary',
icon: 'fa fa-history',
class: 'table-row-history',
disabledTip: false,
click: (row: TableRow) => {
openHistory(row)
},
},
...defaultOptButtons(['edit']),
...defaultOptButtons(['delete']),
]
const toNumber = (value: unknown) => {
const number = Number(value)
return Number.isFinite(number) ? number : 0
}
const formatDateTime = (value: unknown) => {
if (typeof value === 'string' && value.trim() && !Number.isFinite(Number(value))) {
return value
}
const timestamp = toNumber(value)
if (!timestamp) return ''
const date = new Date(timestamp * 1000)
const pad = (number: number) => number.toString().padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
const stringifyChange = (history: Record<string, unknown>) => {
if (history.bank_befter !== undefined || history.bank_after !== undefined) {
return `Bank:${history.bank_befter ?? ''}${history.bank_after ?? ''}`
}
return JSON.stringify(history)
}
const mapHistory = (history: Record<string, unknown>): HistoryRow => ({
id: (history.id || history.money_log_id || '') as number | string,
editedBy: String(history.admin_name || ''),
editedTime: formatDateTime(history.create_time),
changes: stringifyChange(history),
})
const openHistory = (row: TableRow) => {
historyDialog.visible = true
historyDialog.loading = true
historyDialog.rows = []
annualReport({ id: row.id })
.then((res) => {
const data = Array.isArray(res.data) ? res.data : res.data?.list
historyDialog.rows = Array.isArray(data) ? data.map((item) => mapHistory(item as Record<string, unknown>)) : []
})
.finally(() => {
historyDialog.loading = false
})
}
// 🌟 核心修改点:在实例化之前强行改掉 API 的 index 映射路径
const myTableApi = new baTableApi(url)
myTableApi.actionUrl.set('index', 'admin/user.MoneyLog/annualReport')
const baTable = new baTableClass(
myTableApi, // 🌟 传入已经被提前覆写好映射的驱动实例
{
column: [
{ type: 'selection', align: 'center', operator: false },
{
label: t('user.moneyLog.Created by'),
prop: 'admin.username',
align: 'center',
width: 70,
formatter: (row: TableRow) => {
return row.admin?.username || 'web'
},
},
{ label: t('user.moneyLog.User name'), prop: 'user.jk_username', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
{ label: t('user.moneyLog.Change balance'), prop: 'money', align: 'center', operator: 'RANGE', sortable: 'custom' },
{ label: t('user.moneyLog.bank_id'), prop: 'bank.bank_name', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
{ label: t('user.moneyLog.Transaction id'), prop: 'transaction_id', align: 'center', operator: 'RANGE' },
{
label: t('user.moneyLog.Game Ticket'),
prop: 'scoreLog',
align: 'center',
formatter: (row: TableRow) => {
if (!row.scoreLog || row.scoreLog.length === 0) return '-'
return row.scoreLog
.map((item: any) => {
const gameName = gameTypeMap[String(item.game_type)] || item.game_type
return `${gameName}: ${item.score}`
})
.join(' | ')
},
},
{
label: t('user.moneyLog.type'),
prop: 'type',
align: 'center',
operator: 'eq',
sortable: false,
render: 'tag',
custom: {
'1': 'success',
'2': 'danger',
'3': 'success',
'4': 'danger',
},
replaceValue: { ...tm('user.moneyLog.type_list') },
},
{
label: t('user.moneyLog.remarks'),
prop: 'memo',
align: 'center',
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
showOverflowTooltip: true,
},
{ label: t('Create time'), prop: 'create_time', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
{ label: t('Operate'), align: 'center', width: '130', render: 'buttons', buttons: optButtons },
],
dblClickNotEditColumn: ['all'],
},
{
defaultItems: {
user_id: defalutUser,
memo: '',
},
}
)
// 表单提交后
baTable.after.onSubmit = () => {
getUserInfo(baTable.comSearch.form.user_id)
}
baTable.after.onTableHeaderAction = ({ event }) => {
if (event == 'refresh') {
getUserInfo(baTable.comSearch.form.user_id)
}
}
baTable.before.onTableAction = ({ event }) => {
// 公共搜索逻辑
if (event === 'com-search') {
baTable.table.filter!.search = baTable.getComSearchData()
for (const key in baTable.table.filter!.search) {
if (['money', 'before', 'after'].includes(baTable.table.filter!.search[key].field)) {
const val = (baTable.table.filter!.search[key].val as string).split(',')
const newVal: (string | number)[] = []
for (const k in val) {
newVal.push(isNaN(parseFloat(val[k])) ? '' : parseFloat(val[k]) * 100)
}
baTable.table.filter!.search[key].val = newVal.join(',')
}
}
baTable.onTableHeaderAction('refresh', { event: 'com-search', data: baTable.table.filter!.search })
return false
}
}
// 如果年报接口返回了特殊的聚合统计数据(如 search_result在这里捕获存进表格
baTable.after.onTableAction = ({ event, res }) => {
if (event === 'get-data' && res && res.data) {
if (res.data.search_result) {
baTable.table.extend = {
...baTable.table.extend,
searchResult: res.data.search_result
}
}
}
}
baTable.mount()
baTable.getData()
provide('baTable', baTable)
const getUserInfo = debounce((userId: string) => {
if (userId && parseInt(userId) > 0) {
add(userId).then((res) => {
state.userInfo = res.data.user
})
} else {
state.userInfo = {}
}
}, 300)
getUserInfo(baTable.comSearch.form.user_id)
watch(
() => baTable.comSearch.form.user_id,
(newVal) => {
baTable.form.defaultItems!.user_id = newVal
getUserInfo(newVal)
}
)
</script>
<style scoped lang="scss"></style>