You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.8 KiB
97 lines
2.8 KiB
<?php
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Models\AgentProduct;
|
|
use App\Models\AgentProductSpec;
|
|
use App\Models\ProductSpec;
|
|
use Illuminate\Bus\Queueable;
|
|
use Illuminate\Contracts\Queue\ShouldBeUnique;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Bus\Dispatchable;
|
|
use Illuminate\Queue\InteractsWithQueue;
|
|
use Illuminate\Queue\SerializesModels;
|
|
|
|
class ProductSpecSync implements ShouldQueue
|
|
{
|
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
|
|
/**
|
|
* 任务可尝试的次数
|
|
* @var int
|
|
*/
|
|
public $tries = 3;
|
|
|
|
/**
|
|
* 任务失败前允许的最大异常数
|
|
* @var int
|
|
*/
|
|
public $maxExceptions = 3;
|
|
|
|
/**
|
|
* Create a new job instance.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function __construct(private int $product_id)
|
|
{
|
|
//
|
|
}
|
|
|
|
/**
|
|
* Execute the job.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function handle()
|
|
{
|
|
//获取当前供应商产品的所有规格
|
|
$product_specs = ProductSpec::where('product_id', $this->product_id)->get();
|
|
|
|
//获取当前供应商产品的所有代理商产品ID
|
|
AgentProduct::query()
|
|
->where('product_id', $this->product_id)
|
|
->chunk(5, function ($agent_products) use ($product_specs) {
|
|
//当前供应商产品所有规格的ID
|
|
$product_spec_ids = $product_specs->pluck('id')->toArray();
|
|
|
|
//删除供应商已经删除的规格
|
|
AgentProductSpec::query()
|
|
->whereIn('agent_product_id', $agent_products->pluck('id')->toArray())
|
|
->whereNotIn('product_spec_id', $product_spec_ids)
|
|
->delete();
|
|
|
|
//将代理商规格中销售价小于供应商销售价的,将代理商的销售价设置为供应商的销售价
|
|
foreach ($product_specs as $spec) {
|
|
AgentProductSpec::query()
|
|
->where([['product_spec_id', '=', $spec->id], ['price', '<', $spec->price]])
|
|
->update(['price' => $spec->price]);
|
|
}
|
|
|
|
//供应商新增,但代理商还没有的规格,同步给代理商
|
|
foreach ($agent_products as $ap) {
|
|
//代理商已有的规格(如果代理商删除过的规格不再同步过来,这里加上withTrashed即可)
|
|
$ap_spec_ids = AgentProductSpec::where('agent_product_id', $ap->id)->pluck('product_spec_id')->toArray();
|
|
|
|
//代理商没有的规格
|
|
$agent_no_spec_ids = array_diff($product_spec_ids, $ap_spec_ids);
|
|
|
|
AgentProductSpec::query()
|
|
->insert(
|
|
array_map(function ($v) use ($ap, $product_specs) {
|
|
$product_spec = $product_specs->find($v);
|
|
return [
|
|
'agent_product_id' => $ap->id,
|
|
'product_spec_id' => $v,
|
|
'name' => '',
|
|
'date' => null,
|
|
'stock' => $product_spec->stock,
|
|
'original_price' => $product_spec->original_price,
|
|
'price' => $product_spec->price,
|
|
];
|
|
}, $agent_no_spec_ids)
|
|
);
|
|
}
|
|
});
|
|
}
|
|
}
|