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

allow updates, sorting for new row #714

Merged
merged 10 commits into from
May 11, 2022
Merged
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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
In order to read more about upgrading and BC breaks have a look at the [UPGRADE Document](UPGRADE.md).

## 4.4
## 4.4.0

+ [#714](https://github.com/luyadev/luya-module-admin/pull/714) Improve the sorting ability by adding create, update and delete events which are attached from the SortableTrait. Sorting over pagination or swap index from form input is now possible too.
+ [#711](https://github.com/luyadev/luya-module-admin/pull/711) Add option to disable the auto logout when the user ip changes.
+ [#712](https://github.com/luyadev/luya-module-admin/pull/712) Fix issue where field labels where not used from models `getAttributeLabel()` when using `ngRestExport()`.

Expand Down
7 changes: 4 additions & 3 deletions src/ngrest/plugins/Sortable.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ class Sortable extends Plugin
public function renderList($id, $ngModel)
{
return [
$this->createTag('i', 'keyboard_arrow_up', ['ng-init' => '$first ? changeOrder(\''.$this->name.'\', \'+\') : null', 'ng-click' => 'sortableUp($index, item, \''.$this->name.'\')', 'ng-class' => '{\'sortable-up-first\' : $first}', 'class' => 'material-icons btn btn-outline-secondary btn-symbol']),
$this->createTag('i', 'keyboard_arrow_down', ['ng-click' => 'sortableDown($index, item, \''.$this->name.'\')', 'ng-class' => '{\'sortable-up-last\' : $last}', 'class' => 'material-icons btn btn-outline-secondary btn-symbol'])
$this->createTag('i', 'keyboard_arrow_up', ['ng-init' => '$first ? changeOrder(\''.$this->name.'\', \'+\') : null', 'ng-click' => 'sortableUp($index, item, \''.$this->name.'\')', 'ng-class' => '{\'sortable-up-first\' : $first && pager.currentPage == 1}', 'class' => 'material-icons btn btn-outline-secondary btn-symbol']),
$this->createTag('i', 'keyboard_arrow_down', ['ng-click' => 'sortableDown($index, item, \''.$this->name.'\')', 'ng-class' => '{\'sortable-up-last\' : $last && pager.currentPage == pager.pageCount}', 'class' => 'material-icons btn btn-outline-secondary btn-symbol']),
$this->createTag('span', '{{'.$ngModel.'}}', ['class' => 'badge badge-light'])
];
}

Expand All @@ -33,7 +34,7 @@ public function renderList($id, $ngModel)
*/
public function renderCreate($id, $ngModel)
{
return $this->createFormTag('zaa-number', $id, $ngModel);
return $this->createFormTag('zaa-number', $id, $ngModel, ['min' => 1]);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/resources/dist/main.js

Large diffs are not rendered by default.

32 changes: 13 additions & 19 deletions src/resources/js/controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -569,28 +569,22 @@
/**** SORTABLE PLUGIN ****/

$scope.sortableUp = function(index, row, fieldName) {
var switchWith = $scope.data.listArray[index-1];
$scope.data.listArray[index-1] = row;
$scope.data.listArray[index] = switchWith;
$scope.updateSortableIndexPositions(fieldName);
var newPosition = parseInt(row[fieldName]) - 1
$scope.updateSortableIndexPosition(row, fieldName, newPosition);
};

$scope.sortableDown = function(index, row, fieldName) {
var switchWith = $scope.data.listArray[index+1];
$scope.data.listArray[index+1] = row;
$scope.data.listArray[index] = switchWith;
$scope.updateSortableIndexPositions(fieldName);
};

$scope.updateSortableIndexPositions = function(fieldName) {
angular.forEach($scope.data.listArray, function(value, key) {
var json = {};
json[fieldName] = key;
var pk = $scope.getRowPrimaryValue(value);
$http.put($scope.config.apiEndpoint + '/' + pk +'?ngrestCallType=update&fields='+fieldName, angular.toJson(json, true), {
ignoreLoadingBar: true
});
});
var newPosition = parseInt(row[fieldName]) + 1
$scope.updateSortableIndexPosition(row, fieldName, newPosition);
};

$scope.updateSortableIndexPosition = function(row, fieldName, newPosition) {
var json = {};
json[fieldName] = newPosition;
var pk = $scope.getRowPrimaryValue(row);
$http.put($scope.config.apiEndpoint + '/' + pk +'?ngrestCallType=update&fields='+fieldName, angular.toJson(json, true)).then(() => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar blocks of code found in 2 locations. Consider refactoring.

$scope.loadList();
})
};

/***** LIST LOADERS ********/
Expand Down
5 changes: 3 additions & 2 deletions src/resources/js/formdirectives.js
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,8 @@ zaa.directive("zaaNumber", function () {
"i18n": "@",
"id": "@fieldid",
"placeholder": "@",
"initvalue": "@"
"initvalue": "@",
"min": "@"
},
template: function () {
return '' +
Expand All @@ -746,7 +747,7 @@ zaa.directive("zaaNumber", function () {
'<label for="{{id}}">{{label}}</label>' +
'</div>' +
'<div class="form-side">' +
'<luya-number ng-model="model" fieldid="{{id}}" min="0" placeholder="{{placeholder}}" initvalue="{{initvalue}}"></luya-number>' +
'<luya-number ng-model="model" fieldid="{{id}}" min="{{min}}" placeholder="{{placeholder}}" initvalue="{{initvalue}}"></luya-number>' +
'</div>' +
'</div>';
}
Expand Down
135 changes: 134 additions & 1 deletion src/traits/SortableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@

namespace luya\admin\traits;

use luya\admin\ngrest\base\NgRestModel;
use Yii;
use yii\base\Event;
use yii\db\AfterSaveEvent;

/**
* Sortable Trait provides orderBy clause.
* Sortable Trait provides orderBy clause and re-index when update, delete or create rows.
*
* By default the field `sortindex` is taken, change this by override the `sortableField` method.
*
Expand All @@ -23,6 +28,134 @@
*/
trait SortableTrait
{
/**
* {@inheritDoc}
* @since 4.4.0
*/
public function init()
{
parent::init();
$this->on(NgRestModel::EVENT_AFTER_INSERT, [$this, 'newItemIndex']);
$this->on(NgRestModel::EVENT_AFTER_UPDATE, [$this, 'updateItemIndex']);
$this->on(NgRestModel::EVENT_AFTER_DELETE, [$this, 'deleteItemIndex']);
}

/**
* Update the index when deleting an item
*
* @param Event $event
* @since 4.4.0
*/
protected function deleteItemIndex(Event $event)
{
$transaction = Yii::$app->db->beginTransaction();
try {

$pkName = current($event->sender->primaryKey());
$this->reIndex($event, self::sortableField(), $pkName);
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
}

/**
* Update the index for a new item
*
* @param AfterSaveEvent $event
* @since 4.4.0
*/
protected function newItemIndex(AfterSaveEvent $event)
{
$this->updateItemIndex($event, true);
}

/**
* Update the index for a given event.
*
* Either
* - set the highest index available (if a row is created but no value has been given)
* - swap index for high to low position
* - swap index for low to hight position
*
* @param AfterSaveEvent $event
* @param boolean $isNewRecord
* @since 4.4.0
*/
protected function updateItemIndex(AfterSaveEvent $event, $isNewRecord = false)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function updateItemIndex has a Cognitive Complexity of 29 (exceeds 5 allowed). Consider refactoring.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Method updateItemIndex has 40 lines of code (exceeds 25 allowed). Consider refactoring.

{
$attributeName = self::sortableField();
$oldPosition = array_key_exists($attributeName, $event->changedAttributes) ? $event->changedAttributes[$attributeName] : false;
$newPosition = $event->sender[$attributeName];

// nothing has changed, skip further updates
if ($oldPosition == $newPosition && !$isNewRecord) {
return;
}

$transaction = Yii::$app->db->beginTransaction();
try {
$pkName = current($event->sender->primaryKey());
// no index has been set, set max value (last position)
if ($isNewRecord && empty($newPosition)) {
$event->sender->updateAttributes([$attributeName => $event->sender::find()->max($attributeName) + 1]);
} else if ($oldPosition && $newPosition && $oldPosition != $newPosition) {
$i = 1;
if ($newPosition > $oldPosition) {
// when the new position is highter then the old one: (old position - 1) + *1
foreach ($event->sender->find()->andWhere(['and', ['!=', $pkName, $event->sender->primaryKey], ['>', $attributeName, $oldPosition], ['<=', $attributeName, $newPosition]])->all() as $item) {
$item->updateAttributes([$attributeName => ($oldPosition - 1) + $i]);
$i++;
}
} else {
// when the new position is higher then the old one: (new position + *1)
foreach ($event->sender->find()->andWhere(['and', ['!=', $pkName, $event->sender->primaryKey], ['>=', $attributeName, $newPosition], ['<', $attributeName, $oldPosition]])->all() as $item) {
$item->updateAttributes([$attributeName => $newPosition + $i]);
$i++;
}
}
} else if (!empty($newPosition) && empty($oldPosition)) {
// its a new record where the user entered a position, lets move all the other higher indexes
$i = 1;
foreach ($event->sender->find()->andWhere(['and', ['!=', $pkName, $event->sender->primaryKey], ['>=', $attributeName, $newPosition]])->all() as $item) {
$item->updateAttributes([$attributeName => $newPosition + $i]);
$i++;
}
}

$this->reIndex($event, $attributeName, $pkName);
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
}

/**
* ReIndex the all items to ensure consistent numbers
*
* @param Event $event
* @param string $attributeName
* @param string $pkName
* @since 4.4.0
*/
private function reIndex(Event $event, $attributeName, $pkName)
{
$q = $event->sender->find()->asArray()->all();
$i = 1;
foreach ($q as $item) {
$event->sender->updateAll([$attributeName => $i], [$pkName => $item[$pkName]]);
$i++;
}
}

/**
* The field which should by used to sort.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/admin/ngrest/plugins/SortableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace admintests\admin\ngrest\plugins;

use admintests\AdminTestCase;
use luya\admin\ngrest\plugins\Sortable;

class SortableTest extends AdminTestCase
{
public function testSortableRenderList()
{
$renderList = new Sortable([
'alias' => 'slug',
'name' => 'slug',
'i18n' => true,
]);

$html = $renderList->renderList(1,'foobar');
$this->assertNotEmpty($html);
}
}
99 changes: 99 additions & 0 deletions tests/admin/traits/SortableTraitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

namespace admintests\admin\traits;

use admintests\AdminModelTestCase;
use admintests\AdminTestCase;
use admintests\data\fixtures\UserFixture;
use luya\admin\models\Group;
use luya\admin\models\User;
use luya\admin\models\UserOnline;
use luya\admin\traits\SortableTrait;
use luya\testsuite\fixtures\NgRestModelFixture;

class SortableTraitTest extends AdminModelTestCase
{
public function testSorting()
{
new NgRestModelFixture([
'modelClass' => UserStub::class,
'fixtureData' => [
'user1' => [
'id' => 1,
'title' => 1,
'firstname' => 'John',
'lastname' => 'Doe',
'email' => 'john@luya.io',
'password' => 'nohash',
'is_deleted' => 0,
'is_api_user' => 0,
],
'user2' => [
'id' => 2,
'title' => 3,
'firstname' => 'Jane',
'lastname' => 'Doe',
'email' => 'jane@luya.io',
'password' => 'nohash',
'is_deleted' => 0,
'is_api_user' => 0,
],
'user3' => [
'id' => 3,
'title' => 2,
'firstname' => 'James',
'lastname' => 'Doe',
'email' => 'deleted@luya.io',
'password' => 'nohash',
'is_deleted' => 0,
'is_api_user' => 0,
]
]
]);

$this->createAdminNgRestLogFixture();


// ensures the sort index title = 3 is the last item, which is array index 2
$q = UserStub::find()->asArray()->all();
$this->assertSame('Jane', $q[2]['firstname']);

// get last model (jane) and move to new position
$modelLast = UserStub::findOne(['id' => 2]);
$modelLast->title = 1;
$modelLast->save(true, ['title']);

// ensures the sort index title = 3 is the last item, which is now since jane has swap to first position James
$q = UserStub::find()->asArray()->all();
$this->assertSame('James', $q[2]['firstname']);

// delete the model
$modelLast->delete();

// add new item
$newModel = new UserStub();
$newModel->title = 20;
$newModel->firstname = 'Han';
$newModel->lastname = 'Solo';
$newModel->email = 'hansolo@luya.io';
$newModel->password = 'doesnotexis434!@Aasdfts';
$newModel->is_deleted = false;
$this->assertTrue($newModel->save());

$newModel->refresh();

// the index has changed by the sortable plugin, even we have entered 20 as value
// since we have deleted an item, the index has now 3 entries and not 4
$this->assertSame('3', $newModel->title);
}
}

class UserStub extends User {

use SortableTrait;

public static function sortableField()
{
return 'title';
}
}