chore: init saasshop repo + sql migrations runner + gitee go

This commit is contained in:
萝卜
2026-03-10 11:31:02 +00:00
commit 50f15cdea8
210 changed files with 29534 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;
class AuthController extends Controller
{
use ResolvesPlatformAdminContext;
public function showLogin(): View
{
return view('admin.auth.login');
}
public function login(Request $request): RedirectResponse
{
$data = $request->validate([
'email' => ['required', 'email'],
'password' => ['required', 'string'],
]);
$admin = Admin::query()->where('email', $data['email'])->first();
if (! $admin || ! Hash::check($data['password'], $admin->password)) {
return back()->withErrors(['email' => '账号或密码错误'])->withInput();
}
if (! $admin->isPlatformAdmin()) {
return back()->withErrors(['email' => '当前账号是商家管理员,请从商家后台入口登录'])->withInput();
}
$request->session()->put('admin_id', $admin->id);
$request->session()->put('admin_name', $admin->name);
$request->session()->put('admin_email', $admin->email);
$request->session()->put('admin_role', $admin->role);
$request->session()->put('admin_merchant_id', null);
$request->session()->put('admin_scope', $admin->platformLabel());
$admin->forceFill(['last_login_at' => now()])->save();
return redirect('/admin');
}
public function logout(Request $request): RedirectResponse
{
$request->session()->forget(['admin_id', 'admin_name', 'admin_email', 'admin_role', 'admin_merchant_id', 'admin_scope']);
return redirect('/admin/login');
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Order;
use App\Models\Product;
use App\Models\Merchant;
use App\Models\User;
use App\Support\CacheKeys;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;
class DashboardController extends Controller
{
use ResolvesPlatformAdminContext;
public function index(Request $request): View
{
$admin = $this->ensurePlatformAdmin($request);
$stats = Cache::remember(
CacheKeys::platformDashboardStats(),
now()->addMinutes(10),
fn () => [
'merchants' => Merchant::count(),
'admins' => Admin::count(),
'users' => User::count(),
'products' => Product::count(),
'orders' => Order::count(),
'active_merchants' => Merchant::query()->where('status', 'active')->count(),
'pending_orders' => Order::query()->where('status', 'pending')->count(),
]
);
return view('admin.dashboard', [
'adminName' => $admin->name,
'stats' => $stats,
'platformAdmin' => $admin,
'cacheMeta' => [
'store' => config('cache.default'),
'ttl' => '10m',
],
'platformOverview' => [
'system_role' => '总台管理',
'current_scope' => '总台运营方视角',
'merchant_mode' => '统一管理多个站点',
'channel_count' => 5,
'active_merchants' => $stats['active_merchants'],
'pending_orders' => $stats['pending_orders'],
],
]);
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Support\CacheKeys;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;
class MerchantController extends Controller
{
use ResolvesPlatformAdminContext;
public function index(Request $request): View
{
$this->ensurePlatformAdmin($request);
$page = max((int) $request->integer('page', 1), 1);
return view('admin.merchants.index', [
'merchants' => Cache::remember(
CacheKeys::platformMerchantsList($page),
now()->addMinutes(10),
fn () => Merchant::query()->latest()->paginate(10)->withQueryString()
),
'cacheMeta' => [
'store' => config('cache.default'),
'ttl' => '10m',
],
]);
}
public function store(Request $request): RedirectResponse
{
$data = $request->validate([
'name' => ['required', 'string'],
'slug' => ['required', 'string'],
'plan' => ['nullable', 'string'],
'status' => ['nullable', 'string'],
'contact_name' => ['nullable', 'string'],
'contact_phone' => ['nullable', 'string'],
'contact_email' => ['nullable', 'email'],
]);
Merchant::query()->create([
'name' => $data['name'],
'slug' => $data['slug'],
'plan' => $data['plan'] ?? 'basic',
'status' => $data['status'] ?? 'active',
'contact_name' => $data['contact_name'] ?? null,
'contact_phone' => $data['contact_phone'] ?? null,
'contact_email' => $data['contact_email'] ?? null,
'activated_at' => now(),
]);
$this->flushPlatformCaches();
return redirect('/admin/merchants')->with('success', '商家创建成功');
}
protected function flushPlatformCaches(): void
{
for ($page = 1; $page <= 5; $page++) {
Cache::forget(CacheKeys::platformMerchantsList($page));
}
Cache::forget(CacheKeys::platformDashboardStats());
Cache::forget(CacheKeys::platformChannelsOverview());
}
}

View File

@@ -0,0 +1,867 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Support\CacheKeys;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\View\View;
class OrderController extends Controller
{
use ResolvesPlatformAdminContext;
protected array $statuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled'];
public function index(Request $request): View
{
$this->ensurePlatformAdmin($request);
$page = max((int) $request->integer('page', 1), 1);
$filters = $this->filters($request);
$statusStatsFilters = $filters;
$statusStatsFilters['status'] = '';
if ($filters['has_validation_error'] ?? false) {
return view('admin.orders.index', [
'orders' => Order::query()->whereRaw('1 = 0')->paginate(10)->withQueryString(),
'statusStats' => $this->emptyStatusStats(),
'summaryStats' => $this->emptySummaryStats(),
'trendStats' => $this->emptyTrendStats(),
'operationsFocus' => $this->buildOperationsFocus($this->emptySummaryStats(), $filters),
'workbenchLinks' => $this->workbenchLinks(),
'filters' => $filters,
'filterOptions' => [
'statuses' => $this->statuses,
'paymentStatuses' => ['unpaid', 'paid', 'refunded', 'failed'],
'platforms' => ['pc', 'h5', 'wechat_mp', 'wechat_mini', 'app'],
'deviceTypes' => ['desktop', 'mobile', 'mini-program', 'mobile-webview', 'app-api'],
'paymentChannels' => ['wechat_pay', 'alipay'],
'timeRanges' => [
'all' => '全部时间',
'today' => '今天',
'last_7_days' => '近7天',
],
'sortOptions' => [
'latest' => '创建时间倒序',
'oldest' => '创建时间正序',
'pay_amount_desc' => '实付金额从高到低',
'pay_amount_asc' => '实付金额从低到高',
'product_amount_desc' => '商品金额从高到低',
'product_amount_asc' => '商品金额从低到高',
],
],
'cacheMeta' => [
'store' => config('cache.default'),
'ttl' => '10m',
],
'activeFilterSummary' => $this->buildActiveFilterSummary($filters),
'statusLabels' => $this->statusLabels(),
'paymentStatusLabels' => $this->paymentStatusLabels(),
'platformLabels' => $this->platformLabels(),
'deviceTypeLabels' => $this->deviceTypeLabels(),
'paymentChannelLabels' => $this->paymentChannelLabels(),
]);
}
$summaryStats = Cache::remember(
CacheKeys::platformOrdersSummary($statusStatsFilters),
now()->addMinutes(10),
fn () => $this->buildSummaryStats($this->applyFilters(Order::query(), $statusStatsFilters))
);
return view('admin.orders.index', [
'orders' => Cache::remember(
CacheKeys::platformOrdersList($page, $filters),
now()->addMinutes(10),
fn () => $this->applySorting($this->applyFilters(Order::query()->with('merchant'), $filters), $filters)
->paginate(10)
->withQueryString()
),
'statusStats' => Cache::remember(
CacheKeys::platformOrdersStatusStats($statusStatsFilters),
now()->addMinutes(10),
fn () => $this->buildStatusStats($this->applyFilters(Order::query(), $statusStatsFilters))
),
'summaryStats' => $summaryStats,
'operationsFocus' => $this->buildOperationsFocus($summaryStats, $filters),
'workbenchLinks' => $this->workbenchLinks(),
'trendStats' => Cache::remember(
CacheKeys::platformOrdersTrendSummary($statusStatsFilters),
now()->addMinutes(10),
fn () => $this->buildTrendStats($this->applyFilters(Order::query(), $statusStatsFilters))
),
'filters' => $filters,
'filterOptions' => [
'statuses' => $this->statuses,
'paymentStatuses' => ['unpaid', 'paid', 'refunded', 'failed'],
'platforms' => ['pc', 'h5', 'wechat_mp', 'wechat_mini', 'app'],
'deviceTypes' => ['desktop', 'mobile', 'mini-program', 'mobile-webview', 'app-api'],
'paymentChannels' => ['wechat_pay', 'alipay'],
'timeRanges' => [
'all' => '全部时间',
'today' => '今天',
'last_7_days' => '近7天',
],
'sortOptions' => [
'latest' => '创建时间倒序',
'oldest' => '创建时间正序',
'pay_amount_desc' => '实付金额从高到低',
'pay_amount_asc' => '实付金额从低到高',
'product_amount_desc' => '商品金额从高到低',
'product_amount_asc' => '商品金额从低到高',
],
],
'cacheMeta' => [
'store' => config('cache.default'),
'ttl' => '10m',
],
'activeFilterSummary' => $this->buildActiveFilterSummary($filters),
'statusLabels' => $this->statusLabels(),
'paymentStatusLabels' => $this->paymentStatusLabels(),
'platformLabels' => $this->platformLabels(),
'deviceTypeLabels' => $this->deviceTypeLabels(),
'paymentChannelLabels' => $this->paymentChannelLabels(),
]);
}
public function show(Request $request, int $id): View
{
$this->ensurePlatformAdmin($request);
return view('admin.orders.show', [
'order' => Order::query()->with(['merchant', 'items.product', 'user'])->findOrFail($id),
]);
}
public function export(Request $request): StreamedResponse|RedirectResponse
{
$this->ensurePlatformAdmin($request);
$filters = $this->filters($request);
if ($filters['has_validation_error'] ?? false) {
return redirect('/admin/orders?' . http_build_query($this->exportableFilters($filters)))
->withErrors($filters['validation_errors'] ?? ['订单筛选条件不合法,请先修正后再导出。']);
}
$fileName = 'platform_orders_' . now()->format('Ymd_His') . '.csv';
$exportSummary = $this->buildSummaryStats(
$this->applyFilters(Order::query(), $filters)
);
return response()->streamDownload(function () use ($filters, $exportSummary) {
$handle = fopen('php://output', 'w');
fwrite($handle, "\xEF\xBB\xBF");
foreach ($this->exportSummaryRows($filters, 'platform') as $summaryRow) {
fputcsv($handle, $summaryRow);
}
fputcsv($handle, ['导出订单数', $exportSummary['total_orders'] ?? 0]);
fputcsv($handle, ['导出实付总额', number_format((float) ($exportSummary['total_pay_amount'] ?? 0), 2, '.', '')]);
fputcsv($handle, ['导出平均客单价', number_format((float) ($exportSummary['average_order_amount'] ?? 0), 2, '.', '')]);
fputcsv($handle, ['导出已支付订单数', $exportSummary['paid_orders'] ?? 0]);
fputcsv($handle, ['导出支付失败订单', $exportSummary['failed_payment_orders'] ?? 0]);
fputcsv($handle, []);
fputcsv($handle, [
'ID',
'商家ID',
'商家名称',
'用户ID',
'订单号',
'订单状态',
'支付状态',
'平台',
'设备类型',
'支付渠道',
'买家姓名',
'买家手机',
'买家邮箱',
'商品金额',
'优惠金额',
'运费',
'实付金额',
'商品行数',
'商品件数',
'商品摘要',
'创建时间',
'支付时间',
'发货时间',
'完成时间',
'备注',
]);
foreach ($this->applySorting($this->applyFilters(Order::query()->with(['merchant', 'items']), $filters), $filters)->cursor() as $order) {
$itemCount = $order->items->count();
$totalQuantity = (int) $order->items->sum('quantity');
$itemSummary = $order->items
->map(fn ($item) => trim(($item->product_title ?? '商品') . ' x' . ((int) $item->quantity)))
->implode(' | ');
fputcsv($handle, [
$order->id,
$order->merchant_id,
$order->merchant?->name ?? '',
$order->user_id,
$order->order_no,
$this->statusLabel((string) $order->status),
$this->paymentStatusLabel((string) $order->payment_status),
$this->platformLabel((string) $order->platform),
$this->deviceTypeLabel((string) $order->device_type),
$this->paymentChannelLabel((string) $order->payment_channel),
$order->buyer_name,
$order->buyer_phone,
$order->buyer_email,
number_format((float) $order->product_amount, 2, '.', ''),
number_format((float) $order->discount_amount, 2, '.', ''),
number_format((float) $order->shipping_amount, 2, '.', ''),
number_format((float) $order->pay_amount, 2, '.', ''),
$itemCount,
$totalQuantity,
$itemSummary,
optional($order->created_at)?->format('Y-m-d H:i:s'),
optional($order->paid_at)?->format('Y-m-d H:i:s'),
optional($order->shipped_at)?->format('Y-m-d H:i:s'),
optional($order->completed_at)?->format('Y-m-d H:i:s'),
$order->remark,
]);
}
fclose($handle);
}, $fileName, [
'Content-Type' => 'text/csv; charset=UTF-8',
]);
}
public function updateStatus(Request $request, int $id): RedirectResponse
{
$data = $request->validate([
'status' => ['required', 'string'],
]);
$order = Order::query()->findOrFail($id);
$order->update(['status' => $data['status']]);
Cache::add(CacheKeys::platformOrdersVersion(), 1, now()->addDays(30));
Cache::increment(CacheKeys::platformOrdersVersion());
Cache::forget(CacheKeys::platformDashboardStats());
return redirect('/admin/orders')->with('success', '订单状态更新成功');
}
protected function filters(Request $request): array
{
$timeRange = trim((string) $request->string('time_range', 'all'));
$rawStartDate = trim((string) $request->string('start_date'));
$rawEndDate = trim((string) $request->string('end_date'));
$minPayAmount = trim((string) $request->string('min_pay_amount'));
$maxPayAmount = trim((string) $request->string('max_pay_amount'));
$validationErrors = [];
if ($timeRange === 'today') {
$startDate = now()->toDateString();
$endDate = now()->toDateString();
} elseif ($timeRange === 'last_7_days') {
$startDate = now()->subDays(6)->toDateString();
$endDate = now()->toDateString();
} else {
$timeRange = 'all';
$startDate = $rawStartDate;
$endDate = $rawEndDate;
}
if ($rawStartDate !== '' && ! $this->isValidDate($rawStartDate)) {
$validationErrors[] = '开始日期格式不正确,请使用 YYYY-MM-DD。';
}
if ($rawEndDate !== '' && ! $this->isValidDate($rawEndDate)) {
$validationErrors[] = '结束日期格式不正确,请使用 YYYY-MM-DD。';
}
if ($rawStartDate !== '' && $rawEndDate !== '' && $this->isValidDate($rawStartDate) && $this->isValidDate($rawEndDate) && $rawStartDate > $rawEndDate) {
$validationErrors[] = '开始日期不能晚于结束日期。';
}
if ($minPayAmount !== '' && ! is_numeric($minPayAmount)) {
$validationErrors[] = '最低实付金额必须为数字。';
}
if ($maxPayAmount !== '' && ! is_numeric($maxPayAmount)) {
$validationErrors[] = '最高实付金额必须为数字。';
}
if ($minPayAmount !== '' && $maxPayAmount !== '' && is_numeric($minPayAmount) && is_numeric($maxPayAmount) && (float) $minPayAmount > (float) $maxPayAmount) {
$validationErrors[] = '最低实付金额不能大于最高实付金额。';
}
return [
'status' => trim((string) $request->string('status')),
'payment_status' => trim((string) $request->string('payment_status')),
'platform' => trim((string) $request->string('platform')),
'device_type' => trim((string) $request->string('device_type')),
'payment_channel' => trim((string) $request->string('payment_channel')),
'keyword' => trim((string) $request->string('keyword')),
'start_date' => $startDate,
'end_date' => $endDate,
'min_pay_amount' => $minPayAmount,
'max_pay_amount' => $maxPayAmount,
'time_range' => $timeRange,
'sort' => trim((string) $request->string('sort', 'latest')),
'validation_errors' => $validationErrors,
'has_validation_error' => ! empty($validationErrors),
];
}
protected function applyFilters(Builder $query, array $filters): Builder
{
return $query
->when(($filters['status'] ?? '') !== '', fn ($builder) => $builder->where('status', $filters['status']))
->when(($filters['payment_status'] ?? '') !== '', fn ($builder) => $builder->where('payment_status', $filters['payment_status']))
->when(($filters['platform'] ?? '') !== '', fn ($builder) => $builder->where('platform', $filters['platform']))
->when(($filters['device_type'] ?? '') !== '', fn ($builder) => $builder->where('device_type', $filters['device_type']))
->when(($filters['payment_channel'] ?? '') !== '', fn ($builder) => $builder->where('payment_channel', $filters['payment_channel']))
->when(($filters['keyword'] ?? '') !== '', fn ($builder) => $builder->where(function ($subQuery) use ($filters) {
$subQuery->where('order_no', 'like', '%' . $filters['keyword'] . '%')
->orWhere('buyer_name', 'like', '%' . $filters['keyword'] . '%')
->orWhere('buyer_phone', 'like', '%' . $filters['keyword'] . '%')
->orWhere('buyer_email', 'like', '%' . $filters['keyword'] . '%');
}))
->when(($filters['start_date'] ?? '') !== '', fn ($builder) => $builder->whereDate('created_at', '>=', $filters['start_date']))
->when(($filters['end_date'] ?? '') !== '', fn ($builder) => $builder->whereDate('created_at', '<=', $filters['end_date']))
->when(($filters['min_pay_amount'] ?? '') !== '' && is_numeric($filters['min_pay_amount']), fn ($builder) => $builder->where('pay_amount', '>=', $filters['min_pay_amount']))
->when(($filters['max_pay_amount'] ?? '') !== '' && is_numeric($filters['max_pay_amount']), fn ($builder) => $builder->where('pay_amount', '<=', $filters['max_pay_amount']));
}
protected function buildStatusStats(Builder $query): array
{
$counts = (clone $query)
->selectRaw('status, COUNT(*) as aggregate')
->groupBy('status')
->pluck('aggregate', 'status');
$stats = ['all' => (int) $counts->sum()];
foreach ($this->statuses as $status) {
$stats[$status] = (int) ($counts[$status] ?? 0);
}
return $stats;
}
protected function applySorting(Builder $query, array $filters): Builder
{
return match ($filters['sort'] ?? 'latest') {
'oldest' => $query->orderBy('created_at')->orderBy('id'),
'pay_amount_desc' => $query->orderByDesc('pay_amount')->orderByDesc('id'),
'pay_amount_asc' => $query->orderBy('pay_amount')->orderByDesc('id'),
'product_amount_desc' => $query->orderByDesc('product_amount')->orderByDesc('id'),
'product_amount_asc' => $query->orderBy('product_amount')->orderByDesc('id'),
default => $query->latest(),
};
}
protected function buildSummaryStats(Builder $query): array
{
$summary = (clone $query)
->selectRaw('COUNT(*) as total_orders')
->selectRaw('COALESCE(SUM(pay_amount), 0) as total_pay_amount')
->selectRaw("SUM(CASE WHEN payment_status = 'unpaid' THEN pay_amount ELSE 0 END) as unpaid_pay_amount")
->selectRaw("SUM(CASE WHEN payment_status = 'paid' THEN pay_amount ELSE 0 END) as paid_pay_amount")
->selectRaw("SUM(CASE WHEN payment_status = 'paid' THEN 1 ELSE 0 END) as paid_orders")
->selectRaw("SUM(CASE WHEN payment_status = 'refunded' THEN 1 ELSE 0 END) as refunded_orders")
->selectRaw("SUM(CASE WHEN payment_status = 'failed' THEN 1 ELSE 0 END) as failed_payment_orders")
->selectRaw("SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as pending_shipment_orders")
->selectRaw("SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_orders")
->selectRaw("SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_orders")
->first();
$totalOrders = (int) ($summary->total_orders ?? 0);
$totalPayAmount = (float) ($summary->total_pay_amount ?? 0);
$paidOrders = (int) ($summary->paid_orders ?? 0);
$refundedOrders = (int) ($summary->refunded_orders ?? 0);
$completedOrders = (int) ($summary->completed_orders ?? 0);
$cancelledOrders = (int) ($summary->cancelled_orders ?? 0);
return [
'total_orders' => $totalOrders,
'total_pay_amount' => $totalPayAmount,
'unpaid_pay_amount' => (float) ($summary->unpaid_pay_amount ?? 0),
'paid_pay_amount' => (float) ($summary->paid_pay_amount ?? 0),
'paid_orders' => $paidOrders,
'refunded_orders' => $refundedOrders,
'failed_payment_orders' => (int) ($summary->failed_payment_orders ?? 0),
'pending_shipment_orders' => (int) ($summary->pending_shipment_orders ?? 0),
'completed_orders' => $completedOrders,
'cancelled_orders' => $cancelledOrders,
'average_order_amount' => $totalOrders > 0 ? round($totalPayAmount / $totalOrders, 2) : 0,
'payment_rate' => $totalOrders > 0 ? round(($paidOrders / $totalOrders) * 100, 2) : 0,
'refund_rate' => $paidOrders > 0 ? round(($refundedOrders / $paidOrders) * 100, 2) : 0,
'completion_rate' => $totalOrders > 0 ? round(($completedOrders / $totalOrders) * 100, 2) : 0,
'cancellation_rate' => $totalOrders > 0 ? round(($cancelledOrders / $totalOrders) * 100, 2) : 0,
];
}
protected function buildTrendStats(Builder $query): array
{
$todayStart = Carbon::today();
$tomorrowStart = (clone $todayStart)->copy()->addDay();
$last7DaysStart = (clone $todayStart)->copy()->subDays(6)->startOfDay();
$today = (clone $query)
->where('created_at', '>=', $todayStart)
->where('created_at', '<', $tomorrowStart)
->selectRaw('COUNT(*) as total_orders')
->selectRaw('COALESCE(SUM(CASE WHEN payment_status = \'paid\' THEN pay_amount ELSE 0 END), 0) as total_pay_amount')
->first();
$last7Days = (clone $query)
->where('created_at', '>=', $last7DaysStart)
->where('created_at', '<', $tomorrowStart)
->selectRaw('COUNT(*) as total_orders')
->selectRaw('COALESCE(SUM(CASE WHEN payment_status = \'paid\' THEN pay_amount ELSE 0 END), 0) as total_pay_amount')
->first();
return [
'today_orders' => (int) ($today->total_orders ?? 0),
'today_pay_amount' => (float) ($today->total_pay_amount ?? 0),
'last_7_days_orders' => (int) ($last7Days->total_orders ?? 0),
'last_7_days_pay_amount' => (float) ($last7Days->total_pay_amount ?? 0),
];
}
protected function emptyStatusStats(): array
{
$stats = ['all' => 0];
foreach ($this->statuses as $status) {
$stats[$status] = 0;
}
return $stats;
}
protected function emptySummaryStats(): array
{
return [
'total_orders' => 0,
'total_pay_amount' => 0,
'unpaid_pay_amount' => 0,
'paid_pay_amount' => 0,
'paid_orders' => 0,
'refunded_orders' => 0,
'failed_payment_orders' => 0,
'pending_shipment_orders' => 0,
'completed_orders' => 0,
'cancelled_orders' => 0,
'average_order_amount' => 0,
'payment_rate' => 0,
'refund_rate' => 0,
'completion_rate' => 0,
'cancellation_rate' => 0,
];
}
protected function emptyTrendStats(): array
{
return [
'today_orders' => 0,
'today_pay_amount' => 0,
'last_7_days_orders' => 0,
'last_7_days_pay_amount' => 0,
];
}
protected function isValidDate(string $value): bool
{
try {
$date = Carbon::createFromFormat('Y-m-d', $value);
} catch (\Throwable $exception) {
return false;
}
return $date && $date->format('Y-m-d') === $value;
}
protected function exportableFilters(array $filters): array
{
return array_filter([
'status' => $filters['status'] ?? '',
'payment_status' => $filters['payment_status'] ?? '',
'platform' => $filters['platform'] ?? '',
'device_type' => $filters['device_type'] ?? '',
'payment_channel' => $filters['payment_channel'] ?? '',
'keyword' => $filters['keyword'] ?? '',
'start_date' => $filters['start_date'] ?? '',
'end_date' => $filters['end_date'] ?? '',
'min_pay_amount' => $filters['min_pay_amount'] ?? '',
'max_pay_amount' => $filters['max_pay_amount'] ?? '',
'time_range' => $filters['time_range'] ?? '',
'sort' => $filters['sort'] ?? '',
], fn ($value) => $value !== null && $value !== '' && $value !== 'all' && $value !== 'latest');
}
protected function exportSummaryRows(array $filters, string $scope, ?int $merchantId = null): array
{
return [
['导出信息', $scope === 'platform' ? '总台订单导出' : '商家订单导出'],
['导出时间', now()->format('Y-m-d H:i:s')],
['商家ID', $merchantId ? (string) $merchantId : '全部商家'],
['订单状态', $this->statusLabel($filters['status'] ?? '')],
['支付状态', $this->paymentStatusLabel($filters['payment_status'] ?? '')],
['平台', $this->platformLabel($filters['platform'] ?? '')],
['设备类型', $this->displayFilterValue((string) ($filters['device_type'] ?? ''), $this->deviceTypeLabels())],
['支付渠道', $this->displayFilterValue((string) ($filters['payment_channel'] ?? ''), $this->paymentChannelLabels())],
['关键词', $this->displayTextValue($filters['keyword'] ?? '')],
['快捷时间范围', $this->displayFilterValue($filters['time_range'] ?? 'all', [
'all' => '全部时间',
'today' => '今天',
'last_7_days' => '近7天',
])],
['开始日期', $this->displayTextValue($filters['start_date'] ?? '')],
['结束日期', $this->displayTextValue($filters['end_date'] ?? '')],
['最低实付金额', $this->displayMoneyValue($filters['min_pay_amount'] ?? '')],
['最高实付金额', $this->displayMoneyValue($filters['max_pay_amount'] ?? '')],
['排序', $this->sortLabel($filters['sort'] ?? 'latest')],
];
}
protected function buildActiveFilterSummary(array $filters): array
{
return [
'关键词' => $this->displayTextValue($filters['keyword'] ?? '', '全部'),
'订单状态' => $this->statusLabel($filters['status'] ?? ''),
'支付状态' => $this->paymentStatusLabel($filters['payment_status'] ?? ''),
'平台' => $this->platformLabel($filters['platform'] ?? ''),
'设备类型' => $this->displayFilterValue((string) ($filters['device_type'] ?? ''), $this->deviceTypeLabels()),
'支付渠道' => $this->displayFilterValue((string) ($filters['payment_channel'] ?? ''), $this->paymentChannelLabels()),
'实付金额区间' => $this->formatMoneyRange($filters['min_pay_amount'] ?? '', $filters['max_pay_amount'] ?? ''),
'排序' => $this->sortLabel($filters['sort'] ?? 'latest'),
];
}
protected function statusLabels(): array
{
return [
'pending' => '待处理',
'paid' => '已支付',
'shipped' => '已发货',
'completed' => '已完成',
'cancelled' => '已取消',
];
}
protected function statusLabel(string $status): string
{
return $this->statusLabels()[$status] ?? '全部';
}
protected function paymentStatusLabels(): array
{
return [
'unpaid' => '未支付',
'paid' => '已支付',
'refunded' => '已退款',
'failed' => '支付失败',
];
}
protected function paymentStatusLabel(string $status): string
{
return $this->paymentStatusLabels()[$status] ?? '全部';
}
protected function platformLabels(): array
{
return [
'pc' => 'PC 端',
'h5' => 'H5',
'wechat_mp' => '微信公众号',
'wechat_mini' => '微信小程序',
'app' => 'APP 接口预留',
];
}
protected function platformLabel(string $platform): string
{
return $this->platformLabels()[$platform] ?? '全部';
}
protected function deviceTypeLabels(): array
{
return [
'desktop' => '桌面浏览器',
'mobile' => '移动浏览器',
'mini-program' => '小程序环境',
'mobile-webview' => '微信内网页',
'app-api' => 'APP 接口',
];
}
protected function deviceTypeLabel(string $deviceType): string
{
return $this->deviceTypeLabels()[$deviceType] ?? ($deviceType === '' ? '未设置' : $deviceType);
}
protected function paymentChannelLabels(): array
{
return [
'wechat_pay' => '微信支付',
'alipay' => '支付宝',
];
}
protected function paymentChannelLabel(string $paymentChannel): string
{
return $this->paymentChannelLabels()[$paymentChannel] ?? ($paymentChannel === '' ? '未设置' : $paymentChannel);
}
protected function sortLabel(string $sort): string
{
return match ($sort) {
'oldest' => '创建时间正序',
'pay_amount_desc' => '实付金额从高到低',
'pay_amount_asc' => '实付金额从低到高',
'product_amount_desc' => '商品金额从高到低',
'product_amount_asc' => '商品金额从低到高',
default => '创建时间倒序',
};
}
protected function formatMoneyRange(string $min, string $max): string
{
if ($min === '' && $max === '') {
return '全部';
}
$minLabel = $min !== '' && is_numeric($min) ? ('¥' . number_format((float) $min, 2, '.', '')) : '不限';
$maxLabel = $max !== '' && is_numeric($max) ? ('¥' . number_format((float) $max, 2, '.', '')) : '不限';
return $minLabel . ' ~ ' . $maxLabel;
}
protected function displayFilterValue(string $value, array $options): string
{
if ($value === '') {
return '全部';
}
return (string) ($options[$value] ?? $value);
}
protected function displayTextValue(string $value, string $default = '未设置'): string
{
return $value === '' ? $default : $value;
}
protected function displayMoneyValue(string $value): string
{
if ($value === '') {
return '全部';
}
return is_numeric($value) ? ('¥' . number_format((float) $value, 2, '.', '')) : $value;
}
protected function workbenchLinks(): array
{
return [
'paid_high_amount' => '/admin/orders?sort=pay_amount_desc&payment_status=paid',
'pending_latest' => '/admin/orders?sort=latest&payment_status=unpaid',
'failed_latest' => '/admin/orders?sort=latest&payment_status=failed',
'completed_latest' => '/admin/orders?sort=latest&status=completed',
'current' => '/admin/orders',
];
}
protected function buildOperationsFocus(array $summaryStats, array $filters): array
{
$pendingCount = (int) Order::query()->where('payment_status', 'unpaid')->count();
$failedCount = (int) Order::query()->where('payment_status', 'failed')->count();
$completedCount = (int) Order::query()->where('status', 'completed')->count();
$links = $this->workbenchLinks();
$currentQuery = http_build_query(array_filter($this->exportableFilters($filters), fn ($value) => $value !== null && $value !== '' && $value !== 'all' && $value !== 'latest'));
$currentUrl = $links['current'] . ($currentQuery !== '' ? ('?' . $currentQuery) : '');
$workbench = [
'高金额已支付' => $links['paid_high_amount'],
'待支付跟进' => $links['pending_latest'],
'支付失败排查' => $links['failed_latest'],
'最近完成订单' => $links['completed_latest'],
'返回当前筛选视图' => $currentUrl,
];
$signals = [
'待支付订单' => $pendingCount,
'支付失败订单' => $failedCount,
'已完成订单' => $completedCount,
];
if (($filters['platform'] ?? '') === 'wechat_mini') {
return [
'headline' => '当前筛选已聚焦微信小程序订单,建议优先关注下单到支付转化是否顺畅,并同步排查小程序端支付回流体验。',
'actions' => [
['label' => '继续查看微信小程序订单', 'url' => $currentUrl],
['label' => '去看待支付订单', 'url' => $links['pending_latest']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['payment_channel'] ?? '') === 'wechat_pay') {
return [
'headline' => '当前筛选已聚焦微信支付订单,建议优先核对支付成功率、回调稳定性与失败重试转化。',
'actions' => [
['label' => '继续查看微信支付订单', 'url' => $currentUrl],
['label' => '去看支付失败订单', 'url' => $links['failed_latest']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['device_type'] ?? '') === 'mini-program') {
return [
'headline' => '当前筛选已聚焦小程序环境订单,建议优先核对授权链路、支付唤起表现与下单回流是否顺畅。',
'actions' => [
['label' => '继续查看小程序环境订单', 'url' => $currentUrl],
['label' => '去看微信支付订单', 'url' => $links['failed_latest']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['device_type'] ?? '') === 'mobile-webview') {
return [
'headline' => '当前筛选已聚焦微信内网页订单,建议优先关注授权静默登录、页面跳转稳定性与支付拉起后的回流体验。',
'actions' => [
['label' => '继续查看微信内网页订单', 'url' => $currentUrl],
['label' => '去看待支付订单', 'url' => $links['pending_latest']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['device_type'] ?? '') === 'mobile') {
return [
'headline' => '当前筛选已聚焦移动浏览器订单,建议优先关注 H5 下单链路、页面加载稳定性与支付转化流失点。',
'actions' => [
['label' => '继续查看移动浏览器订单', 'url' => $currentUrl],
['label' => '去看待支付订单', 'url' => $links['pending_latest']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['device_type'] ?? '') === 'desktop') {
return [
'headline' => '当前筛选已聚焦桌面浏览器订单,建议优先关注 PC 端下单流程、页面首屏稳定性与高客单转化表现。',
'actions' => [
['label' => '继续查看桌面浏览器订单', 'url' => $currentUrl],
['label' => '去看高金额已支付订单', 'url' => $links['paid_high_amount']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['payment_status'] ?? '') === 'failed') {
return [
'headline' => '当前筛选已聚焦支付失败订单,建议优先排查支付渠道、回调结果与用户重试情况。',
'actions' => [
['label' => '继续查看支付失败订单', 'url' => $currentUrl],
['label' => '去看高金额已支付订单', 'url' => $links['paid_high_amount']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['payment_status'] ?? '') === 'unpaid') {
return [
'headline' => '当前筛选已聚焦待支付订单,建议优先跟进下单未支付用户,并观察支付转化时效。',
'actions' => [
['label' => '继续查看待支付订单', 'url' => $currentUrl],
['label' => '去看高金额已支付订单', 'url' => $links['paid_high_amount']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['payment_status'] ?? '') === 'paid') {
return [
'headline' => '当前正在查看已支付订单,建议优先关注高金额订单履约进度与异常售后风险。',
'actions' => [
['label' => '继续查看已支付订单', 'url' => $currentUrl],
['label' => '去看最近完成订单', 'url' => $links['completed_latest']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($filters['status'] ?? '') === 'completed') {
return [
'headline' => '当前正在查看已完成订单,建议复盘高客单成交与复购来源,沉淀更稳定的转化路径。',
'actions' => [
['label' => '继续查看已完成订单', 'url' => $currentUrl],
['label' => '去看高金额已支付订单', 'url' => $links['paid_high_amount']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($summaryStats['total_orders'] ?? 0) <= 0) {
return [
'headline' => '当前总台视角下暂无订单,建议先确认交易链路、支付链路与站点回写链路是否都已打通。',
'actions' => [
['label' => '先看订单整体情况', 'url' => $links['paid_high_amount']],
['label' => '去看待支付订单', 'url' => $links['pending_latest']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
if (($summaryStats['total_orders'] ?? 0) < 5) {
return [
'headline' => '当前总台订单仍较少,建议优先关注待支付订单,并同步查看已支付订单质量。',
'actions' => [
['label' => '去看待支付订单', 'url' => $links['pending_latest']],
['label' => '去看已支付订单', 'url' => $links['paid_high_amount']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
return [
'headline' => $failedCount > 0
? '当前总台订单已形成基础规模,建议优先关注待支付、支付失败与高金额已支付订单。'
: '当前总台订单已形成基础规模,建议优先关注待支付与高金额已支付订单,保持交易闭环稳定。',
'actions' => $failedCount > 0
? [
['label' => '去看待支付订单', 'url' => $links['pending_latest']],
['label' => '去看支付失败订单', 'url' => $links['failed_latest']],
]
: [
['label' => '去看待支付订单', 'url' => $links['pending_latest']],
['label' => '去看高金额已支付订单', 'url' => $links['paid_high_amount']],
],
'workbench' => $workbench,
'signals' => $signals,
];
}
}

View File

@@ -0,0 +1,249 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\Plan;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PlanController extends Controller
{
use ResolvesPlatformAdminContext;
public function export(Request $request): StreamedResponse
{
$this->ensurePlatformAdmin($request);
$filters = [
'status' => trim((string) $request->query('status', '')),
'billing_cycle' => trim((string) $request->query('billing_cycle', '')),
'keyword' => trim((string) $request->query('keyword', '')),
'published' => trim((string) $request->query('published', '')),
];
$query = $this->applyFilters(Plan::query(), $filters)
->orderBy('sort')
->orderByDesc('id');
$filename = 'plans_' . now()->format('Ymd_His') . '.csv';
return response()->streamDownload(function () use ($query) {
$out = fopen('php://output', 'w');
// UTF-8 BOM避免 Excel 打开中文乱码
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, [
'ID',
'套餐名称',
'编码',
'计费周期',
'售价',
'划线价',
'状态',
'排序',
'发布时间',
'描述',
]);
$query->chunkById(500, function ($plans) use ($out) {
foreach ($plans as $plan) {
fputcsv($out, [
$plan->id,
$plan->name,
$plan->code,
$plan->billing_cycle,
(float) $plan->price,
(float) $plan->list_price,
$plan->status,
(int) $plan->sort,
optional($plan->published_at)->format('Y-m-d H:i:s') ?: '',
$plan->description ?: '',
]);
}
});
fclose($out);
}, $filename, [
'Content-Type' => 'text/csv; charset=UTF-8',
]);
}
public function index(Request $request): View
{
$this->ensurePlatformAdmin($request);
$filters = [
'status' => trim((string) $request->query('status', '')),
'billing_cycle' => trim((string) $request->query('billing_cycle', '')),
'keyword' => trim((string) $request->query('keyword', '')),
// 发布状态筛选(按 published_at 是否为空)
// - published已发布published_at not null
// - unpublished未发布published_at is null
'published' => trim((string) $request->query('published', '')),
];
$plansQuery = $this->applyFilters(Plan::query(), $filters);
$plans = (clone $plansQuery)
->orderBy('sort')
->orderByDesc('id')
->paginate(10)
->withQueryString();
return view('admin.plans.index', [
'plans' => $plans,
'filters' => $filters,
'filterOptions' => [
'statuses' => $this->statusLabels(),
'billingCycles' => $this->billingCycleLabels(),
],
'summaryStats' => [
'total_plans' => (clone $plansQuery)->count(),
'active_plans' => (clone $plansQuery)->where('status', 'active')->count(),
'monthly_plans' => (clone $plansQuery)->where('billing_cycle', 'monthly')->count(),
'yearly_plans' => (clone $plansQuery)->where('billing_cycle', 'yearly')->count(),
'published_plans' => (clone $plansQuery)->whereNotNull('published_at')->count(),
'unpublished_plans' => (clone $plansQuery)->whereNull('published_at')->count(),
],
'statusLabels' => $this->statusLabels(),
'billingCycleLabels' => $this->billingCycleLabels(),
]);
}
public function create(Request $request): View
{
$this->ensurePlatformAdmin($request);
return view('admin.plans.form', [
'plan' => new Plan(),
'statusLabels' => $this->statusLabels(),
'billingCycleLabels' => $this->billingCycleLabels(),
'formAction' => '/admin/plans',
'method' => 'post',
]);
}
public function store(Request $request): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$data = $this->validatePlan($request);
$plan = Plan::query()->create($data);
return redirect('/admin/plans')->with('success', '套餐已创建:' . $plan->name);
}
public function edit(Request $request, Plan $plan): View
{
$this->ensurePlatformAdmin($request);
return view('admin.plans.form', [
'plan' => $plan,
'statusLabels' => $this->statusLabels(),
'billingCycleLabels' => $this->billingCycleLabels(),
'formAction' => '/admin/plans/' . $plan->id,
'method' => 'post',
]);
}
public function setStatus(Request $request, Plan $plan): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$data = $request->validate([
'status' => ['required', Rule::in(array_keys($this->statusLabels()))],
]);
$plan->status = (string) $data['status'];
// 最小治理:当启用且未设置发布时间时,自动补一个发布时间(便于运营口径)
if ($plan->status === 'active' && $plan->published_at === null) {
$plan->published_at = now();
}
$plan->save();
return redirect()->back()->with('success', '套餐状态已更新:' . ($this->statusLabels()[$plan->status] ?? $plan->status));
}
public function update(Request $request, Plan $plan): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$data = $this->validatePlan($request, $plan->id);
$plan->update($data);
return redirect('/admin/plans')->with('success', '套餐已更新:' . $plan->name);
}
protected function validatePlan(Request $request, ?int $planId = null): array
{
$data = $request->validate([
'code' => ['required', 'string', 'max:50', 'regex:/^[A-Za-z0-9-_]+$/', Rule::unique('plans', 'code')->ignore($planId)],
'name' => ['required', 'string', 'max:100'],
'billing_cycle' => ['required', Rule::in(array_keys($this->billingCycleLabels()))],
'price' => ['required', 'numeric', 'min:0'],
'list_price' => ['nullable', 'numeric', 'min:0'],
'status' => ['required', Rule::in(array_keys($this->statusLabels()))],
'sort' => ['nullable', 'integer', 'min:0'],
'description' => ['nullable', 'string'],
'published_at' => ['nullable', 'date'],
], [
'code.regex' => '套餐编码仅支持字母、数字、短横线与下划线。',
]);
$data['sort'] = $data['sort'] ?? 0;
return $data;
}
protected function applyFilters(Builder $query, array $filters): Builder
{
return $query
->when($filters['status'] !== '', fn (Builder $builder) => $builder->where('status', $filters['status']))
->when($filters['billing_cycle'] !== '', fn (Builder $builder) => $builder->where('billing_cycle', $filters['billing_cycle']))
->when(($filters['published'] ?? '') !== '', function (Builder $builder) use ($filters) {
$published = (string) ($filters['published'] ?? '');
if ($published === 'published') {
$builder->whereNotNull('published_at');
} elseif ($published === 'unpublished') {
$builder->whereNull('published_at');
}
})
->when($filters['keyword'] !== '', function (Builder $builder) use ($filters) {
$keyword = $filters['keyword'];
$builder->where(function (Builder $subQuery) use ($keyword) {
$subQuery->where('name', 'like', '%' . $keyword . '%')
->orWhere('code', 'like', '%' . $keyword . '%')
->orWhere('description', 'like', '%' . $keyword . '%');
});
});
}
protected function statusLabels(): array
{
return [
'active' => '启用中',
'draft' => '草稿中',
'inactive' => '未启用',
];
}
protected function billingCycleLabels(): array
{
return [
'monthly' => '月付',
'quarterly' => '季付',
'yearly' => '年付',
'one_time' => '一次性',
];
}
}

View File

@@ -0,0 +1,556 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\PlatformOrder;
use App\Support\SubscriptionActivationService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PlatformOrderController extends Controller
{
use ResolvesPlatformAdminContext;
public function index(Request $request): View
{
$this->ensurePlatformAdmin($request);
$filters = [
'status' => trim((string) $request->query('status', '')),
'payment_status' => trim((string) $request->query('payment_status', '')),
'merchant_id' => trim((string) $request->query('merchant_id', '')),
'plan_id' => trim((string) $request->query('plan_id', '')),
'fail_only' => (string) $request->query('fail_only', ''),
'synced_only' => (string) $request->query('synced_only', ''),
'sync_status' => trim((string) $request->query('sync_status', '')),
// 只看“可同步订阅”的订单:已支付 + 已生效 + 未同步(用于运营快速处理)
'syncable_only' => (string) $request->query('syncable_only', ''),
// 只看最近 24 小时批量同步过的订单(可治理追踪)
'batch_synced_24h' => (string) $request->query('batch_synced_24h', ''),
];
$orders = $this->applyFilters(PlatformOrder::query()->with(['merchant', 'plan', 'siteSubscription']), $filters)
->latest('id')
->paginate(10)
->withQueryString();
$baseQuery = $this->applyFilters(PlatformOrder::query(), $filters);
// 同步失败原因聚合Top 5用于运营快速判断“常见失败原因”
// 注意:这里用 JSON_EXTRACT 做 group byMySQL 会返回带引号的 JSON 字符串,展示时做一次 trim 处理。
$failedReasonRows = (clone $baseQuery)
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NOT NULL")
->selectRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') as reason, count(*) as cnt")
->groupBy('reason')
->orderByDesc('cnt')
->limit(5)
->get();
$failedReasonStats = $failedReasonRows->map(function ($row) {
$reason = (string) ($row->reason ?? '');
$reason = trim($reason, "\" ");
return [
'reason' => $reason !== '' ? $reason : '(空)',
'count' => (int) ($row->cnt ?? 0),
];
})->values()->all();
return view('admin.platform_orders.index', [
'orders' => $orders,
'filters' => $filters,
'filterOptions' => [
'statuses' => $this->statusLabels(),
'paymentStatuses' => $this->paymentStatusLabels(),
],
'merchants' => PlatformOrder::query()->with('merchant')
->select('merchant_id')
->whereNotNull('merchant_id')
->distinct()
->get()
->pluck('merchant')
->filter()
->unique('id')
->values(),
'plans' => PlatformOrder::query()->with('plan')
->select('plan_id')
->whereNotNull('plan_id')
->distinct()
->get()
->pluck('plan')
->filter()
->unique('id')
->values(),
'statusLabels' => $this->statusLabels(),
'paymentStatusLabels' => $this->paymentStatusLabels(),
'summaryStats' => [
'total_orders' => (clone $baseQuery)->count(),
'paid_orders' => (clone $baseQuery)->where('payment_status', 'paid')->count(),
'activated_orders' => (clone $baseQuery)->where('status', 'activated')->count(),
'synced_orders' => (clone $baseQuery)
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation.subscription_id') IS NOT NULL")
->count(),
'failed_sync_orders' => (clone $baseQuery)
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NOT NULL")
->count(),
'unsynced_orders' => (clone $baseQuery)
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation.subscription_id') IS NULL")
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NULL")
->count(),
'total_payable_amount' => (float) ((clone $baseQuery)->sum('payable_amount') ?: 0),
'total_paid_amount' => (float) ((clone $baseQuery)->sum('paid_amount') ?: 0),
],
'failedReasonStats' => $failedReasonStats,
]);
}
public function show(Request $request, PlatformOrder $order): View
{
$this->ensurePlatformAdmin($request);
$order->loadMissing(['merchant', 'plan', 'siteSubscription']);
return view('admin.platform_orders.show', [
'order' => $order,
'statusLabels' => $this->statusLabels(),
'paymentStatusLabels' => $this->paymentStatusLabels(),
]);
}
public function activateSubscription(Request $request, PlatformOrder $order, SubscriptionActivationService $service): RedirectResponse
{
$admin = $this->ensurePlatformAdmin($request);
try {
$subscription = $service->activateOrder($order->id, $admin->id);
// 同步成功:清理失败记录(若存在)
$meta = (array) ($order->meta ?? []);
data_forget($meta, 'subscription_activation_error');
$order->meta = $meta;
$order->save();
} catch (\Throwable $e) {
// 同步失败:写入错误信息,便于运营排查(可治理)
$meta = (array) ($order->meta ?? []);
data_set($meta, 'subscription_activation_error', [
'message' => $e->getMessage(),
'at' => now()->toDateTimeString(),
'admin_id' => $admin->id,
]);
$order->meta = $meta;
$order->save();
return redirect()->back()->with('error', '订阅同步失败:' . $e->getMessage());
}
return redirect()->back()->with('success', '订阅已同步:' . $subscription->subscription_no);
}
public function markPaidAndActivate(Request $request, PlatformOrder $order, SubscriptionActivationService $service): RedirectResponse
{
$admin = $this->ensurePlatformAdmin($request);
// 最小状态推进:将订单标记为已支付 + 已生效,并补齐时间与金额字段
$now = now();
$order->payment_status = 'paid';
$order->status = 'activated';
$order->paid_at = $order->paid_at ?: $now;
$order->activated_at = $order->activated_at ?: $now;
$order->paid_amount = $order->paid_amount > 0 ? $order->paid_amount : $order->payable_amount;
$order->save();
// 立刻同步订阅
try {
$subscription = $service->activateOrder($order->id, $admin->id);
$meta = (array) ($order->meta ?? []);
data_forget($meta, 'subscription_activation_error');
$order->meta = $meta;
$order->save();
} catch (\Throwable $e) {
$meta = (array) ($order->meta ?? []);
data_set($meta, 'subscription_activation_error', [
'message' => $e->getMessage(),
'at' => now()->toDateTimeString(),
'admin_id' => $admin->id,
]);
$order->meta = $meta;
$order->save();
return redirect()->back()->with('error', '订单已标记为已支付/已生效,但订阅同步失败:' . $e->getMessage());
}
return redirect()->back()->with('success', '订单已标记支付并生效,订阅已同步:' . $subscription->subscription_no);
}
public function export(Request $request): StreamedResponse
{
$this->ensurePlatformAdmin($request);
$filters = [
'status' => trim((string) $request->query('status', '')),
'payment_status' => trim((string) $request->query('payment_status', '')),
'merchant_id' => trim((string) $request->query('merchant_id', '')),
'plan_id' => trim((string) $request->query('plan_id', '')),
'fail_only' => (string) $request->query('fail_only', ''),
'synced_only' => (string) $request->query('synced_only', ''),
'sync_status' => trim((string) $request->query('sync_status', '')),
// 只看“可同步订阅”的订单:已支付 + 已生效 + 未同步(用于运营快速处理)
'syncable_only' => (string) $request->query('syncable_only', ''),
// 只看最近 24 小时批量同步过的订单(可治理追踪)
'batch_synced_24h' => (string) $request->query('batch_synced_24h', ''),
];
$includeMeta = (string) $request->query('include_meta', '') === '1';
$query = $this->applyFilters(
PlatformOrder::query()->with(['merchant', 'plan', 'siteSubscription']),
$filters
)->orderBy('id');
$filename = 'platform_orders_' . now()->format('Ymd_His') . '.csv';
return response()->streamDownload(function () use ($query, $includeMeta) {
$out = fopen('php://output', 'w');
// UTF-8 BOM避免 Excel 打开中文乱码
fwrite($out, "\xEF\xBB\xBF");
$headers = [
'ID',
'订单号',
'站点',
'套餐',
'订单类型',
'订单状态',
'支付状态',
'应付金额',
'已付金额',
'下单时间',
'支付时间',
'生效时间',
'同步状态',
'订阅号',
'订阅到期',
'同步时间',
'同步失败原因',
'同步失败时间',
];
if ($includeMeta) {
$headers[] = '原始meta(JSON)';
}
fputcsv($out, $headers);
$query->chunkById(500, function ($orders) use ($out, $includeMeta) {
foreach ($orders as $order) {
$syncedId = (int) data_get($order->meta, 'subscription_activation.subscription_id', 0);
$syncErr = (string) (data_get($order->meta, 'subscription_activation_error.message') ?? '');
if ($syncedId > 0) {
$syncStatus = '已同步';
} elseif ($syncErr !== '') {
$syncStatus = '同步失败';
} else {
$syncStatus = '未同步';
}
$row = [
$order->id,
$order->order_no,
$order->merchant?->name ?? '',
$order->plan_name ?: ($order->plan?->name ?? ''),
$order->order_type,
$order->status,
$order->payment_status,
(float) $order->payable_amount,
(float) $order->paid_amount,
optional($order->placed_at)->format('Y-m-d H:i:s') ?: '',
optional($order->paid_at)->format('Y-m-d H:i:s') ?: '',
optional($order->activated_at)->format('Y-m-d H:i:s') ?: '',
$syncStatus,
$order->siteSubscription?->subscription_no ?: '',
optional($order->siteSubscription?->ends_at)->format('Y-m-d H:i:s') ?: '',
(string) (data_get($order->meta, 'subscription_activation.synced_at') ?? ''),
$syncErr,
(string) (data_get($order->meta, 'subscription_activation_error.at') ?? ''),
];
if ($includeMeta) {
$row[] = json_encode($order->meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
fputcsv($out, $row);
}
});
fclose($out);
}, $filename, [
'Content-Type' => 'text/csv; charset=UTF-8',
]);
}
public function batchActivateSubscriptions(Request $request, SubscriptionActivationService $service): RedirectResponse
{
$admin = $this->ensurePlatformAdmin($request);
// 支持两种 scope
// - scope=filtered只处理当前筛选范围内的订单更安全默认
// - scope=all处理全部订单谨慎
$scope = (string) $request->input('scope', 'filtered');
$filters = [
'status' => trim((string) $request->input('status', '')),
'payment_status' => trim((string) $request->input('payment_status', '')),
'merchant_id' => trim((string) $request->input('merchant_id', '')),
'plan_id' => trim((string) $request->input('plan_id', '')),
'fail_only' => (string) $request->input('fail_only', ''),
'synced_only' => (string) $request->input('synced_only', ''),
'sync_status' => trim((string) $request->input('sync_status', '')),
'syncable_only' => (string) $request->input('syncable_only', ''),
'batch_synced_24h' => (string) $request->input('batch_synced_24h', ''),
];
// 防误操作:批量同步默认要求先勾选“只看可同步”,避免无意识扩大处理范围
if ($scope === 'filtered' && ($filters['syncable_only'] ?? '') !== '1') {
return redirect()->back()->with('warning', '为避免误操作,请先在筛选条件中勾选「只看可同步」,再执行批量同步订阅。');
}
// 防误操作scope=all 需要二次确认
if ($scope === 'all' && (string) $request->input('confirm', '') !== 'YES') {
return redirect()->back()->with('warning', '为避免误操作,执行全量批量同步前请在确认框输入 YES。');
}
$query = PlatformOrder::query();
if ($scope === 'filtered') {
$query = $this->applyFilters($query, $filters);
}
// 只处理“可同步”的订单(双保险,避免误操作)
$query = $query
->where('payment_status', 'paid')
->where('status', 'activated')
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation.subscription_id') IS NULL");
$limit = (int) $request->input('limit', 50);
$limit = max(1, min(500, $limit));
$matchedTotal = (clone $query)->count();
// 默认按最新订单优先处理:避免 seed/demo 数据干扰测试,同时也更符合“先处理新问题”的运营直觉
$orders = $query->orderByDesc('id')->limit($limit)->get(['id']);
$processed = $orders->count();
$success = 0;
$failed = 0;
$failedReasonCounts = [];
foreach ($orders as $orderRow) {
try {
$service->activateOrder($orderRow->id, $admin->id);
// 轻量审计:记录批量同步动作(方便追溯)
$order = PlatformOrder::query()->find($orderRow->id);
if ($order) {
$meta = (array) ($order->meta ?? []);
$audit = (array) (data_get($meta, 'audit', []) ?? []);
$nowStr = now()->toDateTimeString();
$audit[] = [
'action' => 'batch_activate_subscription',
'scope' => $scope,
'at' => $nowStr,
'admin_id' => $admin->id,
];
data_set($meta, 'audit', $audit);
// 便于筛选/统计:记录最近一次批量同步信息(扁平字段)
data_set($meta, 'batch_activation', [
'at' => $nowStr,
'admin_id' => $admin->id,
'scope' => $scope,
]);
$order->meta = $meta;
$order->save();
}
$success++;
} catch (\Throwable $e) {
$failed++;
$reason = trim((string) $e->getMessage());
$reason = $reason !== '' ? $reason : '未知错误';
$failedReasonCounts[$reason] = ($failedReasonCounts[$reason] ?? 0) + 1;
// 批量同步失败也需要可治理:写入失败原因到订单 meta便于后续筛选/导出/清理
$order = PlatformOrder::query()->find($orderRow->id);
if ($order) {
$meta = (array) ($order->meta ?? []);
data_set($meta, 'subscription_activation_error', [
'message' => $reason,
'at' => now()->toDateTimeString(),
'admin_id' => $admin->id,
]);
$order->meta = $meta;
$order->save();
}
}
}
$msg = '批量同步订阅完成:成功 ' . $success . ' 条,失败 ' . $failed . ' 条(命中 ' . $matchedTotal . ' 条,本次处理 ' . $processed . ' 条limit=' . $limit . '';
if ($failed > 0 && count($failedReasonCounts) > 0) {
arsort($failedReasonCounts);
$top = array_slice($failedReasonCounts, 0, 3, true);
$topText = collect($top)->map(function ($cnt, $reason) {
$reason = mb_substr((string) $reason, 0, 60);
return $reason . '' . $cnt . '';
})->implode('');
$msg .= '失败原因Top' . $topText;
}
return redirect()->back()->with('success', $msg);
}
public function clearSyncErrors(Request $request): RedirectResponse
{
$this->ensurePlatformAdmin($request);
// 支持两种模式:
// - scope=all默认清理所有订单的失败标记
// - scope=filtered仅清理当前筛选结果命中的订单更安全
$scope = (string) $request->input('scope', 'all');
$filters = [
'status' => trim((string) $request->input('status', '')),
'payment_status' => trim((string) $request->input('payment_status', '')),
'merchant_id' => trim((string) $request->input('merchant_id', '')),
'plan_id' => trim((string) $request->input('plan_id', '')),
'fail_only' => (string) $request->input('fail_only', ''),
'synced_only' => (string) $request->input('synced_only', ''),
'sync_status' => trim((string) $request->input('sync_status', '')),
'syncable_only' => (string) $request->input('syncable_only', ''),
'batch_synced_24h' => (string) $request->input('batch_synced_24h', ''),
];
$query = PlatformOrder::query()
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NOT NULL");
if ($scope === 'filtered') {
$query = $this->applyFilters($query, $filters);
}
$orders = $query->get(['id', 'meta']);
$matched = $orders->count();
$cleared = 0;
foreach ($orders as $order) {
$meta = (array) ($order->meta ?? []);
if (! data_get($meta, 'subscription_activation_error')) {
continue;
}
data_forget($meta, 'subscription_activation_error');
// 轻量审计:记录清理动作(不做独立表,先落 meta便于排查
$audit = (array) (data_get($meta, 'audit', []) ?? []);
$audit[] = [
'action' => 'clear_sync_error',
'scope' => $scope,
'at' => now()->toDateTimeString(),
'admin_id' => $this->platformAdminId($request),
];
data_set($meta, 'audit', $audit);
$order->meta = $meta;
$order->save();
$cleared++;
}
$msg = $scope === 'filtered'
? '已清除当前筛选范围内的同步失败标记:'
: '已清除全部订单的同步失败标记:';
return redirect()->back()->with('success', $msg . $cleared . ' 条(命中 ' . $matched . ' 条)');
}
protected function applyFilters(Builder $query, array $filters): Builder
{
return $query
->when($filters['status'] !== '', fn (Builder $builder) => $builder->where('status', $filters['status']))
->when($filters['payment_status'] !== '', fn (Builder $builder) => $builder->where('payment_status', $filters['payment_status']))
->when(($filters['merchant_id'] ?? '') !== '', fn (Builder $builder) => $builder->where('merchant_id', (int) $filters['merchant_id']))
->when(($filters['plan_id'] ?? '') !== '', fn (Builder $builder) => $builder->where('plan_id', (int) $filters['plan_id']))
->when(($filters['fail_only'] ?? '') !== '', function (Builder $builder) {
// 只看同步失败meta.subscription_activation_error.message 存在即视为失败
$builder->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NOT NULL");
})
->when(($filters['synced_only'] ?? '') !== '', function (Builder $builder) {
// 只看已同步meta.subscription_activation.subscription_id 存在即视为已同步
$builder->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation.subscription_id') IS NOT NULL");
})
->when(($filters['sync_status'] ?? '') !== '', function (Builder $builder) use ($filters) {
// 同步状态筛选unsynced / synced / failed
if (($filters['sync_status'] ?? '') === 'synced') {
$builder->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation.subscription_id') IS NOT NULL")
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NULL");
} elseif (($filters['sync_status'] ?? '') === 'failed') {
$builder->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NOT NULL");
} elseif (($filters['sync_status'] ?? '') === 'unsynced') {
$builder->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation.subscription_id') IS NULL")
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation_error.message') IS NULL");
}
})
->when(($filters['syncable_only'] ?? '') !== '', function (Builder $builder) {
// 只看可同步:已支付 + 已生效 + 尚未写入 subscription_activation.subscription_id
$builder->where('payment_status', 'paid')
->where('status', 'activated')
->whereRaw("JSON_EXTRACT(meta, '$.subscription_activation.subscription_id') IS NULL");
})
->when(($filters['batch_synced_24h'] ?? '') !== '', function (Builder $builder) {
// 只看最近 24 小时批量同步过的订单(基于 meta.batch_activation.at
$since = now()->subHours(24)->format('Y-m-d H:i:s');
$builder->whereRaw("JSON_EXTRACT(meta, '$.batch_activation.at') IS NOT NULL");
// sqlite 测试库没有 JSON_UNQUOTE(),需要做兼容
$driver = $builder->getQuery()->getConnection()->getDriverName();
if ($driver === 'sqlite') {
$builder->whereRaw("JSON_EXTRACT(meta, '$.batch_activation.at') >= ?", [$since]);
} else {
$builder->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(meta, '$.batch_activation.at')) >= ?", [$since]);
}
});
}
protected function statusLabels(): array
{
return [
'pending' => '待处理',
'paid' => '已支付',
'activated' => '已生效',
'cancelled' => '已取消',
'refunded' => '已退款',
];
}
protected function paymentStatusLabels(): array
{
return [
'unpaid' => '未支付',
'paid' => '已支付',
'partially_refunded' => '部分退款',
'refunded' => '已退款',
'failed' => '支付失败',
];
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\ChannelConfig;
use App\Models\PaymentConfig;
use App\Models\SystemConfig;
use App\Models\Merchant;
use App\Support\CacheKeys;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class PlatformSettingController extends Controller
{
use ResolvesPlatformAdminContext;
public function system(Request $request): View
{
$this->ensurePlatformAdmin($request);
$configs = Cache::remember(
CacheKeys::platformSystemConfigs(),
now()->addMinutes(10),
fn () => SystemConfig::query()
->orderBy('group')
->orderBy('id')
->get()
);
return view('admin.settings.system', [
'systemSettings' => $configs,
'groupedCount' => $configs->groupBy('group')->count(),
'valueTypeOptions' => ['string', 'boolean', 'number', 'json'],
'editingConfigId' => (int) session('editing_config_id', 0),
]);
}
public function updateSystem(Request $request, int $id): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$config = SystemConfig::query()->findOrFail($id);
$data = $request->validate([
'config_name' => ['required', 'string'],
'config_value' => ['nullable', 'string'],
'group' => ['required', 'string'],
'value_type' => ['required', 'string'],
'autoload' => ['nullable', 'boolean'],
'remark' => ['nullable', 'string'],
]);
try {
$normalizedValue = match ($data['value_type']) {
'boolean' => in_array(strtolower((string) ($data['config_value'] ?? '')), ['1', 'true', 'yes', 'on'], true) ? '1' : '0',
'number' => (string) (is_numeric($data['config_value'] ?? null) ? $data['config_value'] : 0),
'json' => $this->normalizeJsonConfigValue($data['config_value'] ?? null),
default => $data['config_value'] ?? null,
};
} catch (ValidationException $exception) {
return redirect('/admin/settings/system')
->withErrors($exception->errors())
->withInput()
->with('editing_config_id', $config->id);
}
$config->update([
'config_name' => $data['config_name'],
'config_value' => $normalizedValue,
'group' => $data['group'],
'value_type' => $data['value_type'],
'autoload' => (bool) ($data['autoload'] ?? false),
'remark' => $data['remark'] ?? null,
]);
Cache::forget(CacheKeys::platformSystemConfigs());
return redirect('/admin/settings/system')->with('success', '系统配置更新成功');
}
public function channels(Request $request): View
{
$this->ensurePlatformAdmin($request);
$payload = Cache::remember(
CacheKeys::platformChannelsOverview(),
now()->addMinutes(10),
fn () => [
'channels' => ChannelConfig::query()
->orderBy('sort')
->orderBy('id')
->get(),
'paymentConfigs' => PaymentConfig::query()->orderBy('id')->get(),
'merchantCount' => Merchant::count(),
]
);
return view('admin.settings.channels', $payload);
}
public function updateChannel(Request $request, int $id): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$channel = ChannelConfig::query()->findOrFail($id);
$data = $request->validate([
'channel_name' => ['required', 'string'],
'channel_type' => ['required', 'string'],
'status' => ['required', 'string'],
'entry_path' => ['nullable', 'string'],
'supports_login' => ['nullable', 'boolean'],
'supports_payment' => ['nullable', 'boolean'],
'supports_share' => ['nullable', 'boolean'],
'remark' => ['nullable', 'string'],
]);
$channel->update([
'channel_name' => $data['channel_name'],
'channel_type' => $data['channel_type'],
'status' => $data['status'],
'entry_path' => $data['entry_path'] ?? null,
'supports_login' => (bool) ($data['supports_login'] ?? false),
'supports_payment' => (bool) ($data['supports_payment'] ?? false),
'supports_share' => (bool) ($data['supports_share'] ?? false),
'remark' => $data['remark'] ?? null,
]);
Cache::forget(CacheKeys::platformChannelsOverview());
return redirect('/admin/settings/channels')->with('success', '渠道配置更新成功');
}
public function updatePayment(Request $request, int $id): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$payment = PaymentConfig::query()->findOrFail($id);
$data = $request->validate([
'payment_name' => ['required', 'string'],
'provider' => ['required', 'string'],
'status' => ['required', 'string'],
'is_sandbox' => ['nullable', 'boolean'],
'supports_refund' => ['nullable', 'boolean'],
'remark' => ['nullable', 'string'],
]);
$payment->update([
'payment_name' => $data['payment_name'],
'provider' => $data['provider'],
'status' => $data['status'],
'is_sandbox' => (bool) ($data['is_sandbox'] ?? false),
'supports_refund' => (bool) ($data['supports_refund'] ?? false),
'remark' => $data['remark'] ?? null,
]);
Cache::forget(CacheKeys::platformChannelsOverview());
return redirect('/admin/settings/channels')->with('success', '支付配置更新成功');
}
protected function normalizeJsonConfigValue(?string $value): string
{
if ($value === null || trim($value) === '') {
return '{}';
}
$decoded = json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw ValidationException::withMessages([
'config_value' => 'JSON 配置值格式不正确,请检查后重试。',
]);
}
return json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\ProductCategory;
use App\Models\Merchant;
use App\Support\CacheKeys;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
class ProductCategoryController extends Controller
{
use ResolvesPlatformAdminContext;
public function index(Request $request): View
{
$this->ensurePlatformAdmin($request);
$page = max((int) $request->integer('page', 1), 1);
return view('admin.product_categories.index', [
'categories' => Cache::remember(
CacheKeys::platformCategoriesList($page),
now()->addMinutes(10),
fn () => ProductCategory::query()->with('merchant')->orderBy('merchant_id')->orderBy('sort')->orderBy('id')->paginate(10)->withQueryString()
),
'merchants' => Merchant::query()->orderBy('id')->get(),
'cacheMeta' => [
'store' => config('cache.default'),
'ttl' => '10m',
],
]);
}
public function store(Request $request): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$data = $request->validate([
'merchant_id' => ['required', 'integer'],
'name' => ['required', 'string'],
'slug' => [
'required',
'string',
Rule::unique('product_categories', 'slug')->where(fn ($query) => $query->where('merchant_id', $data['merchant_id'] ?? $request->input('merchant_id'))),
],
'status' => ['nullable', 'string'],
'sort' => ['nullable', 'integer'],
'description' => ['nullable', 'string'],
], [
'slug.unique' => '当前商家下该分类 slug 已存在,请换一个。',
]);
ProductCategory::query()->create([
'merchant_id' => $data['merchant_id'],
'name' => $data['name'],
'slug' => $data['slug'],
'status' => $data['status'] ?? 'active',
'sort' => $data['sort'] ?? 0,
'description' => $data['description'] ?? null,
]);
$this->flushPlatformCaches();
return redirect('/admin/product-categories')->with('success', '商品分类创建成功');
}
public function update(Request $request, int $id): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$category = ProductCategory::query()->findOrFail($id);
$data = $request->validate([
'name' => ['required', 'string'],
'slug' => [
'nullable',
'string',
Rule::unique('product_categories', 'slug')->where(fn ($query) => $query->where('merchant_id', $category->merchant_id))->ignore($category->id),
],
'status' => ['required', 'string'],
'sort' => ['nullable', 'integer'],
'description' => ['nullable', 'string'],
], [
'slug.unique' => '当前商家下该分类 slug 已存在,请换一个。',
]);
$category->update([
'name' => $data['name'],
'slug' => $data['slug'] ?? $category->slug,
'status' => $data['status'],
'sort' => $data['sort'] ?? 0,
'description' => $data['description'] ?? null,
]);
$this->flushPlatformCaches();
return redirect('/admin/product-categories')->with('success', '商品分类更新成功');
}
public function destroy(Request $request, int $id): RedirectResponse
{
$this->ensurePlatformAdmin($request);
$category = ProductCategory::query()->findOrFail($id);
$category->delete();
$this->flushPlatformCaches();
return redirect('/admin/product-categories')->with('success', '商品分类删除成功');
}
protected function flushPlatformCaches(): void
{
for ($page = 1; $page <= 5; $page++) {
Cache::forget(CacheKeys::platformProductsList($page));
Cache::forget(CacheKeys::platformCategoriesList($page));
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,196 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\SiteSubscription;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
class SiteSubscriptionController extends Controller
{
use ResolvesPlatformAdminContext;
public function export(Request $request): StreamedResponse
{
$this->ensurePlatformAdmin($request);
$filters = [
'status' => trim((string) $request->query('status', '')),
'keyword' => trim((string) $request->query('keyword', '')),
'merchant_id' => trim((string) $request->query('merchant_id', '')),
'plan_id' => trim((string) $request->query('plan_id', '')),
'expiry' => trim((string) $request->query('expiry', '')),
];
$query = $this->applyFilters(
SiteSubscription::query()->with(['merchant', 'plan']),
$filters
)->orderBy('id');
$filename = 'site_subscriptions_' . now()->format('Ymd_His') . '.csv';
return response()->streamDownload(function () use ($query) {
$out = fopen('php://output', 'w');
// UTF-8 BOM避免 Excel 打开中文乱码
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, [
'ID',
'订阅号',
'站点',
'套餐',
'状态',
'计费周期',
'周期(月)',
'金额',
'开始时间',
'到期时间',
'到期状态',
'试用到期',
'生效时间',
'取消时间',
]);
$statusLabels = $this->statusLabels();
$query->chunkById(500, function ($subs) use ($out, $statusLabels) {
foreach ($subs as $sub) {
$endsAt = $sub->ends_at;
$expiryLabel = '无到期';
if ($endsAt) {
if ($endsAt->lt(now())) {
$expiryLabel = '已过期';
} elseif ($endsAt->lt(now()->addDays(7))) {
$expiryLabel = '7天内到期';
} else {
$expiryLabel = '未到期';
}
}
$status = (string) ($sub->status ?? '');
$statusText = ($statusLabels[$status] ?? $status);
$statusText = $statusText . ' (' . $status . ')';
fputcsv($out, [
$sub->id,
$sub->subscription_no,
$sub->merchant?->name ?? '',
$sub->plan_name ?: ($sub->plan?->name ?? ''),
$statusText,
$sub->billing_cycle ?: '',
(int) $sub->period_months,
(float) $sub->amount,
optional($sub->starts_at)->format('Y-m-d H:i:s') ?: '',
optional($sub->ends_at)->format('Y-m-d H:i:s') ?: '',
$expiryLabel,
optional($sub->trial_ends_at)->format('Y-m-d H:i:s') ?: '',
optional($sub->activated_at)->format('Y-m-d H:i:s') ?: '',
optional($sub->cancelled_at)->format('Y-m-d H:i:s') ?: '',
]);
}
});
fclose($out);
}, $filename, [
'Content-Type' => 'text/csv; charset=UTF-8',
]);
}
public function index(Request $request): View
{
$this->ensurePlatformAdmin($request);
$filters = [
'status' => trim((string) $request->query('status', '')),
'keyword' => trim((string) $request->query('keyword', '')),
'merchant_id' => trim((string) $request->query('merchant_id', '')),
'plan_id' => trim((string) $request->query('plan_id', '')),
// 到期辅助筛选(不改变 status 字段,仅按 ends_at 计算)
// - expired已过期ends_at < now
// - expiring_7d7 天内到期now <= ends_at < now+7d
'expiry' => trim((string) $request->query('expiry', '')),
];
$query = $this->applyFilters(
SiteSubscription::query()->with(['merchant', 'plan']),
$filters
);
$subscriptions = (clone $query)
->latest('id')
->paginate(10)
->withQueryString();
$baseQuery = $this->applyFilters(SiteSubscription::query(), $filters);
return view('admin.site_subscriptions.index', [
'subscriptions' => $subscriptions,
'filters' => $filters,
'statusLabels' => $this->statusLabels(),
'filterOptions' => [
'statuses' => $this->statusLabels(),
],
'merchants' => SiteSubscription::query()->with('merchant')->select('merchant_id')->distinct()->get()->pluck('merchant')->filter()->unique('id')->values(),
'plans' => SiteSubscription::query()->with('plan')->select('plan_id')->whereNotNull('plan_id')->distinct()->get()->pluck('plan')->filter()->unique('id')->values(),
'summaryStats' => [
'total_subscriptions' => (clone $baseQuery)->count(),
'activated_subscriptions' => (clone $baseQuery)->where('status', 'activated')->count(),
'pending_subscriptions' => (clone $baseQuery)->where('status', 'pending')->count(),
'cancelled_subscriptions' => (clone $baseQuery)->where('status', 'cancelled')->count(),
// 可治理辅助指标:按 ends_at 计算
'expired_subscriptions' => (clone $baseQuery)
->whereNotNull('ends_at')
->where('ends_at', '<', now())
->count(),
'expiring_7d_subscriptions' => (clone $baseQuery)
->whereNotNull('ends_at')
->where('ends_at', '>=', now())
->where('ends_at', '<', now()->addDays(7))
->count(),
],
]);
}
protected function statusLabels(): array
{
return [
'pending' => '待生效',
'activated' => '已生效',
'cancelled' => '已取消',
'expired' => '已过期',
];
}
protected function applyFilters(Builder $query, array $filters): Builder
{
return $query
->when($filters['status'] !== '', fn (Builder $builder) => $builder->where('status', $filters['status']))
->when(($filters['merchant_id'] ?? '') !== '', fn (Builder $builder) => $builder->where('merchant_id', (int) $filters['merchant_id']))
->when(($filters['plan_id'] ?? '') !== '', fn (Builder $builder) => $builder->where('plan_id', (int) $filters['plan_id']))
->when(($filters['expiry'] ?? '') !== '', function (Builder $builder) use ($filters) {
$expiry = (string) ($filters['expiry'] ?? '');
if ($expiry === 'expired') {
$builder->whereNotNull('ends_at')->where('ends_at', '<', now());
} elseif ($expiry === 'expiring_7d') {
$builder->whereNotNull('ends_at')
->where('ends_at', '>=', now())
->where('ends_at', '<', now()->addDays(7));
}
})
->when($filters['keyword'] !== '', function (Builder $builder) use ($filters) {
$keyword = $filters['keyword'];
$builder->where(function (Builder $subQuery) use ($keyword) {
$subQuery->where('subscription_no', 'like', '%' . $keyword . '%')
->orWhere('plan_name', 'like', '%' . $keyword . '%')
->orWhere('billing_cycle', 'like', '%' . $keyword . '%');
});
});
}
}