You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.2 KiB

<?php
namespace app\common;
use think\facade\Db;
class Affiliate{
public static function calculateProfitShare($order){
$affiliate = json_decode(getConfigValue('affiliate'),true);
//是否開啟分銷
if(!$affiliate['on']){
return ['code'=>-1,'msg'=>'未開啟分銷'];
}
//檢查是否已經計算過
$is_calculate = Db::name('affiliate_log')->where('order_id', $order['order_id'])->count();
if($is_calculate){
return ['code'=>-1,'msg'=>'已經計算過'];
}
try {
//找出第一二三四層介紹人
$sso_user_id = Db::name('users')->where('user_id', $order['user_id'])->value('sso_user_id');
$parents = self::getAffiliate($sso_user_id, 1);
foreach ($parents as $key => $value) {
//計算分銷金額
$money[$key] = $order['order_amount'] * $affiliate['item'][$key]['level_money'] / 100;
//寫入affiliate_log
$affiliate_log = [
'user_id' => Db::name('users')->where('sso_user_id', $value)->value('user_id'),
'order_id' => $order['order_id'],
'time' => time(),
'user_name' => Db::name('users')->where('sso_user_id', $value)->value('real_name'),
'money' => $money[$key],
];
Db::name('affiliate_log')->insert($affiliate_log);
//增加介紹人的獎金
Db::name('users')->where('sso_user_id', $value)->inc('frozen_money', $money[$key])->update();
}
return true;
} catch (\Exception $e) {
print_r($e->getMessage());
return false;
}
}
private static function getAffiliate($sso_user_id, $level = 1)
{
$parents = [];
$parent_id = Db::name('users')->where('sso_user_id', $sso_user_id)->value('parent_id');
if ($parent_id) {
$parents[$level] = $parent_id;
$level++;
$return = self::getAffiliate($parent_id, $level);
$parents = array_merge($parents, $return);
}
return $parents;
}
}