ProcessDeviceZjTask.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Jobs;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. use Illuminate\Foundation\Bus\Dispatchable;
  6. use Illuminate\Queue\InteractsWithQueue;
  7. use Illuminate\Queue\SerializesModels;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. class ProcessDeviceZjTask implements ShouldQueue
  11. {
  12. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  13. public $timeout = 120;
  14. /**
  15. * 接收传入的设备月度折旧单单号数组
  16. */
  17. protected $ids;
  18. /**
  19. * @param array $codes 例如:['1', '2']
  20. */
  21. public function __construct(array $ids)
  22. {
  23. $this->ids = $ids;
  24. }
  25. public function handle()
  26. {
  27. if (empty($this->ids)) {
  28. return;
  29. }
  30. try {
  31. $mainIds = $this->ids;
  32. $affectedDeviceIds = DB::table('monthly_dd_order_details')
  33. ->whereIn('main_id', $mainIds)
  34. ->where('del_time', 0)
  35. ->pluck('device_id')
  36. ->unique() // 去重
  37. ->toArray();
  38. if (empty($affectedDeviceIds)) return;
  39. // 3. 【核心改变】:脱离单号限制!直接去查这些设备在全表里“所有的”历史折旧总和
  40. $globalDepreciationMap = DB::table('monthly_dd_order_details')
  41. ->select('device_id', DB::raw('SUM(depreciation_amount) as total_amount'))
  42. ->whereIn('device_id', $affectedDeviceIds)
  43. ->where('del_time', 0)
  44. ->groupBy('device_id')
  45. ->pluck('total_amount', 'device_id') // 生成 [设备ID => 历史所有折旧累计总额]
  46. ->toArray();
  47. // 4. 分批更新到设备表中
  48. $chunkSize = 100;
  49. $chunks = array_chunk($affectedDeviceIds, $chunkSize);
  50. foreach ($chunks as $chunkDeviceIds) {
  51. DB::transaction(function () use ($chunkDeviceIds, $globalDepreciationMap) {
  52. foreach ($chunkDeviceIds as $deviceId) {
  53. // 拿到该设备有史以来所有的折旧总和(如果没有查到说明被删光了,默认为 0)
  54. $totalAmount = (float)($globalDepreciationMap[$deviceId] ?? 0);
  55. DB::table('device')
  56. ->where('id', $deviceId)
  57. ->update([
  58. 'total_depreciation' => $totalAmount, // 绝对总额直接覆盖
  59. ]);
  60. }
  61. });
  62. }
  63. } catch (\Throwable $e) {
  64. $this->delete();
  65. }
  66. }
  67. }