126 lines
3.2 KiB
PHP
126 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands\Dealer;
|
|
|
|
use App\Models\Dealer;
|
|
use App\Models\DealerManagerSalesLog;
|
|
use App\Models\DealerOrder;
|
|
use App\Models\UserInfo;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class OrderProcessCommand extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'dealer:order-process';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = '处理结算状态是待处理的已付款经销商订单';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*
|
|
* @return int
|
|
*/
|
|
public function handle()
|
|
{
|
|
DealerOrder::chunkById(200, function ($orders) {
|
|
$orders->load(['userInfo.dealer', 'products']);
|
|
|
|
foreach ($orders as $order) {
|
|
try {
|
|
DB::beginTransaction();
|
|
|
|
$this->processOrder($order);
|
|
|
|
DB::commit();
|
|
} catch (Throwable $e) {
|
|
DB::rollBack();
|
|
|
|
report($e);
|
|
}
|
|
}
|
|
});
|
|
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* 处理经销商订单
|
|
*
|
|
* @param \App\Models\DealerOrder $order
|
|
* @return void
|
|
*/
|
|
protected function processOrder(DealerOrder $order)
|
|
{
|
|
$tz = now();
|
|
|
|
$dealers = $this->getDealers($userInfo = $order->userInfo);
|
|
|
|
// 如果当前用户的上级有管理者,则需要增加管理者的商品销售业绩
|
|
if ($manager = $this->firstManager([$userInfo->dealer, ...$dealers])) {
|
|
DealerManagerSalesLog::insert(
|
|
$order->products->map(function ($product) use ($manager, $tz) {
|
|
return [
|
|
'user_id' => $manager->user_id,
|
|
'order_id' => $product->order_id,
|
|
'product_id' => $product->product_id,
|
|
'lvl' => $manager->lvl,
|
|
'sales_volume' => $product->qty,
|
|
'created_at' => $tz,
|
|
'updated_at' => $tz,
|
|
];
|
|
})->all()
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 从给定的经销商中获取第一个管理者
|
|
*
|
|
* @param array $dealers
|
|
* @return \App\Models\Dealer|null
|
|
*/
|
|
protected function firstManager(array $dealers): ?Dealer
|
|
{
|
|
foreach ($dealers as $dealer) {
|
|
if ($dealer->is_manager) {
|
|
return $dealer;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取给定用户的上级经销商
|
|
*
|
|
* @param \App\Models\UserInfo $userInfo
|
|
* @return array
|
|
*/
|
|
protected function getDealers(UserInfo $userInfo)
|
|
{
|
|
$ancestors = [];
|
|
|
|
if (empty($pids = $userInfo->parent_ids)) {
|
|
return $ancestors;
|
|
}
|
|
|
|
$ancestors = UserInfo::with(['dealer'])
|
|
->whereIn('user_id', $pids)
|
|
->latest('depth')
|
|
->get(['user_id', 'depth']);
|
|
|
|
return $ancestors->map(function ($item) {
|
|
return $item->dealer;
|
|
})->all();
|
|
}
|
|
}
|