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

158 lines
3.7 KiB
PHP

<?php
namespace App\Models;
use App\Casts\JsonArray;
use App\Casts\Price;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class AfterSale extends Model
{
use HasFactory;
use HasDateTimeFormatter;
public const STATE_APPLY = 1; // 待补充资料
public const STATE_VERIFY = 2; // 待审核
public const STATE_AGREE = 3; // 待同意
public const STATE_SHIPPING = 4; // 待收货
public const STATE_FINANCE = 5; // 待打款
public const STATE_FINISH = 6; // 完成
public const STATE_CANCEL = 7; // 取消
public const TYPE_REFUND_AND_RETURN = 1; // 退款退货
public const TYPE_REFUND = 2; // 退款不退货
public const TYPE_CHANGE = 3; // 换货
public const TYPE_FILL = 4; // 漏发
protected $casts = [
'images' => JsonArray::class,
'amount' => Price::class,
];
protected $fillable = [
'user_id',
'order_id',
'order_product_id',
'num',
'amount',
'type',
'state',
'description',
'images',
'remarks',
];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function order()
{
return $this->belongsTo(Order::class, 'order_id');
}
public function orderProduct()
{
return $this->belongsTo(OrderProduct::class, 'order_product_id');
}
public function logs()
{
return $this->hasMany(AfterSaleLog::class, 'after_sale_id');
}
/**
* 设置申请售后时的录入操作日志
*
* @param array $attributes
* @param self|null $inviter
* @return self
*/
public static function create(array $attributes = [], ?self $inviter = null): self
{
$afterSale = static::query()->create($attributes);
$afterSale->createApplyLog();
return $afterSale;
}
/**
* 申请日志
*
* @return void
*/
protected function createApplyLog()
{
$this->logs()->create([
'after_sale_id' => $this->id,
'name' => '售后申请',
'desc' => '申请理由:'.$this->description,
'images'=> $this->images,
]);
}
/**
* 取消售后订单日志
*
* @return void
*/
protected function createCancelLog()
{
$this->logs()->create([
'after_sale_id' => $this->id,
'name' => '取消申请',
'desc' => '用户取消售后申请',
]);
}
/**
* 完成售后订单日志
*
* @return void
*/
protected function createFinishLog()
{
$this->logs()->create([
'after_sale_id' => $this->id,
'name' => '售后完成',
'desc' => '售后已结束',
]);
}
/**
* {@inheritdoc}
*/
protected static function booted()
{
parent::saving(function ($afterSale) {
// 如果自动创建sn
if ($afterSale->sn === null) {
$afterSale->sn = self::createSn();
}
//如果取消订单
if ($afterSale->state == self::STATE_CANCEL) {
$afterSale->createCancelLog();
}
//如果完成订单
if ($afterSale->state == self::STATE_FINISH) {
$afterSale->createFinishLog();
}
});
}
/**
* 创建售后单号
*
* @return void
*/
protected static function createSn()
{
return 'AS'.now()->format('YmdHisu').strtoupper(Str::random(2));
}
}