erp/app/Events/BusinessOrdersUpdate.php

84 lines
2.4 KiB
PHP
Raw Normal View History

<?php
namespace App\Events;
2023-11-21 16:27:14 +08:00
use App\Models\DailyStockRecord;
use App\Models\GoodsSku;
2023-11-21 16:27:14 +08:00
use App\Utils\DateTimeUtils;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
2022-08-30 23:11:48 +08:00
use Illuminate\Support\Facades\Log;
class BusinessOrdersUpdate
{
use Dispatchable, InteractsWithSockets, SerializesModels;
2023-11-18 14:35:19 +08:00
public $businessGoodSku;
public $num;
public $goodsSku;
public $type = "BusinessOrdersUpdate";
2023-11-18 14:35:19 +08:00
public $combinationGoodsUpdate = true;
/**
* Create a new event instance.
*
* @return void
*/
2023-11-18 14:35:19 +08:00
public function __construct($businessGoodSku, $num)
{
2023-11-18 14:35:19 +08:00
$this->businessGoodSku = $businessGoodSku->toArray();
$this->num = $num;
$updateResult = false;
//暂时设定重试5次
for ($i = 0; $i < 5; $i++) {
if ($this->updateStock()) {
$updateResult = true;
break;
}
}
if (!$updateResult) {
Log::error("sku 业务更新失败", (array)$this->businessGoodSku);
}
}
private function updateStock()
{
2023-11-18 14:35:19 +08:00
$this->goodsSku = GoodsSku::query()
->where('external_sku_id', $this->businessGoodSku['external_sku_id'])
->first();
2023-11-21 16:27:14 +08:00
if (is_null($this->goodsSku)) {
return false;
}
$oldStock = $this->goodsSku->stock;
2023-11-21 16:27:14 +08:00
$stock = $this->goodsSku->stock + $this->num;
2024-07-26 17:48:07 +08:00
$saleStock = $this->goodsSku->sale_stock + $this->num;
$updateParam = ["stock" => $stock, "sale_stock" => $saleStock];
2024-07-26 17:48:07 +08:00
if (0 >= $saleStock) {
$updateParam['status'] = GoodsSku::$STATUS_DOWN;
2023-11-21 16:27:14 +08:00
} else {
$updateParam['status'] = GoodsSku::$STATUS_ON_SALE;
2023-11-21 16:27:14 +08:00
}
Log::info("sku 业务订单库存更新", $updateParam);
//乐观锁更新
return GoodsSku::query()->where('external_sku_id', $this->businessGoodSku['external_sku_id'])->
where("stock", "=", $oldStock)->update($updateParam);
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}