File: /var/www/ipsremont-demo/app/User.php
<?php
namespace App;
use App\Helpers\UserHelper;
use App\Models\Branch;
use App\Models\Permission;
use App\Models\Role;
use App\Models\Service\Service;
use App\Services\Branch\BranchService;
use App\Services\Log\LogService;
use App\Services\Service\ServiceService;
use App\Traits\HasRolesAndPermissions;
use App\Traits\Sortable;
use Illuminate\Database\Eloquent\Concerns\HasEvents;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
/**
* @property int $id
* @property string $name
* @property string $email
* @property string $additional_email
* @property string $email_verified_at
* @property string $password
* @property int $access_system
* @property string $phone
* @property string $additional_phone
* @property string $lang
* @property string $dt_last_auth
* @property string $remember_token
* @property string $deleted_at
* @property string $created_at
* @property string $updated_at
* @property int $service_id
* @property int $multiservice
*
* @property Service $service
* @property Service[] $services
* @property Branch[] $branches
* @property Branch $branch
*/
class User extends Authenticatable
{
use Notifiable, HasRolesAndPermissions, SoftDeletes, Sortable, HasEvents;
protected $table = 'users';
/** @var int */
const ACTIVE_STATUS = 1;
/** @var int */
const INACTIVE_STATUS = 0;
public $open_password = '';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'access_system',
'lang',
'phone',
'additional_phone',
'service_id',
'additional_email',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public static function statuses()
{
return [
self::INACTIVE_STATUS => 'users.statuses.inactive',
self::ACTIVE_STATUS => 'users.statuses.active',
];
}
protected static $labels = [
'name' => 'admins.users.name',
'email' => 'admins.users.email',
'access_system' => 'admins.users.accessSystem',
'role' => 'admins.users.role',
'phone' => 'admins.users.phone',
'additional_phone' => 'admins.users.additionalPhone',
'branch_ids' => 'admins.users.branches',
'service_ids' => 'admins.users.services',
'status' => 'admins.users.status',
'role_id' => 'admins.users.role',
'new_password' => 'admins.users.new_password',
];
public static function columns()
{
return [
"fields" => [
[
"displayName" => 'admins.users.name',
"field" => "name",
"sort" => true,
"sortType" => 'asc',
],
[
"displayName" => 'admins.users.phone',
"field" => "phone",
"sort" => true,
"sortType" => 'asc',
],
[
"displayName" => 'admins.users.branches',
"field" => "branch_id",
"sort" => true,
"sortType" => 'asc',
],
[
"displayName" => 'admins.users.role',
"field" => "role",
"sort" => false,
"sortType" => 'asc',
],
[
"displayName" => 'admins.users.accessSystemGrid',
"field" => "access_system",
"sort" => true,
"sortType" => 'asc',
],
[
"displayName" => 'admins.users.createdAt',
"field" => "created_at",
"sort" => true,
"sortType" => 'asc',
],
[
"displayName" => '',
"field" => 'action',
"sort" => false,
],
],
"sortDefault" => [
[
"field" => 'access_system',
"sort" => 'desc',
],
[
"field" => 'name',
"sort" => 'asc',
],
],
];
}
public function getLabel($field)
{
return static::$labels[$field] ?? '';
}
public function import()
{
return [
'имя контактного лица' => 'name',
'логин для доступа (емайл)' => 'email',
'емайл' => 'additional_email',
'телефон' => 'phone',
'дополнительный телефон' => 'additional_phone',
];
}
/**
* @return mixed
*/
public function roles()
{
return $this->belongsToMany(Role::class, 'users_roles');
}
public function getBranchIds(): array
{
return $this->branches()->pluck('branch_id')->toArray();
}
public function getFirstBranchId(): ?int
{
$branchIds = $this->branches()->pluck('branch_id')->toArray();
return array_shift($branchIds);
}
public function getAllServices()
{
if ($this->isService() && $this->isMultiService()) {
return ServiceService::getAvailable()
->where('user_id', $this->id)
->orderBy('id', 'desc')->get();
}
return false;
}
public function isMultiService()
{
return $this->multiservice;
}
/**
* Scope a query to only include active users
*
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCanLogin($query)
{
return $query->where('access_system', true);
}
/**
* Get users with special role type
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $roleType admin/manager/service
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeGetByRoleType($query, $roleType)
{
return $query->whereHas('roles', function ($q) use ($roleType) {
$q->where('type', $roleType);
});
}
public function isService(): bool
{
return $this->hasRoleType(Role::service);
}
public function isManager(): bool
{
return $this->hasRoleType(Role::manager);
}
public function isAdmin(): bool
{
return $this->hasRoleType(Role::admin);
}
public function myRoleName()
{
return $this->roles()->first()->name;
}
/**
* Get users with special role
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $roleId Role id
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function scopeGetByRoleId($query, $roleId)
{
return $query->whereHas('roles', function ($q) use ($roleId) {
$q->where('role_id', $roleId);
});
}
/**
* Scope a query to only include My items
*
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeMy($query)
{
$user = UserHelper::getUser();
if (can(Permission::branchesAll)) {
return;
}
$query->whereHas('branches', function ($q) use ($user) {
$q->whereIn('branch_id', $user->getBranchIds());
});
}
public function getName()
{
return $this->name;
}
/**
* Активная компания пользователя, для которой можно что-то создавать
*
* @return integer
*/
public function getRealServiceId()
{
return $this->service_id;
}
/**
* Компания, которая выбрана сейчас в интерфейсе, может быть активная или архивная куфвщтдн
*
* @return integer
*/
public function getCurrentServiceId()
{
$id = 0;
if (request()->session()->has('current_service_id')) {
$id = (int) request()->session()->get('current_service_id');
}
return ($id > 0) ? $id : $this->service_id;
}
public static function getAdmins()
{
return self::whereHas('roles', function ($q) {
$q->where('type', 'admin');
})->where('access_system', 1)->get();
}
public function getBranchWarehousePartsId()
{
return $this->branches->pluck('external_id');
}
public function getServiceWarehousePartsId()
{
if ($this->isService()) {
return $this->service->external_warehouse_id;
}
return '';
}
public function getService()
{
if ($this->isService()) {
return ServiceService::getById($this->getCurrentServiceId());
}
return '';
}
public function syncBranches($branchIds = []): void
{
$currentBranches = $this->branches()->get()->pluck('id')->toArray();
$removeFromBranches = array_diff($currentBranches, $branchIds);
if (!empty($removeFromBranches)) {
foreach ($removeFromBranches as $branchId) {
$branch = BranchService::getById($branchId);
$managers = $branch->managers()->get()->pluck('id')->toArray();
$managers = array_diff($managers, [$this->id]);
$branch->managers()->sync($managers);
LogService::updatedRelations($branch, 'managers', $managers);
}
}
if (!empty($branchIds)) {
foreach ($branchIds as $branchId) {
if (!in_array($branchId, $currentBranches)) {
$branch = BranchService::getById($branchId);
$managers = $branch->managers()->get()->pluck('id')->toArray();
$managers[] = $this->id;
$branch->managers()->sync($managers);
LogService::updatedRelations($branch, 'managers', $managers);
}
}
}
}
// MARK: - Relations
public function service(): BelongsTo
{
return $this->belongsTo(Service::class);
}
public function services(): BelongsToMany
{
return $this->belongsToMany(Service::class, 'managers_services')->withPivot('user_id', 'service_id');
}
public function branches(): BelongsToMany
{
return $this->belongsToMany(Branch::class, 'managers_branches');
}
public function branch(): BelongsTo
{
return $this->belongsTo(Branch::class);
}
}