批量修改在售库存

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); BusinessFactory::init()->make($shop->plat_id)->setShop($shop)->downloadAfterSaleOrdersAndSave($beginTime, $endTime);
} }
Log::info('任务完成:快团团根据更新时间获取增量售后单');
} }
} }

View File

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

View File

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

View File

@ -49,6 +49,11 @@ class GoodsTypesController extends Controller
if ($request->parent_id) { if ($request->parent_id) {
$parentGoodsType = GoodsType::query()->where("id", "=", $request->parent_id)->get()->toArray(); $parentGoodsType = GoodsType::query()->where("id", "=", $request->parent_id)->get()->toArray();
$level = $parentGoodsType['level'] ?? 1 + 1; $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(); $goodsType = new GoodsType();

View File

@ -7,6 +7,7 @@ use App\Http\Controllers\Controller;
use App\Http\Enum\ExcelKeyEnum; use App\Http\Enum\ExcelKeyEnum;
use App\Imports\LossImport; use App\Imports\LossImport;
use App\Models\DailyStockRecord; use App\Models\DailyStockRecord;
use App\Models\Goods;
use App\Models\GoodsSku; use App\Models\GoodsSku;
use App\Models\Log; use App\Models\Log;
use App\Models\Log as LogModel; use App\Models\Log as LogModel;
@ -16,6 +17,7 @@ use App\Models\User;
use App\Services\GoodSku\GoodSkuService; use App\Services\GoodSku\GoodSkuService;
use App\Utils\DateTimeUtils; use App\Utils\DateTimeUtils;
use App\Utils\GeneratorUtils; use App\Utils\GeneratorUtils;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@ -70,6 +72,8 @@ class LossRecordController extends Controller
$buyerUserId = User::query()->where("name", $allParams['buyer_name'] ?? '') $buyerUserId = User::query()->where("name", $allParams['buyer_name'] ?? '')
->pluck("id")->first(); ->pluck("id")->first();
$today = DateTimeUtils::getToday(); $today = DateTimeUtils::getToday();
DB::beginTransaction();
try {
//保存記錄 //保存記錄
$lossRecords = new LossRecords(); $lossRecords = new LossRecords();
$lossRecords->batch_number = GeneratorUtils::generateBatchNumber(); $lossRecords->batch_number = GeneratorUtils::generateBatchNumber();
@ -83,8 +87,13 @@ class LossRecordController extends Controller
$lossRecords->phenomenon = $v['phenomenon'] ?? ''; $lossRecords->phenomenon = $v['phenomenon'] ?? '';
$lossRecords->save(); $lossRecords->save();
$updateIds = GoodSkuService::computeSkuStock($goodsSku->toArray() $updateIds = GoodSkuService::computeSkuStock($goodsSku->toArray()
, ['num' => 0 - $allParams['num'], "cost" => $allParams['cost'],"user_id"=>$request->user()->id]); , ['num' => 0 - $allParams['num'], "cost" => $allParams['cost'], "user_id" => $request->user()->id]);
DB::commit();
event(new BatchStockUpdateEvent($updateIds)); event(new BatchStockUpdateEvent($updateIds));
} catch (\Exception $exception) {
DB::rollBack();
}
} else { } else {
$this->res = [ $this->res = [
'httpCode' => 400, 'httpCode' => 400,
@ -163,6 +172,8 @@ class LossRecordController extends Controller
$today = DateTimeUtils::getToday(); $today = DateTimeUtils::getToday();
//开始保存数据 //开始保存数据
foreach ($lossOrders as $v) { foreach ($lossOrders as $v) {
DB::beginTransaction();
try {
$goodsSkuItem = $goodsSkuMap[$v['external_sku_id']]; $goodsSkuItem = $goodsSkuMap[$v['external_sku_id']];
//保存記錄 //保存記錄
$lossRecords = new LossRecords(); $lossRecords = new LossRecords();
@ -178,8 +189,12 @@ class LossRecordController extends Controller
$lossRecords->save(); $lossRecords->save();
$updateIds = GoodSkuService::computeSkuStock($goodsSkuItem $updateIds = GoodSkuService::computeSkuStock($goodsSkuItem
, ['num' => 0 - $v['num'], "cost" => $v['cost'],"user_id"=>$request->user()->id]); , ['num' => 0 - $v['num'], "cost" => $v['cost'], "user_id" => $request->user()->id]);
DB::commit();
$allUpdateIds = array_merge($allUpdateIds, $updateIds); $allUpdateIds = array_merge($allUpdateIds, $updateIds);
} catch (\Exception $exception) {
DB::rollBack();
}
} }
event(new BatchStockUpdateEvent(collect($allUpdateIds)->unique()->toArray())); 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\DateTimeUtils;
use App\Utils\GeneratorUtils; use App\Utils\GeneratorUtils;
use Exception; use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows; use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray; use Maatwebsite\Excel\Concerns\ToArray;
@ -53,6 +54,8 @@ class LossImport implements ToArray, SkipsEmptyRows
if (!isset($hasGoodsSkus[$row[0]])) { if (!isset($hasGoodsSkus[$row[0]])) {
continue; continue;
} }
DB::beginTransaction();
try {
//执行库存操作 //执行库存操作
$goodsSkuItem = $hasGoodsSkus[$row[0]]; $goodsSkuItem = $hasGoodsSkus[$row[0]];
//保存記錄 //保存記錄
@ -66,13 +69,17 @@ class LossImport implements ToArray, SkipsEmptyRows
$lossRecords->phenomenon = $row[5] ?? ''; $lossRecords->phenomenon = $row[5] ?? '';
$lossRecords->reason = $row[6] ?? ''; $lossRecords->reason = $row[6] ?? '';
$lossRecords->date = $today; $lossRecords->date = $today;
if(!empty($row[7])){ if (!empty($row[7])) {
$lossRecords->date = DateTimeUtils::excelUploadDateToString($row[7],$today); $lossRecords->date = DateTimeUtils::excelUploadDateToString($row[7], $today);
} }
$lossRecords->save(); $lossRecords->save();
$updateIds = GoodSkuService::computeSkuStock($goodsSkuItem, ["num" => 0 - $row[2], 'cost' => $row[3]]); $updateIds = GoodSkuService::computeSkuStock($goodsSkuItem, ["num" => 0 - $row[2], 'cost' => $row[3]]);
DB::commit();
$allUpdateIds = array_merge($allUpdateIds, $updateIds); $allUpdateIds = array_merge($allUpdateIds, $updateIds);
} catch (\Exception $exception) {
DB::rollBack();
}
} }
Log::info("报损导入内容:", $collection); Log::info("报损导入内容:", $collection);
// 批量更新 // 批量更新

View File

@ -20,7 +20,6 @@ class SaleStockImport implements ToArray, SkipsEmptyRows
*/ */
public function array(array $collection) public function array(array $collection)
{ {
Log::info("collection",[$collection]);
if (!empty($collection)) { if (!empty($collection)) {
unset($collection[0]); unset($collection[0]);
$externalSkuIds = []; $externalSkuIds = [];
@ -29,6 +28,9 @@ class SaleStockImport implements ToArray, SkipsEmptyRows
$row = array_map(static function ($v) { $row = array_map(static function ($v) {
return trim($v); return trim($v);
}, $row); }, $row);
if ($row[2] < 0) {
throw new Exception("商品编码{$row[0]}在售库存数不能小于0");
}
$inventoryKeyByExternalSkuIdMap[$row[0]] = $row[2]; $inventoryKeyByExternalSkuIdMap[$row[0]] = $row[2];
$externalSkuIds[] = $row[0]; $externalSkuIds[] = $row[0];
} }
@ -41,7 +43,7 @@ class SaleStockImport implements ToArray, SkipsEmptyRows
foreach ($externalSkuIds as $externalSkuId) { foreach ($externalSkuIds as $externalSkuId) {
// 成本 // 成本
$goodsSku = GoodsSku::query()->where('external_sku_id', $externalSkuId)->first(['id', 'cost', 'sale_stock']); $goodsSku = GoodsSku::query()->where('external_sku_id', $externalSkuId)->first(['id', 'cost', 'sale_stock']);
Log::info("SKU",[$goodsSku]); Log::info("SKU", [$goodsSku]);
if (empty($goodsSku)) { if (empty($goodsSku)) {
continue; continue;
} }

View File

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

View File

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

View File

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

View File

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