SyncFarmHouseJsonTool.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Module\Farm\AdminControllers\Tools;
  3. use Dcat\Admin\Grid\Tools\AbstractTool;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Log;
  6. class SyncFarmHouseJsonTool extends AbstractTool
  7. {
  8. protected $shouldDisplay;
  9. protected $style = 'btn btn-primary waves-effect';
  10. public function __construct(bool $shouldDisplay = true)
  11. {
  12. $this->shouldDisplay = $shouldDisplay;
  13. }
  14. public function title()
  15. {
  16. return '生成JSON';
  17. }
  18. public function confirm()
  19. {
  20. return '确定要生成房屋配置JSON数据吗?';
  21. }
  22. public function handle(Request $request)
  23. {
  24. try {
  25. // 直接调用命令生成JSON
  26. $process = new \Symfony\Component\Process\Process(['php', 'artisan', 'farm:generate-house-json']);
  27. $process->setWorkingDirectory(base_path());
  28. $process->run();
  29. if (!$process->isSuccessful()) {
  30. Log::error('Generate farm_house.json failed: ' . $process->getErrorOutput());
  31. return $this->response()->error('生成失败:' . $process->getErrorOutput());
  32. }
  33. return $this->response()->success('生成成功')->refresh();
  34. } catch (\Exception $e) {
  35. Log::error('Generate farm_house.json exception: '.$e->getMessage());
  36. return $this->response()->error('生成失败:'.$e->getMessage());
  37. }
  38. }
  39. public function render()
  40. {
  41. if (!$this->shouldDisplay) {
  42. return '';
  43. }
  44. return parent::render();
  45. }
  46. public static function shouldDisplay(): bool
  47. {
  48. $jsonPath = public_path('json/farm_house.json');
  49. if (!file_exists($jsonPath)) {
  50. return true;
  51. }
  52. $json = json_decode(file_get_contents($jsonPath), true);
  53. $generatedAt = \Carbon\Carbon::parse($json['generated_at']);
  54. $lastUpdated = \Carbon\Carbon::parse(\App\Module\Farm\Models\FarmHouseConfig::max('updated_at'));
  55. return $generatedAt->lt($lastUpdated);
  56. }
  57. }