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

This commit is contained in:
weryques 2018-03-27 09:34:16 -03:00
commit 33d10c6d51
14 changed files with 684 additions and 20 deletions

View File

@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}

View File

@ -100,6 +100,73 @@
</div>
</b-field>
<!-- Terms List -->
<b-field
:addons="false"
:label="$i18n.get('label_category_terms')">
<button
class="button is-secondary is-small"
type="button"
@click="addNewTerm()">
{{ $i18n.get('label_new_term') }}
</button>
<!-- Term item -->
<div
class="term-item"
:class="{
'not-sortable-item': term.term_id == 'new' || term.term_id == undefined || openedTermId != '' ,
'not-focusable-item': openedTermId == term.term_id
}"
v-for="(term, index) in termsList"
:key="index">
<span
class="term-name"
:class="{'is-danger': formWithErrors == term.term_id }">
{{ term.name }}
</span>
<span
v-if="term.term_id != undefined"
class="label-details">
<span
class="not-saved"
v-if="(editForms[term.term_id] != undefined && editForms[term.term_id].saved != true) || term.term_id == 'new'">
{{ $i18n.get('info_not_saved') }}
</span>
</span>
<span
class="loading-spinner"
v-if="term.term_id == undefined"/>
<span
class="controls"
v-if="term.term_id !== undefined || term.term_id !== 'new'">
<a @click.prevent="editTerm(term)">
<b-icon
type="is-gray"
icon="pencil"/>
</a>
<a @click.prevent="removeTerm(term)">
<b-icon
type="is-gray"
icon="delete"/>
</a>
</span>
<div v-if="openedTermId == term.term_id">
<term-edition-form
:category-id="categoryId"
@onEditionFinished="onTermEditionFinished()"
@onEditionCanceled="onTermEditionCanceled()"
@onErrorFound="formWithErrors = term.term_id"
:index="index"
:original-term="term"
:edited-term="editForms[term.term_id]"/>
</div>
</div>
</b-field>
<!-- Submit -->
<div class="field is-grouped form-submit">
<div class="control">
<button
@ -128,6 +195,7 @@
<script>
import { wpAjax } from "../../js/mixins";
import { mapActions, mapGetters } from 'vuex';
import TermEditionForm from './term-edition-form.vue'
import htmlToJSON from 'html-to-json';
export default {
@ -137,14 +205,14 @@
return {
categoryId: Number,
category: null,
isLoading: false,
isLoadingCategory: false,
isUpdatingSlug: false,
form: {
name: String,
status: String,
description: String,
slug: String,
allowInsert: String,
allowInsert: String
},
statusOptions: [{
value: 'publish',
@ -161,20 +229,41 @@
}],
editFormErrors: {},
formErrorMessage: '',
// Terms related
isLoadingTerms: false,
formWithErrors: '',
openedTermId: '',
editForms: [],
orderedTermsList: []
}
},
computed: {
termsList() {
//this.orderedTermsList = new Array();
//this.buildOrderedTermsList(0, 0);
return this.getTerms();
}
},
components: {
TermEditionForm
},
methods: {
...mapActions('category', [
'createCategory',
'updateCategory',
'fetchCategory',
'fetchOnlySlug',
'fetchTerms',
'updateTerm',
'deleteTerm'
]),
...mapGetters('category',[
'getCategory'
'getCategory',
'getTerms'
]),
onSubmit() {
this.isLoading = true;
this.isLoadingCategory = true;
let data = {
categoryId: this.categoryId,
@ -197,7 +286,7 @@
this.form.status = this.category.status;
this.allowInsert = this.category.allow_insert;
this.isLoading = false;
this.isLoadingCategory = false;
this.formErrorMessage = '';
this.editFormErrors = {};
@ -211,7 +300,7 @@
}
this.formErrorMessage = errors.error_message;
this.isLoading = false;
this.isLoadingCategory = false;
});
},
updateSlug(){
@ -242,7 +331,7 @@
.catch(errors => {
this.$console.error(errors);
this.isLoading = false;
this.isUpdatingSlug = false;
});
},
@ -262,7 +351,7 @@
},
createNewCategory() {
// Puts loading on Draft Category creation
this.isLoading = true;
this.isLoadingCategory = true;
// Creates draft Category
let data = {
@ -288,7 +377,7 @@
// Pre-fill status with publish to incentivate it
this.form.status = 'publish';
this.isLoading = false;
this.isLoadingCategory = false;
}
)
@ -303,6 +392,72 @@
labelNewTerms(){
return ( this.form.allowInsert === 'yes' ) ? this.$i18n.get('label_yes') : this.$i18n.get('label_no');
},
addNewTerm() {
let newTerm = {
categoryId: this.categoryId,
name: '',
description: '',
parent: 0,
term_id: 'new'
}
this.termsList.push(newTerm);
this.editTerm(newTerm);
},
editTerm(term) {
// Closing collapse
if (this.openedTermId == term.term_id) {
this.openedTermId = '';
// Opening collapse
} else {
this.openedTermId = term.term_id;
// First time opening
if (this.editForms[this.openedTermId] == undefined) {
this.editForms[this.openedTermId] = JSON.parse(JSON.stringify(term));
this.editForms[this.openedTermId].saved = true;
if (term.term_id == 'new')
this.editForms[this.openedTermId].saved = false;
}
}
},
removeTerm(term) {
this.$console.log(term);
this.deleteTerm({categoryId: this.categoryId, termId: term.term_id})
.then(() => {
})
.catch((error) => {
this.$console.log(error);
});
},
onTermEditionFinished() {
this.formWithErrors = '';
delete this.editForms[this.openedTermId];
this.openedTermId = '';
},
onTermEditionCanceled() {
this.formWithErrors = '';
delete this.editForms[this.openedTermId];
this.openedTermId = '';
},
buildOrderedTermsList(parentId, termDepth) {
for (let term of this.termsList) {
if (term['parent'] != parentId ) {
continue;
}
term.depth = termDepth;
this.orderedTermsList.push(term);
this.buildOrderedTermsList(term.term_id, termDepth + 1);
}
},
},
created(){
@ -310,7 +465,8 @@
this.createNewCategory();
} else if (this.$route.fullPath.split("/").pop() === "edit") {
this.isLoading = true;
this.isLoadingCategory = true;
this.isLoadingTerms = true;
// Obtains current category ID from URL
this.pathArray = this.$route.fullPath.split("/").reverse();
@ -326,16 +482,47 @@
this.form.status = this.category.status;
this.form.allowInsert = this.category.allow_insert;
this.isLoading = false;
this.isLoadingCategory = false;
});
this.fetchTerms(this.categoryId)
.then(() => {
// Fill this.form data with current data.
this.isLoadingCategory = false;
})
.catch((error) => {
this.$console.log(error);
});
}
},
beforeRouteLeave ( to, from, next ) {
let hasUnsavedForms = false;
for (let editForm in this.editForms) {
if (!this.editForms[editForm].saved)
hasUnsavedForms = true;
}
if ((this.openedTermId != '' && this.openedTermId != undefined) || hasUnsavedForms ) {
this.$dialog.confirm({
message: this.$i18n.get('info_warning_terms_not_saved'),
onConfirm: () => {
this.onEditionCanceled();
next();
},
cancelText: this.$i18n.get('cancel'),
confirmText: this.$i18n.get('continue'),
type: 'is-secondary'
});
} else {
next()
}
}
}
</script>
<style lang="scss" scoped>
@import "../../scss/_variables.scss";
.thumbnail-field {
width: 128px;
height: 128px;
@ -366,6 +553,102 @@
}
}
.loading-spinner {
animation: spinAround 500ms infinite linear;
border: 2px solid #dbdbdb;
border-radius: 290486px;
border-right-color: transparent;
border-top-color: transparent;
content: "";
display: inline-block;
height: 1em;
width: 1em;
}
.term-item {
background-color: white;
padding: 0.7em 0.9em;
margin: 4px;
min-height: 40px;
display: block;
position: relative;
cursor: grab;
.handle {
padding-right: 6em;
}
.grip-icon {
fill: $gray;
top: 2px;
position: relative;
}
.term-name {
text-overflow: ellipsis;
overflow-x: hidden;
white-space: nowrap;
font-weight: bold;
margin-left: 0.4em;
margin-right: 0.4em;
&.is-danger {
color: $danger !important;
}
}
.label-details {
font-weight: normal;
color: $gray;
}
.not-saved {
font-style: italic;
font-weight: bold;
color: $danger;
}
.controls {
position: absolute;
right: 5px;
top: 10px;
.icon {
bottom: 1px;
position: relative;
i, i:before { font-size: 20px; }
}
}
&.not-sortable-item, &.not-sortable-item:hover {
cursor: default;
background-color: white !important;
.handle .label-details, .handle .icon {
color: $gray !important;
}
}
&.not-focusable-item, &.not-focusable-item:hover {
cursor: default;
.term-name {
color: $primary;
}
.handle .label-details, .handle .icon {
color: $gray !important;
}
}
}
.term-item:hover:not(.not-sortable-item) {
background-color: $secondary;
border-color: $secondary;
color: white !important;
.label-details, .icon, .not-saved {
color: white !important;
}
.grip-icon {
fill: white;
}
}
</style>

View File

@ -145,7 +145,7 @@
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { mapActions } from 'vuex'
export default {
name: 'CollectionEditionForm',
@ -190,9 +190,6 @@ export default {
'sendAttachment',
'updateThumbnail'
]),
...mapGetters('collection',[
'getCollection'
]),
onSubmit() {
// Puts loading on Draft Collection creation
this.isLoading = true;

View File

@ -0,0 +1,218 @@
<template>
<form
id="termEditForm"
class="tainacan-form"
@submit.prevent="saveEdition(editForm)">
<b-field
:addons="false"
:type="formErrors['name'] != undefined ? 'is-danger' : ''"
:message="formErrors['name'] != undefined ? formErrors['name'] : ''">
<label class="label">
{{ $i18n.get('label_name') }}
<span
class="required-term-asterisk"
:class="formErrors['name'] != undefined ? 'is-danger' : ''">*</span>
<help-button
:title="$i18n.getHelperTitle('terms', 'name')"
:message="$i18n.getHelperMessage('terms', 'name')"/>
</label>
<b-input
v-model="editForm.name"
name="name"
@focus="clearErrors('name')"/>
</b-field>
<b-field
:addons="false"
:type="formErrors['description'] != undefined ? 'is-danger' : ''"
:message="formErrors['description'] != undefined ? formErrors['description'] : ''">
<label class="label">
{{ $i18n.get('label_description') }}
<help-button
:title="$i18n.getHelperTitle('terms', 'description')"
:message="$i18n.getHelperMessage('terms', 'description')"/>
</label>
<b-input
type="textarea"
name="description"
v-model="editForm.description"
@focus="clearErrors('description')" />
</b-field>
<b-field
:addons="false"
:type="formErrors['parent_term'] != undefined ? 'is-danger' : ''"
:message="formErrors['parent_term'] != undefined ? formErrors['parent_term'] : ''">
<label class="label">
{{ $i18n.get('label_parent_term') }}
<help-button
:title="$i18n.getHelperTitle('terms', 'parent_term')"
:message="$i18n.getHelperMessage('terms', 'parent_term')"/>
</label>
<b-select
id="parent_term_select"
v-model="editForm.parent"
:placeholder="$i18n.get('instruction_select_a_parent_term')">
<option
@focus="clearErrors('label_parent_term')"
id="tainacan-select-parent-term"
v-for="(parentTerm, index) in parentTermsList"
:key="index"
:value="editForm.parent.id">
{{ parentTerm.name }}
</option>
</b-select>
</b-field>
<div class="field is-grouped form-submit">
<div class="control">
<button
class="button is-outlined"
@click.prevent="cancelEdition()"
slot="trigger">
{{ $i18n.get('cancel') }}
</button>
</div>
<div class="control">
<button
class="button is-success"
type="submit">
{{ $i18n.get('save') }}
</button>
</div>
</div>
<p class="help is-danger">{{ formErrorMessage }}</p>
</form>
</template>
<script>
import { mapActions, mapGetters } from 'vuex';
export default {
name: 'TermEditionForm',
data(){
return {
editForm: {},
oldForm: {},
formErrors: {},
formErrorMessage: '',
closedByForm: false
}
},
props: {
index: '',
editedTerm: Object,
originalTerm: Object,
categoryId: ''
},
computed: {
parentTermsList() {
return this.getTerms();
}
},
created() {
this.editForm = this.editedTerm;
this.formErrors = this.editForm.formErrors != undefined ? this.editForm.formErrors : {};
this.formErrorMessage = this.editForm.formErrors != undefined ? this.editForm.formErrorMessage : '';
this.oldForm = JSON.parse(JSON.stringify(this.originalTerm));
},
beforeDestroy() {
if (this.closedByForm) {
this.editedTerm.saved = true;
} else {
this.oldForm.saved = this.editForm.saved;
if (JSON.stringify(this.editForm) != JSON.stringify(this.oldForm))
this.editedTerm.saved = false;
else
this.editedTerm.saved = true;
}
},
methods: {
...mapActions('category', [
'sendTerm',
'updateTerm'
]),
...mapGetters('category', [
'getTerms'
]),
saveEdition(term) {
if (term.term_id == 'new') {
this.sendTerm({
categoryId: this.categoryId,
index: this.index,
name: this.editForm.name,
description: this.editForm.description,
parent: this.editForm.parent
})
.then(() => {
this.editForm = {};
this.formErrors = {};
this.formErrorMessage = '';
this.closedByForm = true;
this.$emit('onEditionFinished');
})
.catch((error) => {
// for (let error of errors.errors) {
// for (let attribute of Object.keys(error))
// this.formErrors[attribute] = error[attribute];
// }
// this.formErrorMessage = errors.error_message;
this.$emit('onErrorFound');
this.$console.log(error);
// this.editForm.formErrors = this.formErrors;
// this.editForm.formErrorMessage = this.formErrorMessage;
});
} else {
this.updateTerm({categoryId: this.categoryId, termId: term.term_id, index: this.index, options: this.editForm})
.then(() => {
this.editForm = {};
this.formErrors = {};
this.formErrorMessage = '';
this.closedByForm = true;
this.$emit('onEditionFinished');
})
.catch((error) => {
// for (let error of errors.errors) {
// for (let attribute of Object.keys(error))
// this.formErrors[attribute] = error[attribute];
// }
// this.formErrorMessage = errors.error_message;
this.$emit('onErrorFound');
this.$console.log(error);
// this.editForm.formErrors = this.formErrors;
// this.editForm.formErrorMessage = this.formErrorMessage;
});
}
},
clearErrors(attribute) {
this.formErrors[attribute] = undefined;
},
cancelEdition() {
this.closedByForm = true;
this.$emit('onEditionCanceled');
},
}
}
</script>
<style lang="scss" scoped>
@import "../../scss/_variables.scss";
form {
padding: 1.0em 2.0em;
border-top: 1px solid $draggable-border-color;
border-bottom: 1px solid $draggable-border-color;
margin-top: 1.0em;
}
</style>

View File

@ -274,7 +274,6 @@ export default {
delete this.editForms[this.openedFieldId];
this.openedFieldId = '';
}
},
computed: {
availableFieldList() {

View File

@ -121,7 +121,8 @@ return [
'label_collection_fields' => __( 'Collection Fields', 'tainacan' ),
'label_collection_filters' => __( 'Collection Filters', 'tainacan' ),
'label_parent_term' => __( 'Parent Term', 'tainacan' ),
'label_add_new_term' => __( 'Add New Term', 'tainacan' ),
'label_new_term' => __( 'New Term', 'tainacan' ),
'label_category_terms' => __( 'Category Terms', 'tainacan' ),
// Instructions. More complex sentences to guide user and placeholders
'instruction_dragndrop_fields_collection' => __( 'Drag and drop Fields here to Collection.', 'tainacan' ),
@ -134,6 +135,7 @@ return [
'instruction_image_upload_box' => __( 'Drop an image here or click to upload.', 'tainacan' ),
'instruction_select_a_status' => __( 'Select a status:', 'tainacan' ),
'instruction_select_a_filter_type' => __( 'Select a filter type:', 'tainacan' ),
'instruction_select_a_parent_term' => __( 'Select a parent term:', 'tainacan' ),
// Info. Other feedback to user.
'info_name_is_required' => __( 'Name is required.', 'tainacan' ),
@ -163,6 +165,7 @@ return [
'info_warning_fields_not_saved' => __('Are you sure? There are fields not saved, changes will be lost.', 'tainacan'),
'info_warning_filters_not_saved' => __('Are you sure? There are filters not saved, changes will be lost.', 'tainacan'),
'info_no_description_provided' => __('No description provided.', 'tainacan'),
'info_warning_terms_not_saved' => __('Are you sure? There are terms not saved, changes will be lost.', 'tainacan'),
// Tainacan Field Types
'tainacan-text' => __( 'Text', 'tainacan' ),

View File

@ -248,9 +248,26 @@ class TAINACAN_REST_Controller extends WP_REST_Controller {
private function prepare_meta($mapped, $request, $query, $mapped_v, $args){
$request_meta_query = $request[$mapped];
// if the meta/date/taxquery has a root relation
if( isset( $request_meta_query['relation']) )
$args[ $mapped_v ]['relation'] = $request_meta_query['relation'];
// If is a multidimensional array (array of array)
if($this->contains_array($request_meta_query, $query)) {
foreach ( $request_meta_query as $index1 => $a ) {
// handle core field
if( array_key_exists("key", $a) ){
$field = new Tainacan\Entities\Field($a['key']);
if( strpos( $field->get_field_type(), 'Core') !== false ){
$args[ 'post_title_in' ] = [
'relation' => ( isset( $request_meta_query['relation']) ) ? $request_meta_query['relation'] : 'AND' ,
'value' => ( is_array( $a['value'] ) ) ? $a['value'] : [$a['value']]
];
continue;
}
}
foreach ( $query as $mapped_meta => $meta_v ) {
if ( isset( $a[ $meta_v ] ) ) {
$args[ $mapped_v ][ $index1 ][ $meta_v ] = $request[ $mapped ][ $index1 ][ $meta_v ];

View File

@ -118,7 +118,6 @@
},
mountQuery( search ){
let query = []
query['search'] = search;
if( this.searchFields.length > 0){
query['metaquery'] = [];
const metaquery = query['metaquery'];
@ -131,6 +130,8 @@
}
query['metaquery'] = metaquery;
} else {
query['search'] = search;
}
return query;
}

View File

@ -641,6 +641,30 @@ class Fields extends Repository {
// Clear the result cache
$wpdb->flush();
$field = new Entities\Field( $field_id );
// handle core titles
if( strpos( $field->get_field_type(), 'Core') !== false ){
$collection = new Entities\Collection( $collection_id );
$Tainacan_Items = \Tainacan\Repositories\Items::getInstance();
$items = $Tainacan_Items->fetch( [], $collection, 'OBJECT');
$return = [];
foreach ($items as $item) {
if( strpos( $field->get_field_type(), 'Core_Title') !== false ){
$return[] = [ 'item_id' => $item->get_id(), 'field_id' => $field_id, 'mvalue' => $item->get_title() ];
} else {
$return[] = [ 'item_id' => $item->get_id(), 'field_id' => $field_id, 'mvalue' => $item->get_description() ];
}
}
if (!empty($return)) {
$results[] = $return;
}
return $results;
}
$item_post_type = "%%{$collection_id}_item";
$collection = new Entities\Collection($collection_id);

View File

@ -25,6 +25,7 @@ class Items extends Repository {
protected function __construct()
{
parent::__construct();
add_filter( 'posts_where', array(&$this, 'title_in_posts_where'), 10, 2 );
}
public function get_map() {
@ -311,4 +312,25 @@ class Items extends Repository {
return new Entities\Item( wp_trash_post( $args[0] ) );
}
/**
* allow wp query filter post by array of titles
*
* @param $where
* @param $wp_query
* @return string
*/
public function title_in_posts_where( $where, &$wp_query ) {
global $wpdb;
if ( $post_title_in = $wp_query->get( 'post_title_in' ) ) {
if(is_array( $post_title_in ) && isset( $post_title_in['value']) ){
$quotes = [];
foreach ($post_title_in['value'] as $title) {
$quotes[] = "'" . esc_sql( $wpdb->esc_like( $title ) ). "'";
}
}
$where .= ' '.$post_title_in['relation'].' ' . $wpdb->posts . '.post_title IN ( ' .implode(',', $quotes ) . ')';
}
return $where;
}
}

View File

@ -1,5 +1,6 @@
import axios from '../../../axios/axios'
// CATEGORIES
export const createCategory = ({commit}, category) => {
return new Promise(( resolve, reject ) => {
axios.tainacan.post('/taxonomies', {
@ -114,4 +115,69 @@ export const fetchCategoryName = ({ commit }, categoryId) => {
reject(error)
})
});
};
};
// CATEGORY TERMS
export const sendTerm = ({commit}, { categoryId, index, name, description, parent }) => {
return new Promise(( resolve, reject ) => {
axios.tainacan.post('/taxonomy/' + categoryId + '/terms/', {
name: name,
description: description,
parent: parent
})
.then( res => {
let term = res.data;
commit('setSingleTerm', term);
resolve( term );
})
.catch(error => {
console.log(error);
reject( error );
});
});
};
export const deleteTerm = ({ commit }, { categoryId, termId }) => {
return new Promise(( resolve, reject ) => {
axios.tainacan.delete(`/taxonomy/${categoryId}/terms/${termId}?permanently=${true}`)
.then(res => {
let term = res.data;
commit('deleteTerm', term);
resolve( term );
})
.catch(error => {
reject( error )
});
});
};
export const updateTerm = ({ commit }, { categoryId, termId, index, options }) => {
return new Promise(( resolve, reject ) => {
axios.tainacan.patch('/taxonomy/' + categoryId + '/terms/' + termId, options)
.then( res => {
let term = res.data;
console.log(term);
commit('setSingleTerm', term);
resolve( term );
})
.catch(error => {
console.log(error);
reject(error)
//reject({ error_message: error['response']['data'].error_message, errors: error['response']['data'].errors });
});
});
};
export const fetchTerms = ({ commit }, categoryId ) => {
return new Promise((resolve, reject) => {
axios.tainacan.get(`/taxonomy/${categoryId}/terms/`)
.then(res => {
let terms = res.data;
commit('setTerms', terms);
resolve( terms );
})
.catch(error => {
reject( error );
});
});
};

View File

@ -8,4 +8,8 @@ export const getCategories = state => {
export const getCategoryName = state => {
return state.categoryName;
};
export const getTerms = state => {
return state.terms;
};

View File

@ -6,6 +6,7 @@ const state = {
categories: [],
category: {},
categoryName: String,
terms: []
};
export default {

View File

@ -1,3 +1,4 @@
// CATEGORIES
export const setCategory = (state, category) => {
state.category = category;
};
@ -16,4 +17,27 @@ export const deleteCategory = ( state, category ) => {
if (index >= 0) {
state.categories.splice(index, 1);
}
};
// CATEGORY TERMS
export const setSingleTerm = (state, term) => {
let index = state.terms.findIndex(updatedTerm => updatedTerm.id === term.id);
if ( index >= 0){
Vue.set( state.terms, index, term );
} else {
state.terms.push( term );
}
};
export const setTerms = (state, terms) => {
state.terms = terms;
};
export const deleteTerm = ( state, term ) => {
let index = state.terms.findIndex(deletedTerm => deletedTerm.id === term.id);
if (index >= 0) {
state.terms.splice(index, 1);
}
};