| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- namespace App\Jobs;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Queue\SerializesModels;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- class ProcessDeviceZjTask implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public $timeout = 120;
- /**
- * 接收传入的设备月度折旧单单号数组
- */
- protected $ids;
- /**
- * @param array $codes 例如:['1', '2']
- */
- public function __construct(array $ids)
- {
- $this->ids = $ids;
- }
- public function handle()
- {
- if (empty($this->ids)) {
- return;
- }
- try {
- $mainIds = $this->ids;
- $affectedDeviceIds = DB::table('monthly_dd_order_details')
- ->whereIn('main_id', $mainIds)
- ->where('del_time', 0)
- ->pluck('device_id')
- ->unique() // 去重
- ->toArray();
- if (empty($affectedDeviceIds)) return;
- // 3. 【核心改变】:脱离单号限制!直接去查这些设备在全表里“所有的”历史折旧总和
- $globalDepreciationMap = DB::table('monthly_dd_order_details')
- ->select('device_id', DB::raw('SUM(depreciation_amount) as total_amount'))
- ->whereIn('device_id', $affectedDeviceIds)
- ->where('del_time', 0)
- ->groupBy('device_id')
- ->pluck('total_amount', 'device_id') // 生成 [设备ID => 历史所有折旧累计总额]
- ->toArray();
- // 4. 分批更新到设备表中
- $chunkSize = 100;
- $chunks = array_chunk($affectedDeviceIds, $chunkSize);
- foreach ($chunks as $chunkDeviceIds) {
- DB::transaction(function () use ($chunkDeviceIds, $globalDepreciationMap) {
- foreach ($chunkDeviceIds as $deviceId) {
- // 拿到该设备有史以来所有的折旧总和(如果没有查到说明被删光了,默认为 0)
- $totalAmount = (float)($globalDepreciationMap[$deviceId] ?? 0);
- DB::table('device')
- ->where('id', $deviceId)
- ->update([
- 'total_depreciation' => $totalAmount, // 绝对总额直接覆盖
- ]);
- }
- });
- }
- } catch (\Throwable $e) {
- $this->delete();
- }
- }
- }
|