Company.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <?php
  2. namespace app\api\controller\invitation;
  3. use app\common\controller\Frontend;
  4. use think\facade\Db;
  5. class Company extends Frontend
  6. {
  7. protected array $noNeedPermission = ['myCompanies', 'members', 'addMember', 'removeMember', 'createCompany', 'updateCompany', 'deleteCompany','searchEmail','checkCompany'];
  8. /**
  9. * 检查当前用户是否已有企业
  10. */
  11. public function checkCompany(): void
  12. {
  13. $userId = $this->auth->id;
  14. if (!$userId) {
  15. $this->error('用户未登录');
  16. }
  17. $hasCompany = $this->hasCompany($userId);
  18. $companyInfo = $hasCompany ? $this->getUserCompany($userId) : null;
  19. $this->success('', [
  20. 'has_company' => $hasCompany,
  21. 'company' => $companyInfo,
  22. 'message' => $hasCompany
  23. ? '您已' . ($companyInfo['role'] == 'creator' ? '创建' : '加入') . '企业《' . ($companyInfo['name'] ?? '') . '》'
  24. : '您尚未创建或加入任何企业'
  25. ]);
  26. }
  27. /**
  28. * 检查用户是否已有企业(创建或加入)
  29. * @return bool 返回true表示已有企业,false表示没有企业
  30. */
  31. private function hasCompany($userId): bool
  32. {
  33. try {
  34. // 1. 检查是否创建了企业
  35. $createdCompany = Db::table('ba_company')
  36. ->where('creator_id', $userId)
  37. ->where('status', 1) // 只检查正常状态的企业
  38. ->count();
  39. if ($createdCompany > 0) {
  40. return true;
  41. }
  42. // 2. 检查是否加入了企业(作为成员)
  43. $joinedCompany = Db::table('ba_company_member')
  44. ->alias('cm')
  45. ->leftJoin('ba_company c', 'c.id = cm.company_id')
  46. ->where('cm.user_id', $userId)
  47. ->where('cm.status', 1) // 成员状态正常
  48. ->where('c.status', 1) // 企业状态正常
  49. ->count();
  50. return $joinedCompany > 0;
  51. } catch (\Throwable $e) {
  52. \think\facade\Log::error('检查用户是否已有企业失败: ' . $e->getMessage());
  53. return false;
  54. }
  55. }
  56. /**
  57. * 获取用户的唯一企业信息(如果有)
  58. * @return array|null 返回企业信息,没有则返回null
  59. */
  60. private function getUserCompany($userId): ?array
  61. {
  62. try {
  63. // 先检查是否是创建人
  64. $createdCompany = Db::table('ba_company')
  65. ->where('creator_id', $userId)
  66. ->where('status', 1)
  67. ->field('id, name, creator_id, creator_name, status')
  68. ->find();
  69. if ($createdCompany) {
  70. $createdCompany['role'] = 'creator'; // 角色:创建人
  71. return $createdCompany;
  72. }
  73. // 再检查是否是成员
  74. $joinedCompany = Db::table('ba_company_member')
  75. ->alias('cm')
  76. ->leftJoin('ba_company c', 'c.id = cm.company_id')
  77. ->where('cm.user_id', $userId)
  78. ->where('cm.status', 1)
  79. ->where('c.status', 1)
  80. ->field('c.id, c.name, cm.role, cm.name as member_name, cm.email as member_email, cm.join_time')
  81. ->find();
  82. if ($joinedCompany) {
  83. $joinedCompany['role'] = $joinedCompany['role'] == 1 ? 'admin' : 'member'; // 管理员或普通成员
  84. return $joinedCompany;
  85. }
  86. return null;
  87. } catch (\Throwable $e) {
  88. \think\facade\Log::error('获取用户企业信息失败: ' . $e->getMessage());
  89. return null;
  90. }
  91. }
  92. /**
  93. * 获取我的企业列表(我创建的企业)
  94. */
  95. public function myCompanies(): void
  96. {
  97. $userId = $this->auth->id;
  98. if (!$userId) {
  99. $this->error('用户未登录');
  100. }
  101. // 获取用户的唯一企业
  102. $companyInfo = $this->getUserCompany($userId);
  103. if (!$companyInfo) {
  104. $this->success('您尚未创建或加入任何企业', [
  105. 'has_company' => false,
  106. 'company' => null,
  107. 'message' => '您可以创建一个新企业,或者请其他企业管理员邀请您加入'
  108. ]);
  109. }
  110. // 获取企业成员数量
  111. $memberCount = Db::table('ba_company_member')
  112. ->where('company_id', $companyInfo['id'])
  113. ->where('status', 1)
  114. ->count();
  115. $companyInfo['member_count'] = $memberCount;
  116. $companyInfo['has_company'] = true;
  117. // 格式化角色文本
  118. if (isset($companyInfo['role'])) {
  119. switch ($companyInfo['role']) {
  120. case 'creator':
  121. $companyInfo['role_text'] = '企业创建人';
  122. break;
  123. case 'admin':
  124. $companyInfo['role_text'] = '管理员';
  125. break;
  126. case 'member':
  127. $companyInfo['role_text'] = '普通成员';
  128. break;
  129. default:
  130. $companyInfo['role_text'] = '未知角色';
  131. }
  132. }
  133. // 格式化时间
  134. if (isset($companyInfo['join_time'])) {
  135. $companyInfo['join_time_formatted'] = date('Y-m-d H:i', strtotime($companyInfo['join_time']));
  136. }
  137. if (isset($companyInfo['create_time'])) {
  138. $companyInfo['create_time_formatted'] = date('Y-m-d H:i', strtotime($companyInfo['create_time']));
  139. }
  140. $this->success('', $companyInfo);
  141. }
  142. /**
  143. * 获取企业成员列表
  144. */
  145. public function members(): void
  146. {
  147. $userId = $this->auth->id;
  148. $companyId = $this->request->get('company_id', 0);
  149. $page = $this->request->get('page', 1);
  150. $pageSize = $this->request->get('pageSize', 10);
  151. if ($companyId <= 0) {
  152. $this->error('请选择企业');
  153. }
  154. // 验证用户是否有权限查看该企业
  155. $company = Db::table('ba_company')
  156. ->where('id', $companyId)
  157. ->field('id, creator_id')
  158. ->find();
  159. if (!$company) {
  160. $this->error('企业不存在');
  161. }
  162. // 检查用户是否是企业创建人或成员
  163. $isCreator = $company['creator_id'] == $userId;
  164. $isMember = Db::table('ba_company_member')
  165. ->where('company_id', $companyId)
  166. ->where('user_id', $userId)
  167. ->find();
  168. if (!$isCreator && !$isMember) {
  169. $this->error('无权查看该企业');
  170. }
  171. // 查询成员列表
  172. $query = Db::table('ba_company_member')
  173. ->where('company_id', $companyId);
  174. $total = $query->count();
  175. $members = $query->field('id, name, email, role, status, join_time, create_time')
  176. ->order('role', 'asc')
  177. ->order('join_time', 'asc')
  178. ->page($page, $pageSize)
  179. ->select()
  180. ->toArray();
  181. // 处理成员数据
  182. foreach ($members as &$member) {
  183. $member['role_text'] = $member['role'] == 1 ? '创建人/管理员' : '普通成员';
  184. $member['status_text'] = $member['status'] == 1 ? '正常' : '禁用';
  185. // 是否可以操作(只有创建人可以操作)
  186. $member['can_operate'] = $isCreator && $member['role'] != 1; // 创建人不能操作自己
  187. }
  188. $this->success('', [
  189. 'list' => $members,
  190. 'total' => $total,
  191. 'page' => $page,
  192. 'page_size' => $pageSize,
  193. 'is_creator' => $isCreator // 前端根据这个判断是否显示操作按钮
  194. ]);
  195. }
  196. /**
  197. * 通过邮箱添加成员
  198. */
  199. public function addMember(): void
  200. {
  201. if (!$this->request->isPost()) {
  202. $this->error('非法请求');
  203. }
  204. $userId = $this->auth->id;
  205. $companyId = $this->request->post('company_id', 0);
  206. $email = $this->request->post('email', '');
  207. $name = $this->request->post('name', '');
  208. if ($companyId <= 0) {
  209. $this->error('请选择企业');
  210. }
  211. if (empty($email) || empty($name)) {
  212. $this->error('邮箱和姓名不能为空');
  213. }
  214. // 验证邮箱格式
  215. if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  216. $this->error('邮箱格式不正确');
  217. }
  218. // 验证用户是否有权限添加成员(必须是企业创建人)
  219. $company = Db::table('ba_company')
  220. ->where('id', $companyId)
  221. ->where('creator_id', $userId)
  222. ->find();
  223. if (!$company) {
  224. $this->error('无权添加成员或企业不存在');
  225. }
  226. // 检查邮箱是否已经是成员
  227. $exists = Db::table('ba_company_member')
  228. ->where('company_id', $companyId)
  229. ->where('email', $email)
  230. ->find();
  231. if ($exists) {
  232. $this->error('该邮箱已经是企业成员');
  233. }
  234. // 查询邮箱对应的用户ID(如果用户已注册)
  235. $user = Db::table('ba_user')
  236. ->where('email', $email)
  237. ->field('id')
  238. ->find();
  239. $userIdForMember = $user ? $user['id'] : null;
  240. // 添加成员
  241. $memberData = [
  242. 'company_id' => $companyId,
  243. 'user_id' => $userIdForMember,
  244. 'email' => $email,
  245. 'name' => $name,
  246. 'role' => 2, // 普通成员
  247. 'status' => 1,
  248. 'join_time' => date('Y-m-d H:i:s'),
  249. 'create_time' => date('Y-m-d H:i:s'),
  250. 'update_time' => date('Y-m-d H:i:s')
  251. ];
  252. $result = Db::table('ba_company_member')->insert($memberData);
  253. if ($result) {
  254. $this->success('添加成员成功');
  255. } else {
  256. $this->error('添加成员失败');
  257. }
  258. }
  259. /**
  260. * 移除企业成员
  261. */
  262. public function removeMember(): void
  263. {
  264. if (!$this->request->isPost()) {
  265. $this->error('非法请求');
  266. }
  267. $userId = $this->auth->id;
  268. $memberId = $this->request->post('member_id', 0);
  269. if ($memberId <= 0) {
  270. $this->error('成员ID错误');
  271. }
  272. // 查询成员信息
  273. $member = Db::table('ba_company_member')
  274. ->where('id', $memberId)
  275. ->find();
  276. if (!$member) {
  277. $this->error('成员不存在');
  278. }
  279. // 验证用户是否有权限移除成员(必须是企业创建人)
  280. $company = Db::table('ba_company')
  281. ->where('id', $member['company_id'])
  282. ->where('creator_id', $userId)
  283. ->find();
  284. if (!$company) {
  285. $this->error('无权移除成员');
  286. }
  287. // 不能移除创建人自己
  288. if ($member['role'] == 1) {
  289. $this->error('不能移除创建人');
  290. }
  291. // 移除成员
  292. $result = Db::table('ba_company_member')
  293. ->where('id', $memberId)
  294. ->delete();
  295. if ($result) {
  296. $this->success('移除成员成功');
  297. } else {
  298. $this->error('移除成员失败');
  299. }
  300. }
  301. /**
  302. * 创建企业
  303. */
  304. public function createCompany(): void
  305. {
  306. if (!$this->request->isPost()) {
  307. $this->error('非法请求');
  308. }
  309. $userId = $this->auth->id;
  310. $name = $this->request->post('name', '');
  311. if (empty($name)) {
  312. $this->error('企业名称不能为空');
  313. }
  314. if ($this->hasCompany($userId)) {
  315. $companyInfo = $this->getUserCompany($userId);
  316. $role = isset($companyInfo['role']) ? $companyInfo['role'] : '';
  317. $companyName = isset($companyInfo['name']) ? $companyInfo['name'] : '';
  318. $message = "您已经";
  319. if ($role == 'creator') {
  320. $message .= "创建了企业《{$companyName}》";
  321. } elseif ($role == 'admin') {
  322. $message .= "加入了企业《{$companyName}》并拥有管理员权限";
  323. } elseif ($role == 'member') {
  324. $message .= "加入了企业《{$companyName}》";
  325. }
  326. $message .= ",无法再创建新企业。";
  327. $this->error($message);
  328. }
  329. // 检查企业名称是否已存在
  330. $exists = Db::table('ba_company')
  331. ->where('name', $name)
  332. ->find();
  333. if ($exists) {
  334. $this->error('企业名称已存在');
  335. }
  336. // 获取当前用户信息
  337. $user = Db::table('ba_user')
  338. ->where('id', $userId)
  339. ->field('username, nickname')
  340. ->find();
  341. $creatorName = $user['nickname'] ?: $user['username'];
  342. // 创建企业
  343. $companyData = [
  344. 'name' => $name,
  345. 'creator_id' => $userId,
  346. 'creator_name' => $creatorName,
  347. 'status' => 1,
  348. 'create_time' => date('Y-m-d H:i:s'),
  349. 'update_time' => date('Y-m-d H:i:s')
  350. ];
  351. $companyId = Db::table('ba_company')->insertGetId($companyData);
  352. if ($companyId) {
  353. // 将创建人自己添加到企业成员表中
  354. $memberData = [
  355. 'company_id' => $companyId,
  356. 'user_id' => $userId,
  357. 'email' => $this->auth->email ?: '',
  358. 'name' => $creatorName,
  359. 'role' => 1, // 创建人/管理员
  360. 'status' => 1,
  361. 'join_time' => date('Y-m-d H:i:s'),
  362. 'create_time' => date('Y-m-d H:i:s'),
  363. 'update_time' => date('Y-m-d H:i:s')
  364. ];
  365. Db::table('ba_company_member')->insert($memberData);
  366. $this->success('创建企业成功', [
  367. 'company_id' => $companyId,
  368. 'name' => $name
  369. ]);
  370. } else {
  371. $this->error('创建企业失败');
  372. }
  373. }
  374. /**
  375. * 更新企业信息
  376. */
  377. public function updateCompany(): void
  378. {
  379. if (!$this->request->isPost()) {
  380. $this->error('非法请求');
  381. }
  382. $userId = $this->auth->id;
  383. $companyId = $this->request->post('company_id', 0);
  384. $name = $this->request->post('name', '');
  385. if ($companyId <= 0) {
  386. $this->error('企业ID错误');
  387. }
  388. if (empty($name)) {
  389. $this->error('企业名称不能为空');
  390. }
  391. // 验证用户是否有权限修改(必须是企业创建人)
  392. $company = Db::table('ba_company')
  393. ->where('id', $companyId)
  394. ->where('creator_id', $userId)
  395. ->find();
  396. if (!$company) {
  397. $this->error('无权修改企业信息或企业不存在');
  398. }
  399. // 检查企业名称是否与其他企业重名(排除自己)
  400. $exists = Db::table('ba_company')
  401. ->where('name', $name)
  402. ->where('id', '<>', $companyId)
  403. ->find();
  404. if ($exists) {
  405. $this->error('企业名称已存在');
  406. }
  407. // 更新企业信息
  408. $result = Db::table('ba_company')
  409. ->where('id', $companyId)
  410. ->update([
  411. 'name' => $name,
  412. 'update_time' => date('Y-m-d H:i:s')
  413. ]);
  414. if ($result !== false) {
  415. $this->success('更新企业信息成功');
  416. } else {
  417. $this->error('更新企业信息失败');
  418. }
  419. }
  420. /**
  421. * 删除企业
  422. */
  423. public function deleteCompany(): void
  424. {
  425. try {
  426. if (!$this->request->isPost()) {
  427. $this->error('非法请求');
  428. }
  429. $userId = $this->auth->id;
  430. $companyId = $this->request->post('company_id', 0);
  431. if ($companyId <= 0) {
  432. $this->error('企业ID错误');
  433. }
  434. // 验证用户是否有权限删除(必须是企业创建人)
  435. $company = Db::table('ba_company')
  436. ->where('id', $companyId)
  437. ->where('creator_id', $userId)
  438. ->find();
  439. if (!$company) {
  440. $this->error('无权删除企业或企业不存在');
  441. }
  442. // 删除企业(会自动删除关联的成员,因为有外键约束)
  443. $result = Db::table('ba_company')
  444. ->where('id', $companyId)
  445. ->delete();
  446. if ($result) {
  447. $this->success('删除企业成功');
  448. } else {
  449. $this->error('删除企业失败');
  450. }
  451. } catch (\Throwable $e) {
  452. \think\facade\Log::error('删除企业失败: ' . $e->getMessage());
  453. $this->error('删除企业失败');
  454. }
  455. }
  456. /**
  457. * 搜索邮箱用户(用于添加成员时搜索)
  458. */
  459. public function searchEmail(): void
  460. {
  461. $keyword = $this->request->get('keyword', '');
  462. if (empty($keyword)) {
  463. $this->success('', []);
  464. }
  465. // 搜索用户表,查找邮箱匹配的用户
  466. $users = Db::table('ba_user')
  467. ->whereLike('email', "%{$keyword}%")
  468. ->field('id, username, nickname, email')
  469. ->limit(10)
  470. ->select()
  471. ->toArray();
  472. // 格式化返回数据
  473. $result = [];
  474. foreach ($users as $user) {
  475. $result[] = [
  476. 'id' => $user['id'],
  477. 'name' => $user['nickname'] ?: $user['username'],
  478. 'email' => $user['email']
  479. ];
  480. }
  481. $this->success('', $result);
  482. }
  483. }