SiteService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Niucloud-admin 企业快速开发的saas管理平台
  4. // +----------------------------------------------------------------------
  5. // | 官方网址:https://www.niucloud.com
  6. // +----------------------------------------------------------------------
  7. // | niucloud团队 版权所有 开源版本可自由商用
  8. // +----------------------------------------------------------------------
  9. // | Author: Niucloud Team
  10. // +----------------------------------------------------------------------
  11. namespace app\service\admin\site;
  12. use app\dict\addon\AddonDict;
  13. use app\dict\site\SiteDict;
  14. use app\dict\sys\AppTypeDict;
  15. use app\model\addon\Addon;
  16. use app\model\site\Site;
  17. use app\model\site\SiteGroup;
  18. use app\model\sys\SysUserRole;
  19. use app\service\admin\addon\AddonService;
  20. use app\service\admin\auth\AuthService;
  21. use app\service\admin\generator\GenerateService;
  22. use app\service\admin\sys\MenuService;
  23. use app\service\admin\sys\RoleService;
  24. use app\service\admin\user\UserRoleService;
  25. use app\service\admin\user\UserService;
  26. use app\service\core\site\CoreSiteService;
  27. use core\base\BaseAdminService;
  28. use core\exception\AdminException;
  29. use core\exception\CommonException;
  30. use Exception;
  31. use think\db\exception\DataNotFoundException;
  32. use think\db\exception\DbException;
  33. use think\db\exception\ModelNotFoundException;
  34. use think\facade\Cache;
  35. use think\facade\Db;
  36. /**
  37. * 站点服务层
  38. * Class Site
  39. * @package app\service\admin\site
  40. */
  41. class SiteService extends BaseAdminService
  42. {
  43. public static $cache_tag_name = 'site_cash';
  44. public function __construct()
  45. {
  46. parent::__construct();
  47. $this->model = new Site();
  48. }
  49. /**
  50. * 获取站点列表
  51. * @param array $where
  52. * @return array
  53. * @throws DbException
  54. */
  55. public function getPage(array $where = [])
  56. {
  57. $field = 'site_id, site_name, front_end_name, front_end_logo, app_type, keywords, logo, icon, `desc`, status, latitude, longitude, province_id, city_id,
  58. district_id, address, full_address, phone, business_hours, create_time, expire_time, group_id, app, addons, site_domain';
  59. $condition = [
  60. [ 'app_type', '<>', 'admin' ]
  61. ];
  62. $search_model = $this->model->where($condition)->withSearch([ 'create_time', 'expire_time', 'keyword', 'status', 'group_id', 'app', 'site_domain' ], $where)->with(['groupName'])->field($field)->append([ 'status_name' ])->order('create_time desc');
  63. return $this->pageQuery($search_model, function ($item){
  64. $item['admin'] = (new SysUserRole())->where([ ['site_id', '=', $item['site_id'] ], ['is_admin', '=', 1] ])
  65. ->field('uid')
  66. ->with(['userinfo'])
  67. ->find()->toArray();
  68. });
  69. }
  70. /**
  71. * 站点信息
  72. * @param int $site_id
  73. * @return array
  74. */
  75. public function getInfo(int $site_id)
  76. {
  77. $field = 'site_id, site_name, front_end_name, front_end_logo, app_type, keywords, logo, icon, `desc`, status, latitude, longitude, province_id, city_id,
  78. district_id, address, full_address, phone, business_hours, create_time, expire_time, group_id, app, addons, site_domain';
  79. $info = $this->model->where([ [ 'site_id', '=', $site_id ] ])->with([ 'groupName' ])->field($field)->append([ 'status_name' ])->findOrEmpty()->toArray();
  80. if (!empty($info)) {
  81. $site_addons = (new CoreSiteService())->getAddonKeysBySiteId($site_id);
  82. $info['site_addons'] = (new Addon())->where([ ['key', 'in', $site_addons]])->field('key,title,desc,icon,type')->select()->toArray();
  83. }
  84. return $info;
  85. }
  86. /**
  87. * 添加站点(平台端添加站点,同时添加用户以及密码)
  88. * @param array $data
  89. * ['site_name' => '', 'username' => '', 'head_img' => '', 'real_name' => '', 'password' => '']
  90. * @return mixed
  91. * @throws DbException
  92. */
  93. public function add(array $data)
  94. {
  95. $user_service = new UserService();
  96. if ($user_service->checkUsername($data[ 'username' ])) throw new AdminException('USERNAME_REPEAT');
  97. $site_group = (new SiteGroup())->where([ ['group_id', '=', $data[ 'group_id' ] ] ])->field('app,addon')->findOrEmpty();
  98. $data[ 'app_type' ] = 'site';
  99. //添加站点
  100. $data_site = [
  101. 'site_name' => $data[ 'site_name' ],
  102. 'app_type' => $data[ 'app_type' ],
  103. 'group_id' => $data[ 'group_id' ],
  104. 'create_time' => time(),
  105. 'expire_time' => $data[ 'expire_time' ],
  106. 'app' => $site_group['app'],
  107. 'addons' => ''
  108. ];
  109. Db::startTrans();
  110. try {
  111. $site = $this->model->create($data_site);
  112. $site_id = $site->site_id;
  113. if ($data['uid']) {
  114. (new UserRoleService())->add($data['uid'], ['role_ids' => '', 'is_admin' => 1], $site_id);
  115. } else {
  116. //添加用户
  117. $data_user = [
  118. 'username' => $data[ 'username' ],
  119. 'head_img' => $data[ 'head_img' ] ?? '',
  120. 'status' => $data[ 'status' ] ?? 1,
  121. 'real_name' => $data[ 'real_name' ] ?? '',
  122. 'password' => $data[ 'password' ],
  123. 'role_ids' => '',
  124. 'is_admin' => 1
  125. ];
  126. $data['uid'] = ( new UserService() )->addSiteUser($data_user, $site_id);
  127. }
  128. //添加站点成功事件
  129. event("AddSiteAfter", [ 'site_id' => $site_id, 'main_app' => $site_group['app'], 'site_addons' => $site_group['addon'] ]);
  130. Cache::delete('user_role_list_' . $data['uid']);
  131. Db::commit();
  132. return $site_id;
  133. } catch ( Exception $e) {
  134. Db::rollback();
  135. throw new AdminException($e->getMessage().$e->getFile().$e->getLine());
  136. }
  137. }
  138. /**
  139. * 修改站点
  140. * @param int $site_id
  141. * @param array $data
  142. * @return bool
  143. */
  144. public function edit(int $site_id, array $data)
  145. {
  146. $site = $this->model->where([ [ 'site_id', '=', $site_id ] ])->with(['site_group'])->findOrEmpty();
  147. if ($site->isEmpty()) throw new AdminException('SITE_NOT_EXIST');
  148. Db::startTrans();
  149. try {
  150. if (isset($data[ 'group_id' ]) && $site['group_id'] != $data[ 'group_id' ]) {
  151. $old_site_group = $site['site_group'];
  152. $site_group = (new SiteGroup())->where([ ['group_id', '=', $data[ 'group_id' ] ] ])->field('app,addon')->findOrEmpty();
  153. $data['app'] = $site_group['app'];
  154. if (empty($site->initalled_addon)) {
  155. $site->initalled_addon = array_merge($old_site_group['app'], $old_site_group['addon']);
  156. }
  157. //添加站点成功事件
  158. event("AddSiteAfter", [ 'site_id' => $site_id, 'main_app' => array_diff($site_group['app'], $site->initalled_addon) , 'site_addons' => array_diff($site_group['addon'], $site->initalled_addon) ]);
  159. $data['initalled_addon'] = array_values(array_unique(array_merge($site->initalled_addon, $site_group['app'], $site_group['addon'])));
  160. }
  161. if (isset($data['expire_time']) && $site['status'] != SiteDict::CLOSE) {
  162. $data['status'] = strtotime($data['expire_time']) > time() ? SiteDict::ON : SiteDict::EXPIRE;
  163. }
  164. $site->save($data);
  165. Cache::tag(self::$cache_tag_name . $site_id)->clear();
  166. Db::commit();
  167. return true;
  168. } catch ( Exception $e) {
  169. Db::rollback();
  170. throw new AdminException($e->getMessage().$e->getFile().$e->getLine());
  171. }
  172. }
  173. /**
  174. * 删除站点
  175. * @param int $site_id
  176. */
  177. public function del(int $site_id) {
  178. Db::startTrans();
  179. try {
  180. $site = $this->model->where([ [ 'site_id', '=', $site_id ] ])->findOrEmpty()->toArray();
  181. // 删除站点相关数据
  182. $sys_models = (new GenerateService())->getModels(['addon' => 'system']);
  183. $addon_models = [];
  184. $addons = (new CoreSiteService())->getAddonKeysBySiteId($site_id);
  185. foreach($addons as $addon) {
  186. $addon_models[] = (new GenerateService())->getModels(['addon' => $addon ]);
  187. }
  188. $models = array_merge($sys_models, ...$addon_models);
  189. foreach ($models as $model) {
  190. $name = "\\$model";
  191. $class = new $name();
  192. if (in_array('site_id', $class->getTableFields())) {
  193. $class->where([ ['site_id', '=', $site['site_id'] ] ])->delete();
  194. }
  195. }
  196. Cache::tag(self::$cache_tag_name . $site_id)->clear();
  197. Db::commit();
  198. return true;
  199. } catch (\Exception $e) {
  200. Db::rollback();
  201. throw new CommonException($e->getMessage());
  202. }
  203. }
  204. /**
  205. * 站点数量
  206. * @return int
  207. * @throws DbException
  208. */
  209. public function getCount(array $where = [])
  210. {
  211. $condition = [];
  212. if(!empty($where['group_id'])){
  213. $condition[] = ['group_id', '=', $where['group_id']];
  214. }
  215. if(!empty($where['create_time'])){
  216. $condition[] = ['create_time', 'between', $where['create_time']];
  217. }
  218. return $this->model->where($condition)->count();
  219. }
  220. /**
  221. * 获取授权当前站点信息(用做缓存)
  222. * @return mixed
  223. */
  224. public function getSiteCache(int $site_id)
  225. {
  226. return (new CoreSiteService())->getSiteCache($site_id);
  227. }
  228. /**
  229. * 通过站点id获取菜单列表
  230. * @param int $site_id
  231. * @param $is_tree
  232. * @param $status
  233. * @param $addon 所以应用名一般不建议叫all
  234. * @return mixed
  235. * @throws DataNotFoundException
  236. * @throws DbException
  237. * @throws ModelNotFoundException
  238. */
  239. public function getMenuList(int $site_id, $is_tree, $status, $addon = 'all', int $is_button = 1)
  240. {
  241. $site_info = $this->getSiteCache($site_id);
  242. if (empty($site_info))
  243. return [];
  244. $app_type = $site_info[ 'app_type' ];
  245. // if ($app_type == AppTypeDict::ADMIN) {
  246. // return ( new MenuService() )->getAllMenuList($app_type, $status, $is_tree, $is_button);
  247. // } else {
  248. // $addons = ( new AddonService() )->getAddonKeysBySiteId($site_id);
  249. // $addons[] = '';
  250. // if($addon != 'all'){
  251. // $addons = [$addon];
  252. // }
  253. // return ( new MenuService() )->getMenuListBySystem($this->app_type, $addons, $is_tree, $is_button, $status);
  254. // }
  255. if (AuthService::isSuperAdmin()) {
  256. $is_admin = 1;
  257. } else {
  258. $user_role_info = (new AuthService())->getAuthRole($this->site_id);
  259. if(empty($user_role_info))
  260. return [];
  261. $is_admin = $user_role_info['is_admin'];//是否是超级管理员组
  262. }
  263. if ($is_admin) {
  264. return ( new MenuService() )->getAllMenuList($app_type, $status, $is_tree, $is_button);
  265. } else {
  266. $user_role_ids = $user_role_info['role_ids'];
  267. $role_service = new RoleService();
  268. $menu_keys = $role_service->getMenuIdsByRoleIds($this->site_id, $user_role_ids);
  269. return ( new MenuService() )->getMenuListByMenuKeys($this->site_id, $menu_keys, $this->app_type, $is_tree, $addon, $is_button);
  270. }
  271. }
  272. /**
  273. * 通过站点id获取站点菜单极限
  274. * @param int $site_id
  275. * @param $status
  276. * @return array|mixed|string|null
  277. */
  278. public function getMenuIdsBySiteId(int $site_id, $status)
  279. {
  280. $site_info = $this->getSiteCache($site_id);
  281. if (empty($site_info))
  282. return [];
  283. $app_type = $site_info[ 'app_type' ];
  284. if ($app_type == AppTypeDict::ADMIN) {
  285. return ( new MenuService() )->getAllMenuIdsByAppType($app_type, $status);
  286. } else {
  287. $addons = ( new AddonService() )->getAddonKeysBySiteId($site_id);
  288. return ( new MenuService() )->getMenuKeysBySystem($app_type, $addons);
  289. }
  290. }
  291. /**
  292. * 通过站点id获取菜单列表
  293. * @param int $site_id
  294. * @param $status
  295. * @return mixed
  296. */
  297. public function getApiList(int $site_id, $status)
  298. {
  299. $site_info = $this->getSiteCache($site_id);
  300. if (empty($site_info))
  301. return [];
  302. $app_type = $site_info[ 'app_type' ];
  303. if ($app_type == AppTypeDict::ADMIN) {
  304. return ( new MenuService() )->getAllApiList($app_type, $status);
  305. } else {
  306. $addons = ( new AddonService() )->getAddonKeysBySiteId($site_id);
  307. return ( new MenuService() )->getApiListBySystem($app_type, $addons);
  308. }
  309. }
  310. /**
  311. * 站点过期时间
  312. * @param int $site_id
  313. * @return array
  314. */
  315. public function getExpireTime(int $site_id)
  316. {
  317. $field = 'expire_time';
  318. return $this->model->where([ [ 'site_id', '=', $site_id ] ])->field($field)->findOrEmpty()->toArray();
  319. }
  320. /**
  321. * 获取站点的插件
  322. * @return array
  323. */
  324. public function getSiteAddons(array $where) {
  325. $site_addon = (new CoreSiteService())->getAddonKeysBySiteId($this->site_id);
  326. return (new Addon())->where([['type', '=', AddonDict::ADDON], ['status', '=', AddonDict::ON], ['key', 'in', $site_addon ]])->withSearch(['title'], $where)->append(['status_name'])->field('title, icon, key, desc, status, type, support_app')->select()->toArray();
  327. }
  328. }