Merge branch 'develop' of github.com:tainacan/tainacan into develop

This commit is contained in:
Jacson Passold 2018-02-16 13:18:19 -02:00
commit 5fb73b3b8e
44 changed files with 653 additions and 346 deletions

View File

@ -1,42 +1,60 @@
<template>
<div>
<b-table
ref="multipleTable"
:data="items"
@selection-change="handleSelectionChange"
stripe>
<template slot-scope="props">
<section class="section">
<button v-if="selectedItems.length > 0" class="button field is-danger" @click="deleteSelectedItems()"><span>Deletar itens selecionados </span><b-icon icon="delete"></b-icon></button>
<b-table
ref="itemsTable"
:data="items"
@selection-change="handleSelectionChange"
:checked-rows.sync="selectedItems"
:loading="isLoading"
checkable>
<template slot-scope="props">
<b-table-column field="featured_image" width="55">
<template v-if="props.row.featured_image" slot-scope="scope">
<img class="table-thumb" :src="`${props.row.featured_image}`"/>
</template>
</b-table-column>
<b-table-column field="featured_image" width="55">
<template v-if="props.row.featured_image" slot-scope="scope">
<img class="table-thumb" :src="`${props.row.featured_image}`"/>
</template>
</b-table-column>
<b-table-column label="Nome" field="title" show-overflow-tooltip>
<router-link
:to="`/collections/${collectionId}/items/${props.row.id}`" tag="a">{{ props.row.title }}
</router-link>
</b-table-column>
<b-table-column label="Nome" field="title" show-overflow-tooltip>
<router-link
:to="`/collections/${collectionId}/items/${props.row.id}`" tag="a">{{ props.row.title }}
</router-link>
</b-table-column>
<b-table-column field="description" label="Descrição">
{{ props.row.description }}
</b-table-column>
<b-table-column field="description" label="Descrição">
{{ props.row.description }}
</b-table-column>
<b-table-column label="Ações">
<router-link :to="`/collections/${collectionId}/items/${props.row.id}/edit`" tag="a"><b-icon icon="pencil"></router-link>
<a @click.native="showMoreItem(props.row.id)">
<b-icon icon="dots-vertical">
</a>
</b-table-column>
<b-table-column label="Ações">
<router-link :to="`/collections/${collectionId}/items/${props.row.id}/edit`" tag="a"><b-icon icon="pencil"></router-link>
<a><b-icon icon="delete" @click.native="deleteOneItem(props.row.id)"></a>
<a><b-icon icon="dots-vertical" @click.native="showMoreItem(props.row.id)"></a>
</b-table-column>
</template>
<!--b-table-column type="selection" width="55">
</b-table-column -->
</b-table>
</template>
<!-- Empty state image -->
<template slot="empty">
<section class="section">
<div class="content has-text-grey has-text-centered">
<p>
<b-icon
icon="inbox"
size="is-large">
</b-icon>
</p>
<p>Nenhum item ainda nesta coleção.</p>
<router-link tag="button" class="button is-primary"
:to="{ path: `/collections/${collectionId}/items/new` }">
Criar Item
</router-link>
</div>
</section>
</template>
</b-table>
</section>
</div>
</template>
@ -47,7 +65,8 @@ export default {
name: 'ItemsList',
data(){
return {
multipleSelection: []
selectedItems: [],
isLoading: Boolean
}
},
props: {
@ -55,19 +74,70 @@ export default {
},
methods: {
...mapActions('collection', [
'fetchItems'
'fetchItems',
'deleteItem'
]),
...mapGetters('collection', [
'getItems'
]),
handleSelectionChange(value) {
this.multipleSelection = value;
deleteOneItem(itemId) {
this.$dialog.confirm({
message: 'Deseja realmente deletar este Item?',
onConfirm: () => {
this.deleteItem(itemId).then(() =>
this.$toast.open({
duration: 3000,
message: `Item deletado`,
position: 'is-bottom',
type: 'is-secondary',
queue: true
})
).catch(() =>
this.$toast.open({
duration: 3000,
message: `Erro ao deletar item`,
position: 'is-bottom',
type: 'is-danger',
queue: true
})
);
}
});
},
shareItem(itemId) {
deleteSelectedItems() {
this.$dialog.confirm({
message: 'Deseja realmente todos os itens selecionados?',
onConfirm: () => {
for (let item of this.selectedItems) {
this.deleteItem(item.id)
.then((res) => {
this.$toast.open({
duration: 3000,
message: `Item deletado`,
position: 'is-bottom',
type: 'is-secondary',
queue: false
})
}).catch((err) => {
this.$toast.open({
duration: 3000,
message: `Erro ao deletar item`,
position: 'is-bottom',
type: 'is-danger',
queue: false
});
});
}
this.selectedItems = [];
}
});
},
handleSelectionChange() {
},
showMoreItem(itemId) {
}
},
computed: {
@ -76,7 +146,12 @@ export default {
}
},
created(){
this.fetchItems(this.collectionId);
this.isLoading = true;
this.fetchItems(this.collectionId)
.then(res => this.isLoading = false)
.catch((error) => {
this.isLoading = false;
});
}
}

View File

@ -20,6 +20,11 @@
</div>
</div>
<footer class="card-footer">
<router-link
class="card-footer-item"
:to="{ path: `/collections/${collection.id}/edit` }">
Editar Coleção
</router-link>
<router-link
class="card-footer-item"
:to="{ path: `/collections/${collection.id}/items/new`, params: { collection_id: collection.id }}">

View File

@ -22,6 +22,10 @@
</div>
</div>
<footer class="card-footer">
<router-link
class="card-footer-item" :to="{ path: `/collections/${collectionId}`}">
Ver Coleção
</router-link>
<router-link
class="card-footer-item" :to="{ path: `/collections/${collectionId}/items/${itemId}/edit`}">
Editar Item

View File

@ -26,6 +26,9 @@ $link: $primary;
$link-invert: $primary-invert;
$link-focus-border: $primary;
// Bulma's modal (needs to be greather than taincan-admin-app
$modal-z: 9999999;
// Import Bulma and Buefy styles
@import "../../assets/css/fonts/materialdesignicons.css";
@import "../../../node_modules/bulma/bulma.sass";
@ -59,4 +62,9 @@ body.tainacan-admin-page #adminmenumain {
/* Rules for using icons as white on a dark background. */
.material-icons.md-light { color: rgba(255, 255, 255, 1); }
.material-icons.md-light.md-inactive { color: rgba(255, 255, 255, 0.3); }
.material-icons.md-light.md-inactive { color: rgba(255, 255, 255, 0.3); }
// Buefy notices (toast)
.notices {
z-index: 99999999 !important;
}

View File

@ -2,6 +2,25 @@
class TAINACAN_REST_Controller extends WP_REST_Controller {
/**
* @param $object
* @param $new_values
*
* @return Tainacan\Entities\Entity
*/
protected function prepare_item_for_updating($object, $new_values){
foreach ($new_values as $key => $value) {
try {
$set_ = 'set_' . $key;
$object->$set_( $value );
} catch (\Error $error){
// Do nothing
}
}
return $object;
}
/**
* @param $entity
@ -11,8 +30,8 @@ class TAINACAN_REST_Controller extends WP_REST_Controller {
protected function get_only_needed_attributes($entity, $map){
$entity_prepared = [
'id' => $entity->get_id(),
'description' => $entity->get_description(),
'id' => $entity->get_id(),
'description' => $entity->get_description(),
];
if(array_key_exists('modification_date', $map)){
@ -41,6 +60,10 @@ class TAINACAN_REST_Controller extends WP_REST_Controller {
$entity_prepared['columns'] = $entity->get_columns();
}
if(array_key_exists('status', $map)){
$entity_prepared['status'] = $entity->get_status();
}
return $entity_prepared;
}
@ -51,22 +74,24 @@ class TAINACAN_REST_Controller extends WP_REST_Controller {
*/
protected function prepare_filters($request){
$map = [
'name' => 'title',
'title' => 'title',
'id' => 'p',
'pageid' => 'page_id',
'authorid' => 'author_id',
'authorname' => 'author_name',
'search' => 's',
'posttype' => 'post_type',
'poststatus' => 'post_status',
'offset' => 'offset',
'metaquery' => 'meta_query',
'datequery' => 'date_query',
'order' => 'order',
'orderby' => 'orderby',
'metakey' => 'meta_key',
'hide_empty' => 'hide_empty',
'name' => 'title',
'title' => 'title',
'id' => 'p',
'pageid' => 'page_id',
'authorid' => 'author_id',
'authorname' => 'author_name',
'search' => 's',
'posttype' => 'post_type',
'status' => 'post_status',
'offset' => 'offset',
'metaquery' => 'meta_query',
'datequery' => 'date_query',
'order' => 'order',
'orderby' => 'orderby',
'metakey' => 'meta_key',
'hideempty' => 'hide_empty',
'perpage' => 'posts_per_page',
'paged' => 'paged'
];
$meta_query = [

View File

@ -82,9 +82,31 @@ class TAINACAN_REST_Collections_Controller extends TAINACAN_REST_Controller {
$collections = $this->collections_repository->fetch($args);
$response = $this->prepare_item_for_response($collections, $request);
$map = $this->collections_repository->get_map();
return new WP_REST_Response($response, 200);
$response = [];
if($collections->have_posts()){
while ($collections->have_posts()){
$collections->the_post();
$collection = new Entities\Collection($collections->post);
array_push($response, $this->get_only_needed_attributes($collection, $map));
}
wp_reset_postdata();
}
$total_collections = $collections->found_posts;
$max_pages = ceil($total_collections / (int) $collections->query_vars['posts_per_page']);
$rest_response = new WP_REST_Response($response, 200);
$rest_response->header('X-WP-Total', (int) $total_collections);
$rest_response->header('X-WP-TotalPages', (int) $max_pages);
return $rest_response;
}
/**
@ -113,28 +135,8 @@ class TAINACAN_REST_Collections_Controller extends TAINACAN_REST_Controller {
* @return mixed|string|void|WP_Error|WP_REST_Response
*/
public function prepare_item_for_response($item, $request){
$map = $this->collections_repository->get_map();
if($item instanceof WP_Query){
$collections = [];
if ($item->have_posts()) {
while ( $item->have_posts() ) {
$item->the_post();
$collection = new Entities\Collection($item->post->ID);
$collection_resumed = $this->get_only_needed_attributes($collection, $map);
array_push($collections, $collection_resumed);
}
wp_reset_postdata();
}
return $collections;
}
elseif(!empty($item)){
return $this->get_only_needed_attributes($item, $map);
if(!empty($item)){
return $item->__toArray();
}
return $item;
@ -177,17 +179,17 @@ class TAINACAN_REST_Collections_Controller extends TAINACAN_REST_Controller {
* @return array|WP_Error|WP_REST_Response
*/
public function create_item( $request ) {
$request = json_decode($request->get_body(), true);
$body = json_decode($request->get_body(), true);
if(empty($request)){
if(empty($body)){
return new WP_REST_Response([
'error_message' => __('Body can not be empty.', 'tainacan'),
'collection' => $request
'collection' => $body
], 400);
}
try {
$prepared_post = $this->prepare_item_for_database( $request );
$prepared_post = $this->prepare_item_for_database( $body );
} catch (\Error $exception){
return new WP_REST_Response($exception->getMessage(), 400);
}
@ -195,13 +197,15 @@ class TAINACAN_REST_Collections_Controller extends TAINACAN_REST_Controller {
if($prepared_post->validate()) {
$collection = $this->collections_repository->insert( $prepared_post );
return new WP_REST_Response($collection->__toArray(), 201);
$response = $this->prepare_item_for_response($collection, $request);
return new WP_REST_Response($response, 201);
}
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $prepared_post->get_errors(),
'collection' => $prepared_post->__toArray()
'collection' => $this->prepare_item_for_response($prepared_post, $request)
], 400);
}
@ -293,17 +297,32 @@ class TAINACAN_REST_Collections_Controller extends TAINACAN_REST_Controller {
$collection = $this->collections_repository->fetch($collection_id);
$updated_collection = $this->collections_repository->update($collection, $attributes);
if($collection) {
$prepared_collection = $this->prepare_item_for_updating( $collection, $attributes );
if(!($updated_collection instanceof Entities\Collection)){
return new WP_REST_Response($updated_collection, 400);
if ( $prepared_collection->validate() ) {
$updated_collection = $this->collections_repository->update( $collection );
$response = $this->prepare_item_for_response($updated_collection, $request);
return new WP_REST_Response( $response, 200 );
}
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $prepared_collection->get_errors(),
'collection' => $this->prepare_item_for_response($prepared_collection, $request)
], 400);
}
return new WP_REST_Response($updated_collection->__toArray(), 200);
return new WP_REST_Response([
'error_message' => __('Collection with that ID not found', 'tainacan' ),
'collection_id' => $collection_id
], 400);
}
return new WP_REST_Response([
'error_message' => 'The body could not be empty',
'error_message' => __('The body could not be empty', 'tainacan'),
'body' => $body
], 400);
}
@ -333,7 +352,7 @@ class TAINACAN_REST_Collections_Controller extends TAINACAN_REST_Controller {
public function get_collection_params() {
$query_params = $this->collections_repository->get_map();
return apply_filters("rest_{$this->collection->get_post_type()}_collection_params", $query_params, $this->collection->get_post_type());
return $query_params;
}
/**
@ -349,7 +368,7 @@ class TAINACAN_REST_Collections_Controller extends TAINACAN_REST_Controller {
]
];
return apply_filters("rest_{$this->collection->get_post_type()}_collection_params", $args, $this->collection->get_post_type());
return $args;
}
/**

View File

@ -119,16 +119,20 @@ class TAINACAN_REST_Fields_Controller extends TAINACAN_REST_Controller {
$field_added = $this->item_metadata_repository->insert($item_meta);
}
return new WP_REST_Response($field_added->get_field()->__toArray(), 201);
$response = $this->prepare_item_for_response($field_added->get_field(), $request);
return new WP_REST_Response($response, 201);
}
else {
return new WP_REST_Response($this->field->__toArray(), 201);
$response = $this->prepare_item_for_response($this->field, $request);
return new WP_REST_Response($response, 201);
}
} else {
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $this->field->get_errors(),
'field' => $this->field->__toArray(),
'field' => $this->prepare_item_for_response($this->field, $request),
], 400);
}
}
@ -157,13 +161,11 @@ class TAINACAN_REST_Fields_Controller extends TAINACAN_REST_Controller {
* @return array|WP_Error|WP_REST_Response
*/
public function prepare_item_for_response( $item, $request ) {
$field_as = [];
foreach ( $item as $field ) {
$field_as[] = $field->__toArray();
if(!empty($item)){
return $item->__toArray();
}
return $field_as;
return $item;
}
/**
@ -180,7 +182,10 @@ class TAINACAN_REST_Fields_Controller extends TAINACAN_REST_Controller {
$collection_metadata = $this->field_repository->fetch_by_collection($collection, $args, 'OBJECT');
$prepared_item = $this->prepare_item_for_response($collection_metadata, $request);
$prepared_item = [];
foreach ($collection_metadata as $item){
$prepared_item[] = $this->prepare_item_for_response($item, $request);
}
return new WP_REST_Response($prepared_item, 200);
}
@ -264,33 +269,51 @@ class TAINACAN_REST_Fields_Controller extends TAINACAN_REST_Controller {
$field = $this->field_repository->fetch($field_id);
$updated_metadata = $this->field_repository->update($field, $attributes);
if($field){
if(!($updated_metadata instanceof Entities\Field)){
return new WP_REST_Response($updated_metadata, 400);
}
$prepared_metadata = $this->prepare_item_for_updating($field, $attributes);
$items = $this->item_repository->fetch([], $collection_id, 'WP_Query');
if($prepared_metadata->validate()){
$updated_metadata = $this->field_repository->update($prepared_metadata);
$up_metadata = '';
if($items->have_posts()){
while ($items->have_posts()){
$items->the_post();
$items = $this->item_repository->fetch([], $collection_id, 'WP_Query');
$item = new Entities\Item($items->post);
$item_meta = new Entities\Item_Metadata_Entity($item, $updated_metadata);
$up_metadata = '';
if($items->have_posts()){
while ($items->have_posts()){
$items->the_post();
$up_metadata = $this->item_metadata_repository->update($item_meta);
$item = new Entities\Item($items->post);
$item_meta = new Entities\Item_Metadata_Entity($item, $updated_metadata);
$up_metadata = $this->item_metadata_repository->update($item_meta);
}
$response = $this->prepare_item_for_response($up_metadata->get_field(), $request);
return new WP_REST_Response($response, 200);
}
$response = $this->prepare_item_for_response($updated_metadata, $request);
return new WP_REST_Response($response, 200);
}
return new WP_REST_Response($up_metadata->get_field()->__toArray(), 201);
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $prepared_metadata->get_errors(),
'metadata' => $this->prepare_item_for_response($prepared_metadata, $request)
], 400);
}
return new WP_REST_Response($updated_metadata->__toArray(), 201);
return new WP_REST_Response([
'error_message' => __('Field with that ID not found', 'tainacan'),
'field_id' => $field_id
], 400);
}
return new WP_REST_Response([
'error_message' => 'The body could not be empty',
'error_message' => __('The body could not be empty', 'tainacan'),
'body' => $body
], 400);
}

View File

@ -215,17 +215,31 @@ class TAINACAN_REST_Filters_Controller extends TAINACAN_REST_Controller {
$filter = $this->filter_repository->fetch($filter_id);
$updated_filter = $this->filter_repository->update($filter, $attributes);
if($filter) {
$prepared_filter = $this->prepare_item_for_updating($filter, $attributes);
if(!($updated_filter instanceof Entities\Filter)){
return new WP_REST_Response($updated_filter, 400);
if($prepared_filter->validate()) {
$updated_filter = $this->filter_repository->update( $prepared_filter );
return new WP_REST_Response($updated_filter->__toArray(), 200);
}
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $prepared_filter->get_errors(),
'filters' => $prepared_filter->__toArray()
], 400);
}
return new WP_REST_Response($updated_filter->__toArray(), 200);
return new WP_REST_Response([
'error_message' => __('Filter with that ID not found', 'tainacan' ),
'filter_id' => $filter_id
], 400);
}
return new WP_REST_Response([
'error_message' => 'The body could not be empty',
'error_message' => __('The body could not be empty', 'tainacan'),
'body' => $body
], 400);

View File

@ -85,13 +85,7 @@ class TAINACAN_REST_Item_Metadata_Controller extends TAINACAN_REST_Controller {
* @return array|WP_Error|WP_REST_Response
*/
public function prepare_item_for_response( $item, $request ) {
$field_as = [];
foreach ( $item as $field ) {
$field_as[] = $field->__toArray();
}
return $field_as;
return $item->__toArray();
}
/**
@ -102,11 +96,16 @@ class TAINACAN_REST_Item_Metadata_Controller extends TAINACAN_REST_Controller {
public function get_items( $request ) {
$item_id = $request['item_id'];
$item = new Entities\Item($item_id);
$item = $this->item_repository->fetch($item_id);
$item_metadata = $item->get_fields();
$items_metadata = $item->get_fields();
$prepared_item = $this->prepare_item_for_response($item_metadata, $request);
$prepared_item = [];
foreach ($items_metadata as $item_metadata){
$index = array_push($prepared_item, $this->prepare_item_for_response($item_metadata, $request));
$prepared_item[$index-1]['field']['field_type_object'] = $item_metadata->get_field()->get_field_type_object()->__toArray();
}
return new WP_REST_Response($prepared_item, 200);
}
@ -182,20 +181,23 @@ class TAINACAN_REST_Item_Metadata_Controller extends TAINACAN_REST_Controller {
if($body) {
$item_id = $request['item_id'];
$item_id = $request['item_id'];
$field_id = $request['metadata_id'];
$value = $body['values'];
$value = $body['values'];
$item = $this->item_repository->fetch( $item_id );
$item = $this->item_repository->fetch( $item_id );
$field = $this->field_repository->fetch( $field_id );
$item_metadata = new Entities\Item_Metadata_Entity( $item, $field );
$item_metadata->set_value( ( is_array($value) ) ? array_filter($value) : $value );
$item_metadata->set_value( $value );
if ( $item_metadata->validate() ) {
$field_updated = $this->item_metadata_repository->update( $item_metadata );
$field_updated = $this->item_metadata_repository->insert( $item_metadata );
return new WP_REST_Response( $field_updated->__toArray(), 200 );
$prepared_item = $this->prepare_item_for_response($field_updated, $request);
$prepared_item['field']['field_type_object'] = $field_updated->get_field()->get_field_type_object()->__toArray();
return new WP_REST_Response( $prepared_item, 200 );
} else {
return new WP_REST_Response( [
'error_message' => __( 'One or more values are invalid.', 'tainacan' ),

View File

@ -85,26 +85,7 @@ class TAINACAN_REST_Items_Controller extends TAINACAN_REST_Controller {
* @return mixed|string|void|WP_Error|WP_REST_Response
*/
public function prepare_item_for_response( $item, $request ) {
$map = $this->items_repository->get_map();
if (!empty($item) && $item instanceof WP_Query){
$items = [];
if ($item->have_posts()) {
while ( $item->have_posts() ) {
$item->the_post();
$ite = new Entities\Item($item->post);
$item_prepared = $this->get_only_needed_attributes($ite, $map);
array_push($items, $item_prepared);
}
wp_reset_postdata();
}
return $items;
} elseif(!empty($item)){
if(!empty($item)){
return $item->__toArray();
}
@ -137,9 +118,30 @@ class TAINACAN_REST_Items_Controller extends TAINACAN_REST_Controller {
$collection_id = $request['collection_id'];
$items = $this->items_repository->fetch($args, $collection_id, 'WP_Query');
$response = $this->prepare_item_for_response($items, $request);
$map = $this->items_repository->get_map();
return new WP_REST_Response($response, 200);
$response = [];
if ($items->have_posts()) {
while ( $items->have_posts() ) {
$items->the_post();
$item = new Entities\Item($items->post);
array_push($response, $this->get_only_needed_attributes($item, $map));
}
wp_reset_postdata();
}
$total_items = $items->found_posts;
$max_pages = ceil($total_items / (int) $items->query_vars['posts_per_page']);
$rest_response = new WP_REST_Response($response, 200);
$rest_response->header('X-WP-Total', (int) $total_items);
$rest_response->header('X-WP-TotalPages', (int) $max_pages);
return $rest_response;
}
/**
@ -215,14 +217,14 @@ class TAINACAN_REST_Items_Controller extends TAINACAN_REST_Controller {
if($this->item->validate()) {
$item = $this->items_repository->insert($this->item );
return new WP_REST_Response($this->item->__toArray(), 201 );
return new WP_REST_Response($this->prepare_item_for_response($item, $request), 201 );
}
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $this->item->get_errors(),
'item' => $this->item->__toArray()
'item' => $this->prepare_item_for_response($this->item, $request)
], 400);
}
@ -295,17 +297,30 @@ class TAINACAN_REST_Items_Controller extends TAINACAN_REST_Controller {
$item = $this->items_repository->fetch($item_id);
$updated_item = $this->items_repository->update($item, $attributes);
if($item){
$prepared_item = $this->prepare_item_for_updating($item, $attributes);
if(!($updated_item instanceof Entities\Item)){
return new WP_REST_Response($updated_item, 400);
if($prepared_item->validate()){
$updated_item = $this->items_repository->update($prepared_item);
return new WP_REST_Response($this->prepare_item_for_response($updated_item, $request), 200);
}
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $prepared_item->get_errors(),
'item' => $this->prepare_item_for_response($prepared_item, $request)
], 400);
}
return new WP_REST_Response($updated_item->__toArray(), 200);
return new WP_REST_Response([
'error_message' => __('Item with that ID not found', 'tainacan' ),
'item_id' => $item_id
], 400);
}
return new WP_REST_Response([
'error_message' => 'The body could not be empty',
'error_message' => __('The body could not be empty', 'tainacan'),
'body' => $body
], 400);
}

View File

@ -286,17 +286,30 @@ class TAINACAN_REST_Taxonomies_Controller extends TAINACAN_REST_Controller {
$taxonomy = $this->taxonomy_repository->fetch($taxonomy_id);
$updated_taxonomy = $this->taxonomy_repository->update($taxonomy, $attributes);
if($taxonomy){
$prepared_taxonomy = $this->prepare_item_for_updating($taxonomy, $attributes);
if(!($updated_taxonomy instanceof Entities\Taxonomy)){
return new WP_REST_Response($updated_taxonomy, 400);
if($prepared_taxonomy->validate()){
$updated_taxonomy = $this->taxonomy_repository->update($prepared_taxonomy);
return new WP_REST_Response($updated_taxonomy->__toArray(), 200);
}
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $prepared_taxonomy->get_errors(),
'taxonomy' => $prepared_taxonomy->__toArray()
], 400);
}
return new WP_REST_Response($updated_taxonomy->__toArray(), 200);
return new WP_REST_Response([
'error_message' => __('Taxonomy with that ID not found', 'tainacan' ),
'taxonomy_id' => $taxonomy_id
], 400);
}
return new WP_REST_Response([
'error_message' => 'The body could not be empty',
'error_message' => __('The body could not be empty', 'tainacan'),
'body' => $body
], 400);
}

View File

@ -201,17 +201,31 @@ class TAINACAN_REST_Terms_Controller extends TAINACAN_REST_Controller {
$term = $this->terms_repository->fetch($term_id, $taxonomy);
$updated_term = $this->terms_repository->update([$term, $tax_name], $attributes);
if($term){
$prepared_term = $this->prepare_item_for_updating($term, $attributes);
if(!($updated_term instanceof Entities\Term)){
return new WP_REST_Response($updated_term, 400);
if($prepared_term->validate()){
$updated_term = $this->terms_repository->update($prepared_term, $tax_name);
return new WP_REST_Response($updated_term->__toArray(), 200);
}
return new WP_REST_Response([
'error_message' => __('One or more values are invalid.', 'tainacan'),
'errors' => $prepared_term->get_errors(),
'term' => $prepared_term->__toArray()
], 400);
}
return new WP_REST_Response($updated_term->__toArray(), 200);
return new WP_REST_Response([
'error_message' => __('Term or Taxonomy with that IDs not found', 'tainacan' ),
'term_id' => $term_id,
'taxonomy_id' => $taxonomy_id
], 400);
}
return new WP_REST_Response([
'error_message' => 'The body could not be empty',
'error_message' => __('The body could not be empty', 'tainacan'),
'body' => $body
], 400);
}

View File

@ -152,6 +152,15 @@ class Field extends Entity {
function get_field_options(){
return $this->get_mapped_property('field_type_options');
}
/**
* Return the if the field may be deleted
*
* @return string
*/
function get_can_delete(){
return $this->get_mapped_property('can_delete');
}
/**
* Return true if this field allow community suggestions, false otherwise
@ -288,6 +297,16 @@ class Field extends Entity {
return $this->set_mapped_property('accept_suggestion', $value);
}
/**
* Set can delete
*
* @param [string] $value
* @return void
*/
function set_can_delete( $value ){
$this->set_mapped_property('can_delete', $value);
}
// helpers
/**

View File

@ -13,6 +13,7 @@ class Checkbox extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('date');
$this->component = 'tainacan-checkbox';
}
/**

View File

@ -15,6 +15,7 @@ class Core_Description extends Field_Type {
parent::set_primitive_type('string');
$this->core = true;
$this->related_mapped_prop = 'description';
$this->component = 'tainacan-textarea';
}
/**

View File

@ -15,6 +15,7 @@ class Core_Title extends Field_Type {
parent::set_primitive_type('string');
$this->core = true;
$this->related_mapped_prop = 'title';
$this->component = 'tainacan-text';
}
/**

View File

@ -14,6 +14,7 @@ class Date extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('date');
$this->component = 'tainacan-date';
}
/**

View File

@ -27,7 +27,13 @@ abstract class Field_Type {
* Used by core field types to indicate where it should be saved
*/
public $related_mapped_prop = false;
/**
* The name of the web component used by this field type
* @var string
*/
public $component;
abstract function render( $itemMetadata );
public function __construct(){
@ -58,6 +64,10 @@ abstract class Field_Type {
public function get_errors() {
return $this->errors;
}
public function get_component() {
return $this->component;
}
/**
* @param $options
@ -72,5 +82,17 @@ abstract class Field_Type {
public function form(){
}
public function __toArray(){
$attributes = [];
$attributes['className'] = get_class($this);
$attributes['core'] = $this->core;
$attributes['component'] = $this->get_component();
$attributes['primitive_type'] = $this->get_primitive_type();
return $attributes;
}
}

View File

@ -13,6 +13,7 @@ class Numeric extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('float');
$this->component = 'tainacan-numeric';
}
/**

View File

@ -13,6 +13,7 @@ class Radio extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('');
$this->component = 'tainacan-radio';
}
/**

View File

@ -15,6 +15,7 @@ class Relationship extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('');
$this->component = 'tainacan-relationship';
}
/**

View File

@ -13,6 +13,7 @@ class Selectbox extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('');
$this->component = 'tainacan-selectbox';
}
/**

View File

@ -3,10 +3,10 @@
:message="getErrorMessage"
:type="fieldTypeMessage">
<div>
<component :is="extractFieldType(field.field.field_type)" v-model="inputs[0]" :field="field" @blur="changeValue()"></component>
<component :is="field.field.field_type_object.component" v-model="inputs[0]" :field="field" @blur="changeValue()"></component>
<div v-if="field.field.multiple == 'yes'">
<div v-if="index > 0" v-for="(input, index) in inputsList " v-bind:key="index" class="multiple-inputs">
<component :is="extractFieldType(field.field.field_type)" v-model="inputs[index]" :field="field" @blur="changeValue()"></component><a class="button" v-if="index > 0" @click="removeInput(index)">-</a>
<component :is="field.field.field_type_object.component" v-model="inputs[index]" :field="field" @blur="changeValue()"></component><a class="button" v-if="index > 0" @click="removeInput(index)">-</a>
</div>
<a class="button" @click="addInput">+</a>
</div>
@ -48,13 +48,12 @@
},
created(){
this.getValue();
},
methods: {
changeValue(){
eventBus.$emit('input', { item_id: this.field.item.id, field_id: this.field.field.id, values: this.inputs, instance: this } );
eventBus.$emit('input', { item_id: this.field.item.id, field_id: this.field.field.id, values: this.inputs } );
},
getValue(){
getValue(){
if (this.field.value instanceof Array) {
this.inputs = this.field.value;
if (this.inputs.length == 0)
@ -63,10 +62,6 @@
this.field.value == null || this.field.value == undefined ? this.inputs.push('') : this.inputs.push(this.field.value);
}
},
extractFieldType(field_type) {
let parts = field_type.split('\\');
return 'tainacan-' + parts.pop().toLowerCase();
},
addInput(){
this.inputs.push('');
this.changeValue();

View File

@ -13,6 +13,7 @@ class Text extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('string');
$this->component = 'tainacan-text';
}
/**

View File

@ -13,6 +13,7 @@ class Textarea extends Field_Type {
// call field type constructor
parent::__construct();
parent::set_primitive_type('string');
$this->component = 'tainacan-textarea';
}
/**

View File

@ -224,20 +224,7 @@ class Collections extends Repository {
}
public function update($object, $new_values = null){
foreach ($new_values as $key => $value) {
try {
$set_ = 'set_' . $key;
$object->$set_( $value );
} catch (\Error $error){
return $error->getMessage();
}
}
if($object->validate()){
return $this->insert($object);
}
return $object->get_errors();
return $this->insert($object);
}
/**

View File

@ -14,6 +14,16 @@ class Fields extends Repository {
protected $default_metadata = 'default';
public $field_types = [];
/**
* Register specific hooks for field repository
*/
function __construct() {
parent::__construct();
add_action('tainacan_activated', array(&$this, 'register_core_fields'));
add_action('wp_trash_post', array( &$this, 'disable_delete_core_fields' ) );
add_action('before_delete_post', array( &$this, 'disable_delete_core_fields' ) );
}
public function get_map() {
return apply_filters('tainacan-get-map-'.$this->get_name(), [
@ -131,14 +141,23 @@ class Fields extends Repository {
'description'=> __('The collection ID', 'tainacan'),
//'validation' => ''
],
'accept_suggestion' => [
'accept_suggestion' => [
'map' => 'meta',
'title' => __('Field Value Accepts Suggestions', 'tainacan'),
'type' => 'bool',
'description'=> __('Allow the community suggest a different values for that field', 'tainacan'),
'default' => false,
'validation' => v::boolType()
]
],
'can_delete' => [
'map' => 'meta',
'title' => __('Can delete', 'tainacan'),
'type' => 'string',
'description'=> __('The field can be deleted', 'tainacan'),
'on_error' => __('Can delete is invalid', 'tainacan'),
'validation' => v::stringType()->in(['yes', 'no']), // yes or no. It cant be multiple if its collection_key
'default' => 'yes'
],
]);
}
@ -274,6 +293,8 @@ class Fields extends Repository {
* @throws \Exception
*/
public function fetch_by_collection(Entities\Collection $collection, $args = [], $output = null){
$this->register_core_fields();
$collection_id = $collection->get_id();
//get parent collections
@ -367,20 +388,7 @@ class Fields extends Repository {
* @throws \Exception
*/
public function update($object, $new_values = null){
foreach ($new_values as $key => $value) {
try {
$set_ = 'set_' . $key;
$object->$set_( $value );
} catch (\Error $error){
return $error->getMessage();
}
}
if($object->validate()){
return $this->insert($object);
}
return $object->get_errors();
return $this->insert($object);
}
public function delete($object){
@ -412,4 +420,73 @@ class Fields extends Repository {
return $this->field_types;
}
}
/**
* verify and, if is not registered, insert the default fields
*/
public function register_core_fields(){
$update_option = [];
$core_fields = get_option('tainacan_core_fields');
if( $core_fields ) {
return $core_fields;
}
// TODO: create a better way to retrieve this data
$data_core_fields = [
'core_title' => [
'name' => 'Title',
'description' => 'title',
'collection_id' => 'default',
'field_type' => 'Tainacan\Field_Types\Core_Title',
'can_delete' => 'no',
'status' => 'publish'
],
'core_description' => [
'name' => 'Description',
'description' => 'description',
'collection_id' => 'default',
'field_type' => 'Tainacan\Field_Types\Core_Description',
'can_delete' => 'no',
'status' => 'publish'
]
];
foreach ( $data_core_fields as $index => $data_core_field ) {
if( !$core_fields || !isset($core_fields[$index]) ){
$field = new Entities\Field();
foreach ($data_core_field as $attribute => $value) {
$set_ = 'set_' . $attribute;
$field->$set_( $value );
}
if ($field->validate()) {
$field = $this->insert($field);
$update_option[$index] = $field->get_id();
} else {
throw new \ErrorException('The entity wasn\'t validated.' . print_r( $field->get_errors(), true));
}
} else if( isset($core_fields[$index]) ) {
$update_option[$index] = $core_fields[$index];
}
}
update_option('tainacan_core_fields', $update_option);
return $update_option;
}
/**
* block user from remove core fields
*
* @param $post_id The post ID which is deleting
* @throws \ErrorException
*/
public function disable_delete_core_fields( $post_id ){
$core_fields = get_option('tainacan_core_fields');
if ( $core_fields && in_array( $post_id, $core_fields ) ) {
throw new \ErrorException('Core fields cannot be deleted.');
}
}
}

View File

@ -169,20 +169,7 @@ class Filters extends Repository {
}
public function update($object, $new_values = null){
foreach ($new_values as $key => $value) {
try {
$set_ = 'set_' . $key;
$object->$set_( $value );
} catch (\Error $error){
return $error->getMessage();
}
}
if($object->validate()){
return $this->insert($object);
}
return $object->get_errors();
return $this->insert($object);
}
/**

View File

@ -17,7 +17,7 @@ class Item_Metadata extends Repository {
if ($field_type->core) {
$this->save_core_field_value($item_metadata);
} else {
add_post_meta($item_metadata->item->get_id(), $item_metadata->field->get_id(), wp_slash( $item_metadata->get_value() ) );
update_post_meta($item_metadata->item->get_id(), $item_metadata->field->get_id(), wp_slash( $item_metadata->get_value() ) );
}
} else {
@ -38,34 +38,6 @@ class Item_Metadata extends Repository {
return new Entities\Item_Metadata_Entity($item_metadata->get_item(), $item_metadata->get_field());
}
public function update($item_metadata, $new_values = null){
$unique = !$item_metadata->is_multiple();
if ($unique) {
$field_type = $item_metadata->get_field()->get_field_type_object();
if ($field_type->core) {
$this->save_core_field_value($item_metadata);
} else {
update_post_meta($item_metadata->item->get_id(), $item_metadata->field->get_id(), wp_slash( $item_metadata->get_value() ) );
}
} else {
delete_post_meta($item_metadata->item->get_id(), $item_metadata->field->get_id());
if (is_array($item_metadata->get_value())){
$values = $item_metadata->get_value();
foreach ($values as $value){
update_post_meta($item_metadata->item->get_id(), $item_metadata->field->get_id(), wp_slash( $value ));
}
}
}
do_action('tainacan-update', $item_metadata);
do_action('tainacan-update-Item_Metadata_Entity', $item_metadata);
return new Entities\Item_Metadata_Entity($item_metadata->get_item(), $item_metadata->get_field());
}
/**
* Delete Item Field
*
@ -100,12 +72,14 @@ class Item_Metadata extends Repository {
}
}
/**
* Fetch Item Field objects related to an Item
*
* @param Entities\Item $object
* @return array
*/
/**
* Fetch Item Field objects related to an Item
*
* @param Entities\Item $object
*
* @return array
* @throws \Exception
*/
public function fetch($object, $output = null ){
if($object instanceof Entities\Item){
global $Tainacan_Items, $Tainacan_Fields;
@ -158,5 +132,11 @@ class Item_Metadata extends Repository {
public function get_map() { return []; }
public function get_default_properties($map) { return []; }
/**
* @param $object
*
* @return mixed
*/
public function update( $object, $new_values = null ) {}
}

View File

@ -232,20 +232,7 @@ class Items extends Repository {
}
public function update($object, $new_values = null){
foreach ($new_values as $key => $value) {
try {
$set_ = 'set_' . $key;
$object->$set_( $value );
} catch (\Error $error){
return $error->getMessage();
}
}
if($object->validate()){
return $this->insert($object);
}
return $object->get_errors();
return $this->insert($object);
}
/**

View File

@ -186,20 +186,7 @@ class Taxonomies extends Repository {
}
public function update($object, $new_values = null){
foreach ($new_values as $key => $value) {
try {
$set_ = 'set_' . $key;
$object->$set_( $value );
} catch (\Error $error){
return $error->getMessage();
}
}
if($object->validate()){
return $this->insert($object);
}
return $object->get_errors();
return $this->insert($object);
}
public function delete($args){

View File

@ -159,24 +159,8 @@ class Terms extends Repository {
}
}
public function update($object, $new_values = null){
$tax_name = $object[1];
$object = $object[0];
foreach ($new_values as $key => $value) {
try {
$set_ = 'set_' . $key;
$object->$set_( $value );
} catch (\Error $error){
return $error->getMessage();
}
}
if($object->validate()){
return new Entities\Term($this->insert($object), $tax_name);
}
return $object->get_errors();
public function update($object, $tax_name = null){
return new Entities\Term($this->insert($object), $tax_name);
}
public function delete($args){

View File

@ -24,18 +24,11 @@ export const eventBus = new Vue({
for (let eventElement of components){
eventElement.addEventListener('input', (event) => {
if (event.detail && event.detail[0] ){
const promisse = this.$store.dispatch('item/updateMetadata',
{ item_id: $(eventElement).attr("item_id"), field_id: $(eventElement).attr("field_id"), values: event.detail });
promisse.then( response => {
// eventElement.errorsMsg = JSON.stringify( [] );
// eventElement.value = response.value;
$(eventElement).val(response.value);
}, error => {
const field = this.errors.find(error => error.field_id === event.detail[0].field_id );
// eventElement.errorsMsg = JSON.stringify( field.error );
// eventElement.value = event.detail[0].values;
});
this.updateValue({
item_id: $(eventElement).attr("item_id"),
field_id: $(eventElement).attr("field_id"),
values: event.detail
})
}
});
}

View File

@ -1,14 +1,30 @@
import axios from '../../../axios/axios';
export const fetchItems = ({ commit, state }, collectionId) => {
axios.get('/collection/'+collectionId+'/items')
return new Promise ((resolve, reject) => {
axios.get('/collection/'+collectionId+'/items')
.then(res => {
let items = res.data;
commit('setItems', items);
resolve(items);
})
.catch(error => console.log( error ));
.catch(error => reject(error));
});
}
export const deleteItem = ({ commit }, item_id ) => {
return new Promise((resolve, reject) => {
axios.delete('/items/' + item_id)
.then( res => {
commit('deleteItem', { id: item_id });
resolve( res );
}).catch( err => {
reject( error );
});
});
};
export const fetchCollections = ({ commit }) => {
axios.get('/collections')
.then(res => {

View File

@ -2,6 +2,13 @@ export const setItems = ( state, items ) => {
state.items = items;
}
export const deleteItem = ( state, item ) => {
let index = state.items.findIndex(deletedItem => deletedItem.id === item.id);
if (index >= 0) {
state.items.splice(index, 1);
}
}
export const setCollections = (state, collections) => {
state.collections = collections;
}

View File

@ -19,9 +19,8 @@ export const sendField = ( { commit }, { item_id, field_id, values }) => {
export const updateMetadata = ({ commit }, { item_id, field_id, values }) => {
return new Promise((resolve, reject) => {
axios.patch(`/item/${item_id}/metadata/${field_id}`, {
values: values
values: values,
})
.then( res => {
let field = res.data;
@ -81,7 +80,7 @@ export const sendItem = ( { commit }, { collection_id, title, description, statu
};
export const updateItem = ({ commit }, { item_id, title, description, status }) => {
export const updateItem = ({ commit }, { item_id, title, description, status }) => {
return new Promise((resolve, reject) => {
axios.patch('/items/' + item_id, {
title: title,
@ -94,5 +93,5 @@ export const sendItem = ( { commit }, { collection_id, title, description, statu
reject( error.response );
});
});
};
});
};

View File

@ -6,7 +6,3 @@ export const getFields = state => {
export const getItem = state => {
return state.item;
}
export const getError = state => {
return state.error;
}

View File

@ -1,6 +1,5 @@
import Vue from 'vue';
export const setItem = ( state, item ) => {
state.item = item;
}

View File

@ -25,6 +25,13 @@ function tnc_enable_dev_wp_interface() {
//return defined('TNC_ENABLE_DEV_WP_INTERFACE') && true === TNC_ENABLE_DEV_WP_INTERFACE ? true : false;
}
// fire actions right after plugin is activate
function tainacan_activate() {
do_action( 'tainacan_activated' );
}
register_activation_hook( __FILE__, 'tainacan_activate' );
// TODO move it somewhere else?
require_once('admin/class-tainacan-admin.php');
global $Tainacan_Admin;

View File

@ -148,13 +148,17 @@ class TAINACAN_REST_Metadata_Controller extends TAINACAN_UnitApiTestCase {
'collection' => $collection,
'status' => 'publish',
'field_type' => 'Tainacan\Field_Types\Text',
'multiple' => 'yes'
),
true
);
$meta_values = json_encode(
array(
'values' => '19/01/2018'
'values' => array(
'19/01/2018',
'19/02/2018',
)
)
);
@ -172,9 +176,8 @@ class TAINACAN_REST_Metadata_Controller extends TAINACAN_UnitApiTestCase {
$this->assertEquals($field->get_id(), $field_updated['id']);
$metav = get_post_meta($item->get_id(), $field_updated['id'], true);
$this->assertEquals('19/01/2018', $metav);
$this->assertEquals('19/01/2018', $item_metadata_updated['value'][0]);
$this->assertEquals('19/02/2018', $item_metadata_updated['value'][1]);
#### UPDATE FIELD IN COLLECTION ####

View File

@ -0,0 +1,19 @@
<?php
namespace Tainacan\Tests;
/**
* @group queries
* **/
class TAINACAN_REST_Queries extends TAINACAN_UnitApiTestCase {
public function test_collections_queries(){
$this->tainacan_entity_factory->create_entity(
'collection',
[],
true
);
}
}
?>

View File

@ -153,7 +153,7 @@ class TAINACAN_REST_Terms extends TAINACAN_UnitApiTestCase {
);
$request->set_query_params([
'hide_empty' => false
'hideempty' => false
]);
$response = $this->server->dispatch($request);

View File

@ -167,7 +167,21 @@ class Fields extends TAINACAN_UnitTestCase {
);
$retrieve_metadata = $Tainacan_Fields->fetch_by_collection( $collection_son, [], 'OBJECT' );
$this->assertEquals( 4, sizeof( $retrieve_metadata ) );
// should return 6
$this->assertEquals( 6, sizeof( $retrieve_metadata ) );
}
function test_core_fields(){
global $Tainacan_Fields;
$core_fields_ids = $Tainacan_Fields->register_core_fields();
$this->expectException(\ErrorException::class);
if( $core_fields_ids ){
foreach( $core_fields_ids as $core_field_id ){
wp_trash_post( $core_field_id );
}
}
}
/**

View File

@ -225,7 +225,9 @@ class Item_Metadata extends TAINACAN_UnitTestCase {
$item_metadatas = $Tainacan_Item_Metadata->fetch($i, 'OBJECT');
$this->assertTrue(is_array($item_metadatas));
$this->assertEquals(1, sizeof($item_metadatas));
// notice for repository fields
$this->assertEquals(3, sizeof($item_metadatas));
$this->assertEquals('metadado', $item_metadatas[0]->get_field()->get_name());
}