6
0
Fork 0
jiqu-library-server/app/Models/Dealer.php

184 lines
4.1 KiB
PHP

<?php
namespace App\Models;
use App\Casts\JsonArray;
use App\Enums\DealerLvl;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
class Dealer extends Model
{
use HasDateTimeFormatter;
protected $attributes = [
'lvl' => DealerLvl::None,
'is_sale' => false,
'is_manager' => false,
];
protected $casts = [
'lvl' => DealerLvl::class,
'is_sale' => 'bool',
'is_manager' => 'bool',
'pay_info' => JsonArray::class,
'contracted_lvl_at' => 'datetime',
];
protected $fillable = [
'user_id',
'lvl',
'is_sale',
'is_manager',
'pay_info',
'contracted_lvl_at',
];
/**
* {@inheritdoc}
*/
protected static function booted()
{
static::creating(function ($dealer) {
if ($dealer->last_upgrade_at === null) {
$dealer->last_upgrade_at = now();
}
});
}
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* 属于此经销商的用户信息
*/
public function userInfo()
{
return $this->hasOne(UserInfo::class, 'user_id', 'user_id');
}
/**
* 属于此经销商的管理者津贴
*/
public function managerSalesLogs()
{
return $this->hasMany(DealerManagerSalesLog::class, 'user_id', 'user_id');
}
/**
* 属于此经销商的管理者津贴
*/
public function manageSubsidyLogs()
{
return $this->hasMany(DealerManageSubsidyLog::class, 'user_id', 'user_id');
}
/**
* 属于此经销商的升级日志
*/
public function upgradeLogs()
{
return $this->hasMany(DealerUpgradeLog::class, 'user_id', 'user_id');
}
public function getLvlTextAttribute()
{
return $this->lvl->text();
}
/**
* 确认此经销商是否是金牌经销商
*
* @return boolean
*/
public function isGoldDealer()
{
return $this->lvl === DealerLvl::Gold;
}
/**
* 确认此经销商是否是特邀经销商
*
* @return boolean
*/
public function isSpecialDealer()
{
return $this->lvl === DealerLvl::Special;
}
/**
* 获取此用户的所有上级经销商
*
* @return array
*/
public function getDealers()
{
if (empty($pids = $this->userInfo->parent_ids)) {
return [];
}
$ancestors = UserInfo::with(['dealer'])
->whereIn('user_id', $pids)
->latest('depth')
->get(['user_id']);
return $ancestors->map(function ($item) {
return $item->dealer;
})->all();
}
/**
* 获取此用户的所有直属上级经销商
*
* @return array
*/
public function getRealDealers()
{
if (empty($pids = $this->userInfo->real_parent_ids)) {
return [];
}
$ancestors = UserInfo::with(['dealer'])
->whereIn('user_id', $pids)
->latest('depth')
->get(['user_id']);
return $ancestors->map(function ($item) {
return $item->dealer;
})->all();
}
/**
* 变更等级
*
* @param \App\Enums\DealerLvl $lvl
* @param string|null $remark
* @return void
*/
public function changeLvl(DealerLvl $lvl, ?string $remark = null)
{
if ($this->lvl === $lvl) {
return;
}
$before = $this->lvl;
if ($lvl->value < DealerLvl::Contracted->value) {
$this->contracted_lvl_at = null;
} elseif ($lvl->value >= DealerLvl::Contracted->value && $this->contracted_lvl_at === null) {
$this->contracted_lvl_at = now();
}
$this->lvl = $lvl;
$this->save();
$this->upgradeLogs()->create([
'before_lvl' => $before,
'change_lvl' => $lvl,
'remark' => $remark,
]);
}
}