]> _ Git - cubedesigners_userdatabase.git/commitdiff
wip #3753 @1
authorVincent Vanwaelscappel <vincent@cubedesigners.com>
Tue, 15 Dec 2020 17:24:29 +0000 (18:24 +0100)
committerVincent Vanwaelscappel <vincent@cubedesigners.com>
Tue, 15 Dec 2020 17:24:29 +0000 (18:24 +0100)
13 files changed:
composer.json
src/Address.php [deleted file]
src/Company.php [deleted file]
src/Operations/LoginasOperation.php [deleted file]
src/Permissions.php [deleted file]
src/User.php [deleted file]
src/app/CubedesignersUserDatabaseServiceProvider.php [new file with mode: 0644]
src/app/Fields/Users.php [new file with mode: 0644]
src/app/Models/Company.php [new file with mode: 0644]
src/app/Models/User.php [new file with mode: 0644]
src/app/Operations/LoginasOperation.php [new file with mode: 0644]
src/app/Permissions.php [new file with mode: 0644]
src/app/SubForms/Address.php [new file with mode: 0644]

index 76a219fb22ae3e0201b3aebe1c954f24318d59f1..28477598609d531fee4d15841e37dc08a6c18e07 100644 (file)
@@ -13,7 +13,7 @@
   ],
   "autoload": {
     "psr-4": {
-      "Cubedesigners\\UserDatabase\\": "src"
+      "Cubedesigners\\UserDatabase\\": "src/app"
     }
   },
   "authors": [
diff --git a/src/Address.php b/src/Address.php
deleted file mode 100644 (file)
index 7e12142..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-<?php
-
-
-namespace Cubedesigners\UserDatabase;
-
-use Cubist\Backpack\Magic\SubForm;
-
-class Address extends SubForm
-{
-    public function init()
-    {
-        parent::init();
-        $this->addField(['name' => 'address',
-            'label' => __('Adresse'),
-            'type' => 'Textarea']);
-
-        $this->addField(['name' => 'postcode',
-            'label' => __('Code postal'),
-            'type' => 'Postcode']);
-
-        $this->addField(['name' => 'city',
-            'label' => __('Ville'),
-            'type' => 'Text']);
-
-        $this->addField(['name' => 'country',
-            'label' => __('Pays'),
-            'type' => 'Country']);
-    }
-}
diff --git a/src/Company.php b/src/Company.php
deleted file mode 100644 (file)
index bbddd0b..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-<?php
-
-namespace Cubedesigners\UserDatabase;
-
-use Cubist\Backpack\Magic\Models\CubistMagicAbstractModel;
-use Illuminate\Database\Eloquent\Builder;
-
-class Company extends CubistMagicAbstractModel
-{
-    protected $connection = 'extranet_users';
-    protected $table = 'company';
-    protected $_options = ['name' => 'company',
-        'singular' => 'entreprise',
-        'plural' => 'entreprises'];
-
-   protected $_enableBulk=false;
-
-    public function setFields()
-    {
-        parent::setFields();
-
-        $this->addField(['name' => 'name',
-            'label' => __('Nom de l\'entreprise'),
-            'type' => 'Text',
-            'column' => true,
-            'tab' => __('Informations')]);
-
-        $this->addField(['name' => 'address',
-            'type' => 'BunchOfFields',
-            'bunch' => Address::class,
-            'label' => __('Adresse'),
-            'tab' => __('Adresses')]);
-
-        $this->addField(['name' => 'billing_address',
-            'type' => 'BunchOfFields',
-            'bunch' => Address::class,
-            'label' => __('Adresse de facturation'),
-            'tab' => __('Adresses')]);
-
-        $this->addField(['name' => 'vat_number',
-            'type' => 'VATNumber',
-            'label' => __('Numéro de TVA'),
-            'tab' => __('Informations')]);
-
-        $this->addField(['name' => 'type',
-                'type' => 'SelectFromArray',
-                'label' => __('Type'),
-                'options' => [
-                    0 => __('Non défini'),
-                    1 => __('TPE'),
-                    2 => __('Startup'),
-                    3 => __('PME'),
-                    4 => __('Agence'),
-                    5 => __('Grande entreprise'),
-                    6 => __('Gouvernement / Institution publique')
-                ],
-                'tab' => __('Informations')
-            ]
-        );
-
-        $this->addField(['name' => 'admin',
-            'type' => 'SelectFromModel',
-            'optionsmodel' => User::class,
-            'attribute' => 'nameWithCompany',
-            'label' => __('Administrateur'),
-            'tab' => __('Informations')]);
-
-        $this->addField(['name' => 'website',
-            'type' => 'URL',
-            'label' => __('Site web'),
-            'tab' => __('Informations')]);
-
-        $this->addField(['name' => 'e1_ws_signatures',
-            'type' => 'Hidden']);
-
-        $this->addField(['name' => 'e1_ws_grade',
-            'type' => 'Hidden']);
-    }
-
-    public function isOwner($user)
-    {
-        if (null === $user) {
-            return false;
-        }
-        /** @var $user User */
-        return in_array($this->id, $user->getManagedCompanies());
-    }
-
-    public static function addOwnerClause(Builder $builder)
-    {
-        $bu = backpack_user();
-        if (null === $bu) {
-            $builder->where('id', '<', '0');
-            return;
-        }
-        if ($bu->hasPermissionTo('company:admin')) {
-            return;
-        }
-        $builder->whereIn('id', Permissions::getManagedCompanies($bu->id));
-    }
-
-}
diff --git a/src/Operations/LoginasOperation.php b/src/Operations/LoginasOperation.php
deleted file mode 100644 (file)
index 0983cef..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-<?php
-
-namespace Cubedesigners\UserDatabase\Operations;
-
-use Cubedesigners\UserDatabase\User;
-use Illuminate\Support\Facades\Route;
-
-trait LoginasOperation
-{
-    protected function setupLoginasRoutes($segment, $routeName, $controller)
-    {
-        Route::match(['get'], $segment . '/{id}/loginas', $controller . '@loginas');
-    }
-
-    protected function setupLoginasDefaults()
-    {
-        $this->crud->addButtonFromView('line', 'loginas', 'user.loginas', 'end');
-    }
-
-    protected function loginas($id)
-    {
-        $user = User::find($id);
-        backpack_auth()->login($user);
-        return redirect('dashboard');
-    }
-
-    public function canLoginas($user)
-    {
-        return $this->isOwner($user);
-    }
-}
diff --git a/src/Permissions.php b/src/Permissions.php
deleted file mode 100644 (file)
index 37348cd..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-<?php
-
-namespace Cubedesigners\UserDatabase;
-
-class Permissions
-{
-    protected static $_data = false;
-
-    public static function _getData()
-    {
-        if (self::$_data !== false) {
-            return self::$_data;
-        }
-
-        $cacheKey = 'cubedesigners_userdatabase_permissions_data';
-
-        \Barryvdh\Debugbar\Facade::startMeasure($cacheKey, 'Build permissions tree');
-        self::$_data = cache()->remember($cacheKey, 86400, function () {
-
-            set_time_limit(0);
-
-            $data = [
-                'companyUsers' => [],
-                'usersCompany' => [],
-                'companyManagedBy' => [],
-                'managedCompanies' => [],
-                'managedUsers' => [],
-            ];
-
-            foreach (User::withoutGlobalScopes()->get() as $user) {
-                /** @var $user User */
-                if (!isset($data['companyUsers'][$user->company])) {
-                    $data['companyUsers'][$user->company] = [];
-                }
-
-                $data['companyUsers'][$user->company][] = $user->id;
-                $data['usersCompany'][$user->id] = $user->company;
-            }
-
-            foreach (Company::withoutGlobalScopes()->get() as $company) {
-                if (!$company->admin || !isset($data['usersCompany'][$company->admin])) {
-                    continue;
-                }
-                $adminCompany = $data['usersCompany'][$company->admin];
-
-                $data['companyManagedBy'][$company->id] = [$adminCompany, $company->id];
-            }
-
-            for ($i = 0; $i <= 3; $i++) {
-                foreach ($data['companyManagedBy'] as $company => $admins) {
-                    foreach ($admins as $admin) {
-                        if ($admin === $company) {
-                            continue;
-                        }
-                        if (isset($data['companyManagedBy'][$admin])) {
-                            $data['companyManagedBy'][$company] = array_unique(array_merge($data['companyManagedBy'][$admin], $data['companyManagedBy'][$company]), SORT_REGULAR);
-                        }
-                    }
-                }
-            }
-
-            foreach ($data['companyManagedBy'] as $company => $admins) {
-                foreach ($admins as $admin) {
-                    if (!isset($data['managedCompanies'][$admin])) {
-                        $data['managedCompanies'][$admin] = [];
-                    }
-                    $data['managedCompanies'][$admin][] = $company;
-                }
-            }
-
-            foreach ($data['companyUsers'] as $company => $users) {
-                if (!isset($data['managedCompanies'][$company])) {
-                    continue;
-                }
-                $managedUsers = [];
-                foreach ($data['managedCompanies'][$company] as $managedCompany) {
-                    if (!isset($data['companyUsers'][$managedCompany])) {
-                        continue;
-                    }
-                    $managedUsers = array_merge($managedUsers, $data['companyUsers'][$managedCompany]);
-                }
-
-                foreach ($users as $user) {
-                    if (!isset($data['managedUsers'][$user])) {
-                        $data['managedUsers'][$user] = [];
-                    }
-                    $data['managedUsers'][$user] = array_merge($data['managedUsers'][$user], $managedUsers);
-                }
-            }
-
-            return $data;
-        });
-        \Barryvdh\Debugbar\Facade::stopMeasure($cacheKey);
-        return self::$_data;
-    }
-
-    /**
-     * @param integer $company
-     * @return array
-     */
-    public static function getUsersByCompany($company)
-    {
-        $data = self::_getData();
-        if (isset($data['companyUsers'][$company])) {
-            return $data['companyUsers'][$company];
-        }
-        return [];
-    }
-
-    /**
-     * @param integer $user
-     * @return integer|null
-     */
-    public static function getCompanyByUser($user)
-    {
-        $data = self::_getData();
-        if (isset($data['usersCompany'][$user])) {
-            return $data['usersCompany'][$user];
-        }
-        return null;
-    }
-
-
-    /**
-     * @param $user integer
-     * @return array
-     */
-    public static function getManagedUsers($user)
-    {
-        $data = self::_getData();
-        if (isset($data['managedUsers'][$user])) {
-            return $data['managedUsers'][$user];
-        }
-        return [];
-    }
-
-
-    /**
-     * @param $user integer
-     * @return array
-     */
-    public static function getManagedCompanies($user)
-    {
-        $data = self::_getData();
-        if (isset($data['managedCompanies'][$user])) {
-            return $data['managedCompanies'][$user];
-        }
-        return [];
-    }
-}
diff --git a/src/User.php b/src/User.php
deleted file mode 100644 (file)
index 02f27a2..0000000
+++ /dev/null
@@ -1,179 +0,0 @@
-<?php
-
-namespace Cubedesigners\UserDatabase;
-
-use Cubist\Backpack\Magic\Models\CubistMagicAuthenticatable;
-use Illuminate\Database\Eloquent\Builder;
-
-class User extends CubistMagicAuthenticatable
-{
-    protected $connection = 'extranet_users';
-    protected $table = 'user';
-    protected $_options = ['name' => 'users',
-        'singular' => 'utilisateur',
-        'plural' => 'utilisateurs'];
-
-    protected $_operations = ['\Cubedesigners\UserDatabase\Operations\LoginasOperation'];
-
-    protected static $_companyNames = null;
-
-    public function getMorphClass()
-    {
-        return 'App\Models\AuthUser';
-    }
-
-    public function setFields()
-    {
-        parent::setFields();
-
-        $this->addField(['name' => 'firstname',
-            'label' => __('Prénom'),
-            'type' => 'Text',
-            'column' => true,
-            'tab' => __('Contact')]);
-
-        $this->addField(['name' => 'lastname',
-            'label' => __('Nom'),
-            'type' => 'Text',
-            'column' => true,
-            'tab' => __('Contact')]);
-
-        $this->addField(['name' => 'company',
-            'label' => __('Entreprise'),
-            'type' => 'SelectFromModel',
-            'optionsmodel' => Company::class,
-            'tab' => __('Contact'),
-            'column' => true,
-        ]);
-
-        $this->addField(['name' => 'address',
-            'type' => 'BunchOfFields',
-            'bunch' => Address::class,
-            'label' => __('Adresse'),
-            'tab' => __('Contact')]);
-
-        $this->addField(['name' => 'phone',
-            'label' => __('Téléphone'),
-            'type' => 'Phone',
-            'tab' => __('Contact')]);
-
-        $this->addField(['name' => 'mobile',
-            'label' => __('Mobile'),
-            'type' => 'Phone',
-            'tab' => __('Contact')]);
-
-        $this->addField(['name' => 'locale',
-            'label' => __('Langue'),
-            'type' => 'Locale',
-            'tab' => __('Paramètres')]);
-
-        $extranetv1 = ['settings', 'ws_password', 'ws_settings', 'ws_rights', 'ws_domains', 'ws_count', 'login', 'mobile', 'fax', 'notes', 'grade', 'resetpassword'];
-
-        foreach ($extranetv1 as $f) {
-            $this->addField(['name' => 'e1_' . $f,
-                'type' => 'Hidden']);
-        }
-
-    }
-
-    public function getNameAttribute()
-    {
-        return trim($this->firstname . ' ' . $this->lastname);
-    }
-
-    public function getCompanyWithNameAttribute()
-    {
-        $name = $this->name;
-        if ($name === '') {
-            return $this->companyName;
-        }
-        return $this->companyName . ' (' . $this->name . ')';
-    }
-
-    public function getNameWithCompanyAttribute()
-    {
-        $name = $this->name;
-        if ($name === '') {
-            return $this->companyName;
-        }
-        return $name . ' (' . $this->companyName . ')';
-    }
-
-    public function getCompanyWithNameOnTwoLinesAttribute()
-    {
-        $name = $this->name;
-        if ($name === '') {
-            return $this->companyName;
-        }
-        $company = $this->companyName;
-        if (mb_strlen($company) > 30) {
-            $company = '<span title="' . $company . '">' . mb_substr($company, 0, 27) . '...</span>';
-        }
-
-        return $company . '<br><em>' . $name . '</em>';
-    }
-
-    public function getCompanyNameAttribute()
-    {
-        return self::_getCompanyNames($this->company);
-    }
-
-    protected static function _getCompanyNames($id = null)
-    {
-        $cacheKey = '_get_compagny_names';
-        start_measure($cacheKey, 'Get compagny names');
-        self::$_companyNames = cache()->tags(['model_' . Company::class])->remember($cacheKey, 86400, function () {
-            return Company::withoutGlobalScopes()->pluck('name', 'id')->toArray();
-        });
-        stop_measure($cacheKey);
-        if (null === $id) {
-            return self::$_companyNames;
-        }
-
-        return isset(self::$_companyNames[$id]) ? self::$_companyNames[$id] : $id;
-    }
-
-    public function getManagedUsers()
-    {
-        start_measure('_get_managed_users', 'Get managed users');
-        $res = Permissions::getManagedUsers($this->id);
-        stop_measure('_get_managed_users');
-        return $res;
-    }
-
-    public function getManagedCompanies()
-    {
-        start_measure('_get_managed_companies', 'Get managed companies');
-        $res = Permissions::getManagedCompanies($this->id);
-        stop_measure('_get_managed_companies');
-        return $res;
-    }
-
-    public function isOwner($user)
-    {
-        if (null === $this->id) {
-            return true;
-        }
-        if (null === $user) {
-            return false;
-        }
-        /** @var $user self */
-        return in_array($this->id, $user->getManagedUsers());
-    }
-
-
-    public static function addOwnerClause(Builder $builder)
-    {
-        $bu = backpack_user();
-        if (null === $bu) {
-            $builder->where('id', '<', '0');
-            return;
-        }
-        if ($bu->hasPermissionTo('users:admin')) {
-            return;
-        }
-        $builder->whereIn('id', Permissions::getManagedUsers($bu->id));
-    }
-
-
-}
diff --git a/src/app/CubedesignersUserDatabaseServiceProvider.php b/src/app/CubedesignersUserDatabaseServiceProvider.php
new file mode 100644 (file)
index 0000000..f829f54
--- /dev/null
@@ -0,0 +1,66 @@
+<?php
+
+
+namespace Cubedesigners\UserDatabase;
+use Illuminate\Support\ServiceProvider;
+
+class CubedesignersUserDatabaseServiceProvider extends ServiceProvider
+{
+    /**
+     * Indicates if loading of the provider is deferred.
+     *
+     * @var bool
+     */
+    protected $defer = false;
+
+    const NAMESPACE = 'cubedesigners_userdatabase';
+
+    /**
+     * Perform post-registration booting of services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+
+
+        $base = realpath(__DIR__ . "/..");
+        $resourcesDir = $base . '/resources';
+//        $this->loadTranslationsFrom(realpath($resourcesDir . '/lang'), self::NAMESPACE);
+//        foreach (glob($base . '/routes/cubist/backpack/*.php') as $filename) {
+//            $this->loadRoutesFrom($filename);
+//        }
+        //$this->publishes([$resourcesDir . '/config/cubedesigners_userdatabase.php' => config_path('cubedesigners_userdatabase.php')], 'config');
+        $this->loadViewsFrom(realpath($resourcesDir . '/views'), self::NAMESPACE);
+    }
+
+
+    /**
+     * Register any package services.
+     *
+     * @return void
+     */
+    public function register()
+    {
+        $base = realpath(__DIR__ . "/..");
+        $resourcesDir = $base . '/resources';
+
+
+//        $configs = ['app', 'cubist'];
+//
+//        foreach ($configs as $config) {
+//            $this->mergeConfigFrom($resourcesDir . '/config/' . $config . '.php', $config);
+//        }
+
+
+//        $this->commands([
+//            InstallCommand::class,
+//            UpdateCommand::class,
+//            GenerateCommand::class,
+//            MigrateCommand::class,
+//            SearchIndexCommand::class,
+//            LocaleCopy::class,
+//            LocaleSlugReset::class
+//        ]);
+    }
+}
diff --git a/src/app/Fields/Users.php b/src/app/Fields/Users.php
new file mode 100644 (file)
index 0000000..41857f2
--- /dev/null
@@ -0,0 +1,11 @@
+<?php
+
+namespace Cubedesigners\UserDatabase\Fields;
+
+use Cubist\Backpack\Magic\Fields\Field;
+
+class Users extends Field
+{
+    protected $_databaseType = 'none';
+
+}
diff --git a/src/app/Models/Company.php b/src/app/Models/Company.php
new file mode 100644 (file)
index 0000000..24d2dbb
--- /dev/null
@@ -0,0 +1,115 @@
+<?php
+
+namespace Cubedesigners\UserDatabase\Models;
+
+use Cubedesigners\UserDatabase\Fields\Users;
+use Cubedesigners\UserDatabase\SubForms\Address;
+use Cubist\Backpack\Magic\Models\CubistMagicAbstractModel;
+use Illuminate\Database\Eloquent\Builder;
+
+class Company extends CubistMagicAbstractModel
+{
+    protected $connection = 'extranet_users';
+    protected $table = 'company';
+    protected $_options = ['name' => 'company',
+        'singular' => 'entreprise',
+        'plural' => 'entreprises'];
+
+    protected $_enableBulk = false;
+    protected $_enableDeletion = false;
+    protected $_enableClone = false;
+
+    public function setFields()
+    {
+        parent::setFields();
+
+        $this->addField(['name' => 'name',
+            'label' => __('Nom de l\'entreprise'),
+            'type' => 'Text',
+            'column' => true,
+            'tab' => __('Informations')]);
+
+        $this->addField(['name' => 'address',
+            'type' => 'BunchOfFields',
+            'bunch' => Address::class,
+            'label' => __('Adresse'),
+            'tab' => __('Adresses')]);
+
+        $this->addField(['name' => 'billing_address',
+            'type' => 'BunchOfFields',
+            'bunch' => Address::class,
+            'label' => __('Adresse de facturation'),
+            'tab' => __('Adresses')]);
+
+        $this->addField(['name' => 'vat_number',
+            'type' => 'VATNumber',
+            'label' => __('Numéro de TVA'),
+            'tab' => __('Informations')]);
+
+        $this->addField(['name' => 'type',
+                'type' => 'SelectFromArray',
+                'label' => __('Type'),
+                'options' => [
+                    0 => __('Non défini'),
+                    1 => __('TPE'),
+                    2 => __('Startup'),
+                    3 => __('PME'),
+                    4 => __('Agence'),
+                    5 => __('Grande entreprise'),
+                    6 => __('Gouvernement / Institution publique')
+                ],
+                'tab' => __('Informations')
+            ]
+        );
+
+        $this->addField(['name' => 'admin',
+            'type' => 'SelectFromModel',
+            'optionsmodel' => User::class,
+            'attribute' => 'nameWithCompany',
+            'label' => __('Administrateur'),
+            'tab' => __('Informations'),
+        ]);
+
+        $this->addField([
+            'name' => 'users',
+            'type' => Users::class,
+            'label' => '',
+            'column' => true,
+            'tab' => __('Contacts'),
+        ]);
+
+        $this->addField(['name' => 'website',
+            'type' => 'URL',
+            'label' => __('Site web'),
+            'tab' => __('Informations')]);
+
+        $this->addField(['name' => 'e1_ws_signatures',
+            'type' => 'Hidden']);
+
+        $this->addField(['name' => 'e1_ws_grade',
+            'type' => 'Hidden']);
+    }
+
+    public function isOwner($user)
+    {
+        if (null === $user) {
+            return false;
+        }
+        /** @var $user User */
+        return in_array($this->id, $user->getManagedCompanies());
+    }
+
+    public static function addOwnerClause(Builder $builder)
+    {
+        $bu = backpack_user();
+        if (null === $bu) {
+            $builder->where('id', '<', '0');
+            return;
+        }
+        if ($bu->hasPermissionTo('company:admin')) {
+            return;
+        }
+        $builder->whereIn('id', $bu->getManagedCompanies());
+    }
+
+}
diff --git a/src/app/Models/User.php b/src/app/Models/User.php
new file mode 100644 (file)
index 0000000..9f271cb
--- /dev/null
@@ -0,0 +1,195 @@
+<?php
+
+namespace Cubedesigners\UserDatabase\Models;
+
+use Cubedesigners\UserDatabase\Permissions;
+use Cubedesigners\UserDatabase\SubForms\Address;
+use Cubist\Backpack\Magic\Models\CubistMagicAuthenticatable;
+use Illuminate\Database\Eloquent\Builder;
+
+class User extends CubistMagicAuthenticatable
+{
+    protected $connection = 'extranet_users';
+    protected $table = 'user';
+    protected $_options = ['name' => 'users',
+        'singular' => 'utilisateur',
+        'plural' => 'utilisateurs'];
+
+    protected $_operations = ['\Cubedesigners\UserDatabase\Operations\LoginasOperation'];
+
+    protected $_managedUsers = null;
+    protected $_managedCompanies = null;
+
+    protected $_enableBulk = false;
+    protected $_enableDeletion = false;
+    protected $_enableClone = false;
+
+    protected static $_companyNames = null;
+
+    public function getMorphClass()
+    {
+        return 'App\Models\AuthUser';
+    }
+
+    public function setFields()
+    {
+        parent::setFields();
+
+        $this->addField(['name' => 'firstname',
+            'label' => __('Prénom'),
+            'type' => 'Text',
+            'column' => true,
+            'tab' => __('Contact')]);
+
+        $this->addField(['name' => 'lastname',
+            'label' => __('Nom'),
+            'type' => 'Text',
+            'column' => true,
+            'tab' => __('Contact')]);
+
+        $this->addField(['name' => 'company',
+            'label' => __('Entreprise'),
+            'type' => 'SelectFromModel',
+            'optionsmodel' => Company::class,
+            'tab' => __('Contact'),
+            'column' => true,
+            'can' => 'users:admin',
+        ]);
+
+        $this->addField(['name' => 'address',
+            'type' => 'BunchOfFields',
+            'bunch' => Address::class,
+            'label' => __('Adresse'),
+            'tab' => __('Contact')]);
+
+        $this->addField(['name' => 'phone',
+            'label' => __('Téléphone'),
+            'type' => 'Phone',
+            'tab' => __('Contact')]);
+
+        $this->addField(['name' => 'mobile',
+            'label' => __('Mobile'),
+            'type' => 'Phone',
+            'tab' => __('Contact')]);
+
+        $this->addField(['name' => 'locale',
+            'label' => __('Langue'),
+            'type' => 'Locale',
+            'tab' => __('Paramètres')]);
+
+        $extranetv1 = ['settings', 'ws_password', 'ws_settings', 'ws_rights', 'ws_domains', 'ws_count', 'login', 'mobile', 'fax', 'notes', 'grade', 'resetpassword'];
+
+        foreach ($extranetv1 as $f) {
+            $this->addField(['name' => 'e1_' . $f,
+                'type' => 'Hidden']);
+        }
+
+    }
+
+    public function getNameAttribute()
+    {
+        return trim($this->firstname . ' ' . $this->lastname);
+    }
+
+    public function getCompanyWithNameAttribute()
+    {
+        $name = $this->name;
+        if ($name === '') {
+            return $this->companyName;
+        }
+        return $this->companyName . ' (' . $this->name . ')';
+    }
+
+    public function getNameWithCompanyAttribute()
+    {
+        $name = $this->name;
+        if ($name === '') {
+            return $this->companyName;
+        }
+        return $name . ' (' . $this->companyName . ')';
+    }
+
+    public function getCompanyWithNameOnTwoLinesAttribute()
+    {
+        $name = $this->name;
+        if ($name === '') {
+            return $this->companyName;
+        }
+        $company = $this->companyName;
+        if (mb_strlen($company) > 30) {
+            $company = '<span title="' . $company . '">' . mb_substr($company, 0, 27) . '...</span>';
+        }
+
+        return $company . '<br><em>' . $name . '</em>';
+    }
+
+    public function getCompanyNameAttribute()
+    {
+        return self::_getCompanyNames($this->company);
+    }
+
+    protected static function _getCompanyNames($id = null)
+    {
+        $cacheKey = '_get_compagny_names';
+        start_measure($cacheKey, 'Get compagny names');
+        self::$_companyNames = cache()->tags(['model_' . Company::class])->remember($cacheKey, 86400, function () {
+            set_time_limit(0);
+            $res = Company::withoutGlobalScopes()->get();
+            return $res->pluck('name', 'id')->toArray();
+        });
+        stop_measure($cacheKey);
+        if (null === $id) {
+            return self::$_companyNames;
+        }
+
+        return isset(self::$_companyNames[$id]) ? self::$_companyNames[$id] : $id;
+    }
+
+    public function getManagedUsers()
+    {
+        if (null === $this->_managedUsers) {
+            start_measure('_get_managed_users', 'Get managed users');
+            $this->_managedUsers = Permissions::getManagedUsers($this->id);
+            stop_measure('_get_managed_users');
+        }
+        return $this->_managedUsers;
+    }
+
+    public function getManagedCompanies()
+    {
+        if (null === $this->_managedCompanies) {
+            start_measure('_get_managed_companies', 'Get managed companies');
+            $this->_managedCompanies = Permissions::getManagedCompanies($this->id);
+            stop_measure('_get_managed_companies');
+        }
+        return $this->_managedCompanies;
+    }
+
+    public function isOwner($user)
+    {
+        if (null === $this->id) {
+            return true;
+        }
+        if (null === $user) {
+            return false;
+        }
+        /** @var $user self */
+        return in_array($this->id, $user->getManagedUsers());
+    }
+
+
+    public static function addOwnerClause(Builder $builder)
+    {
+        $bu = backpack_user();
+        if (null === $bu) {
+            $builder->where('id', '<', '0');
+            return;
+        }
+        if ($bu->hasPermissionTo('users:admin')) {
+            return;
+        }
+        $builder->whereIn('id', Permissions::getManagedUsers($bu->id));
+    }
+
+
+}
diff --git a/src/app/Operations/LoginasOperation.php b/src/app/Operations/LoginasOperation.php
new file mode 100644 (file)
index 0000000..a384ac0
--- /dev/null
@@ -0,0 +1,31 @@
+<?php
+
+namespace Cubedesigners\UserDatabase\Operations;
+
+use Cubedesigners\UserDatabase\Models\User;
+use Illuminate\Support\Facades\Route;
+
+trait LoginasOperation
+{
+    protected function setupLoginasRoutes($segment, $routeName, $controller)
+    {
+        Route::match(['get'], $segment . '/{id}/loginas', $controller . '@loginas');
+    }
+
+    protected function setupLoginasDefaults()
+    {
+        $this->crud->addButtonFromView('line', 'loginas', 'user.loginas', 'end');
+    }
+
+    protected function loginas($id)
+    {
+        $user = User::find($id);
+        backpack_auth()->login($user);
+        return redirect('dashboard');
+    }
+
+    public function canLoginas($user)
+    {
+        return $this->isOwner($user);
+    }
+}
diff --git a/src/app/Permissions.php b/src/app/Permissions.php
new file mode 100644 (file)
index 0000000..90f98c1
--- /dev/null
@@ -0,0 +1,153 @@
+<?php
+
+namespace Cubedesigners\UserDatabase;
+
+use Cubedesigners\UserDatabase\Models\Company;
+use Cubedesigners\UserDatabase\Models\User;
+
+class Permissions
+{
+    protected static $_data = false;
+
+    public static function _getData()
+    {
+        if (self::$_data !== false) {
+            return self::$_data;
+        }
+
+        $cacheKey = 'cubedesigners_userdatabase_permissions_data';
+
+        \Barryvdh\Debugbar\Facade::startMeasure($cacheKey, 'Build permissions tree');
+        self::$_data = cache()->remember($cacheKey, 86400, function () {
+
+            set_time_limit(0);
+
+            $data = [
+                'companyUsers' => [],
+                'usersCompany' => [],
+                'companyManagedBy' => [],
+                'managedCompanies' => [],
+                'managedUsers' => [],
+            ];
+
+            foreach (User::withoutGlobalScopes()->get() as $user) {
+                /** @var $user User */
+                if (!isset($data['companyUsers'][$user->company])) {
+                    $data['companyUsers'][$user->company] = [];
+                }
+
+                $data['companyUsers'][$user->company][] = $user->id;
+                $data['usersCompany'][$user->id] = $user->company;
+            }
+
+            foreach (Company::withoutGlobalScopes()->get() as $company) {
+                if (!$company->admin || !isset($data['usersCompany'][$company->admin])) {
+                    continue;
+                }
+                $adminCompany = $data['usersCompany'][$company->admin];
+
+                $data['companyManagedBy'][$company->id] = [$adminCompany, $company->id];
+            }
+
+            for ($i = 0; $i <= 3; $i++) {
+                foreach ($data['companyManagedBy'] as $company => $admins) {
+                    foreach ($admins as $admin) {
+                        if ($admin === $company) {
+                            continue;
+                        }
+                        if (isset($data['companyManagedBy'][$admin])) {
+                            $data['companyManagedBy'][$company] = array_unique(array_merge($data['companyManagedBy'][$admin], $data['companyManagedBy'][$company]), SORT_REGULAR);
+                        }
+                    }
+                }
+            }
+
+            foreach ($data['companyManagedBy'] as $company => $admins) {
+                foreach ($admins as $admin) {
+                    if (!isset($data['managedCompanies'][$admin])) {
+                        $data['managedCompanies'][$admin] = [];
+                    }
+                    $data['managedCompanies'][$admin][] = $company;
+                }
+            }
+
+            foreach ($data['companyUsers'] as $company => $users) {
+                if (!isset($data['managedCompanies'][$company])) {
+                    continue;
+                }
+                $managedUsers = [];
+                foreach ($data['managedCompanies'][$company] as $managedCompany) {
+                    if (!isset($data['companyUsers'][$managedCompany])) {
+                        continue;
+                    }
+                    $managedUsers = array_merge($managedUsers, $data['companyUsers'][$managedCompany]);
+                }
+
+                foreach ($users as $user) {
+                    if (!isset($data['managedUsers'][$user])) {
+                        $data['managedUsers'][$user] = [];
+                    }
+                    $data['managedUsers'][$user] = array_merge($data['managedUsers'][$user], $managedUsers);
+                }
+            }
+
+            return $data;
+        });
+        \Barryvdh\Debugbar\Facade::stopMeasure($cacheKey);
+        return self::$_data;
+    }
+
+    /**
+     * @param integer $company
+     * @return array
+     */
+    public static function getUsersByCompany($company)
+    {
+        $data = self::_getData();
+        if (isset($data['companyUsers'][$company])) {
+            return $data['companyUsers'][$company];
+        }
+        return [];
+    }
+
+    /**
+     * @param integer $user
+     * @return integer|null
+     */
+    public static function getCompanyByUser($user)
+    {
+        $data = self::_getData();
+        if (isset($data['usersCompany'][$user])) {
+            return $data['usersCompany'][$user];
+        }
+        return null;
+    }
+
+
+    /**
+     * @param $user integer
+     * @return array
+     */
+    public static function getManagedUsers($user)
+    {
+        $data = self::_getData();
+        if (isset($data['managedUsers'][$user])) {
+            return $data['managedUsers'][$user];
+        }
+        return [];
+    }
+
+
+    /**
+     * @param $user integer
+     * @return array
+     */
+    public static function getManagedCompanies($user)
+    {
+        $data = self::_getData();
+        if (isset($data['managedCompanies'][$user])) {
+            return $data['managedCompanies'][$user];
+        }
+        return [];
+    }
+}
diff --git a/src/app/SubForms/Address.php b/src/app/SubForms/Address.php
new file mode 100644 (file)
index 0000000..61601bb
--- /dev/null
@@ -0,0 +1,29 @@
+<?php
+
+
+namespace Cubedesigners\UserDatabase\SubForms;
+
+use Cubist\Backpack\Magic\SubForm;
+
+class Address extends SubForm
+{
+    public function init()
+    {
+        parent::init();
+        $this->addField(['name' => 'address',
+            'label' => __('Adresse'),
+            'type' => 'Textarea']);
+
+        $this->addField(['name' => 'postcode',
+            'label' => __('Code postal'),
+            'type' => 'Postcode']);
+
+        $this->addField(['name' => 'city',
+            'label' => __('Ville'),
+            'type' => 'Text']);
+
+        $this->addField(['name' => 'country',
+            'label' => __('Pays'),
+            'type' => 'Country']);
+    }
+}