SyncFundCurrencyJsonTool.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace App\Module\Fund\AdminControllers\Tools;
  3. use App\Module\Game\DCache\FundCurrencyJsonConfig;
  4. use Dcat\Admin\Grid\Tools\AbstractTool;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Log;
  7. /**
  8. * 货币配置表同步工具
  9. *
  10. * 用于在后台管理界面中同步货币配置表数据到JSON文件
  11. */
  12. class SyncFundCurrencyJsonTool extends AbstractTool
  13. {
  14. /**
  15. * 是否显示按钮
  16. *
  17. * @var bool
  18. */
  19. protected $shouldDisplay;
  20. /**
  21. * 按钮样式
  22. *
  23. * @var string
  24. */
  25. protected $style = 'btn btn-primary waves-effect';
  26. /**
  27. * 构造函数
  28. *
  29. * @param bool $shouldDisplay 是否显示按钮
  30. */
  31. public function __construct(bool $shouldDisplay = true)
  32. {
  33. $this->shouldDisplay = $shouldDisplay;
  34. }
  35. /**
  36. * 按钮标题
  37. *
  38. * @return string
  39. */
  40. public function title()
  41. {
  42. return '生成JSON';
  43. }
  44. /**
  45. * 确认提示
  46. *
  47. * @return string
  48. */
  49. public function confirm()
  50. {
  51. return '确定要生成货币配置JSON数据吗?';
  52. }
  53. /**
  54. * 处理请求
  55. *
  56. * @param Request $request
  57. * @return mixed
  58. */
  59. public function handle(Request $request)
  60. {
  61. try {
  62. // 直接调用缓存类刷新数据,这会同时生成JSON文件
  63. FundCurrencyJsonConfig::getData([], true);
  64. return $this->response()->success('生成成功')->refresh();
  65. } catch (\Exception $e) {
  66. Log::error('Generate fund_currency.json exception: '.$e->getMessage());
  67. return $this->response()->error('生成失败:'.$e->getMessage());
  68. }
  69. }
  70. /**
  71. * 渲染按钮
  72. *
  73. * @return string
  74. */
  75. public function render()
  76. {
  77. if (!$this->shouldDisplay) {
  78. return '';
  79. }
  80. return parent::render();
  81. }
  82. /**
  83. * 判断是否应该显示按钮
  84. *
  85. * @return bool
  86. */
  87. public static function shouldDisplay(): bool
  88. {
  89. // 获取缓存数据
  90. $json = FundCurrencyJsonConfig::getData();
  91. // 如果没有生成时间戳,说明需要生成
  92. if (!isset($json['generated_ts'])) {
  93. return true;
  94. }
  95. // 获取生成时间和最后更新时间
  96. $generatedAt = \Carbon\Carbon::createFromTimestamp($json['generated_ts']);
  97. // 获取货币配置的最后更新时间
  98. $lastUpdated = \Carbon\Carbon::parse(\App\Module\Fund\Models\FundCurrencyModel::max('update_time') ?: '2000-01-01');
  99. // 如果生成时间早于最后更新时间,说明需要重新生成
  100. return $generatedAt->lt($lastUpdated);
  101. }
  102. }