Skip to content

Commit

Permalink
fix organization listing endpoint, fix assign user with role
Browse files Browse the repository at this point in the history
  • Loading branch information
roncodes committed Oct 8, 2024
1 parent 4f7b679 commit b359dd8
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 23 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fleetbase/core-api",
"version": "1.5.9",
"version": "1.5.10",
"description": "Core Framework and Resources for Fleetbase API",
"keywords": [
"fleetbase",
Expand Down
20 changes: 12 additions & 8 deletions src/Http/Controllers/Internal/v1/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -516,11 +516,12 @@ public function getUserOrganizations(Request $request)
$user = $request->user();
$companies = Company::whereHas(
'users',
function ($q) use ($user) {
$q->where('users.uuid', $user->uuid);
function ($query) use ($user) {
$query->where('users.uuid', $user->uuid);
$query->whereNull('company_users.deleted_at');
}
)
->whereHas('owner.companyUser')
->whereHas('owner')
->with(['owner', 'owner.companyUser'])
->get();

Expand Down Expand Up @@ -580,8 +581,7 @@ public function joinOrganization(JoinOrganizationRequest $request)
return response()->error('User is already a member of this organization.');
}

$company->addUser($user);
$user->assignCompany($company);
$company->assignUser($user);
Auth::setSession($user);

return response()->json(['status' => 'ok']);
Expand All @@ -595,10 +595,14 @@ public function joinOrganization(JoinOrganizationRequest $request)
public function createOrganization(Request $request)
{
$user = $request->user();
$company = Company::create(array_merge($request->only(['name', 'description', 'phone', 'email', 'currency', 'country', 'timezone']), ['owner_uuid' => $user->uuid]));
$company->addUser($user);

$user->assignCompany($company);
try {
$company = Company::create(array_merge($request->only(['name', 'description', 'phone', 'email', 'currency', 'country', 'timezone']), ['owner_uuid' => $user->uuid]));
$company->assignUser($user, 'Administrator');
} catch (\Throwable $e) {
return response()->error($e->getMessage());
}

Auth::setSession($user);

return new Organization($company);
Expand Down
81 changes: 68 additions & 13 deletions src/Models/Company.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,14 @@ public function owner(): BelongsTo

public function users(): BelongsToMany
{
return $this->belongsToMany(User::class, 'company_users');
return $this->belongsToMany(
User::class,
'company_users',
'company_uuid',
'user_uuid',
'uuid',
'uuid'
);
}

public function companyUsers(): HasManyThrough
Expand Down Expand Up @@ -317,11 +324,14 @@ public function routeNotificationForTwilio()
}

/**
* Uses the current session to get the current company model instance.
* Retrieves the current session's Company instance.
*
* @return Company|null
* This static method fetches the 'company' identifier from the session and attempts to retrieve
* the corresponding Company model. If no company identifier is found in the session, it returns null.
*
* @return Company|null the current session's Company instance or null if not found
*/
public static function currentSession()
public static function currentSession(): ?Company
{
$id = session('company');

Expand All @@ -333,21 +343,66 @@ public static function currentSession()
}

/**
* Adds a new user to this company.
* Adds a user to the company with an optional role and status.
*
* @return void
* This method associates a given User with the company by creating or retrieving a CompanyUser record.
* If a role name is provided, it assigns that role to the CompanyUser. If no role name is specified,
* it defaults to the user's current role. The status can also be specified, defaulting to 'active'.
*
* @param User $user the user to be added to the company
* @param string|null $roleName The name of the role to assign to the user. Defaults to the user's current role if null.
* @param string $status The status of the user within the company. Defaults to 'active'.
*
* @return CompanyUser the CompanyUser instance representing the association between the user and the company
*/
public function addUser(?User $user)
public function addUser(User $user, ?string $roleName = null, string $status = 'active'): CompanyUser
{
return CompanyUser::create([
'company_uuid' => $this->uuid,
'user_uuid' => $user->uuid,
'status' => 'active',
]);
// Get the currentuser role
$roleName = $roleName ?? $user->getRoleName();

$companyUser = CompanyUser::firstOrCreate(
[
'company_uuid' => $this->uuid,
'user_uuid' => $user->uuid,
],
[
'company_uuid' => $this->uuid,
'user_uuid' => $user->uuid,
'status' => $user->status ?? $status,
]
);

// Assign the role to the new user
$companyUser->assignSingleRole($roleName);

return $companyUser;
}

/**
* Get the latest last login of any user in the company.
* Assigns a user to the company and sets their role.
*
* This method adds a user to the company using the addUser method and then associates the company with the user.
* It optionally allows specifying a role name for the user within the company.
*
* @param User $user the user to assign to the company
* @param string|null $roleName The name of the role to assign to the user. If null, defaults to the user's current role.
*
* @return CompanyUser the CompanyUser instance representing the association between the user and the company
*/
public function assignUser(User $user, ?string $roleName = null): CompanyUser
{
$companyUser = $this->addUser($user, $roleName);
$user->assignCompany($this);

return $companyUser;
}

/**
* Retrieves the timestamp of the most recent user login in the company.
*
* This method queries the company's associated users and returns the latest 'last_login' timestamp.
*
* @return string|null the timestamp of the last user login in 'Y-m-d H:i:s' format, or null if no logins are recorded
*/
public function getLastUserLogin()
{
Expand Down
16 changes: 16 additions & 0 deletions src/Models/Setting.php
Original file line number Diff line number Diff line change
Expand Up @@ -463,4 +463,20 @@ public static function clearSystemCache(): void
{
Utils::clearCacheByPattern('system_setting*');
}

public function getCompany(): ?Company
{
$keySegments = explode('.', $this->key);
if (count($keySegments) >= 3 && $keySegments[0] === 'company' && Str::isUuid($keySegments[1])) {
return Company::where('uuid', $keySegments[1])->first();
}
}

public function getUser(): ?User
{
$keySegments = explode('.', $this->key);
if (count($keySegments) >= 3 && $keySegments[0] === 'user' && Str::isUuid($keySegments[1])) {
return User::where('uuid', $keySegments[1])->first();
}
}
}
33 changes: 32 additions & 1 deletion src/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ public function assignCompany(Company $company): self

// Create company user record
if (CompanyUser::where(['company_uuid' => $company->uuid, 'user_uuid' => $this->uuid])->doesntExist()) {
$companyUser = CompanyUser::create(['company_uuid' => $company->uuid, 'user_uuid' => $this->uuid, 'status' => $this->status ?? 'pending']);
$companyUser = $company->addUser($this);
$this->setRelation('companyUser', $companyUser);
}

Expand Down Expand Up @@ -1235,4 +1235,35 @@ public function assignSingleRole($role): self

throw new \Exception('Company User relationship not found!');
}

/**
* Retrieves the first Role associated with the user.
*
* This method fetches the first Role linked to the user via the roles relationship.
* If the user has no roles assigned, it returns null.
*
* @return Role|null the first Role associated with the user, or null if no roles are found
*/
public function getRole(): ?Role
{
return $this->roles()->first();
}

/**
* Retrieves the name of the first Role associated with the user.
*
* This method obtains the first Role linked to the user and returns its name.
* If the user has no roles assigned, it returns null.
*
* @return string|null the name of the first Role associated with the user, or null if no roles are found
*/
public function getRoleName(): ?string
{
$role = $this->getRole();
if ($role) {
return $role->name;
}

return null;
}
}

0 comments on commit b359dd8

Please sign in to comment.