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

This commit is contained in:
mateuswetah 2018-06-15 17:41:04 -03:00
commit 44a1120225
29 changed files with 1028 additions and 200 deletions

View File

@ -60,6 +60,7 @@
:class="{'tag-container-border': Object.keys(advancedSearchQuery).length > 1}"
class="field column is-12">
<b-field
:style="{'padding': '0.3rem 0 0 0'}"
grouped
group-multiline>
<div
@ -94,6 +95,7 @@
</div>
</div>
</div>
<pre>{{ advancedSearchQuery }}</pre>
</div>
</template>
@ -149,10 +151,10 @@
advancedSearch: true,
};
},
addValueToAdvancedSearchQuery: _.debounce(function(value, type, relation) {
addValueToAdvancedSearchQuery: _.debounce(function(value, type, searchCriteria) {
let vm = this;
vm.addToAdvancedSearchQuery(value, type, relation);
vm.addToAdvancedSearchQuery(value, type, searchCriteria);
}, 900),
searchAdvanced(){
if(Object.keys(this.advancedSearchQuery).length > 2){
@ -165,30 +167,49 @@
this.$eventBusSearch.$emit('searchAdvanced', this.advancedSearchQuery);
},
addToAdvancedSearchQuery(value, type, relation){
if(this.advancedSearchQuery.hasOwnProperty(relation)){
//if(this.advancedSearchQuery[relation].compare === 'IN'){
//this.advancedSearchQuery[relation][type] = value.split(' ');
//} else {
if(type == 'compare' && (this.advancedSearchQuery[relation]['compare'] == 'IN' ||
this.advancedSearchQuery[relation]['compare'] == 'NOT IN')){
this.advancedSearchQuery[relation].value.push(value);
addToAdvancedSearchQuery(value, type, searchCriteria){
if(this.advancedSearchQuery.hasOwnProperty(searchCriteria)){
if(type == 'value' && (this.advancedSearchQuery[searchCriteria]['compare'] == 'IN' ||
this.advancedSearchQuery[searchCriteria]['compare'] == 'NOT IN')){
if(value.includes(';')){
this.advancedSearchQuery[searchCriteria].value = value.split(';');
} else {
this.advancedSearchQuery[searchCriteria].value.pop();
if(!this.advancedSearchQuery[searchCriteria].value.includes(value)){
this.advancedSearchQuery[searchCriteria].value.push(value);
}
}
} else {
this.advancedSearchQuery[relation][type] = value;
if(type == 'compare' &&
this.advancedSearchQuery[searchCriteria].compare &&
!Array.isArray(this.advancedSearchQuery[searchCriteria].value) &&
(this.advancedSearchQuery.compare != 'IN' && value == 'IN' ||
this.advancedSearchQuery.compare != 'NOT IN' && value == 'NOT IN')){
let valueAsArray = this.advancedSearchQuery[searchCriteria].value.split(' ');
this.advancedSearchQuery[searchCriteria].value = valueAsArray;
} else if(type == 'compare' &&
this.advancedSearchQuery[searchCriteria].compare &&
(this.advancedSearchQuery.compare != '=' && value == '=' ||
this.advancedSearchQuery.compare != '!=' && value == '!=')){
let valueAsString = this.advancedSearchQuery[searchCriteria].value.toString().replace(/,/g, ' ');
this.advancedSearchQuery[searchCriteria].value = valueAsString;
}
this.$set(this.advancedSearchQuery[searchCriteria], `${type}`, value);
}
//}
} else {
if(type == 'compare' && (value == 'IN' || value == 'NOT IN')){
this.advancedSearchQuery = Object.assign({}, this.advancedSearchQuery, {
[`${relation}`]: {
[`${searchCriteria}`]: {
[`${type}`]: [value],
}
});
} else {
this.advancedSearchQuery = Object.assign({}, this.advancedSearchQuery, {
[`${relation}`]: {
[`${searchCriteria}`]: {
[`${type}`]: value,
}
});

View File

@ -12,13 +12,6 @@
<b-field :addons="false">
<label class="section-label">{{ $i18n.get('label_header_image') }}</label>
<div class="header-field">
<a
class="button is-rounred is-secondary"
id="button-edit-header-image"
:aria-label="$i18n.get('label_button_edit_header_image')"
@click="headerImageMediaFrame.openFrame($event)">
<b-icon icon="pencil" />
</a>
<figure class="image">
<span
v-if="collection.header_image == undefined || collection.header_image == false"
@ -29,7 +22,15 @@
</figure>
<div class="header-buttons-row">
<a
id="button-delete"
class="button is-rounded is-secondary"
id="button-edit-header-image"
:aria-label="$i18n.get('label_button_edit_header_image')"
@click="headerImageMediaFrame.openFrame($event)">
<b-icon icon="pencil" />
</a>
<a
class="button is-rounded is-secondary"
id="button-delete-header-image"
:aria-label="$i18n.get('label_button_delete_thumb')"
@click="deleteHeaderImage()">
<b-icon icon="delete" />
@ -45,13 +46,7 @@
<b-field :addons="false">
<label class="section-label">{{ $i18n.get('label_thumbnail') }}</label>
<div class="thumbnail-field">
<a
class="button is-rounred is-secondary"
id="button-edit-thumbnail"
:aria-label="$i18n.get('label_button_edit_thumb')"
@click.prevent="thumbnailMediaFrame.openFrame($event)">
<b-icon icon="pencil" />
</a>
<figure class="image">
<span
v-if="collection.thumbnail.thumb == undefined || collection.thumbnail.thumb == false"
@ -63,7 +58,15 @@
</figure>
<div class="thumbnail-buttons-row">
<a
id="button-delete"
class="button is-rounded is-secondary"
id="button-edit-thumbnail"
:aria-label="$i18n.get('label_button_edit_thumb')"
@click.prevent="thumbnailMediaFrame.openFrame($event)">
<b-icon icon="pencil" />
</a>
<a
class="button is-rounded is-secondary"
id="button-delete-header-image"
:aria-label="$i18n.get('label_button_delete_thumb')"
@click="deleteThumbnail()">
<b-icon icon="delete" />
@ -753,13 +756,16 @@ export default {
line-height: 1.2em;
}
#button-edit-thumbnail, #button-edit-header-image {
#button-edit-thumbnail,
#button-edit-header-image,
#button-delete-thumbnail,
#button-delete-header-image {
border-radius: 100px !important;
height: 40px !important;
width: 40px !important;
bottom: -40px;
z-index: 99;
margin-left: 16px !important;
.icon {
display: inherit;
@ -772,6 +778,21 @@ export default {
img {
padding: 20px;
}
.image-placeholder {
position: relative;
left: 45%;
bottom: -100px;
font-size: 0.8rem;
font-weight: bold;
z-index: 99;
text-align: center;
color: gray;
}
.header-buttons-row {
text-align: right;
top: -42px;
position: relative;
}
}
.thumbnail-field {
max-height: 208px;
@ -790,31 +811,19 @@ export default {
padding: 20px;
}
.image-placeholder {
position: absolute;
margin-left: 10px;
margin-right: 10px;
bottom: 50%;
position: relative;
left: 40px;
bottom: -100px;
font-size: 0.8rem;
font-weight: bold;
z-index: 99;
text-align: center;
color: gray;
}
.thumbnail-buttons-row {
visibility: hidden;
display: inline-block;
position: relative;
top: -20px;
background-color: rgba(255, 255, 255, 0.9);
padding: 2px 8px;
border-radius: 0px 0px 0px 4px;
left: 88px;
}
&:hover {
.thumbnail-buttons-row {
visibility: visible;
}
left: 80px;
bottom: -136px;
}
}
.selected-cover-page {

View File

@ -235,7 +235,7 @@
<div class="section-box section-thumbnail">
<div class="thumbnail-field">
<a
class="button is-rounred is-secondary"
class="button is-rounded is-secondary"
id="button-edit-thumbnail"
:aria-label="$i18n.get('label_button_edit_thumb')"
@click.prevent="thumbnailMediaFrame.openFrame($event)">

View File

@ -12,7 +12,7 @@
:label="$i18n.get('label_header_image')">
<div class="thumbnail-field">
<a
class="button is-rounred is-secondary"
class="button is-rounded is-secondary"
id="button-edit-thumbnail"
:aria-label="$i18n.get('label_button_edit_header_image')"
@click="headerImageMediaFrame.openFrame($event)">

View File

@ -361,7 +361,7 @@ export default {
.selection-control {
padding: 6px 0px 0px 13px;
padding: 6px 0px 0px 12px;
background: white;
height: 40px;

View File

@ -263,7 +263,7 @@
column.metadatum !== 'row_actions' &&
column.metadatum !== 'row_creation' &&
column.metadatum !== 'row_author'"
v-html="renderMetadata(item.metadata, column)"/>
v-html="item.metadata != undefined ? renderMetadata(item.metadata, column) : ''"/>
<span v-if="column.metadatum == 'row_thumbnail'">
<img
@ -472,7 +472,7 @@ export default {
.selection-control {
padding: 6px 0px 0px 13px;
padding: 6px 0px 0px 12px;
background: white;
height: 40px;

View File

@ -269,7 +269,7 @@
.selection-control {
padding: 6px 0px 0px 13px;
padding: 6px 0px 0px 12px;
background: white;
height: 40px;

View File

@ -108,8 +108,16 @@ UserPrefsPlugin.install = function (Vue, options = {}) {
'events_per_page': 12,
'order': 'DESC',
'order_by': {
id: 'creation_date',
slug: 'creation_date',
name: 'Creation Date'
},
'view_mode': 'table',
'admin_view_mode': 'table',
'fetch_only': {
0: 'thumbnail',
1: 'creation_date',
2: 'author_name',
meta: []
}
},
init() {
@ -139,7 +147,7 @@ UserPrefsPlugin.install = function (Vue, options = {}) {
if (prefs[key]) {
resolve( prefs[key] );
} else {
reject('Key ' + key + 'does not exists in user preference.');
reject('Key ' + key + ' does not exists in user preference.');
}
})
.catch(error => {

View File

@ -134,11 +134,11 @@
{{ $i18n.get('add_items_external_source') + ' (Not ready)' }}
</b-dropdown-item>
</b-dropdown>
</div>
<!-- Displayed Metadata Dropdown -->
<div
v-if="!isOnTheme || registeredViewModes[viewMode].dynamic_metadata"
v-if="!isOnTheme || (registeredViewModes[viewMode] != undefined && registeredViewModes[viewMode].dynamic_metadata)"
class="search-control-item">
<b-dropdown
ref="displayedMetadataDropdown"
@ -182,6 +182,18 @@
@input="onChangeOrderBy($event)"
:placeholder="$i18n.get('label_sorting')">
<option
v-for="metadatum in tableMetadata"
v-if="
metadatum.slug === 'creation_date' || (
metadatum.metadata_type_object &&
metadatum.metadata_type_object.related_mapped_prop == 'title'
)"
:value="metadatum"
:key="metadatum.slug">
{{ metadatum.name }}
</option>
<!-- Once we have sorting by metadata we can use this -->
<!-- <option
v-for="metadatum in tableMetadata"
v-if="
metadatum.slug === 'creation_date' ||
@ -196,7 +208,7 @@
:value="metadatum"
:key="metadatum.slug">
{{ metadatum.name }}
</option>
</option> -->
</b-select>
<button
:disabled="totalItems <= 0"
@ -242,7 +254,7 @@
class="search-control-item">
<b-field>
<b-dropdown
v-model="adminViewMode"
@change="onChangeAdminViewMode($event)"
:mobile-modal="false"
position="is-bottom-left"
:aria-label="$i18n.get('label_view_mode')">
@ -275,7 +287,6 @@
</div>
</div>
<!-- ADVANCED SEARCH -->
<div
v-if="openAdvancedSearch">
@ -295,7 +306,6 @@
:metadata-list="metadata" />
</div>
<!-- --------------- -->
<!-- STATUS TABS, only on Admin -------- -->
@ -371,7 +381,7 @@
:displayed-metadata="tableMetadata"
:items="items"
:is-loading="isLoadingItems"
:is="registeredViewModes[viewMode].component"/>
:is="registeredViewModes[viewMode] != undefined ? registeredViewModes[viewMode].component : ''"/>
<!-- Empty Placeholder (only used in Admin) -->
<section
@ -399,17 +409,16 @@
</section>
<!-- Pagination -->
<!-- When advanced search -->
<pagination
v-if="totalItems > 0 &&
(!isOnTheme || registeredViewModes[viewMode].show_pagination) &&
(!isOnTheme || (registeredViewModes[viewMode] != undefined && registeredViewModes[viewMode].show_pagination)) &&
advancedSearchResults"/>
<!-- Regular -->
<pagination
v-else-if="totalItems > 0 &&
(!isOnTheme || registeredViewModes[viewMode].show_pagination) &&
(!isOnTheme || (registeredViewModes[viewMode] != undefined && registeredViewModes[viewMode].show_pagination)) &&
!openAdvancedSearch"/>
</div>
</div>
@ -442,7 +451,6 @@
isHeaderShrinked: false,
localTableMetadata: [],
registeredViewModes: tainacan_plugin.registered_view_modes,
adminViewMode: 'table',
openAdvancedSearch: false,
advancedSearchResults: false,
}
@ -477,6 +485,9 @@
viewMode() {
return this.getViewMode();
},
adminViewMode() {
return this.getAdminViewMode();
},
orderBy() {
return this.getOrderBy();
},
@ -524,7 +535,8 @@
'getOrderBy',
'getOrder',
'getViewMode',
'getTotalItems'
'getTotalItems',
'getAdminViewMode'
]),
updateSearch() {
this.$eventBusSearch.setSearchQuery(this.futureSearchQuery);
@ -541,6 +553,9 @@
onChangeViewMode(viewMode) {
this.$eventBusSearch.setViewMode(viewMode);
},
onChangeAdminViewMode(adminViewMode) {
this.$eventBusSearch.setAdminViewMode(adminViewMode);
},
onChangeDisplayedMetadata() {
let fetchOnlyMetadatumIds = [];
@ -557,16 +572,19 @@
let creationDateMetadatum = this.localTableMetadata.find(metadatum => metadatum.slug == 'creation_date');
let authorNameMetadatum = this.localTableMetadata.find(metadatum => metadatum.slug == 'author_name');
// Updates Search
this.$eventBusSearch.addFetchOnly({
'0': thumbnailMetadatum.display ? 'thumbnail' : null,
'meta': fetchOnlyMetadatumIds,
'1': creationDateMetadatum.display ? 'creation_date' : null,
'2': authorNameMetadatum.display ? 'author_name': null
});
// Closes dropdown
this.$refs.displayedMetadataDropdown.toggle();
},
prepareMetadataAndFilters() {
this.isLoadingFilters = true;
this.fetchFilters({
@ -579,22 +597,28 @@
.catch(() => this.isLoadingFilters = false);
this.isLoadingMetadata = true;
// Processing is done inside a local variable
let metadata = [];
this.fetchMetadata({
collectionId: this.collectionId,
isRepositoryLevel: this.isRepositoryLevel,
isContextEdit: !this.isOnTheme
isContextEdit: false
})
.then(() => {
// Loads user prefs object as we'll need to check if there's something configured by user
let prefsFetchOnly = !this.isRepositoryLevel ? 'fetch_only_' + this.collectionId : 'fetch_only';
let prefsFetchOnlyObject = this.$userPrefs.get(prefsFetchOnly);
let thumbnailMetadatumDisplay = prefsFetchOnlyObject != undefined ? (prefsFetchOnlyObject['0'] != null) : true;
metadata.push({
name: this.$i18n.get('label_thumbnail'),
metadatum: 'row_thumbnail',
metadata_type: undefined,
slug: 'thumbnail',
id: undefined,
display: true
display: thumbnailMetadatumDisplay
});
let fetchOnlyMetadatumIds = [];
@ -604,11 +628,22 @@
let display;
// Deciding display based on collection settings
if (metadatum.display == 'no')
display = false;
else if (metadatum.display == 'yes')
display = true;
// // Deciding display based on user prefs
// if (prefsFetchOnlyObject != undefined &&
// prefsFetchOnlyObject.meta != undefined) {
// let index = prefsFetchOnlyObject.meta.findIndex(metadatumId => metadatumId == metadatum.id);
// if (index >= 0)
// display = true;
// else
// display = false;
// }
metadata.push(
{
name: metadatum.name,
@ -625,13 +660,16 @@
}
}
let creationDateMetadatumDisplay = prefsFetchOnlyObject != undefined ? (prefsFetchOnlyObject['1'] != null) : true;
let authorNameMetadatumDisplay = prefsFetchOnlyObject != undefined ? (prefsFetchOnlyObject['2'] != null) : true;
metadata.push({
name: this.$i18n.get('label_creation_date'),
metadatum: 'row_creation',
metadata_type: undefined,
slug: 'creation_date',
id: undefined,
display: true
display: creationDateMetadatumDisplay
});
metadata.push({
name: this.$i18n.get('label_created_by'),
@ -639,22 +677,14 @@
metadata_type: undefined,
slug: 'author_name',
id: undefined,
display: true
display: authorNameMetadatumDisplay
});
// this.prefTableMetadata = this.tableMetadata;
// this.$userPrefs.get('table_columns_' + this.collectionId)
// .then((value) => {
// this.prefTableMetadata = value;
// })
// .catch((error) => {
// this.$userPrefs.set('table_columns_' + this.collectionId, this.prefTableMetadata, null);
// });
this.$eventBusSearch.addFetchOnly({
'0': 'thumbnail',
'0': (thumbnailMetadatumDisplay ? 'thumbnail' : null),
'meta': fetchOnlyMetadatumIds,
'1': 'creation_date',
'2': 'author_name'
'1': (creationDateMetadatumDisplay ? 'creation_date' : null),
'2': (authorNameMetadatumDisplay ? 'author_name' : null)
});
this.isLoadingMetadata = false;
this.tableMetadata = metadata;
@ -665,7 +695,7 @@
}
},
created() {
this.isOnTheme = (this.$route.name === null);
this.isRepositoryLevel = (this.collectionId === undefined);
@ -689,16 +719,16 @@
/* This condition is to prevent a incorrect fetch by filter or metadata when we come from items
* at collection level to items page at repository level
*/
if (this.collectionId === to.params.collectionId) {
if (this.isOnTheme || this.collectionId === to.params.collectionId) {
this.prepareMetadataAndFilters();
}
});
this.$eventBusSearch.setViewMode(this.defaultViewMode);
if(this.$router.query && this.$router.query.metaquery && this.$router.query.metaquery.advancedSearch) {
this.openAdvancedSearch = this.$router.query.advancedSearch;
this.openAdvancedSearch = this.$router.query.metaquery.advancedSearch;
}
},
mounted() {
@ -709,6 +739,22 @@
this.prepareMetadataAndFilters();
this.localTableMetadata = JSON.parse(JSON.stringify(this.tableMetadata));
// Setting initial view mode on Theme
if (this.isOnTheme) {
let prefsViewMode = !this.isRepositoryLevel ? 'view_mode_' + this.collectionId : 'view_mode';
if (this.$userPrefs.get(prefsViewMode) == undefined)
this.$eventBusSearch.setInitialViewMode(this.defaultViewMode);
else
this.$eventBusSearch.setInitialViewMode(this.$userPrefs.get(prefsViewMode));
} else {
let prefsAdminViewMode = !this.isRepositoryLevel ? 'admin_view_mode_' + this.collectionId : 'admin_view_mode';
if (this.$userPrefs.get(prefsAdminViewMode) == undefined)
this.$eventBusSearch.setInitialAdminViewMode('table');
else
this.$eventBusSearch.setInitialAdminViewMode(this.$userPrefs.get(prefsAdminViewMode));
}
// Watch Scroll for shrinking header, only on Admin at collection level
if (!this.isRepositoryLevel && !this.isOnTheme) {
document.getElementById('items-list-area').addEventListener('scroll', ($event) => {
@ -900,8 +946,8 @@
}
.table-container {
padding-left: 8.333333%;
padding-right: 8.333333%;
padding-left: 4.166666667%;
padding-right: 4.166666667%;
min-height: 200px;
//height: calc(100% - 82px);
}

View File

@ -33,7 +33,7 @@
<div>
<taxonomies-list
:is-loading="isLoading"
:total-taxonomies="total"
:total="total"
:page="page"
:taxonomies-per-page="taxonomiesPerPage"
:taxonomies="taxonomies"/>
@ -106,7 +106,7 @@
</template>
<script>
import List from "../../components/lists/taxonomies-list.vue";
import TaxonomiesList from "../../components/lists/taxonomies-list.vue";
import { mapActions, mapGetters } from 'vuex';
//import moment from 'moment'
@ -122,7 +122,7 @@
}
},
components: {
List
TaxonomiesList
},
methods: {
...mapActions('taxonomy', [
@ -184,7 +184,7 @@
this.$userPrefs.set('taxonomies_per_page', 12);
}
this.loadCategories();
this.load();
}
}
</script>

View File

@ -9,6 +9,9 @@
<script>
export default {
name: "ThemeItemsList",
created() {
this.$userPrefs.init();
}
}
</script>
@ -298,11 +301,6 @@ export default {
border-bottom: 0;
}
.table-container {
padding-left: 4.166666667%;
padding-right: 4.166666667%;
}
#items-list-area {
width: 100%;
overflow-y: unset;

View File

@ -0,0 +1,281 @@
<?php
namespace Tainacan\API\EndPoints;
use \Tainacan\API\REST_Controller;
use Tainacan\Repositories;
use Tainacan\Entities;
/**
* Represents the Importers REST Controller
*
* */
class REST_Importers_Controller extends REST_Controller {
private $collections_repository;
private $collection;
/**
* REST_Importers_Controller constructor.
* Define the namespace, rest base and instantiate your attributes.
*/
public function __construct(){
$this->rest_base = 'importers';
parent::__construct();
add_action('init', array(&$this, 'init_objects'), 11);
}
/**
* Initialize objects after post_type register
*/
public function init_objects() {
//$this->collections_repository = Repositories\Collections::get_instance();
//$this->collection = new Entities\Collection();
}
/**
* Register the collections route and their endpoints
*/
public function register_routes(){
register_rest_route($this->namespace, '/' . $this->rest_base, array(
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array($this, 'create_item'),
'permission_callback' => array($this, 'import_permissions_check'),
'args' => [
'importer_slug' => [
'type' => 'string',
'description' => __( 'The slug of the importer to be initialized', 'tainacan' ),
]
],
),
));
register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P<session_id>[0-9a-f]+)', array(
array(
'methods' => \WP_REST_Server::EDITABLE,
'callback' => array($this, 'update_item'),
'permission_callback' => array($this, 'import_permissions_check'),
'args' => [
'url' => [
'type' => 'string',
'description' => __( 'The URL to be used by the importer', 'tainacan' ),
],
'collection' => [
'type' => 'array',
'description' => __( 'The array describing the destination collectino as expected by the importer', 'tainacan' ),
],
'options' => [
'type' => 'array',
'description' => __( 'The importer options', 'tainacan' ),
]
],
),
));
register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P<session_id>[0-9a-f]+)/file', array(
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array($this, 'add_file'),
'permission_callback' => array($this, 'import_permissions_check'),
),
));
register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P<session_id>[0-9a-f]+)/source_info', array(
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array($this, 'source_info'),
'permission_callback' => array($this, 'import_permissions_check'),
),
));
register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P<session_id>[0-9a-f]+)/run', array(
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array($this, 'run'),
'permission_callback' => array($this, 'import_permissions_check'),
),
));
}
/**
*
* @param \WP_REST_Request $request
*
* @return bool|\WP_Error
* @throws \Exception
*/
public function import_permissions_check($request){
// TODO
return true;
}
/**
* Creates a new instance of the desired importer and returns its ID
*
* @param \WP_REST_Request $request
*
* @return array|\WP_Error|\WP_REST_Response
*/
public function create_item( $request ) {
$body = json_decode($request->get_body(), true);
if(empty($body)){
return new \WP_REST_Response([
'error_message' => __('Body can not be empty.', 'tainacan'),
], 400);
}
$slug = $body['importer_slug'];
global $Tainacan_Importer_Handler;
if ($object = $Tainacan_Importer_Handler->initialize_importer($slug)) {
$response = $object->_to_Array();
return new \WP_REST_Response($response, 201);
} else {
return new \WP_REST_Response([
'error_message' => __('Importer not found', 'tainacan'),
], 400);
}
}
/**
* Update a collection
*
* @param \WP_REST_Request $request
*
* @return string|\WP_Error|\WP_REST_Response
*/
public function update_item( $request ) {
$session_id = $request['session_id'];
$body = json_decode($request->get_body(), true);
if(!empty($body)){
$attributes = [];
foreach ($body as $att => $value){
$attributes[$att] = $value;
}
$importer = $_SESSION['tainacan_importer'][$session_id];
if($importer) {
foreach ($body as $att => $value){
$method = 'set_' . $att;
if (method_exists($importer, $method)) {
$importer->$method($value);
}
}
$response = $importer->_to_Array();
return new \WP_REST_Response( $response, 200 );
}
return new \WP_REST_Response([
'error_message' => __('Importer Session not found', 'tainacan' ),
'session_id' => $session_id
], 400);
}
return new \WP_REST_Response([
'error_message' => __('The body can not be empty', 'tainacan'),
'body' => $body
], 400);
}
public function source_info() {
$session_id = $request['session_id'];
$importer = $_SESSION['tainacan_importer'][$session_id];
if(!$importer) {
return new \WP_REST_Response([
'error_message' => __('Importer Session not found', 'tainacan' ),
'session_id' => $session_id
], 400);
}
$response = [
'source_metadata' => false,
'source_total_items' => false
];
if ( method_exists($importer, 'get_source_metadata') ) {
$response['source_metadata'] = $importer->get_source_metadata();
}
if ( method_exists($importer, 'get_source_number_of_items') ) {
$response['source_total_items'] = $importer->get_source_number_of_items();
}
return new \WP_REST_Response( $response, 200 );
}
public function add_file() {
$session_id = $request['session_id'];
$importer = $_SESSION['tainacan_importer'][$session_id];
if(!$importer) {
return new \WP_REST_Response([
'error_message' => __('Importer Session not found', 'tainacan' ),
'session_id' => $session_id
], 400);
}
$files = $request->get_file_params();
$headers = $request->get_headers();
if ( $importer->add_file($files['file']) ) {
$response = $importer->_to_Array();
return new \WP_REST_Response( $response, 200 );
} else {
return new \WP_REST_Response([
'error_message' => __('Failed to upload file', 'tainacan' ),
'session_id' => $session_id
], 400);
}
}
public function run() {
$session_id = $request['session_id'];
$importer = $_SESSION['tainacan_importer'][$session_id];
if(!$importer) {
return new \WP_REST_Response([
'error_message' => __('Importer Session not found', 'tainacan' ),
'session_id' => $session_id
], 400);
}
global $Tainacan_Importer_Handler;
$process = $Tainacan_Importer_Handler->add_to_queue($importer);
$response = [
'bg_process_id' => $process->get_id()
];
return new \WP_REST_Response( $response, 200 );
}
}
?>

View File

@ -13,6 +13,7 @@ $rest_item_metadata_controller = new \Tainacan\API\EndPoints\REST_Item_Metadat
$rest_logs_controller = new \Tainacan\API\EndPoints\REST_Logs_Controller();
$rest_metadata_types_controller = new \Tainacan\API\EndPoints\REST_Metadata_Types_Controller();
$rest_filter_types_controller = new \Tainacan\API\EndPoints\REST_Filter_Types_Controller();
$rest_importers_controller = new \Tainacan\API\EndPoints\REST_Importers_Controller();
new \Tainacan\API\EndPoints\REST_Export_Controller();
new \Tainacan\API\EndPoints\REST_Metadatum_Mappers_Controller();
// Add here other endpoints imports

View File

@ -31,6 +31,12 @@ abstract class Background_Process extends \WP_Background_Process {
* @var string
*/
protected $table = '';
/**
* ID of the process in the database
* @var false|int
*/
protected $ID = false;
/**
* Prefix
@ -60,6 +66,10 @@ abstract class Background_Process extends \WP_Background_Process {
global $wpdb;
$this->table = $wpdb->prefix . 'tnc_bg_process';
}
public function get_id() {
return $this->ID;
}
/**
@ -81,6 +91,7 @@ abstract class Background_Process extends \WP_Background_Process {
'queued_on' => date('Y-m-d H:i:s')
]
);
$this->ID = $wpdb->insert_id;
}
return $this;

View File

@ -79,7 +79,8 @@ class Taxonomy extends Entity {
);
$tax_cpts = [];
$tax_cpts = [];
if (is_array($this->get_collections())){
foreach ($this->get_collections() as $tax_col){
$tax_cpts[] = $tax_col->get_db_identifier();

View File

@ -55,18 +55,20 @@ class CSV extends Importer {
$processedItem[ $header ] = $values[ $index ];
}
$this->set_progress_current($index+1);
return $processedItem;
}
/**
* @inheritdoc
*/
public function get_progress_total_from_source(){
$file = new \SplFileObject( $this->tmp_file, 'r' );
$file->seek(PHP_INT_MAX);
// -1 removing header
return $this->total_items = $file->key() - 1;
public function get_source_number_of_items(){
if (isset($this->tmp_file) && file_exists($this->tmp_file)) {
$file = new \SplFileObject( $this->tmp_file, 'r' );
$file->seek(PHP_INT_MAX);
// -1 removing header
return $this->total_items = $file->key() - 1;
}
return false;
}
}

View File

@ -4,17 +4,68 @@ namespace Tainacan;
class Importer_Handler {
private $registered_importers = [];
function __construct() {
$this->bg_importer = new Background_Importer();
add_action('init', array(&$this, 'init'));
}
public function init() {
$this->register_importer([
'slug' => 'csv',
'class_name' => '\Tainacan\Importer\CSV'
]);
do_action('tainacan_register_importers');
}
function add_to_queue($importer_object) {
function add_to_queue(\Tainacan\Importer\Importer $importer_object) {
$data = $importer_object->_to_Array();
$this->bg_importer->data($data)->save()->dispatch();
$importer_object = $this->bg_importer->data($data)->save()->dispatch();
return $importer_object;
}
/**
* Register Importer
*
* @param array $importer
* [
* 'slug' => 'example-importer',
* 'class_name' => '\Tainacan\Importer\Test_Importer'
* ]
*/
public function register_importer(array $importer) {
$this->registered_importers[$importer['slug']] = $importer;
}
public function unregister_importer($importer_slug) {
unset($this->registered_importers[$importer_slug]);
}
public function get_registered_importers() {
return $this->registered_importers;
}
public function get_importer($importer_slug) {
$importers = $this->get_registered_importers();
if (isset($importers[$importer_slug])) {
return $importers[$importer_slug];
}
return null;
}
public function initialize_importer($importer_slug) {
$importer = $this->get_importer($importer_slug);
if ( is_array($importer) && isset($importer['class_name']) && class_exists($importer['class_name']) ) {
return new $importer['class_name']();
}
return false;
}

View File

@ -47,17 +47,6 @@ abstract class Importer {
protected $manual_collection = true;
/**
* The total number of iterations to be imported.
*
* if not possible to calculate, inform 0 (zero) and no progress bar will be displayed.
*
* @var int
*/
protected $progress_total;
protected $progress_current;
/**
* This array holds the structure that the default step 'process_collections' will handle.
*
@ -191,7 +180,7 @@ abstract class Importer {
}
public function _to_Array() {
$return = [];
$return = ['id' => $this->get_id()];
foreach ($this->array_attributes as $attr) {
$method = 'get_' . $attr;
$return[$attr] = $this->$method();
@ -279,14 +268,6 @@ abstract class Importer {
$this->tmp_file = $filepath;
}
public function get_progress_current() {
return $this->progress_current;
}
public function set_progress_current($value) {
$this->progress_current = $value;
}
public function get_collections() {
return $this->collections;
}
@ -332,22 +313,6 @@ abstract class Importer {
return $this->steps;
}
/**
* return the total progress number to calculate progress
*
* @return int Total of items
*/
public function get_progress_total() {
if ( !isset( $this->progress_total ) ) {
if ( method_exists($this, 'get_progress_total_from_source') ) {
$this->progress_total = $this->get_progress_total_from_source();
} else {
$this->progress_total = 0;
}
}
return $this->progress_total;
}
private function get_transients() {
return $this->transients;
@ -565,13 +530,13 @@ abstract class Importer {
/**
* Method implemented by the child importer class to return the total number of interations the importer must run
* Method implemented by the child importer class to return the total number of items that will be imported
*
* Used to build the progress bar
*
* @return int
*/
public function get_progress_total_from_source() {}
public function get_source_number_of_items() {}

View File

@ -22,10 +22,6 @@ class Old_Tainacan extends Importer{
'name' => 'Create Collections',
'callback' => 'create_collections'
],
[
'name' => 'Link relationship metadata',
'callback' => 'link_relationships'
],
[
'name' => 'Import Items',
'callback' => 'process_collections'
@ -77,8 +73,8 @@ class Old_Tainacan extends Importer{
if ($tax->validate()) {
$tax = $this->tax_repo->insert($tax);
$this->add_transient('tax_' . $term->term_id . '_id', $tax->get_id());
$this->add_transient('tax_' . $term->term_id . '_name', $tax->get_name());
$this->add_transient('tax_' . $taxonomy->term_id . '_id', $tax->get_id());
$this->add_transient('tax_' . $taxonomy->term_id . '_name', $tax->get_name());
if (isset($taxonomy->children) && $tax) {
$this->add_all_terms($tax, $taxonomy->children);
@ -119,35 +115,94 @@ class Old_Tainacan extends Importer{
public function create_collections(){
foreach ($this->fetch_collections() as $collection) {
$map = [];
if ( isset($collection->post_title) && $collection->post_status === 'publish') {
//TODO: insert collection and its metadata
$collection_id = $this->create_collection( $collection );
foreach( $this->get_collection_metadata( $collection->ID ) as $metadatum_old ) {
$metadatum_id = $this->create_metadata( $metadatum_old, $collection_id );
$map[$metadatum_id] = $metadatum_old->id;
}
$this->add_collection([
'id' => $collection_id,
'map' => $map,
'total_items' => $this->get_total_items_from_source( $collection->ID ),
'source_id' => $collection->ID,
'items' => $this->get_all_items( $collection->ID )
]);
}
}
}
/**
* Method implemented by the child importer class to proccess each item
* @return int
*/
public function link_relationships(){
$args = [];
foreach( $this->metadata_repo->fetch($args, 'OBJECT' ) as $metadatum ){
//var_dump($metadatum->get_metadata_type());
}
// TODO: get all imported relationships and find the collection target
}
/**
* Method implemented by the child importer class to proccess each item
* @return int
*/
public function process_item( $index, $collection_id ){
var_dump($collection_id['items'][$index]);
}
/**
* Method implemented by the child importer class to return the number of items to be imported
* @return int
*/
public function get_progress_total_from_source(){
public function get_total_items_from_source( $collection_id ) {
$info = wp_remote_get( $this->get_url() . $this->tainacan_api_address . "/collections/".$collection_id."/items" );
$info = json_decode($info['body']);
if( isset($info->found_items) ){
return $info->found_items;
} else {
return 0;
}
}
/**
* Method implemented by the child importer class to return the number of items to be imported
* Method that retrieves all items
* @return int
*/
public function get_source_metadata(){
public function get_all_items( $collection_id ) {
$page = 1;
$items = [];
$info = wp_remote_get( $this->get_url() . $this->tainacan_api_address . "/collections/".$collection_id."/items?includeMetadata=1&filter[items_per_page]=50&filter[page]=" . $page );
$info = json_decode($info['body']);
while( isset($info->items) && count( $info->items ) > 0 ){
foreach( $info->items as $item){
$items[] = $item;
}
$page++;
$info = wp_remote_get( $this->get_url() . $this->tainacan_api_address . "/collections/".$collection_id."/items?includeMetadata=1&filter[items_per_page]=50&filter[page]=" . $page );
$info = json_decode($info['body']);
}
return $items;
}
// AUX functions
@ -191,7 +246,7 @@ class Old_Tainacan extends Importer{
*/
protected function get_taxonomies(){
$taxonomies_link = $this->get_url() . $this->tainacan_api_address . "/taxonomies";
$taxonomies_link = $this->get_url() . $this->tainacan_api_address . "/categories";
$taxonomies = wp_remote_get($taxonomies_link);
$taxonomies_array = $this->decode_request($taxonomies);
@ -211,6 +266,31 @@ class Old_Tainacan extends Importer{
return ($repo_meta_array) ? $repo_meta_array : [];
}
/**
* return all metadata from collection
* @param $collection_id
* @return array
*/
protected function get_collection_metadata( $collection_id ){
$metadata = [];
$metadata_link = $this->get_url() . $this->tainacan_api_address . "/collections/".$collection_id."/metadata?includeMetadata=1";
$collection = wp_remote_get($metadata_link);
$collection_tabs = $this->decode_request($collection);
if($collection_tabs){
foreach ($collection_tabs as $tab) {
if($tab->{'tab-properties'}){
$metadata = array_merge($metadata, $tab->{'tab-properties'});
}
}
}
return ($metadata) ? $metadata : [];
}
/**
* create recursively the terms from tainacan OLD
*
@ -269,9 +349,9 @@ class Old_Tainacan extends Importer{
$newMetadatum->set_name($name);
$newMetadatum->set_metadata_type('Tainacan\Metadata_Types\\'.$type);
$newMetadatum->set_parent( (isset($collection_id)) ? $collection_id : 'default');
$newMetadatum->set_collection_id( (isset($collection_id)) ? $collection_id : 'default');
if(strcmp($type, "Taxonomy") === 0){
if(strcmp($type, "Category") === 0){
$taxonomy_id = $meta->metadata->taxonomy;
$related_taxonomy = $this->get_transient('tax_' . $taxonomy_id . '_id');
@ -280,14 +360,13 @@ class Old_Tainacan extends Importer{
}
} else if(strcmp($type, "Relationship") === 0){
$relation_id = $meta->metadata->object_taxonomy_id;
$relation_id = $meta->metadata->object_category_id;
$related_taxonomy = $this->get_transient('tax_' . $relation_id . '_id');
$related_name = $this->get_transient('tax_' . $relation_id . '_name');
if(isset($related_taxonomy)){
$newMetadatum->set_metadata_type_options(['collection_id' => $related_taxonomy]);
}
} else if(strcmp($type, "Compound") === 0){
if( isset( $meta->metadata->children ) ){
@ -318,10 +397,11 @@ class Old_Tainacan extends Importer{
}
if($newMetadatum->validate()){
$inserted_metadata = $this->meta_repo->insert( $newMetadatum );
$inserted_metadata = $this->metadata_repo->insert( $newMetadatum );
if(isset( $related_name) )
if(isset( $related_name) ){
$this->add_transient('relation_' . $inserted_metadata->get_id() . '_name', $related_name);
}
return $inserted_metadata->get_id();
} else{
@ -331,6 +411,34 @@ class Old_Tainacan extends Importer{
return false;
}
}
/**
* create the collection in tainacan
*
* @return int $metadatum_id
*/
protected function create_collection( $node_collection ){
$new_collection = new Entities\Collection();
$new_collection->set_name($node_collection->post_title);
$new_collection->set_status('publish');
$new_collection->validate();
if($new_collection->validate()){
$new_collection =$this->col_repo->insert($new_collection);
if( $new_collection )
$this->add_transient('collection_' . $node_collection->ID . '_name', $new_collection->get_id());
return $new_collection->get_id();
} else{
$this->add_error_log('Error creating collection ' . $node_collection->post_title );
$this->add_error_log($new_collection->get_errors());
$this->abort();
return false;
}
}
/**
* Define the class to create in new Tainacan

View File

@ -35,11 +35,15 @@ export default {
},
watch: {
'$route' (to, from) {
this.collectionId = !this.$route.params.collectionId ? this.$route.params.collectionId : parseInt(this.$route.params.collectionId);
// Should set Collection ID from URL only when in admin.
if (this.$route.name == 'CollectionItemsPage' || this.$route.name == 'ItemsPage')
this.collectionId = !this.$route.params.collectionId ? this.$route.params.collectionId : parseInt(this.$route.params.collectionId);
// Fills the URL with apropriate default values in case a query is not passed
if (this.$route.name == null || this.$route.name == undefined || this.$route.name == 'CollectionItemsPage' || this.$route.name == 'ItemsPage') {
// Items Per Page
if (this.$route.query.perpage == undefined || to.params.collectionId != from.params.collectionId) {
let perPageKey = (this.collectionId != undefined ? 'items_per_page_' + this.collectionId : 'items_per_page');
let perPageValue = this.$userPrefs.get(perPageKey);
@ -51,10 +55,25 @@ export default {
this.$userPrefs.set(perPageKey, 12);
}
}
// Page
if (this.$route.query.paged == undefined || to.params.collectionId != from.params.collectionId)
this.$route.query.paged = 1;
if (this.$route.query.order == undefined || to.params.collectionId != from.params.collectionId)
this.$route.query.order = 'DESC';
// Order (ASC, DESC)
if (this.$route.query.order == undefined || to.params.collectionId != from.params.collectionId) {
let orderKey = (this.collectionId != undefined ? 'order_' + this.collectionId : 'order');
let orderValue = this.$userPrefs.get(orderKey);
if (orderValue)
this.$route.query.order = orderValue;
else {
this.$route.query.order = 'DESC';
this.$userPrefs.set(orderKey, 'DESC');
}
}
// Order By (required extra work to deal with custom metadata ordering)
if (this.$route.query.orderby == undefined || to.params.collectionId != from.params.collectionId) {
let orderByKey = (this.collectionId != undefined ? 'order_by_' + this.collectionId : 'order_by');
let orderBy = this.$userPrefs.get(orderByKey);
@ -81,13 +100,46 @@ export default {
} else {
this.$route.query.orderby = 'date';
this.$userPrefs.set(orderByKey, {
id: 'creation_date',
slug: 'creation_date',
name: this.$i18n.get('label_creation_date')
});
}).catch(() => { });
}
}
if(this.$route.query.metaquery && this.$route.query.metaquery.advancedSearch){
// Theme View Modes
if ((this.$route.name == null || this.$route.name == undefined ) &&
this.$route.name != 'CollectionItemsPage' && this.$route.name != 'ItemsPage' &&
(this.$route.query.view_mode == undefined || to.params.collectionId != from.params.collectionId)
) {
let viewModeKey = (this.collectionId != undefined ? 'view_mode_' + this.collectionId : 'view_mode');
let viewModeValue = this.$userPrefs.get(viewModeKey);
if (viewModeValue)
this.$route.query.view_mode = viewModeValue;
else {
this.$route.query.view_mode = 'table';
this.$userPrefs.set(viewModeKey, 'table');
}
}
// Admin View Modes
if (this.$route.name != null && this.$route.name != undefined &&
(this.$route.name == 'CollectionItemsPage' || this.$route.name == 'ItemsPage') &&
(this.$route.query.admin_view_mode == undefined || to.params.collectionId != from.params.collectionId)
) {
let adminViewModeKey = (this.collectionId != undefined ? 'admin_view_mode_' + this.collectionId : 'admin_view_mode');
let adminViewModeValue = this.$userPrefs.get(adminViewModeKey);
if (adminViewModeValue)
this.$route.query.admin_view_mode = adminViewModeValue;
else {
this.$route.query.admin_view_mode = 'table';
this.$userPrefs.set(adminViewModeKey, 'table');
}
}
// Advanced Search
if (this.$route.query.metaquery && this.$route.query.metaquery.advancedSearch){
this.$store.dispatch('search/set_advanced_query', this.$route.query.metaquery);
} else {
this.$store.dispatch('search/set_postquery', this.$route.query);
@ -117,8 +169,14 @@ export default {
this.updateURLQueries();
},
addFetchOnly( metadatum ){
let prefsFetchOnly = this.collectionId != undefined ? 'fetch_only_' + this.collectionId : 'fetch_only';
if(this.$userPrefs.get(prefsFetchOnly) != metadatum) {
this.$userPrefs.set(prefsFetchOnly, metadatum)
.catch(() => {});
}
this.$store.dispatch('search/add_fetchonly', metadatum );
this.updateURLQueries();
this.updateURLQueries();
},
removeFetchOnlyMeta( metadatum ){
this.$store.dispatch('search/remove_fetchonly_meta', metadatum );
@ -144,22 +202,31 @@ export default {
},
setItemsPerPage(itemsPerPage) {
let prefsPerPage = this.collectionId != undefined ? 'items_per_page_' + this.collectionId : 'items_per_page';
this.$userPrefs.set(prefsPerPage, itemsPerPage)
.catch(() => { this.$console.log("Error settings user prefs for items per page.") });
if(this.$userPrefs.get(prefsPerPage) != itemsPerPage) {
this.$userPrefs.set(prefsPerPage, itemsPerPage)
.catch(() => {});
}
this.$store.dispatch('search/setItemsPerPage', itemsPerPage);
this.updateURLQueries();
},
setOrderBy(newOrderBy) {
setOrderBy(orderBy) {
let prefsOrderBy = this.collectionId != undefined ? 'order_by_' + this.collectionId : 'order_by';
this.$userPrefs.set(prefsOrderBy, newOrderBy)
.catch(() => { this.$console.log("Error settings user prefs for order by.") });
this.$store.dispatch('search/setOrderBy', newOrderBy);
if(this.$userPrefs.get(prefsOrderBy) != orderBy) {
this.$userPrefs.set(prefsOrderBy, orderBy)
.catch(() => {});
}
this.$store.dispatch('search/setOrderBy', orderBy);
this.updateURLQueries();
},
setOrder(newOrder) {
this.$store.dispatch('search/setOrder', newOrder);
setOrder(order) {
let prefsOrder = this.collectionId != undefined ? 'order_' + this.collectionId : 'order';
if(this.$userPrefs.get(prefsOrder) != order) {
this.$userPrefs.set(prefsOrder, order)
.catch(() => {});
}
this.$store.dispatch('search/setOrder', order);
this.updateURLQueries();
},
setStatus(status) {
@ -171,10 +238,35 @@ export default {
this.updateURLQueries();
},
setViewMode(viewMode) {
let prefsViewMode = this.collectionId != undefined ? 'view_mode_' + this.collectionId : 'view_mode';
if(this.$userPrefs.get(prefsViewMode) != viewMode) {
this.$userPrefs.set(prefsViewMode, viewMode)
.catch(() => {});
}
this.$store.dispatch('search/setViewMode', viewMode);
this.updateURLQueries();
},
setAdminViewMode(adminViewMode) {
let prefsAdminViewMode = this.collectionId != undefined ? 'admin_view_mode_' + this.collectionId : 'admin_view_mode';
if(this.$userPrefs.get(prefsAdminViewMode) != adminViewMode) {
this.$userPrefs.set(prefsAdminViewMode, adminViewMode)
.catch(() => { });
}
this.$store.dispatch('search/setAdminViewMode', adminViewMode);
this.updateURLQueries();
},
setInitialViewMode(viewMode) {
this.$store.dispatch('search/setViewMode', viewMode);
this.updateURLQueries();
},
setInitialAdminViewMode(adminViewMode) {
this.$store.dispatch('search/setAdminViewMode', adminViewMode);
this.updateURLQueries();
},
updateURLQueries(isAdvancedSearch) {
this.$router.push({query: {}});
this.$route.meta['advancedSearch'] = isAdvancedSearch;
this.$router.push({query: this.$store.getters['search/getPostQuery']});
@ -183,11 +275,12 @@ export default {
this.$store.dispatch('search/set_postquery', this.$route.query);
},
loadItems(to) {
// Forces fetch_only to be filled before any search happens
if (this.$store.getters['search/getFetchOnly'] == undefined) {
this.$emit( 'hasToPrepareMetadataAndFilters', to);
} else {
this.$emit( 'isLoadingItems', true);
this.$store.dispatch('collection/fetchItems', {
@ -195,6 +288,7 @@ export default {
'isOnTheme': (this.$route.name == null)
})
.then((res) => {
this.$emit( 'isLoadingItems', false);
this.$emit( 'hasFiltered', res.hasFiltered);

View File

@ -46,17 +46,20 @@ export const fetchItems = ({ rootGetters, dispatch, commit }, { collectionId, is
}
if (!isOnTheme){
if (postQueries.view_mode != undefined)
postQueries.view_mode = null;
endpoint = endpoint + 'context=edit&'
}
console.log(postQueries);
} else {
if (postQueries.admin_view_mode != undefined)
postQueries.admin_view_mode = null;
}
axios.tainacan.get(endpoint+query)
.then(res => {
let items = res.data;
let viewModeObject = tainacan_plugin.registered_view_modes[postQueries.view_mode];
if (isOnTheme && viewModeObject != undefined && viewModeObject.type == 'template') {
commit('setItemsListTemplate', items);
resolve({'itemsListTemplate': items, 'total': res.headers['x-wp-total'], hasFiltered: hasFiltered, advancedSearchResults: advancedSearchResults});

View File

@ -106,4 +106,9 @@ export const setSearchQuery = ({ commit }, searchQuery ) => {
// Set ViewMode (view_mode)
export const setViewMode = ({ commit }, viewMode ) => {
commit('setViewMode', viewMode );
};
// Set AdminViewMode (admin_view_mode)
export const setAdminViewMode = ({ commit }, adminViewMode ) => {
commit('setAdminViewMode', adminViewMode );
};

View File

@ -52,6 +52,9 @@ export const getViewMode = state => {
return state.postquery.view_mode;
};
export const getAdminViewMode = state => {
return state.postquery.admin_view_mode;
};
export const getFetchOnly = state => {
return state.postquery.fetch_only;
};

View File

@ -19,7 +19,8 @@ const state = {
'1': 'creation_date',
'2': 'author_name'
},
view_mode: 'table'
view_mode: 'table',
admin_view_mode: 'table'
},
totalItems: 0
};

View File

@ -127,4 +127,8 @@ export const setStatus = ( state, status ) => {
export const setViewMode = ( state, viewMode ) => {
state.postquery.view_mode = viewMode;
};
export const setAdminViewMode = ( state, adminViewMode ) => {
state.postquery.admin_view_mode = adminViewMode;
};

View File

@ -36,8 +36,6 @@
v-for="(column, index) in displayedMetadata"
v-if="column.display"
:label="column.name"
:aria-label="(column.metadatum != 'row_thumbnail' && column.metadatum != 'row_creation' && column.metadatum != 'row_author')
? column.name + '' + (item.metadata ? item.metadata[column.slug].value_as_string : '') : ''"
class="column-default-width"
:class="{
'thumbnail-cell': column.metadatum == 'row_thumbnail',

View File

@ -0,0 +1,65 @@
<?php
namespace Tainacan\Tests;
/**
* @group api
*/
class TAINACAN_REST_Importers_Controller extends TAINACAN_UnitApiTestCase {
public function test_create(){
$params = json_encode([
'importer_slug' => 'csv'
]);
$request = new \WP_REST_Request('POST', $this->namespace . '/importers');
$request->set_body($params);
$response = $this->server->dispatch($request);
$this->assertEquals(201, $response->get_status());
$data = $response->get_data();
$this->assertTrue( isset($data['id']) );
$this->assertTrue( is_string($data['id']) );
}
public function test_update() {
$importer = new \Tainacan\Importer\CSV();
$session_id = $importer->get_id();
$params = json_encode([
'url' => 'http://test.com',
'options' => ['delimiter' => ';']
]);
$request = new \WP_REST_Request('PATCH', $this->namespace . '/importers/' . $session_id);
$request->set_body($params);
$response = $this->server->dispatch($request);
$data = $response->get_data();
$this->assertEquals(200, $response->get_status());
$__importer = $_SESSION['tainacan_importer'][$session_id];
$this->assertEquals('http://test.com', $__importer->get_url());
$this->assertEquals(';', $__importer->get_option('delimiter'));
$this->assertEquals($__importer->get_url(), $data['url']);
}
}
?>

View File

@ -178,6 +178,159 @@ class TAINACAN_REST_Items_Controller extends TAINACAN_UnitApiTestCase {
$this->assertNotEquals($item->get_title(), $data['title']);
$this->assertEquals('SCRUM e XP', $data['title']);
}
function test_fetch_only() {
$collection = $this->tainacan_entity_factory->create_entity(
'collection',
array(
'name' => 'Agile',
'description' => 'Agile methods',
'status' => 'publish'
),
true
);
$private_meta = $this->tainacan_entity_factory->create_entity(
'metadatum',
array(
'name' => 'private_meta',
'status' => 'publish',
'collection' => $collection,
'metadata_type' => 'Tainacan\Metadata_Types\Text',
'status' => 'private'
),
true
);
$public_meta = $this->tainacan_entity_factory->create_entity(
'metadatum',
array(
'name' => 'public_meta',
'status' => 'publish',
'collection' => $collection,
'metadata_type' => 'Tainacan\Metadata_Types\Text',
'status' => 'publish'
),
true
);
$discarded = $this->tainacan_entity_factory->create_entity(
'metadatum',
array(
'name' => 'discarded',
'status' => 'publish',
'collection' => $collection,
'metadata_type' => 'Tainacan\Metadata_Types\Text',
'status' => 'publish'
),
true
);
$item1 = $this->tainacan_entity_factory->create_entity(
'item',
array(
'title' => 'Lean Startup',
'description' => 'Um processo ágil de criação de novos negócios.',
'collection' => $collection,
'status' => 'publish'
),
true
);
$item2 = $this->tainacan_entity_factory->create_entity(
'item',
array(
'title' => 'SCRUM',
'description' => 'Um framework ágil para gerenciamento de tarefas.',
'collection' => $collection,
'status' => 'publish'
),
true
);
$itemMetaRepo = \Tainacan\Repositories\Item_Metadata::get_instance();
$newMeta = new \Tainacan\Entities\Item_Metadata_Entity($item1, $public_meta);
$newMeta->set_value('test');
$newMeta->validate();
$itemMetaRepo->insert($newMeta);
$newMeta = new \Tainacan\Entities\Item_Metadata_Entity($item1, $private_meta);
$newMeta->set_value('test');
$newMeta->validate();
$itemMetaRepo->insert($newMeta);
$newMeta = new \Tainacan\Entities\Item_Metadata_Entity($item1, $discarded);
$newMeta->set_value('test');
$newMeta->validate();
$itemMetaRepo->insert($newMeta);
$newMeta = new \Tainacan\Entities\Item_Metadata_Entity($item2, $public_meta);
$newMeta->set_value('test');
$newMeta->validate();
$itemMetaRepo->insert($newMeta);
$newMeta = new \Tainacan\Entities\Item_Metadata_Entity($item2, $private_meta);
$newMeta->set_value('test');
$newMeta->validate();
$itemMetaRepo->insert($newMeta);
$newMeta = new \Tainacan\Entities\Item_Metadata_Entity($item2, $discarded);
$newMeta->set_value('test');
$newMeta->validate();
$itemMetaRepo->insert($newMeta);
$attributes = [
'fetch_only' => [
'meta' => [
$public_meta->get_id(),
$private_meta->get_id()
]
],
];
// First without fetch only
$request = new \WP_REST_Request(
'GET', $this->namespace . '/items'
);
$response = $this->server->dispatch($request);
$data = $response->get_data();
$this->assertEquals( 2, sizeof($data) );
$this->assertEquals( 5, sizeof($data[0]['metadata']) );
// Fetch only as admin
$request = new \WP_REST_Request(
'GET', $this->namespace . '/items'
);
$request->set_query_params($attributes);
$response = $this->server->dispatch($request);
$data = $response->get_data();
$this->assertEquals( 2, sizeof($data) );
$this->assertEquals( 2, sizeof($data[0]['metadata']) );
////
$new_user = $this->factory()->user->create(array( 'role' => 'subscriber' ));
wp_set_current_user($new_user);
// Fetch only as subscriber
$request = new \WP_REST_Request(
'GET', $this->namespace . '/items'
);
$request->set_query_params($attributes);
$response = $this->server->dispatch($request);
$data = $response->get_data();
$this->assertEquals( 2, sizeof($data) );
$this->assertEquals( 1, sizeof($data[0]['metadata']) );
$this->assertEquals( 'public_meta', $data[0]['metadata']['public_meta']['name'] );
}
}
?>

View File

@ -175,7 +175,7 @@ class ImporterTests extends TAINACAN_UnitTestCase {
$this->assertTrue( !empty( $_SESSION['tainacan_importer'][$id]->get_tmp_file() ) );
// count size of csv
$this->assertEquals( 5, $_SESSION['tainacan_importer'][$id]->get_progress_total_from_source() );
$this->assertEquals( 5, $_SESSION['tainacan_importer'][$id]->get_source_number_of_items() );
// get metadata to mapping
$headers = $_SESSION['tainacan_importer'][$id]->get_source_metadata();
@ -195,7 +195,7 @@ class ImporterTests extends TAINACAN_UnitTestCase {
$collection_definition = [
'id' => $collection->get_id(),
'total_items' => $_SESSION['tainacan_importer'][$id]->get_progress_total_from_source(),
'total_items' => $_SESSION['tainacan_importer'][$id]->get_source_number_of_items(),
];
// get collection metadata to map
@ -222,7 +222,7 @@ class ImporterTests extends TAINACAN_UnitTestCase {
$items = $Tainacan_Items->fetch( [], $collection, 'OBJECT' );
$this->assertEquals( $_SESSION['tainacan_importer'][$id]->get_progress_total_from_source(), count( $items ) );
$this->assertEquals( $_SESSION['tainacan_importer'][$id]->get_source_number_of_items(), count( $items ) );
}
/**