Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Relesys Users Laravel Package

getsno/relesys-users

Laravel 10 / PHP 8.1 client for the Relesys User Management API. Authenticate via client ID/secret and access endpoints for users, departments, user groups, custom fields, and communication, with support for filtering, sorting, and pagination.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require getsno/relesys-users
    
  2. Configure .env:
    RELESYS_CLIENT_ID=your_client_id
    RELESYS_CLIENT_SECRET=your_client_secret
    
  3. First API Call:
    use Getsno\Relesys\Facades\Relesys;
    
    // Fetch a single user
    $user = Relesys::users()->getUser('user-uuid-here');
    

First Use Case: User Creation

use Getsno\Relesys\Facades\Relesys;
use Getsno\Relesys\Api\UserManagement\Entities\User;

$user = User::fromArray([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'primaryDepartmentId' => 'dept-uuid-here',
]);

$createdUser = Relesys::users()->createUser($user);

Where to Look First

  • Facade: Getsno\Relesys\Facades\Relesys (primary entry point)
  • Entities: Getsno\Relesys\Api\UserManagement\Entities (e.g., User, UserPatch)
  • Enums: Getsno\Relesys\Api\UserManagement\Enums (e.g., UserStatus)
  • Tests: /tests directory for real-world usage patterns

Implementation Patterns

Core Workflow: CRUD Operations

// Create
$user = Relesys::users()->createUser($userData);

// Read (single)
$user = Relesys::users()->getUser('user-uuid');

// Read (batch with pagination)
$users = Relesys::users()->getUsers(
    queryParams: (new ApiQueryParams)->limit(10)->page(1),
    include: ['customFields']
);

// Update (partial)
$userPatch = (new UserPatch())
    ->title('Updated Title')
    ->status(UserStatus::Disabled);
Relesys::users()->updateUser('user-uuid', $userPatch);

// Delete
Relesys::users()->deleteUser('user-uuid');

Common Patterns

  1. Query Parameters:

    $query = (new ApiQueryParams)
        ->addFilter('status', UserStatus::Activated->value)
        ->sortBy('name', 'asc')
        ->limit(50);
    
  2. Nested Relationships:

    // Fetch user with departments and groups
    $user = Relesys::users()->getUser('user-uuid', include: ['departments', 'userGroups']);
    
  3. Bulk Operations:

    // Update multiple users (via API's bulk endpoint)
    $users = Relesys::users()->updateUsers($userPatches);
    
  4. Communication Endpoints:

    // Send message template
    $message = Relesys::communication()->sendMessageTemplate(
        'template-uuid',
        ['user-uuid-1', 'user-uuid-2']
    );
    

Integration Tips

  • Event Listeners: Use Laravel’s event system to trigger actions on user updates:
    Relesys::users()->updateUser($userId, $patch)
        ->then(fn() => event(new UserUpdated($userId)));
    
  • Service Layer: Wrap API calls in a service class to abstract complexity:
    class UserService {
        public function createUserInDepartment(array $data, string $departmentId) {
            $user = User::fromArray($data + ['primaryDepartmentId' => $departmentId]);
            return Relesys::users()->createUser($user);
        }
    }
    
  • Caching: Cache frequent queries (e.g., user groups) with Laravel’s cache:
    $groups = cache()->remember("relesys:user-groups", now()->addHours(1), fn() =>
        Relesys::userGroups()->getUserGroups()
    );
    

Gotchas and Tips

Common Pitfalls

  1. Empty Arrays in Custom Fields:

    • Issue: The API rejects empty arrays for customFields. Use null instead.
    • Fix:
      $user = User::fromArray([
          'customFields' => null, // Instead of []
      ]);
      
  2. Phone Number Format:

    • Issue: Phone numbers must include countryCode and number as separate fields.
    • Fix:
      $phone = [
          'countryCode' => 44, // UK
          'number' => '7123456789',
      ];
      
  3. Pagination Handling:

    • Issue: Always check hasMore in batch responses for incomplete results.
    • Fix:
      $users = Relesys::users()->getUsers($queryParams);
      while ($users->hasMore) {
          $users = Relesys::users()->getUsers($queryParams->page($users->page + 1));
      }
      
  4. UUID Validation:

    • Issue: The API expects valid UUIDs (e.g., 123e4567-e89b-12d3-a456-426614174000).
    • Fix: Validate with Illuminate\Support\Str::isUuid($id).
  5. Rate Limiting:

    • Issue: Relesys may throttle requests. Implement exponential backoff:
    • Fix:
      use Illuminate\Support\Facades\Http;
      
      Http::withOptions(['timeout' => 30])->retry(3, 100);
      

Debugging Tips

  1. Enable API Logging:
    Relesys::setDebug(true); // Logs all API requests/responses
    
  2. Mock API Calls in Tests:
    • Use Laravel’s HTTP mocking:
      Http::fake([
          'api.relesysapp.net/*' => Http::response([], 200),
      ]);
      
  3. Check HTTP Status Codes:
    • The package throws RelesysHttpClientException for non-2xx responses. Catch and inspect:
      try {
          Relesys::users()->getUser('invalid-uuid');
      } catch (RelesysHttpClientException $e) {
          logger()->error('Relesys API Error:', [
              'status' => $e->getStatusCode(),
              'response' => $e->failedRequest->body(),
          ]);
      }
      

Configuration Quirks

  1. Environment Variables:

    • Ensure RELESYS_CLIENT_ID and RELESYS_CLIENT_SECRET are set in .env.
    • For local development, use .env.local to avoid committing secrets.
  2. API Scope Requirement:

    • The relesys.api.users scope is mandatory for user management. Verify with Relesys support if you encounter 403 errors.
  3. Timezone Handling:

    • Dates in the API are UTC. Convert to user timezone in your application:
      $user->birthDate->setTimezone('Europe/Oslo');
      

Extension Points

  1. Custom Entities:

    • Extend base entities (e.g., User) to add application-specific fields:
      class AppUser extends User {
          public function getFullName(): string {
              return "{$this->title} {$this->name}";
          }
      }
      
  2. Middleware:

    • Add middleware to the Relesys HTTP client:
      Relesys::getHttpClient()->middleware(function ($request) {
          $request->header('X-Custom-Header', 'value');
      });
      
  3. Event Dispatching:

    • Subscribe to Relesys events (if the package emits them) or wrap API calls to dispatch custom events:
      Relesys::users()->getUser($id)->then(fn() => event(new UserFetched($id)));
      
  4. Testing:

    • Use the package’s test utilities to mock API responses:
      // In tests/Feature/UserManagementTest.php
      public function test_user_creation() {
          Http::fake([
              'api.relesysapp.net/users' => Http::response(['id' => 'test-uuid'], 201),
          ]);
          // Test logic...
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui