HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/ehbo.today/app/KommaApp/Users/Kms/UserSection.php
<?php

namespace App\KommaApp\Users\Kms;

//The new object oriented attributes
use App\KommaApp\Courses\Kms\CourseService;
use App\KommaApp\Courses\Models\Course;
use App\KommaApp\IBAN\IBANRule;
use App\KommaApp\Kms\Core\Attributes\AutocompleteInput;
use App\KommaApp\Kms\Core\Attributes\DatePicker;
use App\KommaApp\Kms\Core\Attributes\Documents;
use App\KommaApp\Kms\Core\Attributes\Select;
use App\KommaApp\Kms\Core\Attributes\View;
use App\KommaApp\Kms\Core\Sections\NoLanguageTabsDirector;
use App\KommaApp\Routes\RouteService;
use App\KommaApp\Kms\Core\Attributes\Attribute;
use App\KommaApp\Kms\Core\Attributes\Models\ImageProperty;
use App\KommaApp\Kms\Core\Attributes\Models\SelectOption;
use App\KommaApp\Kms\Core\Attributes\Password;
use App\KommaApp\Kms\Core\Attributes\Seperator;
use App\KommaApp\Kms\Core\Attributes\TextField;

use App\KommaApp\Kms\Core\Attributes\Title;
use App\KommaApp\Kms\Core\Sections\Section;
use App\KommaApp\Kms\Core\Sections\SectionTabGroups;
use App\KommaApp\Kms\Core\Sections\SectionTabItem;
use App\KommaApp\Kms\Core\Sections\SectionTabsBuilder;
use App\KommaApp\Kms\Core\ValidationSet;
use App\KommaApp\Sites\SiteServiceInterface;
use App\KommaApp\Users\Genders;
use App\KommaApp\Users\Models\Role;
use App\KommaApp\Users\Models\User;
use App\KommaApp\Users\Roles;
use Illuminate\Validation\Rule;
use Illuminate\Database\Eloquent\Collection;

class UserSection extends Section
{
    protected $title = "Users";
    protected $subTitle = "The administrators for KMS";
    protected $slug = "users";
    protected $passwordDatabaseColumnName = "password";

    public $showSave = 'all';
    public $showDelete = [Roles::SuperAdmin,Roles::Admin];
    public $showCreate = [Roles::SuperAdmin,Roles::Admin];

    /** @var CourseService */
    private $courseService;

    /**
     * UserSection constructor.
     * @param SiteServiceInterface $siteService
     * @param UserService $sectionService
     * @param RouteService $routeService
     */
    function __construct(UserService $sectionService, RouteService $routeService, SiteServiceInterface $siteService)
    {
        $sectionTabDirector = new NoLanguageTabsDirector(new SectionTabsBuilder()); //Can make tabs for us. also see KmsSection::__construct

        $this->title = __('kms/users.title');
        $this->subTitle = __('kms/users.sub_title');
        $this->courseService = \App::make(CourseService::class);

        parent::__construct($sectionService, $routeService, $siteService, $sectionTabDirector);
    }

    /**
     * Generates the attributes for this section. They all must extend the App\KommaApp\Kms\Core\Attributes\Attribute class
     * This is the place where you need to setup your sections appearance. Just make sure you build an array of attributes
     * and put each attribute in a AbstractSectionTabItem with a SectionTabGroups constant to link them to a tab.
     *
     * @see UserRepository::saveModel()
     * @return Collection A collection of SectionTabItems
     */
    protected function generateAttributes(): Collection
    {
        /** @var User $model */
        $model = $this->loadModel($this->getModel());

        //*****************************************************************************************\\
        //*** Define attribute validation sets (Laravel validation rules and message sets)      ***\\
        //*****************************************************************************************\\
        $usernameValidationSet = (new ValidationSet())
//            ->setRules('required|unique:users,username')
            ->setRules([
                'required',
                Rule::unique('users', 'username')->ignore($model->id)
            ])
            ->setMessages([
                'required' => __('validation.required'),
                'unique' => __('kms/users.username_already_registered')
            ]);

        $emailValidationSet = (new ValidationSet())
            ->setRules([
                'required',
                'email',
                Rule::unique('users', 'email')->ignore($model->id)
            ])
            ->setMessages([
                'required' => __('validation.required'),
                'email' => __('kms/users.enterValidEmailAddress'),
                'unique' => __('kms/users.enterUniqueValue')
            ]);

        $passwordValidationSet = (new ValidationSet())
            ->setRules('sometimes|required|min:6|regex:/[a-zA-Z0-9]+/') //The sometimes rule only validates the password only if it is present in the input
            ->setMessages([
                'sometimes' => '',
                'required' => __('kms/users.enterPassword'),
                'min' => __('kms/users.passwordMinLength'),
                'regex' => __('kms/users.lowerCapitalNumber')
            ]);

        $ibanValidationSet = (new ValidationSet())
            ->setRules([
                new IBANRule()
            ])->setMessages([
                'iban' => __('iban.not_valid')
            ]);

        //*****************************************************************************************\\
        //*** Determine and define role dropdown data                                           ***\\
        //*****************************************************************************************\\
        $roleOptions = [];

        $roles = Role::all();
        $roles->each(function($role) use (&$roleOptions) {
            /** @var Role $role */
            /** @var Role $userRole */
            $userRole = \Auth::user()->mostPrivilegedRole();

            if($userRole->isAtLeast($role)) {
                $roleOptions[] = (new SelectOption())->setContent($role->name)->setHtmlContent(__('auth.roles.'.$role->value))->setValue($role->id);
            }
        });

        //*****************************************************************************************\\
        //*** Generate the attributes                                                           ***\\
        //*****************************************************************************************\\

        $attributes = [];
        $competencesTab = [];


        //Build the general attributes and put them in the attributes array
        $attributes[] = (new Title(__('kms/global.information')));

//        $attributes[] = (new Documents())
//            ->setImageProperties([
//                (new ImageProperty())->setName('thumb')->setCropMethod(ImageProperty::Resize)->setWidth(300)->setHeight(300),
//            ])
//            ->setLabelText(__('kms/global.images'))
//            ->setMaxDocuments(1)
//            ->setSubFolder('users')
//            ->setAccept('image/*')
//            ->mapValueFrom(Attribute::ValueFromDocuments, 'user');


        if($model->exists) {
            $competencesTab[] = $competencePartial = (new View('kms.partials.userCompetences'));
            if ($model->exists) {
                $competencePartial->setViewData([
                    'competences' => $this->courseService->getValidCompetences($model),
                    'expired_competences' => $this->courseService->getExpiredCompetences($model),
                    'expiring_competences' => $this->courseService->getAlmostExpiredCompetences($model),
                    'missing_competences' => $this->courseService->getMissingCompetences($model)
                ]);
            }
        }

        $genderOptions = [];
        collect(Genders::getAsArray())->each(function($gender) use (&$genderOptions) {
            $genderOptions[] = (new SelectOption())->setContent(__('auth.genders.'.$gender))->setHtmlContent(__('auth.genders.'.$gender))->setValue($gender);
        });

        $attributes[] = (new Seperator());

        $attributes[] = (new TextField(__('kms/global.username')))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'username')
            ->setValidationSet($usernameValidationSet);

        $attributes[] = (new TextField(__('kms/global.email')))
            ->setPlaceholderText(__('kms/users.emailPlaceholder'))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'email')
            ->setValidationSet($emailValidationSet);

        $attributes[] = (new Password())
            ->setLabelText(__('kms/global.password'))
            ->setRepeatLabelText(__('kms/global.password_repeat'))
            ->setPlaceholderText(__('kms/users.enterPassword'))
            ->setValidationSet($passwordValidationSet)
            ->mapValueFrom(Attribute::ValueFromModel, $this->passwordDatabaseColumnName);


        $attributes[] = (new AutocompleteInput())
            ->setLabelText(__('kms/users.role'))
            ->setItems($roleOptions)
            ->setPlaceholderText(__('kms/users.exampleRole'))
            ->mapValueFrom(Attribute::ValueFromModelHasManyRelation, 'roles|id');

        $attributes[] = (new Seperator());

        $attributes[] = (new Select())
            ->setLabelText(__('auth.gender'))
            ->setItems($genderOptions)
            ->mapValueFrom(Attribute::ValueFromModel, 'gender');

        $attributes[] = (new TextField(__('kms/users.first_name')))
            ->setPlaceholderText(__('kms/users.enter_first_name'))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'first_name');

        $attributes[] = (new TextField(__('kms/users.last_name')))
            ->setPlaceholderText(__('kms/users.enter_last_name'))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'last_name');

        $attributes[] = (new DatePicker(__('kms/users.birthdate')))
            ->setTimeEnabled(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'birthdate');


        $attributes[] = (new Seperator());

        $attributes[] = (new TextField(__('kms/users.street')))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'street');

        $attributes[] = (new TextField(__('kms/users.housenumber')))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'house_number');

        $attributes[] = (new TextField(__('kms/users.city')))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'city');

        $attributes[] = (new TextField(__('kms/users.postal_code')))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'postal_code');

        $attributes[] = (new Seperator());
        $attributes[] = (new TextField(__('kms/users.phone')))
            ->mapValueFrom(Attribute::ValueFromModel, 'telephone');

        $attributes[] = (new TextField(__('kms/users.mobile')))
            ->mapValueFrom(Attribute::ValueFromModel, 'mobile');

        $attributes[] = (new TextField(__('kms/users.bank_account_number')))
            ->setValidationSet($ibanValidationSet)
            ->mapValueFrom(Attribute::ValueFromModel, 'bank_account_number');

        $attributes[] = (new Seperator());
        $attributes[] = (new TextField(__('kms/certificates.number.label')))
            ->setReadOnly(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'certificate_number');

        $attributes[] = (new DatePicker(__('kms/certificates.acquirement_date')))
            ->setTimeEnabled(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'certificate_acquirement_date');

        $attributes[] = (new DatePicker(__('kms/certificates.valid_trough_date')))
            ->setTimeEnabled(false)
            ->mapValueFrom(Attribute::ValueFromModel, 'certificate_valid_trough_date');


        //****************************************************************************************************************************************\\
        //*** Put the all attributes in a SectionTabItem so we can track for which tab they are. And then put SectionTabItems in a Collection  ***\\
        //****************************************************************************************************************************************\\
        $tabItems = new Collection();
        foreach($attributes as $attribute) $tabItems->push(new SectionTabItem($attribute, SectionTabGroups::General));

        $this->sectionTabDirector->addTab('Competenties');
        foreach($competencesTab as $competencesTabItem) $tabItems->push(new SectionTabItem($competencesTabItem, 'Competenties'));

        return $tabItems;
    }

    /**
     * Strips out an empty password so that the validator validates
     *
     * @see KmsSection::validateInputAndReturnValidator();
     * @param array $input
     * @return \Validator
     */
    public function validateInputAndReturnValidator(array $input = [])
    {
        if(empty($input))
        {
            //Generate a temporary password attribute the same like in the generateAttributes method and retrieve its
            //key so that we can exclude it from the input when it is empty so that the validator ignores it.
            $passwordInputName = "Password-".$this->passwordDatabaseColumnName;
            if(\Input::get($passwordInputName) == "") $input = \Input::except($passwordInputName);
        }

        return parent::validateInputAndReturnValidator($input);
    }


}