admin/plugins/team-dividend/src/models/TeamDividendModel.php

473 lines
16 KiB
PHP

<?php
namespace Yunshop\TeamDividend\models;
use app\backend\modules\member\models\MemberChildren;
use app\common\models\BaseModel;
use app\common\models\finance\Balance;
use app\common\models\MemberShopInfo;
use app\common\services\finance\BalanceChange;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
/**
* Class TeamDividendModel
* @package Yunshop\TeamDividend\models
* @property int id
*/
class TeamDividendModel extends BaseModel
{
use SoftDeletes;
public $table = 'yz_team_dividend';
public $timestamps = true;
protected $guarded = [''];
public $TypeService;
public $LevelService;
public $StatusService;
protected $appends = ['type_name', 'level_name', 'status_name'];
public function scopeRepetition(Builder $query)
{
$teamDividend = self::selectRaw('group_concat(id) as ids,count(1) as count_num')
->where('created_at','>',Carbon::now()->subDays(7)->getTimestamp())
->groupBy(['member_id','order_sn','amount','agent_level'])
->having('count_num', '>', 1)->get();
$errorTeamDividendIds = $teamDividend->reduce(function ($result, $teamDividend) {
$a = explode(',', $teamDividend->ids);
array_pop($a);
return array_merge($result, $a);
}, []);
return $query->whereIn('id', $errorTeamDividendIds);
}
public static function getDividends($search)
{
$model = self::uniacid();
if (!empty($search['member'])) {
$model->whereHas('hasOneMember', function ($query) use ($search) {
$query->where('nickname', 'like', "%{$search['member']}%")
->orWhere('realname', 'like', "%{$search['member']}%")
->orWhere('mobile', 'like', "%{$search['member']}%");
});
}
if ($search['is_pay'] == 1) {
$model->whereHas('hasOneOrder', function ($query) {
$query->select('status', 'order_sn')->where('status', '>=', 1);
});
}
if ($search['is_pay'] == 2) {
$model->whereHas('hasOneOrder', function ($query) {
$query->select('status', 'order_sn')->where('status', '<', 1);
});
}
if (!request()->input('no_with')) {
$model->with([
'hasOneMember' => function ($query) {
$query->select(['uid', 'avatar', 'nickname']);
},
'hasOneOrder' => function ($query) {
$query->select(['id','order_sn']);
}
]);
}
if (!empty($search['member_id'])) {
$model->whereHas('hasOneMember', function ($query) use ($search) {
$query->where('uid', $search['member_id']);
});
}
if (!empty($search['order_sn'])) {
$model->where('order_sn', $search['order_sn']);
}
if (!empty($search['agent_level'])) {
$model->where('agent_level', $search['agent_level']);
}
if ($search['status'] != '') {
$model->where('status', $search['status']);
}
if ($search['type'] != '') {
$model->where('type', $search['type']);
}
if ($search['is_time']) {
if ($search['time']) {
$range = [strtotime($search['time']['start']), strtotime($search['time']['end'])];
$model->whereBetween('created_at', $range);
}
}
return $model;
}
public static function getDataByOrderSn($order_sn)
{
return self::uniacid()->where('order_sn', $order_sn)->first();
}
public static function getStatistic($type, $start, $end, $is_pay_record)
{
if ($is_pay_record) {
return self::uniacid()
->where('member_id', \YunShop::app()->getMemberId())
->where('status', 1)
->where('type', $type)
->whereBetween('created_at', [$start, $end]);
}
return self::uniacid()
->where('member_id', \YunShop::app()->getMemberId())
->where('status', '<>', -1)
->where('type', $type)
->whereBetween('created_at', [$start, $end]);
}
public static function getDividendList($type)
{
$model = self::select('create_month');
$model->uniacid();
$model->with(['hasManyDividend' => function ($query) use ($type) {
$query->where('type', $type);
$query->where('member_id', \YunShop::app()->getMemberId());
$query->orderBy('id', 'desc');
return $query->get();
}]);
$model->where('type', $type);
$model->groupBy('create_month');
$model->orderBy('create_month', 'desc');
return $model;
}
public static function getDividendLists($type, $is_record_list, $display_settle_type)
{
$page = \YunShop::request()->get('page');
// 如果page小于且等于1 就等于0 (因为offset是从0开始取数据)
if ($page <= 1) {
$page = 0;
$offset = ($page) * 15;
} else {
$offset = ($page - 1) * 15;
}
$model = self::select('create_month');
$model->uniacid();
$model->with(['hasManyDividend' => function ($query) use ($type, $offset, $is_record_list, $display_settle_type) {
if ($is_record_list == 0 || is_null($is_record_list)) {
$query->where('is_pay', 1);
}
if ((int)$display_settle_type == 1){
$query->where('status', (int)$display_settle_type);
}
// $query->with('hasOneMember')->with('hasOneMember.yzMember' );
$query->with('hasOneOrder');
$query->where('type', $type);
$query->where('member_id', \YunShop::app()->getMemberId());
$query->orderBy('id', 'desc');
$query->offset($offset)->limit('15');
}]);
$model->with('hasOneOrder');
$model->where('type', $type);
$model->groupBy('create_month');
$model->orderBy('create_month', 'desc');
$model->where('member_id', \YunShop::app()->getMemberId());
return $model;
}
public function getTypeNameAttribute()
{
if (!isset($this->TypeService)) {
switch ($this->type) {
case 0:
$this->TypeService = '分红佣金';
break;
case 1:
$this->TypeService = '平级奖励';
break;
case 2:
$this->TypeService = '感恩奖励';
break;
case 3:
$this->TypeService = '额外分红';
break;
case 7:
$this->TypeService = '月月返';
break;
case 8:
$this->TypeService = '分红奖';
break;
}
}
return $this->TypeService;
}
public function getLevelNameAttribute()
{
if (!isset($this->LevelService)) {
$level = TeamDividendLevelModel::getLevelById($this->agent_level);
$this->LevelService = $level->level_name;
}
return $this->LevelService;
}
public function getStatusNameAttribute()
{
if (!isset($this->StatusService)) {
switch ($this->status) {
case 0:
$this->StatusService = '未结算';
break;
case 1:
$this->StatusService = '已结算';
break;
case 2:
$this->StatusService = '冻结中';
break;
case -1:
$this->StatusService = '已失效';
break;
}
}
return $this->StatusService;
}
public static function updatedTeamDividend($data, $where)
{
return self::uniacid()
->where($where)
->update($data);
}
/**
* @return mixed
* 获取可结算数据
*/
public static function getStatement()
{
return self::uniacid()
->with('hasOneAgent')
->with('hasOneOrder')
->where(function ($query) {
return $query->where(DB::raw('`recrive_at` + (`settle_days` * 86400)'), '<=', time())
->orWhere('settle_days', '=', '0');
})
->whereNotNull('recrive_at')
->where('status', '0');
}
/*
*
* 手动结算:可结算的数据
* */
public static function getNotSettleInfo($where)
{
$model = self::uniacid()
->where($where)
->with('hasOneAgent')
->with('hasOneOrder')
->whereNotNull('recrive_at')
->where('status', '0');
return $model;
}
/*
* 获取未结算总金额
* */
public static function getNotSettleAmount($uid)
{
return self::uniacid()
->where('member_id', $uid)
->where('status', 0)
->whereNotNull('recrive_at')
->sum('dividend_amount');
}
public function OrderGoods()
{
return $this->hasMany('\app\common\models\OrderGoods', 'goods_id', 'goods_id');
}
public function hasOneMember()
{
return $this->hasOne('app\common\models\Member', 'uid', 'member_id');
}
public function hasManyDividend()
{
return $this->hasMany(self::class, "create_month", "create_month");
}
public function hasOneAgent()
{
return $this->hasOne('Yunshop\TeamDividend\models\TeamDividendAgencyModel', 'uid', 'member_id');
}
public function hasOneLevel()
{
return $this->hasOne('Yunshop\TeamDividend\models\TeamDividendLevelModel', 'id', 'agent_level');
}
public function hasOneOrder()
{
return $this->hasOne('\app\common\models\Order', 'order_sn', 'order_sn');
}
public function hasOneMemberShop()
{
return parent::hasOne(MemberShopInfo::class, 'member_id', 'member_id'); // TODO: Change the autogenerated stub
}
public static function getDividendDmountForComplated($uid)
{
return self::uniacid()
->where('member_id', $uid)
->where('status', 1)
->sum('dividend_amount');
}
public static function getTeamDividendByMemberId($status = '', $type = '', $is_pay = 1)
{
$model = self::uniacid();
$model->where('member_id', \YunShop::app()->getMemberId());
if ($is_pay === 1) {
$model->where('is_pay', 1);
}
if ($status !== '') {
$model->where('status', $status);
}
if ($type !== '') {
$model->where('type', $type);
}
return $model;
}
public function incomes()
{
return $this->morphMany('app\common\models\Income', 'incomeTable');
}
/**
* 删除并操作对应的收入记录和提现记录
* @throws \Exception
*/
public function rollback()
{
$uniacid = \YunShop::app()->uniacid;
\YunShop::app()->uniacid = $this->hasOneOrder->uniacid;
// 将记录 减去分红记录的金额
$this->hasOneAgent->dividend_total -= $this->dividend_amount;
if ($this->status == 1) {
$this->hasOneAgent->dividend_final -= $this->dividend_amount;
}else {
$this->hasOneAgent->dividend_open -= $this->dividend_amount;
}
$this->hasOneAgent->save();
//已结算
if ($this->status == 1) {
if ($this->income && $this->income->status == 1) {
// 收入已提现
if (!$this->income->withdraw()) {
$this->logError('提现记录未找到');
} else {
if ($this->income->withdraw()->status == 2) {
$data = [
'member_id' => $this->member_id,
'remark' => "推客分红金额修正",
'relation' => $this->order_sn,
'operator' => Balance::BALANCE_CANCEL_AWARD,
'operator_id' => $this->id,
'change_value' => $this->dividend_amount
];
try {
(new BalanceChange())->consume($data);
ErrorTeamDividend::create(['commission_order_id' => $this->id, 'order_id' => $this->hasOneOrder->id, 'member_id' => $this->member_id, 'dividend_amount' => $this->dividend_amount, 'note' => "用户{$this->member_id}的余额已扣除"]);
} catch (\Exception $exception) {
ErrorTeamDividend::create(['commission_order_id' => $this->id, 'order_id' => $this->hasOneOrder->id, 'member_id' => $this->member_id, 'commission_amount' => $this->dividend_amount, 'note' => "用户{$this->member_id}的余额不足,无法扣除"]);
}
}
$this->income->withdraw()->amounts -= $this->dividend_amount;
if ($this->income->withdraw()->amounts <= 0) {
// 提现记录的对应收入记录全部删除,则提现记录也删除
$this->income->withdraw()->delete();
} else {
// 还有其他收入记录的时候,修改时删除对应id并保存 todo 表结构不合理
$ids = explode(',', $this->income->withdraw()->type_id);
unset($ids[array_search($this->id, $ids)]);
$ids = implode(',', $ids);
$this->income->withdraw()->type_id = $ids;
$this->income->withdraw()->save();
$this->logError("分红记录{$this->order_sn}的分红提现状态为{$this->income->withdraw()->status},已修改");
}
}
$this->logError("分红记录{$this->order_sn}的收入状态为{$this->status},收入记录已删除");
$this->income->delete();
}
}
$this->logError("订单{$this->order_sn}的分红记录{$this->id},已修复");
// 删除对应分红日志
$this->delete();
\YunShop::app()->uniacid = $uniacid;
}
public function logError($msg)
{
\Log::info("订单{$this->order_sn}用户{$this->member_id}:", [$msg]);
}
/**
* 获取提成概况
*/
public function getCommissionSurvey($uid,$times,$recommend_ytpe)
{
$query = self::uniacid()//->where('yz_team_dividend.status',1)
->where('yz_team_dividend.member_id',$uid)
->where('yz_team_dividend.type',0);//查已结算状态和分红佣金类型
if ($recommend_ytpe && $recommend_ytpe != 0){
$query->whereHas('hasOneOrder', function ($query) use ($uid,$recommend_ytpe) {
$query->whereIn('uid', function ($query)use($uid,$recommend_ytpe){
$query->select('child_id')->from('yz_member_children')
->where('member_id',$uid);
if ($recommend_ytpe == 1){
$query->where('level',1);
}else{
$query->where('level','<>',1);
}
});
});
// $query->whereIn('order_sn',function ($query)use($child_ids){
// $query->select('order_sn')->from('yz_order')->whereIn('uid',$child_ids);
// });
// $order = \app\common\models\Order::whereIn('uid',$child_ids)->whereBetween('created_at',$times)->pluck('order_sn')->toArray();
// $query->whereIn('order_sn',$order);
}
if ($times && !is_null($times)){
$query->whereBetween('yz_team_dividend.created_at',$times);
}
return $query->orderBy('yz_team_dividend.id', 'desc');
}
}