6
0
Fork 0
jiqu-library-server/app/Admin/Actions/Store/RowAddStock.php

72 lines
2.2 KiB
PHP

<?php
namespace App\Admin\Actions\Store;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Support\Facades\DB;
use App\Models\Store\{ProductSku, StockBatch};
class RowAddStock extends RowAction
{
protected $title = '确认';
public function handle()
{
// 添加库存记录
$list = [];
$model = StockBatch::findOrFail($this->getKey());
if ($model->status) {
return $this->response()->error('已经确认过了');
}
$admin = $model->adminUser;
$type = $admin->getMorphClass();
try {
DB::beginTransaction();
foreach($model->productSkus()->get() as $item) {
$amount = $item->pivot?->amount;
$product = ProductSku::firstOrCreate([
'store_id' => $model->store_id,
'product_sku_id' => $item->id
], [
'amount' => 0,
'status' => 1,
'product_spu_id' => $item->spu_id,
]);
$balance = $product->amount + $amount;
if ($balance < 0) {
throw new \Exception($item->name . ' 商品库存不足');
}
$list[] = [
'operator_type' => $type,
'operator_id' => $admin->id,
'operator_name' => $admin->name,
'amount' => $amount,
'product_sku_id' => $item->id,
'balance' => $balance,
'store_id' => $model->store_id,
'tag_id' => $model->tag_id,
'remarks' => '批次号: ' . $model->sn,
];
$product->update(['amount' => $balance]);
}
$model->logs()->createMany($list);
$model->update(['status' => 1]);
DB::commit();
} catch (\Exception $exception) {
DB::rollBack();
return $this->response()->error($exception->getMessage());
}
return $this->response()->success('操作成功')->refresh();
}
public function confirm()
{
return ['是否确定?', '不可恢复'];
}
}