Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Consolidate dbproxy and user models #461

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions src/backend/app/Http/Controllers/AgentWebController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use App\Http\Requests\CreateAgentRequest;
use App\Http\Resources\ApiResource;
use App\Models\CompanyDatabase;
use App\Services\AddressesService;
use App\Services\AgentService;
use App\Services\CompanyDatabaseService;
Expand Down Expand Up @@ -50,13 +49,6 @@ public function store(CreateAgentRequest $request): ApiResource {
'connection' => ' ', // TODO: solve this. //auth('api')->user()->company->database->database_name
];
$companyId = auth('api')->payload()->get('companyId');
$companyDatabase = CompanyDatabase::query()->where('company_id', $companyId)->firstOrFail();
$databaseProxyData = [
'email' => $request['email'],
'fk_company_id' => $companyId,
'fk_company_database_id' => $companyDatabase->getId(),
];
$this->databaseProxyService->create($databaseProxyData);

return ApiResource::make($this->agentService->create(
$agentData,
Expand Down
4 changes: 1 addition & 3 deletions src/backend/app/Http/Controllers/Reports.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use App\Models\City;
use App\Models\ConnectionGroup;
use App\Models\ConnectionType;
use App\Models\DatabaseProxy;
use App\Models\Meter\MeterParameter;
use App\Models\PaymentHistory;
use App\Models\Report;
Expand Down Expand Up @@ -580,8 +579,7 @@ static function ($q) {
$writer = new Xlsx($this->spreadsheet);
$dirPath = storage_path('./'.$reportType);
$user = User::query()->first();
$databaseProxy = app()->make(DatabaseProxy::class);
$companyId = $databaseProxy->findByEmail($user->email)->getCompanyId();
$companyId = $user->getCompanyId();

if (!file_exists($dirPath) && !mkdir($dirPath, 0774, true) && !is_dir($dirPath)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dirPath));
Expand Down
12 changes: 2 additions & 10 deletions src/backend/app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,24 @@
use App\Http\Resources\ApiResource;
use App\Models\User;
use App\Services\CompanyDatabaseService;
use App\Services\DatabaseProxyService;
use App\Services\UserService;
use Illuminate\Http\Request;

class UserController extends Controller {
public function __construct(
private UserService $userService,
private DatabaseProxyService $databaseProxyService,
private CompanyDatabaseService $companyDatabaseService,
) {}

public function index(Request $request): ApiResource {
$users = $this->userService->list();
$companyId = auth()->user()->company_id;
$users = $this->userService->list($companyId);

return new ApiResource($users);
}

public function store(CreateAdminRequest $request) {
$user = $this->userService->create($request->only(['name', 'password', 'email']));
$companyDatabase = $this->companyDatabaseService->findByCompanyId($user->getCompanyId());
$databaseProxyData = [
'email' => $user->getEmail(),
'fk_company_id' => $user->getCompanyId(),
'fk_company_database_id' => $companyDatabase->getId(),
];
$this->databaseProxyService->create($databaseProxyData);

return ApiResource::make($user->toArray());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ private function handleApiRequest(Request $request, \Closure $next) {

// webclient login
if ($request->path() === 'api/auth/login' || $request->path() === 'api/app/login') {
$databaseProxy = $this->databaseProxyManager->findByEmail($request->input('email'));
$companyId = $databaseProxy->getCompanyId();
$user = $this->databaseProxyManager->findByEmail($request->input('email'));
$companyId = $user->getCompanyId();
} elseif ($this->isAgentApp($request->path()) && Str::contains($request->path(), 'login')) { // agent app login
$databaseProxy = $this->databaseProxyManager->findByEmail($request->input('email'));
$companyId = $databaseProxy->getCompanyId();
$user = $this->databaseProxyManager->findByEmail($request->input('email'));
$companyId = $user->getCompanyId();
} elseif ($this->isAgentApp($request->path())) { // agent app authenticated user requests
$companyId = auth('agent_api')->payload()->get('companyId');
if (!is_numeric($companyId)) {
Expand Down
6 changes: 5 additions & 1 deletion src/backend/app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class User extends Authenticatable implements JWTSubject {
public const COL_COMPANY_ID = 'company_id';

public function __construct(array $attributes = []) {
$this->setConnection('tenant');
// $this->setConnection('tenant');

parent::__construct($attributes);
}
Expand Down Expand Up @@ -118,4 +118,8 @@ public function getEmail(): string {
public function relationTicketUser(): HasOne {
return $this->hasOne(TicketUser::class, TicketUser::COL_USER_ID, User::COL_ID);
}

public function findByEmail(string $email): ?User {
return self::where('email', $email)->first();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace App\Services;

use App\Models\DatabaseProxy;
use App\Models\User;
use Illuminate\Support\Facades\Cache;

Expand Down Expand Up @@ -31,8 +30,8 @@ public function getDataById($id) {

protected function cacheKeyGenerator(): string {
$user = User::query()->first();
$databaseProxy = app()->make(DatabaseProxy::class);
$companyId = $databaseProxy->findByEmail($user->email)->getCompanyId();

$companyId = $user->getCompanyId();

return $this->cacheDataKey.'-'.$companyId;
}
Expand Down
15 changes: 8 additions & 7 deletions src/backend/app/Services/DatabaseProxyService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,28 @@

namespace App\Services;

use App\Models\DatabaseProxy;
use App\Models\User;
use App\Services\Interfaces\IBaseService;
use Illuminate\Database\Eloquent\Collection;

/**
* @implements IBaseService<DatabaseProxy>
*/
class DatabaseProxyService implements IBaseService {
public function __construct(private DatabaseProxy $databaseProxy) {}
public function __construct(private User $user) {}

public function getById($id): DatabaseProxy {
public function getById($id): User {
throw new \Exception('Method getById() not yet implemented.');

return new DatabaseProxy();
return new User();
}

public function create(array $databaseProxyData): DatabaseProxy {
return $this->databaseProxy->newQuery()->create($databaseProxyData);
public function create(array $userData): User {
// return $this->user->newQuery()->create($userData);
throw new \Exception('Method create() should not be used directly ');
}

public function update($model, array $data): DatabaseProxy {
public function update($model, array $data): User {
throw new \Exception('Method update() not yet implemented.');
}

Expand Down
3 changes: 2 additions & 1 deletion src/backend/app/Services/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,11 @@ public function resetPassword(string $email): ?User {
return $user;
}

public function list(): LengthAwarePaginator {
public function list(int $companyId): LengthAwarePaginator {
return $this->buildQuery()
->select('id', 'name', 'email')
->with(['addressDetails'])
->where('company_id', $companyId) // filter user list with company_id
->paginate();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@
namespace MPM\DatabaseProxy;

use App\Models\CompanyDatabase;
use App\Models\DatabaseProxy;
use App\Models\User;
use App\Utils\DemoCompany;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\Builder;

class DatabaseProxyManagerService {
public function __construct(
private DatabaseProxy $databaseProxy,
private User $user,
private DatabaseManager $databaseManager,
private CompanyDatabase $companyDatabase,
) {}

public function findByEmail(string $email): DatabaseProxy {
return $this->databaseProxy->findByEmail($email);
public function findByEmail(string $email): User {
return $this->user->findByEmail($email);
}

public function runForCompany(int $companyId, callable $callable) {
Expand Down
22 changes: 11 additions & 11 deletions src/backend/app/modules/User/UserListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
use App\Helpers\MailHelperInterface;
use App\Services\CompanyDatabaseService;
use App\Services\CompanyService;
use App\Services\DatabaseProxyService;
// use App\Services\DatabaseProxyService;
use Inensus\Ticket\Services\TicketUserService;
use MPM\User\Events\UserCreatedEvent;

class UserListener {
public function __construct(
private DatabaseProxyService $databaseProxyService,
// private DatabaseProxyService $databaseProxyService,
private CompanyDatabaseService $companyDatabaseService,
private TicketUserService $ticketUserService,
private CompanyService $companyService,
Expand All @@ -27,17 +27,17 @@ public function handle($event): void {
}

public function handleUserCreatedEvent(UserCreatedEvent $event): void {
if ($event->shouldSyncUser) {
$companyDatabase = $this->companyDatabaseService->findByCompanyId($event->user->getCompanyId());
// if ($event->shouldSyncUser) {
// $companyDatabase = $this->companyDatabaseService->findByCompanyId($event->user->getCompanyId());

$databaseProxyData = [
'email' => $event->user->getEmail(),
'fk_company_id' => $event->user->getCompanyId(),
'fk_company_database_id' => $companyDatabase->getId(),
];
// $databaseProxyData = [
// 'email' => $event->user->getEmail(),
// 'fk_company_id' => $event->user->getCompanyId(),
// 'fk_company_database_id' => $companyDatabase->getId(),
// ];

$this->databaseProxyService->create($databaseProxyData);
}
// $this->databaseProxyService->create($databaseProxyData);
// }

$company = $this->companyService->getById($event->user->getCompanyId());
$this->ticketUserService->findOrCreateByUser($event->user);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('company_id')->unsigned();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('users');
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::connection('tenant')->dropIfExists('users');
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::connection('tenant')->create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('company_id')->unsigned();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use App\Models\User;
use App\Services\CompanyDatabaseService;
use App\Services\CompanyService;
use App\Services\DatabaseProxyService;
use App\Services\UserService;
use Carbon\Carbon;
use Illuminate\Console\Command;
Expand All @@ -21,7 +20,6 @@ public function __construct(
private SwiftaAuthentication $authentication,
private CompanyService $companyService,
private CompanyDatabaseService $companyDatabaseService,
private DatabaseProxyService $databaseProxyService,
) {
parent::__construct();
}
Expand Down Expand Up @@ -72,13 +70,6 @@ private function generateAuthenticationToken() {
'email' => $company->getName().'-swifta-user-'.Carbon::now()->timestamp,
'company_id' => $companyId,
]);
$companyDatabase = $this->companyDatabaseService->getById($companyId);
$databaseProxyData = [
'email' => $user->getEmail(),
'fk_company_id' => $user->getCompanyId(),
'fk_company_database_id' => $companyDatabase->getId(),
];
$this->databaseProxyService->create($databaseProxyData);
$customClaims = ['usr' => 'swifta-token', 'exp' => Carbon::now()->addYears(3)->timestamp];
$token = JWTAuth::customClaims($customClaims)->fromUser($user);
$payload = JWTAuth::setToken($token)->getPayload();
Expand Down
Loading