erp/app/Imports/InventoryImport.php

79 lines
2.6 KiB
PHP
Raw Normal View History

2022-09-08 01:02:07 +08:00
<?php
namespace App\Imports;
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\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Utils\ArrayUtils;
2022-09-17 01:53:58 +08:00
use App\Events\StockUpdateEvent;
2022-09-08 01:02:07 +08:00
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');
2022-09-17 01:53:58 +08:00
foreach ($collection as $row) {
if (!isset($hasGoods[$row[0]])) {
continue;
2022-09-08 01:02:07 +08:00
}
2022-09-17 01:53:58 +08:00
$goodsSku = GoodsSku::query()
->where('goods_id', $hasGoods[$row[0]]['id'])
->where('sku_code', $row[4])
->first();
if (empty($goodsSku)) {
Log::warning(json_encode($row, 256) . '=====库存导入未找到');
continue;
}
$goodsSku->stock = $row[6] + $row[7];
if ('下架' === $goodsSku->status) {
$goodsSku->status = 1;
}
2022-10-27 16:35:48 +08:00
$goodsSku->cost = $row[8];
2022-09-17 01:53:58 +08:00
$goodsSku->save();
event(new StockUpdateEvent($goodsSku));
$updateIds[] = $goodsSku->id;
DailyStockRecord::query()->where('sku_id', $goodsSku->id)->where('day', $day)->update([
'arrived_today_num' => $row[7],
'inventory' => $row[6],
'inventory_time' => $dateTime
]);
2022-09-08 01:02:07 +08:00
}
$onSkuIds = GoodsSku::query()
->where('status', '<>', 0)
->pluck('id')
->toArray();
2022-09-14 13:18:25 +08:00
$downSkuIds = array_diff($onSkuIds, $updateIds);
foreach ($downSkuIds as $downSkuId) {
$goodsSku = GoodsSku::query()->find($downSkuId);
$goodsSku->yesterday_num -= $goodsSku->stock;
$goodsSku->stock = 0;
$goodsSku->save();
event(new StockUpdateEvent($goodsSku));
2022-09-08 01:02:07 +08:00
}
}
}