mirror of
https://gitee.com/hzchunfen/erp.git
synced 2025-12-01 14:40:44 +00:00
77 lines
2.5 KiB
PHP
77 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Imports;
|
|
|
|
use App\Events\StockUpdateEvent;
|
|
use App\Models\DailyStockRecord;
|
|
use App\Models\Goods;
|
|
use App\Models\GoodsSku;
|
|
use App\Utils\DateTimeUtils;
|
|
use Exception;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
|
|
use Maatwebsite\Excel\Concerns\ToCollection;
|
|
use App\Utils\ArrayUtils;
|
|
|
|
class InventoryImport implements ToCollection, SkipsEmptyRows
|
|
{
|
|
/**
|
|
* @throws Exception
|
|
*/
|
|
public function collection(Collection $collection)
|
|
{
|
|
unset($collection[0]);
|
|
$collection = $collection->toArray();
|
|
$goodsCodes = [];
|
|
foreach ($collection as &$row) {
|
|
$row = array_map(static function ($v) {
|
|
return trim($v);
|
|
}, $row);
|
|
$goodsCodes[] = $row[0];
|
|
}
|
|
unset($row);
|
|
$hasGoods = Goods::query()->whereIn('goods_code', $goodsCodes)->get(['id', 'goods_code'])->toArray();
|
|
$hasGoods = ArrayUtils::index($hasGoods, 'goods_code');
|
|
$updateIds = [];
|
|
$day = DateTimeUtils::getToday();
|
|
$dateTime = date('Y-m-d H:i:s');
|
|
DB::beginTransaction();
|
|
try {
|
|
foreach ($collection as $row) {
|
|
if (!isset($hasGoods[$row[0]])) {
|
|
continue;
|
|
}
|
|
$goodsSku = GoodsSku::query()
|
|
->where('goods_id', $hasGoods[$row[0]]['id'])
|
|
->where('sku_code', $row[4])
|
|
->first(['id']);
|
|
if (empty($goodsSku)) {
|
|
Log::warning(json_encode($row, 256) . '=====库存导入未找到');
|
|
continue;
|
|
}
|
|
$updateIds[] = $goodsSku->id;
|
|
DailyStockRecord::where('sku_id', $goodsSku->id)->where('day', $day)->update([
|
|
'inventory' => $row[6],
|
|
'inventory_time' => $dateTime
|
|
]);
|
|
}
|
|
DB::commit();
|
|
} catch (Exception $exception) {
|
|
DB::rollBack();
|
|
// 返回错误
|
|
throw $exception;
|
|
}
|
|
$onSkuIds = GoodsSku::query()
|
|
->where('stock', '>', 0)
|
|
->where('status', '<>', 0)
|
|
->pluck('id')
|
|
->toArray();
|
|
if ($downSkuIds = array_diff($onSkuIds, $updateIds)) {
|
|
GoodsSku::whereIn('id', $onSkuIds)->update(['stock' => 0]);
|
|
event(new StockUpdateEvent($downSkuIds));
|
|
}
|
|
}
|
|
}
|