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

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

查看文件

@@ -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,
];
}
}