fastadmin shopro uni-app分销商城 功能定制 二次开发

最近在折腾FastAdmin+Shopro的uniapp分销商城时发现,有些功能得自己动手才能满足运营需求。比如前两天遇到个客户非要三级分销改五级,这玩意不改底层代码真顶不住。

fastadmin shopro uni-app分销商城 功能定制 二次开发

在Shopro的Distribute模型里,层级关系藏在level_config字段。原生的配置处理是这样玩的:

// application/admin/model/Distribute.php
public function setLevelConfigAttr($value)
{
    return json_encode(array_map('intval', $value));
}

想搞自定义层级的话,得在后台管理加个动态配置项。我直接魔改了后台的distribute.html模板,塞了个可增减的表单项:

<div class="form-group">
    <label class="control-label">分销层级设置</label>
    <div id="level-container">
        <input type="number" class="form-control level-input" 
               name="row[level_config][]" 
               v-for="(item,index) in levelConfig" 
               v-model="levelConfig[index]">
    </div>
    <button @click="addLevel" type="button" class="btn btn-success btn-xs">+</button>
</div>

前端uniapp那边处理佣金计算才是重头戏。分销订单详情页的佣金展示得跟着动态层级走,原生的fixed(2)金额处理遇到分佣比例0.88%这种小数位数多的就得改:

// uni-app pages/order/detail.vue
computed: {
    formattedCommission() {
        return this.commissionRates.map(rate => {
            const precision = rate.toString().split('.')[1]?.length || 0
            return (this.orderAmount * rate).toFixed(precision + 2)
        })
    }
}

数据库层面得注意分佣记录表的扩展性。建议单独建个commission_flow表而不是用JSON字段,升级时加个触发器自动同步历史数据:

CREATE TRIGGER sync_commission AFTER INSERT ON orders
FOR EACH ROW
BEGIN
    INSERT INTO commission_flow (user_id, level, amount)
    SELECT distributor_id, 
           FIND_IN_SET(distributor_id, NEW.distribute_chain)-1,
           NEW.amount * (SELECT rate FROM distribute_levels WHERE level = FIND_IN_SET(...))
    FROM ...
END;

二次开发最坑的是插件升级冲突,建议在extends目录里搞继承开发。比如扩展分销中心的时候,别直接改ShoproController,自己建个MyDistributeController继承原类:

// application/admin/controller/MyDistribute.php
class MyDistribute extends \app\admin\controller\ShoproController
{
    public function index()
    {
        parent::index();
        // 追加自定义统计逻辑
        $this->assign('custom_data', $this->getCustomStats());
    }
}

缓存策略也得优化,分销配置这种高频读取的数据别老查数据库。在runtime目录里搞个本地缓存,比用Redis还快:

$cacheFile = RUNTIME_PATH . 'distribute_config.cache';
if (!file_exists($cacheFile) || time()-filemtime($cacheFile) > 3600) {
    $config = Model::get()->toArray();
    file_put_contents($cacheFile, serialize($config));
}
$currentConfig = unserialize(file_get_contents($cacheFile));

搞分销系统最忌死磕源码,多利用FastAdmin的插件机制。最近给客户加了个分销团队人数实时统计,直接挂载到user表的查询事件上,比改核心代码优雅多了:

// 在插件入口文件里挂载事件
Hook::add('user_after_select', function($users) {
    foreach ($users as &$user) {
        $user['team_count'] = Db::name('distribute_relation')
            ->where('leader_chain', 'like', '%,'.$user['id'].',%')
            ->count();
    }
    return $users;
});

改完记得在后台权限管理里把新加的功能路由配上,不然运营妹子又要炸毛。这套组合拳打下来,基本上能满足90%的分销定制需求,剩下的10%就看客户钱包厚度了。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐