| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328 |
- <?php
- namespace App\Services\Payment;
- use App\Models\RechargeChannel;
- use App\Models\OperationAudit;
- use App\Models\RechargeChannelGroup;
- use App\Services\OperationAuditService;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- use RuntimeException;
- class RechargeChannelConfigurationService
- {
- public function saveGroup(array $params): array
- {
- return DB::transaction(function () use ($params) {
- $id = (int)($params['id'] ?? 0);
- unset($params['id']);
- $validTypes = [];
- foreach (['recharge_type' => 1, 'withdraw_type' => 2] as $field => $direction) {
- if (!array_key_exists($field, $params)) continue;
- $params[$field] = $this->normalizeTypes((array)($params[$field] ?? []));
- // Match deletion's lock order: channel rows, then the group being edited.
- $validTypes[$field] = $params[$field] === [] ? [] : RechargeChannel::query()
- ->where('data_type', $direction)->whereIn('type', $params[$field])
- ->orderBy('id')->lockForUpdate()->get(['type'])->pluck('type')->map(fn ($type) => (string)$type)->all();
- }
- $group = $id ? RechargeChannelGroup::query()->lockForUpdate()->findOrFail($id) : new RechargeChannelGroup();
- $before = $group->exists ? $group->toArray() : [];
- $removed = [];
- foreach ($validTypes as $field => $valid) {
- $invalid = array_values(array_diff($params[$field], $valid));
- $previous = $group->exists ? $this->normalizeTypes((array)$group->{$field}) : [];
- $newInvalid = array_values(array_diff($invalid, $previous));
- if ($newInvalid !== []) {
- throw new RuntimeException($field . ' 包含不存在或已删除的通道类型:'
- . implode(',', $newInvalid) . ';请提交选项的 type,不是通道 ID 或公司代码');
- }
- if ($invalid !== []) $removed[$field] = $invalid;
- $params[$field] = array_values(array_intersect($params[$field], $valid));
- }
- $group->fill($params);
- $group->save();
- if ($removed !== []) {
- OperationAuditService::record('recharge_channel_group', (int)$group->id, 'update', $before,
- ['group' => $group->toArray(), 'removed_types' => $removed]);
- }
- return $removed;
- }, 3);
- }
- public function deleteGroup(int $id): void
- {
- if ($id === 1) throw new RuntimeException('默认通道组合不能删除');
- DB::transaction(function () use ($id) {
- $group = RechargeChannelGroup::withTrashed()->lockForUpdate()->findOrFail($id);
- if ($group->trashed()) return;
- if (Schema::hasTable('users') && Schema::hasColumn('users', 'recharge_channel_group_id')
- && DB::table('users')->where('recharge_channel_group_id', $id)->lockForUpdate()->first(['id'])) {
- throw new RuntimeException('该层级仍有会员使用,请先将会员调整到其他层级');
- }
- foreach (['payment_gateways', 'payment_collection_channels', 'payment_direct_recharges'] as $table) {
- if (!Schema::hasTable($table) || !Schema::hasColumn($table, 'recharge_channel_group_ids')) continue;
- DB::table($table)->whereNull('deleted_at')->whereNotNull('recharge_channel_group_ids')
- ->select(['id', 'recharge_channel_group_ids'])
- ->orderBy('id')->lockForUpdate()->chunkById(200, function ($rows) use ($id) {
- foreach ($rows as $row) {
- // Match runtime's integer normalization, including legacy string IDs such as "02".
- $ids = array_map('intval', (array)json_decode($row->recharge_channel_group_ids, true));
- if (in_array($id, $ids, true)) throw new RuntimeException('该层级仍被支付配置引用,请先解除关联');
- }
- }, 'id', 'id');
- }
- $before = $group->toArray();
- $group->delete();
- OperationAuditService::record('recharge_channel_group', $id, 'delete', $before, $group);
- }, 3);
- }
- private function normalizeTypes(array $values): array
- {
- $types = [];
- foreach ($values as $value) {
- if ($value !== null && !is_string($value) && !is_int($value)) {
- throw new RuntimeException('通道类型应提交 type 字符串数组,不能提交选项对象');
- }
- $type = trim((string)$value);
- if ($type !== '') $types[] = $type;
- }
- return array_values(array_unique($types));
- }
- public function options(int $dataType, ?int $id = null): array
- {
- $options = PaymentProviderCatalog::channelFormOptions($dataType, PaymentProviderService::statuses());
- $reason = '';
- if ($id) {
- $channel = RechargeChannel::query()->findOrFail($id);
- if ((int)$channel->data_type !== $dataType) throw new RuntimeException('通道方向与编辑记录不一致');
- $reason = $this->identityLockReason($channel);
- }
- return $options + ['identity_editable' => $reason === '', 'identity_edit_reason' => $reason];
- }
- public function save(array $params): RechargeChannel
- {
- if (array_key_exists('logo', $params)) $params['logo'] = RechargeChannelLogoService::normalize($params['logo']);
- return DB::transaction(function () use ($params) {
- $id = (int)($params['id'] ?? 0);
- unset($params['id']);
- $channel = $id ? RechargeChannel::query()->lockForUpdate()->findOrFail($id) : new RechargeChannel();
- if ($channel->exists && (int)$channel->data_type !== (int)$params['data_type']) {
- throw new RuntimeException('不能修改通道所属的充值或提现方向');
- }
- $isNew = !$channel->exists;
- $before = $isNew ? [] : $channel->toArray();
- $params = PaymentProviderCatalog::normalizeChannelSelection($params);
- $params = $this->amountConfiguration($params, $channel);
- $identityChanged = !$channel->exists || (int)$channel->from !== $params['from'] || (string)$channel->type !== (string)$params['type'];
- $identity = PaymentProviderCatalog::channelIdentity($params);
- if ($identityChanged && $identity) PaymentProviderService::assertEnabled($identity['provider_code']);
- if ($channel->exists && ((int)$channel->from !== $params['from'] || (string)$channel->type !== (string)$params['type'])) {
- $reason = $this->identityLockReason($channel, true);
- if ($reason !== '') throw new RuntimeException($reason);
- }
- foreach (['name', 'key'] as $field) {
- if (array_key_exists($field, $params)) $params[$field] = trim((string)$params[$field]);
- if ((!$channel->exists || array_key_exists($field, $params)) && ($params[$field] ?? '') === '') {
- throw new RuntimeException($field === 'name' ? '请填写通道名称' : '请填写通道标识Key');
- }
- }
- foreach (['status', 'sort'] as $field) {
- if (array_key_exists($field, $params) && $params[$field] === null) unset($params[$field]);
- }
- if (!$channel->exists) $params += ['status' => 1, 'sort' => 0];
- if ($identityChanged && RechargeChannelLogoService::supportsDirection((int)$params['data_type']) && !array_key_exists('logo', $params)) {
- $dataType = (int)$params['data_type'];
- $type = (string)$params['type'];
- $logos = $dataType === 1 ? RechargeChannelLogoService::configured([$type]) : [];
- $peer = RechargeChannel::where('data_type', $dataType)->where('type', $type)->orderBy('sort')->orderBy('id')->first();
- $params['logo'] = array_key_exists($type, $logos) ? $logos[$type] : ($peer ? $peer->getRawOriginal('logo') : null);
- }
- $channel->fill($params);
- $channel->save();
- if (RechargeChannelLogoService::supportsDirection((int)$channel->data_type) && array_key_exists('logo', $params)) {
- RechargeChannelLogoService::store((string)$channel->type, $params['logo'], (int)$channel->data_type);
- }
- $after = $channel->fresh()->toArray();
- if ($isNew || self::diff($before, $after) !== []) {
- OperationAuditService::record('recharge_channel', (int)$channel->id, $isNew ? 'create' : 'update', $before, $after);
- }
- return $channel;
- }, 3);
- }
- private function amountConfiguration(array $params, RechargeChannel $channel): array
- {
- $fixedMode = (int)$params['data_type'] === 1 && $params['type'] === 'zfbge';
- if ($fixedMode || array_key_exists('fixed', $params)) {
- $value = array_key_exists('fixed', $params) ? $params['fixed'] : ($channel->type === 'zfbge' ? $channel->getRawOriginal('fixed') : null);
- if (is_string($value)) $values = explode(',', str_replace(',', ',', $value));
- elseif (is_array($value) && array_values($value) === $value) $values = $value;
- elseif ($value === null) $values = [];
- else throw \Illuminate\Validation\ValidationException::withMessages(['fixed' => '固定金额请提交金额数组或逗号分隔字符串']);
- $amounts = [];
- foreach ($values as $amount) {
- if (!is_string($amount) && !is_int($amount) && !is_float($amount)) throw \Illuminate\Validation\ValidationException::withMessages(['fixed' => '固定金额格式错误']);
- $amount = trim((string)$amount);
- if ($amount === '') continue;
- if (!preg_match('/^\d{1,12}(\.\d{1,2}0*)?$/D', $amount) || bccomp($amount, '0', 2) <= 0) {
- throw \Illuminate\Validation\ValidationException::withMessages(['fixed' => '固定金额必须大于0,最多两位小数']);
- }
- $amount = bcadd($amount, '0', 2);
- if (str_ends_with($amount, '.00')) $amount = substr($amount, 0, -3);
- if (!in_array($amount, $amounts, true)) $amounts[] = $amount;
- }
- if ($fixedMode && !$amounts) throw \Illuminate\Validation\ValidationException::withMessages(['fixed' => '请设置固定充值金额']);
- $params['fixed'] = $amounts ? implode(',', $amounts) : null;
- } elseif ($channel->exists && $channel->type !== $params['type']) {
- $params['fixed'] = null;
- }
- if ($fixedMode) {
- $params['min'] = $params['max'] = null;
- } else {
- $range = ['min' => array_key_exists('min', $params) ? $params['min'] : $channel->min,
- 'max' => array_key_exists('max', $params) ? $params['max'] : $channel->max];
- $rules = ['min' => ['nullable', 'numeric', 'min:0'], 'max' => ['nullable', 'numeric', 'min:0']];
- if ($range['min'] !== null && $range['max'] !== null) $rules['max'][] = 'gte:min';
- \Illuminate\Support\Facades\Validator::make($range, $rules)->validate();
- }
- return $params;
- }
- public function delete(int $id): void
- {
- DB::transaction(function () use ($id) {
- $channel = RechargeChannel::withTrashed()->lockForUpdate()->findOrFail($id);
- if (!in_array((int)$channel->data_type, [1, 2], true)) throw new RuntimeException('只支持删除充值或提现通道');
- if ($channel->trashed()) return;
- if ($this->identityLockReason($channel, true) !== '') {
- throw new RuntimeException('该通道已被支付配置引用,请先解除关联再删除');
- }
- $before = $channel->toArray();
- $channel->status = 0;
- $channel->save();
- $channel->delete();
- // Groups grant access by type, so retain the grant while another row of that type remains.
- $remaining = RechargeChannel::query()->where('data_type', $channel->data_type)
- ->where('type', $channel->type)->lockForUpdate()->first(['id']);
- $groupChanges = [];
- if (!$remaining) {
- $field = (int)$channel->data_type === 1 ? 'recharge_type' : 'withdraw_type';
- foreach (RechargeChannelGroup::query()->orderBy('id')->lockForUpdate()->get() as $group) {
- $types = (array)$group->{$field};
- $updated = array_values(array_filter($types, fn ($type) => trim((string)$type) !== (string)$channel->type));
- if ($types === $updated) continue;
- $groupChanges[] = ['id' => (int)$group->id, 'field' => $field, 'before' => $types, 'after' => $updated];
- $group->{$field} = $updated;
- $group->save();
- }
- }
- OperationAuditService::record('recharge_channel', $id, 'delete', $before,
- ['channel' => $channel->toArray(), 'group_changes' => $groupChanges]);
- }, 3);
- }
- /** 通道操作日志中展示的字段(顺序即展示顺序) */
- private const AUDIT_FIELDS = [
- 'name' => '通道名称', 'key' => '通道标识Key', 'from' => '来源', 'type' => '通道类型', 'rate' => '费率',
- 'min' => '最低金额', 'max' => '最高金额', 'fixed' => '固定金额', 'status' => '状态', 'sort' => '排序', 'logo' => 'Logo',
- ];
- private const AUDIT_ACTIONS = ['create' => '新增', 'update' => '修改', 'delete' => '删除', 'save' => '修改Logo'];
- /** 充值(1)/提现(2)通道操作日志:谁、什么时间、改了什么 */
- public function logs(array $params): array
- {
- $dataType = (int)$params['data_type'];
- $channels = RechargeChannel::withTrashed()->where('data_type', $dataType)->get(['id', 'name', 'type'])->keyBy('id');
- $query = OperationAudit::query()->where(function ($q) use ($channels, $dataType) {
- $q->where('resource_type', 'recharge_channel')->whereIn('resource_id', $channels->keys()->all() ?: [0]);
- // 充值方式Logo按充值类型统一配置,归入充值通道日志
- if ($dataType === 1) $q->orWhere('resource_type', 'recharge_channel_logo');
- });
- if (!empty($params['channel_id'])) {
- $query->where('resource_type', 'recharge_channel')->where('resource_id', (int)$params['channel_id']);
- }
- if (!empty($params['operator_name'])) $query->where('operator_name', 'like', '%' . trim($params['operator_name']) . '%');
- if (!empty($params['action'])) $query->where('action', $params['action']);
- if (!empty($params['start_time'])) $query->where('created_at', '>=', $params['start_time']);
- if (!empty($params['end_time'])) $query->where('created_at', '<=', $params['end_time']);
- $total = (clone $query)->count();
- $rows = $query->orderByDesc('id')->forPage((int)($params['page'] ?? 1), (int)($params['limit'] ?? 20))->get();
- $data = $rows->map(function (OperationAudit $log) use ($channels) {
- $changes = (array)$log->changes;
- $isLogo = $log->resource_type === 'recharge_channel_logo';
- if ($isLogo) {
- $before = ['logo' => $changes['before']['logo'] ?? ''];
- $after = ['logo' => $changes['after']['logo'] ?? ''];
- $type = (string)($changes['after']['channel_type'] ?? $changes['before']['channel_type'] ?? '');
- } else {
- $before = (array)($changes['before'] ?? []);
- // 删除日志的 after 为 {channel, group_changes}
- $after = $log->action === 'delete' ? [] : (array)($changes['after'] ?? []);
- $type = (string)($after['type'] ?? $before['type'] ?? '');
- }
- $channel = $isLogo ? null : $channels->get($log->resource_id);
- $diff = self::diff($before, $after);
- $created = $log->getRawOriginal('created_at');
- return [
- 'id' => (int)$log->id,
- 'channel_id' => $isLogo ? null : (int)$log->resource_id,
- 'channel_name' => (string)($after['name'] ?? $before['name'] ?? ($channel->name ?? '')),
- 'channel_type' => $type,
- 'action' => $isLogo ? 'logo' : (string)$log->action,
- 'action_label' => self::AUDIT_ACTIONS[$log->action] ?? (string)$log->action,
- 'operator_id' => $log->operator_id === null ? null : (int)$log->operator_id,
- 'operator_name' => (string)$log->operator_name,
- 'created_at' => $created ? date('Y-m-d H:i:s', strtotime((string)$created)) : null,
- 'changes' => $diff,
- 'summary' => implode(';', array_map(fn ($c) => "{$c['label']}:{$c['before_text']} → {$c['after_text']}", $diff)),
- ];
- })->all();
- return ['total' => $total, 'data' => $data];
- }
- private static function diff(array $before, array $after): array
- {
- $result = [];
- foreach (self::AUDIT_FIELDS as $field => $label) {
- if (!array_key_exists($field, $before) && !array_key_exists($field, $after)) continue;
- $old = self::auditValue($field, $before[$field] ?? null);
- $new = self::auditValue($field, $after[$field] ?? null);
- if ($old === $new) continue;
- $result[] = ['field' => $field, 'label' => $label, 'before' => $old, 'after' => $new,
- 'before_text' => self::auditText($field, $old), 'after_text' => self::auditText($field, $new)];
- }
- return $result;
- }
- private static function auditValue(string $field, $value)
- {
- if ($value === null || $value === '' || $value === []) return null;
- if ($field === 'fixed') return implode(',', is_array($value) ? $value : explode(',', (string)$value));
- if (in_array($field, ['from', 'status', 'sort'], true)) return (int)$value;
- if (in_array($field, ['rate', 'min', 'max'], true)) return rtrim(rtrim(bcadd((string)$value, '0', 4), '0'), '.');
- return (string)$value;
- }
- private static function auditText(string $field, $value): string
- {
- if ($value === null) return '空';
- if ($field === 'status') return $value === 1 ? '启用' : '停用';
- if ($field === 'from') return [1 => '第三方支付', 2 => 'USDT', 3 => '人工'][$value] ?? (string)$value;
- return (string)$value;
- }
- private function identityLockReason(RechargeChannel $channel, bool $lock = false): string
- {
- foreach (['payment_gateways', 'payment_collection_channels', 'payment_direct_recharges'] as $table) {
- if (!Schema::hasTable($table) || !Schema::hasColumn($table, 'recharge_channel_id')) continue;
- $query = DB::table($table)->where('recharge_channel_id', $channel->id)->whereNull('deleted_at');
- if ($lock) $query->lockForUpdate();
- if ($query->first(['id'])) return '该通道已被支付配置引用,请先解除关联或新增通道,再更换公司或类型';
- }
- return '';
- }
- }
|