<?php
namespace App\Console\Commands;
use App\Modules\Product\Models\ProductRelation;
use App\Modules\Product\Models\ProductStore;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UpdateIsInStockFlat extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'usxs:update-productstore:is-in-stock-flat';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Updates stock flat column';
/**
*
*/
public function handle()
{
// Get all products in stores
$parents = ProductStore::select(['product_id', 'store_id'])
->get()
->toArray();
foreach ($parents as $parent) {
$parentId = $parent['product_id'];
$storeId = $parent['store_id'];
// Get all children of the parent
$children = ProductRelation::where('product_id', $parentId)
->select(['child_id'])
->get()
->pluck('child_id')
->toArray();
$childrenNotInStock = 1;
// Check if the product has children
if (count($children)) {
$this->line("Checking parent " . $parentId . " for store " . $storeId);
$storeHasProduct = FALSE;
foreach ($children as $child) {
$this->line("\tFound child " . $child);
// Get children's stock info
$productInStore = ProductStore::where('product_id', $child)
->where('store_id', $storeId)
->select([
'id',
'qty',
'out_of_stock_qty',
'is_in_stock'
])
->take(1)
->get()
->toArray();
if (isset($productInStore[0]['id'])) {
$storeHasProduct = TRUE;
// Check if child is in stock
if (($productInStore[0]['qty'] > $productInStore[0]['out_of_stock_qty']) AND ($productInStore[0]['is_in_stock'])) {
$this->line("\tChild is in stock");
$childrenNotInStock = 0;
break;
}
$this->warn("\tChild NOT in stock");
}
else {
$this->line("\tChild NOT in any store");
}
}
// Make parent out of stock if all children are out of stock
if ($childrenNotInStock AND $storeHasProduct) {
$this->info("\tParent marked OOS " . $parentId);
ProductStore::where('product_id', $parentId)
->where('store_id', $storeId)
->update(['is_in_stock_flat' => 0]);
} else {
$this->line("\tParent not marked OOS " . $parentId);
ProductStore::where('product_id', $parentId)
->where('store_id', $storeId)
->update(['is_in_stock_flat' => 1]);
}
}
}
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.