From 0d2fa3e3bd3b2d5aa6dbd83702c459adeeff9dd6 Mon Sep 17 00:00:00 2001 From: Thanakorn S Date: Thu, 7 May 2026 08:56:40 +0700 Subject: [PATCH] encapsulate setting api [OOP] --- app/assets/utils/classes/UserManager.php | 273 ++++++++++++++++++++ app/setting/api/engine/manage_users.php | 195 +------------- app/setting/api/engine/retrieve_profile.php | 32 +-- app/setting/api/engine/retrieve_users.php | 37 +-- app/setting/api/engine/search_users.php | 50 +--- app/setting/api/engine/switch_branch.php | 30 +-- 6 files changed, 314 insertions(+), 303 deletions(-) create mode 100644 app/assets/utils/classes/UserManager.php diff --git a/app/assets/utils/classes/UserManager.php b/app/assets/utils/classes/UserManager.php new file mode 100644 index 0000000..0ab7916 --- /dev/null +++ b/app/assets/utils/classes/UserManager.php @@ -0,0 +1,273 @@ +pdo = $pdo; + $this->company_id = $company_id; + $this->user_id = $user_id; + } + + // ───────────────────────────────────────────────────────────── + // READ / IDENTITY BASIS + // ───────────────────────────────────────────────────────────── + + /** + * Return the current user's profile row. + * + * Used to populate the profile settings page and to bootstrap the UI + * with the logged-in user's name and avatar. + * + * @return array Keys: user_id, username, name, surname, email, phone, + * country, address, profile_picture. + * @throws Exception If the user row is not found. + */ + public function getProfile(): array { + $sth = $this->pdo->prepare( + "SELECT user_id, username, name, surname, + email, phone, country, address, profile_picture + FROM user + WHERE user_id = :user_id + LIMIT 1" + ); + $sth->execute([':user_id' => $this->user_id]); + $user = $sth->fetch(PDO::FETCH_ASSOC); + + if (!$user) throw new Exception('User not found.'); + return $user; + } + + /** + * Return all companies the current user belongs to, plus their role in each. + * + * Used to populate the branch-switcher dropdown. Results are ordered by + * company name so the list is stable regardless of membership order. + * + * @return array Each row: company_id, channel_name, company_name, branch, role. + */ + public function getCompanyList(): array { + $sth = $this->pdo->prepare( + "SELECT cl.company_id, cl.channel_name, cl.company_name, cl.branch, cmu.role + FROM company_map_user cmu + JOIN company_list cl ON cl.company_id = cmu.company_id + WHERE cmu.user_id = :user_id + ORDER BY cl.company_name ASC" + ); + $sth->execute([':user_id' => $this->user_id]); + return $sth->fetchAll(PDO::FETCH_ASSOC); + } + + // ───────────────────────────────────────────────────────────── + // COMPANY MEMBER BASIS + // ───────────────────────────────────────────────────────────── + + /** + * Return all users mapped to the current company, ordered by role then name. + * + * Role order: owner → admin → staff → viewer. + * Used to populate the user management table on the settings page. + * + * @return array Each row: map_id, role, created_at, user_id, username, + * name, surname, email, profile_picture. + */ + public function getCompanyUsers(): array { + $sth = $this->pdo->prepare( + "SELECT + m.map_id, + m.role, + m.created_at, + u.user_id, + u.username, + u.name, + u.surname, + u.email, + u.profile_picture + FROM company_map_user m + JOIN user u ON u.user_id = m.user_id + WHERE m.company_id = :company_id + ORDER BY FIELD(m.role, 'owner', 'admin', 'staff', 'viewer'), u.name ASC" + ); + $sth->execute([':company_id' => $this->company_id]); + return $sth->fetchAll(PDO::FETCH_ASSOC); + } + + /** + * Search for registered users by email keyword, excluding existing members. + * + * Returns up to 10 matches. Used for the invite autocomplete input. + * Excludes users already mapped to this company so the results only show + * people who can actually be invited. + * + * @param string $keyword Partial email to match. + * @return array Each row: user_id, username, name, surname, email. + */ + public function searchUsers(string $keyword): array { + if ($keyword === '') return []; + + $sth = $this->pdo->prepare( + "SELECT u.user_id, u.username, u.name, u.surname, u.email + FROM user u + WHERE u.email LIKE :kw + AND u.user_id NOT IN ( + SELECT user_id FROM company_map_user + WHERE company_id = :company_id + ) + ORDER BY u.email ASC + LIMIT 10" + ); + $sth->execute([ + ':kw' => '%' . $keyword . '%', + ':company_id' => $this->company_id, + ]); + return $sth->fetchAll(PDO::FETCH_ASSOC); + } + + /** + * Add a registered user to the current company by email. + * + * Validates email format, role, and that the target account exists. + * Blocks inviting self or someone already mapped to the company. + * + * @param string $email Email address of the user to invite. + * @param string $role Role to assign: 'admin', 'staff', or 'viewer'. + * @return string The invited user's email, for use in the success message. + * @throws Exception On any validation or constraint failure. + */ + public function inviteUser(string $email, string $role): string { + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + throw new Exception('Invalid email address.'); + } + + $allowed_roles = ['admin', 'staff', 'viewer']; + if (!in_array($role, $allowed_roles, true)) { + throw new Exception('Invalid role selected.'); + } + + $sth = $this->pdo->prepare( + "SELECT user_id, email FROM user WHERE email = :email LIMIT 1" + ); + $sth->execute([':email' => $email]); + $target = $sth->fetch(PDO::FETCH_ASSOC); + + if (!$target) { + throw new Exception('No registered account found with that email address.'); + } + + $target_user_id = (int)$target['user_id']; + + if ($target_user_id === $this->user_id) { + throw new Exception('You cannot invite yourself.'); + } + + $sth = $this->pdo->prepare( + "SELECT map_id FROM company_map_user + WHERE company_id = :company_id AND user_id = :user_id + LIMIT 1" + ); + $sth->execute([':company_id' => $this->company_id, ':user_id' => $target_user_id]); + if ($sth->fetch()) { + throw new Exception('This user is already a member of your company.'); + } + + $this->pdo->prepare( + "INSERT INTO company_map_user (company_id, user_id, role, created_at) + VALUES (:company_id, :user_id, :role, NOW())" + )->execute([ + ':company_id' => $this->company_id, + ':user_id' => $target_user_id, + ':role' => $role, + ]); + + return $target['email']; + } + + /** + * Change the role of a company member. + * + * Blocks changing the owner's role. Only 'admin', 'staff', 'viewer' + * are assignable — the owner role is set at company creation and is immutable. + * + * @param int $map_id The company_map_user.map_id to update. + * @param string $role New role: 'admin', 'staff', or 'viewer'. + * @throws Exception If the member is not found or is the owner. + */ + public function updateRole(int $map_id, string $role): void { + $allowed_roles = ['admin', 'staff', 'viewer']; + if (!$map_id || !in_array($role, $allowed_roles, true)) { + throw new Exception('Invalid request.'); + } + + $sth = $this->pdo->prepare( + "SELECT role FROM company_map_user + WHERE map_id = :map_id AND company_id = :company_id + LIMIT 1" + ); + $sth->execute([':map_id' => $map_id, ':company_id' => $this->company_id]); + $current_role = $sth->fetchColumn(); + + if ($current_role === false) throw new Exception('User not found.'); + if ($current_role === 'owner') throw new Exception('Owner role cannot be changed.'); + + $this->pdo->prepare( + "UPDATE company_map_user + SET role = :role + WHERE map_id = :map_id AND company_id = :company_id" + )->execute([ + ':role' => $role, + ':map_id' => $map_id, + ':company_id' => $this->company_id, + ]); + } + + /** + * Remove a user from the current company. + * + * Blocks removing the owner or removing yourself. + * Hard-deletes the company_map_user row — membership history is not retained. + * + * @param int $map_id The company_map_user.map_id to delete. + * @throws Exception If the member is not found, is the owner, or is the caller. + */ + public function removeUser(int $map_id): void { + if (!$map_id) throw new Exception('Invalid request.'); + + $sth = $this->pdo->prepare( + "SELECT role, user_id FROM company_map_user + WHERE map_id = :map_id AND company_id = :company_id + LIMIT 1" + ); + $sth->execute([':map_id' => $map_id, ':company_id' => $this->company_id]); + $row = $sth->fetch(PDO::FETCH_ASSOC); + + if (!$row) throw new Exception('User not found.'); + if ($row['role'] === 'owner') throw new Exception('The owner cannot be removed.'); + if ((int)$row['user_id'] === $this->user_id) throw new Exception('You cannot remove yourself.'); + + $this->pdo->prepare( + "DELETE FROM company_map_user + WHERE map_id = :map_id AND company_id = :company_id" + )->execute([':map_id' => $map_id, ':company_id' => $this->company_id]); + } +} diff --git a/app/setting/api/engine/manage_users.php b/app/setting/api/engine/manage_users.php index 77dad43..d3a590a 100644 --- a/app/setting/api/engine/manage_users.php +++ b/app/setting/api/engine/manage_users.php @@ -1,214 +1,47 @@ prepare(" - SELECT role FROM company_map_user - WHERE company_id = :company_id AND user_id = :user_id - LIMIT 1 - "); - $sth->execute([':company_id' => $company_id, ':user_id' => $user_id]); - db_check($sth, $answer); - $caller_role = $sth->fetchColumn(); - - if (!in_array($caller_role, ['owner', 'admin'], true)) { - $answer['message'] = 'You do not have permission to manage users.'; - http_response_code(403); - exit(json_encode($answer)); - } + require_role($user_role, ['owner', 'admin']); $action = $data['action'] ?? ''; + $um = new UserManager($pdo1, $company_id, $user_id); try { - // ══════════════════════════════════════════════════════════════════════ - // CREATE — invite a user by email - // ══════════════════════════════════════════════════════════════════════ if ($action === 'create') { + $email = strtolower(trim($data['invite_email'] ?? '')); + $role = trim($data['invite_role'] ?? ''); - $invite_email = strtolower(trim($data['invite_email'] ?? '')); - $invite_role = trim($data['invite_role'] ?? ''); - - if (!filter_var($invite_email, FILTER_VALIDATE_EMAIL)) { - $answer['message'] = 'Invalid email address.'; - http_response_code(422); - exit(json_encode($answer)); - } - - $allowed_roles = ['admin', 'staff', 'viewer']; - if (!in_array($invite_role, $allowed_roles, true)) { - $answer['message'] = 'Invalid role selected.'; - http_response_code(422); - exit(json_encode($answer)); - } - - // Look up user by email - $sth = $pdo1->prepare("SELECT user_id, email FROM user WHERE email = :email LIMIT 1"); - $sth->execute([':email' => $invite_email]); - db_check($sth, $answer); - $target = $sth->fetch(PDO::FETCH_ASSOC); - - if (!$target) { - $answer['message'] = 'No registered account found with that email address.'; - http_response_code(404); - exit(json_encode($answer)); - } - - $target_user_id = (int)$target['user_id']; - - // Prevent inviting self - if ($target_user_id === (int)$user_id) { - $answer['message'] = 'You cannot invite yourself.'; - http_response_code(422); - exit(json_encode($answer)); - } - - // Check if already mapped to this company - $sth = $pdo1->prepare(" - SELECT map_id FROM company_map_user - WHERE company_id = :company_id AND user_id = :user_id - LIMIT 1 - "); - $sth->execute([':company_id' => $company_id, ':user_id' => $target_user_id]); - db_check($sth, $answer); - $existing = $sth->fetch(PDO::FETCH_ASSOC); - - if ($existing) { - $answer['message'] = 'This user is already a member of your company.'; - http_response_code(409); - exit(json_encode($answer)); - } - - $sth = $pdo1->prepare(" - INSERT INTO company_map_user - (company_id, user_id, role, created_at) - VALUES - (:company_id, :user_id, :role, NOW()) - "); - $sth->execute([ - ':company_id' => $company_id, - ':user_id' => $target_user_id, - ':role' => $invite_role, - ]); - db_check($sth, $answer); - + $invited_email = $um->inviteUser($email, $role); $answer['success'] = 1; - $answer['message'] = htmlspecialchars($target['email']) . ' has been added to your company.'; + $answer['message'] = htmlspecialchars($invited_email) . ' has been added to your company.'; - - // ══════════════════════════════════════════════════════════════════════ - // UPDATE — change a user's role - // ══════════════════════════════════════════════════════════════════════ } elseif ($action === 'update') { + $map_id = (int)($data['map_id'] ?? 0); + $role = trim($data['role'] ?? ''); - $map_id = (int)($data['map_id'] ?? 0); - $new_role = trim($data['role'] ?? ''); - - $allowed_roles = ['admin', 'staff', 'viewer']; - if (!$map_id || !in_array($new_role, $allowed_roles, true)) { - $answer['message'] = 'Invalid request.'; - http_response_code(422); - exit(json_encode($answer)); - } - - // Verify map belongs to this company and is not the owner - $sth = $pdo1->prepare(" - SELECT role FROM company_map_user - WHERE map_id = :map_id AND company_id = :company_id - LIMIT 1 - "); - $sth->execute([':map_id' => $map_id, ':company_id' => $company_id]); - db_check($sth, $answer); - $target_role = $sth->fetchColumn(); - - if ($target_role === false) { - $answer['message'] = 'User not found.'; - http_response_code(404); - exit(json_encode($answer)); - } - if ($target_role === 'owner') { - $answer['message'] = 'Owner role cannot be changed.'; - http_response_code(403); - exit(json_encode($answer)); - } - - $sth = $pdo1->prepare(" - UPDATE company_map_user - SET role = :role - WHERE map_id = :map_id AND company_id = :company_id - "); - $sth->execute([ - ':role' => $new_role, - ':map_id' => $map_id, - ':company_id' => $company_id, - ]); - db_check($sth, $answer); - + $um->updateRole($map_id, $role); $answer['success'] = 1; $answer['message'] = 'Role updated successfully.'; - - // ══════════════════════════════════════════════════════════════════════ - // DELETE — remove user from company - // ══════════════════════════════════════════════════════════════════════ } elseif ($action === 'delete') { - $map_id = (int)($data['map_id'] ?? 0); - if (!$map_id) { - $answer['message'] = 'Invalid request.'; - http_response_code(422); - exit(json_encode($answer)); - } - - // Verify map belongs to this company, and isn't the owner - $sth = $pdo1->prepare(" - SELECT role, user_id FROM company_map_user - WHERE map_id = :map_id AND company_id = :company_id - LIMIT 1 - "); - $sth->execute([':map_id' => $map_id, ':company_id' => $company_id]); - db_check($sth, $answer); - $row = $sth->fetch(PDO::FETCH_ASSOC); - - if (!$row) { - $answer['message'] = 'User not found.'; - http_response_code(404); - exit(json_encode($answer)); - } - if ($row['role'] === 'owner') { - $answer['message'] = 'The owner cannot be removed.'; - http_response_code(403); - exit(json_encode($answer)); - } - // Prevent removing yourself - if ((int)$row['user_id'] === (int)$user_id) { - $answer['message'] = 'You cannot remove yourself.'; - http_response_code(403); - exit(json_encode($answer)); - } - - // Hard delete — just remove the row - $sth = $pdo1->prepare(" - DELETE FROM company_map_user - WHERE map_id = :map_id AND company_id = :company_id - "); - $sth->execute([':map_id' => $map_id, ':company_id' => $company_id]); - db_check($sth, $answer); + $um->removeUser($map_id); $answer['success'] = 1; $answer['message'] = 'User has been removed from this company.'; - } else { $answer['message'] = 'Unknown action.'; http_response_code(400); } } catch (Exception $e) { - $answer['message'] = 'An error occurred. Please try again.'; - http_response_code(500); + $answer['message'] = $e->getMessage(); + http_response_code(400); } exit(json_encode($answer)); -?> \ No newline at end of file +?> diff --git a/app/setting/api/engine/retrieve_profile.php b/app/setting/api/engine/retrieve_profile.php index eccb26e..e1ce411 100644 --- a/app/setting/api/engine/retrieve_profile.php +++ b/app/setting/api/engine/retrieve_profile.php @@ -1,33 +1,17 @@ prepare( - "SELECT user_id, username, name, surname, - email, phone, country, address, profile_picture - FROM user - WHERE user_id = :user_id - LIMIT 1" - ); - $sth->execute([':user_id' => $user_id]); - db_check($sth, $answer); - - $user = $sth->fetch(PDO::FETCH_ASSOC); - - if (!$user) { - $answer['message'] = 'User not found.'; - http_response_code(404); - exit(json_encode($answer)); - } - $answer['success'] = 1; - $answer['output'] = $user; - + $answer['output'] = $um->getProfile(); } catch (Exception $e) { - $answer['message'] = 'Failed to load profile.'; - http_response_code(500); + $answer['message'] = $e->getMessage(); + http_response_code(404); } - exit(json_encode($answer)); \ No newline at end of file + exit(json_encode($answer)); +?> diff --git a/app/setting/api/engine/retrieve_users.php b/app/setting/api/engine/retrieve_users.php index 77b1fb7..d6fdf55 100644 --- a/app/setting/api/engine/retrieve_users.php +++ b/app/setting/api/engine/retrieve_users.php @@ -1,38 +1,11 @@ prepare(" - SELECT - m.map_id, - m.role, - m.created_at, - u.user_id, - u.username, - u.name, - u.surname, - u.email, - u.profile_picture - FROM company_map_user m - JOIN user u ON u.user_id = m.user_id - WHERE m.company_id = :company_id - ORDER BY - FIELD(m.role, 'owner', 'admin', 'staff', 'viewer'), - u.name ASC - "); - $sth->execute([':company_id' => $company_id]); - db_check($sth, $answer); - - $answer['success'] = 1; - $answer['output'] = $sth->fetchAll(PDO::FETCH_ASSOC); - - } catch (Exception $e) { - $answer['message'] = 'Failed to load users.'; - http_response_code(500); - } + $um = new UserManager($pdo1, $company_id, $user_id); + $answer['success'] = 1; + $answer['output'] = $um->getCompanyUsers(); exit(json_encode($answer)); -?> \ No newline at end of file +?> diff --git a/app/setting/api/engine/search_users.php b/app/setting/api/engine/search_users.php index 901c20a..c446091 100644 --- a/app/setting/api/engine/search_users.php +++ b/app/setting/api/engine/search_users.php @@ -1,50 +1,12 @@ prepare(" - SELECT - u.user_id, - u.username, - u.name, - u.surname, - u.email - FROM user u - WHERE - u.email LIKE :kw - AND u.user_id NOT IN ( - SELECT user_id FROM company_map_user - WHERE company_id = :company_id - ) - ORDER BY u.email ASC - LIMIT 10 - "); - $sth->execute([ - ':kw' => $like, - ':company_id' => $company_id, - ]); - db_check($sth, $answer); - - $answer['success'] = 1; - $answer['result'] = $sth->fetchAll(PDO::FETCH_ASSOC); - - } catch (Exception $e) { - $answer['message'] = 'Search failed.'; - http_response_code(500); - } + $keyword = trim($data['keyword'] ?? ''); + $um = new UserManager($pdo1, $company_id, $user_id); + $answer['success'] = 1; + $answer['result'] = $um->searchUsers($keyword); exit(json_encode($answer)); -?> \ No newline at end of file +?> diff --git a/app/setting/api/engine/switch_branch.php b/app/setting/api/engine/switch_branch.php index ba072c1..ef54c0c 100644 --- a/app/setting/api/engine/switch_branch.php +++ b/app/setting/api/engine/switch_branch.php @@ -4,46 +4,31 @@ * * action: 'read' → return list of companies the user belongs to * action: 'update' → switch to the requested company_id - * - * Both actions verify that the user is actually a member of the target company - * via company_map_user before touching the session. */ session_start(); require '../../../assets/utils/db_auth.php'; +require '../../../assets/utils/classes/UserManager.php'; $action = $data['action'] ?? ''; -// ── READ: return all companies this user belongs to ─────────────────────────── if ($action === 'read') { - - $sth = $pdo1->prepare( - "SELECT cl.company_id, cl.channel_name, cl.company_name, cl.branch, cmu.role - FROM company_map_user cmu - JOIN company_list cl ON cl.company_id = cmu.company_id - WHERE cmu.user_id = :user_id - ORDER BY cl.company_name ASC" - ); - $sth->execute([':user_id' => $user_id]); - $companies = $sth->fetchAll(PDO::FETCH_ASSOC); + $um = new UserManager($pdo1, $company_id, $user_id); $answer['success'] = 1; - $answer['output'] = $companies; - $answer['current'] = (int) $_SESSION['login_company_id']; + $answer['output'] = $um->getCompanyList(); + $answer['current'] = (int)$_SESSION['login_company_id']; exit(json_encode($answer)); } -// ── UPDATE: switch to a different company ───────────────────────────────────── if ($action === 'update') { - $target_company_id = (int)($data['company_id'] ?? 0); if (!$target_company_id) { - http_response_code(400); $answer['message'] = 'Invalid company.'; + http_response_code(400); exit(json_encode($answer)); } - // Verify user actually belongs to the requested company $sth = $pdo1->prepare( "SELECT company_id, role FROM company_map_user WHERE company_id = :company_id AND user_id = :user_id @@ -53,8 +38,8 @@ if ($action === 'update') { $target_map = $sth->fetch(PDO::FETCH_ASSOC); if (!$target_map) { - http_response_code(403); $answer['message'] = 'You do not have access to this company.'; + http_response_code(403); exit(json_encode($answer)); } @@ -66,6 +51,7 @@ if ($action === 'update') { exit(json_encode($answer)); } -http_response_code(400); $answer['message'] = 'Invalid action.'; +http_response_code(400); exit(json_encode($answer)); +?>