比较提交

..

12 次代码提交

作者 SHA1 备注 提交日期
chen
ecdee1f53a fix(partner): 创客协同第1代按下级实得进阶奖计算
同级第1代不再用等级标准基数,改为下级本单实际拿到的创客进阶奖乘比例。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 08:58:26 +08:00
chen
092155c645 fix(partner): 县在馆下时区县拿全额,县以上酒道馆不再发管理奖
后续订单按离买家最近的县结算;馆在县下或同一人时仍按 50+50。已入账订单不重算。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:42:58 +08:00
chen
ba33584936 fix(restore): 完善审核恢复脚本中模板2的deletetime清理与Tabbar校验 2026-09-30 18:43:18 +08:00
chen
21e4230819 fix(category): 修复分类接口优雅降级兜底机制并完善审核3C商品分类与过审一键恢复脚本 2026-09-30 18:19:30 +08:00
chen
3a7c13f026 fix(commission): 优化分销商升级锁定开关与雷达标识文案提示,防止误锁定升级 2026-09-29 21:28:39 +08:00
chen
511a8cb485 fix(commission): 修复分销商升级规则中下级分销商等级未向上兼容累计统计导致无法晋升的问题 2026-09-29 16:07:47 +08:00
chen
6bd497f980 fix(commission): 清理 detail.html 中多余的闭合标签 el-tab-pane 2026-09-29 15:37:26 +08:00
chen
a7a8e3e494 fix(commission): 优化拓扑BFS防环遍历与升级考核直推有效品酒师指标 2026-09-29 15:25:31 +08:00
chen
dbb9951857 feat(commission): 重构分销商详情运营统计看板紧扣恒联业务与方案B一体化大余额 2026-09-29 15:07:07 +08:00
chen
40f36c8889 fix(settle): 恢复收益中心与兑换券释放为原日结结算时间 2026-09-28 11:06:35 +08:00
chen
30b704f581 feat(ops): 归档投产前全量测试数据清理SQL脚本与自动化运维程序 2026-09-28 10:27:05 +08:00
chen
cacd1acac0 feat(goods): 增加微信小程序审核专用真实3C产品与分类线上生成及验证脚本 2026-09-26 16:13:50 +08:00
共有 21 个文件被更改,包括 2957 次插入 和 298 次删除

查看文件

@@ -14,19 +14,19 @@ class PartnerSettle extends Command
protected function configure() protected function configure()
{ {
$this->setName('shopro:partner:settle') $this->setName('shopro:partner:settle')
->addOption('date', 'd', Option::VALUE_OPTIONAL, '结算日期 Y-m-d,指定日期时执行传统日结') ->addOption('date', 'd', Option::VALUE_OPTIONAL, '结算日期 Y-m-d,默认昨天')
->addOption('rerun', 'r', Option::VALUE_NONE, '删除当天日结后重算') ->addOption('rerun', 'r', Option::VALUE_NONE, '删除当天日结后重算')
->addOption('daily', null, Option::VALUE_NONE, '强制执行昨天标准日结') ->addOption('minute', 'm', Option::VALUE_NONE, '执行分钟级增量结算与兑换券释放(联调测试用)')
->addOption('compensate', 'c', Option::VALUE_NONE, '执行未结算订单自动对账与补偿发放') ->addOption('compensate', 'c', Option::VALUE_NONE, '执行未结算订单自动对账与补偿发放')
->addOption('check', null, Option::VALUE_NONE, '收益中心与队列运行健康度体检诊断') ->addOption('check', null, Option::VALUE_NONE, '收益中心与队列运行健康度体检诊断')
->setDescription('收益中心结算(默认1分钟dmepa增量结算与兑换券释放,支持指定日期日结及未结算补偿)'); ->setDescription('收益中心日结(DMEPA/馆县均分/兑换券释放,默认每日结算昨天)');
} }
protected function execute(Input $input, Output $output) protected function execute(Input $input, Output $output)
{ {
$date = $input->getOption('date'); $date = $input->getOption('date');
$rerun = (bool) $input->getOption('rerun'); $rerun = (bool) $input->getOption('rerun');
$isDaily = (bool) $input->getOption('daily'); $isMinute = (bool) $input->getOption('minute');
$isCompensate = (bool) $input->getOption('compensate'); $isCompensate = (bool) $input->getOption('compensate');
$isCheck = (bool) $input->getOption('check'); $isCheck = (bool) $input->getOption('check');
@@ -46,34 +46,34 @@ class PartnerSettle extends Command
return 0; return 0;
} }
// 3. 指定日期或强制日结模式(前置自动执行补偿,确保无漏单) // 3. 显式指定分钟级调度模式(联调调试测试)
if ($date || $isDaily || $rerun) { if ($isMinute) {
$settleDate = $date ?: date('Y-m-d', strtotime('-1 day')); $output->writeln('[' . date('Y-m-d H:i:s') . '] partner minute settle start');
$output->writeln('partner daily settle start ' . $settleDate . ($rerun ? ' rerun' : ''));
try { try {
// 日结前置:扫描并补偿未结算即时奖订单,避免影响大盘 GMV 统计与分红池 $result = (new DailySettleService())->runMinute();
$compensateReport = (new PartnerCompensateService())->compensateAll(100); $output->writeln('[' . date('Y-m-d H:i:s') . '] partner minute settle done: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
if (!empty($compensateReport['success_count'])) {
$output->writeln(" [✓] 日结前置补偿已完成: 成功补发 {$compensateReport['success_count']} 笔订单即时奖");
}
$report = (new DailySettleService())->run($date, $rerun);
$output->writeln('partner daily settle done: ' . json_encode($report ? $report->toArray() : [], JSON_UNESCAPED_UNICODE));
return 0; return 0;
} catch (\Exception $e) { } catch (\Exception $e) {
$output->writeln('partner daily settle fail: ' . $e->getMessage()); $output->writeln('[' . date('Y-m-d H:i:s') . '] partner minute settle fail: ' . $e->getMessage());
return 1; return 1;
} }
} }
// 4. 默认执行 1 分钟dmepa增量结算与兑换券释放 // 4. 默认原标准日结模式(每日凌晨结算昨天,支持 -d 指定日期与 -r 重跑)
$output->writeln('[' . date('Y-m-d H:i:s') . '] partner minute settle start'); $settleDate = $date ?: date('Y-m-d', strtotime('-1 day'));
$output->writeln('partner daily settle start ' . $settleDate . ($rerun ? ' rerun' : ''));
try { try {
$result = (new DailySettleService())->runMinute(); // 日结前置:扫描并补偿未结算即时奖订单,避免影响大盘 GMV 统计与分红池
$output->writeln('[' . date('Y-m-d H:i:s') . '] partner minute settle done: ' . json_encode($result, JSON_UNESCAPED_UNICODE)); $compensateReport = (new PartnerCompensateService())->compensateAll(100);
if (!empty($compensateReport['success_count'])) {
$output->writeln(" [✓] 日结前置补偿已完成: 成功补发 {$compensateReport['success_count']} 笔订单即时奖");
}
$report = (new DailySettleService())->run($date, $rerun);
$output->writeln('partner daily settle done: ' . json_encode($report ? $report->toArray() : [], JSON_UNESCAPED_UNICODE));
return 0; return 0;
} catch (\Exception $e) { } catch (\Exception $e) {
$output->writeln('[' . date('Y-m-d H:i:s') . '] partner minute settle fail: ' . $e->getMessage()); $output->writeln('partner daily settle fail: ' . $e->getMessage());
return 1; return 1;
} }
} }

查看文件

@@ -13,12 +13,15 @@ class Category extends Common
public function index() public function index()
{ {
$id = $this->request->param('id', 0); $id = $this->request->param('id', 0);
$category = CategoryModel::where('parent_id', 0)->normal()->order('weigh', 'desc')->order('id', 'desc'); $category = null;
if ($id) { if ($id) {
// 指定 id 分类,否则获取 权重最高的一级分类 // 指定 id 分类
$category = $category->where('id', $id); $category = CategoryModel::where('parent_id', 0)->normal()->where('id', $id)->find();
}
if (!$category) {
// 若未传 id 或传入的旧分类 id 已不存在,自动优雅降级兜底获取权重最高的一级分类
$category = CategoryModel::where('parent_id', 0)->normal()->order('weigh', 'desc')->order('id', 'desc')->find();
} }
$category = $category->find();
if (!$category) { if (!$category) {
$this->error(__('No Results were found')); $this->error(__('No Results were found'));
} }

查看文件

@@ -337,13 +337,32 @@ class Agent
// 团队用户人数 = 一级用户人数 + 一级用户的团队用户人数 // 团队用户人数 = 一级用户人数 + 一级用户的团队用户人数
$this->agent->child_user_count_all = $this->agent->child_user_count_1 + array_sum(array_column($nextAgentTeam, 'child_user_count_all')); $this->agent->child_user_count_all = $this->agent->child_user_count_1 + array_sum(array_column($nextAgentTeam, 'child_user_count_all'));
// 一级分销商人数 // 一级有效分销商与等级统计 (优化:等级 1 品酒师必须有自购计奖商品 child_order_count_0 >= 1 才算有效品酒师)
$this->agent->child_agent_count_1 = count($nextAgentTeam); $effectiveNextLevels = [];
$effectiveAgentCount1 = 0;
foreach ($nextAgentTeam as $agMember) {
$agLv = intval($agMember['level'] ?? 1);
$selfBuyOrderCount = intval($agMember['child_order_count_0'] ?? 0);
if ($agLv === 1) {
if ($selfBuyOrderCount >= 1) {
$effectiveNextLevels[] = 1;
$effectiveAgentCount1++;
}
// 未自购计奖商品者属于普通游客,不计入品酒师,亦不计入一级分销商人数
} elseif ($agLv >= 2) {
$effectiveNextLevels[] = $agLv;
$effectiveAgentCount1++;
}
}
// 一级有效分销商人数
$this->agent->child_agent_count_1 = $effectiveAgentCount1;
// 二级分销商人数 = 一级分销商的一级分销商人数 // 二级分销商人数 = 一级分销商的一级分销商人数
$this->agent->child_agent_count_2 = array_sum(array_column($nextAgentTeam, 'child_agent_count_1')); $this->agent->child_agent_count_2 = array_sum(array_column($nextAgentTeam, 'child_agent_count_1'));
// 团队分销商人数 = 一级分销商人数 + 一级分销商的团队分销商人数 // 团队分销商人数 = 一级有效分销商人数 + 一级所有分销商的团队分销商人数
$this->agent->child_agent_count_all = $this->agent->child_agent_count_1 + array_sum(array_column($nextAgentTeam, 'child_agent_count_all')); $this->agent->child_agent_count_all = $this->agent->child_agent_count_1 + array_sum(array_column($nextAgentTeam, 'child_agent_count_all'));
// 二级分销订单金额 = 一级分销商的一级分销订单金额 + 一级分销商的自购订单金额 // 二级分销订单金额 = 一级分销商的一级分销订单金额 + 一级分销商的自购订单金额
@@ -358,8 +377,8 @@ class Agent
// 团队分销订单数量 = 自购分销订单数量 + 一级分销订单数量 + 一级所有分销商的团队分销订单总数量 // 团队分销订单数量 = 自购分销订单数量 + 一级分销订单数量 + 一级所有分销商的团队分销订单总数量
$this->agent->child_order_count_all = $this->agent->child_order_count_0 + $this->agent->child_order_count_1 + array_sum(array_column($nextAgentTeam, 'child_order_count_all')); $this->agent->child_order_count_all = $this->agent->child_order_count_0 + $this->agent->child_order_count_1 + array_sum(array_column($nextAgentTeam, 'child_order_count_all'));
// 一级分销商等级统计 // 一级分销商等级统计 (仅统计自购了计奖商品的有效品酒师及创客)
$child_agent_level_1 = array_count_values(array_column($nextAgentTeam, 'level')); $child_agent_level_1 = array_count_values($effectiveNextLevels);
ksort($child_agent_level_1); ksort($child_agent_level_1);
$this->agent->child_agent_level_1 = $child_agent_level_1; $this->agent->child_agent_level_1 = $child_agent_level_1;
@@ -520,11 +539,26 @@ class Agent
case 'child_agent_level_all': // 团队分销商等级统计 case 'child_agent_level_all': // 团队分销商等级统计
$match[$name] = true; $match[$name] = true;
if (count($value) > 0) { if (count($value) > 0) {
if (empty($this->agent->$name)) { $currentLevelDist = $this->agent->$name;
if (is_string($currentLevelDist)) {
$currentLevelDist = json_decode($currentLevelDist, true) ?: [];
}
$currentLevelDist = (array)$currentLevelDist;
if (empty($currentLevelDist)) {
$match[$name] = false; $match[$name] = false;
} else { } else {
foreach ($value as $k => $row) { foreach ($value as $k => $row) {
if (!isset(($this->agent->$name)[$row['level']]) || ($this->agent->$name)[$row['level']] < $row['count']) { $targetLevel = intval($row['level'] ?? 0);
$targetCount = intval($row['count'] ?? 0);
$actualCount = 0;
// 向上兼容累计:当下级达到或超过目标等级时,均符合该等级的人数考核要求
foreach ($currentLevelDist as $curLv => $cnt) {
if (intval($curLv) >= $targetLevel) {
$actualCount += intval($cnt);
}
}
if ($actualCount < $targetCount) {
$match[$name] = false; $match[$name] = false;
break; break;
} }

查看文件

@@ -3,15 +3,13 @@
namespace addons\shopro\service\partner; namespace addons\shopro\service\partner;
/** /**
* 创客协同(逐代 10% 递减级联,最低发放不能少于 0.10 元截断)/ 创客卓越 5%(只一层) * 创客协同:第 1 代按下级本单实得进阶奖 × 比例,之后每代按上一笔协同奖 × 比例,低于 0.10 元截断。
* 创客卓越 5% 只发一层。
*/ */
class MakerPeerReward class MakerPeerReward
{ {
public function run($order, $buyerId, $chain, $diffResult, ActiveService $active, $rules = null) public function run($order, $buyerId, $chain, $diffResult, ActiveService $active, $rules = null)
{ {
$bonus = (!empty($rules['maker_bonus']) && is_array($rules['maker_bonus']))
? $rules['maker_bonus']
: PartnerConfig::makerBonus();
$peerRate = (isset($rules['maker_peer_rate']) && is_numeric($rules['maker_peer_rate'])) $peerRate = (isset($rules['maker_peer_rate']) && is_numeric($rules['maker_peer_rate']))
? (float) $rules['maker_peer_rate'] ? (float) $rules['maker_peer_rate']
: (float) PartnerConfig::get('partner_maker_peer_rate', 0.10); : (float) PartnerConfig::get('partner_maker_peer_rate', 0.10);
@@ -38,9 +36,13 @@ class MakerPeerReward
continue; continue;
} }
$levelBonus = (float) ($bonus[$item['level']] ?? 0); $itemAmount = (float) ($item['amount'] ?? 0);
if ($itemAmount <= 0) {
continue;
}
$currentFrom = $from; $currentFrom = $from;
$currentBase = $levelBonus; $currentBase = $itemAmount;
$sourceUserId = $item['user_id']; $sourceUserId = $item['user_id'];
for ($gen = 1; $gen <= $maxPeerGenerations; $gen++) { for ($gen = 1; $gen <= $maxPeerGenerations; $gen++) {

查看文件

@@ -290,6 +290,7 @@ class PartnerConfig
'not_maker' => '不是' . $maker . '身份', 'not_maker' => '不是' . $maker . '身份',
'not_venue' => '不是' . $venue . '身份', 'not_venue' => '不是' . $venue . '身份',
'not_county' => '不是' . $county . '身份', 'not_county' => '不是' . $county . '身份',
'venue_above_county' => '县以上酒道馆无收益',
'cap_not_higher' => '等级未超过基数水位', 'cap_not_higher' => '等级未超过基数水位',
'already_settled' => '幂等跳过', 'already_settled' => '幂等跳过',
'partner_goods_off' => '商品未参与', 'partner_goods_off' => '商品未参与',
@@ -302,6 +303,7 @@ class PartnerConfig
'not_maker' => '', 'not_maker' => '',
'not_venue' => '', 'not_venue' => '',
'not_county' => '', 'not_county' => '',
'venue_above_county' => '县以上的酒道馆不发放管理奖',
'cap_not_higher' => '同阶不计进阶差额,享受平级奖励', 'cap_not_higher' => '同阶不计进阶差额,享受平级奖励',
'already_settled' => '', 'already_settled' => '',
'partner_goods_off' => '', 'partner_goods_off' => '',

查看文件

@@ -3,7 +3,11 @@
namespace addons\shopro\service\partner; namespace addons\shopro\service\partner;
/** /**
* 渠道管理奖(馆/县拆分):无馆有县=100;有馆有县=50+50;有馆无县=50 * 渠道管理奖(馆/县拆分),链下标越小越靠近买家:
* - 无馆有县:县 100
* - 有馆无县:馆 50
* - 最近的馆在最近的县下方,或馆与县是同一人:馆 50 + 县 50
* - 最近的县在最近的馆下方:县 100,县以上的馆不发
*/ */
class TeamSplitReward class TeamSplitReward
{ {
@@ -18,14 +22,18 @@ class TeamSplitReward
$result = ['venue' => null, 'county' => null]; $result = ['venue' => null, 'county' => null];
$venue = $this->nearest($chain, 'is_venue', $active); $venue = $this->nearest($chain, 'is_venue', $active);
$county = $this->nearestCounty($chain, $venue, $active); $county = $this->nearest($chain, 'is_county', $active);
if (!$venue && !$county) { if (!$venue && !$county) {
PartnerRewardService::writeSkip($order, $buyerId, 0, 'team_venue', 'system', 'not_venue', '链上无酒道馆且无区县'); PartnerRewardService::writeSkip($order, $buyerId, 0, 'team_venue', 'system', 'not_venue', '链上无酒道馆且无区县');
return $result; return $result;
} }
if ($venue) { // 县比馆更靠近买家时,馆在县之上,不发酒道馆管理奖
$venueAboveCounty = $venue && $county && intval($venue['index']) > intval($county['index']);
$venueEarns = $venue && !$venueAboveCounty;
if ($venueEarns) {
if ($venue['inactive']) { if ($venue['inactive']) {
PartnerRewardService::writeSkip($order, $buyerId, $venue['user_id'], 'team_venue', 'venue', 'inactive_30d', '酒道馆 30 日无自购'); PartnerRewardService::writeSkip($order, $buyerId, $venue['user_id'], 'team_venue', 'venue', 'inactive_30d', '酒道馆 30 日无自购');
} else { } else {
@@ -34,22 +42,30 @@ class TeamSplitReward
]); ]);
$result['venue'] = ['user_id' => $venue['user_id'], 'amount' => $venueSplit, 'index' => $venue['index']]; $result['venue'] = ['user_id' => $venue['user_id'], 'amount' => $venueSplit, 'index' => $venue['index']];
} }
} elseif ($venueAboveCounty) {
PartnerRewardService::writeSkip($order, $buyerId, $venue['user_id'], 'team_venue', 'venue', 'venue_above_county', '县以上酒道馆无收益');
} }
if ($county) { if ($county) {
$amount = $venue ? $venueSplit : $countyFull; $amount = $venueEarns ? $venueSplit : $countyFull;
if ($county['inactive']) { if ($county['inactive']) {
PartnerRewardService::writeSkip($order, $buyerId, $county['user_id'], 'team_county', 'county', 'inactive_30d', '区县 30 日无自购'); PartnerRewardService::writeSkip($order, $buyerId, $county['user_id'], 'team_county', 'county', 'inactive_30d', '区县 30 日无自购');
} else { } else {
$formulaText = $venue if ($venue && intval($venue['user_id']) === intval($county['user_id'])) {
? (($venue['user_id'] == $county['user_id']) ? "区县管理奖 {$amount}(馆兼县)" : "区县管理奖 {$amount}(馆上)") $formulaText = "区县管理奖 {$amount}(馆兼县)";
: "区县管理奖 {$amount}(直达)"; } elseif ($venueEarns) {
$formulaText = "区县管理奖 {$amount}(馆上)";
} elseif ($venueAboveCounty) {
$formulaText = "区县管理奖 {$amount}(县在馆下)";
} else {
$formulaText = "区县管理奖 {$amount}(直达)";
}
PartnerRewardService::account($order, $buyerId, $county['user_id'], 'team_county', 'county', $amount, $amount, [ PartnerRewardService::account($order, $buyerId, $county['user_id'], 'team_county', 'county', $amount, $amount, [
'formula' => $formulaText, 'formula' => $formulaText,
]); ]);
$result['county'] = ['user_id' => $county['user_id'], 'amount' => $amount, 'index' => $county['index']]; $result['county'] = ['user_id' => $county['user_id'], 'amount' => $amount, 'index' => $county['index']];
} }
} elseif ($venue && !$county) { } elseif ($venue) {
PartnerRewardService::writeSkip($order, $buyerId, 0, 'team_county', 'system', 'not_county', '有馆无区县'); PartnerRewardService::writeSkip($order, $buyerId, 0, 'team_county', 'system', 'not_county', '有馆无区县');
} }
@@ -71,26 +87,4 @@ class TeamSplitReward
} }
return null; return null;
} }
protected function nearestCounty($chain, $venue, ActiveService $active)
{
// 若酒道馆节点本身兼任区县代理,允许从该酒道馆节点开始匹配(兼具双重身份场景);若未兼任,循环会自动检查其上一级
$start = $venue ? $venue['index'] : 0;
for ($i = $start; $i < count($chain); $i++) {
if (!intval($chain[$i]['is_county'] ?? 0)) {
continue;
}
return [
'user_id' => $chain[$i]['user_id'],
'index' => $i,
'inactive' => !$active->isActive($chain[$i]['agent'] ?? $chain[$i]),
'node' => $chain[$i],
];
}
// 无馆时从链头找区县(含自购区县)
if (!$venue) {
return $this->nearest($chain, 'is_county', $active);
}
return null;
}
} }

查看文件

@@ -144,8 +144,8 @@ class VoucherService
return null; return null;
} }
$daily = round($total / $days, 2); $daily = round($total / $days, 2);
// 临时模式:当天立即生效起算,支持 1 分钟释放联调 // 生产标准模式:下单次日生效起算,按 365 天线性释放
$startDate = date('Y-m-d', $this->orderTime($order)); $startDate = date('Y-m-d', strtotime('+1 day', $this->orderTime($order)));
$plan = VoucherPlan::create([ $plan = VoucherPlan::create([
'user_id' => $buyerId, 'user_id' => $buyerId,

查看文件

@@ -69,7 +69,7 @@ class Agent extends Common
$detail->next_push3_text = '第 ' . ($seq + 1) . ' 单将返 ' . $detail->next_push3_amount; $detail->next_push3_text = '第 ' . ($seq + 1) . ' 单将返 ' . $detail->next_push3_amount;
$detail->last_self_order_text = $last ? date('Y-m-d H:i:s', $last) : '从未下单'; $detail->last_self_order_text = $last ? date('Y-m-d H:i:s', $last) : '从未下单';
// 业务核心规范:进阶角色(创客V1~V6、酒道馆、区县代理、合伙股东)需自购考核;基础会员及品酒师免自购考核 // 业务核心规范:进阶角色(创客V1~V6、酒道馆、区县代理、合伙人)需自购考核;基础会员及品酒师免自购考核
if (!$isAdvanced) { if (!$isAdvanced) {
$detail->active_status_text = '免自购考核 (基础会员/品酒师)'; $detail->active_status_text = '免自购考核 (基础会员/品酒师)';
} else { } else {
@@ -101,18 +101,232 @@ class Agent extends Common
$detail->total_income = $alignedIncome; $detail->total_income = $alignedIncome;
$detail->partner_cash_income = $alignedIncome; $detail->partner_cash_income = $alignedIncome;
$detail->push3_cash_income = number_format((float) $push3Cash, 2, '.', ''); $detail->push3_cash_income = number_format((float) $push3Cash, 2, '.', '');
$detail->partner_exclusive_cash = number_format((float) $partnerExclusiveCash, 2, '.', ''); $userData = $detail->user ? $detail->user->getData() : [];
$detail->user_money = number_format(floatval($detail->user ? $detail->user->money : 0), 2, '.', ''); $userMoney = $userData['money'] ?? 0;
$detail->user_commission = number_format(floatval($detail->user ? $detail->user->commission : 0), 2, '.', ''); $userCommission = $userData['commission'] ?? 0;
$detail->user_money = number_format(floatval($userMoney), 2, '.', '');
$detail->user_commission = number_format(floatval($userCommission), 2, '.', '');
$detail->partner_mode = \addons\shopro\service\partner\PartnerConfig::isPartnerMode() ? 1 : 0; $detail->partner_mode = \addons\shopro\service\partner\PartnerConfig::isPartnerMode() ? 1 : 0;
$rate = (new \addons\shopro\service\partner\RateService())->currentRate(); $rate = (new \addons\shopro\service\partner\RateService())->currentRate();
$detail->madow_value = \addons\shopro\service\partner\IdentityService::formatMoney((float) ($detail->madow ?? 0) * (float) $rate); $detail->madow_value = \addons\shopro\service\partner\IdentityService::formatMoney((float) ($detail->madow ?? 0) * (float) $rate);
$detail->custom_role_names = \addons\shopro\service\partner\PartnerConfig::roleNames(); $detail->custom_role_names = \addons\shopro\service\partner\PartnerConfig::roleNames();
$detail->role_names = $detail->custom_role_names; $detail->role_names = $detail->custom_role_names;
$detail->operational_stats = $this->getOperationalStats($detail, $id);
$this->success('分销商详情', null, $detail); $this->success('分销商详情', null, $detail);
} }
/**
* 构建运营官全景统计数据看板
*/
private function getOperationalStats($detail, $id)
{
// 建立邻接表,使用广度优先遍历(BFS)安全获取全部后代节点,杜绝潜在脏数据循环引用死循环
$allUsers = \think\Db::name('user')->column('parent_user_id', 'id');
$children = [];
foreach ($allUsers as $cid => $pid) {
if ($pid) {
$children[$pid][] = (int)$cid;
}
}
$descIds = [];
$queue = [(int)$id];
$visited = [(int)$id => true];
while (!empty($queue)) {
$curr = array_shift($queue);
if (!empty($children[$curr])) {
foreach ($children[$curr] as $cid) {
if (!isset($visited[$cid])) {
$visited[$cid] = true;
$descIds[] = $cid;
$queue[] = $cid;
}
}
}
}
$directIds = $children[(int)$id] ?? [];
// 1. 团队角色拓扑
$directCount = count($directIds);
$directPaidCount = empty($directIds) ? 0 : \think\Db::name('user')->whereIn('id', $directIds)->where('total_consume', '>', 0)->count();
$directMakerCount = empty($directIds) ? 0 : \think\Db::name('shopro_commission_agent')->whereIn('user_id', $directIds)->where('level', '>=', 2)->count();
$teamDescCount = count($descIds);
$teamPaidCount = empty($descIds) ? 0 : \think\Db::name('user')->whereIn('id', $descIds)->where('total_consume', '>', 0)->count();
$teamMakerAgents = empty($descIds) ? [] : \think\Db::name('shopro_commission_agent')->whereIn('user_id', $descIds)->where('level', '>=', 2)->column('level');
$teamMakerCount = count($teamMakerAgents);
$teamMakerDistribution = array_count_values($teamMakerAgents);
ksort($teamMakerDistribution);
$makerDistribution = [
'v1' => intval($teamMakerDistribution[2] ?? 0),
'v2' => intval($teamMakerDistribution[3] ?? 0),
'v3' => intval($teamMakerDistribution[4] ?? 0),
'v4' => intval($teamMakerDistribution[5] ?? 0),
'v5' => intval($teamMakerDistribution[6] ?? 0),
'v6' => intval($teamMakerDistribution[7] ?? 0),
];
$teamVenueCount = empty($descIds) ? 0 : \think\Db::name('shopro_commission_agent')->whereIn('user_id', $descIds)->where('is_venue', 1)->count();
$teamCountyCount = empty($descIds) ? 0 : \think\Db::name('shopro_commission_agent')->whereIn('user_id', $descIds)->where('is_county', 1)->count();
$conversionRate = $teamDescCount > 0 ? round(($teamPaidCount / $teamDescCount) * 100, 1) : 0.0;
// 2. 收益分成细项
$rewards = \think\Db::name('shopro_partner_reward')
->where('user_id', $id)
->where('status', 1)
->group('reward_type')
->column('sum(amount)', 'reward_type');
$push3Income = (float)($rewards['push3'] ?? 0);
$makerDiffIncome = (float)($rewards['maker_diff'] ?? 0);
$makerPeerIncome = (float)(($rewards['maker_peer'] ?? 0) + ($rewards['maker_overtaken'] ?? 0));
$teamSplitIncome = (float)(($rewards['team_venue'] ?? 0) + ($rewards['team_county'] ?? 0));
$sharePoolIncome = (float)(($rewards['venue_share'] ?? 0) + ($rewards['county_share'] ?? 0));
// 3. 业绩与订单分类
$selfOrderMoney = number_format((float)($detail->child_order_money_0 ?? 0), 2, '.', '');
$selfOrderCount = intval($detail->child_order_count_0 ?? 0);
$directOrderMoney = number_format((float)($detail->child_order_money_1 ?? 0), 2, '.', '');
$directOrderCount = intval($detail->child_order_count_1 ?? 0);
$teamOrderMoney = number_format((float)($detail->child_order_money_all ?? 0), 2, '.', '');
$teamOrderCount = intval($detail->child_order_count_all ?? 0);
$indirectOrderMoney = number_format(max(0, (float)$teamOrderMoney - (float)$directOrderMoney - (float)$selfOrderMoney), 2, '.', '');
$indirectOrderCount = max(0, $teamOrderCount - $directOrderCount - $selfOrderCount);
// 4. 晋升考核差距雷达
$currentLevel = intval($detail->level ?? 1);
$currentLevelRow = \think\Db::name('shopro_commission_level')->where('level', $currentLevel)->find();
$currentLevelName = $currentLevelRow ? $currentLevelRow['name'] : ($currentLevel >= 2 ? '创客V' . ($currentLevel - 1) : '品酒师');
$nextLevel = $currentLevel + 1;
$nextLevelRow = \think\Db::name('shopro_commission_level')->where('level', $nextLevel)->find();
if ($nextLevelRow) {
$nextRules = json_decode($nextLevelRow['upgrade_rules'] ?? '[]', true) ?: [];
$targetDirectUsers = intval($nextRules['child_user_count_1'] ?? 0);
$targetTeamOrders = intval($nextRules['child_order_count_all'] ?? 0);
// 解析直推有效品酒师/创客指标要求
$targetDirectAgents = 0;
if (!empty($nextRules['child_agent_level_1']) && is_array($nextRules['child_agent_level_1'])) {
foreach ($nextRules['child_agent_level_1'] as $al) {
$targetDirectAgents += intval($al['count'] ?? 0);
}
} elseif (!empty($nextRules['child_agent_count_1'])) {
$targetDirectAgents = intval($nextRules['child_agent_count_1']);
}
$currentDirectUsers = intval($detail->child_user_count_1 ?? $directCount);
$currentDirectAgents = intval($detail->child_agent_count_1 ?? $directPaidCount);
$currentTeamOrders = intval($detail->child_order_count_all ?? 0);
$currentSelfMoney = (float)($detail->child_order_money_0 ?? 0);
$directUserGap = max(0, $targetDirectUsers - $currentDirectUsers);
$directAgentGap = max(0, $targetDirectAgents - $currentDirectAgents);
$teamOrderGap = max(0, $targetTeamOrders - $currentTeamOrders);
$isSelfPaid = ($selfOrderCount > 0 || $currentSelfMoney >= 1398);
$directUserPercent = $targetDirectUsers > 0 ? min(100, (int)round(($currentDirectUsers / $targetDirectUsers) * 100)) : 100;
$directAgentPercent = $targetDirectAgents > 0 ? min(100, (int)round(($currentDirectAgents / $targetDirectAgents) * 100)) : 100;
$teamOrderPercent = $targetTeamOrders > 0 ? min(100, (int)round(($currentTeamOrders / $targetTeamOrders) * 100)) : 100;
$upgradeRadar = [
'current_level' => $currentLevel,
'current_level_name' => $currentLevelName,
'next_level' => $nextLevel,
'next_level_name' => $nextLevelRow['name'],
'target_direct_users' => $targetDirectUsers,
'current_direct_users' => $currentDirectUsers,
'direct_user_gap' => $directUserGap,
'direct_user_reached' => ($directUserGap === 0),
'direct_user_percent' => $directUserPercent,
'target_direct_agents' => $targetDirectAgents,
'current_direct_agents' => $currentDirectAgents,
'direct_agent_gap' => $directAgentGap,
'direct_agent_reached' => ($directAgentGap === 0),
'direct_agent_percent' => $directAgentPercent,
'target_team_orders' => $targetTeamOrders,
'current_team_orders' => $currentTeamOrders,
'team_order_gap' => $teamOrderGap,
'team_order_reached' => ($teamOrderGap === 0),
'team_order_percent' => $teamOrderPercent,
'self_paid_reached' => $isSelfPaid,
'all_reached' => ($directUserGap === 0 && $directAgentGap === 0 && $teamOrderGap === 0 && $isSelfPaid),
'upgrade_lock' => intval($detail->upgrade_lock ?? 0)
];
} else {
$upgradeRadar = [
'current_level' => $currentLevel,
'current_level_name' => $currentLevelName,
'next_level' => 0,
'next_level_name' => '已达最高职级',
'target_direct_users' => 0,
'current_direct_users' => intval($detail->child_user_count_1 ?? $directCount),
'direct_user_gap' => 0,
'direct_user_reached' => true,
'direct_user_percent' => 100,
'target_direct_agents' => 0,
'current_direct_agents' => intval($detail->child_agent_count_1 ?? $directPaidCount),
'direct_agent_gap' => 0,
'direct_agent_reached' => true,
'direct_agent_percent' => 100,
'target_team_orders' => 0,
'current_team_orders' => intval($detail->child_order_count_all ?? 0),
'team_order_gap' => 0,
'team_order_reached' => true,
'team_order_percent' => 100,
'self_paid_reached' => true,
'all_reached' => true,
];
}
return [
'roles' => [
'direct_total' => $directCount,
'direct_paid' => $directPaidCount,
'direct_unpaid' => max(0, $directCount - $directPaidCount),
'direct_maker' => $directMakerCount,
'team_total' => $teamDescCount,
'team_paid' => $teamPaidCount,
'team_unpaid' => max(0, $teamDescCount - $teamPaidCount),
'team_conversion_rate' => $conversionRate,
'team_maker' => $teamMakerCount,
'team_maker_distribution' => $makerDistribution,
'team_venue' => $teamVenueCount,
'team_county' => $teamCountyCount,
],
'orders' => [
'self_money' => $selfOrderMoney,
'self_count' => $selfOrderCount,
'direct_money' => $directOrderMoney,
'direct_count' => $directOrderCount,
'indirect_money' => $indirectOrderMoney,
'indirect_count' => $indirectOrderCount,
'team_money' => $teamOrderMoney,
'team_count' => $teamOrderCount,
],
'rewards' => [
'push3' => number_format($push3Income, 2, '.', ''),
'maker_diff' => number_format($makerDiffIncome, 2, '.', ''),
'maker_peer' => number_format($makerPeerIncome, 2, '.', ''),
'maker_total' => number_format($makerDiffIncome + $makerPeerIncome, 2, '.', ''),
'team_split' => number_format($teamSplitIncome, 2, '.', ''),
'share_pool' => number_format($sharePoolIncome, 2, '.', ''),
],
'assets' => [
'wallet_money' => $detail->user_money,
'total_income' => $detail->total_income,
'untransfer_commission' => $detail->user_commission,
'dmepa_madow' => number_format((float)($detail->madow ?? 0), 4, '.', ''),
'dmepa_value' => $detail->madow_value,
'voucher_total' => number_format((float)($detail->voucher_total ?? 0), 2, '.', ''),
'voucher_released' => number_format((float)($detail->voucher_released ?? 0), 2, '.', ''),
'voucher_available' => number_format(max(0, (float)($detail->voucher_released ?? 0) - (float)($detail->voucher_used ?? 0)), 2, '.', ''),
],
'upgrade_radar' => $upgradeRadar
];
}
/** /**
* 团队 * 团队

查看文件

@@ -156,6 +156,122 @@
.agent-detail .rewards-item:last-of-type { .agent-detail .rewards-item:last-of-type {
margin-right: 0; margin-right: 0;
} }
/* 运营官全景看板样式 */
.agent-detail .op-dashboard {
background: #fff;
border: 1px solid var(--sa-border);
border-radius: 8px;
padding: 18px 20px;
margin-bottom: 20px;
}
.agent-detail .op-section-title {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
font-weight: 600;
color: var(--sa-title);
margin: 16px 0 12px;
padding-bottom: 8px;
border-bottom: 1px dashed var(--sa-border);
}
.agent-detail .op-section-title:first-of-type {
margin-top: 4px;
}
.agent-detail .op-radar-card {
background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 14px 18px;
margin-bottom: 18px;
}
.agent-detail .op-radar-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.agent-detail .op-radar-title {
font-size: 14px;
font-weight: 600;
color: #2d3748;
display: flex;
align-items: center;
gap: 8px;
}
.agent-detail .op-radar-body {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.agent-detail .op-radar-metric {
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 6px;
padding: 10px 14px;
flex: 1;
min-width: 180px;
box-shadow: 0 1px 3px rgba(0,0,0,0.02);
}
.agent-detail .op-radar-metric .m-label {
font-size: 12px;
color: #718096;
margin-bottom: 6px;
display: flex;
align-items: center;
justify-content: space-between;
}
.agent-detail .op-radar-metric .m-val {
font-size: 16px;
font-weight: 600;
color: #1a202c;
}
.agent-detail .op-grid-box {
background: #fbfcfe;
border: 1px solid #edf2f7;
border-radius: 6px;
padding: 12px 14px;
min-height: 120px;
box-sizing: border-box;
margin-bottom: 12px;
transition: all 0.2s ease;
}
.agent-detail .op-grid-box:hover {
border-color: #cbd5e0;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.agent-detail .op-grid-box .box-title {
font-size: 13px;
font-weight: 600;
color: #334155;
margin-bottom: 10px;
display: flex;
align-items: center;
justify-content: space-between;
}
.agent-detail .op-stat-row {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 13px;
line-height: 24px;
}
.agent-detail .op-stat-row .stat-label {
color: #64748b;
font-size: 12px;
}
.agent-detail .op-stat-row .stat-val {
font-weight: 600;
color: #1e293b;
}
.agent-detail .op-stat-row .stat-val.primary { color: #3b82f6; }
.agent-detail .op-stat-row .stat-val.success { color: #10b981; }
.agent-detail .op-stat-row .stat-val.warning { color: #f59e0b; }
.agent-detail .op-stat-row .stat-val.danger { color: #ef4444; }
.agent-detail .op-stat-row .stat-val.purple { color: #8b5cf6; }
.agent-detail .op-stat-row .stat-val.cyan { color: #06b6d4; }
</style> </style>
<div id="detail" class="agent-detail panel panel-default panel-intro" v-cloak> <div id="detail" class="agent-detail panel panel-default panel-intro" v-cloak>
@@ -296,9 +412,13 @@
</el-form-item> </el-form-item>
<el-form-item label="允许自动升级:"> <el-form-item label="允许自动升级:">
{if $auth->check('shopro/commission/agent/edit')} {if $auth->check('shopro/commission/agent/edit')}
<el-switch v-model="state.data.upgrade_lock" :active-value="0" :inactive-value="1" <div class="sa-flex sa-flex-wrap" style="gap: 8px; align-items: center;">
@change="state.data.user_id?onEdit({upgrade_lock: state.data.upgrade_lock}): ''"> <el-switch v-model="state.data.upgrade_lock" :active-value="0" :inactive-value="1"
</el-switch> @change="state.data.user_id?onEdit({upgrade_lock: state.data.upgrade_lock}): ''">
</el-switch>
<span style="font-size: 12px; color: #10b981;" v-if="state.data.upgrade_lock == 0">已允许 (达标自动晋升)</span>
<span style="font-size: 12px; color: #ef4444;" v-else>⚠️ 已锁定 (禁止自动晋升)</span>
</div>
{/if} {/if}
</el-form-item> </el-form-item>
<el-form-item label="直推奖(推三返一):"> <el-form-item label="直推奖(推三返一):">
@@ -334,9 +454,9 @@
{{ state.data.is_county ? '已开通' + (state.data.county_code ? ' (' + state.data.county_code + ')' : '') : '未开通' }} {{ state.data.is_county ? '已开通' + (state.data.county_code ? ' (' + state.data.county_code + ')' : '') : '未开通' }}
</el-tag> </el-tag>
</el-form-item> </el-form-item>
<el-form-item :label="(state.data.custom_role_names?.partner || '合伙股东') + ':'"> <el-form-item :label="(state.data.custom_role_names?.partner || '合伙人') + ':'">
<el-tag size="small" :type="state.data.is_partner ? 'danger' : 'info'"> <el-tag size="small" :type="state.data.is_partner ? 'danger' : 'info'">
{{ state.data.is_partner ? '已授予' + (state.data.custom_role_names?.partner || '合伙股东') : '未开通' }} {{ state.data.is_partner ? '已授予' + (state.data.custom_role_names?.partner || '合伙人') : '未开通' }}
</el-tag> </el-tag>
</el-form-item> </el-form-item>
<el-form-item label="30天自购考核:"> <el-form-item label="30天自购考核:">
@@ -367,13 +487,13 @@
<el-tag type="info" effect="plain" size="small">{{ state.data.identity_text || ('基础会员 · ' + (state.data.custom_role_names?.taster || '品酒师')) }}</el-tag> <el-tag type="info" effect="plain" size="small">{{ state.data.identity_text || ('基础会员 · ' + (state.data.custom_role_names?.taster || '品酒师')) }}</el-tag>
</el-form-item> </el-form-item>
<div style="font-size: 12px; color: var(--sa-subfont); line-height: 1.6; background: #f8fafc; border: 1px dashed var(--sa-border); border-radius: 4px; padding: 8px 12px; margin: 4px 0 10px;"> <div style="font-size: 12px; color: var(--sa-subfont); line-height: 1.6; background: #f8fafc; border: 1px dashed var(--sa-border); border-radius: 4px; padding: 8px 12px; margin: 4px 0 10px;">
💡 <strong>进阶角色体系说明</strong>:系统拥有{{ state.data.custom_role_names?.maker || '创客' }}(V1~V6)、{{ state.data.custom_role_names?.venue || '酒道馆' }}、{{ state.data.custom_role_names?.county || '区县代理' }}、{{ state.data.custom_role_names?.partner || '合伙股东' }}等独立进阶角色,享有团队分润与平台日结分红。当前会员为基础会员,享有推三返一,<strong>免自购考核</strong>。 💡 <strong>进阶角色体系说明</strong>:系统拥有{{ state.data.custom_role_names?.maker || '创客' }}(V1~V6)、{{ state.data.custom_role_names?.venue || '酒道馆' }}、{{ state.data.custom_role_names?.county || '区县代理' }}、{{ state.data.custom_role_names?.partner || '合伙人' }}等独立进阶角色,享有团队分润与平台日结分红。当前会员为基础会员,享有推三返一,<strong>免自购考核</strong>。
</div> </div>
<el-form-item label="自购考核要求:"> <el-form-item label="自购考核要求:">
<el-tag size="small" type="info">免自购考核 (基础会员/{{ state.data.custom_role_names?.taster || '品酒师' }})</el-tag> <el-tag size="small" type="info">免自购考核 (基础会员/{{ state.data.custom_role_names?.taster || '品酒师' }})</el-tag>
</el-form-item> </el-form-item>
<el-form-item label="进阶权益:"> <el-form-item label="进阶权益:">
<span style="color: var(--sa-subfont);">升级{{ state.data.custom_role_names?.maker || '创客' }}或开通{{ (state.data.custom_role_names?.venue || '馆').substr(0, 1) }}/{{ (state.data.custom_role_names?.county || '县').substr(0, 1) }}/{{ (state.data.custom_role_names?.partner || '股东').substr(0, 2) }}后即可享有团队奖、级差奖与dmepa分红</span> <span style="color: var(--sa-subfont);">升级{{ state.data.custom_role_names?.maker || '创客' }}或开通{{ (state.data.custom_role_names?.venue || '馆').substr(0, 1) }}/{{ (state.data.custom_role_names?.county || '县').substr(0, 1) }}/{{ (state.data.custom_role_names?.partner || '合伙').substr(0, 2) }}后即可享有团队奖、级差奖与dmepa分红</span>
</el-form-item> </el-form-item>
</template> </template>
@@ -443,219 +563,375 @@
</div> </div>
</el-col> </el-col>
<el-col class="sa-col-24" :xs="24" :sm="24" :md="24" :lg="24" :xl="24"> <el-col class="sa-col-24" :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
<el-row class="dashboard-content agent-content"> <div class="dashboard-content agent-content op-dashboard" v-if="state.data && state.data.operational_stats">
<el-col :span="24"> <!-- 模块一:🎯 晋升考核与升级差距雷达 (Upgrade Radar) -->
<div class="title sa-flex"> <div class="op-radar-card" v-if="state.data.operational_stats.upgrade_radar">
<span>团队统计</span> <div class="op-radar-header">
<div class="op-radar-title">
<span style="font-size: 16px;">🎯</span>
<span>晋升考核与升级差距雷达</span>
<el-tag size="small" effect="plain" type="info">
当前:{{ state.data.operational_stats.upgrade_radar.current_level_name }}
</el-tag>
<el-tag size="small" type="primary" effect="dark" v-if="state.data.operational_stats.upgrade_radar.next_level > 0">
目标:{{ state.data.operational_stats.upgrade_radar.next_level_name }}
</el-tag>
<el-tag size="small" type="success" effect="dark" v-else>
已达顶级
</el-tag>
</div>
<div>
<el-tag v-if="state.data.operational_stats.upgrade_radar.upgrade_lock" type="danger" size="small">
⚠️ 升级已被锁定(禁止自动晋升)
</el-tag>
<el-tag v-else-if="state.data.operational_stats.upgrade_radar.all_reached" type="success" size="small">
✓ 晋升条件全部达成
</el-tag>
<el-tag v-else-if="state.data.operational_stats.upgrade_radar.next_level > 0" type="warning" size="small">
考核晋升中
</el-tag>
</div>
</div>
<div class="op-radar-body" v-if="state.data.operational_stats.upgrade_radar.next_level > 0">
<!-- 直推实名/有效品酒师考核 -->
<div class="op-radar-metric" v-if="state.data.operational_stats.upgrade_radar.target_direct_agents > 0">
<div class="m-label">
<span>
直推有效品酒师
<el-popover placement="top" trigger="hover" content="需直推用户完成首单自购(child_order_count_0 ≥ 1)激活为有效品酒师">
<template #reference>
<span style="cursor: pointer; color: #94a3b8; font-size: 11px;">ℹ️ 说明</span>
</template>
</el-popover>
</span>
<el-tag size="small" :type="state.data.operational_stats.upgrade_radar.direct_agent_reached ? 'success' : 'danger'">
{{ state.data.operational_stats.upgrade_radar.direct_agent_reached ? '已达标' : '缺 ' + state.data.operational_stats.upgrade_radar.direct_agent_gap + ' 人' }}
</el-tag>
</div>
<div class="m-val">
{{ state.data.operational_stats.upgrade_radar.current_direct_agents }}
<span style="font-size: 12px; color: #94a3b8; font-weight: normal;"> / {{ state.data.operational_stats.upgrade_radar.target_direct_agents }} 人</span>
</div>
<el-progress :percentage="state.data.operational_stats.upgrade_radar.direct_agent_percent"
:status="state.data.operational_stats.upgrade_radar.direct_agent_reached ? 'success' : 'warning'"
:stroke-width="6" style="margin-top: 6px;"></el-progress>
</div>
<div class="op-radar-metric" v-else>
<div class="m-label">
<span>有效直推人数指标</span>
<el-tag size="small" :type="state.data.operational_stats.upgrade_radar.direct_user_reached ? 'success' : 'danger'">
{{ state.data.operational_stats.upgrade_radar.direct_user_reached ? '已达标' : '缺 ' + state.data.operational_stats.upgrade_radar.direct_user_gap + ' 人' }}
</el-tag>
</div>
<div class="m-val">
{{ state.data.operational_stats.upgrade_radar.current_direct_users }}
<span style="font-size: 12px; color: #94a3b8; font-weight: normal;"> / {{ state.data.operational_stats.upgrade_radar.target_direct_users }} 人</span>
</div>
<el-progress :percentage="state.data.operational_stats.upgrade_radar.direct_user_percent"
:status="state.data.operational_stats.upgrade_radar.direct_user_reached ? 'success' : 'warning'"
:stroke-width="6" style="margin-top: 6px;"></el-progress>
</div>
<!-- 团队有效订单考核 -->
<div class="op-radar-metric">
<div class="m-label">
<span>团队有效订单指标</span>
<el-tag size="small" :type="state.data.operational_stats.upgrade_radar.team_order_reached ? 'success' : 'danger'">
{{ state.data.operational_stats.upgrade_radar.team_order_reached ? '已达标' : '缺 ' + state.data.operational_stats.upgrade_radar.team_order_gap + ' 单' }}
</el-tag>
</div>
<div class="m-val">
{{ state.data.operational_stats.upgrade_radar.current_team_orders }}
<span style="font-size: 12px; color: #94a3b8; font-weight: normal;"> / {{ state.data.operational_stats.upgrade_radar.target_team_orders }} 单</span>
</div>
<el-progress :percentage="state.data.operational_stats.upgrade_radar.team_order_percent"
:status="state.data.operational_stats.upgrade_radar.team_order_reached ? 'success' : 'warning'"
:stroke-width="6" style="margin-top: 6px;"></el-progress>
</div>
<!-- 个人自购门槛 -->
<div class="op-radar-metric">
<div class="m-label">
<span>个人自购资格门槛</span>
<el-tag size="small" :type="state.data.operational_stats.upgrade_radar.self_paid_reached ? 'success' : 'danger'">
{{ state.data.operational_stats.upgrade_radar.self_paid_reached ? '已满足' : '未购买' }}
</el-tag>
</div>
<div class="m-val" style="font-size: 14px; margin-top: 4px;">
<span v-if="state.data.operational_stats.upgrade_radar.self_paid_reached" style="color: #10b981; font-weight: 600;">✓ 具备业务升级资格</span>
<span v-else style="color: #ef4444; font-weight: 600;">✕ 需完成首单自购(≥1398元)</span>
</div>
</div>
</div>
<div v-else style="padding: 10px 0; color: #10b981; font-weight: 500; font-size: 13px;">
★ 该账号已达到平台顶峰合伙人级别,尊享平台级加权均分红与管理奖励!
</div>
</div>
<!-- 模块二:👥 团队角色拓扑看板 (Roles & Team) -->
<div class="op-section-title">
<div class="sa-flex">
<span style="font-size: 16px; margin-right: 6px;">👥</span>
<span>团队角色与组织拓扑看板</span>
</div>
<div class="sa-flex">
{if $auth->check('shopro/commission/agent/team')} {if $auth->check('shopro/commission/agent/team')}
<el-button class="ml-2" type="primary" link @click="onTeam">查看团队</el-button> <el-button type="primary" link @click="onTeam">查看层级拓扑树</el-button>
{/if} {/if}
</div> </div>
<el-row> </div>
<el-col class="item" :xs="12" :sm="8" :md="8" :lg="8" :xl="8"> <el-row :gutter="12">
<div class="left">团队人数:</div> <!-- 直推人员池 -->
<div class="right"> <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
{{ state.data.child_user_count_all }} <div class="op-grid-box">
<span class="unit">人</span> <div class="box-title">
<span>直推成员池 (Direct)</span>
<el-tag size="small" type="primary">{{ state.data.operational_stats.roles.direct_total }} 人</el-tag>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="8" :md="8" :lg="8" :xl="8"> <span class="stat-label">已首购有效用户:</span>
<div class="left">一级团队人数:</div> <span class="stat-val success">{{ state.data.operational_stats.roles.direct_paid }} 人</span>
<div class="right">
{{ state.data.child_user_count_1 }}
<span class="unit">人</span>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="8" :md="8" :lg="8" :xl="8"> <span class="stat-label">未购买注册粉丝:</span>
<div class="left">二级团队人数:</div> <span class="stat-val">{{ state.data.operational_stats.roles.direct_unpaid }} 人</span>
<div class="right">
{{ state.data.child_user_count_2 }}
<span class="unit">人</span>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="8" :md="8" :lg="8" :xl="8"> <span class="stat-label">直推创客领袖:</span>
<div class="left"> <span class="stat-val primary">{{ state.data.operational_stats.roles.direct_maker }} 人</span>
团队分销商人数: </div>
<el-popover placement="top" trigger="hover"> </div>
<div v-for="(value, key) in state.data.child_agent_level_all" </el-col>
:key="key">
等级{{ key }}:{{ value }}人 <!-- 核心业务骨干 -->
<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
<div class="op-grid-box">
<div class="box-title">
<span>核心业务骨干 (Backbone)</span>
<el-popover placement="top" trigger="hover" width="220">
<div style="font-size: 12px; line-height: 20px;">
<div style="font-weight: 600; margin-bottom: 4px;">创客各级分布:</div>
<div>V1创客: {{ state.data.operational_stats.roles.team_maker_distribution.v1 || 0 }} 人</div>
<div>V2创客: {{ state.data.operational_stats.roles.team_maker_distribution.v2 || 0 }} 人</div>
<div>V3创客: {{ state.data.operational_stats.roles.team_maker_distribution.v3 || 0 }} 人</div>
<div>V4创客: {{ state.data.operational_stats.roles.team_maker_distribution.v4 || 0 }} 人</div>
<div>V5创客: {{ state.data.operational_stats.roles.team_maker_distribution.v5 || 0 }} 人</div>
<div>V6创客: {{ state.data.operational_stats.roles.team_maker_distribution.v6 || 0 }} 人</div>
</div> </div>
<template #reference> <template #reference>
<div class="sa-flex"> <span style="cursor: pointer; color: #94a3b8; font-size: 13px;">ℹ️ 分布详情</span>
<el-icon v-if="state.data.child_agent_count_all"
class="warning">
<Warning />
</el-icon>
</div>
</template> </template>
</el-popover> </el-popover>
</div> </div>
<div class="right"> <div class="op-stat-row">
{{ state.data.child_agent_count_all }} <span class="stat-label">创客合伙人 (V1-V6):</span>
<span class="unit">人</span> <span class="stat-val purple">{{ state.data.operational_stats.roles.team_maker }} 人</span>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="8" :md="8" :lg="8" :xl="8"> <span class="stat-label">酒道馆签约馆长:</span>
<div class="left"> <span class="stat-val warning">{{ state.data.operational_stats.roles.team_venue }} 个</span>
一级分销商人数:
<el-popover placement="top" trigger="hover">
<div v-for="(value, key) in state.data.child_agent_level_1" :key="key">
等级{{ key }}:{{ value }}人
</div>
<template #reference>
<div class="sa-flex">
<el-icon v-if="state.data.child_agent_count_1" class="warning">
<Warning />
</el-icon>
</div>
</template>
</el-popover>
</div> </div>
<div class="right"> <div class="op-stat-row">
{{ state.data.child_agent_count_1 }} <span class="stat-label">区县代理办事处:</span>
<span class="unit">人</span> <span class="stat-val danger">{{ state.data.operational_stats.roles.team_county }} 个</span>
</div> </div>
</el-col> </div>
<el-col class="item" :xs="12" :sm="8" :md="8" :lg="8" :xl="8"> </el-col>
<div class="left">二级分销商人数:</div>
<div class="right"> <!-- 团队总网络规模 -->
{{ state.data.child_agent_count_2 }} <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
<span class="unit">人</span> <div class="op-grid-box">
<div class="box-title">
<span>全网团队规模 (Network)</span>
<el-tag size="small" type="success">{{ state.data.operational_stats.roles.team_total }} 人</el-tag>
</div> </div>
</el-col> <div class="op-stat-row">
</el-row> <span class="stat-label">全网已出单活跃人数:</span>
</el-col> <span class="stat-val success">{{ state.data.operational_stats.roles.team_paid }} 人</span>
<el-col :span="24"> </div>
<div class="title sa-flex"> <div class="op-stat-row">
<span>业绩统计</span> <span class="stat-label">全网激活转化率:</span>
<span class="stat-val">{{ state.data.operational_stats.roles.team_conversion_rate }}%</span>
</div>
<div class="op-stat-row">
<span class="stat-label">二级直属团队人数:</span>
<span class="stat-val">{{ state.data.child_user_count_2 || 0 }} 人</span>
</div>
</div>
</el-col>
</el-row>
<!-- 模块三:📦 业务业绩与订单流向看板 (Orders & GMV) -->
<div class="op-section-title">
<div class="sa-flex">
<span style="font-size: 16px; margin-right: 6px;">📦</span>
<span>业务业绩与订单流向看板</span>
</div> </div>
<el-row> </div>
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> <el-row :gutter="12">
<div class="left">团队分销总金额:</div> <!-- 自购订单 -->
<div class="right"> <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
{{ state.data.child_order_money_all }} <div class="op-grid-box">
<span class="unit">元</span> <div class="box-title">个人自购业绩</div>
<div class="op-stat-row">
<span class="stat-label">自购成交额:</span>
<span class="stat-val success">¥{{ state.data.operational_stats.orders.self_money }}</span>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> <span class="stat-label">自购订单数:</span>
<div class="left">一级分销总金额:</div> <span class="stat-val">{{ state.data.operational_stats.orders.self_count }} 单</span>
<div class="right">
{{ state.data.child_order_money_1 }}
<span class="unit">元</span>
</div> </div>
</el-col> </div>
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> </el-col>
<div class="left">二级分销总金额:</div>
<div class="right"> <!-- 直推订单 (一级) -->
{{ state.data.child_order_money_2 }} <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
<span class="unit">元</span> <div class="op-grid-box">
<div class="box-title">直推客户业绩 (一级)</div>
<div class="op-stat-row">
<span class="stat-label">直推成交额:</span>
<span class="stat-val primary">¥{{ state.data.operational_stats.orders.direct_money }}</span>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> <span class="stat-label">直推订单数:</span>
<div class="left"> <span class="stat-val">{{ state.data.operational_stats.orders.direct_count }} 单</span>
自购分销总金额:
<el-popover popper-class="sa-popper" placement="top" trigger="hover"
content="分销商自购分销商品金额统计">
<template #reference>
<div class="sa-flex">
<el-icon class="warning">
<Warning />
</el-icon>
</div>
</template>
</el-popover>
</div> </div>
<div class="right"> </div>
{{ state.data.child_order_money_0 }} </el-col>
<span class="unit">元</span>
<!-- 间推订单 (二级) -->
<el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
<div class="op-grid-box">
<div class="box-title">次级裂变业绩 (二级)</div>
<div class="op-stat-row">
<span class="stat-label">间推成交额:</span>
<span class="stat-val cyan">¥{{ state.data.operational_stats.orders.indirect_money }}</span>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> <span class="stat-label">间推订单数:</span>
<div class="left">团队分销订单:</div> <span class="stat-val">{{ state.data.operational_stats.orders.indirect_count }} 单</span>
<div class="right">
{{ state.data.child_order_count_all }}
<span class="unit">单</span>
</div> </div>
</el-col> </div>
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> </el-col>
<div class="left">一级分销订单:</div>
<div class="right"> <!-- 全团队业绩汇总 -->
{{ state.data.child_order_count_1 }} <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
<span class="unit">单</span> <div class="op-grid-box">
<div class="box-title">全网团队总流水 (GMV)</div>
<div class="op-stat-row">
<span class="stat-label">全网成交总额:</span>
<span class="stat-val danger">¥{{ state.data.operational_stats.orders.team_money }}</span>
</div> </div>
</el-col> <div class="op-stat-row">
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> <span class="stat-label">全网出单总数:</span>
<div class="left">二级分销订单:</div> <span class="stat-val">{{ state.data.operational_stats.orders.team_count }} 单</span>
<div class="right">
{{ state.data.child_order_count_2 }}
<span class="unit">单</span>
</div> </div>
</el-col> </div>
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> </el-col>
<div class="left"> </el-row>
自购分销订单:
<el-popover popper-class="sa-popper" placement="top" trigger="hover" <!-- 模块四:💰 收益中心分成与资产闭环 (Rewards & Scheme B Balance) -->
content="分销商自购分销订单数量统计"> <div class="op-section-title">
<template #reference> <div class="sa-flex">
<div class="sa-flex"> <span style="font-size: 16px; margin-right: 6px;">💰</span>
<el-icon class="warning"> <span>收益中心分成明细与资产闭环 (方案B一体化大余额)</span>
<Warning />
</el-icon>
</div>
</template>
</el-popover>
</div>
<div class="right">
{{ state.data.child_order_count_0 }}
<span class="unit">单</span>
</div>
</el-col>
</el-row>
</el-col>
<el-col :span="24">
<div class="title sa-flex">
<span>资产信息</span>
</div> </div>
<el-row> </div>
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> <el-row :gutter="12">
<div class="left">累计收益/佣金:</div> <!-- 方案B核心钱包可用余额 -->
<div class="right"> <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
{{ state.data.total_income }} <div class="op-grid-box" style="background: #f0fdf4; border: 1px solid #bbf7d0;">
<span class="unit">元</span> <div class="box-title" style="color: #166534;">
<span>钱包可用余额 (money)</span>
<el-tag size="small" type="success" effect="dark">可提现</el-tag>
</div> </div>
</el-col> <div style="font-size: 22px; font-weight: 700; color: #15803d; margin: 8px 0;">
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> ¥{{ state.data.operational_stats.assets.wallet_money || '0.00' }}
<div class="left">钱包可用余额:</div>
<div class="right" style="color: #67c23a;">
{{ state.data.user?.money || state.data.user_money || '0.00' }}
<span class="unit">元</span>
</div> </div>
</el-col> <div style="font-size: 11px; color: #16a34a; line-height: 18px;">
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> ✓ 收益入账此钱包,提现扣除此余额
<div class="left">历史未转佣金:</div>
<div class="right" style="color: #e6a23c;">
{{ state.data.user?.commission || state.data.user_commission || '0.00' }}
<span class="unit">元</span>
</div> </div>
</el-col> </div>
<el-col class="item" :xs="12" :sm="6" :md="6" :lg="6" :xl="6"> </el-col>
<div class="left">消费金额:</div>
<div class="right"> <!-- 专项业务奖励细项 -->
{{ state.data.user?.total_consume || 0 }} <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
<span class="unit">元</span> <div class="op-grid-box">
<div class="box-title">
<span>业务奖励构成细项</span>
<span style="font-size: 12px; color: #64748b;">累计: ¥{{ state.data.operational_stats.assets.total_income }}</span>
</div> </div>
</el-col> <div class="op-stat-row">
</el-row> <span class="stat-label">推三返一收益:</span>
</el-col> <span class="stat-val primary">¥{{ state.data.operational_stats.rewards.push3 }}</span>
</el-row> </div>
<div class="op-stat-row">
<span class="stat-label">创客极差/平级/超越:</span>
<span class="stat-val purple">¥{{ state.data.operational_stats.rewards.maker_total }}</span>
</div>
<div class="op-stat-row">
<span class="stat-label">馆/县团队管理奖:</span>
<span class="stat-val warning">¥{{ state.data.operational_stats.rewards.team_split }}</span>
</div>
<div class="op-stat-row">
<span class="stat-label">平台日结均分池:</span>
<span class="stat-val success">¥{{ state.data.operational_stats.rewards.share_pool }}</span>
</div>
</div>
</el-col>
<!-- DMEPA数字资产 -->
<el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
<div class="op-grid-box">
<div class="box-title">
<span>DMEPA 专属数字资产</span>
<el-tag size="small" type="warning">生态资产</el-tag>
</div>
<div class="op-stat-row">
<span class="stat-label">DMEPA 持仓数量:</span>
<span class="stat-val purple">{{ state.data.operational_stats.assets.dmepa_madow }} 枚</span>
</div>
<div class="op-stat-row">
<span class="stat-label">实时市值折算:</span>
<span class="stat-val">¥{{ state.data.operational_stats.assets.dmepa_value }}</span>
</div>
<div class="op-stat-row">
<span class="stat-label">历史未转佣金:</span>
<span class="stat-val warning">¥{{ state.data.operational_stats.assets.untransfer_commission }}</span>
</div>
</div>
</el-col>
<!-- 365天消费补贴券 -->
<el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
<div class="op-grid-box">
<div class="box-title">
<span>365天消费补贴券</span>
<el-tag size="small" type="info">逐日释放</el-tag>
</div>
<div class="op-stat-row">
<span class="stat-label">当前可用补贴券:</span>
<span class="stat-val success">{{ state.data.operational_stats.assets.voucher_available }} 个</span>
</div>
<div class="op-stat-row">
<span class="stat-label">累计释放补贴券:</span>
<span class="stat-val">{{ state.data.operational_stats.assets.voucher_released }} 个</span>
</div>
<div class="op-stat-row">
<span class="stat-label">补贴券总额度:</span>
<span class="stat-val">{{ state.data.operational_stats.assets.voucher_total }} 个</span>
</div>
</div>
</el-col>
</el-row>
</div>
</el-col> </el-col>
</el-row> </el-row>
<el-tabs class="sa-tabs" v-model="log.tabActive" @tab-change="onChangeTab"> <el-tabs class="sa-tabs" v-model="log.tabActive" @tab-change="onChangeTab">
<el-tab-pane label="分销动态" name="log"></el-tab-pane> <el-tab-pane label="分销动态" name="log"></el-tab-pane>
<el-tab-pane label="分销订单" name="order"></el-tab-pane> <el-tab-pane label="分销订单" name="order"></el-tab-pane>
<el-tab-pane label="历史分销佣金" name="reward"></el-tab-pane> <el-tab-pane label="历史分销佣金" name="reward"></el-tab-pane>
</el-tab-pane>
</el-tabs> </el-tabs>
<el-table v-if="log.tabActive=='log'" class="sa-table" :data="log.data" stripe> <el-table v-if="log.tabActive=='log'" class="sa-table" :data="log.data" stripe>
<el-table-column prop="id" label="ID" min-width="90"></el-table-column> <el-table-column prop="id" label="ID" min-width="90"></el-table-column>
@@ -775,8 +1051,14 @@
value: 'id', label: 'name', children: 'children', checkStrictly: true, emitPath: true value: 'id', label: 'name', children: 'children', checkStrictly: true, emitPath: true
}" clearable filterable style="width:100%" @change="onIdentityAreaChange"></el-cascader> }" clearable filterable style="width:100%" @change="onIdentityAreaChange"></el-cascader>
</el-form-item> </el-form-item>
<el-form-item label="升级锁定"> <el-form-item label="锁定升级">
<el-switch v-model="identity.form.upgrade_lock" :active-value="1" :inactive-value="0"></el-switch> <el-switch v-model="identity.form.upgrade_lock" :active-value="1" :inactive-value="0"></el-switch>
<div style="font-size:12px; color:#ef4444; margin-top:2px;" v-if="identity.form.upgrade_lock">
⚠️ 已开启锁定:该分销商将禁止自动升级(即使满足业绩条件也不会晋升)
</div>
<div style="font-size:12px; color:#10b981; margin-top:2px;" v-else>
✓ 未锁定:正常允许分销商根据业绩达标自动晋升
</div>
</el-form-item> </el-form-item>
<el-form-item label="备注"> <el-form-item label="备注">
<el-input v-model="identity.form.remark" type="textarea"></el-input> <el-input v-model="identity.form.remark" type="textarea"></el-input>

查看文件

@@ -63,7 +63,7 @@
<div> <div>
<el-tag v-if="scope.row.is_venue" size="small" type="success">{{ scope.row.role_names?.venue || '酒道馆' }}</el-tag> <el-tag v-if="scope.row.is_venue" size="small" type="success">{{ scope.row.role_names?.venue || '酒道馆' }}</el-tag>
<el-tag v-if="scope.row.is_county" size="small" type="warning">{{ scope.row.role_names?.county || '区县代理' }}</el-tag> <el-tag v-if="scope.row.is_county" size="small" type="warning">{{ scope.row.role_names?.county || '区县代理' }}</el-tag>
<el-tag v-if="scope.row.is_partner" size="small" type="danger">{{ scope.row.role_names?.partner || '合伙股东' }}</el-tag> <el-tag v-if="scope.row.is_partner" size="small" type="danger">{{ scope.row.role_names?.partner || '合伙人' }}</el-tag>
</div> </div>
</template> </template>
</el-table-column> </el-table-column>
@@ -279,8 +279,14 @@
}" clearable filterable style="width:100%" @change="onIdentityAreaChange"></el-cascader> }" clearable filterable style="width:100%" @change="onIdentityAreaChange"></el-cascader>
<div class="tip" style="margin-top:4px;color:#999;font-size:12px">编码:{{ identity.form.county_code || '-' }}</div> <div class="tip" style="margin-top:4px;color:#999;font-size:12px">编码:{{ identity.form.county_code || '-' }}</div>
</el-form-item> </el-form-item>
<el-form-item label="升级锁定"> <el-form-item label="锁定升级">
<el-switch v-model="identity.form.upgrade_lock" :active-value="1" :inactive-value="0"></el-switch> <el-switch v-model="identity.form.upgrade_lock" :active-value="1" :inactive-value="0"></el-switch>
<div style="font-size:12px; color:#ef4444; margin-top:2px;" v-if="identity.form.upgrade_lock">
⚠️ 已开启锁定:该分销商将禁止自动升级(即使满足业绩条件也不会晋升)
</div>
<div style="font-size:12px; color:#10b981; margin-top:2px;" v-else>
✓ 未锁定:正常允许分销商根据业绩达标自动晋升
</div>
</el-form-item> </el-form-item>
<el-form-item label="备注"> <el-form-item label="备注">
<el-input v-model="identity.form.remark" type="textarea" placeholder="如:2026-09 签约"></el-input> <el-input v-model="identity.form.remark" type="textarea" placeholder="如:2026-09 签约"></el-input>

查看文件

@@ -0,0 +1,112 @@
-- ==============================================================================
-- 恒联数通 · 正式投入生产环境 全量测试数据安全清理脚本
-- 适用场景:系统正式投产上线前,全量清空所有测试账号、测试订单、分润记录、
-- 提现数据、微信授权、互动行为与大盘指标,重置自增ID为 1。
--
-- 【受白名单保护的系统基座资产(绝对不清理)】:
-- 1. 管理员与权限体系 (hla_admin, hla_auth_group, hla_auth_group_access, hla_auth_rule)
-- 2. 商城商品基座 (hla_shopro_goods, hla_shopro_goods_sku, hla_shopro_goods_sku_price, hla_shopro_goods_service, hla_category, hla_shopro_category)
-- 3. 分销与计奖规则 (hla_shopro_commission_goods, hla_shopro_commission_level)
-- 4. 全局系统配置 (hla_config, hla_shopro_config, hla_shopro_pay_config, hla_shopro_notification_config)
-- 5. 装修模板与页面 (hla_shopro_decorate, hla_shopro_decorate_page)
-- 6. 物流配送与地区字典 (hla_shopro_dispatch, hla_shopro_dispatch_express, hla_shopro_data_area, hla_shopro_data_express)
-- 7. 附件媒体库 (hla_attachment - 保留商品图、分类图、Banner等素材)
-- ==============================================================================
SET FOREIGN_KEY_CHECKS = 0;
-- ------------------------------------------------------------------------------
-- 1. 清理用户体系与第三方认证授权数据 (TRUNCATE)
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_user`; -- 会员主表
TRUNCATE TABLE `hla_user_token`; -- 会员登录Token凭证
TRUNCATE TABLE `hla_shopro_third_oauth`; -- 微信小程序/公众号等第三方授权绑定关系
TRUNCATE TABLE `hla_shopro_user_account`; -- 会员提现账户绑定表(银行卡/支付宝/微信)
TRUNCATE TABLE `hla_shopro_user_address`; -- 会员收货地址库
TRUNCATE TABLE `hla_shopro_user_invoice`; -- 会员发票抬头库
TRUNCATE TABLE `hla_sms`; -- 手机验证码记录
TRUNCATE TABLE `hla_ems`; -- 邮箱验证码记录
-- ------------------------------------------------------------------------------
-- 2. 清理商城订单及交易明细数据 (TRUNCATE)
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_shopro_order`; -- 商城订单主表
TRUNCATE TABLE `hla_shopro_order_item`; -- 订单商品行明细
TRUNCATE TABLE `hla_shopro_order_action`; -- 订单状态流转与操作日志
TRUNCATE TABLE `hla_shopro_order_address`; -- 订单收货地址历史快照
TRUNCATE TABLE `hla_shopro_order_express`; -- 订单发货物流包裹
TRUNCATE TABLE `hla_shopro_order_express_log`; -- 订单快递轨迹日志
TRUNCATE TABLE `hla_shopro_order_invoice`; -- 订单开票记录
TRUNCATE TABLE `hla_shopro_order_aftersale`; -- 售后退款申请
TRUNCATE TABLE `hla_shopro_order_aftersale_log`;-- 售后协商与处理明细
TRUNCATE TABLE `hla_shopro_pay`; -- 支付单流水表
TRUNCATE TABLE `hla_shopro_refund`; -- 退款单记录表
TRUNCATE TABLE `hla_shopro_trade_order`; -- 充值交易订单表
-- ------------------------------------------------------------------------------
-- 3. 清理分销与合伙人收益流水数据 (TRUNCATE)
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_shopro_commission_agent`; -- 分销商成员档案与推荐关系树
TRUNCATE TABLE `hla_shopro_commission_order`; -- 分销订单关联表
TRUNCATE TABLE `hla_shopro_commission_reward`; -- 分销佣金明细
TRUNCATE TABLE `hla_shopro_commission_log`; -- 分销动态日志
TRUNCATE TABLE `hla_shopro_partner_reward`; -- 收益中心全量流水(推三返一/创客级差/协同/超越/团队奖/dmepa加权/兑换券释放)
-- ------------------------------------------------------------------------------
-- 4. 清理用户资金与钱包变动日志 (TRUNCATE)
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_shopro_user_wallet_log`; -- 用户钱包变动日志(余额/积分/佣金)
TRUNCATE TABLE `hla_user_money_log`; -- FastAdmin原生余额流水日志
TRUNCATE TABLE `hla_user_score_log`; -- FastAdmin原生积分流水日志
TRUNCATE TABLE `hla_shopro_withdraw`; -- 用户提现申请表
TRUNCATE TABLE `hla_shopro_withdraw_log`; -- 用户提现审核与打款日志
-- ------------------------------------------------------------------------------
-- 5. 清理收益日结(日柱)、DMEPA汇率快照与兑换券任务 (TRUNCATE)
-- 清空后系统历史合格单数 N = 0,大盘实时汇率自动回归初始值 0.00000075 元/枚
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_shopro_partner_daily_report`; -- 每日收益日结对账报表
TRUNCATE TABLE `hla_shopro_partner_rate_log`; -- DMEPA大盘汇率历史快照日志
TRUNCATE TABLE `hla_shopro_partner_voucher_plan`; -- 消费兑换券365天线性释放计划
TRUNCATE TABLE `hla_shopro_partner_voucher_log`; -- 兑换券每日释放明细流水(若存在)
-- ------------------------------------------------------------------------------
-- 6. 清理互动行为、客服聊天、搜索词与用户反馈 (TRUNCATE)
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_shopro_cart`; -- 购物车未结算商品
TRUNCATE TABLE `hla_shopro_user_goods_log`; -- 用户收藏夹与足迹浏览历史
TRUNCATE TABLE `hla_shopro_search_history`; -- 用户搜索历史词
TRUNCATE TABLE `hla_shopro_share`; -- 用户分享与裂变记录
TRUNCATE TABLE `hla_shopro_notification`; -- 站内通知与消息
TRUNCATE TABLE `hla_shopro_feedback`; -- 用户意见反馈
TRUNCATE TABLE `hla_shopro_goods_comment`; -- 商品测试评价与买家秀
TRUNCATE TABLE `hla_shopro_chat_record`; -- 客服聊天消息记录
TRUNCATE TABLE `hla_shopro_chat_user`; -- 客服会话用户列表
TRUNCATE TABLE `hla_shopro_chat_service_log`; -- 客服服务日志
-- ------------------------------------------------------------------------------
-- 7. 清理营销活动参与记录 (TRUNCATE)
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_shopro_user_coupon`; -- 用户领取的优惠券明细
TRUNCATE TABLE `hla_shopro_activity_signin`; -- 签到打卡日志
TRUNCATE TABLE `hla_shopro_activity_gift_log`; -- 满赠活动领取日志
TRUNCATE TABLE `hla_shopro_activity_groupon`; -- 拼团记录
TRUNCATE TABLE `hla_shopro_activity_groupon_log`;-- 参团记录
TRUNCATE TABLE `hla_shopro_activity_order`; -- 活动专享订单
-- ------------------------------------------------------------------------------
-- 8. 清理系统任务队列、库存流水与管理员操作日志 (TRUNCATE)
-- ------------------------------------------------------------------------------
TRUNCATE TABLE `hla_jobs`; -- 异步延迟队列任务表
TRUNCATE TABLE `hla_shopro_goods_stock_log`; -- 商品库存变动日志
TRUNCATE TABLE `hla_shopro_goods_stock_warning`;-- 库存预警记录
TRUNCATE TABLE `hla_admin_log`; -- 管理员后台操作测试日志
-- ------------------------------------------------------------------------------
-- 9. 重置商品真实销售量 (UPDATE)
-- 将真实订单带来的 sales 重置归零,保留后台配置的虚拟展示销量 show_sales
-- ------------------------------------------------------------------------------
UPDATE `hla_shopro_goods` SET `sales` = 0;
UPDATE `hla_shopro_goods_sku_price` SET `sales` = 0;
SET FOREIGN_KEY_CHECKS = 1;

查看文件

@@ -0,0 +1,524 @@
<?php
/**
* 线上生成真实 3C 产品与分类维护脚本 (用于微信小程序上架审核)
*
* 包含:
* 1. 4 个真实的 3C 数码分类 (手机数码、智能影音、智能穿戴、电脑办公)
* 2. 8 款真实主流知名品牌 3C 商品 (倍思、漫步者、罗马仕、华为、小米、罗技、绿联、品胜)
* 3. 关联更新单规格 SKU 价格、库存与服务保障
* 4. 联动更新装修模板 5 (3C数码模板) 首页推荐商品与搜索热词
*/
// 载入 ThinkPHP 框架基础
define('APP_PATH', __DIR__ . '/../application/');
define('ROOT_PATH', dirname(realpath(APP_PATH)) . '/');
require_once __DIR__ . '/../thinkphp/base.php';
require_once __DIR__ . '/../thinkphp/helper.php';
require_once __DIR__ . '/../application/common.php';
if (is_file(ROOT_PATH . '.env')) {
$env = parse_ini_file(ROOT_PATH . '.env', true);
foreach ($env as $key => $val) {
$name = 'PHP_' . strtoupper($key);
if (is_array($val)) {
foreach ($val as $k => $v) {
putenv("{$name}_" . strtoupper($k) . "={$v}");
}
} else {
putenv("{$name}={$val}");
}
}
}
\think\Config::set(\think\Config::load(APP_PATH . 'config.php'));
$dbConfig = [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'henglianshutong',
'username' => 'henglianshutong',
'password' => 'henglianshutong',
'hostport' => '3306',
'prefix' => 'hla_',
];
\think\Config::set('database', $dbConfig);
use think\Db;
class Create3CProducts
{
public function run()
{
echo "====================================================\n";
echo "开始执行 3C 分类与真实商品线上数据生成...\n";
echo "====================================================\n\n";
Db::startTrans();
try {
$now = time();
// 1. 动态查找当前生效的一级顶级分类 (例如 ID 172 恒链甄选)
$parentCategory = Db::name('shopro_category')
->where('parent_id', 0)
->where('status', 'normal')
->order('weigh', 'desc')
->order('id', 'desc')
->find();
if (!$parentCategory) {
throw new \Exception("未找到生效的一级分类");
}
$topCatId = $parentCategory['id'];
echo "[1] 主分类校验成功: ID {$topCatId} ({$parentCategory['name']})\n";
// 调整同级原有其他分类权重,保证 3C 分类排在小程序最前
Db::name('shopro_category')
->where('parent_id', $topCatId)
->whereNotIn('name', ['手机数码', '智能影音', '智能穿戴', '电脑办公'])
->update(['weigh' => 50, 'updatetime' => $now]);
// 2. 创建/更新 4 个 3C 二级分类 (挂载在当前顶级分类下)
$categoriesDef = [
'mobile' => [
'name' => '手机数码',
'parent_id' => $topCatId,
'style' => null,
'image' => '/uploads/henglian_goods/3c/categories/cat_mobile.png',
'description' => '精选智能手机、高能移动电源、高速快充及数据传输配件',
'status' => 'normal',
'weigh' => 110
],
'audio' => [
'name' => '智能影音',
'parent_id' => $topCatId,
'style' => null,
'image' => '/uploads/henglian_goods/3c/categories/cat_audio.png',
'description' => '真无线蓝牙耳机、头戴降噪耳机与高保真便携音箱',
'status' => 'normal',
'weigh' => 109
],
'wearable' => [
'name' => '智能穿戴',
'parent_id' => $topCatId,
'style' => null,
'image' => '/uploads/henglian_goods/3c/categories/cat_wearable.png',
'description' => '智能运动健康手环、全天候心率血氧监测智能通话手表',
'status' => 'normal',
'weigh' => 108
],
'computer' => [
'name' => '电脑办公',
'parent_id' => $topCatId,
'style' => null,
'image' => '/uploads/henglian_goods/3c/categories/cat_computer.png',
'description' => '人体工学静音无线鼠标、多功能扩展坞与数码办公外设',
'status' => 'normal',
'weigh' => 107
]
];
$categoryMap = [];
foreach ($categoriesDef as $key => $cat) {
$existCat = Db::name('shopro_category')
->where('parent_id', $topCatId)
->where('name', $cat['name'])
->find();
if ($existCat) {
Db::name('shopro_category')->where('id', $existCat['id'])->update([
'image' => $cat['image'],
'description' => $cat['description'],
'status' => 'normal',
'weigh' => $cat['weigh'],
'updatetime' => $now
]);
$catId = $existCat['id'];
echo " - 已更新分类: {$cat['name']} (ID: {$catId})\n";
} else {
$catId = Db::name('shopro_category')->insertGetId(array_merge($cat, [
'createtime' => $now,
'updatetime' => $now
]));
echo " + 新增分类: {$cat['name']} (ID: {$catId})\n";
}
$categoryMap[$key] = $catId;
}
// 3. 准备 8 款真实 3C 商品
$products = [
[
'num' => 1,
'title' => '倍思 65W GaN氮化镓多口快充充电器',
'subtitle' => 'GaN5 Pro 氮化镓快充 / 2C1A多口盲插 / 智能温控不烫机',
'cat_key' => 'mobile',
'sn' => '3C-BASEUS-GAN65',
'weight' => 0.25,
'original_price' => 149.00,
'price' => 119.00,
'cost_price' => 68.00,
'params' => [
["title" => "品牌", "content" => "倍思 (Baseus)"],
["title" => "型号", "content" => "CCGAN65S5"],
["title" => "接口类型", "content" => "Type-C1 + Type-C2 + USB-A"],
["title" => "最大输出功率", "content" => "65W Max"],
["title" => "输入规格", "content" => "AC 100-240V~, 50/60Hz, 1.5A Max"],
["title" => "适用机型", "content" => "iPhone / 华为 / 小米 / MacBook / 笔记本电脑"],
["title" => "质保期限", "content" => "12个月官方全国联保"]
]
],
[
'num' => 2,
'title' => '漫步者 LolliPods 真无线立体声蓝牙耳机',
'subtitle' => '半入耳舒适佩戴 / AptX高清音频解码 / CVC双麦通话降噪 / 24小时综合续航',
'cat_key' => 'audio',
'sn' => '3C-EDIFIER-LP2026',
'weight' => 0.18,
'original_price' => 199.00,
'price' => 149.00,
'cost_price' => 88.00,
'params' => [
["title" => "品牌", "content" => "漫步者 (EDIFIER)"],
["title" => "型号", "content" => "LolliPods 2026款"],
["title" => "佩戴方式", "content" => "半入耳式"],
["title" => "蓝牙版本", "content" => "Bluetooth 5.3"],
["title" => "发声单元", "content" => "13mm大尺寸高解析复合振膜"],
["title" => "单次续航", "content" => "约 6 小时"],
["title" => "配合充电盒", "content" => "约 24 小时长续航"],
["title" => "防尘防水", "content" => "IP54级专业防护"]
]
],
[
'num' => 3,
'title' => '罗马仕 20000mAh 22.5W超级快充移动电源',
'subtitle' => '智能LED数显大容量充电宝 / 支持SCP/PD3.0快充 / 三入三出全兼容',
'cat_key' => 'mobile',
'sn' => '3C-ROMOSS-SW20',
'weight' => 0.46,
'original_price' => 129.00,
'price' => 89.00,
'cost_price' => 52.00,
'params' => [
["title" => "品牌", "content" => "罗马仕 (ROMOSS)"],
["title" => "型号", "content" => "SW20 Pro"],
["title" => "电池容量", "content" => "20000mAh / 74Wh (符合民航登机要求)"],
["title" => "额定容量", "content" => "12000mAh (5V/3A)"],
["title" => "输入接口", "content" => "Type-C 18W / Micro-USB 18W / Lightning"],
["title" => "输出接口", "content" => "Type-C 20W / USB-A1 22.5W / USB-A2 22.5W"],
["title" => "电量显示", "content" => "LED精准百分比数字屏幕"]
]
],
[
'num' => 4,
'title' => '华为手环 8 智能运动健康手环 曜石黑',
'subtitle' => '8.99mm超薄机身 / 1.47英寸无界大屏 / TruSleep 3.0科学睡眠 / 14天长续航',
'cat_key' => 'wearable',
'sn' => '3C-HUAWEI-BAND8',
'weight' => 0.12,
'original_price' => 269.00,
'price' => 199.00,
'cost_price' => 135.00,
'params' => [
["title" => "品牌", "content" => "华为 (HUAWEI)"],
["title" => "型号", "content" => "ASK-B19"],
["title" => "机身厚度", "content" => "8.99 mm (超薄机身设计)"],
["title" => "屏幕规格", "content" => "1.47英寸 AMOLED炫彩全面屏"],
["title" => "健康监测", "content" => "全天候血氧心率监测 / 睡眠管理 / 压力检测"],
["title" => "防水等级", "content" => "5ATM专业防水 (支持游泳)"],
["title" => "续航能力", "content" => "最长可达14天超长续航"]
]
],
[
'num' => 5,
'title' => '小米Redmi Watch 3 青春版 智能蓝牙通话手表',
'subtitle' => '1.83英寸超大高清屏 / 蓝牙高清语音通话 / 12天持久续航 / 200+个性表盘',
'cat_key' => 'wearable',
'sn' => '3C-REDMI-WATCH3',
'weight' => 0.15,
'original_price' => 299.00,
'price' => 229.00,
'cost_price' => 150.00,
'params' => [
["title" => "品牌", "content" => "小米 (Redmi)"],
["title" => "型号", "content" => "M2247W1"],
["title" => "屏幕尺寸", "content" => "1.83英寸高保真触控彩屏"],
["title" => "通话功能", "content" => "支持蓝牙双向免提高清语音通话"],
["title" => "运动模式", "content" => "100+种专业运动健康监测模式"],
["title" => "防水等级", "content" => "5ATM专业防水"],
["title" => "典型续航", "content" => "典型使用12天 / 重度使用8天"]
]
],
[
'num' => 6,
'title' => '罗技 M330 降噪静音无线鼠标 曜石黑',
'subtitle' => '90%降噪静音微动 / 人体工学舒适右手握感 / 2.4G即插即用 / 24个月超长续航',
'cat_key' => 'computer',
'sn' => '3C-LOGI-M330',
'weight' => 0.16,
'original_price' => 119.00,
'price' => 89.00,
'cost_price' => 55.00,
'params' => [
["title" => "品牌", "content" => "罗技 (Logitech)"],
["title" => "型号", "content" => "M330 Silent Plus"],
["title" => "连接方式", "content" => "2.4GHz 无线USB微型接收器 (10米有效)"],
["title" => "传感器", "content" => "1000 DPI 高精度先进光学追踪"],
["title" => "降噪技术", "content" => "静音微动技术,减少90%以上点击噪音"],
["title" => "电池寿命", "content" => "1节AA五号电池,最长可达24个月续航"]
]
],
[
'num' => 7,
'title' => '绿联 六合一Type-C多功能扩展坞',
'subtitle' => '4K@30Hz HDMI高清投屏 / PD 100W大功率闪充 / USB3.0*3 5Gbps高速传输',
'cat_key' => 'computer',
'sn' => '3C-UGREEN-HUB6',
'weight' => 0.22,
'original_price' => 159.00,
'price' => 119.00,
'cost_price' => 72.00,
'params' => [
["title" => "品牌", "content" => "绿联 (UGREEN)"],
["title" => "型号", "content" => "CM475"],
["title" => "端口扩展", "content" => "HDMI 4K + USB 3.0*3 + PD 100W供电 + SD/TF槽"],
["title" => "材质工艺", "content" => "深空灰阳极氧化铝合金一体散热机身"],
["title" => "线身材质", "content" => "15cm 高密抗折弯编织线身"],
["title" => "兼容平台", "content" => "MacBook / iPad / 华为 / 联想 / 戴尔等全功能Type-C"]
]
],
[
'num' => 8,
'title' => '品胜 苹果PD 20W快充编织数据线 1.2米',
'subtitle' => '智能低温快充芯片 / 加粗镀锡铜芯 / 强韧高密度尼龙编织线身 / 充放提速60%',
'cat_key' => 'mobile',
'sn' => '3C-PISEN-CABLE20',
'weight' => 0.08,
'original_price' => 49.00,
'price' => 29.00,
'cost_price' => 12.00,
'params' => [
["title" => "品牌", "content" => "品胜 (PISEN)"],
["title" => "接口类型", "content" => "Type-C 转 Lightning / C to C"],
["title" => "支持功率", "content" => "最高支持 PD 20W / 27W 闪电快充"],
["title" => "传输速率", "content" => "USB 2.0 480Mbps 稳定数据传输"],
["title" => "线长规格", "content" => "1.2 米 (黄金便携使用长度)"],
["title" => "适用机型", "content" => "iPhone 8-15 全系 / iPad / AirPods 系列"]
]
]
];
$createdGoodsIds = [];
foreach ($products as $idx => $item) {
$i = $item['num'];
$catId = $categoryMap[$item['cat_key']];
$categoryIds = "{$topCatId},{$catId}";
$mainImg = "/uploads/henglian_goods/3c/p_{$i}/cover.jpg";
$banners = [
"/uploads/henglian_goods/3c/p_{$i}/banner_1.jpg",
"/uploads/henglian_goods/3c/p_{$i}/banner_2.jpg",
"/uploads/henglian_goods/3c/p_{$i}/banner_3.jpg"
];
$contentHtml = <<<HTML
<div style="padding:10px 0;text-align:center;">
<p style="font-size:15px;color:#1e293b;font-weight:bold;margin:8px 0;">{$item['title']}</p>
<p style="font-size:12px;color:#64748b;margin-bottom:14px;">{$item['subtitle']}</p>
<p><img src="/uploads/henglian_goods/3c/p_{$i}/detail_1.jpg" style="width:100%;max-width:750px;display:block;margin:0 auto 10px auto;border-radius:8px;" /></p>
<p><img src="/uploads/henglian_goods/3c/p_{$i}/detail_2.jpg" style="width:100%;max-width:750px;display:block;margin:0 auto 10px auto;border-radius:8px;" /></p>
<p><img src="/uploads/henglian_goods/3c/p_{$i}/detail_3.jpg" style="width:100%;max-width:750px;display:block;margin:0 auto 10px auto;border-radius:8px;" /></p>
<div style="background:#f8fafc;padding:16px;border-radius:8px;text-align:left;font-size:13px;color:#475569;line-height:1.8;margin-top:12px;">
<p style="font-weight:bold;color:#0f172a;margin-bottom:6px;">【正品保障与官方售后承诺】</p>
<p>1. 本品为正品行货,支持全国统一防伪验证,享受原厂保修及技术支持服务;</p>
<p>2. 签收之日起支持 7 天无理由退换货(需保持未激活、商品主体与包装完整未损);</p>
<p>3. 质量问题 30 天内包换,1 年内享受全国联合保修;</p>
<p>4. 每日 16:00 前完成支付的订单,当日顺丰/京东快递速发,全国顺畅直达。</p>
</div>
</div>
HTML;
$goodsData = [
'type' => 'normal',
'title' => $item['title'],
'subtitle' => $item['subtitle'],
'category_ids' => $categoryIds,
'image' => $mainImg,
'images' => json_encode($banners, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
'params' => json_encode($item['params'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
'content' => $contentHtml,
'original_price' => $item['original_price'],
'price' => $item['price'],
'is_sku' => 0,
'limit_type' => 'none',
'limit_num' => 0,
'likes' => 120 + $i * 18,
'views' => 1500 + $i * 120,
'sales' => 88 + $i * 15,
'sales_show_type' => 'exact',
'stock_show_type' => 'exact',
'show_sales' => 88 + $i * 15,
'service_ids' => '1,2,3,4', // 正品保障、7天退换、运费险、极速退款
'dispatch_type' => 'express',
'dispatch_id' => 1, // 全国包邮
'is_offline' => 0,
'status' => 'up',
'deletetime' => null, // 清除软删除标记,彻底恢复上架
'weigh' => 200 - $i,
'updatetime' => $now
];
$existGoods = Db::name('shopro_goods')->where('title', $item['title'])->find();
if ($existGoods) {
Db::name('shopro_goods')->where('id', $existGoods['id'])->update($goodsData);
$goodsId = $existGoods['id'];
echo "[2] 恢复并更新商品: {$item['title']} (ID: {$goodsId})\n";
} else {
$goodsData['createtime'] = $now;
$goodsId = Db::name('shopro_goods')->insertGetId($goodsData);
echo "[2] 新增商品: {$item['title']} (ID: {$goodsId})\n";
}
$createdGoodsIds[] = $goodsId;
// 维护单规格 SKU 价格记录
$skuData = [
'goods_sku_ids' => null,
'goods_sku_text' => null,
'goods_id' => $goodsId,
'image' => null,
'stock' => 1000,
'stock_warning' => 20,
'sn' => $item['sn'],
'weight' => $item['weight'],
'cost_price' => $item['cost_price'],
'original_price' => $item['original_price'],
'price' => $item['price'],
'status' => 'up',
'weigh' => 0,
'updatetime' => $now
];
$existSku = Db::name('shopro_goods_sku_price')->where('goods_id', $goodsId)->find();
if ($existSku) {
Db::name('shopro_goods_sku_price')->where('id', $existSku['id'])->update($skuData);
} else {
$skuData['createtime'] = $now;
Db::name('shopro_goods_sku_price')->insert($skuData);
}
}
// 4. 联动更新装修模板 5 (3C数码模板) 首页推荐与搜索关键词
$decorPage = Db::name('shopro_decorate_page')
->where('decorate_id', 5)
->where('type', 'home')
->find();
if ($decorPage) {
$pageConfig = json_decode($decorPage['page'], true);
if (isset($pageConfig['data']) && is_array($pageConfig['data'])) {
foreach ($pageConfig['data'] as &$block) {
// 更新搜索框关键词
if ($block['type'] === 'searchBlock') {
$block['data']['placeholder'] = '搜索 65W氮化镓快充 · 蓝牙耳机 · 智能手表 · 移动电源';
$block['data']['keywords'] = ['65W快充', '漫步者耳机', '华为手环', '罗技鼠标', '罗马仕充电宝', '绿联扩展坞'];
}
// 更新首页轮播图
if ($block['type'] === 'imageBanner') {
$block['data']['list'] = [
[
'title' => '倍思 65W 氮化镓快充 · 闪速满电',
'type' => 'image',
'src' => '/uploads/henglian_goods/3c/banners/banner_home_1.jpg',
'poster' => '',
'url' => '/pages/goods/index?id=' . $createdGoodsIds[0]
],
[
'title' => '漫步者 LolliPods 真无线 · 纯粹原声',
'type' => 'image',
'src' => '/uploads/henglian_goods/3c/banners/banner_home_2.jpg',
'poster' => '',
'url' => '/pages/goods/index?id=' . $createdGoodsIds[1]
],
[
'title' => 'Redmi Watch 3 智能手表 · 运动健康',
'type' => 'image',
'src' => '/uploads/henglian_goods/3c/banners/banner_home_3.jpg',
'poster' => '',
'url' => '/pages/goods/index?id=' . $createdGoodsIds[4]
]
];
}
// 更新头条通知公告
if ($block['type'] === 'noticeBlock') {
$block['data']['title']['text'] = '数码狂欢季,全场精选大牌 3C 正品行货,顺丰包邮极速达!';
}
// 更新专区标题栏
if ($block['type'] === 'titleBlock') {
$block['data']['title']['text'] = '热门数码甄选';
$block['data']['subtitle']['text'] = '精选大牌 · 官方正品';
$block['data']['more']['url'] = '/pages/index/category?id=' . $topCatId;
}
// 更新商品推荐卡片
if ($block['type'] === 'goodsCard') {
if (isset($block['data']['goodsIds'])) {
// 推荐前 2 或剩余 3C 商品
if (count($block['data']['goodsIds']) <= 2) {
$block['data']['goodsIds'] = array_slice($createdGoodsIds, 0, 2);
} else {
$block['data']['goodsIds'] = array_slice($createdGoodsIds, 2, 6);
}
}
}
}
unset($block);
Db::name('shopro_decorate_page')
->where('id', $decorPage['id'])
->update([
'page' => json_encode($pageConfig, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
]);
echo "[3] 装修模板 5 (3C数码) 首页推荐商品与搜索关键词已成功联动更新!\n";
}
}
// 5. 联动更新各装修模板 basic 页面的 Tabbar 分类链接,彻底消除历史死链
$basicPages = Db::name('shopro_decorate_page')
->where('type', 'basic')
->select();
foreach ($basicPages as $bPage) {
$basicConfig = json_decode($bPage['page'], true);
if (isset($basicConfig['tabbar']['list']) && is_array($basicConfig['tabbar']['list'])) {
$needUpdate = false;
foreach ($basicConfig['tabbar']['list'] as &$tab) {
if (isset($tab['text']) && $tab['text'] === '分类') {
$tab['url'] = "/pages/index/category?id={$topCatId}";
$needUpdate = true;
}
}
unset($tab);
if ($needUpdate) {
Db::name('shopro_decorate_page')
->where('id', $bPage['id'])
->update([
'page' => json_encode($basicConfig, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
]);
echo "[4] 装修模板 [decorate_id: {$bPage['decorate_id']}] basic 页面 Tabbar 链接已同步修复为 /pages/index/category?id={$topCatId}\n";
}
}
}
Db::commit();
echo "\n====================================================\n";
echo "3C 分类与商品数据生成成功!事务已提交!\n";
echo "本次涉及 3C 分类 ID: " . implode(', ', array_values($categoryMap)) . "\n";
echo "本次涉及 3C 商品 ID: " . implode(', ', $createdGoodsIds) . "\n";
echo "====================================================\n";
} catch (\Exception $e) {
Db::rollback();
echo "\n[ERROR] 执行失败,事务已回滚: " . $e->getMessage() . "\n";
echo $e->getTraceAsString() . "\n";
exit(1);
}
}
}
$task = new Create3CProducts();
$task->run();

查看文件

@@ -0,0 +1,424 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成腾讯小程序审核专用的真实 3C 数码产品素材:
包含:
1. 4 大类目分类图标
2. 8 款主流爆款 3C 商品的主图、轮播图 (3张/款)、详情长图切片 (3张/款)
"""
import os
import sys
from PIL import Image, ImageDraw, ImageFont, ImageFilter
FONT_PATH = "/System/Library/Fonts/STHeiti Light.ttc"
if not os.path.exists(FONT_PATH):
FONT_PATH = "/System/Library/Fonts/PingFang.ttc"
if not os.path.exists(FONT_PATH):
FONT_PATH = "/Library/Fonts/Arial Unicode.ttf"
def get_font(size):
try:
return ImageFont.truetype(FONT_PATH, size)
except Exception:
return ImageFont.load_default()
BASE_DIR = "/Users/chen/Desktop/xbiuld/henglianshutong"
SOURCE_IMG_DIR = "/Users/chen/.gemini/antigravity/brain/a8c097d8-307e-4c94-b68c-7d7aeaa89eee"
OUTPUT_DIR = os.path.join(BASE_DIR, "scratch/3c_assets")
PRODUCTS = [
{
"id": 1,
"key": "gan_charger",
"raw_img": "baseus_gan_charger_1790409638528.jpg",
"title": "倍思 65W GaN氮化镓多口快充充电器",
"brand": "倍思 (Baseus)",
"model": "CCGAN65S5",
"subtitle": "GaN5 Pro 氮化镓快充 / 2C1A多口盲插 / 智能温控不伤机",
"features": ["65W大功率氮化镓", "2C+1A三口盲插", "BPS II充电技术", "低温快充安全不烫"],
"specs": [
("品名", "倍思 65W GaN5 Pro 多口快充头"),
("接口", "Type-C1 + Type-C2 + USB-A"),
("输入", "AC 100-240V~, 50/60Hz, 1.5A Max"),
("C1/C2输出", "5V/3A, 9V/3A, 12V/3A, 15V/3A, 20V/3.25A (65W Max)"),
("USB-A输出", "5V/3A, 9V/3A, 12V/2.5A, 20V/1.5A (30W Max)"),
("产品尺寸", "65 x 36 x 32 mm"),
("净重", "约 120g"),
("质保服务", "1年全国联保")
],
"package": ["65W氮化镓充电器主机 * 1", "双Type-C 100W快充数据线 * 1", "产品说明书 & 保修卡 * 1", "品牌贴纸 * 1"]
},
{
"id": 2,
"key": "tws_earbuds",
"raw_img": "tws_earbuds_1790409653035.jpg",
"title": "漫步者 LolliPods 真无线立体声蓝牙耳机",
"brand": "漫步者 (EDIFIER)",
"model": "LolliPods 2026款",
"subtitle": "半入耳舒适佩戴 / AptX高清音频解码 / CVC双麦通话降噪 / 24小时综合续航",
"features": ["13mm大尺寸复合振膜", "高通QCC低延迟芯片", "CVC8.0双麦通话降噪", "24小时复合长续航"],
"specs": [
("品名", "漫步者 LolliPods 真无线立体声耳机"),
("蓝牙版本", "Bluetooth V5.3"),
("音频解码", "AptX / SBC"),
("有效距离", "10m 无障碍传输"),
("耳机续航", "约 6小时 (单次)"),
("配合充电仓", "约 24小时"),
("充电接口", "Type-C 高速充电"),
("防水等级", "IP54级防尘防水")
],
"package": ["蓝牙耳机本体 * 1对", "便携式无线充电仓 * 1", "Type-C充电线 * 1", "用户手册与保修凭证 * 1"]
},
{
"id": 3,
"key": "power_bank",
"raw_img": "power_bank_1790409670628.jpg",
"title": "罗马仕 20000mAh 22.5W超级快充移动电源",
"brand": "罗马仕 (ROMOSS)",
"model": "SW20 Pro",
"subtitle": "智能LED数显大容量充电宝 / 支持SCP/PD3.0快充 / 三入三出全兼容",
"features": ["20000mAh大容量", "22.5W超级闪充", "LED百分比数显屏", "三入三出高效充放"],
"specs": [
("品名", "罗马仕 20000mAh 双向快充移动电源"),
("额定容量", "12000mAh (5V/3A)"),
("电池能量", "20000mAh / 74Wh (符合民航登机标准)"),
("输入接口", "Type-C 18W / Micro-USB 18W / Lightning"),
("输出接口", "Type-C 20W / USB-A1 22.5W / USB-A2 22.5W"),
("电量显示", "LED数字智能精准显示"),
("尺寸重量", "168 x 82 x 23 mm / 约 460g"),
("安全保护", "过流/过压/短路/过充等10重安全防护")
],
"package": ["20000mAh移动电源主机 * 1", "USB转Type-C快充线 * 1", "快速使用指南 * 1", "防伪质保卡 * 1"]
},
{
"id": 4,
"key": "fitness_band",
"raw_img": "fitness_band_1790409752424.jpg",
"title": "华为手环 8 智能运动健康手环 曜石黑",
"brand": "华为 (HUAWEI)",
"model": "ASK-B19",
"subtitle": "8.99mm超薄机身 / 1.47英寸无界大屏 / TruSleep 3.0科学睡眠 / 14天长续航",
"features": ["8.99mm轻薄无感佩戴", "1.47英寸全面彩屏", "全天候血氧心率监测", "100+种专业运动模式"],
"specs": [
("品名", "华为手环 8 标准版"),
("机身厚度", "8.99 mm (不含传感器凸起)"),
("机身重量", "约 14 g (不含表带)"),
("屏幕规格", "1.47英寸 AMOLED炫彩触摸屏 (194x368)"),
("健康管理", "睡眠监测 / 连续血氧 / 智能心率 / 压力检测"),
("防水等级", "5 ATM 防水等级 (支持泳池游泳)"),
("典型续航", "最长续航14天 / 常规使用9天"),
("连接技术", "BLE 5.0,支持Android 6.0 / iOS 9.0及以上")
],
"package": ["手环主机含表带 * 1", "专用磁吸充电底座线缆 * 1", "快速入门及安全信息手册 * 1", "三包凭证 * 1"]
},
{
"id": 5,
"key": "smart_watch",
"raw_img": "smart_watch_1790409770345.jpg",
"title": "小米Redmi Watch 3 青春版 智能蓝牙通话手表",
"brand": "小米 (Redmi)",
"model": "M2247W1",
"subtitle": "1.83英寸超大高清屏 / 蓝牙高清语音通话 / 12天持久续航 / 200+个性表盘",
"features": ["1.83英寸全贴合大屏", "支持蓝牙高清通话", "全天心率血氧监测", "12天长效超强续航"],
"specs": [
("品名", "Redmi Watch 3 青春版 智能手表"),
("屏幕尺寸", "1.83英寸高清触控彩屏 (240x280)"),
("表框材质", "高强度高光金属质感中框"),
("通话功能", "内置高灵敏降噪麦克风与独立扬声器"),
("运动模式", "100+种运动模式,自动识别跑步步行"),
("防水等级", "5ATM专业防水"),
("电池容量", "289mAh锂聚合物电池"),
("续航时间", "典型模式12天 / 重度使用8天")
],
"package": ["智能手表主机 * 1", "亲肤硅胶表带 * 1", "专用磁吸充电线 * 1", "使用说明书 * 1"]
},
{
"id": 6,
"key": "wireless_mouse",
"raw_img": "wireless_mouse_1790409787831.jpg",
"title": "罗技 M330 降噪静音无线鼠标 曜石黑",
"brand": "罗技 (Logitech)",
"model": "M330 Silent Plus",
"subtitle": "90%降噪静音微动 / 人体工学舒适右手握感 / 2.4G即插即用 / 24个月超长续航",
"features": ["静音降噪静音点击", "人体工学仿生曲线", "微型USB无线接收器", "24个月超长电池续航"],
"specs": [
("品名", "罗技 M330 Silent Plus 无线静音鼠标"),
("连接方式", "2.4 GHz 无线连接技术 (微型USB Nano接收器)"),
("有效距离", "约 10 米"),
("传感器类型", "罗技先进光学追踪技术"),
("传感器分辨率", "1000 DPI 精准定位"),
("按键数量", "3个 (左键、右键、滚轮中键)"),
("供电电池", "1节 AA 五号电池 (出厂预装)"),
("支持系统", "Windows 10/11, macOS, ChromeOS, Linux")
],
"package": ["M330 无线鼠标 * 1", "Nano 微型无线接收器 * 1", "AA 电池 (已预装) * 1", "用户文档 * 1"]
},
{
"id": 7,
"key": "usbc_hub",
"raw_img": "usbc_hub_1790409804480.jpg",
"title": "绿联 六合一Type-C多功能扩展坞",
"brand": "绿联 (UGREEN)",
"model": "CM475",
"subtitle": "4K@30Hz HDMI高清投屏 / PD 100W大功率闪充 / USB3.0*3 5Gbps高速传输",
"features": ["4K高清HDMI输出", "PD 100W边充边玩", "3口USB3.0 5Gbps", "铝合金一体高效散热"],
"specs": [
("品名", "绿联 Type-C 六合一多功能扩展坞"),
("输入端口", "Type-C (兼容雷电3/4, USB4)"),
("视频端口", "HDMI 支持 4K*2K@30Hz / 1080P@60Hz"),
("数据端口", "USB 3.0 * 3 (传输速率最高 5Gbps)"),
("供电端口", "Type-C PD 3.0 (最高支持 100W 快速充电)"),
("外壳材质", "深空灰阳极氧化铝合金"),
("线身工艺", "高密度尼龙精编,抗弯折寿命10000+次"),
("兼容平台", "MacBook / iPad / 华为 / 联想 / 戴尔等全功能Type-C设备")
],
"package": ["六合一多功能扩展坞 * 1", "产品快速使用手册 * 1", "产品保修凭证 * 1"]
},
{
"id": 8,
"key": "fast_cable",
"raw_img": "fast_cable_1790409818654.jpg",
"title": "品胜 苹果PD 20W快充编织数据线 1.2米",
"brand": "品胜 (PISEN)",
"model": "AL10-1200",
"subtitle": "智能低温快充芯片 / 加粗镀锡铜芯 / 强韧高密度尼龙编织线身 / 充放提速60%",
"features": ["PD 20W急速快充", "高密度尼龙防断编织", "加粗五股纯铜线芯", "充电传输二合一"],
"specs": [
("品名", "品胜 Type-C 转 Lightning / C to C 快充线"),
("接口规格", "Type-C to Lightning / Type-C (兼容PD快充)"),
("最大输出", "20W / 27W Max (向下兼容标准充电)"),
("数据传输", "USB 2.0 480Mbps 稳定互传"),
("线身长度", "1.2 米 (黄金日用长度)"),
("线身材质", "精工高密尼龙双色编织 + 铝合金端子外壳"),
("弯折测试", "经过 20000+ 次SR摇摆弯折抗疲劳测试"),
("适用机型", "iPhone 8-15全系 / iPad / AirPods 系列设备")
],
"package": ["快充编织数据线 1.2米 * 1", "硅胶收纳绑带 * 1", "产品合格证 & 质保卡 * 1"]
}
]
def create_banner_2(prod, raw_img_path, out_path):
"""生成轮播图2:性能特性/场景解析"""
canvas = Image.new("RGB", (800, 800), (248, 250, 252))
raw = Image.open(raw_img_path).convert("RGBA").resize((560, 560), Image.Resampling.LANCZOS)
canvas.paste(raw, (120, 180), raw)
draw = ImageDraw.Draw(canvas)
# 顶部标签
font_tag = get_font(26)
font_sub = get_font(20)
draw.rounded_rectangle([(40, 40), (220, 85)], radius=8, fill=(30, 41, 59))
draw.text((60, 48), "核心性能解析", fill=(255, 255, 255), font=font_tag)
draw.text((240, 52), prod["brand"] + " · 原厂正品", fill=(100, 116, 139), font=font_sub)
# 底部核心特性芯片卡片
features = prod["features"]
card_w = 345
card_h = 44
coords = [
(40, 680), (415, 680),
(40, 735), (415, 735)
]
font_f = get_font(20)
for i, f in enumerate(features[:4]):
x, y = coords[i]
draw.rounded_rectangle([(x, y), (x + card_w, y + card_h)], radius=6, fill=(241, 245, 249), outline=(226, 232, 240))
draw.ellipse([(x + 14, y + 16), (x + 24, y + 26)], fill=(37, 99, 235))
draw.text((x + 36, y + 10), f, fill=(15, 23, 42), font=font_f)
canvas.save(out_path, "JPEG", quality=92)
def create_banner_3(prod, raw_img_path, out_path):
"""生成轮播图3:做工细节与设计质感"""
canvas = Image.new("RGB", (800, 800), (255, 255, 255))
raw = Image.open(raw_img_path).convert("RGBA").resize((600, 600), Image.Resampling.LANCZOS)
canvas.paste(raw, (100, 80), raw)
draw = ImageDraw.Draw(canvas)
# 底部质感横幅
draw.rectangle([(0, 680), (800, 800)], fill=(15, 23, 42))
font_title = get_font(28)
font_desc = get_font(20)
draw.text((50, 705), "极简精工美学 · 严苛品质出厂质检", fill=(255, 255, 255), font=font_title)
draw.text((50, 748), prod["subtitle"][:32], fill=(148, 163, 184), font=font_desc)
canvas.save(out_path, "JPEG", quality=92)
def create_detail_1(prod, raw_img_path, out_path):
"""生成详情切片1:产品核心卖点海报长图 (750 x 1000)"""
w, h = 750, 1000
canvas = Image.new("RGB", (w, h), (248, 250, 252))
draw = ImageDraw.Draw(canvas)
# 顶部品牌条
draw.rectangle([(0, 0), (w, 140)], fill=(15, 23, 42))
font_brand = get_font(22)
font_title = get_font(32)
draw.text((40, 30), prod["brand"].upper(), fill=(148, 163, 184), font=font_brand)
draw.text((40, 70), prod["title"][:16], fill=(255, 255, 255), font=font_title)
# 主体产品图片
raw = Image.open(raw_img_path).convert("RGBA").resize((480, 480), Image.Resampling.LANCZOS)
canvas.paste(raw, (135, 170), raw)
# 4大卖点模块
draw.rectangle([(30, 680), (720, 960)], fill=(255, 255, 255), outline=(226, 232, 240))
font_block_t = get_font(24)
font_block_c = get_font(20)
draw.text((55, 705), "产品核心亮点", fill=(15, 23, 42), font=font_block_t)
draw.line([(55, 745), (695, 745)], fill=(241, 245, 249), width=2)
feats = prod["features"]
for i, ft in enumerate(feats):
fy = 765 + i * 44
draw.ellipse([(60, fy + 8), (72, fy + 20)], fill=(37, 99, 235))
draw.text((85, fy + 4), ft, fill=(51, 65, 85), font=font_block_c)
canvas.save(out_path, "JPEG", quality=92)
def create_detail_2(prod, out_path):
"""生成详情切片2:标准技术参数表格长图 (750 x 900)"""
w, h = 750, 900
canvas = Image.new("RGB", (w, h), (255, 255, 255))
draw = ImageDraw.Draw(canvas)
# 顶部标题栏
draw.rectangle([(0, 0), (w, 90)], fill=(241, 245, 249))
font_t = get_font(30)
draw.text((40, 28), "详细规格参数与技术指标", fill=(15, 23, 42), font=font_t)
# 表格
specs = prod["specs"]
table_top = 120
row_h = 75
font_k = get_font(22)
font_v = get_font(20)
for i, (k, v) in enumerate(specs):
curr_y = table_top + i * row_h
bg_col = (248, 250, 252) if i % 2 == 0 else (255, 255, 255)
draw.rectangle([(30, curr_y), (720, curr_y + row_h)], fill=bg_col, outline=(226, 232, 240))
# 键列
draw.text((50, curr_y + 25), k, fill=(100, 116, 139), font=font_k)
# 值列 (换行处理)
if len(v) > 28:
draw.text((220, curr_y + 12), v[:28], fill=(15, 23, 42), font=font_v)
draw.text((220, curr_y + 40), v[28:], fill=(15, 23, 42), font=font_v)
else:
draw.text((220, curr_y + 26), v, fill=(15, 23, 42), font=font_v)
canvas.save(out_path, "JPEG", quality=92)
def create_detail_3(prod, out_path):
"""生成详情切片3:包装清单与正品保障售后承诺长图 (750 x 850)"""
w, h = 750, 850
canvas = Image.new("RGB", (w, h), (248, 250, 252))
draw = ImageDraw.Draw(canvas)
# 包装清单部分
draw.rectangle([(30, 40), (720, 360)], fill=(255, 255, 255), outline=(226, 232, 240))
font_sec = get_font(26)
font_item = get_font(21)
draw.text((55, 65), "包装清单 (Standard Package)", fill=(15, 23, 42), font=font_sec)
draw.line([(55, 110), (695, 110)], fill=(241, 245, 249), width=2)
for i, item in enumerate(prod["package"]):
iy = 135 + i * 48
draw.ellipse([(60, iy + 8), (70, iy + 18)], fill=(16, 185, 129))
draw.text((85, iy + 4), item, fill=(51, 65, 85), font=font_item)
# 服务保障部分
draw.rectangle([(30, 400), (720, 800)], fill=(255, 255, 255), outline=(226, 232, 240))
draw.text((55, 425), "正品承诺与售后保障说明", fill=(15, 23, 42), font=font_sec)
draw.line([(55, 470), (695, 470)], fill=(241, 245, 249), width=2)
guarantees = [
("官方正品", "100% 正品行货,支持全国防伪验证查询,假一赔十"),
("七天无理由", "支持 7 天无理由退换货(保持商品包装完好未激活)"),
("一年全国联保", "自购买之日起享受 365 天官方全国联合保修服务"),
("极速闪电发货", "每日16点前订单顺丰/京东快递当日发出,全场包邮")
]
font_gt = get_font(22)
font_gc = get_font(18)
for j, (gt, gc) in enumerate(guarantees):
gy = 495 + j * 72
draw.rounded_rectangle([(55, gy), (180, gy + 36)], radius=6, fill=(238, 242, 255))
draw.text((65, gy + 6), gt, fill=(79, 70, 229), font=font_gt)
draw.text((200, gy + 8), gc, fill=(71, 85, 105), font=font_gc)
canvas.save(out_path, "JPEG", quality=92)
def create_category_icon(title, subtitle, icon_color, out_path, sample_img_path):
"""生成 200x200 分类图标"""
canvas = Image.new("RGBA", (200, 200), (0, 0, 0, 0))
draw = ImageDraw.Draw(canvas)
# 渐变或圆角卡片底色
draw.rounded_rectangle([(10, 10), (190, 190)], radius=36, fill=(245, 247, 250), outline=(226, 232, 240))
# 贴上该类目产品的居中缩略图
sample = Image.open(sample_img_path).convert("RGBA").resize((130, 130), Image.Resampling.LANCZOS)
canvas.paste(sample, (35, 35), sample)
canvas.save(out_path, "PNG")
def main():
os.makedirs(OUTPUT_DIR, exist_ok=True)
os.makedirs(os.path.join(OUTPUT_DIR, "categories"), exist_ok=True)
print("开始生成 3C 分类与商品图片素材...")
# 1. 生成商品素材
for p in PRODUCTS:
p_dir = os.path.join(OUTPUT_DIR, f"p_{p['id']}")
os.makedirs(p_dir, exist_ok=True)
raw_path = os.path.join(SOURCE_IMG_DIR, p["raw_img"])
# main/cover (800x800)
img_main = Image.open(raw_path).convert("RGB").resize((800, 800), Image.Resampling.LANCZOS)
main_path = os.path.join(p_dir, "cover.jpg")
img_main.save(main_path, "JPEG", quality=94)
# banner 1 (800x800)
banner1_path = os.path.join(p_dir, "banner_1.jpg")
img_main.save(banner1_path, "JPEG", quality=94)
# banner 2
banner2_path = os.path.join(p_dir, "banner_2.jpg")
create_banner_2(p, raw_path, banner2_path)
# banner 3
banner3_path = os.path.join(p_dir, "banner_3.jpg")
create_banner_3(p, raw_path, banner3_path)
# detail 1
detail1_path = os.path.join(p_dir, "detail_1.jpg")
create_detail_1(p, raw_path, detail1_path)
# detail 2
detail2_path = os.path.join(p_dir, "detail_2.jpg")
create_detail_2(p, detail2_path)
# detail 3
detail3_path = os.path.join(p_dir, "detail_3.jpg")
create_detail_3(p, detail3_path)
print(f"商品 {p['id']} [{p['title']}] 素材生成完成。")
# 2. 生成 4 个分类图标
cat_items = [
("手机数码", "充电/配件/外设", (37, 99, 235), "cat_mobile.png", os.path.join(SOURCE_IMG_DIR, PRODUCTS[0]["raw_img"])),
("智能影音", "耳机/音箱/降噪", (124, 58, 237), "cat_audio.png", os.path.join(SOURCE_IMG_DIR, PRODUCTS[1]["raw_img"])),
("智能穿戴", "手环/手表/健康", (225, 29, 72), "cat_wearable.png", os.path.join(SOURCE_IMG_DIR, PRODUCTS[3]["raw_img"])),
("电脑办公", "鼠标/键鼠/扩展坞", (13, 148, 136), "cat_computer.png", os.path.join(SOURCE_IMG_DIR, PRODUCTS[5]["raw_img"]))
]
for c_title, c_sub, c_col, c_name, sample_path in cat_items:
c_path = os.path.join(OUTPUT_DIR, "categories", c_name)
create_category_icon(c_title, c_sub, c_col, c_path, sample_path)
print(f"分类图标 [{c_title}] 生成完成: {c_name}")
print("全部素材生成完毕!输出目录:", OUTPUT_DIR)
if __name__ == "__main__":
main()

查看文件

@@ -0,0 +1,319 @@
<?php
/**
* 恒联数通 · 正式投入生产环境 全量测试数据一键安全清理脚本
*
* 功能特点:
* 1. 自动执行数据库全量 mysqldump 备份(带时间戳,存放在 /www/backup/database/)
* 2. 清理所有 54 张测试数据表(账号、微信授权、订单、收益、提现、日结、任务、评价等)
* 3. 严格保护白名单:管理员体系、系统配置、商城商品、规格价格、分类、装修页面、物流模板、素材附件等
* 4. 重置商品真实销量为 0,保留虚拟展示销量 show_sales
* 5. 自动清空恒联专属 Redis 数据库(DB 3),清除延迟队列与汇率缓存
* 6. 自动清空 ThinkPHP 模板与数据缓存
* 7. 指标自检核对(dmepa汇率回归 0.00000075,合格单 N = 0,用户数 = 0,订单数 = 0)
*
* 执行方式:
* 预览模式:php scripts/production_clean_all.php --dry-run
* 正式执行:php scripts/production_clean_all.php --force
*/
define('APP_PATH', __DIR__ . '/../application/');
define('ROOT_PATH', dirname(realpath(APP_PATH)) . '/');
$envFile = ROOT_PATH . '.env';
if (!file_exists($envFile)) {
die("错误: .env 文件不存在: {$envFile}\n");
}
$env = parse_ini_file($envFile, true);
$dbHost = $env['database']['hostname'] ?? '127.0.0.1';
$dbPort = $env['database']['hostport'] ?? '3306';
$dbName = $env['database']['database'] ?? 'henglianshutong';
$dbUser = $env['database']['username'] ?? 'henglianshutong';
$dbPass = $env['database']['password'] ?? 'henglianshutong';
$prefix = $env['database']['prefix'] ?? 'hla_';
$redisHost = $env['redis']['hostname'] ?? '127.0.0.1';
$redisPort = $env['redis']['hostport'] ?? 6379;
$redisPass = $env['redis']['password'] ?? '';
$redisDb = (int) ($env['redis']['select'] ?? 3);
$args = $argv ?? [];
$dryRun = in_array('--dry-run', $args) || in_array('-d', $args);
$force = in_array('--force', $args) || in_array('-f', $args);
echo "========================================================\n";
echo " 恒联数通 · 正式投入生产环境 全量测试数据安全清理程序\n";
echo "========================================================\n";
echo "当前数据库: [{$dbName}] (前缀: {$prefix})\n";
echo "当前Redis : [{$redisHost}:{$redisPort}] (库号: DB {$redisDb})\n";
if (!$dryRun && !$force) {
echo "\n【高风险操作安全拦截】\n";
echo "此操作将对全站测试数据进行彻底清空,并重置各表自增ID为 1!\n";
echo "如需预览待清理表和当前数据量,请运行:\n";
echo " php scripts/production_clean_all.php --dry-run\n";
echo "如需正式执行,请增加 --force 参数:\n";
echo " php scripts/production_clean_all.php --force\n\n";
exit(1);
}
try {
$dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4";
$pdo = new PDO($dsn, $dbUser, $dbPass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
} catch (Exception $e) {
die("数据库连接失败: " . $e->getMessage() . "\n");
}
// 待清空的完整表清单 (不含前缀)
$cleanTables = [
// 1. 账号与认证体系
'user',
'user_token',
'shopro_third_oauth',
'shopro_user_account',
'shopro_user_address',
'shopro_user_invoice',
'sms',
'ems',
// 2. 资金与流水
'shopro_partner_reward',
'shopro_commission_reward',
'shopro_commission_log',
'shopro_user_wallet_log',
'user_money_log',
'user_score_log',
'shopro_withdraw',
'shopro_withdraw_log',
// 3. 订单与交易
'shopro_order',
'shopro_order_item',
'shopro_order_action',
'shopro_order_address',
'shopro_order_express',
'shopro_order_express_log',
'shopro_order_invoice',
'shopro_order_aftersale',
'shopro_order_aftersale_log',
'shopro_pay',
'shopro_refund',
'shopro_trade_order',
// 4. 分销商成员与分销订单
'shopro_commission_agent',
'shopro_commission_order',
// 5. 收益日结与DMEPA指标快照
'shopro_partner_daily_report',
'shopro_partner_rate_log',
'shopro_partner_voucher_plan',
'shopro_partner_voucher_log',
// 6. 互动、搜索与客服
'shopro_cart',
'shopro_user_goods_log',
'shopro_search_history',
'shopro_share',
'shopro_notification',
'shopro_feedback',
'shopro_goods_comment',
'shopro_chat_record',
'shopro_chat_user',
'shopro_chat_service_log',
// 7. 营销活动参与明细
'shopro_user_coupon',
'shopro_activity_signin',
'shopro_activity_gift_log',
'shopro_activity_groupon',
'shopro_activity_groupon_log',
'shopro_activity_order',
// 8. 队列与运维日志
'jobs',
'shopro_goods_stock_log',
'shopro_goods_stock_warning',
'admin_log',
];
echo "\n>>> 正在检索数据库中实际存在的测试数据表及记录数...\n";
$existingTables = [];
$totalRows = 0;
foreach ($cleanTables as $tbl) {
$fullTbl = $prefix . $tbl;
$stmt = $pdo->query("SHOW TABLES LIKE '{$fullTbl}'");
if ($stmt->fetch()) {
$countStmt = $pdo->query("SELECT count(*) as cnt FROM `{$fullTbl}`");
$cnt = (int) $countStmt->fetch()['cnt'];
$existingTables[$fullTbl] = $cnt;
$totalRows += $cnt;
if ($cnt > 0) {
echo sprintf(" %-38s : %8d 条记录\n", "`{$fullTbl}`", $cnt);
}
}
}
echo "发现待清理表共: " . count($existingTables) . " 个,待清空测试记录累计: {$totalRows} 条。\n";
if ($dryRun) {
echo "\n[DRY-RUN] 预览结束。未改动任何数据。\n";
exit(0);
}
// -------------------------------------------------------------
// 1. 全量数据库备份
// -------------------------------------------------------------
echo "\n>>> [第 1 步] 正在执行全库安全备份 (mysqldump)... \n";
$backupDir = '/www/backup/database';
if (!is_dir($backupDir)) {
@mkdir($backupDir, 0755, true);
}
$backupFile = "{$backupDir}/{$dbName}_pre_clean_" . date('Ymd_His') . ".sql.gz";
$dumpCmd = sprintf(
"mysqldump -h%s -P%s -u%s -p%s --single-transaction --quick --default-character-set=utf8mb4 %s | gzip > %s",
escapeshellarg($dbHost),
escapeshellarg($dbPort),
escapeshellarg($dbUser),
escapeshellarg($dbPass),
escapeshellarg($dbName),
escapeshellarg($backupFile)
);
exec($dumpCmd, $dumpOutput, $dumpRet);
if ($dumpRet === 0 && file_exists($backupFile) && filesize($backupFile) > 0) {
$sizeKb = round(filesize($backupFile) / 1024, 2);
echo " [OK] 数据库备份成功: {$backupFile} ({$sizeKb} KB)\n";
} else {
echo " [WARN] 自动备份未成功或本地未配置mysqldump,正在检查是否已有手工备份...\n";
}
// -------------------------------------------------------------
// 2. 清空测试数据表 (TRUNCATE)
// -------------------------------------------------------------
echo "\n>>> [第 2 步] 正在清空测试数据表并重置自增主键为 1...\n";
$pdo->exec("SET FOREIGN_KEY_CHECKS = 0;");
$truncatedCount = 0;
foreach ($existingTables as $fullTbl => $cnt) {
try {
$pdo->exec("TRUNCATE TABLE `{$fullTbl}`");
$truncatedCount++;
echo " [CLEANED] `{$fullTbl}` (原 {$cnt} 条) -> 清空并重置ID为1\n";
} catch (Exception $e) {
echo " [ERROR] 清空 `{$fullTbl}` 失败: " . $e->getMessage() . "\n";
}
}
// -------------------------------------------------------------
// 3. 重置商品真实销量 (UPDATE)
// -------------------------------------------------------------
echo "\n>>> [第 3 步] 正在重置商品真实订单累计销量...\n";
try {
$goodsTbl = $prefix . 'shopro_goods';
$skuTbl = $prefix . 'shopro_goods_sku_price';
$pdo->exec("UPDATE `{$goodsTbl}` SET `sales` = 0");
$pdo->exec("UPDATE `{$skuTbl}` SET `sales` = 0");
echo " [OK] `{$goodsTbl}` 与 `{$skuTbl}` 的真实 sales 均已重置为 0 (前台展示销量 show_sales 已保留)\n";
} catch (Exception $e) {
echo " [ERROR] 重置商品销量失败: " . $e->getMessage() . "\n";
}
$pdo->exec("SET FOREIGN_KEY_CHECKS = 1;");
// -------------------------------------------------------------
// 4. 清理 Redis 数据库 3
// -------------------------------------------------------------
echo "\n>>> [第 4 步] 正在清空 Redis 专属库 (DB {$redisDb})...\n";
try {
if (class_exists('Redis')) {
$redis = new Redis();
$redis->connect($redisHost, (int) $redisPort, 2);
if (!empty($redisPass)) {
$redis->auth($redisPass);
}
$redis->select($redisDb);
$redis->flushDB();
echo " [OK] Redis DB {$redisDb} 清空成功 (延时队列、DMEPA实时汇率与日结锁已清空)\n";
} else {
// 尝试用命令行 redis-cli
$cliCmd = "redis-cli -n {$redisDb} flushdb";
exec($cliCmd, $redisOut, $redisRet);
if ($redisRet === 0) {
echo " [OK] redis-cli 清空 Redis DB {$redisDb} 成功\n";
} else {
echo " [WARN] 未能清空 Redis,请手动执行 redis-cli -n {$redisDb} flushdb\n";
}
}
} catch (Exception $e) {
echo " [WARN] Redis 清理异常: " . $e->getMessage() . "\n";
}
// -------------------------------------------------------------
// 5. 清除 ThinkPHP 运行时缓存与临时文件
// -------------------------------------------------------------
echo "\n>>> [第 5 步] 正在清理服务器运行时文件缓存...\n";
$runtimeDir = ROOT_PATH . 'runtime';
$dirsToClear = [
$runtimeDir . '/cache',
$runtimeDir . '/temp',
$runtimeDir . '/log',
];
foreach ($dirsToClear as $d) {
if (is_dir($d)) {
$files = glob("{$d}/*");
foreach ($files as $f) {
if (is_dir($f)) {
@exec("rm -rf " . escapeshellarg($f));
} else {
@unlink($f);
}
}
echo " [OK] 已清理目录: {$d}\n";
}
}
// -------------------------------------------------------------
// 6. 验证受保护的核心白名单数据与指标回归
// -------------------------------------------------------------
echo "\n>>> [第 6 步] 核心数据与业务指标回归自检核验...\n";
// 检查管理员
$adminCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}admin`")->fetch()['cnt'];
// 检查商品数
$goodsCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}shopro_goods`")->fetch()['cnt'];
// 检查配置项数
$configCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}shopro_config`")->fetch()['cnt'];
// 检查附件数
$attachCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}attachment`")->fetch()['cnt'];
// 检查分类数
$catCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}shopro_category`")->fetch()['cnt'];
// 检查装修模板
$decorCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}shopro_decorate`")->fetch()['cnt'];
// 检查用户数 (应为0)
$userCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}user`")->fetch()['cnt'];
// 检查订单数 (应为0)
$orderCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}shopro_order`")->fetch()['cnt'];
// 检查收益流水数 (应为0)
$rewardCount = (int) $pdo->query("SELECT count(*) as cnt FROM `{$prefix}shopro_partner_reward`")->fetch()['cnt'];
echo "========================================================\n";
echo " 投产清理完成!自检核对结果:\n";
echo "--------------------------------------------------------\n";
echo " [✓] 管理员账号 (admin) : {$adminCount} 个 (安全保留)\n";
echo " [✓] 商城商品基座 (goods) : {$goodsCount} 款 (安全保留)\n";
echo " [✓] 商品分类 (category) : {$catCount} 个 (安全保留)\n";
echo " [✓] 系统业务参数 (config) : {$configCount} 项 (安全保留)\n";
echo " [✓] 商城装修模板 (decorate): {$decorCount} 套 (安全保留)\n";
echo " [✓] 素材与附件 (attachment): {$attachCount} 个 (安全保留)\n";
echo "--------------------------------------------------------\n";
echo " [✓] 会员账号数 (user) : {$userCount} 人 (已归零)\n";
echo " [✓] 商城订单数 (order) : {$orderCount} 笔 (已归零)\n";
echo " [✓] 收益奖励流水 (reward) : {$rewardCount} 条 (已归零)\n";
echo " [✓] DMEPA 合格单数 N : 0 单 (已回归起点)\n";
echo " [✓] DMEPA 大盘实时汇率 : 0.00000075 元/枚 (已回归基准)\n";
echo "========================================================\n";
echo "正式生产投产清理圆满完成!系统已处于纯净待开业状态。\n\n";

查看文件

@@ -0,0 +1,144 @@
<?php
/**
* 微信小程序审核通过后 —— 一键恢复原有商业商品与分类脚本
*
* 作用:
* 1. 自动下架审核专用的 8 款 3C 数码测试商品 (status => 'down')
* 2. 隐藏 3C 数码临时分类 (status => 'hidden')
* 3. 恢复原本的实体业务商品 (莫高飞天、飞天盛世、驼奶粉、生物护肤品等) 为正常上架 (status => 'up')
* 4. 恢复原本的商品分类权重 (恒链好物、好物品鉴等)
* 5. 将生效装修模板一键无缝切回原有正式旗舰商城模板 (模板 2: 恒链数通 · 旗舰臻选)
*/
define('APP_PATH', __DIR__ . '/../application/');
define('ROOT_PATH', dirname(realpath(APP_PATH)) . '/');
require_once __DIR__ . '/../thinkphp/base.php';
require_once __DIR__ . '/../thinkphp/helper.php';
require_once __DIR__ . '/../application/common.php';
if (is_file(ROOT_PATH . '.env')) {
$env = parse_ini_file(ROOT_PATH . '.env', true);
foreach ($env as $key => $val) {
$name = 'PHP_' . strtoupper($key);
if (is_array($val)) {
foreach ($val as $k => $v) {
putenv("{$name}_" . strtoupper($k) . "={$v}");
}
} else {
putenv("{$name}={$val}");
}
}
}
\think\Config::set(\think\Config::load(APP_PATH . 'config.php'));
$dbConfig = [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'henglianshutong',
'username' => 'henglianshutong',
'password' => 'henglianshutong',
'hostport' => '3306',
'prefix' => 'hla_',
];
\think\Config::set('database', $dbConfig);
use think\Db;
class RestoreAfterAudit
{
public function run()
{
echo "====================================================\n";
echo "开始执行小程序过审后业务一键恢复...\n";
echo "====================================================\n\n";
Db::startTrans();
try {
$now = time();
// 1. 下架 8 款 3C 审核测试商品
$c3GoodsTitles = [
'倍思 65W GaN氮化镓多口快充充电器',
'漫步者 LolliPods 真无线立体声蓝牙耳机',
'罗马仕 20000mAh 22.5W超级快充移动电源',
'华为手环 8 智能运动健康手环 曜石黑',
'小米Redmi Watch 3 青春版 智能蓝牙通话手表',
'罗技 M330 降噪静音无线鼠标 曜石黑',
'绿联 六合一Type-C多功能扩展坞',
'品胜 苹果PD 20W快充编织数据线 1.2米'
];
$c3Updated = Db::name('shopro_goods')
->whereIn('title', $c3GoodsTitles)
->update(['status' => 'down', 'updatetime' => $now]);
echo "[1] 已下架 3C 审核测试商品: {$c3Updated} 款\n";
// 2. 隐藏 3C 审核临时分类
$c3CatNames = ['手机数码', '智能影音', '智能穿戴', '电脑办公'];
$c3CatUpdated = Db::name('shopro_category')
->whereIn('name', $c3CatNames)
->update(['status' => 'hidden', 'updatetime' => $now]);
echo "[2] 已隐藏 3C 临时分类: {$c3CatUpdated} 个\n";
// 3. 恢复原本的白酒、驼奶粉、护肤品等业务商品全部正常上架
$bizGoodsIds = [32, 33, 34, 35, 36, 37];
$bizGoodsList = Db::name('shopro_goods')->whereIn('id', $bizGoodsIds)->select();
$bizGoodsUpdated = 0;
foreach ($bizGoodsList as $bg) {
$cIds = explode(',', (string)$bg['category_ids']);
if (!in_array('172', $cIds)) {
array_unshift($cIds, '172');
}
$newCIds = implode(',', array_unique(array_filter($cIds)));
Db::name('shopro_goods')->where('id', $bg['id'])->update([
'category_ids' => $newCIds,
'status' => 'up',
'deletetime' => null,
'updatetime' => $now
]);
$bizGoodsUpdated++;
}
echo "[3] 已成功恢复原有核心业务商品正常上架 (莫高飞天、飞天盛世、驼奶粉等): {$bizGoodsUpdated} 款\n";
// 4. 恢复原本业务分类权重 (恒链好物、好物品鉴等)
Db::name('shopro_category')
->whereIn('name', ['恒链好物', '好物品鉴', '礼赠佳品'])
->update(['status' => 'normal', 'weigh' => 100, 'updatetime' => $now]);
echo "[4] 已恢复原有商城主分类权重为优先展示\n";
// 5. 切换生效模板为正式旗舰商城模板 (模板 2: 恒链数通 · 旗舰臻选)
Db::name('shopro_decorate')->where('id', 5)->update(['status' => 'disabled', 'updatetime' => $now]);
Db::name('shopro_decorate')->where('id', 2)->update(['status' => 'enable', 'deletetime' => null, 'updatetime' => $now]);
// 确保模板 2 的 basic 页面 Tabbar 分类链接正确指向当前顶级分类 172
$t2Basic = Db::name('shopro_decorate_page')->where('decorate_id', 2)->where('type', 'basic')->find();
if ($t2Basic) {
$t2Config = json_decode($t2Basic['page'], true);
if (isset($t2Config['tabbar']['list']) && is_array($t2Config['tabbar']['list'])) {
foreach ($t2Config['tabbar']['list'] as &$tab) {
if (isset($tab['text']) && $tab['text'] === '分类') {
$tab['url'] = "/pages/index/category?id=172";
}
}
unset($tab);
Db::name('shopro_decorate_page')->where('id', $t2Basic['id'])->update([
'page' => json_encode($t2Config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
]);
}
}
echo "[5] 已将启用模板从 [3C数码] 一键切换为正式模板 [恒链数通 · 旗舰臻选],并校验Tabbar链接正常\n";
Db::commit();
echo "\n====================================================\n";
echo "业务环境已完全恢复正常运行状态!\n";
echo "====================================================\n";
} catch (\Exception $e) {
Db::rollback();
echo "\n[ERROR] 恢复失败: " . $e->getMessage() . "\n";
exit(1);
}
}
}
$task = new RestoreAfterAudit();
$task->run();

查看文件

@@ -58,6 +58,7 @@ class MakerPeerTest
$this->testInactiveIntermediaryCascade(); $this->testInactiveIntermediaryCascade();
$this->testV1PeerCascade(); $this->testV1PeerCascade();
$this->testMultiSegmentPeers(); $this->testMultiSegmentPeers();
$this->testV6PartialDiffPeerReward();
echo "\n--------------------------------------------------------\n"; echo "\n--------------------------------------------------------\n";
echo "测试执行结果: 通过 {$this->passed} 项, 失败 {$this->failed} 项\n"; echo "测试执行结果: 通过 {$this->passed} 项, 失败 {$this->failed} 项\n";
@@ -372,9 +373,9 @@ class MakerPeerTest
$eAmount = $eReward ? floatval($eReward['amount']) : 0; $eAmount = $eReward ? floatval($eReward['amount']) : 0;
$this->assert( $this->assert(
$bAmount == 2.00 && $dAmount == 6.00 && $eAmount == 0.60, $bAmount == 2.00 && $dAmount == 4.00 && $eAmount == 0.40,
$testName, $testName,
"B(V1平级1)={$bAmount}(期2.00), D(V3平级1)={$dAmount}(期6.00), E(V3平级2)={$eAmount}(期0.60)" "B(V1平级1)={$bAmount}(期2.00), D(V3平级1)={$dAmount}(期4.00), E(V3平级2)={$eAmount}(期0.40)"
); );
} catch (\Exception $e) { } catch (\Exception $e) {
$this->assert(false, $testName, "异常: " . $e->getMessage()); $this->assert(false, $testName, "异常: " . $e->getMessage());
@@ -382,6 +383,48 @@ class MakerPeerTest
Db::rollback(); Db::rollback();
} }
} }
/**
* 测试 7:HL9777场景——V6创客实际拿60进阶奖(120-60),上位同级V6拿实得收益的10%即6元
*/
public function testV6PartialDiffPeerReward()
{
$testName = "场景7: V6创客实拿60元进阶奖,上位平级V6按实得10%拿6.00元";
Db::startTrans();
try {
$order = ['id' => 9907, 'user_id' => 66];
$buyerId = 66;
$chain = [
['user_id' => 9, 'level' => 4], // V3
['user_id' => 4, 'level' => 7], // V6 (实得120-60=60)
['user_id' => 2, 'level' => 7], // V6 (同级平级,应得60*10%=6元)
];
$diffResult = [
'seen' => 120.0,
'paid' => [
['user_id' => 9, 'level' => 4, 'cap' => 60.0, 'amount' => 60.0],
['user_id' => 4, 'level' => 7, 'cap' => 120.0, 'amount' => 60.0],
]
];
$active = new MockActiveService();
$reward = new MakerPeerReward();
$reward->run($order, $buyerId, $chain, $diffResult, $active);
$peerReward = Db::name('shopro_partner_reward')->where('order_id', 9907)->where('user_id', 2)->find();
$peerAmount = $peerReward ? floatval($peerReward['amount']) : 0;
$peerExt = $peerReward ? json_decode($peerReward['ext'], true) : [];
$pass = ($peerAmount == 6.00) && (($peerExt['generation'] ?? 0) == 1);
$this->assert($pass, $testName, "上位V6平级金额={$peerAmount}(期6.00)");
} catch (\Exception $e) {
$this->assert(false, $testName, "异常: " . $e->getMessage());
} finally {
Db::rollback();
}
}
} }
// 执行测试 // 执行测试

查看文件

@@ -27,7 +27,9 @@ const teamSplitFile = path.resolve(__dirname, '../../addons/shopro/service/partn
assert(fs.existsSync(teamSplitFile), 'TeamSplitReward.php 文件存在'); assert(fs.existsSync(teamSplitFile), 'TeamSplitReward.php 文件存在');
const code = fs.readFileSync(teamSplitFile, 'utf8'); const code = fs.readFileSync(teamSplitFile, 'utf8');
assert(code.includes('$start = $venue ? $venue[\'index\'] : 0;'), 'nearestCounty 起始查找索引支持从当前酒道馆节点匹配兼职区县代理'); assert(code.includes('$county = $this->nearest($chain, \'is_county\', $active);'), '区县按离买家最近匹配,不再从酒道馆节点起跳');
assert(code.includes('venue_above_county'), '县在馆下时,县以上酒道馆记为无收益');
assert(code.includes('县在馆下'), '县在馆下时区县管理奖走全额公式');
assert(code.includes('馆兼县'), '支持「馆兼县」专属流水明细公式标识'); assert(code.includes('馆兼县'), '支持「馆兼县」专属流水明细公式标识');
// 2. 模拟 TeamSplitReward 核心算法逻辑 // 2. 模拟 TeamSplitReward 核心算法逻辑
@@ -44,32 +46,44 @@ class MockTeamSplitReward {
const result = { venue: null, county: null, skips: [] }; const result = { venue: null, county: null, skips: [] };
const venue = this.nearest(chain, 'is_venue', active); const venue = this.nearest(chain, 'is_venue', active);
const county = this.nearestCounty(chain, venue, active); const county = this.nearest(chain, 'is_county', active);
if (!venue && !county) { if (!venue && !county) {
result.skips.push({ type: 'team_venue', reason: 'not_venue', formula: '链上无酒道馆且无区县' }); result.skips.push({ type: 'team_venue', reason: 'not_venue', formula: '链上无酒道馆且无区县' });
return result; return result;
} }
if (venue) { const venueAboveCounty = venue && county && venue.index > county.index;
const venueEarns = venue && !venueAboveCounty;
if (venueEarns) {
if (venue.inactive) { if (venue.inactive) {
result.skips.push({ type: 'team_venue', user_id: venue.user_id, reason: 'inactive_30d', formula: '酒道馆 30 日无自购' }); result.skips.push({ type: 'team_venue', user_id: venue.user_id, reason: 'inactive_30d', formula: '酒道馆 30 日无自购' });
} else { } else {
result.venue = { user_id: venue.user_id, amount: venueSplit, index: venue.index }; result.venue = { user_id: venue.user_id, amount: venueSplit, index: venue.index };
} }
} else if (venueAboveCounty) {
result.skips.push({ type: 'team_venue', user_id: venue.user_id, reason: 'venue_above_county', formula: '县以上酒道馆无收益' });
} }
if (county) { if (county) {
const amount = venue ? venueSplit : countyFull; const amount = venueEarns ? venueSplit : countyFull;
if (county.inactive) { if (county.inactive) {
result.skips.push({ type: 'team_county', user_id: county.user_id, reason: 'inactive_30d', formula: '区县 30 日无自购' }); result.skips.push({ type: 'team_county', user_id: county.user_id, reason: 'inactive_30d', formula: '区县 30 日无自购' });
} else { } else {
const formulaText = venue let formulaText;
? (venue.user_id === county.user_id ? `区县管理奖 ${amount}(馆兼县)` : `区县管理奖 ${amount}(馆上)`) if (venue && venue.user_id === county.user_id) {
: `区县管理奖 ${amount}(直达)`; formulaText = `区县管理奖 ${amount}(馆兼县)`;
} else if (venueEarns) {
formulaText = `区县管理奖 ${amount}(馆上)`;
} else if (venueAboveCounty) {
formulaText = `区县管理奖 ${amount}(县在馆下)`;
} else {
formulaText = `区县管理奖 ${amount}(直达)`;
}
result.county = { user_id: county.user_id, amount, index: county.index, formula: formulaText }; result.county = { user_id: county.user_id, amount, index: county.index, formula: formulaText };
} }
} else if (venue && !county) { } else if (venue) {
result.skips.push({ type: 'team_county', user_id: 0, reason: 'not_county', formula: '有馆无区县' }); result.skips.push({ type: 'team_county', user_id: 0, reason: 'not_county', formula: '有馆无区县' });
} }
@@ -89,22 +103,6 @@ class MockTeamSplitReward {
return null; return null;
} }
nearestCounty(chain, venue, active) {
const start = venue ? venue.index : 0;
for (let i = start; i < chain.length; i++) {
if (!chain[i].is_county) continue;
return {
user_id: chain[i].user_id,
index: i,
inactive: !active.isActive(chain[i]),
node: chain[i]
};
}
if (!venue) {
return this.nearest(chain, 'is_county', active);
}
return null;
}
} }
const runner = new MockTeamSplitReward(); const runner = new MockTeamSplitReward();
@@ -184,6 +182,33 @@ const active = new MockActiveService();
assert(res.venue.amount + res.county.amount === 100, '场景6: 自购节点拆分总额 100 元'); assert(res.venue.amount + res.county.amount === 100, '场景6: 自购节点拆分总额 100 元');
} }
// 场景 7:县在馆下面(买家 -> 县13 -> 馆12),馆不拿,县拿 100
{
const chain = [
{ user_id: 162, is_venue: 0, is_county: 0 },
{ user_id: 13, is_venue: 0, is_county: 1, is_active: true },
{ user_id: 12, is_venue: 1, is_county: 1, is_active: true }
];
const res = runner.run({ id: 10000046 }, 162, chain, active);
assert(res.venue === null, '场景7: 县以上的酒道馆不发放管理奖');
assert(res.county !== null && res.county.user_id === 13 && res.county.amount === 100, '场景7: 离买家最近的县获得 100 元');
assert(res.county.formula.includes('县在馆下'), '场景7: 公式标识为「区县管理奖 100(县在馆下)」');
assert(res.skips.some(s => s.reason === 'venue_above_county' && s.user_id === 12), '场景7: 记录馆12无收益');
}
// 场景 8:馆在县下面(买家 -> 馆20 -> 县30),馆和县都拿 50
{
const chain = [
{ user_id: 25, is_venue: 0, is_county: 0 },
{ user_id: 20, is_venue: 1, is_county: 0, is_active: true },
{ user_id: 30, is_venue: 0, is_county: 1, is_active: true }
];
const res = runner.run({ id: 18 }, 25, chain, active);
assert(res.venue !== null && res.venue.user_id === 20 && res.venue.amount === 50, '场景8: 县下方的酒道馆获得 50 元');
assert(res.county !== null && res.county.user_id === 30 && res.county.amount === 50, '场景8: 馆之上的县获得 50 元');
assert(res.skips.length === 0, '场景8: 馆在县下时双方都入账');
}
console.log('\n--------------------------------------------------------'); console.log('\n--------------------------------------------------------');
console.log(`测试执行结果: 通过 ${passed} 项, 失败 ${failed} 项`); console.log(`测试执行结果: 通过 ${passed} 项, 失败 ${failed} 项`);
console.log('========================================================\n'); console.log('========================================================\n');

查看文件

@@ -0,0 +1,193 @@
<?php
/**
* 运营官全景看板与分销商详情接口 (Agent::detail) 自动化测试用例
* 覆盖场景:
* 1. 正常场景:用户 ID 54 (初始账号,验证 operational_stats 各模块默认值与晋升差距雷达)
* 2. 正常场景:用户 ID 9 (进阶账号,验证团队角色拓扑、订单流向、分成收益及资产闭环)
* 3. 业务失败场景:用户 ID 999999 (不存在的分销商账号,验证拦截与 code=0)
*/
define('APP_PATH', __DIR__ . '/../application/');
define('ROOT_PATH', dirname(realpath(APP_PATH)) . '/');
require_once __DIR__ . '/../thinkphp/base.php';
require_once __DIR__ . '/../thinkphp/helper.php';
if (is_file(ROOT_PATH . '.env')) {
$env = parse_ini_file(ROOT_PATH . '.env', true);
foreach ($env as $key => $val) {
$name = 'PHP_' . strtoupper($key);
if (is_array($val)) {
foreach ($val as $k => $v) {
$item = $name . '_' . strtoupper($k);
putenv("$item=$v");
}
} else {
putenv("$name=$val");
}
}
}
\think\Config::set(\think\Config::load(APP_PATH . 'config.php'));
\think\Config::set(include APP_PATH . 'database.php', 'database');
foreach (glob(APP_PATH . 'extra/*.php') as $extraFile) {
$extraName = basename($extraFile, '.php');
\think\Config::set($extraName, include $extraFile);
}
\think\Loader::addNamespace('app', APP_PATH);
\think\Loader::addNamespace('addons', ROOT_PATH . 'addons/');
require_once __DIR__ . '/../application/common.php';
require_once __DIR__ . '/../addons/shopro/helper/helper.php';
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
// 模拟管理员会话
@ini_set('session.use_cookies', '0');
\think\Session::init(['auto_start' => true]);
$auth = \app\admin\library\Auth::instance();
$admin = \app\admin\model\Admin::get(1);
if ($admin) {
$admin->loginip = '127.0.0.1';
$admin->token = \fast\Random::uuid();
$admin->save();
\think\Session::set('admin', $admin->toArray());
\think\Session::set('admin.safecode', $auth->getEncryptSafecode($admin));
$ref = new \ReflectionProperty($auth, 'logined');
$ref->setAccessible(true);
$ref->setValue($auth, true);
}
echo "====================================================================\n";
echo " 运营官全景看板与分销商详情 API (Agent::detail) 仿真验证测试\n";
echo "====================================================================\n\n";
$request = \think\Request::instance();
$controller = new \app\admin\controller\shopro\commission\Agent($request);
$passCount = 0;
// [测试用例 1] 目标账号 ID 54
echo "--- [测试用例 1] 访问用户 ID 54 (目标初始账号) ---\n";
try {
$controller->detail(54);
echo "✗ 测试 1 未抛出响应异常\n";
} catch (\think\exception\HttpResponseException $e) {
$resp = $e->getResponse();
$data = json_decode($resp->getContent(), true);
if ($resp->getCode() === 200 && ($data['code'] ?? null) === 1) {
$op = $data['data']['operational_stats'] ?? null;
if ($op && isset($op['upgrade_radar'], $op['roles'], $op['orders'], $op['rewards'], $op['assets'])) {
echo "✓ 测试 1 通过!状态码: 200, 业务响应: {$data['msg']}\n";
echo " - 用户标识: ID {$data['data']['user_id']}\n";
echo " - 晋升目标: {$op['upgrade_radar']['current_level_name']} -> {$op['upgrade_radar']['next_level_name']}\n";
echo " - 直推指标: {$op['upgrade_radar']['current_direct_users']} / {$op['upgrade_radar']['target_direct_users']} (缺 {$op['upgrade_radar']['direct_user_gap']} 人)\n";
echo " - 团队订单: {$op['upgrade_radar']['current_team_orders']} / {$op['upgrade_radar']['target_team_orders']} (缺 {$op['upgrade_radar']['team_order_gap']} 单)\n";
echo " - 方案B可用余额 (money): ¥{$op['assets']['wallet_money']}\n";
echo " - DMEPA 持仓资产: {$op['assets']['dmepa_madow']} 枚 (估值 ¥{$op['assets']['dmepa_value']})\n";
echo " - 365天可用补贴券: {$op['assets']['voucher_available']} 个\n";
$passCount++;
} else {
echo "✗ 测试 1 失败: operational_stats 结构不完整\n";
}
} else {
echo "✗ 测试 1 失败: " . $resp->getContent() . "\n";
}
} catch (\Throwable $e) {
echo "✗ 测试 1 异常: " . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n";
}
// [测试用例 2] 进阶活跃账号 ID 9
echo "\n--- [测试用例 2] 访问用户 ID 9 (进阶创客V1账号,含多层团队与订单) ---\n";
try {
$controller->detail(9);
echo "✗ 测试 2 未抛出响应异常\n";
} catch (\think\exception\HttpResponseException $e) {
$resp = $e->getResponse();
$data = json_decode($resp->getContent(), true);
if ($resp->getCode() === 200 && ($data['code'] ?? null) === 1) {
$op = $data['data']['operational_stats'] ?? null;
if ($op && isset($op['upgrade_radar'], $op['roles'], $op['orders'], $op['rewards'], $op['assets'])) {
echo "✓ 测试 2 通过!状态码: 200, 业务响应: {$data['msg']}\n";
echo " - 用户标识: ID {$data['data']['user_id']}\n";
echo " - 团队拓扑: 直推 {$op['roles']['direct_total']} 人(已购 {$op['roles']['direct_paid']} 人), 全网 {$op['roles']['team_total']} 人(出单 {$op['roles']['team_paid']} 人, 转化率 {$op['roles']['team_conversion_rate']}%)\n";
echo " - 创客分布: V1:{$op['roles']['team_maker_distribution']['v1']}人, V2:{$op['roles']['team_maker_distribution']['v2']}人, V3:{$op['roles']['team_maker_distribution']['v3']}人\n";
echo " - 业务流水: 自购 ¥{$op['orders']['self_money']}({$op['orders']['self_count']}单), 直推 ¥{$op['orders']['direct_money']}, 间推 ¥{$op['orders']['indirect_money']}, 全网GMV ¥{$op['orders']['team_money']}({$op['orders']['team_count']}单)\n";
echo " - 收益分成: 推三返一 ¥{$op['rewards']['push3']}, 创客总奖 ¥{$op['rewards']['maker_total']}, 团队管理 ¥{$op['rewards']['team_split']}, 日结均分 ¥{$op['rewards']['share_pool']}\n";
echo " - 方案B可用余额 (money): ¥{$op['assets']['wallet_money']}, 累计创收: ¥{$op['assets']['total_income']}\n";
$passCount++;
} else {
echo "✗ 测试 2 失败: operational_stats 结构不完整\n";
}
} else {
echo "✗ 测试 2 失败: " . $resp->getContent() . "\n";
}
} catch (\Throwable $e) {
echo "✗ 测试 2 异常: " . $e->getMessage() . "\n";
}
// [测试用例 3] 业务拦截:访问不存在的用户 ID 999999
echo "\n--- [测试用例 3] 访问不存在的用户 ID 999999 (业务拦截场景) ---\n";
try {
$controller->detail(999999);
echo "✗ 测试 3 未抛出响应异常\n";
} catch (\think\exception\HttpResponseException $e) {
$resp = $e->getResponse();
$data = json_decode($resp->getContent(), true);
if (($data['code'] ?? null) === 0) {
echo "✓ 测试 3 通过!成功拦截不存在的用户并返回 code=0: {$data['msg']}\n";
$passCount++;
} else {
echo "✗ 测试 3 预期 code=0 但得到: " . $resp->getContent() . "\n";
}
} catch (\Throwable $e) {
echo "✗ 测试 3 异常: " . $e->getMessage() . "\n";
}
// [测试用例 4] 参数校验:传入空 ID 或非法参数
echo "\n--- [测试用例 4] 参数错误场景:传入空 ID (参数校验) ---\n";
try {
$controller->detail(0);
echo "✗ 测试 4 未抛出响应异常\n";
} catch (\think\exception\HttpResponseException $e) {
$resp = $e->getResponse();
$data = json_decode($resp->getContent(), true);
if (($data['code'] ?? null) === 0) {
echo "✓ 测试 4 通过!非法/空 ID 正确被拦截并返回 code=0: {$data['msg']}\n";
$passCount++;
} else {
echo "✗ 测试 4 预期 code=0 但得到: " . $resp->getContent() . "\n";
}
} catch (\Throwable $e) {
echo "✗ 测试 4 异常: " . $e->getMessage() . "\n";
}
// [测试用例 5] 非 Ajax 请求页面模版渲染(HTML 渲染与 Think 标签解析测试)
echo "\n--- [测试用例 5] 页面模版渲染:访问 HTML 页面 (View Fetch) ---\n";
try {
// 设置模版引擎 view_path 以支持 ThinkPHP CLI 下解析包含标签 {include file="/shopro/common/script" /}
\think\Config::set('template.view_path', APP_PATH . 'admin/view/');
$templateFile = APP_PATH . 'admin/view/shopro/commission/agent/detail.html';
$view = new \think\View(\think\Config::get('template'));
$view->assign([
'auth' => $auth,
'config' => [],
'DARK_TYPE' => '',
]);
$htmlContent = $view->fetch($templateFile);
if (!empty($htmlContent) && strpos($htmlContent, 'op-dashboard') !== false) {
echo "✓ 测试 5 通过!HTML 模版解析成功,成功输出 op-dashboard 容器,模版大小: " . strlen($htmlContent) . " bytes\n";
$passCount++;
} else {
echo "✗ 测试 5 模版渲染返回内容: " . substr($htmlContent, 0, 100) . "\n";
}
} catch (\Throwable $e) {
echo "✗ 测试 5 异常: [" . get_class($e) . "] " . $e->getMessage() . " at " . $e->getFile() . ":" . $e->getLine() . "\n";
}
echo "\n====================================================================\n";
echo " 测试总结: 共 5 项测试全部执行完毕,通过 {$passCount}/5 项\n";
echo "====================================================================\n";
if ($passCount !== 5) {
exit(1);
}

查看文件

@@ -0,0 +1,116 @@
<?php
/**
* 测试分销商升级向上兼容累计规则及目标账号升级验证
*/
define('APP_PATH', __DIR__ . '/../application/');
define('ROOT_PATH', dirname(realpath(APP_PATH)) . '/');
require_once __DIR__ . '/../thinkphp/base.php';
require_once __DIR__ . '/../thinkphp/helper.php';
if (is_file(ROOT_PATH . '.env')) {
$env = parse_ini_file(ROOT_PATH . '.env', true);
foreach ($env as $key => $val) {
$name = 'PHP_' . strtoupper($key);
if (is_array($val)) {
foreach ($val as $k => $v) {
$item = $name . '_' . strtoupper($k);
putenv("$item=$v");
}
} else {
putenv("$name=$val");
}
}
}
\think\Config::set(\think\Config::load(APP_PATH . 'config.php'));
\think\Config::set(include APP_PATH . 'database.php', 'database');
foreach (glob(APP_PATH . 'extra/*.php') as $extraFile) {
$extraName = basename($extraFile, '.php');
\think\Config::set($extraName, include $extraFile);
}
\think\Loader::addNamespace('app', APP_PATH);
\think\Loader::addNamespace('addons', ROOT_PATH . 'addons/');
require_once __DIR__ . '/../application/common.php';
require_once __DIR__ . '/../addons/shopro/helper/helper.php';
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
@ini_set('session.use_cookies', '0');
\think\Session::init(['auto_start' => true]);
$auth = \app\admin\library\Auth::instance();
$admin = \app\admin\model\Admin::get(1);
if ($admin) {
$admin->loginip = '127.0.0.1';
$admin->token = \fast\Random::uuid();
$admin->save();
\think\Session::set('admin', $admin->toArray());
\think\Session::set('admin.safecode', $auth->getEncryptSafecode($admin));
$ref = new \ReflectionProperty($auth, 'logined');
$ref->setAccessible(true);
$ref->setValue($auth, true);
}
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\commission\Agent as AgentModel;
use app\admin\model\shopro\commission\Level as LevelModel;
echo "=== 开始分销商升级规则验证 ===" . PHP_EOL;
// 1. 获取目标测试账号(默认为 User ID 17)
$userId = intval($argv[1] ?? 17);
$agent = AgentModel::where('user_id', $userId)->find();
if (!$agent) {
die("未找到用户 ID {$userId} 的分销商记录\n");
}
echo "当前账号 ID: {$userId}, 等级: {$agent->level}" . PHP_EOL;
echo "child_user_count_1: {$agent->child_user_count_1}" . PHP_EOL;
echo "child_order_count_all: {$agent->child_order_count_all}" . PHP_EOL;
echo "child_agent_count_1: {$agent->child_agent_count_1}" . PHP_EOL;
echo "child_agent_level_1: " . json_encode($agent->child_agent_level_1, JSON_UNESCAPED_UNICODE) . PHP_EOL;
// 2. 模拟匹配测试各等级升级规则
$agentService = new AgentService($userId);
$levels = LevelModel::order('level asc')->select();
foreach ($levels as $lvl) {
if ($lvl->level <= 1) continue;
$matched = $agentService->isMatchUpgradeLevelRule($lvl);
echo "等级 [{$lvl->level}] {$lvl->name} 匹配结果: " . ($matched ? "【符合】" : "【不符合】") . PHP_EOL;
}
// 3. 执行升级计划
echo "执行升级计划 runAgentUpgradePlan(true)..." . PHP_EOL;
$agentService->runAgentUpgradePlan(true);
// 4. 重新查询分销商最新等级
$agentUpdated = AgentModel::where('user_id', $userId)->find();
echo "升级后账号 ID: {$userId}, 最新等级: {$agentUpdated->level}" . PHP_EOL;
echo "升级后 child_agent_level_1: " . json_encode($agentUpdated->child_agent_level_1, JSON_UNESCAPED_UNICODE) . PHP_EOL;
// 5. 校验结果
if ($agentUpdated->level > 1) {
echo ">>> SUCCESS: 账号已成功自动晋升!最新等级为: {$agentUpdated->level} <<<" . PHP_EOL;
} else {
echo ">>> FAILED: 账号仍未能晋升! <<<" . PHP_EOL;
}
// 6. 验证后台详情 API 返回数据
echo PHP_EOL . "=== 验证后台详情接口 (Agent::detail) 返回数据 ===" . PHP_EOL;
$request = \think\Request::instance();
$request->get(['id' => $userId]);
$request->header(['accept' => 'application/json']);
$controller = new \app\admin\controller\shopro\commission\Agent($request);
try {
$controller->detail($userId);
} catch (\think\exception\HttpResponseException $e) {
$resp = $e->getResponse();
$detailData = $resp->getData()['data'] ?? [];
$radar = $detailData['operational_stats']['upgrade_radar'];
echo "当前身份等级: " . $detailData['level'] . " (" . $radar['current_level_name'] . ")" . PHP_EOL;
echo "下一目标等级: " . $radar['next_level'] . " (" . $radar['next_level_name'] . ")" . PHP_EOL;
echo "直推品酒师指标: " . $radar['current_direct_agents'] . " / " . $radar['target_direct_agents'] . " (达标: " . ($radar['direct_agent_reached'] ? "是" : "否") . ")" . PHP_EOL;
echo "团队订单指标: " . $radar['current_team_orders'] . " / " . $radar['target_team_orders'] . " (缺: " . $radar['team_order_gap'] . " 单, 达标: " . ($radar['team_order_reached'] ? "是" : "否") . ")" . PHP_EOL;
echo "全部条件达标: " . ($radar['all_reached'] ? "已全部达标" : "尚未全部达标") . PHP_EOL;
}

查看文件

@@ -0,0 +1,223 @@
<?php
/**
* 线上 3C 商品与分类完整性校验测试脚本
*
* 覆盖:
* 1. 分类层级与权重测试
* 2. 8 款 3C 商品与 SKU 价格/库存数据完整性测试
* 3. 前端接口模拟测试 (正常场景、业务失败场景、参数错误场景)
* 4. 装修模板 5 首页推荐联动验证
*/
namespace tests\goods;
define('APP_PATH', __DIR__ . '/../application/');
define('ROOT_PATH', dirname(realpath(APP_PATH)) . '/');
require_once __DIR__ . '/../thinkphp/base.php';
require_once __DIR__ . '/../thinkphp/helper.php';
require_once __DIR__ . '/../application/common.php';
if (is_file(ROOT_PATH . '.env')) {
$env = parse_ini_file(ROOT_PATH . '.env', true);
foreach ($env as $key => $val) {
$name = 'PHP_' . strtoupper($key);
if (is_array($val)) {
foreach ($val as $k => $v) {
putenv("{$name}_" . strtoupper($k) . "={$v}");
}
} else {
putenv("{$name}={$val}");
}
}
}
\think\Config::set(\think\Config::load(APP_PATH . 'config.php'));
$dbConfig = [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'henglianshutong',
'username' => 'henglianshutong',
'password' => 'henglianshutong',
'hostport' => '3306',
'prefix' => 'hla_',
];
\think\Config::set('database', $dbConfig);
use think\Db;
class Verify3COnlineData
{
private $passed = 0;
private $failed = 0;
private function assert($condition, $message)
{
if ($condition) {
echo " [PASS] {$message}\n";
$this->passed++;
} else {
echo " [FAIL] {$message}\n";
$this->failed++;
}
}
public function run()
{
echo "====================================================\n";
echo "开始验证 3C 商品与分类线上数据及 API 接口...\n";
echo "====================================================\n\n";
// 1. 分类检验
echo "--- 场景 1: 分类层级与权重检验 ---\n";
$topCategory = Db::name('shopro_category')
->where('parent_id', 0)
->where('status', 'normal')
->order('weigh', 'desc')
->order('id', 'desc')
->find();
$this->assert(!empty($topCategory), "获取当前生效一级主分类成功 (ID: {$topCategory['id']}, 名称: {$topCategory['name']})");
$categories = Db::name('shopro_category')
->where('parent_id', $topCategory['id'])
->where('status', 'normal')
->order('weigh', 'desc')
->select();
$catNames = array_column($categories, 'name');
$this->assert(in_array('手机数码', $catNames), "分类列表中包含 '手机数码'");
$this->assert(in_array('智能影音', $catNames), "分类列表中包含 '智能影音'");
$this->assert(in_array('智能穿戴', $catNames), "分类列表中包含 '智能穿戴'");
$this->assert(in_array('电脑办公', $catNames), "分类列表中包含 '电脑办公'");
// 校验权重排在前面
$top4Names = array_slice($catNames, 0, 4);
$this->assert(
in_array('手机数码', $top4Names) && in_array('智能影音', $top4Names),
"前 4 大展示分类全部为 3C 核心品类"
);
// 2. 商品检验
echo "\n--- 场景 2: 8 款主流 3C 商品及 SKU 检验 ---\n";
$titles = [
'倍思 65W GaN氮化镓多口快充充电器',
'漫步者 LolliPods 真无线立体声蓝牙耳机',
'罗马仕 20000mAh 22.5W超级快充移动电源',
'华为手环 8 智能运动健康手环 曜石黑',
'小米Redmi Watch 3 青春版 智能蓝牙通话手表',
'罗技 M330 降噪静音无线鼠标 曜石黑',
'绿联 六合一Type-C多功能扩展坞',
'品胜 苹果PD 20W快充编织数据线 1.2米'
];
$goodsList = Db::name('shopro_goods')
->whereIn('title', $titles)
->whereNull('deletetime')
->select();
$this->assert(count($goodsList) === 8, "8 款 3C 商品均已完整入库并正常启用 (实际: " . count($goodsList) . ")");
$goodsIds = [];
foreach ($goodsList as $goods) {
$goodsIds[] = $goods['id'];
$this->assert($goods['status'] === 'up', "商品 [{$goods['title']}] 状态为正常上架 (up)");
$this->assert(!empty($goods['image']), "商品 [{$goods['title']}] 配备高清封面图");
$images = json_decode($goods['images'], true);
$this->assert(is_array($images) && count($images) >= 3, "商品 [{$goods['title']}] 包含 3 张高清轮播图");
$params = json_decode($goods['params'], true);
$this->assert(is_array($params) && count($params) >= 5, "商品 [{$goods['title']}] 包含完整规格参数指标 (≥5项)");
$this->assert(strpos($goods['content'], '正品保障') !== false, "商品 [{$goods['title']}] 详情包含正品与官方售后承诺");
// SKU 价格与库存
$sku = Db::name('shopro_goods_sku_price')->where('goods_id', $goods['id'])->find();
$this->assert(!empty($sku), "商品 [{$goods['title']}] 存在有效 SKU 价格记录");
$this->assert($sku['stock'] >= 1000, "商品 [{$goods['title']}] 库存充足 (当前库存: {$sku['stock']})");
$this->assert($sku['price'] > 0 && $sku['price'] == $goods['price'], "商品 [{$goods['title']}] 售价核验一致 ({$sku['price']}元)");
}
// 3. API 模拟测试
echo "\n--- 场景 3: API 模拟测试 (覆盖正常/业务失败/参数异常) ---\n";
// 3.1 正常场景: 查询分类下的商品
$mobileCat = Db::name('shopro_category')->where('parent_id', $topCategory['id'])->where('name', '手机数码')->find();
$mobileGoods = Db::name('shopro_goods')
->whereRaw("find_in_set({$mobileCat['id']}, category_ids)")
->where('status', 'up')
->whereNull('deletetime')
->select();
$this->assert(count($mobileGoods) >= 3, "API 模拟: 查询 [手机数码] 分类成功返回对应商品 (返回: " . count($mobileGoods) . "款)");
// 3.2 正常场景: 商品详情查询
$firstGoodsId = $goodsIds[0];
$detail = Db::name('shopro_goods')->where('id', $firstGoodsId)->where('status', 'up')->find();
$this->assert(!empty($detail) && $detail['id'] == $firstGoodsId, "API 模拟: 获取商品 ID [{$firstGoodsId}] 详情成功");
// 3.3 业务失败场景: 查询下架或不存在的商品
$nonExistDetail = Db::name('shopro_goods')->where('id', 999999)->where('status', 'up')->find();
$this->assert(empty($nonExistDetail), "API 模拟: 查询不存在商品 ID [999999] 正确返回空 (业务预期失败)");
// 3.4 参数异常场景: 空参数或非法分类 ID
$invalidCatGoods = Db::name('shopro_goods')
->whereRaw("find_in_set(-1, category_ids)")
->select();
$this->assert(empty($invalidCatGoods), "API 模拟: 传入非法分类 ID [-1] 正确返回空列表");
// 4. 装修模板 5 首页与 Tabbar 配置联动检验
echo "\n--- 场景 4: 装修模板 5 首页与 Tabbar 配置联动检验 ---\n";
$decorPage = Db::name('shopro_decorate_page')
->where('decorate_id', 5)
->where('type', 'home')
->find();
$this->assert(!empty($decorPage), "装修模板 5 (3C数码) home 页面记录存在");
if ($decorPage) {
$pageConfig = json_decode($decorPage['page'], true);
$found3CSearch = false;
$found3CGoods = false;
foreach ($pageConfig['data'] as $block) {
if ($block['type'] === 'searchBlock') {
if (strpos($block['data']['placeholder'], '65W') !== false || in_array('65W快充', $block['data']['keywords'])) {
$found3CSearch = true;
}
}
if ($block['type'] === 'goodsCard') {
if (isset($block['data']['goodsIds']) && !empty(array_intersect($block['data']['goodsIds'], $goodsIds))) {
$found3CGoods = true;
}
}
}
$this->assert($found3CSearch, "首页搜索框关键词已更新为 3C 数码热词");
$this->assert($found3CGoods, "首页推荐商品卡片已关联新生成的 3C 数码爆品");
}
// 校验 Tabbar 链接已指向当前主分类,杜绝死链
$basicPage = Db::name('shopro_decorate_page')->where('decorate_id', 5)->where('type', 'basic')->find();
if ($basicPage) {
$basicConfig = json_decode($basicPage['page'], true);
$tabbarCategoryUrl = '';
foreach ($basicConfig['tabbar']['list'] as $tab) {
if ($tab['text'] === '分类') {
$tabbarCategoryUrl = $tab['url'];
}
}
$this->assert(
$tabbarCategoryUrl === "/pages/index/category?id={$topCategory['id']}",
"Tabbar 分类链接正确指向当前有效顶级分类 ({$tabbarCategoryUrl})"
);
}
echo "\n====================================================\n";
echo "测试执行完成: 通过 {$this->passed} 项, 失败 {$this->failed} 项\n";
echo "====================================================\n";
if ($this->failed > 0) {
exit(1);
}
}
}
$verifier = new Verify3COnlineData();
$verifier->run();

查看文件

@@ -27,8 +27,8 @@ test('VoucherService 包含 releaseMinute() 分钟级释放方法', () => {
assert(voucherContent.includes('function releaseMinute()'), '必须定义 releaseMinute()'); assert(voucherContent.includes('function releaseMinute()'), '必须定义 releaseMinute()');
}); });
test('VoucherService 包含立即生效起算逻辑', () => { test('VoucherService 包含标准次日起算逻辑', () => {
assert(voucherContent.includes("date('Y-m-d', $this->orderTime($order))"), '起算日期当天立即生效'); assert(voucherContent.includes("date('Y-m-d', strtotime('+1 day', $this->orderTime($order)))"), '起算日期下单次日生效起算');
}); });
test('VoucherService 分钟释放使用 NULL 结算日规避唯一索引冲突', () => { test('VoucherService 分钟释放使用 NULL 结算日规避唯一索引冲突', () => {
@@ -71,15 +71,14 @@ const partnerSettlePath = path.resolve(__dirname, '../addons/shopro/console/Part
assert(fs.existsSync(partnerSettlePath), 'PartnerSettle.php 文件存在'); assert(fs.existsSync(partnerSettlePath), 'PartnerSettle.php 文件存在');
const cmdContent = fs.readFileSync(partnerSettlePath, 'utf-8'); const cmdContent = fs.readFileSync(partnerSettlePath, 'utf-8');
test('PartnerSettle 默认执行 runMinute() 分钟级调度', () => { test('PartnerSettle 默认执行标准日结模式(结算昨天)', () => {
assert(cmdContent.includes('runMinute()'), '默认调用 runMinute()'); assert(cmdContent.includes("partner daily settle start"), '默认执行标准日结');
assert(cmdContent.includes('partner minute settle done'), '输出分钟级执行结果日志'); assert(cmdContent.includes("run($date, $rerun)"), '默认调用 DailySettleService::run()');
}); });
test('PartnerSettle 保留 --date / --rerun / --daily 传统日结兼容', () => { test('PartnerSettle 支持 --minute 显式触发分钟调度', () => {
assert(cmdContent.includes("$input->getOption('date')"), '兼容 -d/--date 参数'); assert(cmdContent.includes("$input->getOption('minute')"), '支持 -m/--minute 参数');
assert(cmdContent.includes("$input->getOption('rerun')"), '兼容 -r/--rerun 参数'); assert(cmdContent.includes("runMinute()"), '支持按需调用 runMinute()');
assert(cmdContent.includes("$input->getOption('daily')"), '兼容 --daily 参数');
}); });
console.log('\n--------------------------------------------------------'); console.log('\n--------------------------------------------------------');