bztang-admin/plugins/cultural-space/src/models/CulturalSpace.php

311 lines
12 KiB
PHP

<?php
namespace Yunshop\CulturalSpace\models;
use app\common\facades\Setting;
use app\common\models\BaseModel;
use app\common\models\Member;
use app\common\models\member\MemberParent;
use app\common\models\OrderGoods;
use Illuminate\Support\Facades\DB;
class CulturalSpace extends BaseModel
{
public $table = 'yz_cultural_space';
public $timestamps = false;
protected $fillable = [
'uniacid',
'uid',
'contribution'
];
/**
* Common: 贡献值持有信息列表
* Author: wu-hui
* Time: 2023/11/03 9:51
* @param $search
* @return array
*/
public function getList($search)
{
// 条件生成
$where = [];
if ($search['uid'] > 0) $where[] = ['uid', '=', $search['uid']];
// 查询model
$model = self::uniacid()
->where($where)
->with([
'member' => function ($query) {
$query->select(['uid', 'nickname', 'realname', 'avatar']);
}
]);
// 信息获取
$totalContribution = $model->sum('contribution');
$list = $model->select(['id', 'uid', 'contribution'])
->orderBy('id', 'DESC')
->paginate(10)
->toArray();
foreach ($list['data'] as &$item) {
$item['total_proportion'] = (float)sprintf("%.2f", $totalContribution);
$item['ratio'] = (float)sprintf("%.2f", $item['contribution'] / $totalContribution * 100);
}
return $list;
}
/**
* Common: 购买商品奖励贡献值
* Author: wu-hui
* Time: 2023/11/02 17:59
* @param $uid
* @param $orderId
*/
public function buyGoodsGiveContribution($uid, $orderId)
{
\Log::debug('文创空间 - 购买商品奖励贡献值', ['uid' => $uid, 'order_id' => $orderId]);
DB::beginTransaction();
try {
$set = Setting::get('plugin.cultural_space_set');
if ($set['is_give_contribution'] != 1 || (float)$set['contribution_ratio'] <= 0) throw new \Exception('文创空间 - 购买商品奖励贡献值 - 未开启贡献值奖励或者奖励比例为0');
// 获取直推上级id && 获取订单商品信息
$parentUid = (int)MemberParent::getParentId($uid);
$orderGoodsList = (array)$this->getGoodsModel($orderId)
->where('yz_goods_cultural_space.is_give_contribution', 1)
->get()
->makeHidden(['buttons', 'after_sales', 'order'])
->toArray();
if (count($orderGoodsList) <= 0) throw new \Exception('文创空间 - 购买商品奖励贡献值 - 无奖励商品信息');
// 获取文创空间用户信息
$memberList = $parentUid <= 0 ? $this->getCulturalSpace([$uid]) : $this->getCulturalSpace([$uid, $parentUid]);
$userName = Member::getMemberById($uid, ['realname', 'nickname'])->username ?? '';
// 循环商品处理奖励贡献值
$changeList = [];
foreach ($orderGoodsList as $goodsInfo) {
// 计算奖励贡献值
$contribution = (float)sprintf('%.2f', $goodsInfo['payment_amount'] * (float)$set['contribution_ratio'] / 100);
if ($contribution > 0) {
foreach ($memberList as $memberInfo) {
// 用户当前持有数量
$changeFront = (float)$memberList[$memberInfo['uid']]['contribution'];
// 变更后的数量
$changeAfter = (float)sprintf("%.2f", $changeFront + $contribution);
// 记录变更信息
$changeList[] = [
'uniacid' => $goodsInfo['uniacid'],
'uid' => $memberInfo['uid'],
'goods_id' => $goodsInfo['goods_id'],
'order_id' => $orderId,
'order_goods_id' => $goodsInfo['id'],
'change_type' => 1,
'change_quantity' => $contribution,
'change_front' => $changeFront,
'change_after' => $changeAfter,
'remark' => ($memberInfo['uid'] == $uid ? '' : "{$userName}") . "购买商品【{$goodsInfo['title']}】赠送",
'created_at' => time(),
];
// 刷新持有处理
$memberList[$memberInfo['uid']]['contribution'] = $changeAfter;
}
}
}
// 数据操作
if (count($changeList) > 0) {
$this->batchUpdate($memberList, 'uid', 'uid');
ContributionLog::insert($changeList);
}
DB::commit();
} catch (\Exception $e) {
\Log::debug('文创空间 - 购买商品奖励贡献值 - 错误抛出', $e->getMessage());
DB::rollBack();
}
}
/***
* 计算基金比例
* @param $uid
* @param $orderId
* @return void
*/
public function GiveGoodsFundMoney($uid, $orderId)
{
DB::beginTransaction();
try {
$set = Setting::get('plugin.cultural_space_set');
if (isset($set['is_fund_open'])&&$set['is_fund_open'] == 1) {
// 获取直推上级id && 获取订单商品信息
$orderGoodsList = $this->getGoodsModel($orderId)
->where('yz_goods_cultural_space.is_fund_open', 1)
->get()
->makeHidden(['buttons', 'after_sales', 'order'])
->toArray();
if (count($orderGoodsList) <= 0) throw new \Exception('文创空间 - 购买商品奖励贡献值 - 无奖励商品信息');
$current_fee = $set['fund_start_price']; //当前价格
$last_fee = $current_fee;
$fund_money = 0;
$voucher_number = 0;
$history_number = 0;
$history_fund_money = 0;
$fundInfo = CulturalFund::getfund();
if ($fundInfo) {
$current_fee = $fundInfo['current_fee'];
$last_fee = $current_fee;
$fund_money = $fundInfo['fund_money'];
$voucher_number = $fundInfo['voucher_number'];
$history_number = $fundInfo['history_number'];
$history_fund_money = $fundInfo['history_fund_money'];
}
$user_voucher_number = 0;//用户凭证数量
$user_voucher_total = 0;//用户总计凭证数量
foreach ($orderGoodsList as $goodsInfo) {
$user_voucher_number = (($goodsInfo['payment_amount'] * $set['user_fund_ratio']) / 100) / $current_fee; //赠送数量
$user_fund_money = round(($goodsInfo['payment_amount'] * $set['order_fund_ratio']) / 100, 2);//资金数量
$fund_money += $user_fund_money;
$user_voucher_total += $user_voucher_number;
$voucher_number += $user_voucher_number;
$history_number += $user_voucher_number;
$history_fund_money += $user_fund_money;
$data_log = [
'member_id' => $uid,
'order_id' => $orderId,
'goods_id' => $goodsInfo['goods_id'],
'good_name' => $goodsInfo['title'],
'pay_money' => $goodsInfo['payment_amount'],
'fund_money' => $user_fund_money,
'voucher_number' => $user_voucher_number,
'current_fee' => $current_fee,
];
CulturalOrderFundLog::InsertLog($data_log); //写入日记
}
$this->where('uid', $uid)->increment('voucher_number', $user_voucher_total);//用户增量
$next_fee = round($fund_money / $voucher_number, 2);
$FundData = [
'last_fee' => $last_fee,
'current_fee' => $next_fee,
'fund_money' => $fund_money,
'voucher_number' => $voucher_number,
'history_number' => $history_number,
'history_fund_money' => $history_fund_money,
];
$culturalFund = new CulturalFund();
$culturalFund->SaveData($FundData);
if ($user_voucher_number <= $set['min_number']) {
$this->capitalIncrease($set);//小于数量增加积分倍数
}
// 获取文创空间用户信息
// 数据操作
DB::commit();
} else {
DB::rollBack();
}
} catch (\Exception $e) {
DB::rollBack();
}
}
/***
* 增加资本
* @return void
*/
public function capitalIncrease($config){
$uniacid=\YunShop::app()->uniacid;
$this->where('uniacid', $uniacid) ->update(
[
'voucher_number' => DB::raw('voucher_number * '.$config['fund_multiple']),
]
); //增加会员资本
$culturalFund = new CulturalFund();
$data=$culturalFund->where('uniacid', $uniacid)->first()->toArray();
$data['up_voucher_number']=$data['voucher_number']*$config['fund_multiple'];
$data['up_current_fee']=$data['current_fee']/$config['fund_multiple'];
$data['fund_multiple']=$config['fund_multiple'];
$data['created_at']=time();
$data['updated_at']=time();
unset($data['id']);
DB::table('yz_cultural_fund_increase_log')->insert($data);
$culturalFund->where('uniacid', $uniacid)->update( //增加资本数量
[
'voucher_number' => DB::raw('voucher_number * '.$config['fund_multiple']),
'history_number' => DB::raw('history_number * '.$config['fund_multiple']),
'current_fee' => DB::raw('current_fee /'.$config['fund_multiple']),
]
);
}
/**
* Common: 获取订单商品查询model
* Author: wu-hui
* Time: 2023/11/02 16:26
* @param $orderId
* @return mixed
*/
private function getGoodsModel($orderId)
{
return OrderGoods::uniacid()
->select([
'yz_order_goods.id',
'yz_order_goods.uniacid',
'yz_order_goods.goods_id',
'yz_order_goods.total',
'yz_order_goods.title',
'yz_order_goods.payment_amount',
])
->leftJoin('yz_goods_cultural_space', 'yz_goods_cultural_space.goods_id', 'yz_order_goods.goods_id')
->where('yz_order_goods.order_id', $orderId)
->where('yz_goods_cultural_space.is_open', 1);
}
/**
* Common: 根据用户ids获取用户文创空间相关信息(如果不存在则添加默认信息并且返回默认信息)
* Author: wu-hui
* Time: 2023/11/02 17:36
* @param $ids
* @return array
*/
private function getCulturalSpace($ids)
{
// 获取已经存在的信息
$list = self::uniacid()
->select(['id', 'uid', 'contribution'])
->whereIn('uid', $ids)
->get()
->keyBy('uid')
->toArray();
// 循环处理:不存在则添加,并且赋值默认值;存在则使用已经存在的信息
$memberList = [];
$insertData = [];
foreach ($ids as $userId) {
if ($list[$userId]) {
// 存在
$memberList[$userId] = $list[$userId];
} else {
// 不存在
$insertData[] = [
'uniacid' => \YunShop::app()->uniacid,
'uid' => $userId,
];
$memberList[$userId] = [
'uniacid' => \YunShop::app()->uniacid,
'uid' => $userId,
'contribution' => 0
];
}
}
if ($insertData) self::insert($insertData);
return $memberList;
}
/**
* Common: 一对一关联 用户信息
* Author: wu-hui
* Time: 2023/11/03 9:35
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function member()
{
return $this->hasOne(Member::class, 'uid', 'uid');
}
}