Factory.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace app\api\controller\ps;
  3. use app\common\controller\Api;
  4. use app\common\library\ps\FactoryContext;
  5. use app\common\model\ps\Factory as FactoryModel;
  6. /**
  7. * 当前工厂信息
  8. */
  9. class Factory extends Api
  10. {
  11. protected $noNeedRight = '*';
  12. public function index()
  13. {
  14. $factoryId = FactoryContext::id();
  15. if (!$factoryId) {
  16. $this->error('账号未绑定工厂');
  17. }
  18. $factory = FactoryModel::get($factoryId);
  19. if (!$factory) {
  20. $this->error('工厂不存在');
  21. }
  22. $info = $factory->toArray();
  23. unset($info['api_key_hash']);
  24. $info['has_api_key'] = trim((string)$factory['api_key_hash']) !== '';
  25. if ($this->auth->factory_role !== 'owner') {
  26. unset($info['invite_code'], $info['api_key_prefix'], $info['api_key_time'], $info['has_api_key']);
  27. }
  28. $this->success('', [
  29. 'factory' => $info,
  30. 'role' => $this->auth->factory_role,
  31. ]);
  32. }
  33. /**
  34. * 管理员修改本厂资料
  35. */
  36. public function edit()
  37. {
  38. if ($this->auth->factory_role !== 'owner') {
  39. $this->error('只有工厂管理员可以修改本厂资料');
  40. }
  41. $factoryId = FactoryContext::id();
  42. $factory = FactoryModel::get($factoryId);
  43. if (!$factory) {
  44. $this->error('工厂不存在');
  45. }
  46. $name = trim((string)$this->request->post('name', ''));
  47. if ($name === '') {
  48. $this->error('请填写工厂名称');
  49. }
  50. $factory->allowField(['name', 'contact', 'mobile', 'address', 'logo'])->save([
  51. 'name' => mb_substr($name, 0, 100),
  52. 'contact' => mb_substr(trim((string)$this->request->post('contact', '')), 0, 50),
  53. 'mobile' => mb_substr(trim((string)$this->request->post('mobile', '')), 0, 20),
  54. 'address' => mb_substr(trim((string)$this->request->post('address', '')), 0, 255),
  55. 'logo' => trim((string)$this->request->post('logo', '')),
  56. ]);
  57. $info = $factory->toArray();
  58. unset($info['api_key_hash']);
  59. $info['has_api_key'] = trim((string)$factory['api_key_hash']) !== '';
  60. $this->success('已保存', ['factory' => $info]);
  61. }
  62. /**
  63. * 生成或重置本厂 Open API Key(明文只返回一次)
  64. */
  65. public function reset_api_key()
  66. {
  67. if ($this->auth->factory_role !== 'owner') {
  68. $this->error('只有工厂管理员可以管理 API Key');
  69. }
  70. $factoryId = FactoryContext::id();
  71. $factory = FactoryModel::get($factoryId);
  72. if (!$factory) {
  73. $this->error('工厂不存在');
  74. }
  75. $plain = \app\common\library\ps\FactoryApiKey::generate($factory);
  76. $this->success('请立即复制保存,关闭后无法再查看完整 Key', [
  77. 'api_key' => $plain,
  78. 'api_key_prefix' => $factory['api_key_prefix'],
  79. 'api_key_time' => (int)$factory['api_key_time'],
  80. ]);
  81. }
  82. }