重构初始化

This commit is contained in:
技术老胡
2026-04-15 11:45:46 +08:00
parent 72d72d735b
commit 7612026773
381 changed files with 28287 additions and 14717 deletions

View File

@@ -1,34 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\services\AdminService;
use support\Request;
/**
* 管理员控制器
*/
class AdminController extends BaseController
{
public function __construct(
protected AdminService $adminService
) {
}
/**
* GET /admin/getUserInfo
*
* 获取当前登录管理员信息
*/
public function getUserInfo(Request $request)
{
$adminId = $this->currentUserId($request);
if ($adminId <= 0) {
return $this->fail('未获取到用户信息,请先登录', 401);
}
$data = $this->adminService->getInfoById($adminId);
return $this->success($data);
}
}

View File

@@ -1,55 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\services\AuthService;
use app\services\CaptchaService;
use support\Request;
/**
* 认证控制器
*
* 处理登录、验证码等认证相关接口
*/
class AuthController extends BaseController
{
public function __construct(
protected CaptchaService $captchaService,
protected AuthService $authService
) {
}
/**
* GET /captcha
*
* 生成验证码
*/
public function captcha(Request $request)
{
$data = $this->captchaService->generate();
return $this->success($data);
}
/**
* POST /login
*
* 用户登录
*/
public function login(Request $request)
{
$username = $request->post('username', '');
$password = $request->post('password', '');
$verifyCode = $request->post('verifyCode', '');
$captchaId = $request->post('captchaId', '');
// 参数校验
if (empty($username) || empty($password) || empty($verifyCode) || empty($captchaId)) {
return $this->fail('请填写完整登录信息', 400);
}
$data = $this->authService->login($username, $password, $verifyCode, $captchaId);
return $this->success($data);
}
}

View File

@@ -1,651 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\repositories\PaymentChannelRepository;
use app\repositories\PaymentMethodRepository;
use app\repositories\PaymentOrderRepository;
use app\services\ChannelRoutePolicyService;
use app\services\ChannelRouterService;
use app\services\PluginService;
use support\Request;
class ChannelController extends BaseController
{
public function __construct(
protected PaymentChannelRepository $channelRepository,
protected PaymentMethodRepository $methodRepository,
protected PaymentOrderRepository $orderRepository,
protected PluginService $pluginService,
protected ChannelRoutePolicyService $routePolicyService,
protected ChannelRouterService $channelRouterService,
) {
}
public function list(Request $request)
{
$page = max(1, (int)$request->get('page', 1));
$pageSize = max(1, (int)$request->get('page_size', 10));
$filters = $this->resolveChannelFilters($request, true);
return $this->page($this->channelRepository->searchPaginate($filters, $page, $pageSize));
}
public function detail(Request $request)
{
$id = (int)$request->get('id', 0);
if ($id <= 0) {
return $this->fail('通道ID不能为空', 400);
}
$channel = $this->channelRepository->find($id);
if (!$channel) {
return $this->fail('通道不存在', 404);
}
$methodCode = '';
if ((int)$channel->method_id > 0) {
$method = $this->methodRepository->find((int)$channel->method_id);
$methodCode = $method ? (string)$method->method_code : '';
}
try {
$configSchema = $this->pluginService->getConfigSchema((string)$channel->plugin_code, $methodCode);
$currentConfig = $channel->getConfigArray();
if (isset($configSchema['fields']) && is_array($configSchema['fields'])) {
foreach ($configSchema['fields'] as &$field) {
$fieldName = $field['field'] ?? '';
if ($fieldName !== '' && array_key_exists($fieldName, $currentConfig)) {
$field['value'] = $currentConfig[$fieldName];
}
}
unset($field);
}
} catch (\Throwable $e) {
$configSchema = ['fields' => []];
}
return $this->success([
'channel' => $channel,
'method_code' => $methodCode,
'config_schema' => $configSchema,
]);
}
public function save(Request $request)
{
$data = $request->post();
$id = (int)($data['id'] ?? 0);
$merchantId = (int)($data['merchant_id'] ?? 0);
$merchantAppId = (int)($data['merchant_app_id'] ?? ($data['app_id'] ?? 0));
$channelCode = trim((string)($data['channel_code'] ?? ($data['chan_code'] ?? '')));
$channelName = trim((string)($data['channel_name'] ?? ($data['chan_name'] ?? '')));
$pluginCode = trim((string)($data['plugin_code'] ?? ''));
$methodCode = trim((string)($data['method_code'] ?? ''));
$enabledProducts = $data['enabled_products'] ?? [];
if ($merchantId <= 0) {
return $this->fail('请选择所属商户', 400);
}
if ($merchantAppId <= 0) {
return $this->fail('请选择所属应用', 400);
}
if ($channelName === '') {
return $this->fail('请输入通道名称', 400);
}
if ($pluginCode === '' || $methodCode === '') {
return $this->fail('支付插件和支付方式不能为空', 400);
}
$method = $this->methodRepository->findAnyByCode($methodCode);
if (!$method) {
return $this->fail('支付方式不存在', 400);
}
if ($channelCode !== '') {
$exists = $this->channelRepository->findByChanCode($channelCode);
if ($exists && (int)$exists->id !== $id) {
return $this->fail('通道编码已存在', 400);
}
}
try {
$configJson = $this->pluginService->buildConfigFromForm($pluginCode, $methodCode, $data);
} catch (\Throwable $e) {
return $this->fail('插件不存在或配置错误:' . $e->getMessage(), 400);
}
$channelData = [
'mer_id' => $merchantId,
'app_id' => $merchantAppId,
'chan_code' => $channelCode !== '' ? $channelCode : 'CH' . date('YmdHis') . mt_rand(1000, 9999),
'chan_name' => $channelName,
'plugin_code' => $pluginCode,
'pay_type_id' => (int)$method->id,
'config' => array_merge($configJson, [
'enabled_products' => is_array($enabledProducts) ? array_values($enabledProducts) : [],
]),
'split_ratio' => isset($data['split_ratio']) ? (float)$data['split_ratio'] : 100,
'chan_cost' => isset($data['channel_cost']) ? (float)$data['channel_cost'] : 0,
'chan_mode' => in_array(strtolower(trim((string)($data['channel_mode'] ?? 'wallet'))), ['1', 'direct', 'merchant'], true) ? 1 : 0,
'daily_limit' => isset($data['daily_limit']) ? (float)$data['daily_limit'] : 0,
'daily_cnt' => isset($data['daily_count']) ? (int)$data['daily_count'] : 0,
'min_amount' => isset($data['min_amount']) && $data['min_amount'] !== '' ? (float)$data['min_amount'] : null,
'max_amount' => isset($data['max_amount']) && $data['max_amount'] !== '' ? (float)$data['max_amount'] : null,
'status' => (int)($data['status'] ?? 1),
'sort' => (int)($data['sort'] ?? 0),
];
if ($id > 0) {
$channel = $this->channelRepository->find($id);
if (!$channel) {
return $this->fail('通道不存在', 404);
}
$this->channelRepository->updateById($id, $channelData);
} else {
$channel = $this->channelRepository->create($channelData);
$id = (int)$channel->id;
}
return $this->success(['id' => $id], '保存成功');
}
public function toggle(Request $request)
{
$id = (int)$request->post('id', 0);
$status = $request->post('status', null);
if ($id <= 0 || $status === null) {
return $this->fail('参数错误', 400);
}
$ok = $this->channelRepository->updateById($id, ['status' => (int)$status]);
return $ok ? $this->success(null, '操作成功') : $this->fail('操作失败', 500);
}
public function monitor(Request $request)
{
$filters = $this->resolveChannelFilters($request);
$days = $this->resolveDays($request->get('days', 7));
$channels = $this->channelRepository->searchList($filters);
if ($channels->isEmpty()) {
return $this->success(['list' => [], 'summary' => $this->buildMonitorSummary([])]);
}
$orderFilters = [
'merchant_id' => $filters['merchant_id'] ?? null,
'merchant_app_id' => $filters['merchant_app_id'] ?? null,
'method_id' => $filters['method_id'] ?? null,
'created_from' => $days['created_from'],
'created_to' => $days['created_to'],
];
$channelIds = [];
foreach ($channels as $channel) {
$channelIds[] = (int)$channel->id;
}
$statsMap = $this->orderRepository->aggregateByChannel($channelIds, $orderFilters);
$rows = [];
foreach ($channels as $channel) {
$rows[] = $this->buildMonitorRow($channel->toArray(), $statsMap[(int)$channel->id] ?? []);
}
usort($rows, function (array $left, array $right) {
if (($right['health_score'] ?? 0) === ($left['health_score'] ?? 0)) {
return ($left['sort'] ?? 0) <=> ($right['sort'] ?? 0);
}
return ($right['health_score'] ?? 0) <=> ($left['health_score'] ?? 0);
});
return $this->success(['list' => $rows, 'summary' => $this->buildMonitorSummary($rows)]);
}
public function polling(Request $request)
{
$filters = $this->resolveChannelFilters($request);
$days = $this->resolveDays($request->get('days', 7));
$channels = $this->channelRepository->searchList($filters);
$testAmount = $request->get('test_amount', null);
$testAmount = ($testAmount === null || $testAmount === '') ? null : (float)$testAmount;
if ($channels->isEmpty()) {
return $this->success(['list' => [], 'summary' => $this->buildPollingSummary([])]);
}
$orderFilters = [
'merchant_id' => $filters['merchant_id'] ?? null,
'merchant_app_id' => $filters['merchant_app_id'] ?? null,
'method_id' => $filters['method_id'] ?? null,
'created_from' => $days['created_from'],
'created_to' => $days['created_to'],
];
$channelIds = [];
foreach ($channels as $channel) {
$channelIds[] = (int)$channel->id;
}
$statsMap = $this->orderRepository->aggregateByChannel($channelIds, $orderFilters);
$rows = [];
foreach ($channels as $channel) {
$monitorRow = $this->buildMonitorRow($channel->toArray(), $statsMap[(int)$channel->id] ?? []);
$rows[] = $this->buildPollingRow($monitorRow, $testAmount);
}
$stateWeight = ['ready' => 0, 'degraded' => 1, 'blocked' => 2];
usort($rows, function (array $left, array $right) use ($stateWeight) {
$leftWeight = $stateWeight[$left['route_state'] ?? 'blocked'] ?? 9;
$rightWeight = $stateWeight[$right['route_state'] ?? 'blocked'] ?? 9;
if ($leftWeight === $rightWeight) {
if (($right['route_score'] ?? 0) === ($left['route_score'] ?? 0)) {
return ($left['sort'] ?? 0) <=> ($right['sort'] ?? 0);
}
return ($right['route_score'] ?? 0) <=> ($left['route_score'] ?? 0);
}
return $leftWeight <=> $rightWeight;
});
foreach ($rows as $index => &$row) {
$row['route_rank'] = $index + 1;
}
unset($row);
return $this->success(['list' => $rows, 'summary' => $this->buildPollingSummary($rows)]);
}
public function policyList(Request $request)
{
$merchantId = (int)$request->get('merchant_id', 0);
$merchantAppId = (int)$request->get('merchant_app_id', $request->get('app_id', 0));
$methodCode = trim((string)$request->get('method_code', ''));
$pluginCode = trim((string)$request->get('plugin_code', ''));
$status = $request->get('status', null);
$policies = $this->routePolicyService->list();
$channelMap = [];
foreach ($this->channelRepository->searchList([]) as $channel) {
$channelMap[(int)$channel->id] = $channel->toArray();
}
$filtered = array_values(array_filter($policies, function (array $policy) use ($merchantId, $merchantAppId, $methodCode, $pluginCode, $status) {
if ($merchantId > 0 && (int)($policy['merchant_id'] ?? 0) !== $merchantId) return false;
if ($merchantAppId > 0 && (int)($policy['merchant_app_id'] ?? 0) !== $merchantAppId) return false;
if ($methodCode !== '' && (string)($policy['method_code'] ?? '') !== $methodCode) return false;
if ($pluginCode !== '' && (string)($policy['plugin_code'] ?? '') !== $pluginCode) return false;
if ($status !== null && $status !== '' && (int)($policy['status'] ?? 0) !== (int)$status) return false;
return true;
}));
$list = [];
foreach ($filtered as $policy) {
$items = [];
foreach (($policy['items'] ?? []) as $index => $item) {
$channelId = (int)($item['channel_id'] ?? 0);
$channel = $channelMap[$channelId] ?? [];
$items[] = [
'channel_id' => $channelId,
'role' => trim((string)($item['role'] ?? ($index === 0 ? 'primary' : 'backup'))),
'weight' => max(0, (int)($item['weight'] ?? 100)),
'priority' => max(1, (int)($item['priority'] ?? ($index + 1))),
'chan_code' => (string)($channel['chan_code'] ?? ''),
'chan_name' => (string)($channel['chan_name'] ?? ''),
'channel_status' => isset($channel['status']) ? (int)$channel['status'] : null,
'sort' => (int)($channel['sort'] ?? 0),
'plugin_code' => (string)($channel['plugin_code'] ?? ''),
'method_id' => (int)($channel['method_id'] ?? 0),
'merchant_id' => (int)($channel['merchant_id'] ?? 0),
'merchant_app_id' => (int)($channel['merchant_app_id'] ?? 0),
];
}
usort($items, fn(array $left, array $right) => ($left['priority'] ?? 0) <=> ($right['priority'] ?? 0));
$policy['items'] = $items;
$policy['channel_count'] = count($items);
$list[] = $policy;
}
return $this->success([
'list' => $list,
'summary' => [
'total' => count($list),
'enabled' => count(array_filter($list, fn(array $policy) => (int)($policy['status'] ?? 0) === 1)),
],
]);
}
public function policySave(Request $request)
{
try {
$payload = $this->preparePolicyPayload($request->post(), true);
return $this->success($this->routePolicyService->save($payload), '保存成功');
} catch (\InvalidArgumentException $e) {
return $this->fail($e->getMessage(), 400);
}
}
public function policyPreview(Request $request)
{
try {
$payload = $this->preparePolicyPayload($request->post(), false);
$testAmount = $request->post('test_amount', $request->post('preview_amount', 0));
$amount = ($testAmount === null || $testAmount === '') ? 0 : (float)$testAmount;
$preview = $this->channelRouterService->previewPolicyDraft(
(int)$payload['merchant_id'],
(int)$payload['merchant_app_id'],
(int)$payload['method_id'],
$payload,
$amount
);
return $this->success($preview);
} catch (\Throwable $e) {
return $this->fail($e->getMessage(), 400);
}
}
public function policyDelete(Request $request)
{
$id = trim((string)$request->post('id', ''));
if ($id === '') {
return $this->fail('策略ID不能为空', 400);
}
$ok = $this->routePolicyService->delete($id);
return $ok ? $this->success(null, '删除成功') : $this->fail('策略不存在或已删除', 404);
}
private function preparePolicyPayload(array $data, bool $requirePolicyName = true): array
{
$policyName = trim((string)($data['policy_name'] ?? ''));
$merchantId = (int)($data['merchant_id'] ?? 0);
$merchantAppId = (int)($data['merchant_app_id'] ?? ($data['app_id'] ?? 0));
$methodCode = trim((string)($data['method_code'] ?? ''));
$pluginCode = trim((string)($data['plugin_code'] ?? ''));
$routeMode = trim((string)($data['route_mode'] ?? 'priority'));
$status = (int)($data['status'] ?? 1);
$itemsInput = $data['items'] ?? [];
if ($requirePolicyName && $policyName === '') throw new \InvalidArgumentException('请输入策略名称');
if ($methodCode === '') throw new \InvalidArgumentException('请选择支付方式');
if (!in_array($routeMode, ['priority', 'weight', 'failover'], true)) throw new \InvalidArgumentException('路由模式不合法');
if (!is_array($itemsInput) || $itemsInput === []) throw new \InvalidArgumentException('请至少选择一个通道');
if ($merchantId <= 0 || $merchantAppId <= 0) throw new \InvalidArgumentException('请先选择商户和应用');
$method = $this->methodRepository->findAnyByCode($methodCode);
if (!$method) throw new \InvalidArgumentException('支付方式不存在');
$channelMap = [];
foreach ($this->channelRepository->searchList([]) as $channel) {
$channelMap[(int)$channel->id] = $channel->toArray();
}
$normalizedItems = [];
$usedChannelIds = [];
foreach ($itemsInput as $index => $item) {
$channelId = (int)($item['channel_id'] ?? 0);
if ($channelId <= 0) throw new \InvalidArgumentException('策略项中的通道ID不合法');
if (in_array($channelId, $usedChannelIds, true)) throw new \InvalidArgumentException('策略中存在重复通道,请去重后再提交');
$channel = $channelMap[$channelId] ?? null;
if (!$channel) throw new \InvalidArgumentException('存在未找到的通道,请刷新后重试');
if ($merchantId > 0 && (int)$channel['merchant_id'] !== $merchantId) throw new \InvalidArgumentException('策略中的通道与商户不匹配');
if ($merchantAppId > 0 && (int)$channel['merchant_app_id'] !== $merchantAppId) throw new \InvalidArgumentException('策略中的通道与应用不匹配');
if ((int)$channel['method_id'] !== (int)$method->id) throw new \InvalidArgumentException('策略中的通道与支付方式不匹配');
if ($pluginCode !== '' && (string)$channel['plugin_code'] !== $pluginCode) throw new \InvalidArgumentException('策略中的通道与插件不匹配');
$defaultRole = $routeMode === 'weight' ? 'normal' : ($index === 0 ? 'primary' : 'backup');
$role = trim((string)($item['role'] ?? $defaultRole));
if (!in_array($role, ['primary', 'backup', 'normal'], true)) {
$role = $defaultRole;
}
$normalizedItems[] = [
'channel_id' => $channelId,
'role' => $role,
'weight' => max(0, (int)($item['weight'] ?? 100)),
'priority' => max(1, (int)($item['priority'] ?? ($index + 1))),
];
$usedChannelIds[] = $channelId;
}
usort($normalizedItems, function (array $left, array $right) {
if (($left['priority'] ?? 0) === ($right['priority'] ?? 0)) {
return ($right['weight'] ?? 0) <=> ($left['weight'] ?? 0);
}
return ($left['priority'] ?? 0) <=> ($right['priority'] ?? 0);
});
foreach ($normalizedItems as $index => &$item) {
$item['priority'] = $index + 1;
if ($routeMode === 'weight' && $item['role'] === 'backup') {
$item['role'] = 'normal';
}
}
unset($item);
return [
'id' => trim((string)($data['id'] ?? '')),
'policy_name' => $policyName !== '' ? $policyName : '策略草稿预览',
'merchant_id' => $merchantId,
'merchant_app_id' => $merchantAppId,
'method_code' => $methodCode,
'method_id' => (int)$method->id,
'plugin_code' => $pluginCode,
'route_mode' => $routeMode,
'status' => $status,
'circuit_breaker_threshold' => max(0, min(100, (int)($data['circuit_breaker_threshold'] ?? 50))),
'failover_cooldown' => max(0, (int)($data['failover_cooldown'] ?? 10)),
'remark' => trim((string)($data['remark'] ?? '')),
'items' => $normalizedItems,
];
}
private function resolveChannelFilters(Request $request, bool $withKeywords = false): array
{
$filters = [];
$merchantId = (int)$request->get('merchant_id', 0);
if ($merchantId > 0) $filters['merchant_id'] = $merchantId;
$merchantAppId = (int)$request->get('merchant_app_id', $request->get('app_id', 0));
if ($merchantAppId > 0) $filters['merchant_app_id'] = $merchantAppId;
$methodCode = trim((string)$request->get('method_code', ''));
if ($methodCode !== '') {
$method = $this->methodRepository->findAnyByCode($methodCode);
$filters['method_id'] = $method ? (int)$method->id : -1;
}
$pluginCode = trim((string)$request->get('plugin_code', ''));
if ($pluginCode !== '') $filters['plugin_code'] = $pluginCode;
$status = $request->get('status', null);
if ($status !== null && $status !== '') $filters['status'] = (int)$status;
if ($withKeywords) {
$chanCode = trim((string)$request->get('chan_code', ''));
if ($chanCode !== '') $filters['chan_code'] = $chanCode;
$chanName = trim((string)$request->get('chan_name', ''));
if ($chanName !== '') $filters['chan_name'] = $chanName;
}
return $filters;
}
private function resolveDays(mixed $daysInput): array
{
$days = max(1, min(30, (int)$daysInput));
return [
'days' => $days,
'created_from' => date('Y-m-d 00:00:00', strtotime('-' . ($days - 1) . ' days')),
'created_to' => date('Y-m-d H:i:s'),
];
}
private function buildMonitorRow(array $channel, array $stats): array
{
$totalOrders = (int)($stats['total_orders'] ?? 0);
$successOrders = (int)($stats['success_orders'] ?? 0);
$pendingOrders = (int)($stats['pending_orders'] ?? 0);
$failOrders = (int)($stats['fail_orders'] ?? 0);
$closedOrders = (int)($stats['closed_orders'] ?? 0);
$todayOrders = (int)($stats['today_orders'] ?? 0);
$todaySuccessOrders = (int)($stats['today_success_orders'] ?? 0);
$todaySuccessAmount = round((float)($stats['today_success_amount'] ?? 0), 2);
$successRate = $totalOrders > 0 ? round($successOrders / $totalOrders * 100, 2) : 0;
$dailyLimit = isset($channel['daily_limit']) ? (float)$channel['daily_limit'] : 0;
$dailyCnt = isset($channel['daily_cnt']) ? (int)$channel['daily_cnt'] : 0;
$todayLimitUsageRate = $dailyLimit > 0 ? round(min(100, ($todaySuccessAmount / $dailyLimit) * 100), 2) : null;
$healthScore = 0;
$healthLevel = 'disabled';
$status = (int)($channel['status'] ?? 0);
if ($status === 1) {
if ($totalOrders === 0) {
$healthScore = 60;
$healthLevel = 'idle';
} else {
$healthScore = 90;
if ($successRate < 95) $healthScore -= 10;
if ($successRate < 80) $healthScore -= 15;
if ($successRate < 60) $healthScore -= 20;
if ($failOrders > 0) $healthScore -= min(15, $failOrders * 3);
if ($pendingOrders > max(3, (int)floor($successOrders / 2))) $healthScore -= 10;
if ($todayLimitUsageRate !== null && $todayLimitUsageRate >= 90) $healthScore -= 20;
elseif ($todayLimitUsageRate !== null && $todayLimitUsageRate >= 75) $healthScore -= 10;
$healthScore = max(0, min(100, $healthScore));
if ($healthScore >= 80) $healthLevel = 'healthy';
elseif ($healthScore >= 60) $healthLevel = 'warning';
else $healthLevel = 'danger';
}
}
return [
'id' => (int)($channel['id'] ?? 0),
'merchant_id' => (int)($channel['merchant_id'] ?? 0),
'merchant_app_id' => (int)($channel['merchant_app_id'] ?? 0),
'chan_code' => (string)($channel['chan_code'] ?? ''),
'chan_name' => (string)($channel['chan_name'] ?? ''),
'plugin_code' => (string)($channel['plugin_code'] ?? ''),
'method_id' => (int)($channel['method_id'] ?? 0),
'status' => $status,
'sort' => (int)($channel['sort'] ?? 0),
'daily_limit' => $dailyLimit > 0 ? round($dailyLimit, 2) : 0,
'daily_cnt' => $dailyCnt > 0 ? $dailyCnt : 0,
'min_amount' => $channel['min_amount'] === null ? null : round((float)$channel['min_amount'], 2),
'max_amount' => $channel['max_amount'] === null ? null : round((float)$channel['max_amount'], 2),
'total_orders' => $totalOrders,
'success_orders' => $successOrders,
'pending_orders' => $pendingOrders,
'fail_orders' => $failOrders,
'closed_orders' => $closedOrders,
'today_orders' => $todayOrders,
'today_success_orders' => $todaySuccessOrders,
'total_amount' => round((float)($stats['total_amount'] ?? 0), 2),
'success_amount' => round((float)($stats['success_amount'] ?? 0), 2),
'today_amount' => round((float)($stats['today_amount'] ?? 0), 2),
'today_success_amount' => $todaySuccessAmount,
'last_order_at' => $stats['last_order_at'] ?? null,
'last_success_at' => $stats['last_success_at'] ?? null,
'success_rate' => $successRate,
'today_limit_usage_rate' => $todayLimitUsageRate,
'health_score' => $healthScore,
'health_level' => $healthLevel,
];
}
private function buildMonitorSummary(array $rows): array
{
$summary = [
'total_channels' => count($rows),
'enabled_channels' => 0,
'healthy_channels' => 0,
'warning_channels' => 0,
'danger_channels' => 0,
'total_orders' => 0,
'success_rate' => 0,
'today_success_amount' => 0,
];
$successOrders = 0;
foreach ($rows as $row) {
if ((int)($row['status'] ?? 0) === 1) $summary['enabled_channels']++;
$level = $row['health_level'] ?? '';
if ($level === 'healthy') $summary['healthy_channels']++;
elseif ($level === 'warning') $summary['warning_channels']++;
elseif ($level === 'danger') $summary['danger_channels']++;
$summary['total_orders'] += (int)($row['total_orders'] ?? 0);
$summary['today_success_amount'] = round($summary['today_success_amount'] + (float)($row['today_success_amount'] ?? 0), 2);
$successOrders += (int)($row['success_orders'] ?? 0);
}
if ($summary['total_orders'] > 0) {
$summary['success_rate'] = round($successOrders / $summary['total_orders'] * 100, 2);
}
return $summary;
}
private function buildPollingRow(array $monitorRow, ?float $testAmount): array
{
$reasons = [];
$status = (int)($monitorRow['status'] ?? 0);
$dailyLimit = (float)($monitorRow['daily_limit'] ?? 0);
$dailyCnt = (int)($monitorRow['daily_cnt'] ?? 0);
$todaySuccessAmount = (float)($monitorRow['today_success_amount'] ?? 0);
$todayOrders = (int)($monitorRow['today_orders'] ?? 0);
$minAmount = $monitorRow['min_amount'];
$maxAmount = $monitorRow['max_amount'];
$remainingDailyLimit = $dailyLimit > 0 ? round($dailyLimit - $todaySuccessAmount, 2) : null;
$remainingDailyCount = $dailyCnt > 0 ? $dailyCnt - $todayOrders : null;
$routeState = 'ready';
if ($status !== 1) { $routeState = 'blocked'; $reasons[] = '通道已禁用'; }
if ($testAmount !== null) {
if ($minAmount !== null && $testAmount < (float)$minAmount) { $routeState = 'blocked'; $reasons[] = '低于最小支付金额'; }
if ($maxAmount !== null && (float)$maxAmount > 0 && $testAmount > (float)$maxAmount) { $routeState = 'blocked'; $reasons[] = '超过最大支付金额'; }
}
if ($remainingDailyLimit !== null && $remainingDailyLimit <= 0) { $routeState = 'blocked'; $reasons[] = '单日限额已用尽'; }
if ($remainingDailyCount !== null && $remainingDailyCount <= 0) { $routeState = 'blocked'; $reasons[] = '单日笔数已用尽'; }
if ($routeState !== 'blocked') {
if (($monitorRow['health_level'] ?? '') === 'warning' || ($monitorRow['health_level'] ?? '') === 'danger') { $routeState = 'degraded'; $reasons[] = '监控健康度偏低'; }
if ((int)($monitorRow['total_orders'] ?? 0) === 0) { $routeState = 'degraded'; $reasons[] = '暂无订单样本,建议灰度'; }
if ((float)($monitorRow['success_rate'] ?? 0) < 80 && (int)($monitorRow['total_orders'] ?? 0) > 0) { $routeState = 'degraded'; $reasons[] = '成功率偏低'; }
if ((int)($monitorRow['pending_orders'] ?? 0) > max(3, (int)($monitorRow['success_orders'] ?? 0))) { $routeState = 'degraded'; $reasons[] = '待支付订单偏多'; }
}
$priorityBonus = max(0, 20 - min(20, (int)($monitorRow['sort'] ?? 0) * 2));
$sampleBonus = (int)($monitorRow['total_orders'] ?? 0) > 0 ? min(10, (int)floor(((float)($monitorRow['success_rate'] ?? 0)) / 10)) : 5;
$routeScore = round(max(0, min(100, ((float)($monitorRow['health_score'] ?? 0) * 0.7) + $priorityBonus + $sampleBonus)), 2);
if ($routeState === 'degraded') $routeScore = max(0, round($routeScore - 15, 2));
if ($routeState === 'blocked') $routeScore = 0;
return array_merge($monitorRow, [
'route_state' => $routeState,
'route_rank' => 0,
'route_score' => $routeScore,
'remaining_daily_limit' => $remainingDailyLimit === null ? null : round(max(0, $remainingDailyLimit), 2),
'remaining_daily_count' => $remainingDailyCount === null ? null : max(0, $remainingDailyCount),
'reasons' => array_values(array_unique($reasons)),
]);
}
private function buildPollingSummary(array $rows): array
{
$summary = [
'total_channels' => count($rows),
'ready_channels' => 0,
'degraded_channels' => 0,
'blocked_channels' => 0,
'recommended_channel' => null,
'fallback_chain' => [],
];
foreach ($rows as $row) {
$state = $row['route_state'] ?? 'blocked';
if ($state === 'ready') $summary['ready_channels']++;
elseif ($state === 'degraded') $summary['degraded_channels']++;
else $summary['blocked_channels']++;
}
foreach ($rows as $row) {
if ($summary['recommended_channel'] === null && ($row['route_state'] ?? '') !== 'blocked') {
$summary['recommended_channel'] = $row;
continue;
}
if (($row['route_state'] ?? '') !== 'blocked' && count($summary['fallback_chain']) < 5) {
$summary['fallback_chain'][] = sprintf('%s%s', (string)($row['chan_name'] ?? ''), (string)($row['chan_code'] ?? ''));
}
}
if ($summary['recommended_channel'] !== null) {
$recommendedId = (int)($summary['recommended_channel']['id'] ?? 0);
if ($recommendedId > 0) {
$summary['fallback_chain'] = [];
foreach ($rows as $row) {
if ((int)($row['id'] ?? 0) === $recommendedId || ($row['route_state'] ?? '') === 'blocked') continue;
$summary['fallback_chain'][] = sprintf('%s%s', (string)($row['chan_name'] ?? ''), (string)($row['chan_code'] ?? ''));
if (count($summary['fallback_chain']) >= 5) break;
}
}
}
return $summary;
}
}

View File

@@ -1,522 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\repositories\PaymentMethodRepository;
use support\Db;
use support\Request;
class FinanceController extends BaseController
{
public function __construct(
protected PaymentMethodRepository $methodRepository,
) {
}
public function reconciliation(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildFilters($request);
$baseQuery = $this->buildOrderQuery($filters);
$summaryRow = (clone $baseQuery)
->selectRaw(
'COUNT(*) AS total_orders,
SUM(CASE WHEN o.status = 1 THEN 1 ELSE 0 END) AS success_orders,
SUM(CASE WHEN o.status = 0 THEN 1 ELSE 0 END) AS pending_orders,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS notify_pending_orders,
COALESCE(SUM(o.amount), 0) AS total_amount,
COALESCE(SUM(o.fee), 0) AS total_fee,
COALESCE(SUM(o.real_amount - o.fee), 0) AS total_net_amount'
)
->first();
$paginator = (clone $baseQuery)
->selectRaw(
"o.*, m.merchant_no, m.merchant_name, ma.app_id AS merchant_app_code, ma.app_name, pm.method_code, pm.method_name,
pc.chan_code, pc.chan_name,
COALESCE(o.real_amount - o.fee, 0) AS net_amount,
JSON_UNQUOTE(JSON_EXTRACT(o.extra, '$.routing.policy.policy_name')) AS route_policy_name"
)
->orderByDesc('o.id')
->paginate($pageSize, ['*'], 'page', $page);
$items = [];
foreach ($paginator->items() as $row) {
$item = (array)$row;
$item['reconcile_status'] = $this->reconcileStatus((int)($item['status'] ?? 0), (int)($item['notify_stat'] ?? 0));
$item['reconcile_status_text'] = $this->reconcileStatusText($item['reconcile_status']);
$items[] = $item;
}
return $this->success([
'summary' => [
'total_orders' => (int)($summaryRow->total_orders ?? 0),
'success_orders' => (int)($summaryRow->success_orders ?? 0),
'pending_orders' => (int)($summaryRow->pending_orders ?? 0),
'notify_pending_orders' => (int)($summaryRow->notify_pending_orders ?? 0),
'total_amount' => (string)($summaryRow->total_amount ?? '0.00'),
'total_fee' => (string)($summaryRow->total_fee ?? '0.00'),
'total_net_amount' => (string)($summaryRow->total_net_amount ?? '0.00'),
],
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function settlement(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildFilters($request);
$baseQuery = $this->buildOrderQuery($filters)->where('o.status', 1);
$summaryRow = (clone $baseQuery)
->selectRaw(
'COUNT(DISTINCT o.merchant_id) AS merchant_count,
COUNT(DISTINCT o.merchant_app_id) AS app_count,
COUNT(*) AS success_orders,
COALESCE(SUM(o.real_amount), 0) AS gross_amount,
COALESCE(SUM(o.fee), 0) AS fee_amount,
COALESCE(SUM(o.real_amount - o.fee), 0) AS net_amount,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS notify_pending_orders,
COALESCE(SUM(CASE WHEN o.notify_stat = 0 THEN o.real_amount - o.fee ELSE 0 END), 0) AS notify_pending_amount'
)
->first();
$paginator = (clone $baseQuery)
->selectRaw(
'o.merchant_id, o.merchant_app_id,
m.merchant_no, m.merchant_name, ma.app_id AS merchant_app_code, ma.app_name,
COUNT(*) AS success_orders,
COUNT(DISTINCT o.channel_id) AS channel_count,
COUNT(DISTINCT o.method_id) AS method_count,
COALESCE(SUM(o.real_amount), 0) AS gross_amount,
COALESCE(SUM(o.fee), 0) AS fee_amount,
COALESCE(SUM(o.real_amount - o.fee), 0) AS net_amount,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS notify_pending_orders,
COALESCE(SUM(CASE WHEN o.notify_stat = 0 THEN o.real_amount - o.fee ELSE 0 END), 0) AS notify_pending_amount,
MAX(o.pay_at) AS last_pay_at'
)
->groupBy('o.merchant_id', 'o.merchant_app_id', 'm.merchant_no', 'm.merchant_name', 'ma.app_id', 'ma.app_name')
->orderByRaw('SUM(o.real_amount - o.fee) DESC')
->paginate($pageSize, ['*'], 'page', $page);
return $this->success([
'summary' => [
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'app_count' => (int)($summaryRow->app_count ?? 0),
'success_orders' => (int)($summaryRow->success_orders ?? 0),
'gross_amount' => (string)($summaryRow->gross_amount ?? '0.00'),
'fee_amount' => (string)($summaryRow->fee_amount ?? '0.00'),
'net_amount' => (string)($summaryRow->net_amount ?? '0.00'),
'notify_pending_orders' => (int)($summaryRow->notify_pending_orders ?? 0),
'notify_pending_amount' => (string)($summaryRow->notify_pending_amount ?? '0.00'),
],
'list' => array_map(fn ($row) => (array)$row, $paginator->items()),
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function fee(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildFilters($request);
$baseQuery = $this->buildOrderQuery($filters);
if (($filters['status'] ?? '') === '') {
$baseQuery->where('o.status', 1);
}
$summaryRow = (clone $baseQuery)
->selectRaw(
'COUNT(DISTINCT o.merchant_id) AS merchant_count,
COUNT(DISTINCT o.channel_id) AS channel_count,
COUNT(DISTINCT o.method_id) AS method_count,
COUNT(*) AS order_count,
COALESCE(SUM(o.real_amount), 0) AS total_amount,
COALESCE(SUM(o.fee), 0) AS total_fee'
)
->first();
$paginator = (clone $baseQuery)
->selectRaw(
'o.merchant_id, o.channel_id, o.method_id,
m.merchant_no, m.merchant_name,
pm.method_code, pm.method_name,
pc.chan_code, pc.chan_name,
COUNT(*) AS order_count,
SUM(CASE WHEN o.status = 1 THEN 1 ELSE 0 END) AS success_orders,
COALESCE(SUM(o.real_amount), 0) AS total_amount,
COALESCE(SUM(o.fee), 0) AS total_fee,
COALESCE(AVG(CASE WHEN o.real_amount > 0 THEN o.fee / o.real_amount ELSE NULL END), 0) AS avg_fee_rate,
MAX(o.created_at) AS last_order_at'
)
->groupBy('o.merchant_id', 'o.channel_id', 'o.method_id', 'm.merchant_no', 'm.merchant_name', 'pm.method_code', 'pm.method_name', 'pc.chan_code', 'pc.chan_name')
->orderByRaw('SUM(o.fee) DESC')
->paginate($pageSize, ['*'], 'page', $page);
$items = [];
foreach ($paginator->items() as $row) {
$item = (array)$row;
$item['avg_fee_rate_percent'] = round(((float)($item['avg_fee_rate'] ?? 0)) * 100, 4);
$items[] = $item;
}
return $this->success([
'summary' => [
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'channel_count' => (int)($summaryRow->channel_count ?? 0),
'method_count' => (int)($summaryRow->method_count ?? 0),
'order_count' => (int)($summaryRow->order_count ?? 0),
'total_amount' => (string)($summaryRow->total_amount ?? '0.00'),
'total_fee' => (string)($summaryRow->total_fee ?? '0.00'),
],
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function settlementRecord(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildFilters($request);
$baseQuery = $this->buildOrderQuery($filters)->where('o.status', 1);
$summaryRow = (clone $baseQuery)
->selectRaw(
"COUNT(DISTINCT CONCAT(o.merchant_app_id, '#', DATE(COALESCE(o.pay_at, o.created_at)))) AS record_count,
COUNT(DISTINCT o.merchant_id) AS merchant_count,
COUNT(DISTINCT o.merchant_app_id) AS app_count,
COUNT(*) AS success_orders,
COALESCE(SUM(o.real_amount), 0) AS gross_amount,
COALESCE(SUM(o.fee), 0) AS fee_amount,
COALESCE(SUM(o.real_amount - o.fee), 0) AS net_amount,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS notify_pending_orders"
)
->first();
$paginator = (clone $baseQuery)
->selectRaw(
"DATE(COALESCE(o.pay_at, o.created_at)) AS settlement_date,
o.merchant_id, o.merchant_app_id,
m.merchant_no, m.merchant_name, ma.app_id AS merchant_app_code, ma.app_name,
COUNT(*) AS success_orders,
COALESCE(SUM(o.real_amount), 0) AS gross_amount,
COALESCE(SUM(o.fee), 0) AS fee_amount,
COALESCE(SUM(o.real_amount - o.fee), 0) AS net_amount,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS notify_pending_orders,
MAX(o.pay_at) AS last_pay_at"
)
->groupByRaw("DATE(COALESCE(o.pay_at, o.created_at)), o.merchant_id, o.merchant_app_id, m.merchant_no, m.merchant_name, ma.app_id, ma.app_name")
->orderByDesc('settlement_date')
->orderByRaw('SUM(o.real_amount - o.fee) DESC')
->paginate($pageSize, ['*'], 'page', $page);
$items = [];
foreach ($paginator->items() as $row) {
$item = (array)$row;
$item['settlement_status'] = (int)($item['notify_pending_orders'] ?? 0) > 0 ? 'pending' : 'ready';
$item['settlement_status_text'] = $item['settlement_status'] === 'ready' ? 'ready' : 'pending_notify';
$items[] = $item;
}
return $this->success([
'summary' => [
'record_count' => (int)($summaryRow->record_count ?? 0),
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'app_count' => (int)($summaryRow->app_count ?? 0),
'success_orders' => (int)($summaryRow->success_orders ?? 0),
'gross_amount' => (string)($summaryRow->gross_amount ?? '0.00'),
'fee_amount' => (string)($summaryRow->fee_amount ?? '0.00'),
'net_amount' => (string)($summaryRow->net_amount ?? '0.00'),
'notify_pending_orders' => (int)($summaryRow->notify_pending_orders ?? 0),
],
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function batchSettlement(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildFilters($request);
$baseQuery = $this->buildOrderQuery($filters)->where('o.status', 1);
$summaryRow = (clone $baseQuery)
->selectRaw(
"COUNT(DISTINCT o.merchant_id) AS merchant_count,
COUNT(DISTINCT o.merchant_app_id) AS app_count,
COUNT(*) AS success_orders,
COUNT(DISTINCT CONCAT(o.merchant_app_id, '#', DATE(COALESCE(o.pay_at, o.created_at)))) AS batch_days,
COALESCE(SUM(CASE WHEN o.notify_stat = 1 THEN o.real_amount - o.fee ELSE 0 END), 0) AS ready_amount,
COALESCE(SUM(CASE WHEN o.notify_stat = 0 THEN o.real_amount - o.fee ELSE 0 END), 0) AS pending_amount"
)
->first();
$paginator = (clone $baseQuery)
->selectRaw(
"o.merchant_id, o.merchant_app_id,
m.merchant_no, m.merchant_name, ma.app_id AS merchant_app_code, ma.app_name,
COUNT(*) AS success_orders,
COUNT(DISTINCT DATE(COALESCE(o.pay_at, o.created_at))) AS batch_days,
COALESCE(SUM(CASE WHEN o.notify_stat = 1 THEN o.real_amount - o.fee ELSE 0 END), 0) AS ready_amount,
COALESCE(SUM(CASE WHEN o.notify_stat = 0 THEN o.real_amount - o.fee ELSE 0 END), 0) AS pending_amount,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS pending_notify_orders,
MAX(o.pay_at) AS last_pay_at"
)
->groupBy('o.merchant_id', 'o.merchant_app_id', 'm.merchant_no', 'm.merchant_name', 'ma.app_id', 'ma.app_name')
->orderByRaw('SUM(CASE WHEN o.notify_stat = 1 THEN o.real_amount - o.fee ELSE 0 END) DESC')
->paginate($pageSize, ['*'], 'page', $page);
$items = [];
foreach ($paginator->items() as $row) {
$item = (array)$row;
$item['batch_status'] = (float)($item['pending_amount'] ?? 0) > 0 ? 'pending' : 'ready';
$item['batch_status_text'] = $item['batch_status'] === 'ready' ? 'ready_to_batch' : 'pending_notify';
$items[] = $item;
}
return $this->success([
'summary' => [
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'app_count' => (int)($summaryRow->app_count ?? 0),
'success_orders' => (int)($summaryRow->success_orders ?? 0),
'batch_days' => (int)($summaryRow->batch_days ?? 0),
'ready_amount' => (string)($summaryRow->ready_amount ?? '0.00'),
'pending_amount' => (string)($summaryRow->pending_amount ?? '0.00'),
],
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function split(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildFilters($request);
$baseQuery = $this->buildOrderQuery($filters)->where('o.status', 1);
$summaryRow = (clone $baseQuery)
->selectRaw(
'COUNT(DISTINCT o.channel_id) AS channel_count,
COUNT(DISTINCT o.merchant_id) AS merchant_count,
COUNT(*) AS order_count,
COALESCE(SUM(o.real_amount), 0) AS gross_amount,
COALESCE(SUM(o.real_amount - o.fee), 0) AS net_amount,
COALESCE(SUM((o.real_amount - o.fee) * COALESCE(pc.split_ratio, 100) / 100), 0) AS merchant_share_amount,
COALESCE(SUM((o.real_amount - o.fee) * (100 - COALESCE(pc.split_ratio, 100)) / 100), 0) AS platform_share_amount,
COALESCE(SUM(o.real_amount * COALESCE(pc.chan_cost, 0) / 100), 0) AS channel_cost_amount'
)
->first();
$paginator = (clone $baseQuery)
->selectRaw(
'o.merchant_id, o.channel_id, o.method_id,
m.merchant_no, m.merchant_name,
pm.method_code, pm.method_name,
pc.chan_code, pc.chan_name,
COALESCE(pc.split_ratio, 100) AS split_ratio,
COALESCE(pc.chan_cost, 0) AS chan_cost,
COUNT(*) AS order_count,
COALESCE(SUM(o.real_amount), 0) AS gross_amount,
COALESCE(SUM(o.fee), 0) AS fee_amount,
COALESCE(SUM(o.real_amount - o.fee), 0) AS net_amount,
COALESCE(SUM((o.real_amount - o.fee) * COALESCE(pc.split_ratio, 100) / 100), 0) AS merchant_share_amount,
COALESCE(SUM((o.real_amount - o.fee) * (100 - COALESCE(pc.split_ratio, 100)) / 100), 0) AS platform_share_amount,
COALESCE(SUM(o.real_amount * COALESCE(pc.chan_cost, 0) / 100), 0) AS channel_cost_amount,
MAX(o.pay_at) AS last_pay_at'
)
->groupBy('o.merchant_id', 'o.channel_id', 'o.method_id', 'm.merchant_no', 'm.merchant_name', 'pm.method_code', 'pm.method_name', 'pc.chan_code', 'pc.chan_name', 'pc.split_ratio', 'pc.chan_cost')
->orderByRaw('SUM((o.real_amount - o.fee) * COALESCE(pc.split_ratio, 100) / 100) DESC')
->paginate($pageSize, ['*'], 'page', $page);
return $this->success([
'summary' => [
'channel_count' => (int)($summaryRow->channel_count ?? 0),
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'order_count' => (int)($summaryRow->order_count ?? 0),
'gross_amount' => (string)($summaryRow->gross_amount ?? '0.00'),
'net_amount' => (string)($summaryRow->net_amount ?? '0.00'),
'merchant_share_amount' => (string)($summaryRow->merchant_share_amount ?? '0.00'),
'platform_share_amount' => (string)($summaryRow->platform_share_amount ?? '0.00'),
'channel_cost_amount' => (string)($summaryRow->channel_cost_amount ?? '0.00'),
],
'list' => array_map(fn ($row) => (array)$row, $paginator->items()),
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function invoice(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildFilters($request);
$baseQuery = $this->buildOrderQuery($filters)->where('o.status', 1);
$summaryRow = (clone $baseQuery)
->selectRaw(
'COUNT(DISTINCT o.merchant_id) AS merchant_count,
COUNT(DISTINCT o.merchant_app_id) AS app_count,
COUNT(*) AS success_orders,
COALESCE(SUM(CASE WHEN o.notify_stat = 1 THEN o.real_amount - o.fee ELSE 0 END), 0) AS invoiceable_amount,
COALESCE(SUM(CASE WHEN o.notify_stat = 0 THEN o.real_amount - o.fee ELSE 0 END), 0) AS pending_invoice_amount,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS pending_notify_orders'
)
->first();
$paginator = (clone $baseQuery)
->selectRaw(
'o.merchant_id, o.merchant_app_id,
m.merchant_no, m.merchant_name, ma.app_id AS merchant_app_code, ma.app_name,
COUNT(*) AS success_orders,
COALESCE(SUM(o.real_amount - o.fee), 0) AS net_amount,
COALESCE(SUM(CASE WHEN o.notify_stat = 1 THEN o.real_amount - o.fee ELSE 0 END), 0) AS invoiceable_amount,
COALESCE(SUM(CASE WHEN o.notify_stat = 0 THEN o.real_amount - o.fee ELSE 0 END), 0) AS pending_invoice_amount,
SUM(CASE WHEN o.notify_stat = 0 THEN 1 ELSE 0 END) AS pending_notify_orders,
MAX(o.pay_at) AS last_pay_at'
)
->groupBy('o.merchant_id', 'o.merchant_app_id', 'm.merchant_no', 'm.merchant_name', 'ma.app_id', 'ma.app_name')
->orderByRaw('SUM(CASE WHEN o.notify_stat = 1 THEN o.real_amount - o.fee ELSE 0 END) DESC')
->paginate($pageSize, ['*'], 'page', $page);
$items = [];
foreach ($paginator->items() as $row) {
$item = (array)$row;
$item['invoice_status'] = (float)($item['pending_invoice_amount'] ?? 0) > 0 ? 'pending' : 'ready';
$item['invoice_status_text'] = $item['invoice_status'] === 'ready' ? 'ready' : 'pending_review';
$items[] = $item;
}
return $this->success([
'summary' => [
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'app_count' => (int)($summaryRow->app_count ?? 0),
'success_orders' => (int)($summaryRow->success_orders ?? 0),
'invoiceable_amount' => (string)($summaryRow->invoiceable_amount ?? '0.00'),
'pending_invoice_amount' => (string)($summaryRow->pending_invoice_amount ?? '0.00'),
'pending_notify_orders' => (int)($summaryRow->pending_notify_orders ?? 0),
],
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
private function buildFilters(Request $request): array
{
$methodCode = trim((string)$request->get('method_code', ''));
$methodId = 0;
if ($methodCode !== '') {
$method = $this->methodRepository->findAnyByCode($methodCode);
$methodId = $method ? (int)$method->id : 0;
}
return [
'merchant_id' => (int)$request->get('merchant_id', 0),
'merchant_app_id' => (int)$request->get('merchant_app_id', 0),
'method_id' => $methodId,
'channel_id' => (int)$request->get('channel_id', 0),
'status' => (string)$request->get('status', ''),
'notify_stat' => (string)$request->get('notify_stat', ''),
'order_id' => trim((string)$request->get('order_id', '')),
'mch_order_no' => trim((string)$request->get('mch_order_no', '')),
'created_from' => trim((string)$request->get('created_from', '')),
'created_to' => trim((string)$request->get('created_to', '')),
];
}
private function buildOrderQuery(array $filters)
{
$query = Db::table('ma_pay_order as o')
->leftJoin('ma_merchant as m', 'm.id', '=', 'o.merchant_id')
->leftJoin('ma_merchant_app as ma', 'ma.id', '=', 'o.merchant_app_id')
->leftJoin('ma_pay_method as pm', 'pm.id', '=', 'o.method_id')
->leftJoin('ma_pay_channel as pc', 'pc.id', '=', 'o.channel_id');
if (!empty($filters['merchant_id'])) {
$query->where('o.merchant_id', (int)$filters['merchant_id']);
}
if (!empty($filters['merchant_app_id'])) {
$query->where('o.merchant_app_id', (int)$filters['merchant_app_id']);
}
if (!empty($filters['method_id'])) {
$query->where('o.method_id', (int)$filters['method_id']);
}
if (!empty($filters['channel_id'])) {
$query->where('o.channel_id', (int)$filters['channel_id']);
}
if (($filters['status'] ?? '') !== '') {
$query->where('o.status', (int)$filters['status']);
}
if (($filters['notify_stat'] ?? '') !== '') {
$query->where('o.notify_stat', (int)$filters['notify_stat']);
}
if (!empty($filters['order_id'])) {
$query->where('o.order_id', 'like', '%' . $filters['order_id'] . '%');
}
if (!empty($filters['mch_order_no'])) {
$query->where('o.mch_order_no', 'like', '%' . $filters['mch_order_no'] . '%');
}
if (!empty($filters['created_from'])) {
$query->where('o.created_at', '>=', $filters['created_from']);
}
if (!empty($filters['created_to'])) {
$query->where('o.created_at', '<=', $filters['created_to']);
}
return $query;
}
private function reconcileStatus(int $status, int $notifyStat): string
{
if ($status === 1 && $notifyStat === 1) {
return 'matched';
}
if ($status === 1 && $notifyStat === 0) {
return 'notify_pending';
}
if ($status === 0) {
return 'pending';
}
if ($status === 2) {
return 'failed';
}
if ($status === 3) {
return 'closed';
}
return 'unknown';
}
private function reconcileStatusText(string $status): string
{
return match ($status) {
'matched' => 'matched',
'notify_pending' => 'notify_pending',
'pending' => 'pending',
'failed' => 'failed',
'closed' => 'closed',
default => 'unknown',
};
}
}

View File

@@ -1,25 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\services\MenuService;
use support\Request;
/**
* 菜单控制器
*/
class MenuController extends BaseController
{
public function __construct(
protected MenuService $menuService
) {
}
public function getRouters()
{
$routers = $this->menuService->getRouters();
return $this->success($routers);
}
}

View File

@@ -1,303 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\repositories\MerchantAppRepository;
use app\repositories\MerchantRepository;
use app\services\SystemConfigService;
use support\Request;
class MerchantAppController extends BaseController
{
public function __construct(
protected MerchantAppRepository $merchantAppRepository,
protected MerchantRepository $merchantRepository,
protected SystemConfigService $systemConfigService,
) {
}
public function list(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = [
'merchant_id' => (int)$request->get('merchant_id', 0),
'status' => $request->get('status', ''),
'app_id' => trim((string)$request->get('app_id', '')),
'app_name' => trim((string)$request->get('app_name', '')),
'api_type' => trim((string)$request->get('api_type', '')),
];
$paginator = $this->merchantAppRepository->searchPaginate($filters, $page, $pageSize);
$packageMap = $this->buildPackageMap();
$items = [];
foreach ($paginator->items() as $row) {
$item = method_exists($row, 'toArray') ? $row->toArray() : (array)$row;
$packageCode = trim((string)($item['package_code'] ?? ''));
$item['package_code'] = $packageCode;
$item['package_name'] = $packageCode !== '' ? ($packageMap[$packageCode] ?? $packageCode) : '';
$items[] = $item;
}
return $this->success([
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function detail(Request $request)
{
$id = (int)$request->get('id', 0);
if ($id <= 0) {
return $this->fail('app id is required', 400);
}
$row = $this->merchantAppRepository->find($id);
if (!$row) {
return $this->fail('app not found', 404);
}
return $this->success(method_exists($row, 'toArray') ? $row->toArray() : (array)$row);
}
public function configDetail(Request $request)
{
$id = (int)$request->get('id', 0);
if ($id <= 0) {
return $this->fail('app id is required', 400);
}
$app = $this->merchantAppRepository->find($id);
if (!$app) {
return $this->fail('app not found', 404);
}
$appRow = method_exists($app, 'toArray') ? $app->toArray() : (array)$app;
$config = $this->buildAppConfig($appRow);
return $this->success([
'app' => $app,
'config' => $config,
]);
}
public function save(Request $request)
{
$data = $request->post();
$id = (int)($data['id'] ?? 0);
$merchantId = (int)($data['merchant_id'] ?? 0);
$apiType = trim((string)($data['api_type'] ?? 'epay'));
$appId = trim((string)($data['app_id'] ?? ''));
$appName = trim((string)($data['app_name'] ?? ''));
$status = (int)($data['status'] ?? 1);
if ($merchantId <= 0 || $appId === '' || $appName === '') {
return $this->fail('merchant_id, app_id and app_name are required', 400);
}
$merchant = $this->merchantRepository->find($merchantId);
if (!$merchant) {
return $this->fail('merchant not found', 404);
}
if (!in_array($apiType, ['openapi', 'epay', 'custom', 'default'], true)) {
return $this->fail('invalid api_type', 400);
}
if ($id > 0) {
$row = $this->merchantAppRepository->find($id);
if (!$row) {
return $this->fail('app not found', 404);
}
if ($row->app_id !== $appId) {
$exists = $this->merchantAppRepository->findAnyByAppId($appId);
if ($exists) {
return $this->fail('app_id already exists', 400);
}
}
$update = [
'mer_id' => $merchantId,
'api_type' => $apiType,
'app_code' => $appId,
'app_name' => $appName,
'status' => $status,
'updated_at' => date('Y-m-d H:i:s'),
];
if (!empty($data['app_secret'])) {
$update['app_secret'] = (string)$data['app_secret'];
}
$this->merchantAppRepository->updateById($id, $update);
} else {
$exists = $this->merchantAppRepository->findAnyByAppId($appId);
if ($exists) {
return $this->fail('app_id already exists', 400);
}
$secret = !empty($data['app_secret']) ? (string)$data['app_secret'] : $this->generateSecret();
$this->merchantAppRepository->create([
'mer_id' => $merchantId,
'api_type' => $apiType,
'app_code' => $appId,
'app_secret' => $secret,
'app_name' => $appName,
'status' => $status,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
return $this->success(null, 'saved');
}
public function resetSecret(Request $request)
{
$id = (int)$request->post('id', 0);
if ($id <= 0) {
return $this->fail('app id is required', 400);
}
$row = $this->merchantAppRepository->find($id);
if (!$row) {
return $this->fail('app not found', 404);
}
$secret = $this->generateSecret();
$this->merchantAppRepository->updateById($id, ['app_secret' => $secret]);
return $this->success(['app_secret' => $secret], 'reset success');
}
public function toggle(Request $request)
{
$id = (int)$request->post('id', 0);
$status = $request->post('status', null);
if ($id <= 0 || $status === null) {
return $this->fail('invalid params', 400);
}
$ok = $this->merchantAppRepository->updateById($id, ['status' => (int)$status]);
return $ok ? $this->success(null, 'updated') : $this->fail('update failed', 500);
}
public function configSave(Request $request)
{
$id = (int)$request->post('id', 0);
if ($id <= 0) {
return $this->fail('app id is required', 400);
}
$app = $this->merchantAppRepository->find($id);
if (!$app) {
return $this->fail('app not found', 404);
}
$signType = trim((string)$request->post('sign_type', 'md5'));
$callbackMode = trim((string)$request->post('callback_mode', 'server'));
if (!in_array($signType, ['md5', 'sha256', 'hmac-sha256'], true)) {
return $this->fail('invalid sign_type', 400);
}
if (!in_array($callbackMode, ['server', 'server+page', 'manual'], true)) {
return $this->fail('invalid callback_mode', 400);
}
$config = [
'package_code' => trim((string)$request->post('package_code', '')),
'notify_url' => trim((string)$request->post('notify_url', '')),
'return_url' => trim((string)$request->post('return_url', '')),
'callback_mode' => $callbackMode,
'sign_type' => $signType,
'order_expire_minutes' => max(0, (int)$request->post('order_expire_minutes', 30)),
'callback_retry_limit' => max(0, (int)$request->post('callback_retry_limit', 6)),
'ip_whitelist' => trim((string)$request->post('ip_whitelist', '')),
'amount_min' => max(0, (float)$request->post('amount_min', 0)),
'amount_max' => max(0, (float)$request->post('amount_max', 0)),
'daily_limit' => max(0, (float)$request->post('daily_limit', 0)),
'notify_enabled' => (int)$request->post('notify_enabled', 1) === 1 ? 1 : 0,
'remark' => trim((string)$request->post('remark', '')),
'updated_at' => date('Y-m-d H:i:s'),
];
if ($config['package_code'] !== '') {
$packageExists = false;
foreach ($this->getConfigEntries('merchant_packages') as $package) {
if (($package['package_code'] ?? '') === $config['package_code']) {
$packageExists = true;
break;
}
}
if (!$packageExists) {
return $this->fail('package_code not found', 400);
}
}
$updateData = $config;
$updateData['updated_at'] = date('Y-m-d H:i:s');
$this->merchantAppRepository->updateById($id, $updateData);
return $this->success(null, 'saved');
}
private function generateSecret(): string
{
$raw = random_bytes(24);
return rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
}
private function getConfigEntries(string $configKey): array
{
$raw = $this->systemConfigService->getValue($configKey, '[]');
if (!is_string($raw) || $raw === '') {
return [];
}
$decoded = json_decode($raw, true);
if (!is_array($decoded)) {
return [];
}
return array_values(array_filter($decoded, 'is_array'));
}
private function buildAppConfig(array $app): array
{
return [
'package_code' => trim((string)($app['package_code'] ?? '')),
'notify_url' => trim((string)($app['notify_url'] ?? '')),
'return_url' => trim((string)($app['return_url'] ?? '')),
'callback_mode' => trim((string)($app['callback_mode'] ?? 'server')) ?: 'server',
'sign_type' => trim((string)($app['sign_type'] ?? 'md5')) ?: 'md5',
'order_expire_minutes' => (int)($app['order_expire_minutes'] ?? 30),
'callback_retry_limit' => (int)($app['callback_retry_limit'] ?? 6),
'ip_whitelist' => trim((string)($app['ip_whitelist'] ?? '')),
'amount_min' => (string)($app['amount_min'] ?? '0.00'),
'amount_max' => (string)($app['amount_max'] ?? '0.00'),
'daily_limit' => (string)($app['daily_limit'] ?? '0.00'),
'notify_enabled' => (int)($app['notify_enabled'] ?? 1),
'remark' => trim((string)($app['remark'] ?? '')),
'updated_at' => (string)($app['updated_at'] ?? ''),
];
}
private function buildPackageMap(): array
{
$map = [];
foreach ($this->getConfigEntries('merchant_packages') as $package) {
$packageCode = trim((string)($package['package_code'] ?? ''));
if ($packageCode === '') {
continue;
}
$map[$packageCode] = trim((string)($package['package_name'] ?? $packageCode));
}
return $map;
}
}

View File

@@ -1,884 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\repositories\MerchantRepository;
use app\services\SystemConfigService;
use support\Db;
use support\Request;
class MerchantController extends BaseController
{
public function __construct(
protected MerchantRepository $merchantRepository,
protected SystemConfigService $systemConfigService,
) {
}
public function list(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = [
'status' => $request->get('status', ''),
'merchant_no' => trim((string)$request->get('merchant_no', '')),
'merchant_name' => trim((string)$request->get('merchant_name', '')),
'email' => trim((string)$request->get('email', '')),
'balance' => trim((string)$request->get('balance', '')),
];
$paginator = $this->merchantRepository->searchPaginate($filters, $page, $pageSize);
$items = [];
foreach ($paginator->items() as $row) {
$item = method_exists($row, 'toArray') ? $row->toArray() : (array)$row;
$items[] = $this->normalizeMerchantRow($item);
}
return $this->success([
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function detail(Request $request)
{
$id = (int)$request->get('id', 0);
if ($id <= 0) {
return $this->fail('merchant id is required', 400);
}
$row = $this->merchantRepository->find($id);
if (!$row) {
return $this->fail('merchant not found', 404);
}
$merchant = method_exists($row, 'toArray') ? $row->toArray() : (array)$row;
return $this->success($this->normalizeMerchantRow($merchant));
}
public function profileDetail(Request $request)
{
$id = (int)$request->get('id', 0);
if ($id <= 0) {
return $this->fail('merchant id is required', 400);
}
$merchant = $this->merchantRepository->find($id);
if (!$merchant) {
return $this->fail('merchant not found', 404);
}
$merchantRow = method_exists($merchant, 'toArray') ? $merchant->toArray() : (array)$merchant;
return $this->success([
'merchant' => $this->normalizeMerchantRow($merchantRow),
'profile' => $this->buildMerchantProfile($merchantRow),
]);
}
public function save(Request $request)
{
$data = $request->post();
$id = (int)($data['id'] ?? 0);
$merchantNo = trim((string)($data['merchant_no'] ?? ''));
$merchantName = trim((string)($data['merchant_name'] ?? ''));
$balance = max(0, (float)($data['balance'] ?? 0));
$email = trim((string)($data['email'] ?? $data['notify_email'] ?? ''));
$status = (int)($data['status'] ?? 1);
$remark = trim((string)($data['remark'] ?? ''));
if ($merchantNo === '' || $merchantName === '') {
return $this->fail('merchant_no and merchant_name are required', 400);
}
if ($id > 0) {
$this->merchantRepository->updateById($id, [
'merchant_no' => $merchantNo,
'merchant_name' => $merchantName,
'balance' => $balance,
'email' => $email,
'status' => $status,
'remark' => $remark,
'updated_at' => date('Y-m-d H:i:s'),
]);
} else {
$exists = $this->merchantRepository->findByMerchantNo($merchantNo);
if ($exists) {
return $this->fail('merchant_no already exists', 400);
}
$this->merchantRepository->create([
'merchant_no' => $merchantNo,
'merchant_name' => $merchantName,
'balance' => $balance,
'email' => $email,
'status' => $status,
'remark' => $remark,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
return $this->success(null, 'saved');
}
public function toggle(Request $request)
{
$id = (int)$request->post('id', 0);
$status = $request->post('status', null);
if ($id <= 0 || $status === null) {
return $this->fail('invalid params', 400);
}
$ok = $this->merchantRepository->updateById($id, ['status' => (int)$status]);
return $ok ? $this->success(null, 'updated') : $this->fail('update failed', 500);
}
public function profileSave(Request $request)
{
$merchantId = (int)$request->post('merchant_id', 0);
if ($merchantId <= 0) {
return $this->fail('merchant_id is required', 400);
}
$merchant = $this->merchantRepository->find($merchantId);
if (!$merchant) {
return $this->fail('merchant not found', 404);
}
$merchantRow = method_exists($merchant, 'toArray') ? $merchant->toArray() : (array)$merchant;
$profile = [
'email' => trim((string)$request->post('email', $request->post('notify_email', ''))),
'remark' => trim((string)$request->post('remark', '')),
'balance' => max(0, (float)$request->post('balance', $merchantRow['balance'] ?? 0)),
];
$updateData = $profile;
$updateData['updated_at'] = date('Y-m-d H:i:s');
$this->merchantRepository->updateById($merchantId, $updateData);
return $this->success(null, 'saved');
}
public function statistics(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildOpFilters($request);
$summaryQuery = Db::table('ma_mer as m')
->leftJoin('ma_pay_app as ma', 'ma.mer_id', '=', 'm.id')
->leftJoin('ma_pay_channel as pc', 'pc.mer_id', '=', 'm.id')
->leftJoin('ma_pay_order as o', function ($join) use ($filters) {
$join->on('o.merchant_id', '=', 'm.id');
if (!empty($filters['created_from'])) {
$join->where('o.created_at', '>=', $filters['created_from']);
}
if (!empty($filters['created_to'])) {
$join->where('o.created_at', '<=', $filters['created_to']);
}
});
$this->applyMerchantFilters($summaryQuery, $filters);
$summaryRow = $summaryQuery
->selectRaw(
'COUNT(DISTINCT m.id) AS merchant_count,
COUNT(DISTINCT CASE WHEN m.status = 1 THEN m.id END) AS active_merchant_count,
COUNT(DISTINCT ma.id) AS app_count,
COUNT(DISTINCT pc.id) AS channel_count,
COUNT(DISTINCT o.id) AS order_count,
COUNT(DISTINCT CASE WHEN o.status = 1 THEN o.id END) AS success_order_count,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.real_amount ELSE 0 END), 0) AS success_amount,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.fee ELSE 0 END), 0) AS fee_amount'
)
->first();
$listQuery = Db::table('ma_mer as m')
->leftJoin('ma_pay_app as ma', 'ma.mer_id', '=', 'm.id')
->leftJoin('ma_pay_channel as pc', 'pc.mer_id', '=', 'm.id')
->leftJoin('ma_pay_order as o', function ($join) use ($filters) {
$join->on('o.merchant_id', '=', 'm.id');
if (!empty($filters['created_from'])) {
$join->where('o.created_at', '>=', $filters['created_from']);
}
if (!empty($filters['created_to'])) {
$join->where('o.created_at', '<=', $filters['created_to']);
}
});
$this->applyMerchantFilters($listQuery, $filters);
$paginator = $listQuery
->selectRaw(
'm.id, m.merchant_no, m.merchant_name, m.balance, m.email, m.status, m.remark, m.created_at,
COUNT(DISTINCT ma.id) AS app_count,
COUNT(DISTINCT CASE WHEN ma.status = 1 THEN ma.id END) AS active_app_count,
COUNT(DISTINCT pc.id) AS channel_count,
COUNT(DISTINCT o.id) AS order_count,
COUNT(DISTINCT CASE WHEN o.status = 1 THEN o.id END) AS success_order_count,
COUNT(DISTINCT CASE WHEN o.status = 0 THEN o.id END) AS pending_order_count,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.real_amount ELSE 0 END), 0) AS success_amount,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.fee ELSE 0 END), 0) AS fee_amount,
MAX(o.created_at) AS last_order_at'
)
->groupBy('m.id', 'm.merchant_no', 'm.merchant_name', 'm.balance', 'm.email', 'm.status', 'm.remark', 'm.created_at')
->orderByDesc('m.id')
->paginate($pageSize, ['*'], 'page', $page);
return $this->success([
'summary' => [
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'active_merchant_count' => (int)($summaryRow->active_merchant_count ?? 0),
'app_count' => (int)($summaryRow->app_count ?? 0),
'channel_count' => (int)($summaryRow->channel_count ?? 0),
'order_count' => (int)($summaryRow->order_count ?? 0),
'success_order_count' => (int)($summaryRow->success_order_count ?? 0),
'success_amount' => (string)($summaryRow->success_amount ?? '0.00'),
'fee_amount' => (string)($summaryRow->fee_amount ?? '0.00'),
],
'list' => array_map(fn ($row) => (array)$row, $paginator->items()),
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function funds(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildOpFilters($request);
$summaryQuery = Db::table('ma_mer as m')
->leftJoin('ma_pay_order as o', function ($join) use ($filters) {
$join->on('o.merchant_id', '=', 'm.id');
if (!empty($filters['created_from'])) {
$join->where('o.created_at', '>=', $filters['created_from']);
}
if (!empty($filters['created_to'])) {
$join->where('o.created_at', '<=', $filters['created_to']);
}
});
$this->applyMerchantFilters($summaryQuery, $filters);
$summaryRow = $summaryQuery
->selectRaw(
'COUNT(DISTINCT m.id) AS merchant_count,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.real_amount ELSE 0 END), 0) AS settled_amount,
COALESCE(SUM(CASE WHEN o.status = 0 THEN o.amount ELSE 0 END), 0) AS pending_amount,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.fee ELSE 0 END), 0) AS fee_amount,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.real_amount - o.fee ELSE 0 END), 0) AS net_amount,
COUNT(DISTINCT CASE WHEN o.notify_stat = 0 THEN o.id END) AS notify_pending_orders'
)
->first();
$listQuery = Db::table('ma_mer as m')
->leftJoin('ma_pay_order as o', function ($join) use ($filters) {
$join->on('o.merchant_id', '=', 'm.id');
if (!empty($filters['created_from'])) {
$join->where('o.created_at', '>=', $filters['created_from']);
}
if (!empty($filters['created_to'])) {
$join->where('o.created_at', '<=', $filters['created_to']);
}
});
$this->applyMerchantFilters($listQuery, $filters);
$paginator = $listQuery
->selectRaw(
'm.id, m.merchant_no, m.merchant_name, m.balance, m.email, m.status, m.remark, m.created_at,
COUNT(DISTINCT CASE WHEN o.status = 1 THEN o.id END) AS success_order_count,
COUNT(DISTINCT CASE WHEN o.status = 0 THEN o.id END) AS pending_order_count,
COUNT(DISTINCT CASE WHEN o.notify_stat = 0 THEN o.id END) AS notify_pending_orders,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.real_amount ELSE 0 END), 0) AS settled_amount,
COALESCE(SUM(CASE WHEN o.status = 0 THEN o.amount ELSE 0 END), 0) AS pending_amount,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.fee ELSE 0 END), 0) AS fee_amount,
COALESCE(SUM(CASE WHEN o.status = 1 THEN o.real_amount - o.fee ELSE 0 END), 0) AS net_amount,
MAX(o.pay_at) AS last_pay_at'
)
->groupBy('m.id', 'm.merchant_no', 'm.merchant_name', 'm.balance', 'm.email', 'm.status', 'm.remark', 'm.created_at')
->orderByRaw('COALESCE(SUM(CASE WHEN o.status = 1 THEN o.real_amount - o.fee ELSE 0 END), 0) DESC')
->paginate($pageSize, ['*'], 'page', $page);
return $this->success([
'summary' => [
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'settled_amount' => (string)($summaryRow->settled_amount ?? '0.00'),
'pending_amount' => (string)($summaryRow->pending_amount ?? '0.00'),
'fee_amount' => (string)($summaryRow->fee_amount ?? '0.00'),
'net_amount' => (string)($summaryRow->net_amount ?? '0.00'),
'notify_pending_orders' => (int)($summaryRow->notify_pending_orders ?? 0),
],
'list' => array_map(fn ($row) => (array)$row, $paginator->items()),
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function audit(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$auditStatus = trim((string)$request->get('audit_status', ''));
$keyword = trim((string)$request->get('keyword', ''));
$summaryQuery = Db::table('ma_mer as m');
if ($keyword !== '') {
$summaryQuery->where(function ($query) use ($keyword) {
$query->where('m.merchant_no', 'like', '%' . $keyword . '%')
->orWhere('m.merchant_name', 'like', '%' . $keyword . '%');
});
}
if ($auditStatus === 'pending') {
$summaryQuery->where('m.status', 0);
} elseif ($auditStatus === 'approved') {
$summaryQuery->where('m.status', 1);
}
$summaryRow = $summaryQuery
->selectRaw(
'COUNT(DISTINCT m.id) AS merchant_count,
COUNT(DISTINCT CASE WHEN m.status = 0 THEN m.id END) AS pending_count,
COUNT(DISTINCT CASE WHEN m.status = 1 THEN m.id END) AS approved_count'
)
->first();
$listQuery = Db::table('ma_mer as m')
->leftJoin('ma_pay_app as ma', 'ma.mer_id', '=', 'm.id');
if ($keyword !== '') {
$listQuery->where(function ($query) use ($keyword) {
$query->where('m.merchant_no', 'like', '%' . $keyword . '%')
->orWhere('m.merchant_name', 'like', '%' . $keyword . '%');
});
}
if ($auditStatus === 'pending') {
$listQuery->where('m.status', 0);
} elseif ($auditStatus === 'approved') {
$listQuery->where('m.status', 1);
}
$paginator = $listQuery
->selectRaw(
'm.id, m.merchant_no, m.merchant_name, m.balance, m.email, m.status, m.remark, m.created_at, m.updated_at,
COUNT(DISTINCT ma.id) AS app_count,
COUNT(DISTINCT CASE WHEN ma.status = 1 THEN ma.id END) AS active_app_count,
COUNT(DISTINCT CASE WHEN ma.status = 0 THEN ma.id END) AS disabled_app_count'
)
->groupBy('m.id', 'm.merchant_no', 'm.merchant_name', 'm.balance', 'm.email', 'm.status', 'm.remark', 'm.created_at', 'm.updated_at')
->orderBy('m.status', 'asc')
->orderByDesc('m.id')
->paginate($pageSize, ['*'], 'page', $page);
$items = [];
foreach ($paginator->items() as $row) {
$item = (array)$row;
$item['audit_status'] = (int)($item['status'] ?? 0) === 1 ? 'approved' : 'pending';
$item['audit_status_text'] = $item['audit_status'] === 'approved' ? 'approved' : 'pending';
$items[] = $item;
}
return $this->success([
'summary' => [
'merchant_count' => (int)($summaryRow->merchant_count ?? 0),
'pending_count' => (int)($summaryRow->pending_count ?? 0),
'approved_count' => (int)($summaryRow->approved_count ?? 0),
],
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
public function auditAction(Request $request)
{
$id = (int)$request->post('id', 0);
$action = trim((string)$request->post('action', ''));
if ($id <= 0 || !in_array($action, ['approve', 'suspend'], true)) {
return $this->fail('invalid params', 400);
}
$status = $action === 'approve' ? 1 : 0;
Db::connection()->transaction(function () use ($id, $status) {
Db::table('ma_mer')->where('id', $id)->update([
'status' => $status,
'updated_at' => date('Y-m-d H:i:s'),
]);
Db::table('ma_pay_app')->where('mer_id', $id)->update([
'status' => $status,
'updated_at' => date('Y-m-d H:i:s'),
]);
});
return $this->success(null, $action === 'approve' ? 'approved' : 'suspended');
}
public function groupList(Request $request)
{
$page = max(1, (int)$request->get('page', 1));
$pageSize = max(1, (int)$request->get('page_size', 10));
$keyword = trim((string)$request->get('keyword', ''));
$status = $request->get('status', '');
$items = array_map([$this, 'normalizeGroupItem'], $this->getConfigEntries('merchant_groups'));
$items = array_values(array_filter($items, function (array $item) use ($keyword, $status) {
if ($keyword !== '') {
$haystacks = [
strtolower((string)($item['group_code'] ?? '')),
strtolower((string)($item['group_name'] ?? '')),
strtolower((string)($item['remark'] ?? '')),
];
$needle = strtolower($keyword);
$matched = false;
foreach ($haystacks as $haystack) {
if ($haystack !== '' && str_contains($haystack, $needle)) {
$matched = true;
break;
}
}
if (!$matched) {
return false;
}
}
if ($status !== '' && (int)$item['status'] !== (int)$status) {
return false;
}
return true;
}));
usort($items, function (array $a, array $b) {
$sortCompare = (int)($a['sort'] ?? 0) <=> (int)($b['sort'] ?? 0);
if ($sortCompare !== 0) {
return $sortCompare;
}
return strcmp((string)($b['updated_at'] ?? ''), (string)($a['updated_at'] ?? ''));
});
return $this->success($this->buildConfigPagePayload(
$items,
$page,
$pageSize,
[
'group_count' => count($items),
'active_count' => count(array_filter($items, fn (array $item) => (int)$item['status'] === 1)),
'disabled_count' => count(array_filter($items, fn (array $item) => (int)$item['status'] !== 1)),
]
));
}
public function groupSave(Request $request)
{
$data = $request->post();
$id = trim((string)($data['id'] ?? ''));
$groupCode = trim((string)($data['group_code'] ?? ''));
$groupName = trim((string)($data['group_name'] ?? ''));
if ($groupCode === '' || $groupName === '') {
return $this->fail('group_code and group_name are required', 400);
}
$items = array_map([$this, 'normalizeGroupItem'], $this->getConfigEntries('merchant_groups'));
foreach ($items as $item) {
if (($item['group_code'] ?? '') === $groupCode && ($item['id'] ?? '') !== $id) {
return $this->fail('group_code already exists', 400);
}
}
$now = date('Y-m-d H:i:s');
$saved = false;
foreach ($items as &$item) {
if (($item['id'] ?? '') !== $id || $id === '') {
continue;
}
$item = array_merge($item, [
'group_code' => $groupCode,
'group_name' => $groupName,
'sort' => (int)($data['sort'] ?? 0),
'status' => (int)($data['status'] ?? 1),
'remark' => trim((string)($data['remark'] ?? '')),
'updated_at' => $now,
]);
$saved = true;
break;
}
unset($item);
if (!$saved) {
$items[] = [
'id' => $id !== '' ? $id : uniqid('grp_', true),
'group_code' => $groupCode,
'group_name' => $groupName,
'sort' => (int)($data['sort'] ?? 0),
'status' => (int)($data['status'] ?? 1),
'remark' => trim((string)($data['remark'] ?? '')),
'merchant_count' => 0,
'created_at' => $now,
'updated_at' => $now,
];
}
$this->setConfigEntries('merchant_groups', $items);
return $this->success(null, 'saved');
}
public function groupDelete(Request $request)
{
$id = trim((string)$request->post('id', ''));
if ($id === '') {
return $this->fail('id is required', 400);
}
$items = array_map([$this, 'normalizeGroupItem'], $this->getConfigEntries('merchant_groups'));
$filtered = array_values(array_filter($items, fn (array $item) => ($item['id'] ?? '') !== $id));
if (count($filtered) === count($items)) {
return $this->fail('group not found', 404);
}
$this->setConfigEntries('merchant_groups', $filtered);
return $this->success(null, 'deleted');
}
public function packageList(Request $request)
{
$page = max(1, (int)$request->get('page', 1));
$pageSize = max(1, (int)$request->get('page_size', 10));
$keyword = trim((string)$request->get('keyword', ''));
$status = $request->get('status', '');
$apiType = trim((string)$request->get('api_type', ''));
$items = array_map([$this, 'normalizePackageItem'], $this->getConfigEntries('merchant_packages'));
$items = array_values(array_filter($items, function (array $item) use ($keyword, $status, $apiType) {
if ($keyword !== '') {
$haystacks = [
strtolower((string)($item['package_code'] ?? '')),
strtolower((string)($item['package_name'] ?? '')),
strtolower((string)($item['fee_desc'] ?? '')),
strtolower((string)($item['remark'] ?? '')),
];
$needle = strtolower($keyword);
$matched = false;
foreach ($haystacks as $haystack) {
if ($haystack !== '' && str_contains($haystack, $needle)) {
$matched = true;
break;
}
}
if (!$matched) {
return false;
}
}
if ($status !== '' && (int)$item['status'] !== (int)$status) {
return false;
}
if ($apiType !== '' && (string)$item['api_type'] !== $apiType) {
return false;
}
return true;
}));
usort($items, function (array $a, array $b) {
$sortCompare = (int)($a['sort'] ?? 0) <=> (int)($b['sort'] ?? 0);
if ($sortCompare !== 0) {
return $sortCompare;
}
return strcmp((string)($b['updated_at'] ?? ''), (string)($a['updated_at'] ?? ''));
});
$apiTypeCount = [];
foreach ($items as $item) {
$type = (string)($item['api_type'] ?? 'custom');
$apiTypeCount[$type] = ($apiTypeCount[$type] ?? 0) + 1;
}
return $this->success($this->buildConfigPagePayload(
$items,
$page,
$pageSize,
[
'package_count' => count($items),
'active_count' => count(array_filter($items, fn (array $item) => (int)$item['status'] === 1)),
'disabled_count' => count(array_filter($items, fn (array $item) => (int)$item['status'] !== 1)),
'api_type_count' => $apiTypeCount,
]
));
}
public function packageSave(Request $request)
{
$data = $request->post();
$id = trim((string)($data['id'] ?? ''));
$packageCode = trim((string)($data['package_code'] ?? ''));
$packageName = trim((string)($data['package_name'] ?? ''));
$apiType = trim((string)($data['api_type'] ?? 'epay'));
if ($packageCode === '' || $packageName === '') {
return $this->fail('package_code and package_name are required', 400);
}
if (!in_array($apiType, ['epay', 'openapi', 'custom'], true)) {
return $this->fail('invalid api_type', 400);
}
$items = array_map([$this, 'normalizePackageItem'], $this->getConfigEntries('merchant_packages'));
foreach ($items as $item) {
if (($item['package_code'] ?? '') === $packageCode && ($item['id'] ?? '') !== $id) {
return $this->fail('package_code already exists', 400);
}
}
$now = date('Y-m-d H:i:s');
$saved = false;
foreach ($items as &$item) {
if (($item['id'] ?? '') !== $id || $id === '') {
continue;
}
$item = array_merge($item, [
'package_code' => $packageCode,
'package_name' => $packageName,
'api_type' => $apiType,
'sort' => (int)($data['sort'] ?? 0),
'status' => (int)($data['status'] ?? 1),
'channel_limit' => max(0, (int)($data['channel_limit'] ?? 0)),
'daily_limit' => trim((string)($data['daily_limit'] ?? '')),
'fee_desc' => trim((string)($data['fee_desc'] ?? '')),
'callback_policy' => trim((string)($data['callback_policy'] ?? '')),
'remark' => trim((string)($data['remark'] ?? '')),
'updated_at' => $now,
]);
$saved = true;
break;
}
unset($item);
if (!$saved) {
$items[] = [
'id' => $id !== '' ? $id : uniqid('pkg_', true),
'package_code' => $packageCode,
'package_name' => $packageName,
'api_type' => $apiType,
'sort' => (int)($data['sort'] ?? 0),
'status' => (int)($data['status'] ?? 1),
'channel_limit' => max(0, (int)($data['channel_limit'] ?? 0)),
'daily_limit' => trim((string)($data['daily_limit'] ?? '')),
'fee_desc' => trim((string)($data['fee_desc'] ?? '')),
'callback_policy' => trim((string)($data['callback_policy'] ?? '')),
'remark' => trim((string)($data['remark'] ?? '')),
'created_at' => $now,
'updated_at' => $now,
];
}
$this->setConfigEntries('merchant_packages', $items);
return $this->success(null, 'saved');
}
public function packageDelete(Request $request)
{
$id = trim((string)$request->post('id', ''));
if ($id === '') {
return $this->fail('id is required', 400);
}
$items = array_map([$this, 'normalizePackageItem'], $this->getConfigEntries('merchant_packages'));
$filtered = array_values(array_filter($items, fn (array $item) => ($item['id'] ?? '') !== $id));
if (count($filtered) === count($items)) {
return $this->fail('package not found', 404);
}
$this->setConfigEntries('merchant_packages', $filtered);
return $this->success(null, 'deleted');
}
private function buildOpFilters(Request $request): array
{
return [
'merchant_id' => (int)$request->get('merchant_id', 0),
'status' => (string)$request->get('status', ''),
'keyword' => trim((string)$request->get('keyword', '')),
'email' => trim((string)$request->get('email', '')),
'balance' => trim((string)$request->get('balance', '')),
'created_from' => trim((string)$request->get('created_from', '')),
'created_to' => trim((string)$request->get('created_to', '')),
];
}
private function applyMerchantFilters($query, array $filters): void
{
if (($filters['status'] ?? '') !== '') {
$query->where('m.status', (int)$filters['status']);
}
if (!empty($filters['merchant_id'])) {
$query->where('m.id', (int)$filters['merchant_id']);
}
if (!empty($filters['keyword'])) {
$query->where(function ($builder) use ($filters) {
$builder->where('m.merchant_no', 'like', '%' . $filters['keyword'] . '%')
->orWhere('m.merchant_name', 'like', '%' . $filters['keyword'] . '%')
->orWhere('m.email', 'like', '%' . $filters['keyword'] . '%');
});
}
if (!empty($filters['email'])) {
$query->where('m.email', 'like', '%' . $filters['email'] . '%');
}
if (isset($filters['balance']) && $filters['balance'] !== '') {
$query->where('m.balance', (string)$filters['balance']);
}
}
private function getConfigEntries(string $configKey): array
{
$raw = $this->systemConfigService->getValue($configKey, '[]');
if (!is_string($raw) || $raw === '') {
return [];
}
$decoded = json_decode($raw, true);
if (!is_array($decoded)) {
return [];
}
return array_values(array_filter($decoded, 'is_array'));
}
private function setConfigEntries(string $configKey, array $items): void
{
$this->systemConfigService->setValue($configKey, array_values($items));
}
private function buildConfigPagePayload(array $items, int $page, int $pageSize, array $summary): array
{
$offset = ($page - 1) * $pageSize;
return [
'summary' => $summary,
'list' => array_values(array_slice($items, $offset, $pageSize)),
'total' => count($items),
'page' => $page,
'size' => $pageSize,
];
}
private function normalizeGroupItem(array $item): array
{
return [
'id' => (string)($item['id'] ?? ''),
'group_code' => trim((string)($item['group_code'] ?? '')),
'group_name' => trim((string)($item['group_name'] ?? '')),
'sort' => (int)($item['sort'] ?? 0),
'status' => (int)($item['status'] ?? 1),
'remark' => trim((string)($item['remark'] ?? '')),
'merchant_count' => max(0, (int)($item['merchant_count'] ?? 0)),
'created_at' => (string)($item['created_at'] ?? ''),
'updated_at' => (string)($item['updated_at'] ?? ''),
];
}
private function normalizePackageItem(array $item): array
{
$apiType = trim((string)($item['api_type'] ?? 'epay'));
if (!in_array($apiType, ['epay', 'openapi', 'custom'], true)) {
$apiType = 'custom';
}
return [
'id' => (string)($item['id'] ?? ''),
'package_code' => trim((string)($item['package_code'] ?? '')),
'package_name' => trim((string)($item['package_name'] ?? '')),
'api_type' => $apiType,
'sort' => (int)($item['sort'] ?? 0),
'status' => (int)($item['status'] ?? 1),
'channel_limit' => max(0, (int)($item['channel_limit'] ?? 0)),
'daily_limit' => trim((string)($item['daily_limit'] ?? '')),
'fee_desc' => trim((string)($item['fee_desc'] ?? '')),
'callback_policy' => trim((string)($item['callback_policy'] ?? '')),
'remark' => trim((string)($item['remark'] ?? '')),
'created_at' => (string)($item['created_at'] ?? ''),
'updated_at' => (string)($item['updated_at'] ?? ''),
];
}
private function merchantProfileKey(int $merchantId): string
{
return 'merchant_profile_' . $merchantId;
}
private function defaultMerchantProfile(): array
{
return [
'group_code' => '',
'contact_name' => '',
'contact_phone' => '',
'notify_email' => '',
'callback_domain' => '',
'callback_ip_whitelist' => '',
'risk_level' => 'standard',
'single_limit' => 0,
'daily_limit' => 0,
'settlement_cycle' => 't1',
'tech_support' => '',
'remark' => '',
'updated_at' => '',
];
}
private function buildGroupMap(): array
{
$map = [];
foreach ($this->getConfigEntries('merchant_groups') as $group) {
$groupCode = trim((string)($group['group_code'] ?? ''));
if ($groupCode === '') {
continue;
}
$map[$groupCode] = trim((string)($group['group_name'] ?? $groupCode));
}
return $map;
}
private function normalizeMerchantRow(array $merchant): array
{
$merchant['merchant_no'] = trim((string)($merchant['merchant_no'] ?? ''));
$merchant['merchant_name'] = trim((string)($merchant['merchant_name'] ?? ''));
$merchant['balance'] = (string)($merchant['balance'] ?? '0.00');
$merchant['email'] = trim((string)($merchant['email'] ?? ''));
$merchant['remark'] = trim((string)($merchant['remark'] ?? ''));
$merchant['status'] = (int)($merchant['status'] ?? 1);
$merchant['created_at'] = (string)($merchant['created_at'] ?? '');
$merchant['updated_at'] = (string)($merchant['updated_at'] ?? '');
return $merchant;
}
private function buildMerchantProfile(array $merchant): array
{
return [
'merchant_no' => trim((string)($merchant['merchant_no'] ?? '')),
'merchant_name' => trim((string)($merchant['merchant_name'] ?? '')),
'balance' => (string)($merchant['balance'] ?? '0.00'),
'email' => trim((string)($merchant['email'] ?? '')),
'status' => (int)($merchant['status'] ?? 1),
'remark' => trim((string)($merchant['remark'] ?? '')),
];
}
private function getConfigObject(string $configKey): array
{
$raw = $this->systemConfigService->getValue($configKey, '{}');
if (!is_string($raw) || $raw === '') {
return [];
}
$decoded = json_decode($raw, true);
return is_array($decoded) ? $decoded : [];
}
}

View File

@@ -1,316 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\models\Merchant;
use app\models\MerchantApp;
use app\models\PaymentChannel;
use app\models\PaymentMethod;
use app\repositories\PaymentMethodRepository;
use app\repositories\PaymentOrderRepository;
use app\services\PayOrderService;
use support\Request;
use support\Response;
/**
* 订单管理
*/
class OrderController extends BaseController
{
public function __construct(
protected PaymentOrderRepository $orderRepository,
protected PaymentMethodRepository $methodRepository,
protected PayOrderService $payOrderService,
) {
}
/**
* GET /adminapi/order/list
*/
public function list(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = $this->buildListFilters($request);
$paginator = $this->orderRepository->searchPaginate($filters, $page, $pageSize);
$items = [];
foreach ($paginator->items() as $row) {
$items[] = $this->formatOrderRow($row);
}
return $this->success([
'list' => $items,
'total' => $paginator->total(),
'page' => $paginator->currentPage(),
'size' => $paginator->perPage(),
]);
}
/**
* GET /adminapi/order/detail?id=1 或 order_id=P...
*/
public function detail(Request $request)
{
$id = (int)$request->get('id', 0);
$orderId = trim((string)$request->get('order_id', ''));
if ($id > 0) {
$row = $this->orderRepository->find($id);
} elseif ($orderId !== '') {
$row = $this->orderRepository->findByOrderId($orderId);
} else {
return $this->fail('参数错误', 400);
}
if (!$row) {
return $this->fail('订单不存在', 404);
}
return $this->success($this->formatOrderRow($row));
}
/**
* GET /adminapi/order/export
*/
public function export(Request $request): Response
{
$limit = 5000;
$filters = $this->buildListFilters($request);
$rows = $this->orderRepository->searchList($filters, $limit);
$merchantIds = [];
$merchantAppIds = [];
$methodIds = [];
$channelIds = [];
$items = [];
foreach ($rows as $row) {
$item = $this->formatOrderRow($row);
$items[] = $item;
if (!empty($item['merchant_id'])) {
$merchantIds[] = (int)$item['merchant_id'];
}
if (!empty($item['merchant_app_id'])) {
$merchantAppIds[] = (int)$item['merchant_app_id'];
}
if (!empty($item['method_id'])) {
$methodIds[] = (int)$item['method_id'];
}
if (!empty($item['channel_id'])) {
$channelIds[] = (int)$item['channel_id'];
}
}
$merchantMap = Merchant::query()
->whereIn('id', array_values(array_unique($merchantIds)))
->get(['id', 'merchant_no', 'merchant_name'])
->keyBy('id');
$merchantAppMap = MerchantApp::query()
->whereIn('id', array_values(array_unique($merchantAppIds)))
->get(['id', 'app_id', 'app_name'])
->keyBy('id');
$methodMap = PaymentMethod::query()
->whereIn('id', array_values(array_unique($methodIds)))
->get(['id', 'method_code', 'method_name'])
->keyBy('id');
$channelMap = PaymentChannel::query()
->whereIn('id', array_values(array_unique($channelIds)))
->get(['id', 'chan_code', 'chan_name'])
->keyBy('id');
$stream = fopen('php://temp', 'r+');
fwrite($stream, "\xEF\xBB\xBF");
fputcsv($stream, [
'系统单号',
'商户单号',
'商户编号',
'商户名称',
'应用APPID',
'应用名称',
'支付方式编码',
'支付方式名称',
'通道编码',
'通道名称',
'订单金额',
'实收金额',
'手续费',
'币种',
'订单状态',
'路由结果',
'路由模式',
'策略名称',
'通道单号',
'通道交易号',
'通知状态',
'通知次数',
'客户端IP',
'商品标题',
'创建时间',
'支付时间',
'路由错误',
]);
foreach ($items as $item) {
$merchant = $merchantMap->get((int)($item['merchant_id'] ?? 0));
$merchantApp = $merchantAppMap->get((int)($item['merchant_app_id'] ?? 0));
$method = $methodMap->get((int)($item['method_id'] ?? 0));
$channel = $channelMap->get((int)($item['channel_id'] ?? 0));
fputcsv($stream, [
(string)($item['order_id'] ?? ''),
(string)($item['mch_order_no'] ?? ''),
(string)($merchant->merchant_no ?? ''),
(string)($merchant->merchant_name ?? ''),
(string)($merchantApp->app_id ?? ''),
(string)($merchantApp->app_name ?? ''),
(string)($method->method_code ?? ''),
(string)($method->method_name ?? ''),
(string)($channel->chan_code ?? $item['route_channel_code'] ?? ''),
(string)($channel->chan_name ?? $item['route_channel_name'] ?? ''),
(string)($item['amount'] ?? '0.00'),
(string)($item['real_amount'] ?? '0.00'),
(string)($item['fee'] ?? '0.00'),
(string)($item['currency'] ?? ''),
$this->statusText((int)($item['status'] ?? 0)),
(string)($item['route_source_text'] ?? ''),
(string)($item['route_mode_text'] ?? ''),
(string)($item['route_policy_name'] ?? ''),
(string)($item['chan_order_no'] ?? ''),
(string)($item['chan_trade_no'] ?? ''),
$this->notifyStatusText((int)($item['notify_stat'] ?? 0)),
(string)($item['notify_cnt'] ?? '0'),
(string)($item['client_ip'] ?? ''),
(string)($item['subject'] ?? ''),
(string)($item['created_at'] ?? ''),
(string)($item['pay_at'] ?? ''),
(string)($item['route_error']['message'] ?? ''),
]);
}
rewind($stream);
$content = stream_get_contents($stream) ?: '';
fclose($stream);
$filename = 'orders-' . date('Ymd-His') . '.csv';
return response($content, 200, [
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => "attachment; filename*=UTF-8''" . rawurlencode($filename),
'X-Export-Count' => (string)count($items),
'X-Export-Limit' => (string)$limit,
'X-Export-Limited' => count($items) >= $limit ? '1' : '0',
]);
}
/**
* POST /adminapi/order/refund
* - order_id: 系统订单号
* - refund_amount: 退款金额
*/
public function refund(Request $request)
{
$orderId = trim((string)$request->post('order_id', ''));
$refundAmount = (float)$request->post('refund_amount', 0);
$refundReason = trim((string)$request->post('refund_reason', ''));
try {
$result = $this->payOrderService->refundOrder([
'order_id' => $orderId,
'refund_amount' => $refundAmount,
'refund_reason' => $refundReason,
]);
return $this->success($result, '退款发起成功');
} catch (\Throwable $e) {
return $this->fail($e->getMessage(), 400);
}
}
private function formatOrderRow(object $row): array
{
$data = method_exists($row, 'toArray') ? $row->toArray() : (array)$row;
$extra = is_array($data['extra'] ?? null) ? $data['extra'] : [];
$routing = is_array($extra['routing'] ?? null) ? $extra['routing'] : null;
$routeError = is_array($extra['route_error'] ?? null) ? $extra['route_error'] : null;
$data['routing'] = $routing;
$data['route_error'] = $routeError;
$data['route_candidates'] = is_array($routing['candidates'] ?? null) ? $routing['candidates'] : [];
$data['route_policy_name'] = (string)($routing['policy']['policy_name'] ?? '');
$data['route_source'] = (string)($routing['source'] ?? '');
$data['route_source_text'] = $this->routeSourceText($routing, $routeError);
$data['route_mode_text'] = $this->routeModeText((string)($routing['route_mode'] ?? ''));
$data['route_channel_name'] = (string)($routing['selected_channel_name'] ?? '');
$data['route_channel_code'] = (string)($routing['selected_channel_code'] ?? '');
$data['route_state'] = $routeError
? 'error'
: ($routing ? (string)($routing['source'] ?? 'unknown') : 'none');
return $data;
}
private function buildListFilters(Request $request): array
{
$methodCode = trim((string)$request->get('method_code', ''));
$methodId = 0;
if ($methodCode !== '') {
$method = $this->methodRepository->findAnyByCode($methodCode);
$methodId = $method ? (int)$method->id : 0;
}
return [
'merchant_id' => (int)$request->get('merchant_id', 0),
'merchant_app_id' => (int)$request->get('merchant_app_id', 0),
'method_id' => $methodId,
'channel_id' => (int)$request->get('channel_id', 0),
'route_state' => trim((string)$request->get('route_state', '')),
'route_policy_name' => trim((string)$request->get('route_policy_name', '')),
'status' => $request->get('status', ''),
'order_id' => trim((string)$request->get('order_id', '')),
'mch_order_no' => trim((string)$request->get('mch_order_no', '')),
'created_from' => trim((string)$request->get('created_from', '')),
'created_to' => trim((string)$request->get('created_to', '')),
];
}
private function statusText(int $status): string
{
return match ($status) {
0 => '待支付',
1 => '成功',
2 => '失败',
3 => '关闭',
default => (string)$status,
};
}
private function notifyStatusText(int $notifyStatus): string
{
return $notifyStatus === 1 ? '已通知' : '待通知';
}
private function routeSourceText(?array $routing, ?array $routeError): string
{
if ($routeError) {
return '路由失败';
}
return match ((string)($routing['source'] ?? '')) {
'policy' => '策略命中',
'fallback' => '回退选择',
default => '未记录',
};
}
private function routeModeText(string $routeMode): string
{
return match ($routeMode) {
'priority' => '优先级',
'weight' => '权重分流',
'failover' => '主备切换',
'sort' => '排序兜底',
default => $routeMode ?: '-',
};
}
}

View File

@@ -1,96 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\repositories\PaymentMethodRepository;
use support\Request;
/**
* 支付方式管理
*/
class PayMethodController extends BaseController
{
public function __construct(
protected PaymentMethodRepository $methodRepository,
) {
}
/**
* GET /adminapi/pay-method/list
*/
public function list(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = [
'status' => $request->get('status', ''),
'method_code' => trim((string)$request->get('method_code', '')),
'method_name' => trim((string)$request->get('method_name', '')),
];
$paginator = $this->methodRepository->searchPaginate($filters, $page, $pageSize);
return $this->page($paginator);
}
/**
* POST /adminapi/pay-method/save
*/
public function save(Request $request)
{
$data = $request->post();
$id = (int)($data['id'] ?? 0);
$code = trim((string)($data['method_code'] ?? ''));
$name = trim((string)($data['method_name'] ?? ''));
$icon = trim((string)($data['icon'] ?? ''));
$sort = (int)($data['sort'] ?? 0);
$status = (int)($data['status'] ?? 1);
if ($code === '' || $name === '') {
return $this->fail('支付方式编码与名称不能为空', 400);
}
if ($id > 0) {
$this->methodRepository->updateById($id, [
'type' => $code,
'name' => $name,
'icon' => $icon,
'sort' => $sort,
'status' => $status,
]);
} else {
$exists = $this->methodRepository->findAnyByCode($code);
if ($exists) {
return $this->fail('支付方式编码已存在', 400);
}
$this->methodRepository->create([
'type' => $code,
'name' => $name,
'icon' => $icon,
'sort' => $sort,
'status' => $status,
]);
}
return $this->success(null, '保存成功');
}
/**
* POST /adminapi/pay-method/toggle
*/
public function toggle(Request $request)
{
$id = (int)$request->post('id', 0);
$status = $request->post('status', null);
if ($id <= 0 || $status === null) {
return $this->fail('参数错误', 400);
}
$ok = $this->methodRepository->updateById($id, ['status' => (int)$status]);
return $ok ? $this->success(null, '操作成功') : $this->fail('操作失败', 500);
}
}

View File

@@ -1,85 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\repositories\PaymentPluginRepository;
use support\Request;
/**
* 插件注册表管理ma_pay_plugin
*
* 注意:与 /channel/plugin/* 的“插件能力读取schema/products”不同这里负责维护插件注册表本身。
*/
class PayPluginController extends BaseController
{
public function __construct(
protected PaymentPluginRepository $pluginRepository,
) {
}
/**
* GET /adminapi/pay-plugin/list
*/
public function list(Request $request)
{
$page = (int)$request->get('page', 1);
$pageSize = (int)$request->get('page_size', 10);
$filters = [
'status' => $request->get('status', ''),
'plugin_code' => trim((string)$request->get('plugin_code', '')),
'plugin_name' => trim((string)$request->get('plugin_name', '')),
];
$paginator = $this->pluginRepository->searchPaginate($filters, $page, $pageSize);
return $this->page($paginator);
}
/**
* POST /adminapi/pay-plugin/save
*/
public function save(Request $request)
{
$data = $request->post();
$pluginCode = trim((string)($data['plugin_code'] ?? ''));
$pluginName = trim((string)($data['plugin_name'] ?? ''));
$className = trim((string)($data['class_name'] ?? ''));
$status = (int)($data['status'] ?? 1);
if ($pluginCode === '' || $pluginName === '') {
return $this->fail('插件编码与名称不能为空', 400);
}
if ($className === '') {
// 默认约定类名
$className = ucfirst($pluginCode) . 'Payment';
}
$this->pluginRepository->upsertByCode($pluginCode, [
'name' => $pluginName,
'class_name' => $className,
'status' => $status,
]);
return $this->success(null, '保存成功');
}
/**
* POST /adminapi/pay-plugin/toggle
*/
public function toggle(Request $request)
{
$pluginCode = trim((string)$request->post('plugin_code', ''));
$status = $request->post('status', null);
if ($pluginCode === '' || $status === null) {
return $this->fail('参数错误', 400);
}
$ok = $this->pluginRepository->updateStatus($pluginCode, (int)$status);
return $ok ? $this->success(null, '操作成功') : $this->fail('操作失败', 500);
}
}

View File

@@ -1,71 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\services\PluginService;
use support\Request;
/**
* 插件管理控制器
*/
class PluginController extends BaseController
{
public function __construct(
protected PluginService $pluginService
) {
}
/**
* 获取所有可用插件列表
* GET /adminapi/channel/plugins
*/
public function plugins()
{
$plugins = $this->pluginService->listPlugins();
return $this->success($plugins);
}
/**
* 获取插件配置Schema
* GET /adminapi/channel/plugin/config-schema
*/
public function configSchema(Request $request)
{
$pluginCode = $request->get('plugin_code', '');
$methodCode = $request->get('method_code', '');
if (empty($pluginCode) || empty($methodCode)) {
return $this->fail('插件编码和支付方式不能为空', 400);
}
try {
$schema = $this->pluginService->getConfigSchema($pluginCode, $methodCode);
return $this->success($schema);
} catch (\Throwable $e) {
return $this->fail('获取配置Schema失败' . $e->getMessage(), 400);
}
}
/**
* 获取插件支持的支付产品列表
* GET /adminapi/channel/plugin/products
*/
public function products(Request $request)
{
$pluginCode = $request->get('plugin_code', '');
$methodCode = $request->get('method_code', '');
if (empty($pluginCode) || empty($methodCode)) {
return $this->fail('插件编码和支付方式不能为空', 400);
}
try {
$products = $this->pluginService->getSupportedProducts($pluginCode, $methodCode);
return $this->success($products);
} catch (\Throwable $e) {
return $this->fail('获取产品列表失败:' . $e->getMessage(), 400);
}
}
}

View File

@@ -1,312 +0,0 @@
<?php
namespace app\http\admin\controller;
use app\common\base\BaseController;
use app\services\SystemConfigService;
use app\services\SystemSettingService;
use support\Db;
use support\Request;
class SystemController extends BaseController
{
public function __construct(
protected SystemSettingService $settingService,
protected SystemConfigService $configService
) {
}
public function getDict(Request $request, string $code = '')
{
$data = $this->settingService->getDict($code);
return $this->success($data);
}
public function getTabsConfig()
{
return $this->success($this->settingService->getTabs());
}
public function getFormConfig(Request $request, string $tabKey)
{
return $this->success($this->settingService->getFormConfig($tabKey));
}
public function submitConfig(Request $request, string $tabKey)
{
$formData = $request->post();
if (empty($formData)) {
return $this->fail('submitted data is empty', 400);
}
$this->settingService->saveFormConfig($tabKey, $formData);
return $this->success(null, 'saved');
}
public function logFiles()
{
$logDir = runtime_path('logs');
if (!is_dir($logDir)) {
return $this->success([]);
}
$items = [];
foreach (glob($logDir . DIRECTORY_SEPARATOR . '*.log') ?: [] as $file) {
if (!is_file($file)) {
continue;
}
$items[] = [
'name' => basename($file),
'size' => filesize($file) ?: 0,
'updated_at' => date('Y-m-d H:i:s', filemtime($file) ?: time()),
];
}
usort($items, fn ($a, $b) => strcmp((string)$b['updated_at'], (string)$a['updated_at']));
return $this->success($items);
}
public function logSummary()
{
$logDir = runtime_path('logs');
if (!is_dir($logDir)) {
return $this->success([
'total_files' => 0,
'total_size' => 0,
'latest_file' => '',
'categories' => [],
]);
}
$files = glob($logDir . DIRECTORY_SEPARATOR . '*.log') ?: [];
$categoryStats = [];
$totalSize = 0;
$latestFile = '';
$latestTime = 0;
foreach ($files as $file) {
if (!is_file($file)) {
continue;
}
$size = filesize($file) ?: 0;
$updatedAt = filemtime($file) ?: 0;
$name = basename($file);
$category = $this->resolveLogCategory($name);
$totalSize += $size;
if (!isset($categoryStats[$category])) {
$categoryStats[$category] = [
'category' => $category,
'file_count' => 0,
'total_size' => 0,
];
}
$categoryStats[$category]['file_count']++;
$categoryStats[$category]['total_size'] += $size;
if ($updatedAt >= $latestTime) {
$latestTime = $updatedAt;
$latestFile = $name;
}
}
return $this->success([
'total_files' => count($files),
'total_size' => $totalSize,
'latest_file' => $latestFile,
'categories' => array_values($categoryStats),
]);
}
public function logContent(Request $request)
{
$file = basename(trim((string)$request->get('file', '')));
$lines = max(20, min(1000, (int)$request->get('lines', 200)));
$keyword = trim((string)$request->get('keyword', ''));
$level = strtoupper(trim((string)$request->get('level', '')));
if ($file === '') {
return $this->fail('file is required', 400);
}
$logDir = runtime_path('logs');
$fullPath = realpath($logDir . DIRECTORY_SEPARATOR . $file);
$realLogDir = realpath($logDir);
if (!$fullPath || !$realLogDir || !str_starts_with($fullPath, $realLogDir) || !is_file($fullPath)) {
return $this->fail('log file not found', 404);
}
$contentLines = file($fullPath, FILE_IGNORE_NEW_LINES);
if (!is_array($contentLines)) {
return $this->fail('failed to read log file', 500);
}
if ($keyword !== '') {
$contentLines = array_values(array_filter($contentLines, static function ($line) use ($keyword) {
return stripos($line, $keyword) !== false;
}));
}
if ($level !== '') {
$contentLines = array_values(array_filter($contentLines, static function ($line) use ($level) {
return stripos(strtoupper($line), $level) !== false;
}));
}
$matchedLineCount = count($contentLines);
$tail = array_slice($contentLines, -$lines);
return $this->success([
'file' => $file,
'size' => filesize($fullPath) ?: 0,
'updated_at' => date('Y-m-d H:i:s', filemtime($fullPath) ?: time()),
'line_count' => $matchedLineCount,
'keyword' => $keyword,
'level' => $level,
'lines' => $tail,
'content' => implode(PHP_EOL, $tail),
]);
}
public function noticeOverview()
{
$config = $this->configService->getValues([
'smtp_host',
'smtp_port',
'smtp_ssl',
'smtp_username',
'smtp_password',
'from_email',
'from_name',
]);
$taskSummary = Db::table('ma_notify_task')
->selectRaw(
'COUNT(*) AS total_tasks,
SUM(CASE WHEN status = \'PENDING\' THEN 1 ELSE 0 END) AS pending_tasks,
SUM(CASE WHEN status = \'SUCCESS\' THEN 1 ELSE 0 END) AS success_tasks,
SUM(CASE WHEN status = \'FAIL\' THEN 1 ELSE 0 END) AS fail_tasks,
MAX(last_notify_at) AS last_notify_at'
)
->first();
$orderSummary = Db::table('ma_pay_order')
->selectRaw(
'SUM(CASE WHEN status = 1 AND notify_stat = 0 THEN 1 ELSE 0 END) AS notify_pending_orders,
SUM(CASE WHEN status = 1 AND notify_stat = 1 THEN 1 ELSE 0 END) AS notified_orders'
)
->first();
$requiredKeys = ['smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'from_email'];
$configuredCount = 0;
foreach ($requiredKeys as $key) {
if (!empty($config[$key])) {
$configuredCount++;
}
}
return $this->success([
'config' => [
'smtp_host' => (string)($config['smtp_host'] ?? ''),
'smtp_port' => (string)($config['smtp_port'] ?? ''),
'smtp_ssl' => in_array(strtolower((string)($config['smtp_ssl'] ?? '')), ['1', 'true', 'yes', 'on'], true),
'smtp_username' => $this->maskString((string)($config['smtp_username'] ?? '')),
'from_email' => (string)($config['from_email'] ?? ''),
'from_name' => (string)($config['from_name'] ?? ''),
'configured_fields' => $configuredCount,
'required_fields' => count($requiredKeys),
'is_ready' => $configuredCount === count($requiredKeys),
],
'tasks' => [
'total_tasks' => (int)($taskSummary->total_tasks ?? 0),
'pending_tasks' => (int)($taskSummary->pending_tasks ?? 0),
'success_tasks' => (int)($taskSummary->success_tasks ?? 0),
'fail_tasks' => (int)($taskSummary->fail_tasks ?? 0),
'last_notify_at' => (string)($taskSummary->last_notify_at ?? ''),
],
'orders' => [
'notify_pending_orders' => (int)($orderSummary->notify_pending_orders ?? 0),
'notified_orders' => (int)($orderSummary->notified_orders ?? 0),
],
]);
}
public function noticeTest(Request $request)
{
$config = $this->configService->getValues([
'smtp_host',
'smtp_port',
'smtp_ssl',
'smtp_username',
'smtp_password',
'from_email',
]);
$missingFields = [];
foreach (['smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'from_email'] as $field) {
if (empty($config[$field])) {
$missingFields[] = $field;
}
}
if ($missingFields !== []) {
return $this->fail('missing config fields: ' . implode(', ', $missingFields), 400);
}
$host = (string)$config['smtp_host'];
$port = (int)$config['smtp_port'];
$useSsl = in_array(strtolower((string)($config['smtp_ssl'] ?? '')), ['1', 'true', 'yes', 'on'], true);
$transport = ($useSsl ? 'ssl://' : 'tcp://') . $host . ':' . $port;
$errno = 0;
$errstr = '';
$connection = @stream_socket_client($transport, $errno, $errstr, 5, STREAM_CLIENT_CONNECT);
if (!is_resource($connection)) {
return $this->fail('smtp connection failed: ' . ($errstr !== '' ? $errstr : 'unknown error'), 500);
}
stream_set_timeout($connection, 3);
$banner = fgets($connection, 512) ?: '';
fclose($connection);
return $this->success([
'transport' => $transport,
'banner' => trim($banner),
'checked_at' => date('Y-m-d H:i:s'),
'note' => 'only smtp connectivity and basic config were verified; no test email was sent',
], 'smtp connection ok');
}
private function resolveLogCategory(string $fileName): string
{
$name = strtolower($fileName);
if (str_contains($name, 'pay') || str_contains($name, 'notify')) {
return 'payment';
}
if (str_contains($name, 'queue') || str_contains($name, 'job')) {
return 'queue';
}
if (str_contains($name, 'error') || str_contains($name, 'exception')) {
return 'error';
}
if (str_contains($name, 'admin') || str_contains($name, 'system')) {
return 'system';
}
return 'other';
}
private function maskString(string $value): string
{
$length = strlen($value);
if ($length <= 4) {
return $value === '' ? '' : str_repeat('*', $length);
}
return substr($value, 0, 2) . str_repeat('*', max(2, $length - 4)) . substr($value, -2);
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace app\http\admin\controller\account;
use app\common\base\BaseController;
use app\http\admin\validation\MerchantAccountValidator;
use app\service\account\funds\MerchantAccountService;
use support\Request;
use support\Response;
/**
* 商户账户控制器。
*/
class MerchantAccountController extends BaseController
{
/**
* 构造函数,注入商户账户服务。
*/
public function __construct(
protected MerchantAccountService $merchantAccountService
) {
}
/**
* 查询商户账户列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), MerchantAccountValidator::class, 'index');
return $this->page(
$this->merchantAccountService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* 资金中心概览。
*/
public function summary(Request $request): Response
{
return $this->success($this->merchantAccountService->summary());
}
/**
* 查询商户账户详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantAccountValidator::class, 'show');
$account = $this->merchantAccountService->findById((int) $data['id']);
if (!$account) {
return $this->fail('商户账户不存在', 404);
}
return $this->success($account);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace app\http\admin\controller\account;
use app\common\base\BaseController;
use app\http\admin\validation\MerchantAccountLedgerValidator;
use app\service\account\ledger\MerchantAccountLedgerService;
use support\Request;
use support\Response;
/**
* 商户账户流水控制器。
*/
class MerchantAccountLedgerController extends BaseController
{
/**
* 构造函数,注入账户流水服务。
*/
public function __construct(
protected MerchantAccountLedgerService $merchantAccountLedgerService
) {
}
/**
* 查询账户流水列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), MerchantAccountLedgerValidator::class, 'index');
return $this->page(
$this->merchantAccountLedgerService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* 查询账户流水详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantAccountLedgerValidator::class, 'show');
$ledger = $this->merchantAccountLedgerService->findById((int) $data['id']);
if (!$ledger) {
return $this->fail('账户流水不存在', 404);
}
return $this->success($ledger);
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace app\http\admin\controller\file;
use app\common\base\BaseController;
use app\http\admin\validation\FileRecordValidator;
use app\service\file\FileRecordService;
use Webman\Http\UploadFile;
use support\Request;
use support\Response;
/**
* 文件控制器。
*/
class FileRecordController extends BaseController
{
public function __construct(
protected FileRecordService $fileRecordService
) {
}
public function index(Request $request): Response
{
$data = $this->validated($request->all(), FileRecordValidator::class, 'index');
return $this->page(
$this->fileRecordService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
public function options(Request $request): Response
{
return $this->success($this->fileRecordService->options());
}
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], FileRecordValidator::class, 'show');
return $this->success($this->fileRecordService->detail((int) $data['id']));
}
public function upload(Request $request): Response
{
$data = $this->validated(array_merge($this->payload($request), ['scene' => $request->input('scene')]), FileRecordValidator::class, 'store');
$uploadedFile = $request->file('file');
if ($uploadedFile === null) {
return $this->fail('请先选择上传文件', 400);
}
$createdBy = $this->currentAdminId($request);
$createdByName = (string) $this->requestAttribute($request, 'auth.admin_username', '');
if (is_array($uploadedFile)) {
$items = [];
foreach ($uploadedFile as $file) {
if ($file instanceof UploadFile) {
$items[] = $this->fileRecordService->upload($file, $data, $createdBy, $createdByName);
}
}
return $this->success([
'list' => $items,
'total' => count($items),
]);
}
if (!$uploadedFile instanceof UploadFile) {
return $this->fail('上传文件无效', 400);
}
return $this->success($this->fileRecordService->upload($uploadedFile, $data, $createdBy, $createdByName));
}
public function importRemote(Request $request): Response
{
$data = $this->validated($this->payload($request), FileRecordValidator::class, 'importRemote');
$createdBy = $this->currentAdminId($request);
$createdByName = (string) $this->requestAttribute($request, 'auth.admin_username', '');
return $this->success(
$this->fileRecordService->importRemote(
(string) $data['remote_url'],
$data,
$createdBy,
$createdByName
)
);
}
public function preview(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], FileRecordValidator::class, 'preview');
return $this->fileRecordService->previewResponse((int) $data['id']);
}
public function download(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], FileRecordValidator::class, 'download');
return $this->fileRecordService->downloadResponse((int) $data['id']);
}
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], FileRecordValidator::class, 'destroy');
if (!$this->fileRecordService->delete((int) $data['id'])) {
return $this->fail('文件不存在', 404);
}
return $this->success(true);
}
}

View File

@@ -0,0 +1,103 @@
<?php
namespace app\http\admin\controller\merchant;
use app\common\base\BaseController;
use app\http\admin\validation\MerchantApiCredentialValidator;
use app\service\merchant\security\MerchantApiCredentialService;
use support\Request;
use support\Response;
/**
* 商户接口凭证管理控制器。
*/
class MerchantApiCredentialController extends BaseController
{
/**
* 构造函数,注入商户 API 凭证服务。
*/
public function __construct(
protected MerchantApiCredentialService $merchantApiCredentialService
) {
}
/**
* 查询商户 API 凭证列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), MerchantApiCredentialValidator::class, 'index');
return $this->page(
$this->merchantApiCredentialService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* 查询商户 API 凭证详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantApiCredentialValidator::class, 'show');
$credential = $this->merchantApiCredentialService->findById((int) $data['id']);
if (!$credential) {
return $this->fail('商户接口凭证不存在', 404);
}
return $this->success($credential);
}
/**
* 新增商户 API 凭证。
*/
public function store(Request $request): Response
{
$data = $this->validated($request->all(), MerchantApiCredentialValidator::class, 'store');
return $this->success($this->merchantApiCredentialService->create($data));
}
/**
* 修改商户 API 凭证。
*/
public function update(Request $request, string $id): Response
{
$data = $this->validated(
array_merge($request->all(), ['id' => (int) $id]),
MerchantApiCredentialValidator::class,
'update'
);
$credential = $this->merchantApiCredentialService->update((int) $data['id'], $data);
if (!$credential) {
return $this->fail('商户接口凭证不存在', 404);
}
return $this->success($credential);
}
/**
* 删除商户 API 凭证。
*/
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantApiCredentialValidator::class, 'destroy');
$credential = $this->merchantApiCredentialService->findById((int) $data['id']);
if (!$credential) {
return $this->fail('商户接口凭证不存在', 404);
}
if (!$this->merchantApiCredentialService->delete((int) $data['id'])) {
return $this->fail('商户接口凭证删除失败');
}
return $this->success(true);
}
}

View File

@@ -0,0 +1,141 @@
<?php
namespace app\http\admin\controller\merchant;
use app\common\base\BaseController;
use app\http\admin\validation\MerchantValidator;
use app\service\merchant\MerchantService;
use support\Request;
use support\Response;
/**
* 商户管理控制器。
*
* 当前先提供商户列表查询,后续可继续扩展商户详情、新增、编辑等能力。
*/
class MerchantController extends BaseController
{
/**
* 构造函数,注入商户服务。
*/
public function __construct(
protected MerchantService $merchantService
) {
}
/**
* 查询商户列表。
*
* 返回值里额外携带启用中的商户分组选项,方便前端一次性渲染筛选条件。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), MerchantValidator::class, 'index');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = max(1, (int) ($data['page_size'] ?? 10));
return $this->success($this->merchantService->paginateWithGroupOptions($data, $page, $pageSize));
}
/**
* 查询商户详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantValidator::class, 'show');
$merchant = $this->merchantService->findById((int) $data['id']);
if (!$merchant) {
return $this->fail('商户不存在', 404);
}
return $this->success($merchant);
}
/**
* 新增商户。
*/
public function store(Request $request): Response
{
$data = $this->validated($request->all(), MerchantValidator::class, 'store');
return $this->success($this->merchantService->createWithDetail($data));
}
/**
* 更新商户。
*/
public function update(Request $request, string $id): Response
{
$payload = array_merge($request->all(), ['id' => (int) $id]);
$scene = count(array_diff(array_keys($request->all()), ['status'])) === 0 ? 'updateStatus' : 'update';
$data = $this->validated($payload, MerchantValidator::class, $scene);
$merchant = $this->merchantService->updateWithDetail((int) $data['id'], $data);
if (!$merchant) {
return $this->fail('商户不存在', 404);
}
return $this->success($merchant);
}
/**
* 删除商户。
*/
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantValidator::class, 'destroy');
return $this->success($this->merchantService->delete((int) $data['id']));
}
/**
* 重置商户登录密码。
*/
public function resetPassword(Request $request, string $id): Response
{
$payload = array_merge($request->all(), ['id' => (int) $id]);
$data = $this->validated($payload, MerchantValidator::class, 'resetPassword');
return $this->success($this->merchantService->resetPassword((int) $data['id'], (string) $data['password']));
}
/**
* 生成或重置商户接口凭证。
*/
public function issueCredential(Request $request, string $id): Response
{
$merchantId = (int) $id;
return $this->success($this->merchantService->issueCredential($merchantId));
}
/**
* 查询商户总览。
*/
public function overview(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantValidator::class, 'overview');
return $this->success($this->merchantService->overview((int) $data['id']));
}
/**
* 查询商户下拉选项。
*/
public function options(Request $request): Response
{
return $this->success($this->merchantService->enabledOptions());
}
/**
* 远程查询商户选择项。
*/
public function selectOptions(Request $request): Response
{
$page = max(1, (int) $request->input('page', 1));
$pageSize = min(50, max(1, (int) $request->input('page_size', 20)));
return $this->success($this->merchantService->searchOptions($request->all(), $page, $pageSize));
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace app\http\admin\controller\merchant;
use app\common\base\BaseController;
use app\http\admin\validation\MerchantGroupValidator;
use app\service\merchant\group\MerchantGroupService;
use support\Request;
use support\Response;
/**
* 商户分组管理控制器。
*
* 负责商户分组的列表、详情、新增、修改和删除。
*/
class MerchantGroupController extends BaseController
{
/**
* 构造函数,注入商户分组服务。
*/
public function __construct(
protected MerchantGroupService $merchantGroupService
) {
}
/**
* GET /admin/merchant-groups
*
* 查询商户分组列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), MerchantGroupValidator::class, 'index');
return $this->page(
$this->merchantGroupService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* GET /admin/merchant-groups/{id}
*
* 查询商户分组详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantGroupValidator::class, 'show');
$merchantGroup = $this->merchantGroupService->findById((int) $data['id']);
if (!$merchantGroup) {
return $this->fail('商户分组不存在', 404);
}
return $this->success($merchantGroup);
}
/**
* POST /admin/merchant-groups
*
* 新增商户分组。
*/
public function store(Request $request): Response
{
$data = $this->validated($request->all(), MerchantGroupValidator::class, 'store');
return $this->success($this->merchantGroupService->create($data));
}
/**
* PUT /admin/merchant-groups/{id}
*
* 修改商户分组。
*/
public function update(Request $request, string $id): Response
{
$data = $this->validated(
array_merge($request->all(), ['id' => (int) $id]),
MerchantGroupValidator::class,
'update'
);
$merchantGroup = $this->merchantGroupService->update((int) $data['id'], $data);
if (!$merchantGroup) {
return $this->fail('商户分组不存在', 404);
}
return $this->success($merchantGroup);
}
/**
* DELETE /admin/merchant-groups/{id}
*
* 删除商户分组。
*/
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], MerchantGroupValidator::class, 'destroy');
if (!$this->merchantGroupService->delete((int) $data['id'])) {
return $this->fail('商户分组不存在', 404);
}
return $this->success(true);
}
/**
* 查询商户分组下拉选项。
*/
public function options(Request $request): Response
{
return $this->success($this->merchantGroupService->enabledOptions());
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace app\http\admin\controller\merchant;
use app\common\base\BaseController;
use app\http\admin\validation\MerchantPolicyValidator;
use app\service\merchant\policy\MerchantPolicyService;
use support\Request;
use support\Response;
/**
* 商户策略控制器。
*/
class MerchantPolicyController extends BaseController
{
public function __construct(
protected MerchantPolicyService $merchantPolicyService
) {
}
public function index(Request $request): Response
{
$data = $this->validated($request->all(), MerchantPolicyValidator::class, 'index');
return $this->page(
$this->merchantPolicyService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
public function show(Request $request, string $merchantId): Response
{
$data = $this->validated(['merchant_id' => (int) $merchantId], MerchantPolicyValidator::class, 'show');
return $this->success($this->merchantPolicyService->findByMerchantId((int) $data['merchant_id']));
}
public function store(Request $request): Response
{
$data = $this->validated($request->all(), MerchantPolicyValidator::class, 'store');
return $this->success($this->merchantPolicyService->saveByMerchantId((int) $data['merchant_id'], $data));
}
public function update(Request $request, string $merchantId): Response
{
$data = $this->validated(
array_merge($request->all(), ['merchant_id' => (int) $merchantId]),
MerchantPolicyValidator::class,
'update'
);
return $this->success($this->merchantPolicyService->saveByMerchantId((int) $data['merchant_id'], $data));
}
public function destroy(Request $request, string $merchantId): Response
{
$data = $this->validated(['merchant_id' => (int) $merchantId], MerchantPolicyValidator::class, 'show');
return $this->success($this->merchantPolicyService->deleteByMerchantId((int) $data['merchant_id']));
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace app\http\admin\controller\ops;
use app\common\base\BaseController;
use app\http\admin\validation\ChannelDailyStatValidator;
use app\service\ops\stat\ChannelDailyStatService;
use support\Request;
use support\Response;
/**
* 通道日统计控制器。
*/
class ChannelDailyStatController extends BaseController
{
/**
* 构造函数,注入通道日统计服务。
*/
public function __construct(
protected ChannelDailyStatService $channelDailyStatService
) {
}
/**
* 查询通道日统计列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), ChannelDailyStatValidator::class, 'index');
return $this->page(
$this->channelDailyStatService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* 查询通道日统计详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], ChannelDailyStatValidator::class, 'show');
$stat = $this->channelDailyStatService->findById((int) $data['id']);
if (!$stat) {
return $this->fail('通道日统计不存在', 404);
}
return $this->success($stat);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace app\http\admin\controller\ops;
use app\common\base\BaseController;
use app\http\admin\validation\ChannelNotifyLogValidator;
use app\service\ops\log\ChannelNotifyLogService;
use support\Request;
use support\Response;
/**
* 渠道通知日志控制器。
*/
class ChannelNotifyLogController extends BaseController
{
/**
* 构造函数,注入渠道通知日志服务。
*/
public function __construct(
protected ChannelNotifyLogService $channelNotifyLogService
) {
}
/**
* 查询渠道通知日志列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), ChannelNotifyLogValidator::class, 'index');
return $this->page(
$this->channelNotifyLogService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* 查询渠道通知日志详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], ChannelNotifyLogValidator::class, 'show');
$log = $this->channelNotifyLogService->findById((int) $data['id']);
if (!$log) {
return $this->fail('渠道通知日志不存在', 404);
}
return $this->success($log);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace app\http\admin\controller\ops;
use app\common\base\BaseController;
use app\http\admin\validation\PayCallbackLogValidator;
use app\service\ops\log\PayCallbackLogService;
use support\Request;
use support\Response;
/**
* 支付回调日志控制器。
*/
class PayCallbackLogController extends BaseController
{
/**
* 构造函数,注入支付回调日志服务。
*/
public function __construct(
protected PayCallbackLogService $payCallbackLogService
) {
}
/**
* 查询支付回调日志列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PayCallbackLogValidator::class, 'index');
return $this->page(
$this->payCallbackLogService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* 查询支付回调日志详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PayCallbackLogValidator::class, 'show');
$log = $this->payCallbackLogService->findById((int) $data['id']);
if (!$log) {
return $this->fail('支付回调日志不存在', 404);
}
return $this->success($log);
}
}

View File

@@ -0,0 +1,138 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\PaymentChannelValidator;
use app\service\payment\config\PaymentChannelService;
use support\Request;
use support\Response;
/**
* 支付通道管理控制器。
*
* 负责支付通道的列表、详情、新增、修改和删除。
*/
class PaymentChannelController extends BaseController
{
/**
* 构造函数,注入支付通道服务。
*/
public function __construct(
protected PaymentChannelService $paymentChannelService
) {
}
/**
* GET /admin/payment-channels
*
* 查询支付通道列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PaymentChannelValidator::class, 'index');
return $this->page(
$this->paymentChannelService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* GET /admin/payment-channels/{id}
*
* 查询支付通道详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentChannelValidator::class, 'show');
$paymentChannel = $this->paymentChannelService->findById((int) $data['id']);
if (!$paymentChannel) {
return $this->fail('支付通道不存在', 404);
}
return $this->success($paymentChannel);
}
/**
* POST /admin/payment-channels
*
* 新增支付通道。
*/
public function store(Request $request): Response
{
$data = $this->validated($request->all(), PaymentChannelValidator::class, 'store');
return $this->success($this->paymentChannelService->create($data));
}
/**
* PUT /admin/payment-channels/{id}
*
* 修改支付通道。
*/
public function update(Request $request, string $id): Response
{
$payload = $request->all();
$scene = array_diff(array_keys($payload), ['status']) === [] ? 'updateStatus' : 'update';
$data = $this->validated(
array_merge($payload, ['id' => (int) $id]),
PaymentChannelValidator::class,
$scene
);
$paymentChannel = $this->paymentChannelService->update((int) $data['id'], $data);
if (!$paymentChannel) {
return $this->fail('支付通道不存在', 404);
}
return $this->success($paymentChannel);
}
/**
* DELETE /admin/payment-channels/{id}
*
* 删除支付通道。
*/
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentChannelValidator::class, 'destroy');
if (!$this->paymentChannelService->delete((int) $data['id'])) {
return $this->fail('支付通道不存在', 404);
}
return $this->success(true);
}
/**
* 查询启用中的通道选项。
*/
public function options(Request $request): Response
{
return $this->success($this->paymentChannelService->enabledOptions());
}
/**
* 查询路由编排场景下的通道选项。
*/
public function routeOptions(Request $request): Response
{
return $this->success($this->paymentChannelService->routeOptions($request->all()));
}
/**
* 远程查询支付通道选择项。
*/
public function selectOptions(Request $request): Response
{
$page = max(1, (int) $request->input('page', 1));
$pageSize = min(50, max(1, (int) $request->input('page_size', 20)));
return $this->success($this->paymentChannelService->searchOptions($request->all(), $page, $pageSize));
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\PaymentPluginConfValidator;
use app\service\payment\config\PaymentPluginConfService;
use support\Request;
use support\Response;
/**
* 支付插件配置控制器。
*
* 负责插件公共配置的列表、详情、增删改和选项输出。
*/
class PaymentPluginConfController extends BaseController
{
public function __construct(
protected PaymentPluginConfService $paymentPluginConfService
) {
}
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPluginConfValidator::class, 'index');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = max(1, (int) ($data['page_size'] ?? 10));
return $this->page($this->paymentPluginConfService->paginate($data, $page, $pageSize));
}
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPluginConfValidator::class, 'show');
$pluginConf = $this->paymentPluginConfService->findById((int) $data['id']);
if (!$pluginConf) {
return $this->fail('插件配置不存在', 404);
}
return $this->success($pluginConf);
}
public function store(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPluginConfValidator::class, 'store');
return $this->success($this->paymentPluginConfService->create($data));
}
public function update(Request $request, string $id): Response
{
$data = $this->validated(
array_merge($request->all(), ['id' => (int) $id]),
PaymentPluginConfValidator::class,
'update'
);
$pluginConf = $this->paymentPluginConfService->update((int) $data['id'], $data);
if (!$pluginConf) {
return $this->fail('插件配置不存在', 404);
}
return $this->success($pluginConf);
}
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPluginConfValidator::class, 'destroy');
if (!$this->paymentPluginConfService->delete((int) $data['id'])) {
return $this->fail('插件配置不存在', 404);
}
return $this->success(true);
}
public function options(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPluginConfValidator::class, 'options');
return $this->success([
'configs' => $this->paymentPluginConfService->options((string) ($data['plugin_code'] ?? '')),
]);
}
/**
* 远程查询插件配置选项。
*/
public function selectOptions(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPluginConfValidator::class, 'selectOptions');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = min(50, max(1, (int) ($data['page_size'] ?? 20)));
return $this->success($this->paymentPluginConfService->searchOptions($data, $page, $pageSize));
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\PaymentPluginValidator;
use app\service\payment\config\PaymentPluginService;
use support\Request;
use support\Response;
/**
* 支付插件管理控制器。
*
* 负责插件字典的列表、详情、刷新同步和状态备注维护。
*/
class PaymentPluginController extends BaseController
{
/**
* 构造函数,注入支付插件服务。
*/
public function __construct(
protected PaymentPluginService $paymentPluginService
) {
}
/**
* 查询支付插件列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPluginValidator::class, 'index');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = max(1, (int) ($data['page_size'] ?? 10));
return $this->page($this->paymentPluginService->paginate($data, $page, $pageSize));
}
/**
* 查询支付插件详情。
*/
public function show(Request $request, string $code): Response
{
$data = $this->validated(['code' => $code], PaymentPluginValidator::class, 'show');
$paymentPlugin = $this->paymentPluginService->findByCode((string) $data['code']);
if (!$paymentPlugin) {
return $this->fail('支付插件不存在', 404);
}
return $this->success($paymentPlugin);
}
/**
* 修改支付插件。
*/
public function update(Request $request, string $code): Response
{
$payload = $request->all();
$scene = array_diff(array_keys($payload), ['status']) === [] ? 'updateStatus' : 'update';
$data = $this->validated(
array_merge($payload, ['code' => $code]),
PaymentPluginValidator::class,
$scene
);
$paymentPlugin = $this->paymentPluginService->update((string) $data['code'], $data);
if (!$paymentPlugin) {
return $this->fail('支付插件不存在', 404);
}
return $this->success($paymentPlugin);
}
/**
* 从插件目录刷新同步支付插件。
*/
public function refresh(Request $request): Response
{
return $this->success($this->paymentPluginService->refreshFromClasses());
}
/**
* 查询支付插件下拉选项。
*/
public function options(Request $request): Response
{
return $this->success([
'plugins' => $this->paymentPluginService->enabledOptions(),
]);
}
/**
* 远程查询支付插件选项。
*/
public function selectOptions(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPluginValidator::class, 'selectOptions');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = min(50, max(1, (int) ($data['page_size'] ?? 20)));
return $this->success($this->paymentPluginService->searchOptions($data, $page, $pageSize));
}
/**
* 查询通道配置场景下的插件选项。
*/
public function channelOptions(Request $request): Response
{
return $this->success([
'plugins' => $this->paymentPluginService->channelOptions(),
]);
}
/**
* 查询插件配置结构。
*/
public function schema(Request $request, string $code): Response
{
$data = $this->validated(['code' => $code], PaymentPluginValidator::class, 'show');
return $this->success($this->paymentPluginService->getSchema((string) $data['code']));
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\PaymentPollGroupBindValidator;
use app\service\payment\config\PaymentPollGroupBindService;
use support\Request;
use support\Response;
/**
* 商户分组路由绑定控制器。
*/
class PaymentPollGroupBindController extends BaseController
{
public function __construct(
protected PaymentPollGroupBindService $paymentPollGroupBindService
) {
}
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPollGroupBindValidator::class, 'index');
return $this->page(
$this->paymentPollGroupBindService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPollGroupBindValidator::class, 'show');
$row = $this->paymentPollGroupBindService->findById((int) $data['id']);
if (!$row) {
return $this->fail('商户分组路由绑定不存在', 404);
}
return $this->success($row);
}
public function store(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPollGroupBindValidator::class, 'store');
return $this->success($this->paymentPollGroupBindService->create($data));
}
public function update(Request $request, string $id): Response
{
$data = $this->validated(
array_merge($request->all(), ['id' => (int) $id]),
PaymentPollGroupBindValidator::class,
'update'
);
$row = $this->paymentPollGroupBindService->update((int) $data['id'], $data);
if (!$row) {
return $this->fail('商户分组路由绑定不存在', 404);
}
return $this->success($row);
}
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPollGroupBindValidator::class, 'destroy');
if (!$this->paymentPollGroupBindService->delete((int) $data['id'])) {
return $this->fail('商户分组路由绑定不存在', 404);
}
return $this->success(true);
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\PaymentPollGroupChannelValidator;
use app\service\payment\config\PaymentPollGroupChannelService;
use support\Request;
use support\Response;
/**
* 轮询组通道编排控制器。
*/
class PaymentPollGroupChannelController extends BaseController
{
public function __construct(
protected PaymentPollGroupChannelService $paymentPollGroupChannelService
) {
}
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPollGroupChannelValidator::class, 'index');
return $this->page(
$this->paymentPollGroupChannelService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPollGroupChannelValidator::class, 'show');
$row = $this->paymentPollGroupChannelService->findById((int) $data['id']);
if (!$row) {
return $this->fail('轮询组通道编排不存在', 404);
}
return $this->success($row);
}
public function store(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPollGroupChannelValidator::class, 'store');
return $this->success($this->paymentPollGroupChannelService->create($data));
}
public function update(Request $request, string $id): Response
{
$payload = $request->all();
$scene = array_diff(array_keys($payload), ['status']) === [] ? 'updateStatus' : 'update';
$data = $this->validated(
array_merge($payload, ['id' => (int) $id]),
PaymentPollGroupChannelValidator::class,
$scene
);
$row = $this->paymentPollGroupChannelService->update((int) $data['id'], $data);
if (!$row) {
return $this->fail('轮询组通道编排不存在', 404);
}
return $this->success($row);
}
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPollGroupChannelValidator::class, 'destroy');
if (!$this->paymentPollGroupChannelService->delete((int) $data['id'])) {
return $this->fail('轮询组通道编排不存在', 404);
}
return $this->success(true);
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\PaymentPollGroupValidator;
use app\service\payment\config\PaymentPollGroupService;
use support\Request;
use support\Response;
/**
* 支付轮询组管理控制器。
*
* 负责轮询组的列表、详情、新增、修改和删除。
*/
class PaymentPollGroupController extends BaseController
{
/**
* 构造函数,注入轮询组服务。
*/
public function __construct(
protected PaymentPollGroupService $paymentPollGroupService
) {
}
/**
* GET /admin/payment-poll-groups
*
* 查询轮询组列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPollGroupValidator::class, 'index');
return $this->page(
$this->paymentPollGroupService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* GET /admin/payment-poll-groups/{id}
*
* 查询轮询组详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPollGroupValidator::class, 'show');
$paymentPollGroup = $this->paymentPollGroupService->findById((int) $data['id']);
if (!$paymentPollGroup) {
return $this->fail('轮询组不存在', 404);
}
return $this->success($paymentPollGroup);
}
/**
* POST /admin/payment-poll-groups
*
* 新增轮询组。
*/
public function store(Request $request): Response
{
$data = $this->validated($request->all(), PaymentPollGroupValidator::class, 'store');
return $this->success($this->paymentPollGroupService->create($data));
}
/**
* PUT /admin/payment-poll-groups/{id}
*
* 修改轮询组。
*/
public function update(Request $request, string $id): Response
{
$payload = $request->all();
$scene = array_diff(array_keys($payload), ['status']) === [] ? 'updateStatus' : 'update';
$data = $this->validated(
array_merge($payload, ['id' => (int) $id]),
PaymentPollGroupValidator::class,
$scene
);
$paymentPollGroup = $this->paymentPollGroupService->update((int) $data['id'], $data);
if (!$paymentPollGroup) {
return $this->fail('轮询组不存在', 404);
}
return $this->success($paymentPollGroup);
}
/**
* DELETE /admin/payment-poll-groups/{id}
*
* 删除轮询组。
*/
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentPollGroupValidator::class, 'destroy');
if (!$this->paymentPollGroupService->delete((int) $data['id'])) {
return $this->fail('轮询组不存在', 404);
}
return $this->success(true);
}
/**
* 查询轮询组下拉选项。
*/
public function options(Request $request): Response
{
return $this->success($this->paymentPollGroupService->enabledOptions($request->all()));
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\PaymentTypeValidator;
use app\service\payment\config\PaymentTypeService;
use support\Request;
use support\Response;
/**
* 支付方式管理控制器。
*
* 负责支付方式字典的列表、详情、新增、修改、删除和选项输出。
*/
class PaymentTypeController extends BaseController
{
/**
* 构造函数,注入支付方式服务。
*/
public function __construct(
protected PaymentTypeService $paymentTypeService
) {
}
/**
* 查询支付方式列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PaymentTypeValidator::class, 'index');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = max(1, (int) ($data['page_size'] ?? 10));
return $this->page($this->paymentTypeService->paginate($data, $page, $pageSize));
}
/**
* 查询支付方式详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentTypeValidator::class, 'show');
$paymentType = $this->paymentTypeService->findById((int) $data['id']);
if (!$paymentType) {
return $this->fail('支付方式不存在', 404);
}
return $this->success($paymentType);
}
/**
* 新增支付方式。
*/
public function store(Request $request): Response
{
$data = $this->validated($request->all(), PaymentTypeValidator::class, 'store');
return $this->success($this->paymentTypeService->create($data));
}
/**
* 修改支付方式。
*/
public function update(Request $request, string $id): Response
{
$payload = $request->all();
$scene = array_diff(array_keys($payload), ['status']) === [] ? 'updateStatus' : 'update';
$data = $this->validated(
array_merge($payload, ['id' => (int) $id]),
PaymentTypeValidator::class,
$scene
);
$paymentType = $this->paymentTypeService->update((int) $data['id'], $data);
if (!$paymentType) {
return $this->fail('支付方式不存在', 404);
}
return $this->success($paymentType);
}
/**
* 删除支付方式。
*/
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], PaymentTypeValidator::class, 'destroy');
if (!$this->paymentTypeService->delete((int) $data['id'])) {
return $this->fail('支付方式不存在', 404);
}
return $this->success(true);
}
/**
* 查询支付方式下拉选项。
*/
public function options(Request $request): Response
{
return $this->success($this->paymentTypeService->enabledOptions());
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace app\http\admin\controller\payment;
use app\common\base\BaseController;
use app\http\admin\validation\RouteResolveValidator;
use app\service\payment\runtime\PaymentRouteService;
use support\Request;
use support\Response;
/**
* 管理后台路由预览控制器。
*
* 负责按商户分组、支付方式和金额条件解析可用通道。
*/
class RouteController extends BaseController
{
/**
* 构造函数,注入路由服务。
*/
public function __construct(
protected PaymentRouteService $paymentRouteService
) {
}
/**
* GET /admin/routes/resolve
*
* 解析路由结果。
*/
public function resolve(Request $request): Response
{
$data = $this->validated($request->all(), RouteResolveValidator::class, 'resolve');
return $this->success($this->paymentRouteService->resolveByMerchantGroup(
(int) $data['merchant_group_id'],
(int) $data['pay_type_id'],
(int) $data['pay_amount'],
$data
));
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace app\http\admin\controller\system;
use app\common\base\BaseController;
use app\http\admin\validation\AdminUserValidator;
use app\service\system\user\AdminUserService;
use support\Request;
use support\Response;
/**
* 管理员用户管理控制器。
*
* 负责管理员账号的列表、详情、新增、修改和删除。
*/
class AdminUserController extends BaseController
{
/**
* 构造函数,注入管理员用户服务。
*/
public function __construct(
protected AdminUserService $adminUserService
) {
}
/**
* GET /adminapi/admin-users
*
* 查询管理员用户列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), AdminUserValidator::class, 'index');
return $this->page(
$this->adminUserService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* GET /adminapi/admin-users/{id}
*
* 查询管理员用户详情。
*/
public function show(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], AdminUserValidator::class, 'show');
$adminUser = $this->adminUserService->findById((int) $data['id']);
if (!$adminUser) {
return $this->fail('管理员用户不存在', 404);
}
return $this->success($adminUser);
}
/**
* POST /adminapi/admin-users
*
* 新增管理员用户。
*/
public function store(Request $request): Response
{
$data = $this->validated($request->all(), AdminUserValidator::class, 'store');
return $this->success($this->adminUserService->create($data));
}
/**
* PUT /adminapi/admin-users/{id}
*
* 修改管理员用户。
*/
public function update(Request $request, string $id): Response
{
$data = $this->validated(
array_merge($request->all(), ['id' => (int) $id]),
AdminUserValidator::class,
'update'
);
$adminUser = $this->adminUserService->update((int) $data['id'], $data);
if (!$adminUser) {
return $this->fail('管理员用户不存在', 404);
}
return $this->success($adminUser);
}
/**
* DELETE /adminapi/admin-users/{id}
*
* 删除管理员用户。
*/
public function destroy(Request $request, string $id): Response
{
$data = $this->validated(['id' => (int) $id], AdminUserValidator::class, 'destroy');
$adminUser = $this->adminUserService->findById((int) $data['id']);
if (!$adminUser) {
return $this->fail('管理员用户不存在', 404);
}
if ((int) $adminUser->is_super === 1) {
return $this->fail('超级管理员不允许删除');
}
if ((int) $data['id'] === $this->currentAdminId($request)) {
return $this->fail('不允许删除当前登录用户');
}
if (!$this->adminUserService->delete((int) $data['id'])) {
return $this->fail('管理员用户删除失败');
}
return $this->success(true);
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace app\http\admin\controller\system;
use app\common\base\BaseController;
use app\http\admin\validation\AuthValidator;
use app\service\system\access\AdminAuthService;
use app\service\system\user\AdminUserService;
use support\Request;
use support\Response;
/**
* 管理员认证控制器。
*/
class AuthController extends BaseController
{
public function __construct(
protected AdminAuthService $adminAuthService,
protected AdminUserService $adminUserService
) {
}
public function login(Request $request): Response
{
$data = $this->validated($request->all(), AuthValidator::class, 'login');
return $this->success($this->adminAuthService->authenticateCredentials(
(string) $data['username'],
(string) $data['password'],
$request->getRealIp(),
$request->header('user-agent', '')
));
}
public function logout(Request $request): Response
{
$token = trim((string) ($request->header('authorization', '') ?: $request->header('x-admin-token', '')));
$token = preg_replace('/^Bearer\s+/i', '', $token) ?: $token;
if ($token === '') {
return $this->fail('未获取到登录令牌', 401);
}
$this->adminAuthService->revokeToken($token);
return $this->success(true);
}
/**
* 获取当前登录管理员的信息
*/
public function profile(Request $request): Response
{
$adminId = $this->currentAdminId($request);
if ($adminId <= 0) {
return $this->fail('未获取到当前管理员信息', 401);
}
return $this->success($this->adminUserService->profile(
$adminId,
(string) $this->requestAttribute($request, 'auth.admin_username', '')
));
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace app\http\admin\controller\system;
use app\common\base\BaseController;
use app\http\admin\validation\SystemConfigPageValidator;
use app\service\system\config\SystemConfigPageService;
use support\Request;
use support\Response;
class SystemConfigPageController extends BaseController
{
public function __construct(
protected SystemConfigPageService $systemConfigPageService
) {
}
public function index(Request $request): Response
{
return $this->success($this->systemConfigPageService->tabs());
}
public function show(Request $request, string $groupCode): Response
{
$data = $this->validated(['group_code' => $groupCode], SystemConfigPageValidator::class, 'show');
return $this->success($this->systemConfigPageService->detail((string) $data['group_code']));
}
public function store(Request $request, string $groupCode): Response
{
$data = $this->validated(
array_merge($this->payload($request), ['group_code' => $groupCode]),
SystemConfigPageValidator::class,
'store'
);
return $this->success(
$this->systemConfigPageService->save((string) $data['group_code'], (array) ($data['values'] ?? []))
);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace app\http\admin\controller\system;
use app\common\base\BaseController;
use app\service\bootstrap\SystemBootstrapService;
use support\Request;
use support\Response;
/**
* 管理后台系统数据控制器。
*/
class SystemController extends BaseController
{
public function __construct(
protected SystemBootstrapService $systemBootstrapService
) {
}
public function menuTree(Request $request): Response
{
return $this->success($this->systemBootstrapService->getMenuTree('admin'));
}
public function dictItems(Request $request): Response
{
return $this->success($this->systemBootstrapService->getDictItems((string) $request->get('code', '')));
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace app\http\admin\controller\trade;
use app\common\base\BaseController;
use app\http\admin\validation\PayOrderValidator;
use app\service\payment\order\PayOrderService;
use support\Request;
use support\Response;
/**
* 支付订单管理控制器。
*
* 当前先提供列表查询,后续可以继续扩展支付单详情、关闭、重试等管理操作。
*/
class PayOrderController extends BaseController
{
/**
* 构造函数,注入支付订单服务。
*/
public function __construct(
protected PayOrderService $payOrderService
) {
}
/**
* 查询支付订单列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), PayOrderValidator::class, 'index');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = max(1, (int) ($data['page_size'] ?? 10));
return $this->success($this->payOrderService->paginate($data, $page, $pageSize));
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace app\http\admin\controller\trade;
use app\common\base\BaseController;
use app\http\admin\validation\RefundActionValidator;
use app\http\admin\validation\RefundOrderValidator;
use app\service\payment\order\RefundService;
use support\Request;
use support\Response;
/**
* 退款订单管理控制器。
*/
class RefundOrderController extends BaseController
{
public function __construct(
protected RefundService $refundService
) {
}
/**
* 查询退款订单列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), RefundOrderValidator::class, 'index');
$page = max(1, (int) ($data['page'] ?? 1));
$pageSize = max(1, (int) ($data['page_size'] ?? 10));
return $this->success($this->refundService->paginate($data, $page, $pageSize));
}
/**
* 查询退款订单详情。
*/
public function show(Request $request, string $refundNo): Response
{
return $this->success($this->refundService->detail($refundNo));
}
/**
* 重试退款。
*/
public function retry(Request $request, string $refundNo): Response
{
$data = $this->validated(
array_merge($request->all(), ['refund_no' => $refundNo]),
RefundActionValidator::class,
'retry'
);
return $this->success($this->refundService->retryRefund($refundNo, $data));
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace app\http\admin\controller\trade;
use app\common\base\BaseController;
use app\exception\ResourceNotFoundException;
use app\http\admin\validation\SettlementOrderValidator;
use app\service\payment\settlement\SettlementOrderQueryService;
use support\Request;
use support\Response;
/**
* 清算订单控制器。
*/
class SettlementOrderController extends BaseController
{
/**
* 构造函数,注入清算订单服务。
*/
public function __construct(
protected SettlementOrderQueryService $settlementOrderQueryService
) {
}
/**
* 查询清算订单列表。
*/
public function index(Request $request): Response
{
$data = $this->validated($request->all(), SettlementOrderValidator::class, 'index');
return $this->page(
$this->settlementOrderQueryService->paginate(
$data,
(int) ($data['page'] ?? 1),
(int) ($data['page_size'] ?? 10)
)
);
}
/**
* 查询清算订单详情。
*/
public function show(Request $request, string $settleNo): Response
{
$data = $this->validated(['settle_no' => $settleNo], SettlementOrderValidator::class, 'show');
try {
return $this->success($this->settlementOrderQueryService->detail((string) $data['settle_no']));
} catch (ResourceNotFoundException) {
return $this->fail('清算订单不存在', 404);
}
}
}