diff --git a/app/Models/Dealer.php b/app/Models/Dealer.php index 217fca61..023c8b1c 100644 --- a/app/Models/Dealer.php +++ b/app/Models/Dealer.php @@ -21,7 +21,8 @@ class Dealer extends Model 'lvl' => DealerLvl::class, 'is_sale' => 'bool', 'is_manager' => 'bool', - 'pay_info'=>JsonArray::class, + 'pay_info' => JsonArray::class, + 'contracted_lvl_at' => 'datetime', ]; protected $fillable = [ @@ -30,8 +31,21 @@ class Dealer extends Model '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'); @@ -64,9 +78,9 @@ class Dealer extends Model /** * 属于此经销商的升级日志 */ - public function lvlUpgradeLogs() + public function upgradeLogs() { - return $this->hasMany(DealerLvlUpgradeLog::class, 'user_id', 'user_id'); + return $this->hasMany(DealerUpgradeLog::class, 'user_id', 'user_id'); } public function getLvlTextAttribute() @@ -135,4 +149,35 @@ class Dealer extends Model 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) { + $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, + ]); + } } diff --git a/app/Models/DealerUpgradeLog.php b/app/Models/DealerUpgradeLog.php new file mode 100644 index 00000000..56ef885c --- /dev/null +++ b/app/Models/DealerUpgradeLog.php @@ -0,0 +1,21 @@ + DealerLvl::class, + 'change_lvl' => DealerLvl::class, + ]; + + protected $fillable = [ + 'user_id', + 'before_lvl', + 'change_lvl', + 'remark', + ]; +} diff --git a/database/migrations/2022_01_17_160300_add_contracted_lvl_at_to_dealers_table.php b/database/migrations/2022_01_17_160300_add_contracted_lvl_at_to_dealers_table.php new file mode 100644 index 00000000..7e98eee9 --- /dev/null +++ b/database/migrations/2022_01_17_160300_add_contracted_lvl_at_to_dealers_table.php @@ -0,0 +1,32 @@ +timestamp('contracted_lvl_at')->nullable()->comment('成为签约的时间'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('dealers', function (Blueprint $table) { + $table->dropColumn(['contracted_lvl_at']); + }); + } +}