feat: 收益全额直入商城余额、存量结转与奖项名称全局规范化对齐

这个提交包含在:
chen
2026-09-19 11:49:57 +08:00
父节点 85947e43ae
当前提交 aca0d3c671
共有 83 个文件被更改,包括 4146 次插入 和 443 次删除

查看文件

@@ -112,6 +112,7 @@ class Shopro extends Addons
'addons\shopro\console\PartnerDemo',
'addons\shopro\console\PartnerAccept',
'addons\shopro\console\PartnerClean',
'addons\shopro\console\PartnerTransferCommission',
]);
}

查看文件

@@ -227,24 +227,8 @@ class PartnerInstall extends Command
protected function backfillLastSelfOrder(Output $output)
{
$rows = Db::name('shopro_order')
->where('status', 'in', ['paid', 'completed'])
->where('paid_time', '>', 0)
->field('user_id, max(paid_time) as last_paid')
->group('user_id')
->select();
$count = 0;
foreach ($rows as $row) {
$agent = Db::name('shopro_commission_agent')->where('user_id', $row['user_id'])->find();
if (!$agent || !empty($agent['last_self_order_time'])) {
continue;
}
Db::name('shopro_commission_agent')->where('user_id', $row['user_id'])->update([
'last_self_order_time' => intval($row['last_paid']),
]);
$count++;
}
$output->writeln("backfill last_self_order_time: {$count}");
$count = (new \addons\shopro\service\partner\ActiveService())->syncActiveTimes();
$output->writeln("backfill last_self_order_time (self + direct): {$count}");
}
protected function clearConfigCache(Output $output)

查看文件

@@ -0,0 +1,84 @@
<?php
namespace addons\shopro\console;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use addons\shopro\service\partner\WalletMigrationService;
/**
* 历史收益全量结转至商城余额控制台命令
*/
class PartnerTransferCommission extends Command
{
protected function configure()
{
$this->setName('shopro:partner:transfer-commission')
->addOption('dry-run', 'd', Option::VALUE_NONE, '只读试算预览,不真实扣减与增加资金')
->addOption('force', 'f', Option::VALUE_NONE, '强制执行,不提示二次确认')
->setDescription('将所有会员账户已有佣金收益全量结转至商城余额');
}
protected function execute(Input $input, Output $output)
{
$dryRun = (bool) $input->getOption('dry-run');
$force = (bool) $input->getOption('force');
$output->writeln("========================================================");
$output->writeln(" 恒联数通 · 历史收益全量结转至商城余额工具");
$output->writeln("========================================================");
$service = new WalletMigrationService();
$preview = $service->preview();
$output->writeln("待处理会员总数: {$preview['total_users']} 人");
$output->writeln("待结转收益总金额: ¥{$preview['total_commission']} 元");
if ($preview['total_users'] === 0) {
$output->writeln("\n当前无任何待结转佣金余额,无需处理。");
return 0;
}
$output->writeln("\n部分待结转会员抽样(前 10 名):");
foreach (array_slice($preview['samples'], 0, 10) as $i => $s) {
$idx = $i + 1;
$output->writeln(" [{$idx}] 会员ID: {$s['id']} | 手机: {$s['mobile']} | 当前佣金: ¥{$s['current_commission']} -> 商城余额: ¥{$s['current_money']} (结转后预计: ¥{$s['target_money']})");
}
if ($dryRun) {
$output->writeln("\n【DRY-RUN 试算模式已结束】未对数据库发生任何资金变动。");
return 0;
}
if (!$force) {
$output->writeln("\n【安全警告】即将对全量 {$preview['total_users']} 名会员执行结转,将 ¥{$preview['total_commission']} 元佣金划入商城余额!");
$output->writeln("若确认执行,请增加参数 --force 或 -f,例如:");
$output->writeln("php think shopro:partner:transfer-commission --force");
return 1;
}
$output->writeln("\n>>> 开始执行资金划转...");
$startTime = microtime(true);
$res = $service->transferAll(false, function ($current, $total, $userId, $amount, $err) use ($output) {
if ($err) {
$output->writeln(" [{$current}/{$total}] 会员 {$userId} 结转失败: {$err}");
} else {
$output->writeln(" [{$current}/{$total}] 会员 {$userId} 成功结转 ¥" . number_format($amount, 2, '.', '') . " 元至商城余额");
}
});
$cost = round(microtime(true) - $startTime, 2);
$output->writeln("\n========================================================");
$output->writeln("结转完成!耗时: {$cost} 秒");
$output->writeln("成功处理: {$res['success_count']} 人");
$output->writeln("失败人数: {$res['fail_count']} 人");
$output->writeln("累计结转资金: ¥{$res['transferred_amount']} 元");
$output->writeln("========================================================");
return $res['fail_count'] > 0 ? 1 : 0;
}
}

查看文件

@@ -36,7 +36,7 @@ class Pay extends Common
$payment = $this->request->post('payment');
$openid = $this->request->post('openid', '');
$money = $this->request->post('money', 0);
$money = $money > 0 ? $money : 0;
$money = floatval($money) > 0 ? round(floatval($money), 2) : 0;
$platform = $this->request->header('platform');
list($order, $order_type) = $this->getOrderInstance($order_sn);
@@ -65,30 +65,62 @@ class Pay extends Common
// pay 实例
$payOper = new PayOper();
if ($money && $order_type == 'order') {
// 余额混合支付
$order = Db::transaction(function () use ($payOper, $order, $order_type, $money) {
$mixedPayRecord = null;
if ($money > 0 && $order_type == 'order') {
// 余额混合支付(行锁串行化保障并发资金安全)
$order = Db::transaction(function () use ($order, $order_type, $money, $user, &$mixedPayRecord) {
// 加锁读订单
$order = $order->lock(true)->find($order->id);
if (in_array($order->status, [$order::STATUS_PAID, $order::STATUS_COMPLETED])) {
$this->error('订单已支付');
}
// 余额支付
$order = $payOper->money($order, $money, $order_type);
// 事务内行级排他锁查验用户最新可用余额,杜绝并发快照双花
$lockedUser = \app\admin\model\shopro\user\User::where('id', $user->id)->lock(true)->find();
if (bccomp((string)$money, (string)$lockedUser->money, 2) === 1) {
$this->error('账户可用余额不足以进行本次抵扣');
}
$deductMoney = min($money, floatval($order->remain_pay_fee));
if ($deductMoney <= 0) {
return $order;
}
// 使用锁定的实时用户对象执行余额扣减
$lockedPayOper = new PayOper($lockedUser);
$order = $lockedPayOper->money($order, $deductMoney, $order_type);
return $order;
});
// 获取刚才产生的余额支付记录,用于异常情况冲正
$mixedPayRecord = PayModel::where('order_id', $order->id)
->where('order_type', $order_type)
->where('pay_type', 'money')
->order('id', 'desc')
->find();
if (in_array($order->status, [$order::STATUS_PAID, $order::STATUS_COMPLETED])) {
$this->success('订单支付成功', $order);
}
}
if ($payment == 'money' && $order_type == 'order') {
// 余额支付
$order = Db::transaction(function () use ($payOper, $order, $order_type) {
// 纯余额支付
$order = Db::transaction(function () use ($order, $order_type, $user) {
// 加锁读订单
$order = $order->lock(true)->find($order->id);
if (in_array($order->status, [$order::STATUS_PAID, $order::STATUS_COMPLETED])) {
$this->error('订单已支付');
}
$order = $payOper->money($order, $order->remain_pay_fee, $order_type);
$lockedUser = \app\admin\model\shopro\user\User::where('id', $user->id)->lock(true)->find();
if (bccomp((string)$order->remain_pay_fee, (string)$lockedUser->money, 2) === 1) {
$this->error('账户可用余额不足以付清该订单');
}
$lockedPayOper = new PayOper($lockedUser);
$order = $lockedPayOper->money($order, $order->remain_pay_fee, $order_type);
return $order;
});
@@ -146,7 +178,10 @@ class Pay extends Common
}
if (empty($order_data['payer']['openid'])) {
// 缺少 openid
// 缺少 openid 时,若前面预扣了余额则冲正
if ($mixedPayRecord) {
$this->rollbackMixedMoney($order, $mixedPayRecord, $user, $order_type);
}
$this->error('miss_openid', -1);
}
}
@@ -160,11 +195,18 @@ class Pay extends Common
try {
$result = $payService->pay($order_data);
} catch (\Yansongda\Pay\Exception\Exception $e) {
$this->error('支付失败' . (config('app_debug') ? ":" . $e->getMessage() : ',请重试'));
} catch (HttpResponseException $e) {
$data = $e->getResponse()->getData();
$message = $data ? ($data['msg'] ?? '') : $e->getMessage();
} catch (\Exception $e) {
// 第三方预支付异常,安全冲正本次混合支付预扣款
if ($mixedPayRecord) {
$this->rollbackMixedMoney($order, $mixedPayRecord, $user, $order_type);
}
if ($e instanceof HttpResponseException) {
$data = $e->getResponse()->getData();
$message = $data ? ($data['msg'] ?? '') : $e->getMessage();
} else {
$message = $e->getMessage();
}
$this->error('支付失败' . (config('app_debug') ? ":" . $message : ',请重试'));
}
@@ -183,6 +225,39 @@ class Pay extends Common
]);
}
/**
* 混合支付预下单异常时,冲正退回预扣余额
*
* @param \think\Model $order
* @param \think\Model $mixedPayRecord
* @param \think\Model $user
* @param string $order_type
* @return void
*/
protected function rollbackMixedMoney($order, $mixedPayRecord, $user, $order_type)
{
try {
Db::transaction(function () use ($order, $mixedPayRecord, $user, $order_type) {
\addons\shopro\service\Wallet::change($user, 'money', $mixedPayRecord->pay_fee, 'order_refund', [
'order_id' => $order->id,
'order_sn' => $order->order_sn,
'order_type' => $order_type,
'remark' => '混合支付预下单未完成,安全冲正退回'
]);
$mixedPayRecord->status = PayModel::PAY_STATUS_REFUND;
$mixedPayRecord->refund_fee = $mixedPayRecord->pay_fee;
$mixedPayRecord->save();
$order = $order->lock(true)->find($order->id);
$order->remain_pay_fee = bcadd((string)$order->remain_pay_fee, (string)$mixedPayRecord->pay_fee, 2);
$order->save();
});
} catch (\Exception $e) {
Log::write('混合支付预扣款冲正异常: ' . $e->getMessage(), 'error');
}
}
/**

查看文件

@@ -303,16 +303,18 @@ class Agent extends Commission
->column('id');
if (empty($teamUserIds)) {
$selfAgent = AgentModel::where('user_id', $agentId)->find();
$selfUser = UserModel::where('id', $agentId)->find();
return [
'total_count' => 0,
'active_count' => 0,
'expiring_count' => 0,
'inactive_count' => 0,
'partner_count' => 0,
'team_total_consume' => '0.00',
'team_total_consume' => \addons\shopro\service\partner\IdentityService::formatMoney($selfUser->total_consume ?? 0),
'team_total_reward' => '0.00',
'team_month_reward' => '0.00',
'team_order_count' => 0,
'team_order_count' => intval($selfAgent->child_order_count_0 ?? 0),
];
}
@@ -348,8 +350,17 @@ class Agent extends Commission
$inactiveCount += $missingAgentCount;
}
// 1. 团队累计自购总业绩
$teamTotalConsume = UserModel::whereIn('id', $teamUserIds)->sum('total_consume');
// 1. 团队累计自购总业绩与团队订单总数(统一使用包含本人自购的分销团队全口径)
$selfAgent = AgentModel::where('user_id', $agentId)->find();
$selfUser = UserModel::where('id', $agentId)->find();
$teamTotalConsume = isset($selfAgent->child_order_money_all) && floatval($selfAgent->child_order_money_all) > 0
? floatval($selfAgent->child_order_money_all)
: (UserModel::whereIn('id', $teamUserIds)->sum('total_consume') + floatval($selfUser->total_consume ?? 0));
$teamOrderCount = isset($selfAgent->child_order_count_all) && intval($selfAgent->child_order_count_all) > 0
? intval($selfAgent->child_order_count_all)
: ($teamOrderCount + intval($selfAgent->child_order_count_0 ?? 0));
// 2. 团队成员为当前用户贡献的累计收益与本月收益
$monthStart = strtotime(date('Y-m-01 00:00:00'));

查看文件

@@ -28,8 +28,10 @@ class Index extends Commission
->where('createtime', '>=', $monthStart)
->count();
$agent = IdentityService::attachAgent($this->service->agent);
$totalIncome = $agent['total_income'] ?? '0.00';
$this->success('ok', [
'total_income' => $totalIncome,
'month_income' => IdentityService::formatMoney($monthIncome),
'skip_count' => intval($skipCount),
'active_30d' => $agent['active_30d'] ?? true,
@@ -92,10 +94,21 @@ class Index extends Commission
}
}
$monthStart = strtotime(date('Y-m-01 00:00:00'));
$monthIncome = RewardModel::where('user_id', $userId)
->where('status', 1)
->where('createtime', '>=', $monthStart)
->whereIn('reward_type', array_merge(PartnerConfig::instantTypes(), ['venue_share', 'county_share']))
->sum('amount');
$agent = IdentityService::attachAgent($this->service->agent);
$totalIncome = $agent['total_income'] ?? '0.00';
$this->success('ok', [
'total' => $list->total(),
'per_page' => $list->listRows(),
'current_page' => $list->currentPage(),
'total_income' => $totalIncome,
'month_income' => IdentityService::formatMoney($monthIncome),
'data' => $rows,
'buyer_info' => $buyerInfo,
]);
@@ -127,6 +140,7 @@ class Index extends Commission
'madow' => $agent['madow'] ?? '0.00000000',
'madow_rate' => $agent['madow_rate'] ?? IdentityService::formatRate(null),
'madow_value' => $agent['madow_value'] ?? '0.00',
'show_madow_rate' => PartnerConfig::showMadowRate(),
'list' => $list,
]);
}

查看文件

@@ -84,7 +84,20 @@ class User extends Common
$agent = \addons\shopro\service\partner\IdentityService::findAgent($user->id);
$partner = \addons\shopro\service\partner\IdentityService::attachProfile($agent);
if (empty($partner['total_income']) || $partner['total_income'] === '0.00') {
$userRewardCash = \app\admin\model\shopro\partner\Reward::where('user_id', $user->id)
->where('status', 1)
->where('amount', '>', 0)
->sum('amount');
if ($userRewardCash > 0) {
$formatted = \addons\shopro\service\partner\IdentityService::formatMoney($userRewardCash);
$partner['total_income'] = $formatted;
$partner['income_total_cash'] = $formatted;
}
}
$data = array_merge($user->toArray(), $partner);
// 对齐用户余额字段:统一映射商城余额,避免前端不同字段读取出现口径偏差
$data['balance'] = $user->money;
$this->success('个人详情', $data);
}

查看文件

@@ -19,20 +19,102 @@ class WalletLog extends Common
$list_rows = $this->request->param('list_rows', 10);
$date = $this->request->param('date/a');
$user = auth_user();
$where['user_id'] = $user->id;
$rewardEvents = [
'push3', 'maker_diff', 'maker_peer', 'maker_overtaken',
'team_venue', 'team_county', 'venue_peer', 'county_peer',
'venue_share', 'county_share', 'reward_income', 'transfer_by_commission', 'transfer_to_money'
];
$baseQuery = function () use ($user, $type, $rewardEvents) {
$model = UserWalletLogModel::where('user_id', $user->id);
if ($type === 'commission') {
// 收益记录:既包含历史 commission 流水,也对齐直入 money 的收益分成流水
$model->where(function ($query) use ($rewardEvents) {
$query->where('type', 'commission')
->whereOr(function ($sub) use ($rewardEvents) {
$sub->where('type', 'money')->whereIn('event', $rewardEvents);
});
});
} else {
$model->where('type', $type);
}
return $model;
};
$filterQuery = $baseQuery();
if (!empty($date) && is_array($date) && count($date) === 2) {
$filterQuery->whereTime('createtime', 'between', $date);
}
switch ($tab) {
case 'reward':
$filterQuery->where('amount', '>', 0)->whereIn('event', $rewardEvents);
break;
case 'income':
$where['amount'] = ['>', 0];
$filterQuery->where('amount', '>', 0);
break;
case 'expense':
$where['amount'] = ['<', 0];
$filterQuery->where('amount', '<', 0);
break;
}
$income = UserWalletLogModel::where('user_id', $user->id)->{$type}()->where('amount', '>', 0)->whereTime('createtime', 'between', $date)->sum('amount');
$expense = UserWalletLogModel::where('user_id', $user->id)->{$type}()->where('amount', '<', 0)->whereTime('createtime', 'between', $date)->sum('amount');
$logs = UserWalletLogModel::where($where)->{$type}()->whereTime('createtime', 'between', $date)->order('createtime', 'desc')->paginate($list_rows);
$this->success('获取成功', ['list' => $logs, 'income' => $income, 'expense' => $expense]);
// 统计收入与支出(统一统计口径,避免内部互转重叠统计造成误导)
$incomeQuery = $baseQuery();
$expenseQuery = $baseQuery();
$rewardQuery = $baseQuery();
if (!empty($date) && is_array($date) && count($date) === 2) {
$incomeQuery->whereTime('createtime', 'between', $date);
$expenseQuery->whereTime('createtime', 'between', $date);
$rewardQuery->whereTime('createtime', 'between', $date);
}
$actualRewardEvents = [
'push3', 'maker_diff', 'maker_peer', 'maker_overtaken',
'team_venue', 'team_county', 'venue_peer', 'county_peer',
'venue_share', 'county_share', 'reward_income'
];
if ($type === 'commission') {
// 收益流水统计口径对齐:
// 1. 真实收益(总收入):排除内部互转入账事件 transfer_by_commission,避免佣金转入余额时重复计入收益
// 2. 真实扣减(总支出):排除内部结转转出事件 transfer_to_money 与 commission_transfer,避免误导用户认为产生了消费支出
$income = (float) $incomeQuery->where('amount', '>', 0)
->where(function ($q) use ($actualRewardEvents) {
$q->where(function ($sub) use ($actualRewardEvents) {
$sub->where('type', 'money')->whereIn('event', $actualRewardEvents);
})->whereOr(function ($sub) {
$sub->where('type', 'commission')->whereNotIn('event', ['transfer_by_commission']);
});
})->sum('amount');
$expense = (float) $expenseQuery->where('amount', '<', 0)
->whereNotIn('event', ['transfer_to_money', 'commission_transfer'])
->sum('amount');
$rewardIncome = (float) $rewardQuery->where('amount', '>', 0)
->where(function ($q) use ($actualRewardEvents) {
$q->where(function ($sub) use ($actualRewardEvents) {
$sub->where('type', 'money')->whereIn('event', $actualRewardEvents);
})->whereOr(function ($sub) {
$sub->where('type', 'commission')->whereNotIn('event', ['transfer_by_commission']);
});
})->sum('amount');
} else {
$income = (float) $incomeQuery->where('amount', '>', 0)->sum('amount');
$expense = (float) $expenseQuery->where('amount', '<', 0)->sum('amount');
$rewardIncome = (float) $rewardQuery->where('amount', '>', 0)->whereIn('event', $actualRewardEvents)->sum('amount');
}
$logs = $filterQuery->order('id', 'desc')->paginate($list_rows);
$this->success('获取成功', [
'list' => $logs,
'income' => $income,
'expense' => $expense,
'reward_income' => $rewardIncome,
]);
}
}

查看文件

@@ -38,12 +38,9 @@ class Partner
\addons\shopro\service\partner\RateService::clearCache();
$userId = $order['user_id'] ?? ($params['user']['id'] ?? 0);
if ($userId) {
$agent = new AgentService($userId);
if (method_exists($agent, 'touchLastSelfOrderTime')) {
$agent->touchLastSelfOrderTime();
} else {
$service->touchSelfOrder($userId);
}
// 自购与直推订单双向保活(自购更新买家,直推更新一级推荐人)
$paidTime = !empty($order['paid_time']) ? intval($order['paid_time']) : time();
$service->touchOrderTimes($userId, $paidTime);
}
Queue::push('\addons\shopro\job\PartnerSettle@order', [
'order_id' => $order['id'],

查看文件

@@ -38,7 +38,7 @@ class Goods
if ($this->commissionGoods) {
$commission_config = $this->commissionGoods->commission_config;
if ($commission_config['status']) {
if (!empty($commission_config) && !empty($commission_config['status'])) {
$this->commissionConfig = $commission_config;
}
switch ($this->commissionGoods->self_rules) {
@@ -112,10 +112,12 @@ class Goods
$commissionRules = [];
foreach ($agentLevelRules as $agentLevel => $rule) {
$rule = json_decode($rule, true);
foreach ($rule as $commission_level => $percent) {
$commission_level = explode('_', $commission_level);
$level = intval($commission_level[1]);
$commissionRules[$agentLevel][$level] = ['rate' => $percent];
if (is_array($rule)) {
foreach ($rule as $commission_level => $percent) {
$commission_level = explode('_', $commission_level);
$level = intval($commission_level[1] ?? 1);
$commissionRules[$agentLevel][$level] = ['rate' => $percent];
}
}
}
return $commissionRules;

查看文件

@@ -71,8 +71,8 @@ class Order
return false;
}
// 是否自购分销订单
$this->selfBuy = $this->buyer->isAgentAvaliable() && $this->config->isSelfBuy();
// 是否自购分销订单(收益中心模式或开启自购时,分销商本人订单均记为自购订单以累积团队业绩)
$this->selfBuy = $this->buyer->isAgentAvaliable() && ($this->config->isSelfBuy() || boolval(sheep_config('shop.commission.partner_mode')));
// 未找到上级分销商且不是自购
if (!$this->buyer->getParentUserId() && !$this->selfBuy) {
@@ -202,7 +202,7 @@ class Order
'buyer_id' => $commissionOrder->buyer_id, // 购买人
'commission_order_id' => $commissionOrder->id, // 分销订单ID
'agent_id' => $currentAgent->user->id, // 待分佣分销商ID
'type' => 'commission', // 奖金类型
'type' => \addons\shopro\service\partner\PartnerConfig::rewardWalletType(), // 奖金类型
'commission' => $commission, // 佣金
'status' => 0, // 佣金状态
'original_commission' => $commission, // 原始佣金

查看文件

@@ -36,11 +36,20 @@ class ActiveService
return $this->hasQualifiedOrder($userId, $start, $at);
}
/**
* 判断指定用户在时间窗口内是否有有效订单(本人自购或直推下级合格订单)
*/
public function hasQualifiedOrder($userId, $start, $end)
{
if (!$userId) {
return false;
}
$rateService = new RateService();
$directChildIds = \think\Db::name('user')->where('parent_user_id', $userId)->column('id');
$candidateUserIds = array_merge([$userId], $directChildIds);
$order = $rateService->qualifiedOrderQuery($start, $end)
->where('o.user_id', $userId)
->whereIn('o.user_id', $candidateUserIds)
->find();
return (bool) $order;
}
@@ -70,6 +79,7 @@ class ActiveService
if (!empty($nullUserIds)) {
$rateService = new RateService();
// 2.1 自购订单命中
$orderHits = $rateService->qualifiedOrderQuery($start, $end)
->whereIn('o.user_id', $nullUserIds)
->group('o.user_id')
@@ -79,8 +89,67 @@ class ActiveService
\think\Db::name('shopro_commission_agent')->where('user_id', $uId)->update(['last_self_order_time' => $lastTime]);
$hitUserIds[] = intval($uId);
}
// 2.2 直推下级订单命中(针对仍未命中的代理商)
$remainingNullIds = array_diff($nullUserIds, array_keys($orderHits));
if (!empty($remainingNullIds)) {
$userTable = \think\Db::name('user')->getTable();
$directHits = $rateService->qualifiedOrderQuery($start, $end)
->join($userTable . ' u', 'u.id = o.user_id')
->whereIn('u.parent_user_id', $remainingNullIds)
->group('u.parent_user_id')
->column('max(o.paid_time)', 'u.parent_user_id');
foreach ($directHits as $pId => $lastTime) {
\think\Db::name('shopro_commission_agent')->where('user_id', $pId)->update(['last_self_order_time' => $lastTime]);
$hitUserIds[] = intval($pId);
}
}
}
return array_values(array_unique(array_map('intval', $hitUserIds)));
}
/**
* 批量校准所有分销商的有效订单时间(自购及直推合格订单最大值回填)
*/
public function syncActiveTimes($sinceTime = null)
{
$rateService = new RateService();
$userTable = \think\Db::name('user')->getTable();
// 1. 本人自购最新合格订单时间
$selfQuery = $rateService->qualifiedOrderQuery($sinceTime)
->group('o.user_id')
->column('max(o.paid_time)', 'o.user_id');
// 2. 直推下级最新合格订单时间
$directQuery = $rateService->qualifiedOrderQuery($sinceTime)
->join($userTable . ' u', 'u.id = o.user_id')
->where('u.parent_user_id', '>', 0)
->group('u.parent_user_id')
->column('max(o.paid_time)', 'u.parent_user_id');
// 3. 汇总取最大值
$allUserIds = array_unique(array_merge(array_keys($selfQuery), array_keys($directQuery)));
$updated = 0;
foreach ($allUserIds as $uId) {
$selfTime = intval($selfQuery[$uId] ?? 0);
$directTime = intval($directQuery[$uId] ?? 0);
$maxTime = max($selfTime, $directTime);
if ($maxTime > 0) {
$agent = \think\Db::name('shopro_commission_agent')->where('user_id', $uId)->find();
if ($agent && $maxTime > intval($agent['last_self_order_time'] ?? 0)) {
\think\Db::name('shopro_commission_agent')->where('user_id', $uId)->update([
'last_self_order_time' => $maxTime,
]);
$updated++;
}
}
}
return $updated;
}
}

查看文件

@@ -373,6 +373,7 @@ class DailySettleService
}
$each = function_exists('bcdiv') ? bcdiv((string) $pool, (string) $count, 2) : number_format($pool / $count, 2, '.', '');
$distributed = 0;
$walletType = PartnerConfig::rewardWalletType();
foreach ($userIds as $userId) {
PartnerRewardService::write([
'order_id' => $orderId,
@@ -382,11 +383,14 @@ class DailySettleService
'amount' => $each,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "{$label}奖池 {$pool} / {$count} = {$each}", 'share_user_count' => $count],
'ext' => [
'formula' => "{$label}奖池 {$pool} / {$count} = {$each}",
'share_user_count' => $count,
'wallet_type' => $walletType,
],
'status' => 1,
]);
if ((float) $each > 0) {
$walletType = PartnerConfig::rewardWalletType();
Wallet::change($userId, $walletType, $each, $type, [
'settle_date' => $settleDate,
]);
@@ -404,7 +408,10 @@ class DailySettleService
'amount' => $tail,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "{$label}尾差 {$tail} 进平台"],
'ext' => [
'formula' => "{$label}尾差 {$tail} 进平台",
'wallet_type' => 'system',
],
'status' => 1,
]);
}
@@ -434,7 +441,11 @@ class DailySettleService
'amount' => $pool,
'base_amount' => $pool,
'settle_date' => null,
'ext' => ['formula' => "{$label}分母为0,奖池 {$pool} 进平台", 'orders' => $orderIds],
'ext' => [
'formula' => "{$label}分母为0,奖池 {$pool} 进平台",
'orders' => $orderIds,
'wallet_type' => 'system',
],
'status' => 1,
]);
return ['pool' => $pool, 'count' => 0, 'each' => '0.00'];
@@ -442,6 +453,7 @@ class DailySettleService
$each = function_exists('bcdiv') ? bcdiv((string) $pool, (string) $count, 2) : number_format($pool / $count, 2, '.', '');
$distributed = 0;
$walletType = PartnerConfig::rewardWalletType();
foreach ($userIds as $userId) {
PartnerRewardService::write([
@@ -453,11 +465,16 @@ class DailySettleService
'amount' => $each,
'base_amount' => $pool,
'settle_date' => null,
'ext' => ['formula' => "{$label}奖池 {$pool} / {$count} = {$each}", 'share_user_count' => $count, 'pool' => $pool, 'orders' => $orderIds],
'ext' => [
'formula' => "{$label}奖池 {$pool} / {$count} = {$each}",
'share_user_count' => $count,
'pool' => $pool,
'orders' => $orderIds,
'wallet_type' => $walletType,
],
'status' => 1,
]);
if ((float) $each > 0) {
$walletType = PartnerConfig::rewardWalletType();
Wallet::change($userId, $walletType, $each, $type, [
'minute_settle' => 1,
'orders' => $orderIds,
@@ -478,7 +495,11 @@ class DailySettleService
'amount' => $tail,
'base_amount' => $pool,
'settle_date' => null,
'ext' => ['formula' => "{$label}尾差 {$tail} 进平台", 'orders' => $orderIds],
'ext' => [
'formula' => "{$label}尾差 {$tail} 进平台",
'orders' => $orderIds,
'wallet_type' => 'system',
],
'status' => 1,
]);
}

查看文件

@@ -153,7 +153,17 @@ class IdentityService
}
$data = is_object($agent) ? $agent->toArray() : $agent;
$userId = intval($data['user_id'] ?? 0);
$agentTotalIncome = floatval($data['total_income'] ?? 0);
$rewardCash = $userId > 0 ? \app\admin\model\shopro\partner\Reward::where('user_id', $userId)
->where('status', 1)
->where('amount', '>', 0)
->sum('amount') : 0;
$unifiedTotalIncome = max($agentTotalIncome, floatval($rewardCash));
return array_merge($data, $identity, [
'total_income' => self::formatMoney($unifiedTotalIncome),
'income_total_cash' => self::formatMoney($unifiedTotalIncome),
'is_venue' => intval($data['is_venue'] ?? 0),
'is_county' => intval($data['is_county'] ?? 0),
'county_code' => (string) ($data['county_code'] ?? ''),
@@ -161,6 +171,7 @@ class IdentityService
'madow' => self::formatMadow($madow),
'madow_rate' => self::formatRate($rate),
'madow_value' => self::formatMoney((float) $madow * (float) $rate),
'show_madow_rate' => PartnerConfig::showMadowRate(),
'voucher_total' => self::formatMoney($total),
'voucher_released' => self::formatMoney($released),
'voucher_used' => self::formatMoney($used),
@@ -190,6 +201,9 @@ class IdentityService
'madow' => '0',
'madow_rate' => self::formatRate($baseRate),
'madow_value' => '0.00',
'show_madow_rate' => PartnerConfig::showMadowRate(),
'total_income' => '0.00',
'income_total_cash' => '0.00',
'voucher_available' => '0.00',
'active_30d' => true,
'active_status' => 'inactive',
@@ -211,9 +225,12 @@ class IdentityService
'maker_level_name' => $full['maker_level_name'],
'role_names' => $roleNames,
'custom_role_names' => $roleNames,
'total_income' => $full['total_income'] ?? '0.00',
'income_total_cash' => $full['income_total_cash'] ?? '0.00',
'madow' => $full['madow'],
'madow_rate' => $full['madow_rate'],
'madow_value' => $full['madow_value'],
'show_madow_rate' => $full['show_madow_rate'] ?? PartnerConfig::showMadowRate(),
'voucher_available' => $full['voucher_available'],
'active_30d' => $full['active_30d'],
'active_status' => $full['active_status'] ?? 'inactive',

查看文件

@@ -40,6 +40,15 @@ class PartnerConfig
return $enable === null ? true : (bool) $enable;
}
public static function showMadowRate()
{
$show = self::get('partner_show_madow_rate', 1);
if ($show === null || $show === '') {
return 1;
}
return intval($show) ? 1 : 0;
}
public static function activeDays()
{
$days = intval(self::get('partner_active_days', 30));
@@ -97,18 +106,20 @@ class PartnerConfig
$maker = $roles['maker'];
$venue = $roles['venue'];
$county = $roles['county'];
$countyShort = in_array($county, ['区县代理', '区县']) ? '区县' : $county;
$countyAgentShort = in_array($county, ['区县代理', '区县']) ? '区县代' : $county;
return [
'push3' => '推荐开拓奖',
'push3' => '推荐提成',
'maker_diff' => $maker . '进阶奖',
'maker_peer' => $maker . '协同奖',
'maker_overtaken' => $maker . '卓越奖',
'team_venue' => $venue . '运营奖',
'team_county' => $county . '统筹奖',
'venue_peer' => $venue . '协同奖',
'county_peer' => $county . '协同奖',
'venue_share' => $venue . '加权奖励',
'county_share' => $county . '加权奖励',
'team_venue' => $venue . '管理奖',
'team_county' => $countyShort . '管理奖',
'venue_peer' => $venue . '平级奖',
'county_peer' => $countyAgentShort . '平级奖',
'venue_share' => $venue . '加权奖',
'county_share' => $countyShort . '加权奖',
'madow_share' => '每日贡献马豆',
'admin_madow' => '管理员调整马豆',
'voucher_grant' => '消费补贴发放',
@@ -139,13 +150,13 @@ class PartnerConfig
'partner_off' => '结算未开启',
];
$user = [
'no_parent' => '暂无推荐人,不计提推荐开拓奖',
'self_buy' => '本人下单不计提推荐开拓奖',
'no_parent' => '暂无推荐人,不计提推荐提成',
'self_buy' => '本人下单不计提推荐提成',
'inactive_30d' => '需 30 日内有本人订单才能领取奖励',
'not_maker' => '',
'not_venue' => '',
'not_county' => '',
'cap_not_higher' => '同阶不计进阶差额,享受协同奖励',
'cap_not_higher' => '同阶不计进阶差额,享受平级奖励',
'already_settled' => '',
'partner_goods_off' => '',
'partner_off' => '',

查看文件

@@ -310,6 +310,10 @@ class PartnerRewardService
public static function account($order, $buyerId, $userId, $type, $role, $amount, $base, $ext = [])
{
$orderId = is_array($order) || $order instanceof \think\Model ? ($order['id'] ?? 0) : intval($order);
$walletType = PartnerConfig::rewardWalletType();
if (!isset($ext['wallet_type'])) {
$ext['wallet_type'] = $walletType;
}
$row = self::write([
'order_id' => $orderId,
'buyer_id' => $buyerId,
@@ -322,7 +326,6 @@ class PartnerRewardService
'status' => 1,
]);
if ($row && self::$lastWriteCreated && (float) $amount > 0 && $userId > 0 && $row->status == 1 && in_array($type, PartnerConfig::instantTypes())) {
$walletType = PartnerConfig::rewardWalletType();
Wallet::change($userId, $walletType, $amount, $type, [
'partner_reward_id' => $row->id,
'order_id' => $orderId,

查看文件

@@ -3,7 +3,7 @@
namespace addons\shopro\service\partner;
/**
* 酒道馆 / 区县协同奖 10% 逐代递减级联,最低发放不能少于 0.10 元截断
* 酒道馆 / 区县代平级奖 10% 逐代递减级联,最低发放不能少于 0.10 元截断
*/
class PeerShareReward
{
@@ -66,7 +66,7 @@ class PeerShareReward
$type,
$role,
'inactive_30d',
"{$label}协同(第{$gen}代) 30 日无自购"
"{$label}平级(第{$gen}代) 30 日无自购"
);
} else {
PartnerRewardService::account(
@@ -79,7 +79,7 @@ class PeerShareReward
$currentBase,
[
'generation' => $gen,
'formula' => "{$label}协同(第{$gen}代) {$currentBase} × " . ($rate * 100) . "% = {$amount}",
'formula' => "{$label}平级(第{$gen}代) {$currentBase} × " . ($rate * 100) . "% = {$amount}",
'from_user_id' => $sourceUserId,
]
);

查看文件

@@ -5,18 +5,18 @@ namespace addons\shopro\service\partner;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 推荐开拓奖:398/400/600 循环,计到推荐人,自购不发
* 推荐提成:398/400/600 循环,计到推荐人,自购不发
*/
class Push3Reward
{
public function run($order, $buyerId, $parent, ActiveService $active, $rules = null)
{
if (!$parent) {
PartnerRewardService::writeSkip($order, $buyerId, 0, 'push3', 'taster', 'no_parent', '暂无推荐人,不计提推荐开拓奖');
PartnerRewardService::writeSkip($order, $buyerId, 0, 'push3', 'taster', 'no_parent', '暂无推荐人,不计提推荐提成');
return;
}
if (intval($parent['user_id']) === intval($buyerId)) {
PartnerRewardService::writeSkip($order, $buyerId, $parent['user_id'], 'push3', 'taster', 'self_buy', '本人下单不计提推荐开拓奖');
PartnerRewardService::writeSkip($order, $buyerId, $parent['user_id'], 'push3', 'taster', 'self_buy', '本人下单不计提推荐提成');
return;
}
if (intval($parent['level']) < 1) {
@@ -42,7 +42,7 @@ class Push3Reward
$amount = $amounts[($seq - 1) % 3];
PartnerRewardService::account($order, $buyerId, $agent->user_id, 'push3', 'taster', $amount, $amount, [
'formula' => "推荐开拓第{$seq}单,循环第" . ((($seq - 1) % 3) + 1) . "档 +{$amount}",
'formula' => "推荐提成第{$seq}单,循环第" . ((($seq - 1) % 3) + 1) . "档 +{$amount}",
'seq' => $seq,
]);
}

查看文件

@@ -3,7 +3,7 @@
namespace addons\shopro\service\partner;
/**
* 统筹运营奖励:无馆有县=100;有馆有县=50+50;有馆无县=50
* 渠道管理奖(馆/县拆分):无馆有县=100;有馆有县=50+50;有馆无县=50
*/
class TeamSplitReward
{
@@ -30,7 +30,7 @@ class TeamSplitReward
PartnerRewardService::writeSkip($order, $buyerId, $venue['user_id'], 'team_venue', 'venue', 'inactive_30d', '酒道馆 30 日无自购');
} else {
PartnerRewardService::account($order, $buyerId, $venue['user_id'], 'team_venue', 'venue', $venueSplit, $venueSplit, [
'formula' => "酒道馆运营奖 {$venueSplit}",
'formula' => "酒道馆管理奖 {$venueSplit}",
]);
$result['venue'] = ['user_id' => $venue['user_id'], 'amount' => $venueSplit, 'index' => $venue['index']];
}
@@ -41,8 +41,11 @@ class TeamSplitReward
if ($county['inactive']) {
PartnerRewardService::writeSkip($order, $buyerId, $county['user_id'], 'team_county', 'county', 'inactive_30d', '区县 30 日无自购');
} else {
$formulaText = $venue
? (($venue['user_id'] == $county['user_id']) ? "区县管理奖 {$amount}(馆兼县)" : "区县管理奖 {$amount}(馆上)")
: "区县管理奖 {$amount}(直达)";
PartnerRewardService::account($order, $buyerId, $county['user_id'], 'team_county', 'county', $amount, $amount, [
'formula' => $venue ? "区县统筹奖 {$amount}(馆上)" : "区县统筹奖 {$amount}(直达)",
'formula' => $formulaText,
]);
$result['county'] = ['user_id' => $county['user_id'], 'amount' => $amount, 'index' => $county['index']];
}
@@ -71,7 +74,8 @@ class TeamSplitReward
protected function nearestCounty($chain, $venue, ActiveService $active)
{
$start = $venue ? ($venue['index'] + 1) : 0;
// 若酒道馆节点本身兼任区县代理,允许从该酒道馆节点开始匹配(兼具双重身份场景);若未兼任,循环会自动检查其上一级
$start = $venue ? $venue['index'] : 0;
for ($i = $start; $i < count($chain); $i++) {
if (!intval($chain[$i]['is_county'] ?? 0)) {
continue;

查看文件

@@ -0,0 +1,141 @@
<?php
namespace addons\shopro\service\partner;
use think\Db;
use app\admin\model\shopro\user\User as UserModel;
use addons\shopro\service\Wallet;
/**
* 历史收益全量结转至商城余额服务
*/
class WalletMigrationService
{
/**
* 结转前数据预览(只读试算)
*
* @return array
*/
public function preview()
{
$query = UserModel::where('commission', '>', 0);
$totalCount = (int) $query->count();
$totalCommission = (float) $query->sum('commission');
$sampleList = UserModel::where('commission', '>', 0)
->field('id,nickname,mobile,money,commission')
->order('commission', 'desc')
->limit(20)
->select();
$samples = [];
foreach ($sampleList as $u) {
$samples[] = [
'id' => (int) $u->id,
'nickname' => (string) ($u->nickname ?: '用户' . $u->id),
'mobile' => (string) ($u->mobile ?: ''),
'current_money' => number_format((float) $u->money, 2, '.', ''),
'current_commission' => number_format((float) $u->commission, 2, '.', ''),
'target_money' => number_format((float) bcadd((string) $u->money, (string) $u->commission, 2), 2, '.', ''),
];
}
return [
'total_users' => $totalCount,
'total_commission' => number_format($totalCommission, 2, '.', ''),
'samples' => $samples,
];
}
/**
* 执行全量结转:将所有会员的 commission 余额转入 money 钱包
*
* @param bool $isDryRun 是否只读模拟
* @param callable|null $progressCallback 进度回调
* @param array $operator 操作人上下文
* @return array
*/
public function transferAll($isDryRun = false, $progressCallback = null, $operator = [])
{
if ($isDryRun) {
$preview = $this->preview();
return [
'status' => 'dry_run',
'dry_run' => true,
'total_users' => $preview['total_users'],
'transferred_amount' => $preview['total_commission'],
'success_count' => 0,
'fail_count' => 0,
'errors' => [],
'preview' => $preview,
];
}
$userIds = UserModel::where('commission', '>', 0)->order('id', 'asc')->column('id');
$totalUsers = count($userIds);
$successCount = 0;
$failCount = 0;
$transferredAmount = '0.00';
$errors = [];
foreach ($userIds as $idx => $userId) {
try {
$transferResult = Db::transaction(function () use ($userId) {
$user = UserModel::where('id', $userId)->lock(true)->find();
if (!$user) {
return 0.0;
}
$amount = floatval($user->commission);
if ($amount <= 0) {
return 0.0;
}
// 1. 扣减佣金钱包
Wallet::change($user, 'commission', -$amount, 'transfer_to_money', [
'batch_migration' => 1,
'reason' => '全量历史收益结转至商城余额',
], '收益结转至商城余额');
// 2. 增加商城余额
Wallet::change($user, 'money', $amount, 'transfer_by_commission', [
'batch_migration' => 1,
'reason' => '全量历史收益结转至商城余额',
], '收益结转至商城余额');
return $amount;
});
if ($transferResult > 0) {
$successCount++;
$transferredAmount = bcadd($transferredAmount, (string) $transferResult, 2);
}
if (is_callable($progressCallback)) {
$progressCallback($idx + 1, $totalUsers, $userId, $transferResult, null);
}
} catch (\Throwable $e) {
$failCount++;
$errItem = [
'user_id' => $userId,
'error' => $e->getMessage(),
];
$errors[] = $errItem;
if (is_callable($progressCallback)) {
$progressCallback($idx + 1, $totalUsers, $userId, 0.0, $e->getMessage());
}
}
}
return [
'status' => 'completed',
'dry_run' => false,
'total_users' => $totalUsers,
'success_count' => $successCount,
'fail_count' => $failCount,
'transferred_amount' => number_format((float) $transferredAmount, 2, '.', ''),
'errors' => $errors,
];
}
}

查看文件

@@ -246,6 +246,7 @@ INSERT INTO `__PREFIX__shopro_config` (`code`, `parent_code`, `name`, `descripti
('shop.commission.partner_chain_max_depth', 'shop.commission', '关系链最大追溯层级', '向上寻找创客/酒道馆/区县时的最大关系链深度', 'int', '50', NULL, NULL, 84),
('shop.commission.partner_push3_amounts', 'shop.commission', '推三返一循环金额配置', '品酒师推荐直推合格单获得的阶梯奖励金额循环数组', 'array', '[398,400,600]', NULL, NULL, 85),
('shop.commission.partner_madow_mode', 'shop.commission', '每日GMV分润模式', 'madow=以马豆形式发放 cash=直接以佣金现金发放', 'string', 'madow', NULL, NULL, 86),
('shop.commission.partner_show_madow_rate', 'shop.commission', '显示马币市值胶囊', '控制移动端我的马豆页面是否显示马币市值胶囊 1=显示 0=隐藏', 'int', '1', NULL, NULL, 86),
('shop.commission.partner_madow_base_rate', 'shop.commission', '马豆基准汇率', '大盘初始起步汇率 (元/马豆)', 'string', '0.00000075', NULL, NULL, 87),
('shop.commission.partner_madow_step_orders', 'shop.commission', '马豆汇率步进单数', '每达成指定合格订单数,马豆大盘汇率递增1个基数', 'int', '1', NULL, NULL, 88),
('shop.commission.partner_voucher_times', 'shop.commission', '买酒赠送兑换券倍数', '符合条件的订单实付金额倍数,默认1.5倍', 'float', '1.5', NULL, NULL, 89),