113 lines
2.8 KiB
PHP
113 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\DistributionPreIncome;
|
|
use App\Models\Order;
|
|
use App\Models\UserInfo;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class OrderSettleCommand extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'order:settle';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = '订单结算';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*
|
|
* @return int
|
|
*/
|
|
public function handle()
|
|
{
|
|
// 只查询可结算的订单,并且没有处理中的售后单
|
|
Order::whereDoesntHave('afterSales', function ($query) {
|
|
return $query->processing();
|
|
})->settlable()->chunkById(200, function ($orders) {
|
|
$orders->load(['user', 'afterSales']);
|
|
|
|
foreach ($orders as $order) {
|
|
try {
|
|
DB::beginTransaction();
|
|
|
|
$this->settle($order);
|
|
|
|
DB::commit();
|
|
} catch (Throwable $e) {
|
|
DB::rollBack();
|
|
|
|
report($e);
|
|
}
|
|
}
|
|
});
|
|
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* 结算成长值
|
|
*
|
|
* @param \App\Models\Order $order
|
|
* @return void
|
|
*/
|
|
protected function settle(Order $order)
|
|
{
|
|
// 用户可得销售值
|
|
$salesValue = $order->sales_value;
|
|
|
|
foreach ($order->afterSales as $afterSale) {
|
|
if ($afterSale->isCancelled()) {
|
|
continue;
|
|
}
|
|
|
|
$salesValue = bcsub($salesValue, $afterSale->sales_value, 2);
|
|
}
|
|
|
|
$user = $order->user;
|
|
|
|
// 结算下单用户的成长值
|
|
$user->userInfo()->update([
|
|
'growth_value' => DB::raw("growth_value+{$salesValue}"),
|
|
'pre_growth_value' => DB::raw("pre_growth_value-{$salesValue}"),
|
|
]);
|
|
|
|
// 尝试提升用户的代理等级
|
|
$user->userInfo->attemptUpgradeAgentLevel();
|
|
|
|
if (count($pids = $user->userInfo->parent_ids) > 0) {
|
|
// 更新上级的团队销售值
|
|
UserInfo::whereIn('user_id', $pids)->update([
|
|
'group_sales_value' => DB::raw("group_sales_value + {$salesValue}"),
|
|
]);
|
|
|
|
$ancestors = UserInfo::whereIn('user_id', $pids)->latest('depth')->get();
|
|
|
|
foreach ($ancestors as $ancestor) {
|
|
$ancestor->attemptUpgradeAgentLevel();
|
|
}
|
|
}
|
|
|
|
// 将订单标记未已结算
|
|
$order->update([
|
|
'is_settle' => true,
|
|
]);
|
|
|
|
// 将预收益标记为结算中
|
|
DistributionPreIncome::where('order_id', $order->id)->update([
|
|
'status' => DistributionPreIncome::STATUS_PROCESSING,
|
|
]);
|
|
}
|
|
}
|