| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- <?php
- namespace App\Services\Payment;
- use App\Models\RechargeChannel;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- use RuntimeException;
- class RechargeChannelConfigurationService
- {
- public function options(int $dataType, ?int $id = null): array
- {
- $options = PaymentProviderCatalog::channelFormOptions($dataType);
- $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
- {
- 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('不能修改通道所属的充值、提现或活动方向');
- }
- $params = PaymentProviderCatalog::normalizeChannelSelection($params);
- 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];
- $channel->fill($params);
- $channel->save();
- return $channel;
- }, 3);
- }
- 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 '';
- }
- }
|