批量修改在售库存

This commit is contained in:
杨建炊 2024-10-29 16:33:30 +08:00
parent 7bcecbe435
commit 67ed7dbe6b
14 changed files with 195 additions and 74 deletions

View File

@ -0,0 +1,54 @@
<?php
namespace App\Console\Commands;
use App\Http\Service\MessageService;
use App\Models\GoodsSku;
use App\Services\Business\MiaoXuan\Goods;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class InitSaleStock extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'init:sale_stock {ids?}';
/**
* The console command description.
*
* @var string
*/
protected $description = '初始化在售库存';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$ids = $this->argument('ids');
if(!empty($ids)){
$ids = explode(',',$ids);
}
GoodsSku::query()->where("stock",'>',0)->when($ids,function($query)use($ids){
$query->whereIn('id',$ids);
})->update(['sale_stock' => DB::raw('stock')]);
}
}

View File

@ -49,6 +49,5 @@ class KttOrderAfterSaleQuery extends Command
BusinessFactory::init()->make($shop->plat_id)->setShop($shop)->downloadAfterSaleOrdersAndSave($beginTime, $endTime);
}
Log::info('任务完成:快团团根据更新时间获取增量售后单');
}
}

View File

@ -42,6 +42,7 @@ class BusinessOrdersUpdate
$updateResult = true;
break;
}
usleep(140);
}
if (!$updateResult) {
Log::error("sku 业务更新失败", (array)$this->businessGoodSku);
@ -63,6 +64,7 @@ class BusinessOrdersUpdate
$oldStock = $this->goodsSku->stock;
$stock = $this->goodsSku->stock + $this->num;
$saleStock = $this->goodsSku->sale_stock + $this->num;
$saleStock = ($saleStock > 0) ? $saleStock : 0;
$updateParam = ["stock" => $stock, "sale_stock" => $saleStock];
if (0 >= $saleStock) {
$updateParam['status'] = GoodsSku::$STATUS_DOWN;

View File

@ -259,6 +259,9 @@ class GoodsSkusController extends Controller
try {
$logs = [];
foreach ($request->skus as $sku) {
if ($sku['sale_stock'] < 0) {
throw new \Exception("商品id{$sku['id']}在售库存数不能小于0");
}
$costLog = [
'module' => 'goods',
'action' => $request->getMethod(),

View File

@ -49,6 +49,11 @@ class GoodsTypesController extends Controller
if ($request->parent_id) {
$parentGoodsType = GoodsType::query()->where("id", "=", $request->parent_id)->get()->toArray();
$level = $parentGoodsType['level'] ?? 1 + 1;
$existTypeName = GoodsType::query()->where("parent_id", "=", $request->parent_id)
->where("name",$request->name)->first();
if($existTypeName){
throw new \Exception("当前品类下该名称已存在");
}
}
$goodsType = new GoodsType();

View File

@ -7,6 +7,7 @@ use App\Http\Controllers\Controller;
use App\Http\Enum\ExcelKeyEnum;
use App\Imports\LossImport;
use App\Models\DailyStockRecord;
use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\Log;
use App\Models\Log as LogModel;
@ -16,6 +17,7 @@ use App\Models\User;
use App\Services\GoodSku\GoodSkuService;
use App\Utils\DateTimeUtils;
use App\Utils\GeneratorUtils;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\DB;
@ -70,6 +72,8 @@ class LossRecordController extends Controller
$buyerUserId = User::query()->where("name", $allParams['buyer_name'] ?? '')
->pluck("id")->first();
$today = DateTimeUtils::getToday();
DB::beginTransaction();
try {
//保存記錄
$lossRecords = new LossRecords();
$lossRecords->batch_number = GeneratorUtils::generateBatchNumber();
@ -84,7 +88,12 @@ class LossRecordController extends Controller
$lossRecords->save();
$updateIds = GoodSkuService::computeSkuStock($goodsSku->toArray()
, ['num' => 0 - $allParams['num'], "cost" => $allParams['cost'], "user_id" => $request->user()->id]);
DB::commit();
event(new BatchStockUpdateEvent($updateIds));
} catch (\Exception $exception) {
DB::rollBack();
}
} else {
$this->res = [
'httpCode' => 400,
@ -163,6 +172,8 @@ class LossRecordController extends Controller
$today = DateTimeUtils::getToday();
//开始保存数据
foreach ($lossOrders as $v) {
DB::beginTransaction();
try {
$goodsSkuItem = $goodsSkuMap[$v['external_sku_id']];
//保存記錄
$lossRecords = new LossRecords();
@ -179,7 +190,11 @@ class LossRecordController extends Controller
$updateIds = GoodSkuService::computeSkuStock($goodsSkuItem
, ['num' => 0 - $v['num'], "cost" => $v['cost'], "user_id" => $request->user()->id]);
DB::commit();
$allUpdateIds = array_merge($allUpdateIds, $updateIds);
} catch (\Exception $exception) {
DB::rollBack();
}
}
event(new BatchStockUpdateEvent(collect($allUpdateIds)->unique()->toArray()));

View File

@ -14,6 +14,7 @@ use App\Services\GoodSku\GoodSkuService;
use App\Utils\DateTimeUtils;
use App\Utils\GeneratorUtils;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
@ -53,6 +54,8 @@ class LossImport implements ToArray, SkipsEmptyRows
if (!isset($hasGoodsSkus[$row[0]])) {
continue;
}
DB::beginTransaction();
try {
//执行库存操作
$goodsSkuItem = $hasGoodsSkus[$row[0]];
//保存記錄
@ -72,7 +75,11 @@ class LossImport implements ToArray, SkipsEmptyRows
$lossRecords->save();
$updateIds = GoodSkuService::computeSkuStock($goodsSkuItem, ["num" => 0 - $row[2], 'cost' => $row[3]]);
DB::commit();
$allUpdateIds = array_merge($allUpdateIds, $updateIds);
} catch (\Exception $exception) {
DB::rollBack();
}
}
Log::info("报损导入内容:", $collection);
// 批量更新

View File

@ -20,7 +20,6 @@ class SaleStockImport implements ToArray, SkipsEmptyRows
*/
public function array(array $collection)
{
Log::info("collection",[$collection]);
if (!empty($collection)) {
unset($collection[0]);
$externalSkuIds = [];
@ -29,6 +28,9 @@ class SaleStockImport implements ToArray, SkipsEmptyRows
$row = array_map(static function ($v) {
return trim($v);
}, $row);
if ($row[2] < 0) {
throw new Exception("商品编码{$row[0]}在售库存数不能小于0");
}
$inventoryKeyByExternalSkuIdMap[$row[0]] = $row[2];
$externalSkuIds[] = $row[0];
}

View File

@ -40,11 +40,8 @@ class BatchStockUpdateListener implements ShouldQueue
try {
foreach ($shops as $shop) {
foreach ($event->goodsSkus as $goodsSku) {
if ($shop['plat_id'] == "快团团") {
//后续同步三方使用在售库存
$num = $goodsSku->sale_stock;
} else {
$num = $goodsSku->stock;
}
$businessGoodsSkus = BusinessGoodsSku::query()
->select(['goods_id', 'sku_id', 'external_sku_id'])
->where('shop_id', $shop->id)

View File

@ -36,11 +36,7 @@ class StockUpdateListener implements ShouldQueue
return;
}
foreach ($shops as $shop) {
if ($shop['plat_id'] == "快团团") {
$num = $event->goodsSku->sale_stock;
} else {
$num = $event->goodsSku->stock;
}
$businessGoodsSkus = BusinessGoodsSku::query()
->select(['goods_id', 'sku_id', 'external_sku_id'])
->where('shop_id', $shop->id)

View File

@ -60,11 +60,7 @@ class UpdateBusinessGoodsStock implements ShouldQueue
}
foreach ($shops as $shop) {
if ($shop['plat_id'] == "快团团") {
$num = $event->goodsSku->sale_stock;
} else {
$num = $event->goodsSku->stock;
}
$businessGoodsSkus = BusinessGoodsSku::query()
->where('shop_id', $shop->id)
->where('is_sync', 1)

View File

@ -126,8 +126,6 @@ class GoodSkuService
public static function computeSkuStock(array $goodsSkuItem, array $changeData, $targetType = TargetTypeEnum::LOSS)
{
$updateIds = [];
Log::info("库存更新前完整商品信息", $goodsSkuItem);
Log::info("库存更新前完整请求信息", $changeData);
$updateParams = [];
//添加系统日志
$costLogs = [];
@ -135,12 +133,15 @@ class GoodSkuService
if (empty($goodsSkuItem['is_combination'])) {
$updateParam = [
'stock' => $goodsSkuItem['stock'] + $changeData['num'],
'sale_stock' => $goodsSkuItem['sale_stock'] + $changeData['num'],
'sale_stock' => max($goodsSkuItem['sale_stock'] + $changeData['num'], 0),
];
if ($targetType == TargetTypeEnum::PURCHASE) {
$updateParam['cost'] = $changeData['cost'];
}
if ($updateParam['sale_stock'] <= 0) {
$updateParam['status'] = GoodsSku::$STATUS_DOWN;
}
GoodsSku::query()->where('external_sku_id', "=", $goodsSkuItem['external_sku_id'])
->update($updateParam);
$updateIds[] = $goodsSkuItem['id'];
@ -154,8 +155,11 @@ class GoodSkuService
foreach ($combinationGood as $item) {
$updateParam = [
'stock' => $item['goodsSkuItem']['stock'] + $changeData['num'] * $item['item_num'],
'sale_stock' => $item['goodsSkuItem']['sale_stock'] + $changeData['num'] * $item['item_num'],
'sale_stock' => max($item['goodsSkuItem']['sale_stock'] + $changeData['num'] * $item['item_num'], 0),
];
if ($updateParam['sale_stock'] <= 0) {
$updateParam['status'] = GoodsSku::$STATUS_DOWN;
}
GoodsSku::query()->where('id', $item['goodsSkuItem']['id'])->update($updateParam);
$updateIds[] = $item['goodsSkuItem']['id'];

View File

@ -0,0 +1,41 @@
<?php
namespace App\Utils;
use App\Exceptions\ServiceException;
use Illuminate\Support\Facades\Redis;
class RedisLockUtils
{
private static $prefix = 'lock';
public static function getKey($keyType, $extend = '')
{
return collect([
self::$prefix,
$keyType,
$extend
])->filter()->implode(':');
}
public static function getLock($lockKey, $expireSeconds = 1, $throwException = false)
{
$lock = Redis::setnx($lockKey, 1);
if (!$lock) {
if ($throwException) {
throw new ServiceException('操作频繁');
}
return false;
}
Redis::expire($lockKey, $expireSeconds);
return true;
}
public static function deleteLock($lockKey)
{
return Redis::del($lockKey);
}
}

View File

@ -18,7 +18,7 @@ class AddSaleStockAndQualityPeriodToGoodsSkusTable extends Migration
}
Schema::table('goods_skus', function (Blueprint $table) {
//
$table->integer('sale_stock')->default(9000)->comment("在售库存数");
$table->integer('sale_stock')->default(0)->comment("在售库存数");
$table->integer('quality_period')->nullable()->comment("保质期时间,单位天");
});