1
0
mirror of https://github.com/ascribe/onion.git synced 2024-12-22 17:33:14 +01:00

Merge with master

This commit is contained in:
Brett Sun 2016-01-26 13:50:03 +01:00
commit 6a1dc7ed98
163 changed files with 3444 additions and 2185 deletions

3
.env-template Normal file
View File

@ -0,0 +1,3 @@
SAUCE_USERNAME=ascribe
SAUCE_ACCESS_KEY=
SAUCE_DEFAULT_URL=

View File

@ -2,7 +2,7 @@
"parser": "babel-eslint", "parser": "babel-eslint",
"env": { "env": {
"browser": true, "browser": true,
"es6": true "es6": true,
}, },
"rules": { "rules": {
"new-cap": [2, {newIsCap: true, capIsNew: false}], "new-cap": [2, {newIsCap: true, capIsNew: false}],

1
.gitignore vendored
View File

@ -22,3 +22,4 @@ node_modules/*
build build
.DS_Store .DS_Store
.env

View File

@ -48,15 +48,18 @@ For this project, we're using:
Branch names Branch names
===================== =====================
Since we moved to Github, we cannot create branch names automatically with JIRA anymore.
To not lose context, but still be able to switch branches quickly using a ticket's number, we're recommending the following rules when naming our branches in onion. To allow Github and JIRA to track branches while still allowing us to switch branches quickly using a ticket's number (and keep our peace of mind), we have the following rules for naming branches:
``` ```
// For issues logged in Github:
AG-<Github-issue-id>-brief-and-sane-description-of-the-ticket
// For issues logged in JIRA:
AD-<JIRA-ticket-id>-brief-and-sane-description-of-the-ticket AD-<JIRA-ticket-id>-brief-and-sane-description-of-the-ticket
``` ```
where `brief-and-sane-description-of-the-ticket` does not need to equal to the ticket's title. where `brief-and-sane-description-of-the-ticket` does not need to equal to the issue or ticket's title.
This allows JIRA to still track branches and pull-requests while allowing us to keep our peace of mind.
Example Example
------------- -------------

View File

@ -83,9 +83,9 @@ class ContractAgreementListActions {
contractAgreementList in the store is already set to null; contractAgreementList in the store is already set to null;
*/ */
} }
}).then((publicContracAgreement) => { }).then((publicContractAgreement) => {
if (publicContracAgreement) { if (publicContractAgreement) {
this.actions.updateContractAgreementList([publicContracAgreement]); this.actions.updateContractAgreementList([publicContractAgreement]);
} }
}).catch(console.logGlobal); }).catch(console.logGlobal);
} }
@ -93,7 +93,10 @@ class ContractAgreementListActions {
createContractAgreement(issuer, contract){ createContractAgreement(issuer, contract){
return Q.Promise((resolve, reject) => { return Q.Promise((resolve, reject) => {
OwnershipFetcher OwnershipFetcher
.createContractAgreement(issuer, contract).then(resolve) .createContractAgreement(issuer, contract)
.then((res) => {
resolve(res && res.contractagreement)
})
.catch((err) => { .catch((err) => {
console.logGlobal(err); console.logGlobal(err);
reject(err); reject(err);

View File

@ -28,12 +28,10 @@ class ContractListActions {
} }
changeContract(contract){ changeContract(contract) {
return Q.Promise((resolve, reject) => { return Q.Promise((resolve, reject) => {
OwnershipFetcher.changeContract(contract) OwnershipFetcher.changeContract(contract)
.then((res) => { .then(resolve)
resolve(res);
})
.catch((err)=> { .catch((err)=> {
console.logGlobal(err); console.logGlobal(err);
reject(err); reject(err);
@ -41,13 +39,11 @@ class ContractListActions {
}); });
} }
removeContract(contractId){ removeContract(contractId) {
return Q.Promise( (resolve, reject) => { return Q.Promise((resolve, reject) => {
OwnershipFetcher.deleteContract(contractId) OwnershipFetcher.deleteContract(contractId)
.then((res) => { .then(resolve)
resolve(res); .catch((err) => {
})
.catch( (err) => {
console.logGlobal(err); console.logGlobal(err);
reject(err); reject(err);
}); });

View File

@ -7,11 +7,11 @@ class EditionActions {
constructor() { constructor() {
this.generateActions( this.generateActions(
'fetchEdition', 'fetchEdition',
'successFetchEdition',
'successFetchCoa', 'successFetchCoa',
'flushEdition', 'successFetchEdition',
'errorCoa', 'errorCoa',
'errorEdition' 'errorEdition',
'flushEdition'
); );
} }
} }

View File

@ -17,23 +17,31 @@ class EditionListActions {
); );
} }
fetchEditionList(pieceId, page, pageSize, orderBy, orderAsc, filterBy) { fetchEditionList({ pieceId, page, pageSize, orderBy, orderAsc, filterBy, maxEdition }) {
if((!orderBy && typeof orderAsc === 'undefined') || !orderAsc) { if ((!orderBy && typeof orderAsc === 'undefined') || !orderAsc) {
orderBy = 'edition_number'; orderBy = 'edition_number';
orderAsc = true; orderAsc = true;
} }
// Taken from: http://stackoverflow.com/a/519157/1263876 // Taken from: http://stackoverflow.com/a/519157/1263876
if((typeof page === 'undefined' || !page) && (typeof pageSize === 'undefined' || !pageSize)) { if ((typeof page === 'undefined' || !page) && (typeof pageSize === 'undefined' || !pageSize)) {
page = 1; page = 1;
pageSize = 10; pageSize = 10;
} }
let itemsToFetch = pageSize;
// If we only want to fetch up to a specified edition, fetch all pages up to it
// as one page and adjust afterwards
if (typeof maxEdition === 'number') {
itemsToFetch = Math.ceil(maxEdition / pageSize) * pageSize;
page = 1;
}
return Q.Promise((resolve, reject) => { return Q.Promise((resolve, reject) => {
EditionListFetcher EditionListFetcher
.fetch(pieceId, page, pageSize, orderBy, orderAsc, filterBy) .fetch({ pieceId, page, orderBy, orderAsc, filterBy, pageSize: itemsToFetch })
.then((res) => { .then((res) => {
if(res && !res.editions) { if (res && !res.editions) {
throw new Error('Piece has no editions to fetch.'); throw new Error('Piece has no editions to fetch.');
} }
@ -44,8 +52,9 @@ class EditionListActions {
orderBy, orderBy,
orderAsc, orderAsc,
filterBy, filterBy,
'editionListOfPiece': res.editions, maxEdition,
'count': res.count count: res.count,
editionListOfPiece: res.editions
}); });
resolve(res); resolve(res);
}) })
@ -54,7 +63,6 @@ class EditionListActions {
reject(err); reject(err);
}); });
}); });
} }
} }

View File

@ -0,0 +1,14 @@
'use strict';
import { altThirdParty } from '../alt';
class FacebookActions {
constructor() {
this.generateActions(
'sdkReady'
);
}
}
export default altThirdParty.createActions(FacebookActions);

View File

@ -9,10 +9,13 @@ class NotificationActions {
constructor() { constructor() {
this.generateActions( this.generateActions(
'updatePieceListNotifications', 'updatePieceListNotifications',
'flushPieceListNotifications',
'updateEditionListNotifications', 'updateEditionListNotifications',
'flushEditionListNotifications',
'updateEditionNotifications', 'updateEditionNotifications',
'updatePieceNotifications', 'updatePieceNotifications',
'updateContractAgreementListNotifications' 'updateContractAgreementListNotifications',
'flushContractAgreementListNotifications'
); );
} }

View File

@ -1,28 +1,19 @@
'use strict'; 'use strict';
import { alt } from '../alt'; import { alt } from '../alt';
import PieceFetcher from '../fetchers/piece_fetcher';
class PieceActions { class PieceActions {
constructor() { constructor() {
this.generateActions( this.generateActions(
'fetchPiece',
'successFetchPiece',
'errorPiece',
'flushPiece',
'updatePiece', 'updatePiece',
'updateProperty', 'updateProperty'
'pieceFailed'
); );
} }
fetchOne(pieceId) {
PieceFetcher.fetchOne(pieceId)
.then((res) => {
this.actions.updatePiece(res.piece);
})
.catch((err) => {
console.logGlobal(err);
this.actions.pieceFailed(err.json);
});
}
} }
export default alt.createActions(PieceActions); export default alt.createActions(PieceActions);

View File

@ -15,7 +15,7 @@ class PieceListActions {
); );
} }
fetchPieceList(page, pageSize, search, orderBy, orderAsc, filterBy) { fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy }) {
// To prevent flickering on a pagination request, // To prevent flickering on a pagination request,
// we overwrite the piecelist with an empty list before // we overwrite the piecelist with an empty list before
// pieceListCount === -1 defines the loading state // pieceListCount === -1 defines the loading state
@ -34,7 +34,7 @@ class PieceListActions {
// afterwards, we can load the list // afterwards, we can load the list
return Q.Promise((resolve, reject) => { return Q.Promise((resolve, reject) => {
PieceListFetcher PieceListFetcher
.fetch(page, pageSize, search, orderBy, orderAsc, filterBy) .fetch({ page, pageSize, search, orderBy, orderAsc, filterBy })
.then((res) => { .then((res) => {
this.actions.updatePieceList({ this.actions.updatePieceList({
page, page,

View File

@ -1,34 +0,0 @@
'use strict';
import { alt } from '../alt';
import Q from 'q';
import PrizeListFetcher from '../fetchers/prize_list_fetcher';
class PrizeListActions {
constructor() {
this.generateActions(
'updatePrizeList'
);
}
fetchPrizeList() {
return Q.Promise((resolve, reject) => {
PrizeListFetcher
.fetch()
.then((res) => {
this.actions.updatePrizeList({
prizeList: res.prizes,
prizeListCount: res.count
});
resolve(res);
})
.catch((err) => {
console.logGlobal(err);
reject(err);
});
});
}
}
export default alt.createActions(PrizeListActions);

View File

@ -1,14 +1,13 @@
'use strict'; 'use strict';
import polyfill from 'babel/polyfill'; import 'babel/polyfill';
import 'classlist-polyfill';
import React from 'react'; import React from 'react';
import { Router, Redirect } from 'react-router'; import { Router, Redirect } from 'react-router';
import history from './history'; import history from './history';
/* eslint-disable */
import fetch from 'isomorphic-fetch'; import fetch from 'isomorphic-fetch';
/* eslint-enable */
import ApiUrls from './constants/api_urls'; import ApiUrls from './constants/api_urls';
@ -17,44 +16,27 @@ import getRoutes from './routes';
import requests from './utils/requests'; import requests from './utils/requests';
import { updateApiUrls } from './constants/api_urls'; import { updateApiUrls } from './constants/api_urls';
import { getSubdomainSettings } from './utils/constants_utils'; import { getDefaultSubdomainSettings, getSubdomainSettings } from './utils/constants_utils';
import { initLogging } from './utils/error_utils'; import { initLogging } from './utils/error_utils';
import { getSubdomain } from './utils/general_utils'; import { getSubdomain } from './utils/general_utils';
import EventActions from './actions/event_actions'; import EventActions from './actions/event_actions';
/* eslint-disable */
// You can comment out the modules you don't need // You can comment out the modules you don't need
// import DebugHandler from './third_party/debug'; // import DebugHandler from './third_party/debug_handler';
import GoogleAnalyticsHandler from './third_party/ga'; import FacebookHandler from './third_party/facebook_handler';
import RavenHandler from './third_party/raven'; import GoogleAnalyticsHandler from './third_party/ga_handler';
import IntercomHandler from './third_party/intercom'; import IntercomHandler from './third_party/intercom_handler';
import NotificationsHandler from './third_party/notifications'; import NotificationsHandler from './third_party/notifications_handler';
import FacebookHandler from './third_party/facebook'; import RavenHandler from './third_party/raven_handler';
/* eslint-enable */
initLogging();
let headers = { const AppGateway = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
requests.defaults({
urlMap: ApiUrls,
http: {
headers: headers,
credentials: 'include'
}
});
class AppGateway {
start() { start() {
let settings;
let subdomain = getSubdomain();
try { try {
settings = getSubdomainSettings(subdomain); const subdomain = getSubdomain();
const settings = getSubdomainSettings(subdomain);
AppConstants.whitelabel = settings; AppConstants.whitelabel = settings;
updateApiUrls(settings.type, subdomain); updateApiUrls(settings.type, subdomain);
this.load(settings); this.load(settings);
@ -62,27 +44,24 @@ class AppGateway {
// if there are no matching subdomains, we're routing // if there are no matching subdomains, we're routing
// to the default frontend // to the default frontend
console.logGlobal(err); console.logGlobal(err);
this.load(); this.load(getDefaultSubdomainSettings());
}
} }
},
load(settings) { load(settings) {
let type = 'default'; const { subdomain, type } = settings;
let subdomain = 'www';
let redirectRoute = (<Redirect from="/" to="/collection" />); let redirectRoute = (<Redirect from="/" to="/collection" />);
if (settings) { if (subdomain) {
type = settings.type; // Some whitelabels have landing pages so we should not automatically redirect from / to /collection.
subdomain = settings.subdomain; // Only www and cc do not have a landing page.
} if (subdomain !== 'cc') {
// www and cc do not have a landing page
if(subdomain && subdomain !== 'cc') {
redirectRoute = null; redirectRoute = null;
} }
// Adds a client specific class to the body for whitelabel styling // Adds a client specific class to the body for whitelabel styling
window.document.body.classList.add('client--' + subdomain); window.document.body.classList.add('client--' + subdomain);
}
// Send the applicationWillBoot event to the third-party stores // Send the applicationWillBoot event to the third-party stores
EventActions.applicationWillBoot(settings); EventActions.applicationWillBoot(settings);
@ -101,8 +80,21 @@ class AppGateway {
// Send the applicationDidBoot event to the third-party stores // Send the applicationDidBoot event to the third-party stores
EventActions.applicationDidBoot(settings); EventActions.applicationDidBoot(settings);
} }
} };
let ag = new AppGateway(); // Initialize pre-start components
ag.start(); initLogging();
requests.defaults({
urlMap: ApiUrls,
http: {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include'
}
});
// And bootstrap app
AppGateway.start();

View File

@ -19,9 +19,10 @@ import { getLangText } from '../../utils/lang_utils';
let AccordionListItemEditionWidget = React.createClass({ let AccordionListItemEditionWidget = React.createClass({
propTypes: { propTypes: {
className: React.PropTypes.string,
piece: React.PropTypes.object.isRequired, piece: React.PropTypes.object.isRequired,
toggleCreateEditionsDialog: React.PropTypes.func.isRequired, toggleCreateEditionsDialog: React.PropTypes.func.isRequired,
className: React.PropTypes.string,
onPollingSuccess: React.PropTypes.func onPollingSuccess: React.PropTypes.func
}, },
@ -50,14 +51,15 @@ let AccordionListItemEditionWidget = React.createClass({
* Calls the store to either show or hide the editionListTable * Calls the store to either show or hide the editionListTable
*/ */
toggleTable() { toggleTable() {
let pieceId = this.props.piece.id; const { piece: { id: pieceId } } = this.props;
let isEditionListOpen = this.state.isEditionListOpenForPieceId[pieceId] ? this.state.isEditionListOpenForPieceId[pieceId].show : false; const { filterBy, isEditionListOpenForPieceId } = this.state;
const isEditionListOpen = isEditionListOpenForPieceId[pieceId] ? isEditionListOpenForPieceId[pieceId].show : false;
if(isEditionListOpen) { if (isEditionListOpen) {
EditionListActions.toggleEditionList(pieceId); EditionListActions.toggleEditionList(pieceId);
} else { } else {
EditionListActions.toggleEditionList(pieceId); EditionListActions.toggleEditionList(pieceId);
EditionListActions.fetchEditionList(pieceId, null, null, null, null, this.state.filterBy); EditionListActions.fetchEditionList({ pieceId, filterBy });
} }
}, },

View File

@ -12,8 +12,11 @@ import { getLangText } from '../../utils/lang_utils';
let AccordionListItemPiece = React.createClass({ let AccordionListItemPiece = React.createClass({
propTypes: { propTypes: {
className: React.PropTypes.string, className: React.PropTypes.string,
artistName: React.PropTypes.string, artistName: React.PropTypes.oneOfType([
piece: React.PropTypes.object, React.PropTypes.string,
React.PropTypes.element
]),
piece: React.PropTypes.object.isRequired,
children: React.PropTypes.oneOfType([ children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element), React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element React.PropTypes.element
@ -51,17 +54,21 @@ let AccordionListItemPiece = React.createClass({
piece, piece,
subsubheading, subsubheading,
thumbnailPlaceholder: ThumbnailPlaceholder } = this.props; thumbnailPlaceholder: ThumbnailPlaceholder } = this.props;
const { url, url_safe } = piece.thumbnail; const { url: thumbnailUrl, url_safe: thumbnailSafeUrl } = piece.thumbnail;
// Display the 300x300 thumbnail if we have it, otherwise just use the safe url
const thumbnailDisplayUrl = (piece.thumbnail.thumbnail_sizes && piece.thumbnail.thumbnail_sizes['300x300']) || thumbnailSafeUrl;
let thumbnail; let thumbnail;
// Since we're going to refactor the thumbnail generation anyway at one point, // Since we're going to refactor the thumbnail generation anyway at one point,
// for not use the annoying ascribe_spiral.png, we're matching the url against // for not use the annoying ascribe_spiral.png, we're matching the url against
// this name and replace it with a CSS version of the new logo. // this name and replace it with a CSS version of the new logo.
if (url.match(/https:\/\/.*\/media\/thumbnails\/ascribe_spiral.png/)) { if (thumbnailUrl.match(/https:\/\/.*\/media\/thumbnails\/ascribe_spiral.png/)) {
thumbnail = (<ThumbnailPlaceholder />); thumbnail = (<ThumbnailPlaceholder />);
} else { } else {
thumbnail = ( thumbnail = (
<div style={{backgroundImage: 'url("' + url_safe + '")'}}/> <div style={{backgroundImage: 'url("' + thumbnailDisplayUrl + '")'}} />
); );
} }
@ -79,8 +86,7 @@ let AccordionListItemPiece = React.createClass({
subsubheading={subsubheading} subsubheading={subsubheading}
buttons={buttons} buttons={buttons}
badge={badge} badge={badge}
linkData={this.getLinkData()} linkData={this.getLinkData()}>
>
{children} {children}
</AccordionListItem> </AccordionListItem>
); );

View File

@ -66,22 +66,34 @@ let AccordionListItemTableEditions = React.createClass({
}, },
filterSelectedEditions() { filterSelectedEditions() {
let selectedEditions = this.state.editionList[this.props.parentId] return this.state
.editionList[this.props.parentId]
.filter((edition) => edition.selected); .filter((edition) => edition.selected);
return selectedEditions;
}, },
loadFurtherEditions() { loadFurtherEditions() {
const { parentId: pieceId } = this.props;
const { page, pageSize, orderBy, orderAsc, filterBy } = this.state.editionList[pieceId];
// trigger loading animation // trigger loading animation
this.setState({ this.setState({
showMoreLoading: true showMoreLoading: true
}); });
let editionList = this.state.editionList[this.props.parentId]; EditionListActions.fetchEditionList({
EditionListActions.fetchEditionList(this.props.parentId, editionList.page + 1, editionList.pageSize, pieceId,
editionList.orderBy, editionList.orderAsc, editionList.filterBy); pageSize,
orderBy,
orderAsc,
filterBy,
page: page + 1
});
}, },
render() { render() {
const { className, parentId } = this.props;
const { editionList, isEditionListOpenForPieceId, showMoreLoading } = this.state;
const editionsForPiece = editionList[parentId];
let selectedEditionsCount = 0; let selectedEditionsCount = 0;
let allEditionsCount = 0; let allEditionsCount = 0;
let orderBy; let orderBy;
@ -89,95 +101,97 @@ let AccordionListItemTableEditions = React.createClass({
let show = false; let show = false;
let showExpandOption = false; let showExpandOption = false;
let editionsForPiece = this.state.editionList[this.props.parentId];
let loadingSpinner = <AscribeSpinner size="sm" color="dark-blue" />;
// here we need to check if all editions of a specific // here we need to check if all editions of a specific
// piece are already defined. Otherwise .length will throw an error and we'll not // piece are already defined. Otherwise .length will throw an error and we'll not
// be notified about it. // be notified about it.
if(editionsForPiece) { if (editionsForPiece) {
selectedEditionsCount = this.filterSelectedEditions().length; selectedEditionsCount = this.filterSelectedEditions().length;
allEditionsCount = editionsForPiece.length; allEditionsCount = editionsForPiece.length;
orderBy = editionsForPiece.orderBy; orderBy = editionsForPiece.orderBy;
orderAsc = editionsForPiece.orderAsc; orderAsc = editionsForPiece.orderAsc;
} }
if(this.props.parentId in this.state.isEditionListOpenForPieceId) { if (parentId in isEditionListOpenForPieceId) {
show = this.state.isEditionListOpenForPieceId[this.props.parentId].show; show = isEditionListOpenForPieceId[parentId].show;
} }
// if the number of editions in the array is equal to the maximum number of editions, // if the number of editions in the array is equal to the maximum number of editions,
// then the "Show me more" dialog should be hidden from the user's view // then the "Show me more" dialog should be hidden from the user's view
if(editionsForPiece && editionsForPiece.count > editionsForPiece.length) { if (editionsForPiece && editionsForPiece.count > editionsForPiece.length) {
showExpandOption = true; showExpandOption = true;
} }
let transition = new TransitionModel('editions', 'editionId', 'bitcoin_id', (e) => e.stopPropagation() ); const transition = new TransitionModel({
to: 'editions',
queryKey: 'editionId',
valueKey: 'bitcoin_id',
callback: (e) => e.stopPropagation()
});
let columnList = [ const columnList = [
new ColumnModel( new ColumnModel({
(item) => { transformFn: (item) => {
return { return {
'editionId': item.id, 'editionId': item.id,
'pieceId': this.props.parentId, 'pieceId': parentId,
'selectItem': this.selectItem, 'selectItem': this.selectItem,
'selected': item.selected 'selected': item.selected
}; }, };
'', },
displayElement: (
<AccordionListItemTableSelectAllEditionsCheckbox <AccordionListItemTableSelectAllEditionsCheckbox
onChange={this.toggleAllItems} onChange={this.toggleAllItems}
numOfSelectedEditions={selectedEditionsCount} numOfSelectedEditions={selectedEditionsCount}
numOfAllEditions={allEditionsCount}/>, numOfAllEditions={allEditionsCount}/>
TableItemCheckbox,
1,
false
), ),
new ColumnModel( displayType: TableItemCheckbox,
(item) => { rowWidth: 1
}),
new ColumnModel({
transition,
transformFn: (item) => {
return { return {
'content': item.edition_number + ' ' + getLangText('of') + ' ' + item.num_editions 'content': item.edition_number + ' ' + getLangText('of') + ' ' + item.num_editions
}; }, };
'edition_number', },
getLangText('Edition'), columnName: 'edition_number',
TableItemText, displayElement: getLangText('Edition'),
1, displayType: TableItemText,
false, rowWidth: 1
transition }),
), new ColumnModel({
new ColumnModel( transition,
(item) => { transformFn: (item) => {
return { return {
'content': item.bitcoin_id 'content': item.bitcoin_id
}; }, };
'bitcoin_id', },
getLangText('ID'), columnName: 'bitcoin_id',
TableItemText, displayElement: getLangText('ID'),
5, displayType: TableItemText,
false, rowWidth: 5,
className: 'hidden-xs visible-sm visible-md visible-lg'
}),
new ColumnModel({
transition, transition,
'hidden-xs visible-sm visible-md visible-lg' transformFn: (item) => {
),
new ColumnModel(
(item) => {
let content = item.acl;
return { return {
'content': content, 'content': item.acl,
'notifications': item.notifications 'notifications': item.notifications
}; }, };
'acl', },
getLangText('Actions'), columnName: 'acl',
TableItemAclFiltered, displayElement: getLangText('Actions'),
4, displayType: TableItemAclFiltered,
false, rowWidth: 4
transition })
)
]; ];
if(show && editionsForPiece && editionsForPiece.length > 0) { if (show && editionsForPiece && editionsForPiece.length) {
return ( return (
<div className={this.props.className}> <div className={className}>
<AccordionListItemTable <AccordionListItemTable
parentId={this.props.parentId} parentId={parentId}
itemList={editionsForPiece} itemList={editionsForPiece}
columnList={columnList} columnList={columnList}
show={show} show={show}
@ -188,7 +202,14 @@ let AccordionListItemTableEditions = React.createClass({
<AccordionListItemTableToggle <AccordionListItemTableToggle
className="ascribe-accordion-list-table-toggle" className="ascribe-accordion-list-table-toggle"
onClick={this.loadFurtherEditions} onClick={this.loadFurtherEditions}
message={show && showExpandOption ? <span>{this.state.showMoreLoading ? loadingSpinner : <span className="glyphicon glyphicon-option-horizontal" aria-hidden="true" style={{top: 3}} />} Show me more</span> : null} /> message={show && showExpandOption ? (
<span>
{showMoreLoading ? <AscribeSpinner size="sm" color="dark-blue" />
: <span className="glyphicon glyphicon-option-horizontal" aria-hidden="true" style={{top: 3}} />}
{getLangText('Show me more')}
</span>
) : null
} />
</div> </div>
); );
} else { } else {

View File

@ -88,11 +88,12 @@ let AccordionListItemWallet = React.createClass({
}, },
onPollingSuccess(pieceId) { onPollingSuccess(pieceId) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
EditionListActions.toggleEditionList(pieceId); EditionListActions.toggleEditionList(pieceId);
let notification = new GlobalNotificationModel('Editions successfully created', 'success', 10000); const notification = new GlobalNotificationModel('Editions successfully created', 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },

View File

@ -28,6 +28,12 @@ let CreateEditionsButton = React.createClass({
EditionListStore.listen(this.onChange); EditionListStore.listen(this.onChange);
}, },
componentDidUpdate() {
if(this.props.piece.num_editions === 0 && typeof this.state.pollingIntervalIndex === 'undefined') {
this.startPolling();
}
},
componentWillUnmount() { componentWillUnmount() {
EditionListStore.unlisten(this.onChange); EditionListStore.unlisten(this.onChange);
clearInterval(this.state.pollingIntervalIndex); clearInterval(this.state.pollingIntervalIndex);
@ -37,24 +43,20 @@ let CreateEditionsButton = React.createClass({
this.setState(state); this.setState(state);
}, },
componentDidUpdate() {
if(this.props.piece.num_editions === 0 && typeof this.state.pollingIntervalIndex === 'undefined') {
this.startPolling();
}
},
startPolling() { startPolling() {
// start polling until editions are defined // start polling until editions are defined
let pollingIntervalIndex = setInterval(() => { let pollingIntervalIndex = setInterval(() => {
// requests, will try to merge the filterBy parameter with other parameters (mergeOptions). // requests, will try to merge the filterBy parameter with other parameters (mergeOptions).
// Therefore it can't but null but instead has to be an empty object // Therefore it can't but null but instead has to be an empty object
EditionListActions.fetchEditionList(this.props.piece.id, null, null, null, null, {}) EditionListActions
.fetchEditionList({
pieceId: this.props.piece.id,
filterBy: {}
})
.then((res) => { .then((res) => {
clearInterval(this.state.pollingIntervalIndex); clearInterval(this.state.pollingIntervalIndex);
this.props.onPollingSuccess(this.props.piece.id, res.editions[0].num_editions); this.props.onPollingSuccess(this.props.piece.id, res.editions[0].num_editions);
}) })
.catch((err) => { .catch((err) => {
/* Ignore and keep going */ /* Ignore and keep going */

View File

@ -1,9 +1,10 @@
'use strict'; 'use strict';
import React from 'react'; import React from 'react';
import classNames from 'classnames';
let DetailProperty = React.createClass({ const DetailProperty = React.createClass({
propTypes: { propTypes: {
label: React.PropTypes.string, label: React.PropTypes.string,
value: React.PropTypes.oneOfType([ value: React.PropTypes.oneOfType([
@ -12,6 +13,7 @@ let DetailProperty = React.createClass({
React.PropTypes.element React.PropTypes.element
]), ]),
separator: React.PropTypes.string, separator: React.PropTypes.string,
className: React.PropTypes.string,
labelClassName: React.PropTypes.string, labelClassName: React.PropTypes.string,
valueClassName: React.PropTypes.string, valueClassName: React.PropTypes.string,
ellipsis: React.PropTypes.bool, ellipsis: React.PropTypes.bool,
@ -30,31 +32,23 @@ let DetailProperty = React.createClass({
}, },
render() { render() {
let styles = {}; const {
const { labelClassName, children,
className,
ellipsis,
label, label,
labelClassName,
separator, separator,
valueClassName, valueClassName,
children,
value } = this.props; value } = this.props;
if(this.props.ellipsis) {
styles = {
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis'
};
}
return ( return (
<div className="row ascribe-detail-property"> <div className={classNames('row ascribe-detail-property', className)}>
<div className="row-same-height"> <div className="row-same-height">
<div className={labelClassName}> <div className={labelClassName}>
{label} {separator} {label} {separator}
</div> </div>
<div <div className={classNames(valueClassName, {'add-overflow-ellipsis': ellipsis})}>
className={valueClassName}
style={styles}>
{children || value} {children || value}
</div> </div>
</div> </div>

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
import React from 'react'; import React from 'react';
import { Link, History } from 'react-router'; import { Link } from 'react-router';
import Moment from 'moment'; import Moment from 'moment';
import Row from 'react-bootstrap/lib/Row'; import Row from 'react-bootstrap/lib/Row';
@ -16,7 +16,7 @@ import CollapsibleParagraph from './../ascribe_collapsible/collapsible_paragraph
import Form from './../ascribe_forms/form'; import Form from './../ascribe_forms/form';
import Property from './../ascribe_forms/property'; import Property from './../ascribe_forms/property';
import EditionDetailProperty from './detail_property'; import DetailProperty from './detail_property';
import LicenseDetail from './license_detail'; import LicenseDetail from './license_detail';
import FurtherDetails from './further_details'; import FurtherDetails from './further_details';
@ -44,8 +44,6 @@ let Edition = React.createClass({
loadEdition: React.PropTypes.func loadEdition: React.PropTypes.func
}, },
mixins: [History],
getDefaultProps() { getDefaultProps() {
return { return {
furtherDetailsType: FurtherDetails furtherDetailsType: FurtherDetails
@ -53,98 +51,103 @@ let Edition = React.createClass({
}, },
render() { render() {
let FurtherDetailsType = this.props.furtherDetailsType; const {
actionPanelButtonListType,
coaError,
currentUser,
edition,
furtherDetailsType: FurtherDetailsType,
loadEdition } = this.props;
return ( return (
<Row> <Row>
<Col md={6}> <Col md={6} className="ascribe-print-col-left">
<MediaContainer <MediaContainer
content={this.props.edition}/> content={edition}
currentUser={currentUser} />
</Col> </Col>
<Col md={6} className="ascribe-edition-details"> <Col md={6} className="ascribe-edition-details ascribe-print-col-right">
<div className="ascribe-detail-header"> <div className="ascribe-detail-header">
<hr style={{marginTop: 0}}/> <hr className="hidden-print" style={{marginTop: 0}}/>
<h1 className="ascribe-detail-title">{this.props.edition.title}</h1> <h1 className="ascribe-detail-title">{edition.title}</h1>
<EditionDetailProperty label="BY" value={this.props.edition.artist_name} /> <DetailProperty label="CREATED BY" value={edition.artist_name} />
<EditionDetailProperty label="DATE" value={Moment(this.props.edition.date_created, 'YYYY-MM-DD').year()} /> <DetailProperty label="DATE" value={Moment(edition.date_created, 'YYYY-MM-DD').year()} />
<hr/> <hr/>
</div> </div>
<EditionSummary <EditionSummary
actionPanelButtonListType={this.props.actionPanelButtonListType} actionPanelButtonListType={actionPanelButtonListType}
edition={this.props.edition} edition={edition}
currentUser={this.props.currentUser} currentUser={currentUser}
handleSuccess={this.props.loadEdition}/> handleSuccess={loadEdition}/>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Certificate of Authenticity')} title={getLangText('Certificate of Authenticity')}
show={this.props.edition.acl.acl_coa === true}> show={edition.acl.acl_coa === true}>
<CoaDetails <CoaDetails
coa={this.props.edition.coa} coa={edition.coa}
coaError={this.props.coaError} coaError={coaError}
editionId={this.props.edition.bitcoin_id}/> editionId={edition.bitcoin_id}/>
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Provenance/Ownership History')} title={getLangText('Provenance/Ownership History')}
show={this.props.edition.ownership_history && this.props.edition.ownership_history.length > 0}> show={edition.ownership_history && edition.ownership_history.length > 0}>
<HistoryIterator <HistoryIterator
history={this.props.edition.ownership_history} /> history={edition.ownership_history} />
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Consignment History')} title={getLangText('Consignment History')}
show={this.props.edition.consign_history && this.props.edition.consign_history.length > 0}> show={edition.consign_history && edition.consign_history.length > 0}>
<HistoryIterator <HistoryIterator
history={this.props.edition.consign_history} /> history={edition.consign_history} />
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Loan History')} title={getLangText('Loan History')}
show={this.props.edition.loan_history && this.props.edition.loan_history.length > 0}> show={edition.loan_history && edition.loan_history.length > 0}>
<HistoryIterator <HistoryIterator
history={this.props.edition.loan_history} /> history={edition.loan_history} />
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title="Notes" title="Notes"
show={!!(this.props.currentUser.username show={!!(currentUser.username || edition.acl.acl_edit || edition.public_note)}>
|| this.props.edition.acl.acl_edit
|| this.props.edition.public_note)}>
<Note <Note
id={() => {return {'bitcoin_id': this.props.edition.bitcoin_id}; }} id={() => {return {'bitcoin_id': edition.bitcoin_id}; }}
label={getLangText('Personal note (private)')} label={getLangText('Personal note (private)')}
defaultValue={this.props.edition.private_note ? this.props.edition.private_note : null} defaultValue={edition.private_note ? edition.private_note : null}
placeholder={getLangText('Enter your comments ...')} placeholder={getLangText('Enter your comments ...')}
editable={true} editable={true}
successMessage={getLangText('Private note saved')} successMessage={getLangText('Private note saved')}
url={ApiUrls.note_private_edition} url={ApiUrls.note_private_edition}
currentUser={this.props.currentUser}/> currentUser={currentUser}/>
<Note <Note
id={() => {return {'bitcoin_id': this.props.edition.bitcoin_id}; }} id={() => {return {'bitcoin_id': edition.bitcoin_id}; }}
label={getLangText('Personal note (public)')} label={getLangText('Personal note (public)')}
defaultValue={this.props.edition.public_note ? this.props.edition.public_note : null} defaultValue={edition.public_note ? edition.public_note : null}
placeholder={getLangText('Enter your comments ...')} placeholder={getLangText('Enter your comments ...')}
editable={!!this.props.edition.acl.acl_edit} editable={!!edition.acl.acl_edit}
show={!!this.props.edition.public_note || !!this.props.edition.acl.acl_edit} show={!!edition.public_note || !!edition.acl.acl_edit}
successMessage={getLangText('Public edition note saved')} successMessage={getLangText('Public edition note saved')}
url={ApiUrls.note_public_edition} url={ApiUrls.note_public_edition}
currentUser={this.props.currentUser}/> currentUser={currentUser}/>
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Further Details')} title={getLangText('Further Details')}
show={this.props.edition.acl.acl_edit show={edition.acl.acl_edit ||
|| Object.keys(this.props.edition.extra_data).length > 0 Object.keys(edition.extra_data).length > 0 ||
|| this.props.edition.other_data.length > 0}> edition.other_data.length > 0}>
<FurtherDetailsType <FurtherDetailsType
editable={this.props.edition.acl.acl_edit} editable={edition.acl.acl_edit}
pieceId={this.props.edition.parent} pieceId={edition.parent}
extraData={this.props.edition.extra_data} extraData={edition.extra_data}
otherData={this.props.edition.other_data} otherData={edition.other_data}
handleSuccess={this.props.loadEdition} /> handleSuccess={loadEdition} />
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('SPOOL Details')}> title={getLangText('SPOOL Details')}>
<SpoolDetails <SpoolDetails
edition={this.props.edition} /> edition={edition} />
</CollapsibleParagraph> </CollapsibleParagraph>
</Col> </Col>
</Row> </Row>
@ -169,10 +172,10 @@ let EditionSummary = React.createClass({
let status = null; let status = null;
if (this.props.edition.status.length > 0){ if (this.props.edition.status.length > 0){
let statusStr = this.props.edition.status.join(', ').replace(/_/g, ' '); let statusStr = this.props.edition.status.join(', ').replace(/_/g, ' ');
status = <EditionDetailProperty label="STATUS" value={ statusStr }/>; status = <DetailProperty label="STATUS" value={ statusStr }/>;
if (this.props.edition.pending_new_owner && this.props.edition.acl.acl_withdraw_transfer){ if (this.props.edition.pending_new_owner && this.props.edition.acl.acl_withdraw_transfer){
status = ( status = (
<EditionDetailProperty label="STATUS" value={ statusStr } /> <DetailProperty label="STATUS" value={ statusStr } />
); );
} }
} }
@ -183,14 +186,14 @@ let EditionSummary = React.createClass({
let { actionPanelButtonListType, edition, currentUser } = this.props; let { actionPanelButtonListType, edition, currentUser } = this.props;
return ( return (
<div className="ascribe-detail-header"> <div className="ascribe-detail-header">
<EditionDetailProperty <DetailProperty
label={getLangText('EDITION')} label={getLangText('EDITION')}
value={ edition.edition_number + ' ' + getLangText('of') + ' ' + edition.num_editions} /> value={ edition.edition_number + ' ' + getLangText('of') + ' ' + edition.num_editions} />
<EditionDetailProperty <DetailProperty
label={getLangText('ID')} label={getLangText('ID')}
value={ edition.bitcoin_id } value={ edition.bitcoin_id }
ellipsis={true} /> ellipsis={true} />
<EditionDetailProperty <DetailProperty
label={getLangText('OWNER')} label={getLangText('OWNER')}
value={ edition.owner } /> value={ edition.owner } />
<LicenseDetail license={edition.license_type}/> <LicenseDetail license={edition.license_type}/>
@ -201,14 +204,15 @@ let EditionSummary = React.createClass({
`AclInformation` would show up `AclInformation` would show up
*/} */}
<AclProxy show={currentUser && currentUser.email && Object.keys(edition.acl).length > 1}> <AclProxy show={currentUser && currentUser.email && Object.keys(edition.acl).length > 1}>
<EditionDetailProperty <DetailProperty
label={getLangText('ACTIONS')}> label={getLangText('ACTIONS')}
className="hidden-print">
<EditionActionPanel <EditionActionPanel
actionPanelButtonListType={actionPanelButtonListType} actionPanelButtonListType={actionPanelButtonListType}
edition={edition} edition={edition}
currentUser={currentUser} currentUser={currentUser}
handleSuccess={this.handleSuccess} /> handleSuccess={this.handleSuccess} />
</EditionDetailProperty> </DetailProperty>
</AclProxy> </AclProxy>
<hr/> <hr/>
</div> </div>
@ -220,41 +224,46 @@ let EditionSummary = React.createClass({
let CoaDetails = React.createClass({ let CoaDetails = React.createClass({
propTypes: { propTypes: {
editionId: React.PropTypes.string, editionId: React.PropTypes.string,
coa: React.PropTypes.object, coa: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string,
React.PropTypes.object
]),
coaError: React.PropTypes.object coaError: React.PropTypes.object
}, },
contactOnIntercom() { contactOnIntercom() {
window.Intercom('showNewMessage', `Hi, I'm having problems generating a Certificate of Authenticity for Edition: ${this.props.editionId}`); const { coaError, editionId } = this.props;
console.logGlobal(new Error(`Coa couldn't be created for edition: ${this.props.editionId}`));
window.Intercom('showNewMessage', getLangText("Hi, I'm having problems generating a Certificate of Authenticity for Edition: %s", editionId));
console.logGlobal(new Error(`Coa couldn't be created for edition: ${editionId}`), coaError);
}, },
render() { render() {
if(this.props.coaError) { const { coa, coaError } = this.props;
return ( let coaDetailElement;
<div className="text-center">
<p>{getLangText('There was an error generating your Certificate of Authenticity.')}</p> if (coaError) {
coaDetailElement = [
<p>{getLangText('There was an error generating your Certificate of Authenticity.')}</p>,
<p> <p>
{getLangText('Try to refresh the page. If this happens repeatedly, please ')} {getLangText('Try to refresh the page. If this happens repeatedly, please ')}
<a style={{ cursor: 'pointer' }} onClick={this.contactOnIntercom}>{getLangText('contact us')}</a>. <a style={{ cursor: 'pointer' }} onClick={this.contactOnIntercom}>{getLangText('contact us')}</a>.
</p> </p>
</div> ];
); } else if (coa && coa.url_safe) {
} coaDetailElement = [
if(this.props.coa && this.props.coa.url_safe) {
return (
<div>
<div <div
className="notification-contract-pdf" className="notification-contract-pdf"
style={{paddingBottom: '1em'}}> style={{paddingBottom: '1em'}}>
<embed <embed
className="embed-form" className="embed-form"
src={this.props.coa.url_safe} src={coa.url_safe}
alt="pdf" alt="pdf"
pluginspage="http://www.adobe.com/products/acrobat/readstep2.html"/> pluginspage="http://www.adobe.com/products/acrobat/readstep2.html"/>
</div> </div>,
<div className="text-center ascribe-button-list"> <div className="text-center ascribe-button-list">
<a href={this.props.coa.url_safe} target="_blank"> <a href={coa.url_safe} target="_blank">
<button className="btn btn-default btn-xs"> <button className="btn btn-default btn-xs">
{getLangText('Download')} <Glyphicon glyph="cloud-download"/> {getLangText('Download')} <Glyphicon glyph="cloud-download"/>
</button> </button>
@ -264,22 +273,27 @@ let CoaDetails = React.createClass({
{getLangText('Verify')} <Glyphicon glyph="check"/> {getLangText('Verify')} <Glyphicon glyph="check"/>
</button> </button>
</Link> </Link>
</div> </div>
</div> ];
); } else if (typeof coa === 'string') {
} else if(typeof this.props.coa === 'string'){ coaDetailElement = coa;
return ( } else {
<div className="text-center"> coaDetailElement = [
{this.props.coa} <AscribeSpinner color='dark-blue' size='md'/>,
</div> <p>{getLangText("Just a sec, we're generating your COA")}</p>,
);
}
return (
<div className="text-center">
<AscribeSpinner color='dark-blue' size='md'/>
<p>{getLangText("Just a sec, we\'re generating your COA")}</p>
<p>{getLangText('(you may leave the page)')}</p> <p>{getLangText('(you may leave the page)')}</p>
];
}
return (
<div>
<div className="text-center hidden-print">
{coaDetailElement}
</div>
{/* Hide the COA and just show that it's a seperate document when printing */}
<div className="visible-print ascribe-coa-print-placeholder">
{getLangText('The COA is available as a seperate document')}
</div>
</div> </div>
); );
} }
@ -291,16 +305,34 @@ let SpoolDetails = React.createClass({
}, },
render() { render() {
let bitcoinIdValue = ( const { edition: {
<a target="_blank" href={'https://www.blocktrail.com/BTC/address/' + this.props.edition.bitcoin_id}>{this.props.edition.bitcoin_id}</a> bitcoin_id: bitcoinId,
hash_as_address: hashAsAddress,
btc_owner_address_noprefix: bitcoinOwnerAddress
} } = this.props;
const bitcoinIdValue = (
<a className="anchor-no-expand-print"
target="_blank"
href={'https://www.blocktrail.com/BTC/address/' + bitcoinId}>
{bitcoinId}
</a>
); );
let hashOfArtwork = ( const hashOfArtwork = (
<a target="_blank" href={'https://www.blocktrail.com/BTC/address/' + this.props.edition.hash_as_address}>{this.props.edition.hash_as_address}</a> <a className="anchor-no-expand-print"
target="_blank"
href={'https://www.blocktrail.com/BTC/address/' + hashAsAddress}>
{hashAsAddress}
</a>
); );
let ownerAddress = ( const ownerAddress = (
<a target="_blank" href={'https://www.blocktrail.com/BTC/address/' + this.props.edition.btc_owner_address_noprefix}>{this.props.edition.btc_owner_address_noprefix}</a> <a className="anchor-no-expand-print"
target="_blank"
href={'https://www.blocktrail.com/BTC/address/' + bitcoinOwnerAddress}>
{bitcoinOwnerAddress}
</a>
); );
return ( return (

View File

@ -72,19 +72,20 @@ let EditionActionPanel = React.createClass({
EditionListActions.closeAllEditionLists(); EditionListActions.closeAllEditionLists();
EditionListActions.clearAllEditionSelections(); EditionListActions.clearAllEditionSelections();
let notification = new GlobalNotificationModel(response.notification, 'success'); const notification = new GlobalNotificationModel(response.notification, 'success');
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.history.pushState(null, '/collection'); this.history.push('/collection');
}, },
refreshCollection() { refreshCollection() {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
EditionListActions.refreshEditionList({pieceId: this.props.edition.parent}); PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
EditionListActions.refreshEditionList({ pieceId: this.props.edition.parent });
}, },
handleSuccess(response){ handleSuccess(response) {
this.refreshCollection(); this.refreshCollection();
this.props.handleSuccess(); this.props.handleSuccess();
if (response){ if (response){
@ -93,7 +94,7 @@ let EditionActionPanel = React.createClass({
} }
}, },
render(){ render() {
const { const {
actionPanelButtonListType: ActionPanelButtonListType, actionPanelButtonListType: ActionPanelButtonListType,
edition, edition,

View File

@ -35,7 +35,7 @@ let EditionContainer = React.createClass({
getInitialState() { getInitialState() {
return mergeOptions( return mergeOptions(
EditionStore.getState(), EditionStore.getInitialState(),
UserStore.getState() UserStore.getState()
); );
}, },
@ -44,27 +44,23 @@ let EditionContainer = React.createClass({
EditionStore.listen(this.onChange); EditionStore.listen(this.onChange);
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
// Every time we're entering the edition detail page, this.loadEdition();
// just reset the edition that is saved in the edition store
// as it will otherwise display wrong/old data once the user loads
// the edition detail a second time
EditionActions.flushEdition();
EditionActions.fetchEdition(this.props.params.editionId);
UserActions.fetchCurrentUser(); UserActions.fetchCurrentUser();
}, },
// This is done to update the container when the user clicks on the prev or next // This is done to update the container when the user clicks on the prev or next
// button to update the URL parameter (and therefore to switch pieces) // button to update the URL parameter (and therefore to switch pieces)
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
if(this.props.params.editionId !== nextProps.params.editionId) { if (this.props.params.editionId !== nextProps.params.editionId) {
EditionActions.fetchEdition(this.props.params.editionId); EditionActions.flushEdition();
this.loadEdition(nextProps.params.editionId);
} }
}, },
componentDidUpdate() { componentDidUpdate() {
const { editionMeta } = this.state; const { err: editionErr } = this.state.editionMeta;
if(editionMeta.err && editionMeta.err.json && editionMeta.err.json.status === 404) {
if (editionErr && editionErr.json && editionErr.json.status === 404) {
this.throws(new ResourceNotFoundError(getLangText("Oops, the edition you're looking for doesn't exist."))); this.throws(new ResourceNotFoundError(getLangText("Oops, the edition you're looking for doesn't exist.")));
} }
}, },
@ -81,18 +77,22 @@ let EditionContainer = React.createClass({
if(state && state.edition && state.edition.digital_work) { if(state && state.edition && state.edition.digital_work) {
let isEncoding = state.edition.digital_work.isEncoding; let isEncoding = state.edition.digital_work.isEncoding;
if (state.edition.digital_work.mime === 'video' && typeof isEncoding === 'number' && isEncoding !== 100 && !this.state.timerId) { if (state.edition.digital_work.mime === 'video' && typeof isEncoding === 'number' && isEncoding !== 100 && !this.state.timerId) {
let timerId = window.setInterval(() => EditionActions.fetchOne(this.props.params.editionId), 10000); let timerId = window.setInterval(() => EditionActions.fetchEdition(this.props.params.editionId), 10000);
this.setState({timerId: timerId}); this.setState({timerId: timerId});
} }
} }
}, },
loadEdition(editionId = this.props.params.editionId) {
EditionActions.fetchEdition(editionId);
},
render() { render() {
const { edition, currentUser, coaMeta } = this.state; const { edition, currentUser, coaMeta } = this.state;
const { actionPanelButtonListType, furtherDetailsType } = this.props; const { actionPanelButtonListType, furtherDetailsType } = this.props;
if (Object.keys(edition).length && edition.id) { if (edition.id) {
setDocumentTitle([edition.artist_name, edition.title].join(', ')); setDocumentTitle(`${edition.artist_name}, ${edition.title}`);
return ( return (
<Edition <Edition
@ -101,7 +101,7 @@ let EditionContainer = React.createClass({
edition={edition} edition={edition}
coaError={coaMeta.err} coaError={coaMeta.err}
currentUser={currentUser} currentUser={currentUser}
loadEdition={() => EditionActions.fetchEdition(this.props.params.editionId)} /> loadEdition={this.loadEdition} />
); );
} else { } else {
return ( return (

View File

@ -5,25 +5,27 @@ import React from 'react';
import Row from 'react-bootstrap/lib/Row'; import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col'; import Col from 'react-bootstrap/lib/Col';
import Form from './../ascribe_forms/form';
import PieceExtraDataForm from './../ascribe_forms/form_piece_extradata';
import GlobalNotificationModel from '../../models/global_notification_model'; import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions'; import GlobalNotificationActions from '../../actions/global_notification_actions';
import FurtherDetailsFileuploader from './further_details_fileuploader'; import FurtherDetailsFileuploader from './further_details_fileuploader';
import Form from './../ascribe_forms/form';
import PieceExtraDataForm from './../ascribe_forms/form_piece_extradata';
import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils'; import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils';
import { getLangText } from '../../utils/lang_utils';
let FurtherDetails = React.createClass({ let FurtherDetails = React.createClass({
propTypes: { propTypes: {
pieceId: React.PropTypes.number.isRequired,
editable: React.PropTypes.bool, editable: React.PropTypes.bool,
pieceId: React.PropTypes.number,
extraData: React.PropTypes.object, extraData: React.PropTypes.object,
handleSuccess: React.PropTypes.func,
otherData: React.PropTypes.arrayOf(React.PropTypes.object), otherData: React.PropTypes.arrayOf(React.PropTypes.object),
handleSuccess: React.PropTypes.func
}, },
getInitialState() { getInitialState() {
@ -32,13 +34,18 @@ let FurtherDetails = React.createClass({
}; };
}, },
showNotification(){ showNotification() {
this.props.handleSuccess(); const { handleSuccess } = this.props;
let notification = new GlobalNotificationModel('Details updated', 'success');
if (typeof handleSucess === 'function') {
handleSuccess();
}
const notification = new GlobalNotificationModel(getLangText('Details updated'), 'success');
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },
submitFile(file){ submitFile(file) {
this.setState({ this.setState({
otherDataKey: file.key otherDataKey: file.key
}); });
@ -51,40 +58,42 @@ let FurtherDetails = React.createClass({
}, },
render() { render() {
const { editable, extraData, otherData, pieceId } = this.props;
return ( return (
<Row> <Row>
<Col md={12} className="ascribe-edition-personal-note"> <Col md={12} className="ascribe-edition-personal-note">
<PieceExtraDataForm <PieceExtraDataForm
name='artist_contact_info' name='artist_contact_info'
title='Artist Contact Info' title='Artist Contact Info'
convertLinks
editable={editable}
extraData={extraData}
handleSuccess={this.showNotification} handleSuccess={this.showNotification}
editable={this.props.editable} pieceId={pieceId} />
pieceId={this.props.pieceId}
extraData={this.props.extraData}
/>
<PieceExtraDataForm <PieceExtraDataForm
name='display_instructions' name='display_instructions'
title='Display Instructions' title='Display Instructions'
editable={editable}
extraData={extraData}
handleSuccess={this.showNotification} handleSuccess={this.showNotification}
editable={this.props.editable} pieceId={pieceId} />
pieceId={this.props.pieceId}
extraData={this.props.extraData} />
<PieceExtraDataForm <PieceExtraDataForm
name='technology_details' name='technology_details'
title='Technology Details' title='Technology Details'
editable={editable}
extraData={extraData}
handleSuccess={this.showNotification} handleSuccess={this.showNotification}
editable={this.props.editable} pieceId={pieceId} />
pieceId={this.props.pieceId}
extraData={this.props.extraData} />
<Form> <Form>
<FurtherDetailsFileuploader <FurtherDetailsFileuploader
submitFile={this.submitFile} submitFile={this.submitFile}
setIsUploadReady={this.setIsUploadReady} setIsUploadReady={this.setIsUploadReady}
isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile} isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile}
editable={this.props.editable} editable={editable}
overrideForm={true} overrideForm={true}
pieceId={this.props.pieceId} pieceId={pieceId}
otherData={this.props.otherData} otherData={otherData}
multiple={true} /> multiple={true} />
</Form> </Form>
</Col> </Col>

View File

@ -8,6 +8,7 @@ import ReactS3FineUploader from './../ascribe_uploader/react_s3_fine_uploader';
import ApiUrls from '../../constants/api_urls'; import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants'; import AppConstants from '../../constants/application_constants';
import { validationTypes } from '../../constants/uploader_constants';
import { getCookie } from '../../utils/fetch_api_utils'; import { getCookie } from '../../utils/fetch_api_utils';
import { getLangText } from '../../utils/lang_utils'; import { getLangText } from '../../utils/lang_utils';
@ -15,20 +16,26 @@ import { getLangText } from '../../utils/lang_utils';
let FurtherDetailsFileuploader = React.createClass({ let FurtherDetailsFileuploader = React.createClass({
propTypes: { propTypes: {
pieceId: React.PropTypes.number.isRequired,
areAssetsDownloadable: React.PropTypes.bool,
editable: React.PropTypes.bool,
isReadyForFormSubmission: React.PropTypes.func,
label: React.PropTypes.string, label: React.PropTypes.string,
pieceId: React.PropTypes.number, multiple: React.PropTypes.bool,
otherData: React.PropTypes.arrayOf(React.PropTypes.object), otherData: React.PropTypes.arrayOf(React.PropTypes.object),
onValidationFailed: React.PropTypes.func,
setIsUploadReady: React.PropTypes.func, setIsUploadReady: React.PropTypes.func,
submitFile: React.PropTypes.func, submitFile: React.PropTypes.func,
isReadyForFormSubmission: React.PropTypes.func, validation: ReactS3FineUploader.propTypes.validation
editable: React.PropTypes.bool,
multiple: React.PropTypes.bool
}, },
getDefaultProps() { getDefaultProps() {
return { return {
areAssetsDownloadable: true,
label: getLangText('Additional files'), label: getLangText('Additional files'),
multiple: false multiple: false,
validation: validationTypes.additionalData
}; };
}, },
@ -58,8 +65,9 @@ let FurtherDetailsFileuploader = React.createClass({
url: ApiUrls.blob_otherdatas, url: ApiUrls.blob_otherdatas,
pieceId: this.props.pieceId pieceId: this.props.pieceId
}} }}
validation={AppConstants.fineUploader.validation.additionalData} validation={this.props.validation}
submitFile={this.props.submitFile} submitFile={this.props.submitFile}
onValidationFailed={this.props.onValidationFailed}
setIsUploadReady={this.props.setIsUploadReady} setIsUploadReady={this.props.setIsUploadReady}
isReadyForFormSubmission={this.props.isReadyForFormSubmission} isReadyForFormSubmission={this.props.isReadyForFormSubmission}
session={{ session={{
@ -89,7 +97,7 @@ let FurtherDetailsFileuploader = React.createClass({
'X-CSRFToken': getCookie(AppConstants.csrftoken) 'X-CSRFToken': getCookie(AppConstants.csrftoken)
} }
}} }}
areAssetsDownloadable={true} areAssetsDownloadable={this.props.areAssetsDownloadable}
areAssetsEditable={this.props.editable} areAssetsEditable={this.props.editable}
multiple={this.props.multiple} /> multiple={this.props.multiple} />
</Property> </Property>

View File

@ -22,7 +22,11 @@ let HistoryIterator = React.createClass({
return ( return (
<span> <span>
{historicalEventDescription} {historicalEventDescription}
<a href={historicalEvent[2]} target="_blank">{contractName}</a> <a className="anchor-no-expand-print"
target="_blank"
href={historicalEvent[2]}>
{contractName}
</a>
</span> </span>
); );
} else if(historicalEvent.length === 2) { } else if(historicalEvent.length === 2) {

View File

@ -14,11 +14,9 @@ import CollapsibleButton from './../ascribe_collapsible/collapsible_button';
import AclProxy from '../acl_proxy'; import AclProxy from '../acl_proxy';
import UserActions from '../../actions/user_actions'; import { getLangText } from '../../utils/lang_utils';
import UserStore from '../../stores/user_store'; import { extractFileExtensionFromString } from '../../utils/file_utils';
import { mergeOptions } from '../../utils/general_utils.js';
import { getLangText } from '../../utils/lang_utils.js';
const EMBED_IFRAME_HEIGHT = { const EMBED_IFRAME_HEIGHT = {
video: 315, video: 315,
@ -28,25 +26,22 @@ const EMBED_IFRAME_HEIGHT = {
let MediaContainer = React.createClass({ let MediaContainer = React.createClass({
propTypes: { propTypes: {
content: React.PropTypes.object, content: React.PropTypes.object,
currentUser: React.PropTypes.object,
refreshObject: React.PropTypes.func refreshObject: React.PropTypes.func
}, },
getInitialState() { getInitialState() {
return mergeOptions( return {
UserStore.getState(),
{
timerId: null timerId: null
}); };
}, },
componentDidMount() { componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
if (!this.props.content.digital_work) { if (!this.props.content.digital_work) {
return; return;
} }
let isEncoding = this.props.content.digital_work.isEncoding;
const isEncoding = this.props.content.digital_work.isEncoding;
if (this.props.content.digital_work.mime === 'video' && typeof isEncoding === 'number' && isEncoding !== 100 && !this.state.timerId) { if (this.props.content.digital_work.mime === 'video' && typeof isEncoding === 'number' && isEncoding !== 100 && !this.state.timerId) {
let timerId = window.setInterval(this.props.refreshObject, 10000); let timerId = window.setInterval(this.props.refreshObject, 10000);
this.setState({timerId: timerId}); this.setState({timerId: timerId});
@ -60,22 +55,26 @@ let MediaContainer = React.createClass({
}, },
componentWillUnmount() { componentWillUnmount() {
UserStore.unlisten(this.onChange);
window.clearInterval(this.state.timerId); window.clearInterval(this.state.timerId);
}, },
onChange(state) {
this.setState(state);
},
render() { render() {
const { content } = this.props; const { content, currentUser } = this.props;
// Pieces and editions are joined to the user by a foreign key in the database, so // Pieces and editions are joined to the user by a foreign key in the database, so
// the information in content will be updated if a user updates their username. // the information in content will be updated if a user updates their username.
// We also force uniqueness of usernames, so this check is safe to dtermine if the // We also force uniqueness of usernames, so this check is safe to dtermine if the
// content was registered by the current user. // content was registered by the current user.
const didUserRegisterContent = this.state.currentUser && (this.state.currentUser.username === content.user_registered); const didUserRegisterContent = currentUser && (currentUser.username === content.user_registered);
// We want to show the file's extension as a label of the download button.
// We can however not only use `extractFileExtensionFromString` on the url for that
// as files might be saved on S3 without a file extension which leads
// `extractFileExtensionFromString` to extract everything starting from the top level
// domain: e.g. '.net/live/<hash>'.
// Therefore, we extract the file's name (last part of url, separated with a slash)
// and try to extract the file extension from there.
const fileName = content.digital_work.url.split('/').pop();
const fileExtension = extractFileExtensionFromString(fileName);
let thumbnail = content.thumbnail.thumbnail_sizes && content.thumbnail.thumbnail_sizes['600x600'] ? let thumbnail = content.thumbnail.thumbnail_sizes && content.thumbnail.thumbnail_sizes['600x600'] ?
content.thumbnail.thumbnail_sizes['600x600'] : content.thumbnail.url_safe; content.thumbnail.thumbnail_sizes['600x600'] : content.thumbnail.url_safe;
@ -94,8 +93,11 @@ let MediaContainer = React.createClass({
embed = ( embed = (
<CollapsibleButton <CollapsibleButton
button={ button={
<Button bsSize="xsmall" className="ascribe-margin-1px" disabled={isEmbedDisabled ? '"disabled"' : ''}> <Button
Embed bsSize="xsmall"
className="ascribe-margin-1px"
disabled={isEmbedDisabled}>
{getLangText('Embed')}
</Button> </Button>
} }
panel={ panel={
@ -114,7 +116,7 @@ let MediaContainer = React.createClass({
url={content.digital_work.url} url={content.digital_work.url}
extraData={extraData} extraData={extraData}
encodingStatus={content.digital_work.isEncoding} /> encodingStatus={content.digital_work.isEncoding} />
<p className="text-center"> <p className="text-center hidden-print">
<span className="ascribe-social-button-list"> <span className="ascribe-social-button-list">
<FacebookShareButton /> <FacebookShareButton />
<TwitterShareButton <TwitterShareButton
@ -125,8 +127,16 @@ let MediaContainer = React.createClass({
show={['video', 'audio', 'image'].indexOf(mimetype) === -1 || content.acl.acl_download} show={['video', 'audio', 'image'].indexOf(mimetype) === -1 || content.acl.acl_download}
aclObject={content.acl} aclObject={content.acl}
aclName="acl_download"> aclName="acl_download">
<Button bsSize="xsmall" className="ascribe-margin-1px" href={this.props.content.digital_work.url} target="_blank"> <Button
Download .{mimetype} <Glyphicon glyph="cloud-download"/> bsSize="xsmall"
className="ascribe-margin-1px"
href={content.digital_work.url}
target="_blank">
{/*
If it turns out that `fileExtension` is an empty string, we're just
using the label 'file'.
*/}
{getLangText('Download')} .{fileExtension || 'file'} <Glyphicon glyph="cloud-download"/>
</Button> </Button>
</AclProxy> </AclProxy>
{embed} {embed}

View File

@ -16,10 +16,10 @@ import MediaContainer from './media_container';
let Piece = React.createClass({ let Piece = React.createClass({
propTypes: { propTypes: {
piece: React.PropTypes.object, piece: React.PropTypes.object,
currentUser: React.PropTypes.object,
header: React.PropTypes.object, header: React.PropTypes.object,
subheader: React.PropTypes.object, subheader: React.PropTypes.object,
buttons: React.PropTypes.object, buttons: React.PropTypes.object,
loadPiece: React.PropTypes.func,
children: React.PropTypes.oneOfType([ children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element), React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element React.PropTypes.element
@ -28,24 +28,26 @@ let Piece = React.createClass({
updateObject() { updateObject() {
return PieceActions.fetchOne(this.props.piece.id); return PieceActions.fetchPiece(this.props.piece.id);
}, },
render() { render() {
const { buttons, children, currentUser, header, piece, subheader } = this.props;
return ( return (
<Row> <Row>
<Col md={6}> <Col md={6} className="ascribe-print-col-left">
<MediaContainer <MediaContainer
refreshObject={this.updateObject} content={piece}
content={this.props.piece}/> currentUser={currentUser}
refreshObject={this.updateObject} />
</Col> </Col>
<Col md={6} className="ascribe-edition-details"> <Col md={6} className="ascribe-edition-details ascribe-print-col-right">
{this.props.header} {header}
{this.props.subheader} {subheader}
{this.props.buttons} {buttons}
{this.props.children}
{children}
</Col> </Col>
</Row> </Row>
); );

View File

@ -69,7 +69,7 @@ let PieceContainer = React.createClass({
return mergeOptions( return mergeOptions(
UserStore.getState(), UserStore.getState(),
PieceListStore.getState(), PieceListStore.getState(),
PieceStore.getState(), PieceStore.getInitialState(),
{ {
showCreateEditionsDialog: false showCreateEditionsDialog: false
} }
@ -81,19 +81,24 @@ let PieceContainer = React.createClass({
PieceListStore.listen(this.onChange); PieceListStore.listen(this.onChange);
PieceStore.listen(this.onChange); PieceStore.listen(this.onChange);
// Every time we enter the piece detail page, just reset the piece
// store as it will otherwise display wrong/old data once the user loads
// the piece detail a second time
PieceActions.updatePiece({});
this.loadPiece(); this.loadPiece();
UserActions.fetchCurrentUser(); UserActions.fetchCurrentUser();
}, },
componentDidUpdate() { // This is done to update the container when the user clicks on the prev or next
const { pieceError } = this.state; // button to update the URL parameter (and therefore to switch pieces) or
// when the user clicks on a notification while being in another piece view
componentWillReceiveProps(nextProps) {
if (this.props.params.pieceId !== nextProps.params.pieceId) {
PieceActions.flushPiece();
this.loadPiece(nextProps.params.pieceId);
}
},
if (pieceError && pieceError.status === 404) { componentDidUpdate() {
const { err: pieceErr } = this.state.pieceMeta;
if (pieceErr && pieceErr.json && pieceErr.json.status === 404) {
this.throws(new ResourceNotFoundError(getLangText("Oops, the piece you're looking for doesn't exist."))); this.throws(new ResourceNotFoundError(getLangText("Oops, the piece you're looking for doesn't exist.")));
} }
}, },
@ -116,8 +121,7 @@ let PieceContainer = React.createClass({
ALSO, WE ENABLED THE LOAN BUTTON FOR IKONOTV TO LET THEM LOAN ON A PIECE LEVEL ALSO, WE ENABLED THE LOAN BUTTON FOR IKONOTV TO LET THEM LOAN ON A PIECE LEVEL
*/ */
if(state && state.piece && state.piece.acl && typeof state.piece.acl.acl_loan !== 'undefined') { if (state && state.piece && state.piece.acl && typeof state.piece.acl.acl_loan !== 'undefined') {
let pieceState = mergeOptions({}, state.piece); let pieceState = mergeOptions({}, state.piece);
pieceState.acl.acl_loan = false; pieceState.acl.acl_loan = false;
this.setState({ this.setState({
@ -129,11 +133,10 @@ let PieceContainer = React.createClass({
} }
}, },
loadPiece() { loadPiece(pieceId = this.props.params.pieceId) {
PieceActions.fetchOne(this.props.params.pieceId); PieceActions.fetchPiece(pieceId);
}, },
toggleCreateEditionsDialog() { toggleCreateEditionsDialog() {
this.setState({ this.setState({
showCreateEditionsDialog: !this.state.showCreateEditionsDialog showCreateEditionsDialog: !this.state.showCreateEditionsDialog
@ -141,43 +144,47 @@ let PieceContainer = React.createClass({
}, },
handleEditionCreationSuccess() { handleEditionCreationSuccess() {
PieceActions.updateProperty({key: 'num_editions', value: 0}); const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search,
this.state.orderBy, this.state.orderAsc, this.state.filterBy); PieceActions.updateProperty({ key: 'num_editions', value: 0 });
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
this.toggleCreateEditionsDialog(); this.toggleCreateEditionsDialog();
}, },
handleDeleteSuccess(response) { handleDeleteSuccess(response) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
// since we're deleting a piece, we just need to close // since we're deleting a piece, we just need to close
// all editions dialogs and not reload them // all editions dialogs and not reload them
EditionListActions.closeAllEditionLists(); EditionListActions.closeAllEditionLists();
EditionListActions.clearAllEditionSelections(); EditionListActions.clearAllEditionSelections();
let notification = new GlobalNotificationModel(response.notification, 'success'); const notification = new GlobalNotificationModel(response.notification, 'success');
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.history.pushState(null, '/collection'); this.history.push('/collection');
}, },
getCreateEditionsDialog() { getCreateEditionsDialog() {
if(this.state.piece.num_editions < 1 && this.state.showCreateEditionsDialog) { if (this.state.piece.num_editions < 1 && this.state.showCreateEditionsDialog) {
return ( return (
<div style={{marginTop: '1em'}}> <div style={{marginTop: '1em'}}>
<CreateEditionsForm <CreateEditionsForm
pieceId={this.state.piece.id} pieceId={this.state.piece.id}
handleSuccess={this.handleEditionCreationSuccess} /> handleSuccess={this.handleEditionCreationSuccess} />
<hr/> <hr />
</div> </div>
); );
} else { } else {
return (<hr/>); return (<hr />);
} }
}, },
handlePollingSuccess(pieceId, numEditions) { handlePollingSuccess(pieceId, numEditions) {
const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
// we need to refresh the num_editions property of the actual piece we're looking at // we need to refresh the num_editions property of the actual piece we're looking at
PieceActions.updateProperty({ PieceActions.updateProperty({
@ -189,27 +196,26 @@ let PieceContainer = React.createClass({
// btw.: It's not sufficient to just set num_editions to numEditions, since a single accordion // btw.: It's not sufficient to just set num_editions to numEditions, since a single accordion
// list item also uses the firstEdition property which we can only get from the server in that case. // list item also uses the firstEdition property which we can only get from the server in that case.
// Therefore we need to at least refetch the changed piece from the server or on our case simply all // Therefore we need to at least refetch the changed piece from the server or on our case simply all
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
let notification = new GlobalNotificationModel('Editions successfully created', 'success', 10000); const notification = new GlobalNotificationModel(getLangText('Editions successfully created'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },
getId() { getId() {
return {'id': this.state.piece.id}; return { 'id': this.state.piece.id };
}, },
getActions() { getActions() {
const { piece, currentUser } = this.state; const { piece, currentUser } = this.state;
if (piece && piece.notifications && piece.notifications.length > 0) { if (piece.notifications && piece.notifications.length > 0) {
return ( return (
<ListRequestActions <ListRequestActions
pieceOrEditions={piece} pieceOrEditions={piece}
currentUser={currentUser} currentUser={currentUser}
handleSuccess={this.loadPiece} handleSuccess={this.loadPiece}
notifications={piece.notifications}/>); notifications={piece.notifications} />);
} else { } else {
return ( return (
<AclProxy <AclProxy
@ -219,7 +225,9 @@ let PieceContainer = React.createClass({
no more than 1 key, we're hiding the `DetailProperty` actions as otherwise no more than 1 key, we're hiding the `DetailProperty` actions as otherwise
`AclInformation` would show up `AclInformation` would show up
*/} */}
<DetailProperty label={getLangText('ACTIONS')}> <DetailProperty
label={getLangText('ACTIONS')}
className="hidden-print">
<AclButtonList <AclButtonList
className="ascribe-button-list" className="ascribe-button-list"
availableAcls={piece.acl} availableAcls={piece.acl}
@ -233,12 +241,12 @@ let PieceContainer = React.createClass({
onPollingSuccess={this.handlePollingSuccess}/> onPollingSuccess={this.handlePollingSuccess}/>
<DeleteButton <DeleteButton
handleSuccess={this.handleDeleteSuccess} handleSuccess={this.handleDeleteSuccess}
piece={piece}/> piece={piece} />
<AclInformation <AclInformation
aim="button" aim="button"
verbs={['acl_share', 'acl_transfer', 'acl_create_editions', 'acl_loan', 'acl_delete', verbs={['acl_share', 'acl_transfer', 'acl_create_editions', 'acl_loan', 'acl_delete',
'acl_consign']} 'acl_consign']}
aclObject={piece.acl}/> aclObject={piece.acl} />
</AclButtonList> </AclButtonList>
</DetailProperty> </DetailProperty>
</AclProxy> </AclProxy>
@ -247,76 +255,76 @@ let PieceContainer = React.createClass({
}, },
render() { render() {
if (this.state.piece && this.state.piece.id) { const { furtherDetailsType: FurtherDetailsType } = this.props;
let FurtherDetailsType = this.props.furtherDetailsType; const { currentUser, piece } = this.state;
setDocumentTitle([this.state.piece.artist_name, this.state.piece.title].join(', '));
if (piece.id) {
setDocumentTitle(`${piece.artist_name}, ${piece.title}`);
return ( return (
<Piece <Piece
piece={this.state.piece} piece={piece}
loadPiece={this.loadPiece} currentUser={currentUser}
header={ header={
<div className="ascribe-detail-header"> <div className="ascribe-detail-header">
<hr style={{marginTop: 0}}/> <hr className="hidden-print" style={{marginTop: 0}} />
<h1 className="ascribe-detail-title">{this.state.piece.title}</h1> <h1 className="ascribe-detail-title">{piece.title}</h1>
<DetailProperty label="BY" value={this.state.piece.artist_name} /> <DetailProperty label="CREATED BY" value={piece.artist_name} />
<DetailProperty label="DATE" value={Moment(this.state.piece.date_created, 'YYYY-MM-DD').year() } /> <DetailProperty label="DATE" value={Moment(piece.date_created, 'YYYY-MM-DD').year() } />
{this.state.piece.num_editions > 0 ? <DetailProperty label="EDITIONS" value={ this.state.piece.num_editions } /> : null} {piece.num_editions > 0 ? <DetailProperty label="EDITIONS" value={ piece.num_editions } /> : null}
<hr/> <hr/>
</div> </div>
} }
subheader={ subheader={
<div className="ascribe-detail-header"> <div className="ascribe-detail-header">
<DetailProperty label={getLangText('REGISTREE')} value={ this.state.piece.user_registered } /> <DetailProperty label={getLangText('ASCRIBED BY')} value={ piece.user_registered } />
<DetailProperty label={getLangText('ID')} value={ this.state.piece.bitcoin_id } ellipsis={true} /> <DetailProperty label={getLangText('ID')} value={ piece.bitcoin_id } ellipsis={true} />
<LicenseDetail license={this.state.piece.license_type} /> <LicenseDetail license={piece.license_type} />
</div> </div>
} }
buttons={this.getActions()}> buttons={this.getActions()}>
{this.getCreateEditionsDialog()} {this.getCreateEditionsDialog()}
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Loan History')} title={getLangText('Loan History')}
show={this.state.piece.loan_history && this.state.piece.loan_history.length > 0}> show={piece.loan_history && piece.loan_history.length > 0}>
<HistoryIterator <HistoryIterator
history={this.state.piece.loan_history} /> history={piece.loan_history} />
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Notes')} title={getLangText('Notes')}
show={!!(this.state.currentUser.username show={!!(currentUser.username || piece.acl.acl_edit || piece.public_note)}>
|| this.state.piece.acl.acl_edit
|| this.state.piece.public_note)}>
<Note <Note
id={this.getId} id={this.getId}
label={getLangText('Personal note (private)')} label={getLangText('Personal note (private)')}
defaultValue={this.state.piece.private_note || null} defaultValue={piece.private_note || null}
show = {!!this.state.currentUser.username} show = {!!currentUser.username}
placeholder={getLangText('Enter your comments ...')} placeholder={getLangText('Enter your comments ...')}
editable={true} editable={true}
successMessage={getLangText('Private note saved')} successMessage={getLangText('Private note saved')}
url={ApiUrls.note_private_piece} url={ApiUrls.note_private_piece}
currentUser={this.state.currentUser}/> currentUser={currentUser} />
<Note <Note
id={this.getId} id={this.getId}
label={getLangText('Personal note (public)')} label={getLangText('Personal note (public)')}
defaultValue={this.state.piece.public_note || null} defaultValue={piece.public_note || null}
placeholder={getLangText('Enter your comments ...')} placeholder={getLangText('Enter your comments ...')}
editable={!!this.state.piece.acl.acl_edit} editable={!!piece.acl.acl_edit}
show={!!(this.state.piece.public_note || this.state.piece.acl.acl_edit)} show={!!(piece.public_note || piece.acl.acl_edit)}
successMessage={getLangText('Public note saved')} successMessage={getLangText('Public note saved')}
url={ApiUrls.note_public_piece} url={ApiUrls.note_public_piece}
currentUser={this.state.currentUser}/> currentUser={currentUser} />
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Further Details')} title={getLangText('Further Details')}
show={this.state.piece.acl.acl_edit show={piece.acl.acl_edit
|| Object.keys(this.state.piece.extra_data).length > 0 || Object.keys(piece.extra_data).length > 0
|| this.state.piece.other_data.length > 0} || piece.other_data.length > 0}
defaultExpanded={true}> defaultExpanded={true}>
<FurtherDetailsType <FurtherDetailsType
editable={this.state.piece.acl.acl_edit} editable={piece.acl.acl_edit}
pieceId={this.state.piece.id} pieceId={piece.id}
extraData={this.state.piece.extra_data} extraData={piece.extra_data}
otherData={this.state.piece.other_data} otherData={piece.other_data}
handleSuccess={this.loadPiece} /> handleSuccess={this.loadPiece} />
</CollapsibleParagraph> </CollapsibleParagraph>

View File

@ -19,7 +19,7 @@ let CreateEditionsForm = React.createClass({
pieceId: React.PropTypes.number pieceId: React.PropTypes.number
}, },
getFormData(){ getFormData() {
return { return {
piece_id: parseInt(this.props.pieceId, 10) piece_id: parseInt(this.props.pieceId, 10)
}; };
@ -58,7 +58,8 @@ let CreateEditionsForm = React.createClass({
<input <input
type="number" type="number"
placeholder="(e.g. 32)" placeholder="(e.g. 32)"
min={1}/> min={1}
max={100} />
</Property> </Property>
</Form> </Form>
); );

View File

@ -178,20 +178,20 @@ let Form = React.createClass({
let formData = this.getFormData(); let formData = this.getFormData();
// sentry shouldn't post the user's password // sentry shouldn't post the user's password
if(formData.password) { if (formData.password) {
delete formData.password; delete formData.password;
} }
console.logGlobal(err, formData); console.logGlobal(err, formData);
if(this.props.isInline) { if (this.props.isInline) {
let notification = new GlobalNotificationModel(getLangText('Something went wrong, please try again later'), 'danger'); let notification = new GlobalNotificationModel(getLangText('Something went wrong, please try again later'), 'danger');
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
} else { } else {
this.setState({errors: [getLangText('Something went wrong, please try again later')]}); this.setState({errors: [getLangText('Something went wrong, please try again later')]});
} }
} }
this.setState({submitted: false}); this.setState({submitted: false});
}, },
@ -205,16 +205,15 @@ let Form = React.createClass({
}, },
getButtons() { getButtons() {
if (this.state.submitted){ if (this.state.submitted) {
return this.props.spinner; return this.props.spinner;
} }
if (this.props.buttons){ if (this.props.buttons !== undefined) {
return this.props.buttons; return this.props.buttons;
} }
let buttons = null;
if (this.state.edited && !this.props.disabled){ if (this.state.edited && !this.props.disabled) {
buttons = ( return (
<div className="row" style={{margin: 0}}> <div className="row" style={{margin: 0}}>
<p className="pull-right"> <p className="pull-right">
<Button <Button
@ -230,9 +229,9 @@ let Form = React.createClass({
</p> </p>
</div> </div>
); );
} else {
return null;
} }
return buttons;
}, },
getErrors() { getErrors() {

View File

@ -41,6 +41,14 @@ let ConsignForm = React.createClass({
}; };
}, },
componentWillReceiveProps(nextProps) {
if (this.props.email !== nextProps.email) {
this.setState({
email: nextProps.email
});
}
},
getFormData() { getFormData() {
return this.props.id; return this.props.id;
}, },

View File

@ -2,19 +2,20 @@
import React from 'react'; import React from 'react';
import Form from '../ascribe_forms/form'; import ContractListActions from '../../actions/contract_list_actions';
import Property from '../ascribe_forms/property';
import GlobalNotificationModel from '../../models/global_notification_model'; import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions'; import GlobalNotificationActions from '../../actions/global_notification_actions';
import ContractListActions from '../../actions/contract_list_actions';
import AppConstants from '../../constants/application_constants';
import ApiUrls from '../../constants/api_urls';
import InputFineUploader from './input_fineuploader'; import InputFineUploader from './input_fineuploader';
import Form from '../ascribe_forms/form';
import Property from '../ascribe_forms/property';
import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants';
import { validationTypes } from '../../constants/uploader_constants';
import { getLangText } from '../../utils/lang_utils'; import { getLangText } from '../../utils/lang_utils';
import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils'; import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils';
@ -78,8 +79,8 @@ let CreateContractForm = React.createClass({
url: ApiUrls.blob_contracts url: ApiUrls.blob_contracts
}} }}
validation={{ validation={{
itemLimit: AppConstants.fineUploader.validation.additionalData.itemLimit, itemLimit: validationTypes.additionalData.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit, sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: ['pdf'] allowedExtensions: ['pdf']
}} }}
areAssetsDownloadable={true} areAssetsDownloadable={true}

View File

@ -61,6 +61,14 @@ let LoanForm = React.createClass({
}; };
}, },
componentWillReceiveProps(nextProps) {
if (this.props.email !== nextProps.email) {
this.setState({
email: nextProps.email
});
}
},
onChange(state) { onChange(state) {
this.setState(state); this.setState(state);
}, },

View File

@ -13,43 +13,48 @@ import InputTextAreaToggable from './input_textarea_toggable';
let PieceExtraDataForm = React.createClass({ let PieceExtraDataForm = React.createClass({
propTypes: { propTypes: {
pieceId: React.PropTypes.number, name: React.PropTypes.string.isRequired,
pieceId: React.PropTypes.number.isRequired,
convertLinks: React.PropTypes.bool,
editable: React.PropTypes.bool,
extraData: React.PropTypes.object, extraData: React.PropTypes.object,
handleSuccess: React.PropTypes.func, handleSuccess: React.PropTypes.func,
name: React.PropTypes.string, title: React.PropTypes.string
title: React.PropTypes.string,
editable: React.PropTypes.bool
}, },
getFormData() { getFormData() {
let extradata = {};
extradata[this.props.name] = this.refs.form.refs[this.props.name].state.value;
return { return {
extradata: extradata, extradata: {
[this.props.name]: this.refs.form.refs[this.props.name].state.value
},
piece_id: this.props.pieceId piece_id: this.props.pieceId
}; };
}, },
render() { render() {
let defaultValue = this.props.extraData[this.props.name] || ''; const { convertLinks, editable, extraData, handleSuccess, name, pieceId, title } = this.props;
if (defaultValue.length === 0 && !this.props.editable){ const defaultValue = (extraData && extraData[name]) || null;
if (!defaultValue && !editable) {
return null; return null;
} }
let url = requests.prepareUrl(ApiUrls.piece_extradata, {piece_id: this.props.pieceId});
return ( return (
<Form <Form
ref='form' ref='form'
url={url} disabled={!editable}
handleSuccess={this.props.handleSuccess}
getFormData={this.getFormData} getFormData={this.getFormData}
disabled={!this.props.editable}> handleSuccess={handleSuccess}
url={requests.prepareUrl(ApiUrls.piece_extradata, { piece_id: pieceId })}>
<Property <Property
name={this.props.name} name={name}
label={this.props.title}> label={title}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
convertLinks={convertLinks}
defaultValue={defaultValue} defaultValue={defaultValue}
placeholder={getLangText('Fill in%s', ' ') + this.props.title} placeholder={getLangText('Fill in%s', ' ') + title}
required /> required />
</Property> </Property>
<hr /> <hr />

View File

@ -8,12 +8,16 @@ import UserActions from '../../actions/user_actions';
import Form from './form'; import Form from './form';
import Property from './property'; import Property from './property';
import InputFineUploader from './input_fineuploader'; import InputFineUploader from './input_fineuploader';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import FormSubmitButton from '../ascribe_buttons/form_submit_button'; import FormSubmitButton from '../ascribe_buttons/form_submit_button';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import AscribeSpinner from '../ascribe_spinner';
import ApiUrls from '../../constants/api_urls'; import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants'; import AppConstants from '../../constants/application_constants';
import AscribeSpinner from '../ascribe_spinner'; import { validationParts, validationTypes } from '../../constants/uploader_constants';
import { getLangText } from '../../utils/lang_utils'; import { getLangText } from '../../utils/lang_utils';
import { mergeOptions } from '../../utils/general_utils'; import { mergeOptions } from '../../utils/general_utils';
@ -109,6 +113,11 @@ let RegisterPieceForm = React.createClass({
); );
}, },
handleThumbnailValidationFailed(thumbnailFile) {
// If the validation fails, set the thumbnail as submittable since its optional
this.refs.submitButton.setReadyStateForKey('thumbnailKeyReady', true);
},
isThumbnailDialogExpanded() { isThumbnailDialogExpanded() {
const { enableSeparateThumbnail } = this.props; const { enableSeparateThumbnail } = this.props;
const { digitalWorkFile } = this.state; const { digitalWorkFile } = this.state;
@ -175,7 +184,7 @@ let RegisterPieceForm = React.createClass({
createBlobRoutine={{ createBlobRoutine={{
url: ApiUrls.blob_digitalworks url: ApiUrls.blob_digitalworks
}} }}
validation={AppConstants.fineUploader.validation.registerWork} validation={validationTypes.registerWork}
setIsUploadReady={this.setIsUploadReady('digitalWorkKeyReady')} setIsUploadReady={this.setIsUploadReady('digitalWorkKeyReady')}
isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile} isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile}
isFineUploaderActive={isFineUploaderActive} isFineUploaderActive={isFineUploaderActive}
@ -194,15 +203,16 @@ let RegisterPieceForm = React.createClass({
url: ApiUrls.blob_thumbnails url: ApiUrls.blob_thumbnails
}} }}
handleChangedFile={this.handleChangedThumbnail} handleChangedFile={this.handleChangedThumbnail}
onValidationFailed={this.handleThumbnailValidationFailed}
isReadyForFormSubmission={formSubmissionValidation.fileOptional} isReadyForFormSubmission={formSubmissionValidation.fileOptional}
keyRoutine={{ keyRoutine={{
url: AppConstants.serverUrl + 's3/key/', url: AppConstants.serverUrl + 's3/key/',
fileClass: 'thumbnail' fileClass: 'thumbnail'
}} }}
validation={{ validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit, itemLimit: validationTypes.workThumbnail.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit, sizeLimit: validationTypes.workThumbnail.sizeLimit,
allowedExtensions: ['png', 'jpg', 'jpeg', 'gif'] allowedExtensions: validationParts.allowedExtensions.images
}} }}
setIsUploadReady={this.setIsUploadReady('thumbnailKeyReady')} setIsUploadReady={this.setIsUploadReady('thumbnailKeyReady')}
fileClassToUpload={{ fileClassToUpload={{
@ -210,9 +220,7 @@ let RegisterPieceForm = React.createClass({
plural: getLangText('Select representative images') plural: getLangText('Select representative images')
}} }}
isFineUploaderActive={isFineUploaderActive} isFineUploaderActive={isFineUploaderActive}
disabled={!isFineUploaderEditable} disabled={!isFineUploaderEditable} />
enableLocalHashing={enableLocalHashing}
uploadMethod={location.query.method} />
</Property> </Property>
<Property <Property
name='artist_name' name='artist_name'

View File

@ -58,7 +58,7 @@ let SendContractAgreementForm = React.createClass({
notification = new GlobalNotificationModel(notification, 'success', 10000); notification = new GlobalNotificationModel(notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.history.pushState(null, '/collection'); this.history.push('/collection');
}, },
getFormData() { getFormData() {

View File

@ -28,11 +28,7 @@ const InputFineUploader = React.createClass({
createBlobRoutine: shape({ createBlobRoutine: shape({
url: string url: string
}), }),
validation: shape({ validation: ReactS3FineUploader.propTypes.validation,
itemLimit: number,
sizeLimit: string,
allowedExtensions: arrayOf(string)
}),
// isFineUploaderActive is used to lock react fine uploader in case // isFineUploaderActive is used to lock react fine uploader in case
// a user is actually not logged in already to prevent him from droping files // a user is actually not logged in already to prevent him from droping files
@ -52,6 +48,7 @@ const InputFineUploader = React.createClass({
plural: string plural: string
}), }),
handleChangedFile: func, handleChangedFile: func,
onValidationFailed: func,
// Provided by `Property` // Provided by `Property`
onChange: React.PropTypes.func onChange: React.PropTypes.func
@ -107,6 +104,7 @@ const InputFineUploader = React.createClass({
isFineUploaderActive, isFineUploaderActive,
isReadyForFormSubmission, isReadyForFormSubmission,
keyRoutine, keyRoutine,
onValidationFailed,
setIsUploadReady, setIsUploadReady,
uploadMethod, uploadMethod,
validation, validation,
@ -127,6 +125,7 @@ const InputFineUploader = React.createClass({
createBlobRoutine={createBlobRoutine} createBlobRoutine={createBlobRoutine}
validation={validation} validation={validation}
submitFile={this.submitFile} submitFile={this.submitFile}
onValidationFailed={onValidationFailed}
setIsUploadReady={setIsUploadReady} setIsUploadReady={setIsUploadReady}
isReadyForFormSubmission={isReadyForFormSubmission} isReadyForFormSubmission={isReadyForFormSubmission}
areAssetsDownloadable={areAssetsDownloadable} areAssetsDownloadable={areAssetsDownloadable}

View File

@ -4,17 +4,20 @@ import React from 'react';
import TextareaAutosize from 'react-textarea-autosize'; import TextareaAutosize from 'react-textarea-autosize';
import { anchorize } from '../../utils/dom_utils';
let InputTextAreaToggable = React.createClass({ let InputTextAreaToggable = React.createClass({
propTypes: { propTypes: {
autoFocus: React.PropTypes.bool, autoFocus: React.PropTypes.bool,
disabled: React.PropTypes.bool, convertLinks: React.PropTypes.bool,
rows: React.PropTypes.number.isRequired,
required: React.PropTypes.bool,
defaultValue: React.PropTypes.string, defaultValue: React.PropTypes.string,
placeholder: React.PropTypes.string, disabled: React.PropTypes.bool,
onBlur: React.PropTypes.func, onBlur: React.PropTypes.func,
onChange: React.PropTypes.func onChange: React.PropTypes.func,
placeholder: React.PropTypes.string,
required: React.PropTypes.bool,
rows: React.PropTypes.number.isRequired
}, },
getInitialState() { getInitialState() {
@ -36,7 +39,7 @@ let InputTextAreaToggable = React.createClass({
componentDidUpdate() { componentDidUpdate() {
// If the initial value of state.value is null, we want to set props.defaultValue // If the initial value of state.value is null, we want to set props.defaultValue
// as a value. In all other cases TextareaAutosize.onChange is updating.handleChange already // as a value. In all other cases TextareaAutosize.onChange is updating.handleChange already
if(this.state.value === null && this.props.defaultValue) { if (this.state.value === null && this.props.defaultValue) {
this.setState({ this.setState({
value: this.props.defaultValue value: this.props.defaultValue
}); });
@ -49,28 +52,26 @@ let InputTextAreaToggable = React.createClass({
}, },
render() { render() {
let className = 'form-control ascribe-textarea'; const { convertLinks, disabled, onBlur, placeholder, required, rows } = this.props;
let textarea = null; const { value } = this.state;
if(!this.props.disabled) { if (!disabled) {
className = className + ' ascribe-textarea-editable'; return (
textarea = (
<TextareaAutosize <TextareaAutosize
ref='textarea' ref='textarea'
className={className} className='form-control ascribe-textarea ascribe-textarea-editable'
value={this.state.value} value={value}
rows={this.props.rows} rows={rows}
maxRows={10} maxRows={10}
required={this.props.required} required={required}
onChange={this.handleChange} onChange={this.handleChange}
onBlur={this.props.onBlur} onBlur={onBlur}
placeholder={this.props.placeholder} /> placeholder={placeholder} />
); );
} else { } else {
textarea = <pre className="ascribe-pre">{this.state.value}</pre>; // Can only convert links when not editable, as textarea does not support anchors
return <pre className="ascribe-pre">{convertLinks ? anchorize(value) : value}</pre>;
} }
return textarea;
} }
}); });

View File

@ -240,7 +240,17 @@ const Property = React.createClass({
}, },
handleCheckboxToggle() { handleCheckboxToggle() {
this.setExpanded(!this.state.expanded); const expanded = !this.state.expanded;
this.setExpanded(expanded);
// Reset the value to be the initial value when the checkbox is unticked since the
// user doesn't want to specify their own value.
if (!expanded) {
this.setState({
value: this.state.initialValue
});
}
}, },
renderChildren(style) { renderChildren(style) {

View File

@ -184,7 +184,7 @@ let Video = React.createClass({
); );
} else { } else {
return ( return (
<Image src={this.props.preview} /> <Image preview={this.props.preview} />
); );
} }
} }

View File

@ -1,19 +1,20 @@
'use strict'; 'use strict';
import React from 'react'; import React from 'react';
import ReactAddons from 'react/addons';
import Modal from 'react-bootstrap/lib/Modal'; import Modal from 'react-bootstrap/lib/Modal';
let ModalWrapper = React.createClass({ let ModalWrapper = React.createClass({
propTypes: { propTypes: {
trigger: React.PropTypes.element,
title: React.PropTypes.oneOfType([ title: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element), React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element, React.PropTypes.element,
React.PropTypes.string React.PropTypes.string
]).isRequired, ]).isRequired,
handleSuccess: React.PropTypes.func.isRequired,
handleCancel: React.PropTypes.func,
handleSuccess: React.PropTypes.func,
trigger: React.PropTypes.element,
children: React.PropTypes.oneOfType([ children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element), React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element React.PropTypes.element
@ -38,15 +39,32 @@ let ModalWrapper = React.createClass({
}); });
}, },
handleCancel() {
if (typeof this.props.handleCancel === 'function') {
this.props.handleCancel();
}
this.hide();
},
handleSuccess(response) { handleSuccess(response) {
if (typeof this.props.handleSuccess === 'function') {
this.props.handleSuccess(response); this.props.handleSuccess(response);
}
this.hide(); this.hide();
}, },
renderChildren() { renderChildren() {
return ReactAddons.Children.map(this.props.children, (child) => { return React.Children.map(this.props.children, (child) => {
return ReactAddons.addons.cloneWithProps(child, { return React.cloneElement(child, {
handleSuccess: this.handleSuccess handleSuccess: (response) => {
if (typeof child.props.handleSuccess === 'function') {
child.props.handleSuccess(response);
}
this.handleSuccess(response);
}
}); });
}); });
}, },
@ -54,14 +72,23 @@ let ModalWrapper = React.createClass({
render() { render() {
const { trigger, title } = this.props; const { trigger, title } = this.props;
// If the trigger component exists, we add the ModalWrapper's show() as its onClick method. // If the trigger component exists, we add the ModalWrapper's show() to its onClick method.
// The trigger component should, in most cases, be a button. // The trigger component should, in most cases, be a button.
const clonedTrigger = React.isValidElement(trigger) ? React.cloneElement(trigger, {onClick: this.show}) const clonedTrigger = React.isValidElement(trigger) ?
: null; React.cloneElement(trigger, {
onClick: (...params) => {
if (typeof trigger.props.onClick === 'function') {
trigger.props.onClick(...params);
}
this.show();
}
}) : null;
return ( return (
<span> <span>
{clonedTrigger} {clonedTrigger}
<Modal show={this.state.showModal} onHide={this.hide}> <Modal show={this.state.showModal} onHide={this.handleCancel}>
<Modal.Header closeButton> <Modal.Header closeButton>
<Modal.Title> <Modal.Title>
{title} {title}

View File

@ -39,30 +39,6 @@ let PieceListToolbar = React.createClass({
]) ])
}, },
getFilterWidget(){
if (this.props.filterParams){
return (
<PieceListToolbarFilterWidget
filterParams={this.props.filterParams}
filterBy={this.props.filterBy}
applyFilterBy={this.props.applyFilterBy} />
);
}
return null;
},
getOrderWidget(){
if (this.props.orderParams){
return (
<PieceListToolbarOrderWidget
orderParams={this.props.orderParams}
orderBy={this.props.orderBy}
applyOrderBy={this.props.applyOrderBy}/>
);
}
return null;
},
render() { render() {
const { className, children, searchFor, searchQuery } = this.props; const { className, children, searchFor, searchQuery } = this.props;
@ -75,8 +51,14 @@ let PieceListToolbar = React.createClass({
{children} {children}
</span> </span>
<span className="pull-right"> <span className="pull-right">
{this.getOrderWidget()} <PieceListToolbarOrderWidget
{this.getFilterWidget()} orderParams={this.props.orderParams}
orderBy={this.props.orderBy}
applyOrderBy={this.props.applyOrderBy}/>
<PieceListToolbarFilterWidget
filterParams={this.props.filterParams}
filterBy={this.props.filterBy}
applyFilterBy={this.props.applyFilterBy} />
</span> </span>
<SearchBar <SearchBar
className="pull-right search-bar ascribe-input-glyph" className="pull-right search-bar ascribe-input-glyph"

View File

@ -30,15 +30,15 @@ let PieceListToolbarFilterWidget = React.createClass({
generateFilterByStatement(param) { generateFilterByStatement(param) {
const filterBy = Object.assign({}, this.props.filterBy); const filterBy = Object.assign({}, this.props.filterBy);
if(filterBy) { if (filterBy) {
// we need hasOwnProperty since the values are all booleans // we need hasOwnProperty since the values are all booleans
if(filterBy.hasOwnProperty(param)) { if (filterBy.hasOwnProperty(param)) {
filterBy[param] = !filterBy[param]; filterBy[param] = !filterBy[param];
// if the parameter is false, then we want to remove it again // if the parameter is false, then we want to remove it again
// from the list of queryParameters as this component is only about // from the list of queryParameters as this component is only about
// which actions *CAN* be done and not what *CANNOT* // which actions *CAN* be done and not what *CANNOT*
if(!filterBy[param]) { if (!filterBy[param]) {
delete filterBy[param]; delete filterBy[param];
} }
@ -66,7 +66,7 @@ let PieceListToolbarFilterWidget = React.createClass({
// We're hiding the star in that complicated matter so that, // We're hiding the star in that complicated matter so that,
// the surrounding button is not resized up on appearance // the surrounding button is not resized up on appearance
if(trueValuesOnly.length > 0) { if (trueValuesOnly.length) {
return { visibility: 'visible'}; return { visibility: 'visible'};
} else { } else {
return { visibility: 'hidden' }; return { visibility: 'hidden' };
@ -81,6 +81,7 @@ let PieceListToolbarFilterWidget = React.createClass({
</span> </span>
); );
if (this.props.filterParams && this.props.filterParams.length) {
return ( return (
<DropdownButton <DropdownButton
pullRight={true} pullRight={true}
@ -90,13 +91,13 @@ let PieceListToolbarFilterWidget = React.createClass({
label also iterate over its items, to get all filterable options */} label also iterate over its items, to get all filterable options */}
{this.props.filterParams.map(({ label, items }, i) => { {this.props.filterParams.map(({ label, items }, i) => {
return ( return (
<div> <div key={label}>
<li <li style={{'textAlign': 'center'}}>
style={{'textAlign': 'center'}}
key={i}>
<em>{label}:</em> <em>{label}:</em>
</li> </li>
{items.map((param, j) => { {items.map((paramItem) => {
let itemLabel;
let param;
// As can be seen in the PropTypes, a param can either // As can be seen in the PropTypes, a param can either
// be a string or an object of the shape: // be a string or an object of the shape:
@ -107,22 +108,22 @@ let PieceListToolbarFilterWidget = React.createClass({
// } // }
// //
// This is why we need to distinguish between both here. // This is why we need to distinguish between both here.
if(typeof param !== 'string') { if (typeof paramItem !== 'string') {
label = param.label; param = paramItem.key;
param = param.key; itemLabel = paramItem.label;
} else { } else {
param = param; param = paramItem;
label = param.split('acl_')[1].replace(/_/g, ' '); itemLabel = paramItem.split('acl_')[1].replace(/_/g, ' ');
} }
return ( return (
<li <li
key={j} key={itemLabel}
onClick={this.filterBy(param)} onClick={this.filterBy(param)}
className="filter-widget-item"> className="filter-widget-item">
<div className="checkbox-line"> <div className="checkbox-line">
<span> <span>
{getLangText(label)} {getLangText(itemLabel)}
</span> </span>
<input <input
readOnly readOnly
@ -137,6 +138,9 @@ let PieceListToolbarFilterWidget = React.createClass({
})} })}
</DropdownButton> </DropdownButton>
); );
} else {
return null;
}
} }
}); });

View File

@ -37,7 +37,7 @@ let PieceListToolbarOrderWidget = React.createClass({
isOrderActive() { isOrderActive() {
// We're hiding the star in that complicated matter so that, // We're hiding the star in that complicated matter so that,
// the surrounding button is not resized up on appearance // the surrounding button is not resized up on appearance
if(this.props.orderBy.length > 0) { if (this.props.orderBy && this.props.orderBy.length) {
return { visibility: 'visible'}; return { visibility: 'visible'};
} else { } else {
return { visibility: 'hidden' }; return { visibility: 'hidden' };
@ -51,8 +51,9 @@ let PieceListToolbarOrderWidget = React.createClass({
<span style={this.isOrderActive()}>&middot;</span> <span style={this.isOrderActive()}>&middot;</span>
</span> </span>
); );
return (
if (this.props.orderParams && this.props.orderParams.length) {
return (
<DropdownButton <DropdownButton
pullRight={true} pullRight={true}
title={filterIcon} title={filterIcon}
@ -62,7 +63,6 @@ let PieceListToolbarOrderWidget = React.createClass({
</li> </li>
{this.props.orderParams.map((param) => { {this.props.orderParams.map((param) => {
return ( return (
<div>
<li <li
key={param} key={param}
onClick={this.orderBy(param)} onClick={this.orderBy(param)}
@ -77,11 +77,13 @@ let PieceListToolbarOrderWidget = React.createClass({
checked={param.indexOf(this.props.orderBy) > -1} /> checked={param.indexOf(this.props.orderBy) > -1} />
</div> </div>
</li> </li>
</div>
); );
})} })}
</DropdownButton> </DropdownButton>
); );
} else {
return null;
}
} }
}); });

View File

@ -40,7 +40,7 @@ export function AuthRedirect({to, when}) {
// and redirect if `true`. // and redirect if `true`.
if(exprToValidate) { if(exprToValidate) {
window.setTimeout(() => history.replaceState(null, to, query)); window.setTimeout(() => history.replace({ query, pathname: to }));
return true; return true;
// Otherwise there can also be the case that the backend // Otherwise there can also be the case that the backend
@ -48,7 +48,7 @@ export function AuthRedirect({to, when}) {
} else if(!exprToValidate && when === 'loggedIn' && redirect) { } else if(!exprToValidate && when === 'loggedIn' && redirect) {
delete query.redirect; delete query.redirect;
window.setTimeout(() => history.replaceState(null, '/' + redirect, query)); window.setTimeout(() => history.replace({ query, pathname: '/' + redirect }));
return true; return true;
} else if(!exprToValidate && when === 'loggedOut' && redirectAuthenticated) { } else if(!exprToValidate && when === 'loggedOut' && redirectAuthenticated) {

View File

@ -28,11 +28,7 @@ import { mergeOptions, truncateTextAtCharIndex } from '../../utils/general_utils
let ContractSettings = React.createClass({ let ContractSettings = React.createClass({
propTypes: { getInitialState() {
location: React.PropTypes.object
},
getInitialState(){
return mergeOptions( return mergeOptions(
ContractListStore.getState(), ContractListStore.getState(),
UserStore.getState() UserStore.getState()
@ -64,40 +60,39 @@ let ContractSettings = React.createClass({
ContractListActions.removeContract(contract.id) ContractListActions.removeContract(contract.id)
.then((response) => { .then((response) => {
ContractListActions.fetchContractList(true); ContractListActions.fetchContractList(true);
let notification = new GlobalNotificationModel(response.notification, 'success', 4000); const notification = new GlobalNotificationModel(response.notification, 'success', 4000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}) })
.catch((err) => { .catch((err) => {
let notification = new GlobalNotificationModel(err, 'danger', 10000); const notification = new GlobalNotificationModel(err, 'danger', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}); });
}; };
}, },
getPublicContracts(){ getPublicContracts() {
return this.state.contractList.filter((contract) => contract.is_public); return this.state.contractList.filter((contract) => contract.is_public);
}, },
getPrivateContracts(){ getPrivateContracts() {
return this.state.contractList.filter((contract) => !contract.is_public); return this.state.contractList.filter((contract) => !contract.is_public);
}, },
render() { render() {
let publicContracts = this.getPublicContracts(); const publicContracts = this.getPublicContracts();
let privateContracts = this.getPrivateContracts(); const privateContracts = this.getPrivateContracts();
let createPublicContractForm = null; let createPublicContractForm = null;
setDocumentTitle(getLangText('Contracts settings')); setDocumentTitle(getLangText('Contracts settings'));
if(publicContracts.length === 0) { if (publicContracts.length === 0) {
createPublicContractForm = ( createPublicContractForm = (
<CreateContractForm <CreateContractForm
isPublic={true} isPublic={true}
fileClassToUpload={{ fileClassToUpload={{
singular: 'new contract', singular: 'new contract',
plural: 'new contracts' plural: 'new contracts'
}} }} />
location={this.props.location}/>
); );
} }
@ -114,7 +109,7 @@ let ContractSettings = React.createClass({
{publicContracts.map((contract, i) => { {publicContracts.map((contract, i) => {
return ( return (
<ActionPanel <ActionPanel
key={i} key={contract.id}
title={contract.name} title={contract.name}
content={truncateTextAtCharIndex(contract.name, 120, '(...).pdf')} content={truncateTextAtCharIndex(contract.name, 120, '(...).pdf')}
buttons={ buttons={
@ -123,8 +118,7 @@ let ContractSettings = React.createClass({
aclObject={this.state.whitelabel} aclObject={this.state.whitelabel}
aclName="acl_update_public_contract"> aclName="acl_update_public_contract">
<ContractSettingsUpdateButton <ContractSettingsUpdateButton
contract={contract} contract={contract} />
location={this.props.location}/>
</AclProxy> </AclProxy>
<a <a
className="btn btn-default btn-sm margin-left-2px" className="btn btn-default btn-sm margin-left-2px"
@ -154,12 +148,11 @@ let ContractSettings = React.createClass({
fileClassToUpload={{ fileClassToUpload={{
singular: getLangText('new contract'), singular: getLangText('new contract'),
plural: getLangText('new contracts') plural: getLangText('new contracts')
}} }} />
location={this.props.location}/>
{privateContracts.map((contract, i) => { {privateContracts.map((contract, i) => {
return ( return (
<ActionPanel <ActionPanel
key={i} key={contract.id}
title={contract.name} title={contract.name}
content={truncateTextAtCharIndex(contract.name, 120, '(...).pdf')} content={truncateTextAtCharIndex(contract.name, 120, '(...).pdf')}
buttons={ buttons={
@ -168,8 +161,7 @@ let ContractSettings = React.createClass({
aclObject={this.state.whitelabel} aclObject={this.state.whitelabel}
aclName="acl_update_private_contract"> aclName="acl_update_private_contract">
<ContractSettingsUpdateButton <ContractSettingsUpdateButton
contract={contract} contract={contract} />
location={this.props.location}/>
</AclProxy> </AclProxy>
<a <a
className="btn btn-default btn-sm margin-left-2px" className="btn btn-default btn-sm margin-left-2px"

View File

@ -2,17 +2,18 @@
import React from 'react'; import React from 'react';
import ReactS3FineUploader from '../ascribe_uploader/react_s3_fine_uploader';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import AppConstants from '../../constants/application_constants';
import ApiUrls from '../../constants/api_urls';
import ContractListActions from '../../actions/contract_list_actions'; import ContractListActions from '../../actions/contract_list_actions';
import GlobalNotificationModel from '../../models/global_notification_model'; import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions'; import GlobalNotificationActions from '../../actions/global_notification_actions';
import ReactS3FineUploader from '../ascribe_uploader/react_s3_fine_uploader';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants';
import { validationTypes } from '../../constants/uploader_constants';
import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils'; import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils';
import { getCookie } from '../../utils/fetch_api_utils'; import { getCookie } from '../../utils/fetch_api_utils';
import { getLangText } from '../../utils/lang_utils'; import { getLangText } from '../../utils/lang_utils';
@ -24,38 +25,42 @@ let ContractSettingsUpdateButton = React.createClass({
}, },
submitFile(file) { submitFile(file) {
let contract = this.props.contract;
// override the blob with the key's value // override the blob with the key's value
contract.blob = file.key; const contract = Object.assign(this.props.contract, { blob: file.key });
// send it to the server // send it to the server
ContractListActions ContractListActions
.changeContract(contract) .changeContract(contract)
.then((res) => { .then((res) => {
// Display feedback to the user // Display feedback to the user
let notification = new GlobalNotificationModel(getLangText('Contract %s successfully updated', res.name), 'success', 5000); const notification = new GlobalNotificationModel(getLangText('Contract %s successfully updated', contract.name), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
// and refresh the contract list to get the updated contracs // and refresh the contract list to get the updated contracs
return ContractListActions.fetchContractList(true); return ContractListActions
}) .fetchContractList(true)
.then(() => { // Also, reset the fineuploader component if fetch is successful so that the user can again 'update' his contract
// Also, reset the fineuploader component so that the user can again 'update' his contract .then(this.refs.fineuploader.reset)
this.refs.fineuploader.reset();
})
.catch((err) => { .catch((err) => {
console.logGlobal(err); const notification = new GlobalNotificationModel(getLangText('Latest contract failed to load'), 'danger', 5000);
let notification = new GlobalNotificationModel(getLangText('Contract could not be updated'), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
return Promise.reject(err);
}); });
}, (err) => {
const notification = new GlobalNotificationModel(getLangText('Contract could not be updated'), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
return Promise.reject(err);
})
.catch(console.logGlobal);
}, },
render() { render() {
return ( return (
<ReactS3FineUploader <ReactS3FineUploader
fileInputElement={UploadButton()} ref='fineuploader'
fileInputElement={UploadButton({ showLabel: false })}
keyRoutine={{ keyRoutine={{
url: AppConstants.serverUrl + 's3/key/', url: AppConstants.serverUrl + 's3/key/',
fileClass: 'contract' fileClass: 'contract'
@ -64,8 +69,8 @@ let ContractSettingsUpdateButton = React.createClass({
url: ApiUrls.blob_contracts url: ApiUrls.blob_contracts
}} }}
validation={{ validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit, itemLimit: validationTypes.registerWork.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit, sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: ['pdf'] allowedExtensions: ['pdf']
}} }}
setIsUploadReady={() =>{/* So that ReactS3FineUploader is not complaining */}} setIsUploadReady={() =>{/* So that ReactS3FineUploader is not complaining */}}

View File

@ -34,7 +34,6 @@ let WebhookSettings = React.createClass({
componentDidMount() { componentDidMount() {
WebhookStore.listen(this.onChange); WebhookStore.listen(this.onChange);
WebhookActions.fetchWebhooks(); WebhookActions.fetchWebhooks();
WebhookActions.fetchWebhookEvents();
}, },
componentWillUnmount() { componentWillUnmount() {
@ -49,7 +48,7 @@ let WebhookSettings = React.createClass({
return (event) => { return (event) => {
WebhookActions.removeWebhook(webhookId); WebhookActions.removeWebhook(webhookId);
let notification = new GlobalNotificationModel(getLangText('Webhook deleted'), 'success', 2000); const notification = new GlobalNotificationModel(getLangText('Webhook deleted'), 'success', 2000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}; };
}, },
@ -57,16 +56,16 @@ let WebhookSettings = React.createClass({
handleCreateSuccess() { handleCreateSuccess() {
this.refs.webhookCreateForm.reset(); this.refs.webhookCreateForm.reset();
WebhookActions.fetchWebhooks(true); WebhookActions.fetchWebhooks(true);
let notification = new GlobalNotificationModel(getLangText('Webhook successfully created'), 'success', 5000);
const notification = new GlobalNotificationModel(getLangText('Webhook successfully created'), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },
getWebhooks(){ getWebhooks() {
let content = <AscribeSpinner color='dark-blue' size='lg'/>;
if (this.state.webhooks) { if (this.state.webhooks) {
content = this.state.webhooks.map(function(webhook, i) { return this.state.webhooks.map(function(webhook, i) {
const event = webhook.event.split('.')[0]; const event = webhook.event.split('.')[0];
return ( return (
<ActionPanel <ActionPanel
name={webhook.event} name={webhook.event}
@ -91,11 +90,14 @@ let WebhookSettings = React.createClass({
</button> </button>
</div> </div>
</div> </div>
}/> } />
); );
}, this); }, this);
} else {
return (
<AscribeSpinner color='dark-blue' size='lg'/>
);
} }
return content;
}, },
getEvents() { getEvents() {
@ -110,18 +112,18 @@ let WebhookSettings = React.createClass({
<option <option
name={i} name={i}
key={i} key={i}
value={ event + '.webhook' }> value={event + '.webhook'}>
{ event.toUpperCase() } {event.toUpperCase()}
</option> </option>
); );
})} })}
</select> </select>
</Property>); </Property>);
} } else {
return null; return null;
}
}, },
render() { render() {
return ( return (
<CollapsibleParagraph <CollapsibleParagraph
@ -138,20 +140,19 @@ let WebhookSettings = React.createClass({
a target url. a target url.
</p> </p>
</div> </div>
<AclProxy <AclProxy show={this.state.webhookEvents && this.state.webhookEvents.length}>
show={this.state.webhookEvents && this.state.webhookEvents.length}>
<Form <Form
ref="webhookCreateForm" ref="webhookCreateForm"
url={ApiUrls.webhooks} url={ApiUrls.webhooks}
handleSuccess={this.handleCreateSuccess}> handleSuccess={this.handleCreateSuccess}>
{ this.getEvents() } {this.getEvents()}
<Property <Property
name='target' name='target'
label={getLangText('Redirect Url')}> label={getLangText('Redirect Url')}>
<input <input
type="text" type="text"
placeholder={getLangText('Enter the url to be triggered')} placeholder={getLangText('Enter the url to be triggered')}
required/> required />
</Property> </Property>
<hr /> <hr />
</Form> </Form>

View File

@ -57,21 +57,21 @@ const SlidesContainer = React.createClass({
// When the start_from parameter is used, this.setSlideNum can not simply be used anymore. // When the start_from parameter is used, this.setSlideNum can not simply be used anymore.
nextSlide(additionalQueryParams) { nextSlide(additionalQueryParams) {
const slideNum = parseInt(this.props.location.query.slide_num, 10) || 0; const slideNum = parseInt(this.props.location.query.slide_num, 10) || 0;
let nextSlide = slideNum + 1; this.setSlideNum(slideNum + 1, additionalQueryParams);
this.setSlideNum(nextSlide, additionalQueryParams);
}, },
setSlideNum(nextSlideNum, additionalQueryParams = {}) { setSlideNum(nextSlideNum, additionalQueryParams = {}) {
let queryParams = Object.assign(this.props.location.query, additionalQueryParams); const { location: { pathname } } = this.props;
queryParams.slide_num = nextSlideNum; const query = Object.assign({}, this.props.location.query, additionalQueryParams, { slide_num: nextSlideNum });
this.history.pushState(null, this.props.location.pathname, queryParams);
this.history.push({ pathname, query });
}, },
// breadcrumbs are defined as attributes of the slides. // breadcrumbs are defined as attributes of the slides.
// To extract them we have to read the DOM element's attributes // To extract them we have to read the DOM element's attributes
extractBreadcrumbs() { extractBreadcrumbs() {
const startFrom = parseInt(this.props.location.query.start_from, 10) || -1; const startFrom = parseInt(this.props.location.query.start_from, 10) || -1;
let breadcrumbs = []; const breadcrumbs = [];
React.Children.map(this.props.children, (child, i) => { React.Children.map(this.props.children, (child, i) => {
if(child && i >= startFrom && child.props['data-slide-title']) { if(child && i >= startFrom && child.props['data-slide-title']) {

View File

@ -2,6 +2,8 @@
import React from 'react'; import React from 'react';
import FacebookHandler from '../../third_party/facebook_handler';
import AppConstants from '../../constants/application_constants'; import AppConstants from '../../constants/application_constants';
import { InjectInHeadUtils } from '../../utils/inject_utils'; import { InjectInHeadUtils } from '../../utils/inject_utils';
@ -17,24 +19,40 @@ let FacebookShareButton = React.createClass({
}; };
}, },
componentDidMount() { getInitialState() {
/** return FacebookHandler.getState();
* Ideally we would only use FB.XFBML.parse() on the component that we're
* mounting, but doing this when we first load the FB sdk causes unpredictable behaviour.
* The button sometimes doesn't get initialized, likely because FB hasn't properly
* been initialized yet.
*
* To circumvent this, we always have the sdk parse the entire DOM on the initial load
* (see FacebookHandler) and then use FB.XFBML.parse() on the mounting component later.
*/
InjectInHeadUtils
.inject(AppConstants.facebook.sdkUrl)
.then(() => { FB.XFBML.parse(this.refs.fbShareButton.getDOMNode().parentElement) });
}, },
shouldComponentUpdate(nextProps) { componentDidMount() {
return this.props.type !== nextProps.type; FacebookHandler.listen(this.onChange);
this.loadFacebook();
},
shouldComponentUpdate(nextProps, nextState) {
// Don't update if the props haven't changed or the FB SDK loading status is still the same
return this.props.type !== nextProps.type || nextState.loaded !== this.state.loaded;
},
componentDidUpdate() {
// If the component changes, we need to reparse the share button's XFBML.
// To prevent cases where the Facebook SDK hasn't been loaded yet at this stage,
// let's make sure that it's injected before trying to reparse.
this.loadFacebook();
},
onChange(state) {
this.setState(state);
},
loadFacebook() {
InjectInHeadUtils
.inject(AppConstants.facebook.sdkUrl)
.then(() => {
if (this.state.loaded) {
FB.XFBML.parse(this.refs.fbShareButton.getDOMNode().parent)
}
});
}, },
render() { render() {

View File

@ -2,15 +2,15 @@
export class ColumnModel { export class ColumnModel {
// ToDo: Add validation for all passed-in parameters // ToDo: Add validation for all passed-in parameters
constructor(transformFn, columnName, displayName, displayType, rowWidth, canBeOrdered, transition, className) { constructor({ transformFn, columnName = '', displayElement, displayType, rowWidth, canBeOrdered, transition, className = '' }) {
this.transformFn = transformFn; this.transformFn = transformFn;
this.columnName = columnName; this.columnName = columnName;
this.displayName = displayName; this.displayElement = displayElement;
this.displayType = displayType; this.displayType = displayType;
this.rowWidth = rowWidth; this.rowWidth = rowWidth;
this.canBeOrdered = canBeOrdered; this.canBeOrdered = canBeOrdered;
this.transition = transition; this.transition = transition;
this.className = className ? className : ''; this.className = className;
} }
} }
@ -28,7 +28,7 @@ export class ColumnModel {
* our selfes, using this TransitionModel. * our selfes, using this TransitionModel.
*/ */
export class TransitionModel { export class TransitionModel {
constructor(to, queryKey, valueKey, callback) { constructor({ to, queryKey, valueKey, callback }) {
this.to = to; this.to = to;
this.queryKey = queryKey; this.queryKey = queryKey;
this.valueKey = valueKey; this.valueKey = valueKey;

View File

@ -1,5 +1,5 @@
'use strict';
'use strict';
import React from 'react'; import React from 'react';
import TableHeaderItem from './table_header_item'; import TableHeaderItem from './table_header_item';
@ -29,7 +29,7 @@ let TableHeader = React.createClass({
<TableHeaderItem <TableHeaderItem
className={column.className} className={column.className}
key={i} key={i}
displayName={column.displayName} displayElement={column.displayElement}
columnName={columnName} columnName={columnName}
canBeOrdered={canBeOrdered} canBeOrdered={canBeOrdered}
orderAsc={this.props.orderAsc} orderAsc={this.props.orderAsc}

View File

@ -7,7 +7,7 @@ import TableHeaderItemCarret from './table_header_item_carret';
let TableHeaderItem = React.createClass({ let TableHeaderItem = React.createClass({
propTypes: { propTypes: {
displayName: React.PropTypes.oneOfType([ displayElement: React.PropTypes.oneOfType([
React.PropTypes.string, React.PropTypes.string,
React.PropTypes.element React.PropTypes.element
]).isRequired, ]).isRequired,
@ -24,29 +24,31 @@ let TableHeaderItem = React.createClass({
}, },
render() { render() {
if(this.props.canBeOrdered && this.props.changeOrder && this.props.orderAsc != null && this.props.orderBy) { const { canBeOrdered, changeOrder, className, columnName, displayElement, orderAsc, orderBy } = this.props;
if(this.props.columnName === this.props.orderBy) {
if (canBeOrdered && changeOrder && orderAsc != null && orderBy) {
if (columnName === orderBy) {
return ( return (
<th <th
className={'ascribe-table-header-column ' + this.props.className} className={'ascribe-table-header-column ' + className}
onClick={this.changeOrder}> onClick={this.changeOrder}>
<span>{this.props.displayName} <TableHeaderItemCarret orderAsc={this.props.orderAsc} /></span> <span>{displayElement} <TableHeaderItemCarret orderAsc={orderAsc} /></span>
</th> </th>
); );
} else { } else {
return ( return (
<th <th
className={'ascribe-table-header-column ' + this.props.className} className={'ascribe-table-header-column ' + className}
onClick={this.changeOrder}> onClick={this.changeOrder}>
<span>{this.props.displayName}</span> <span>{displayElement}</span>
</th> </th>
); );
} }
} else { } else {
return ( return (
<th className={'ascribe-table-header-column ' + this.props.className}> <th className={'ascribe-table-header-column ' + className}>
<span> <span>
{this.props.displayName} {displayElement}
</span> </span>
</th> </th>
); );

View File

@ -3,15 +3,15 @@
import React from 'react'; import React from 'react';
let TableItemAclFiltered = React.createClass({ const TableItemAclFiltered = React.createClass({
propTypes: { propTypes: {
content: React.PropTypes.object, content: React.PropTypes.object,
notifications: React.PropTypes.string notifications: React.PropTypes.array
}, },
render() { render() {
var availableAcls = ['acl_consign', 'acl_loan', 'acl_transfer', 'acl_view', 'acl_share', 'acl_unshare', 'acl_delete']; const availableAcls = ['acl_consign', 'acl_loan', 'acl_transfer', 'acl_view', 'acl_share', 'acl_unshare', 'acl_delete'];
if (this.props.notifications && this.props.notifications.length > 0){ if (this.props.notifications && this.props.notifications.length) {
return ( return (
<span> <span>
{this.props.notifications[0].action_str} {this.props.notifications[0].action_str}
@ -19,15 +19,14 @@ let TableItemAclFiltered = React.createClass({
); );
} }
let filteredAcls = Object.keys(this.props.content).filter((key) => { const filteredAcls = Object.keys(this.props.content)
return availableAcls.indexOf(key) > -1 && this.props.content[key]; .filter((key) => availableAcls.indexOf(key) > -1 && this.props.content[key])
}); .map((acl) => acl.split('acl_')[1])
.join('/');
filteredAcls = filteredAcls.map((acl) => acl.split('acl_')[1]);
return ( return (
<span> <span>
{filteredAcls.join('/')} {filteredAcls}
</span> </span>
); );
} }

View File

@ -26,7 +26,7 @@ let FileDragAndDropDialog = React.createClass({
getDragDialog(fileClass) { getDragDialog(fileClass) {
if (dragAndDropAvailable) { if (dragAndDropAvailable) {
return [ return [
<p>{getLangText('Drag %s here', fileClass)}</p>, <p className="file-drag-and-drop-dialog-title">{getLangText('Drag %s here', fileClass)}</p>,
<p>{getLangText('or')}</p> <p>{getLangText('or')}</p>
]; ];
} else { } else {
@ -46,6 +46,8 @@ let FileDragAndDropDialog = React.createClass({
if (hasFiles) { if (hasFiles) {
return null; return null;
} else { } else {
let dialogElement;
if (enableLocalHashing && !uploadMethod) { if (enableLocalHashing && !uploadMethod) {
const currentQueryParams = getCurrentQueryParams(); const currentQueryParams = getCurrentQueryParams();
@ -55,9 +57,9 @@ let FileDragAndDropDialog = React.createClass({
const queryParamsUpload = Object.assign({}, currentQueryParams); const queryParamsUpload = Object.assign({}, currentQueryParams);
queryParamsUpload.method = 'upload'; queryParamsUpload.method = 'upload';
return ( dialogElement = (
<div className="file-drag-and-drop-dialog present-options"> <div className="present-options">
<p>{getLangText('Would you rather')}</p> <p className="file-drag-and-drop-dialog-title">{getLangText('Would you rather')}</p>
{/* {/*
The frontend in live is hosted under /app, The frontend in live is hosted under /app,
Since `Link` is appending that base url, if its defined Since `Link` is appending that base url, if its defined
@ -85,34 +87,42 @@ let FileDragAndDropDialog = React.createClass({
); );
} else { } else {
if (multipleFiles) { if (multipleFiles) {
return ( dialogElement = [
<span className="file-drag-and-drop-dialog"> this.getDragDialog(fileClassToUpload.plural),
{this.getDragDialog(fileClassToUpload.plural)}
<span <span
className="btn btn-default" className="btn btn-default"
onClick={onClick}> onClick={onClick}>
{getLangText('choose %s to upload', fileClassToUpload.plural)} {getLangText('choose %s to upload', fileClassToUpload.plural)}
</span> </span>
</span> ];
);
} else { } else {
const dialog = uploadMethod === 'hash' ? getLangText('choose a %s to hash', fileClassToUpload.singular) const dialog = uploadMethod === 'hash' ? getLangText('choose a %s to hash', fileClassToUpload.singular)
: getLangText('choose a %s to upload', fileClassToUpload.singular); : getLangText('choose a %s to upload', fileClassToUpload.singular);
return ( dialogElement = [
<span className="file-drag-and-drop-dialog"> this.getDragDialog(fileClassToUpload.singular),
{this.getDragDialog(fileClassToUpload.singular)}
<span <span
className="btn btn-default" className="btn btn-default"
onClick={onClick}> onClick={onClick}>
{dialog} {dialog}
</span> </span>
</span> ];
}
}
return (
<div className="file-drag-and-drop-dialog">
<div className="hidden-print">
{dialogElement}
</div>
{/* Hide the uploader and just show that there's been on files uploaded yet when printing */}
<p className="text-align-center visible-print">
{getLangText('No files uploaded')}
</p>
</div>
); );
} }
} }
}
}
}); });
export default FileDragAndDropDialog; export default FileDragAndDropDialog;

View File

@ -68,7 +68,7 @@ const FileDragAndDropPreviewImage = React.createClass({
return ( return (
<div <div
className="file-drag-and-drop-preview-image" className="file-drag-and-drop-preview-image hidden-print"
style={imageStyle}> style={imageStyle}>
<AclProxy <AclProxy
show={showProgress}> show={showProgress}>

View File

@ -1,6 +1,7 @@
'use strict'; 'use strict';
import React from 'react'; import React from 'react';
import classNames from 'classnames';
import { displayValidProgressFilesFilter } from '../react_s3_fine_uploader_utils'; import { displayValidProgressFilesFilter } from '../react_s3_fine_uploader_utils';
import { getLangText } from '../../../utils/lang_utils'; import { getLangText } from '../../../utils/lang_utils';
@ -9,7 +10,7 @@ import { truncateTextAtCharIndex } from '../../../utils/general_utils';
const { func, array, bool, shape, string } = React.PropTypes; const { func, array, bool, shape, string } = React.PropTypes;
export default function UploadButton({ className = 'btn btn-default btn-sm' } = {}) { export default function UploadButton({ className = 'btn btn-default btn-sm', showLabel = true } = {}) {
return React.createClass({ return React.createClass({
displayName: 'UploadButton', displayName: 'UploadButton',
@ -119,17 +120,18 @@ export default function UploadButton({ className = 'btn btn-default btn-sm' } =
}, },
getUploadedFileLabel() { getUploadedFileLabel() {
if (showLabel) {
const uploadedFile = this.getUploadedFile(); const uploadedFile = this.getUploadedFile();
const uploadingFiles = this.getUploadingFiles(); const uploadingFiles = this.getUploadingFiles();
if(uploadingFiles.length) { if (uploadingFiles.length) {
return ( return (
<span> <span>
{' ' + truncateTextAtCharIndex(uploadingFiles[0].name, 40) + ' '} {' ' + truncateTextAtCharIndex(uploadingFiles[0].name, 40) + ' '}
[<a onClick={this.onClickRemove}>{getLangText('cancel upload')}</a>] [<a onClick={this.onClickRemove}>{getLangText('cancel upload')}</a>]
</span> </span>
); );
} else if(uploadedFile) { } else if (uploadedFile) {
return ( return (
<span> <span>
<span className='ascribe-icon icon-ascribe-ok'/> <span className='ascribe-icon icon-ascribe-ok'/>
@ -138,9 +140,8 @@ export default function UploadButton({ className = 'btn btn-default btn-sm' } =
</span> </span>
); );
} else { } else {
return ( return <span>{getLangText('No file chosen')}</span>;
<span>{getLangText('No file chosen')}</span> }
);
} }
}, },
@ -158,7 +159,7 @@ export default function UploadButton({ className = 'btn btn-default btn-sm' } =
* Therefore the wrapping component needs to be an `anchor` tag instead of a `button` * Therefore the wrapping component needs to be an `anchor` tag instead of a `button`
*/ */
return ( return (
<div className="upload-button-wrapper"> <div className={classNames('ascribe-upload-button', {'ascribe-upload-button-has-label': showLabel})}>
{/* {/*
The button needs to be of `type="button"` as it would The button needs to be of `type="button"` as it would
otherwise submit the form its in. otherwise submit the form its in.

View File

@ -13,9 +13,9 @@ import GlobalNotificationActions from '../../actions/global_notification_actions
import AppConstants from '../../constants/application_constants'; import AppConstants from '../../constants/application_constants';
import { computeHashOfFile } from '../../utils/file_utils';
import { displayValidFilesFilter, transformAllowedExtensionsToInputAcceptProp } from './react_s3_fine_uploader_utils'; import { displayValidFilesFilter, transformAllowedExtensionsToInputAcceptProp } from './react_s3_fine_uploader_utils';
import { getCookie } from '../../utils/fetch_api_utils'; import { getCookie } from '../../utils/fetch_api_utils';
import { computeHashOfFile, extractFileExtensionFromString } from '../../utils/file_utils';
import { getLangText } from '../../utils/lang_utils'; import { getLangText } from '../../utils/lang_utils';
@ -36,20 +36,15 @@ const ReactS3FineUploader = React.createClass({
keyRoutine: shape({ keyRoutine: shape({
url: string, url: string,
fileClass: string, fileClass: string,
pieceId: oneOfType([ pieceId: number
string,
number
])
}), }),
createBlobRoutine: shape({ createBlobRoutine: shape({
url: string, url: string,
pieceId: oneOfType([ pieceId: number
string,
number
])
}), }),
handleChangedFile: func, // is for when a file is dropped or selected handleChangedFile: func, // is for when a file is dropped or selected
submitFile: func, // is for when a file has been successfully uploaded, TODO: rename to handleSubmitFile submitFile: func, // is for when a file has been successfully uploaded, TODO: rename to handleSubmitFile
onValidationFailed: func,
autoUpload: bool, autoUpload: bool,
debug: bool, debug: bool,
objectProperties: shape({ objectProperties: shape({
@ -96,7 +91,7 @@ const ReactS3FineUploader = React.createClass({
}), }),
validation: shape({ validation: shape({
itemLimit: number, itemLimit: number,
sizeLimit: string, sizeLimit: number,
allowedExtensions: arrayOf(string) allowedExtensions: arrayOf(string)
}), }),
messages: shape({ messages: shape({
@ -283,22 +278,6 @@ const ReactS3FineUploader = React.createClass({
this.setState(this.getInitialState()); this.setState(this.getInitialState());
}, },
// Cancel uploads and clear previously selected files on the input element
cancelUploads(id) {
typeof id !== 'undefined' ? this.state.uploader.cancel(id) : this.state.uploader.cancelAll();
// Reset the file input element to clear the previously selected files so that
// the user can reselect them again.
this.clearFileSelection();
},
clearFileSelection() {
const { fileInput } = this.refs;
if (fileInput && typeof fileInput.clearSelection === 'function') {
fileInput.clearSelection();
}
},
requestKey(fileId) { requestKey(fileId) {
let filename = this.state.uploader.getName(fileId); let filename = this.state.uploader.getName(fileId);
let uuid = this.state.uploader.getUuid(fileId); let uuid = this.state.uploader.getUuid(fileId);
@ -389,6 +368,107 @@ const ReactS3FineUploader = React.createClass({
}); });
}, },
// Cancel uploads and clear previously selected files on the input element
cancelUploads(id) {
typeof id !== 'undefined' ? this.state.uploader.cancel(id) : this.state.uploader.cancelAll();
// Reset the file input element to clear the previously selected files so that
// the user can reselect them again.
this.clearFileSelection();
},
clearFileSelection() {
const { fileInput } = this.refs;
if (fileInput && typeof fileInput.clearSelection === 'function') {
fileInput.clearSelection();
}
},
getAllowedExtensions() {
const { validation: { allowedExtensions } = {} } = this.props;
if (allowedExtensions && allowedExtensions.length) {
return transformAllowedExtensionsToInputAcceptProp(allowedExtensions);
} else {
return null;
}
},
getXhrErrorComment(xhr) {
if (xhr) {
return {
response: xhr.response,
url: xhr.responseURL,
status: xhr.status,
statusText: xhr.statusText
};
}
},
isDropzoneInactive() {
const filesToDisplay = this.state.filesToUpload.filter((file) => file.status !== 'deleted' && file.status !== 'canceled' && file.size !== -1);
if ((this.props.enableLocalHashing && !this.props.uploadMethod) || !this.props.areAssetsEditable || !this.props.multiple && filesToDisplay.length > 0) {
return true;
} else {
return false;
}
},
isFileValid(file) {
const { validation: { allowedExtensions, sizeLimit = 0 }, onValidationFailed } = this.props;
const fileExt = extractFileExtensionFromString(file.name);
if (file.size > sizeLimit) {
const fileSizeInMegaBytes = sizeLimit / 1000000;
const notification = new GlobalNotificationModel(getLangText('A file you submitted is bigger than ' + fileSizeInMegaBytes + 'MB.'), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
if (typeof onValidationFailed === 'function') {
onValidationFailed(file);
}
return false;
} else if (allowedExtensions && !allowedExtensions.includes(fileExt)) {
const notification = new GlobalNotificationModel(getLangText(`The file you've submitted is of an invalid file format: Valid format(s): ${allowedExtensions.join(', ')}`), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
return false;
} else {
return true;
}
},
selectValidFiles(files) {
return Array.from(files).reduce((validFiles, file) => {
if (this.isFileValid(file)) {
validFiles.push(file);
}
return validFiles;
}, []);
},
// This method has been made promise-based to immediately afterwards
// call a callback function (instantly after this.setState went through)
// This is e.g. needed when showing/hiding the optional thumbnail upload
// field in the registration form
setStatusOfFile(fileId, status) {
return Q.Promise((resolve) => {
let changeSet = {};
if(status === 'deleted' || status === 'canceled') {
changeSet.progress = { $set: 0 };
}
changeSet.status = { $set: status };
let filesToUpload = React.addons.update(this.state.filesToUpload, { [fileId]: changeSet });
this.setState({ filesToUpload }, resolve);
});
},
setThumbnailForFileId(fileId, url) { setThumbnailForFileId(fileId, url) {
const { filesToUpload } = this.state; const { filesToUpload } = this.state;
@ -511,31 +591,6 @@ const ReactS3FineUploader = React.createClass({
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },
getXhrErrorComment(xhr) {
if (xhr) {
return {
response: xhr.response,
url: xhr.responseURL,
status: xhr.status,
statusText: xhr.statusText
};
}
},
isFileValid(file) {
if(file.size > this.props.validation.sizeLimit) {
let fileSizeInMegaBytes = this.props.validation.sizeLimit / 1000000;
let notification = new GlobalNotificationModel(getLangText('A file you submitted is bigger than ' + fileSizeInMegaBytes + 'MB.'), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
return false;
} else {
return true;
}
},
onCancel(id) { onCancel(id) {
// when a upload is canceled, we need to update this components file array // when a upload is canceled, we need to update this components file array
this.setStatusOfFile(id, 'canceled') this.setStatusOfFile(id, 'canceled')
@ -672,6 +727,13 @@ const ReactS3FineUploader = React.createClass({
this.cancelUploads(fileId); this.cancelUploads(fileId);
}, },
handleCancelHashing() {
// Every progress tick of the hashing function in handleUploadFile there is a
// check if this.state.hashingProgress is -1. If so, there is an error thrown that cancels
// the hashing of all files immediately.
this.setState({ hashingProgress: -1 });
},
handlePauseFile(fileId) { handlePauseFile(fileId) {
if(this.state.uploader.pauseUpload(fileId)) { if(this.state.uploader.pauseUpload(fileId)) {
this.setStatusOfFile(fileId, 'paused'); this.setStatusOfFile(fileId, 'paused');
@ -700,15 +762,8 @@ const ReactS3FineUploader = React.createClass({
return; return;
} }
// validate each submitted file if it fits the file size // Select only the submitted files that fit the file size and allowed extensions
let validFiles = []; files = this.selectValidFiles(files);
for(let i = 0; i < files.length; i++) {
if(this.isFileValid(files[i])) {
validFiles.push(files[i]);
}
}
// override standard files list with only valid files
files = validFiles;
// if multiple is set to false and user drops multiple files into the dropzone, // if multiple is set to false and user drops multiple files into the dropzone,
// take the first one and notify user that only one file can be submitted // take the first one and notify user that only one file can be submitted
@ -819,13 +874,6 @@ const ReactS3FineUploader = React.createClass({
} }
}, },
handleCancelHashing() {
// Every progress tick of the hashing function in handleUploadFile there is a
// check if this.state.hashingProgress is -1. If so, there is an error thrown that cancels
// the hashing of all files immediately.
this.setState({ hashingProgress: -1 });
},
// ReactFineUploader is essentially just a react layer around s3 fineuploader. // ReactFineUploader is essentially just a react layer around s3 fineuploader.
// However, since we need to display the status of a file (progress, uploading) as well as // However, since we need to display the status of a file (progress, uploading) as well as
// be able to execute actions on a currently uploading file we need to exactly sync the file list // be able to execute actions on a currently uploading file we need to exactly sync the file list
@ -895,46 +943,6 @@ const ReactS3FineUploader = React.createClass({
}); });
}, },
// This method has been made promise-based to immediately afterwards
// call a callback function (instantly after this.setState went through)
// This is e.g. needed when showing/hiding the optional thumbnail upload
// field in the registration form
setStatusOfFile(fileId, status) {
return Q.Promise((resolve) => {
let changeSet = {};
if(status === 'deleted' || status === 'canceled') {
changeSet.progress = { $set: 0 };
}
changeSet.status = { $set: status };
let filesToUpload = React.addons.update(this.state.filesToUpload, { [fileId]: changeSet });
this.setState({ filesToUpload }, resolve);
});
},
isDropzoneInactive() {
const filesToDisplay = this.state.filesToUpload.filter((file) => file.status !== 'deleted' && file.status !== 'canceled' && file.size !== -1);
if ((this.props.enableLocalHashing && !this.props.uploadMethod) || !this.props.areAssetsEditable || !this.props.multiple && filesToDisplay.length > 0) {
return true;
} else {
return false;
}
},
getAllowedExtensions() {
let { validation } = this.props;
if(validation && validation.allowedExtensions && validation.allowedExtensions.length > 0) {
return transformAllowedExtensionsToInputAcceptProp(validation.allowedExtensions);
} else {
return null;
}
},
render() { render() {
const { const {
multiple, multiple,

View File

@ -7,7 +7,7 @@ import { getLangText } from '../utils/lang_utils';
let Footer = React.createClass({ let Footer = React.createClass({
render() { render() {
return ( return (
<div className="ascribe-footer"> <div className="ascribe-footer hidden-print">
<p className="ascribe-sub-sub-statement"> <p className="ascribe-sub-sub-statement">
<br /> <br />
<a href="http://docs.ascribe.apiary.io/" target="_blank">api</a> | <a href="http://docs.ascribe.apiary.io/" target="_blank">api</a> |

View File

@ -1,43 +0,0 @@
'use strict';
import React from 'react';
let GlobalAction = React.createClass({
propTypes: {
requestActions: React.PropTypes.object
},
render() {
let pieceActions = null;
if (this.props.requestActions && this.props.requestActions.pieces){
pieceActions = this.props.requestActions.pieces.map((item) => {
return (
<div className="ascribe-global-action">
{item}
</div>);
});
}
let editionActions = null;
if (this.props.requestActions && this.props.requestActions.editions){
editionActions = Object.keys(this.props.requestActions.editions).map((pieceId) => {
return this.props.requestActions.editions[pieceId].map((item) => {
return (
<div className="ascribe-global-action">
{item}
</div>);
});
});
}
if (pieceActions || editionActions) {
return (
<div className="ascribe-global-action-wrapper">
{pieceActions}
{editionActions}
</div>);
}
return null;
}
});
export default GlobalAction;

View File

@ -18,6 +18,8 @@ import AclProxy from './acl_proxy';
import EventActions from '../actions/event_actions'; import EventActions from '../actions/event_actions';
import PieceListStore from '../stores/piece_list_store';
import UserActions from '../actions/user_actions'; import UserActions from '../actions/user_actions';
import UserStore from '../stores/user_store'; import UserStore from '../stores/user_store';
@ -43,12 +45,17 @@ let Header = React.createClass({
getInitialState() { getInitialState() {
return mergeOptions( return mergeOptions(
PieceListStore.getState(),
WhitelabelStore.getState(), WhitelabelStore.getState(),
UserStore.getState() UserStore.getState()
); );
}, },
componentDidMount() { componentDidMount() {
// Listen to the piece list store, but don't fetch immediately to avoid
// conflicts with routes that may need to wait to load the piece list
PieceListStore.listen(this.onChange);
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
UserActions.fetchCurrentUser.defer(); UserActions.fetchCurrentUser.defer();
@ -75,11 +82,16 @@ let Header = React.createClass({
}, },
componentWillUnmount() { componentWillUnmount() {
PieceListStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange); UserStore.unlisten(this.onChange);
WhitelabelStore.unlisten(this.onChange); WhitelabelStore.unlisten(this.onChange);
//history.unlisten(this.onRouteChange); //history.unlisten(this.onRouteChange);
}, },
onChange(state) {
this.setState(state);
},
getLogo() { getLogo() {
let { whitelabel } = this.state; let { whitelabel } = this.state;
@ -93,16 +105,16 @@ let Header = React.createClass({
<img className="img-brand" src={whitelabel.logo} alt="Whitelabel brand"/> <img className="img-brand" src={whitelabel.logo} alt="Whitelabel brand"/>
</Link> </Link>
); );
} } else {
return ( return (
<span> <span>
<Link className="icon-ascribe-logo" to="/collection"/> <Link className="icon-ascribe-logo" to="/collection"/>
</span> </span>
); );
}
}, },
getPoweredBy(){ getPoweredBy() {
return ( return (
<AclProxy <AclProxy
aclObject={this.state.whitelabel} aclObject={this.state.whitelabel}
@ -117,10 +129,6 @@ let Header = React.createClass({
); );
}, },
onChange(state) {
this.setState(state);
},
onMenuItemClick() { onMenuItemClick() {
/* /*
This is a hack to make the dropdown close after clicking on an item This is a hack to make the dropdown close after clicking on an item
@ -156,15 +164,17 @@ let Header = React.createClass({
}, },
render() { render() {
const { currentUser, unfilteredPieceListCount } = this.state;
let account; let account;
let signup; let signup;
let navRoutesLinks; let navRoutesLinks;
if (this.state.currentUser.username){
if (currentUser.username) {
account = ( account = (
<DropdownButton <DropdownButton
ref='dropdownbutton' ref='dropdownbutton'
eventKey="1" eventKey="1"
title={this.state.currentUser.username}> title={currentUser.username}>
<LinkContainer <LinkContainer
to="/settings" to="/settings"
onClick={this.onMenuItemClick}> onClick={this.onMenuItemClick}>
@ -174,7 +184,7 @@ let Header = React.createClass({
</MenuItem> </MenuItem>
</LinkContainer> </LinkContainer>
<AclProxy <AclProxy
aclObject={this.state.currentUser.acl} aclObject={currentUser.acl}
aclName="acl_view_settings_contract"> aclName="acl_view_settings_contract">
<LinkContainer <LinkContainer
to="/contract_settings" to="/contract_settings"
@ -195,9 +205,21 @@ let Header = React.createClass({
</LinkContainer> </LinkContainer>
</DropdownButton> </DropdownButton>
); );
navRoutesLinks = <NavRoutesLinks routes={this.props.routes} userAcl={this.state.currentUser.acl} navbar right/>;
} // Let's assume that if the piece list hasn't loaded yet (ie. when unfilteredPieceListCount === -1)
else { // then the user has pieces
// FIXME: this doesn't work that well as the user may not load their piece list
// until much later, so we would show the 'Collection' header as available until
// they actually click on it and get redirected to piece registration.
navRoutesLinks = (
<NavRoutesLinks
navbar
right
hasPieces={!!unfilteredPieceListCount}
routes={this.props.routes}
userAcl={currentUser.acl} />
);
} else {
account = ( account = (
<LinkContainer <LinkContainer
to="/login"> to="/login">
@ -219,10 +241,11 @@ let Header = React.createClass({
return ( return (
<div> <div>
<Navbar <Navbar
ref="navbar"
brand={this.getLogo()} brand={this.getLogo()}
toggleNavKey={0} toggleNavKey={0}
fixedTop={true} fixedTop={true}
ref="navbar"> className="hidden-print">
<CollapsibleNav <CollapsibleNav
eventKey={0}> eventKey={0}>
<Nav navbar left> <Nav navbar left>
@ -237,6 +260,9 @@ let Header = React.createClass({
{navRoutesLinks} {navRoutesLinks}
</CollapsibleNav> </CollapsibleNav>
</Navbar> </Navbar>
<p className="ascribe-print-header visible-print">
<span className="icon-ascribe-logo" />
</p>
</div> </div>
); );
} }

View File

@ -11,14 +11,33 @@ import AclProxy from './acl_proxy';
import { sanitizeList } from '../utils/general_utils'; import { sanitizeList } from '../utils/general_utils';
const DISABLE_ENUM = ['hasPieces', 'noPieces'];
let NavRoutesLinks = React.createClass({ let NavRoutesLinks = React.createClass({
propTypes: { propTypes: {
hasPieces: React.PropTypes.bool,
routes: React.PropTypes.arrayOf(React.PropTypes.object), routes: React.PropTypes.arrayOf(React.PropTypes.object),
userAcl: React.PropTypes.object userAcl: React.PropTypes.object
}, },
isRouteDisabled(disableOn) {
const { hasPieces } = this.props;
if (disableOn) {
if (!DISABLE_ENUM.includes(disableOn)) {
throw new Error(`"disableOn" must be one of: [${DISABLE_ENUM.join(', ')}] got "${disableOn}" instead`);
}
if (disableOn === 'hasPieces') {
return hasPieces;
} else if (disableOn === 'noPieces') {
return !hasPieces;
}
}
},
/** /**
* This method generales a bunch of react-bootstrap specific links * This method generates a bunch of react-bootstrap specific links
* from the routes we defined in one of the specific routes.js file * from the routes we defined in one of the specific routes.js file
* *
* We can define a headerTitle as well as a aclName and according to that the * We can define a headerTitle as well as a aclName and according to that the
@ -29,48 +48,50 @@ let NavRoutesLinks = React.createClass({
* @return {Array} Array of ReactElements that can be displayed to the user * @return {Array} Array of ReactElements that can be displayed to the user
*/ */
extractLinksFromRoutes(node, userAcl, i) { extractLinksFromRoutes(node, userAcl, i) {
if(!node) { if (!node) {
return; return;
} }
let links = node.childRoutes.map((child, j) => { const links = node.childRoutes.map((child, j) => {
let childrenFn = null; const { aclName, disableOn, headerTitle, path, childRoutes } = child;
let { aclName, headerTitle, path, childRoutes } = child;
// We validate if the user has set the title correctly,
// otherwise we're not going to render his route
if (headerTitle && typeof headerTitle === 'string') {
let nestedChildren = null;
// If the node has children that could be rendered, then we want // If the node has children that could be rendered, then we want
// to execute this function again with the child as the root // to execute this function again with the child as the root
// //
// Otherwise we'll just pass childrenFn as false // Otherwise we'll just pass nestedChildren as false
if(child.childRoutes && child.childRoutes.length > 0) { if (child.childRoutes && child.childRoutes.length) {
childrenFn = this.extractLinksFromRoutes(child, userAcl, i++); nestedChildren = this.extractLinksFromRoutes(child, userAcl, i++);
} }
// We validate if the user has set the title correctly, const navLinkProps = {
// otherwise we're not going to render his route headerTitle,
if(headerTitle && typeof headerTitle === 'string') { children: nestedChildren,
depth: i,
disabled: this.isRouteDisabled(disableOn),
routePath: `/${path}`
};
// if there is an aclName present on the route definition, // if there is an aclName present on the route definition,
// we evaluate it against the user's acl // we evaluate it against the user's acl
if(aclName && typeof aclName !== 'undefined') { if (aclName && typeof aclName !== 'undefined') {
return ( return (
<AclProxy <AclProxy
key={j} key={j}
aclName={aclName} aclName={aclName}
aclObject={this.props.userAcl}> aclObject={this.props.userAcl}>
<NavRoutesLinksLink <NavRoutesLinksLink {...navLinkProps} />
headerTitle={headerTitle}
routePath={'/' + path}
depth={i}
children={childrenFn}/>
</AclProxy> </AclProxy>
); );
} else { } else {
return ( return (
<NavRoutesLinksLink <NavRoutesLinksLink
key={j} key={j}
headerTitle={headerTitle} {...navLinkProps} />
routePath={'/' + path}
depth={i}
children={childrenFn}/>
); );
} }
} else { } else {
@ -84,7 +105,7 @@ let NavRoutesLinks = React.createClass({
}, },
render() { render() {
let {routes, userAcl} = this.props; const {routes, userAcl} = this.props;
return ( return (
<Nav {...this.props}> <Nav {...this.props}>

View File

@ -11,40 +11,45 @@ import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
let NavRoutesLinksLink = React.createClass({ let NavRoutesLinksLink = React.createClass({
propTypes: { propTypes: {
headerTitle: React.PropTypes.string,
routePath: React.PropTypes.string,
children: React.PropTypes.oneOfType([ children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element), React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element React.PropTypes.element
]), ]),
disabled: React.PropTypes.bool,
depth: React.PropTypes.number depth: React.PropTypes.number,
headerTitle: React.PropTypes.string,
routePath: React.PropTypes.string
}, },
render() { render() {
let { children, headerTitle, depth, routePath } = this.props; const { children, headerTitle, depth, disabled, routePath } = this.props;
// if the route has children, we're returning a DropdownButton that will get filled // if the route has children, we're returning a DropdownButton that will get filled
// with MenuItems // with MenuItems
if(children) { if (children) {
return ( return (
<DropdownButton title={headerTitle}> <DropdownButton
disabled={disabled}
title={headerTitle}>
{children} {children}
</DropdownButton> </DropdownButton>
); );
} else { } else {
if(depth === 1) { if (depth === 1) {
// if the node's child is actually a node of level one (a child of a node), we're // if the node's child is actually a node of level one (a child of a node), we're
// returning a DropdownButton matching MenuItem // returning a DropdownButton matching MenuItem
return ( return (
<LinkContainer to={routePath}> <LinkContainer
disabled={disabled}
to={routePath}>
<MenuItem>{headerTitle}</MenuItem> <MenuItem>{headerTitle}</MenuItem>
</LinkContainer> </LinkContainer>
); );
} else if(depth === 0) { } else if (depth === 0) {
return ( return (
<LinkContainer to={routePath}> <LinkContainer
disabled={disabled}
to={routePath}>
<NavItem>{headerTitle}</NavItem> <NavItem>{headerTitle}</NavItem>
</LinkContainer> </LinkContainer>
); );

View File

@ -130,8 +130,9 @@ let PasswordResetForm = React.createClass({
}, },
handleSuccess() { handleSuccess() {
this.history.pushState(null, '/collection'); this.history.push('/collection');
let notification = new GlobalNotificationModel(getLangText('password successfully updated'), 'success', 10000);
const notification = new GlobalNotificationModel(getLangText('password successfully updated'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },

View File

@ -37,6 +37,7 @@ let PieceList = React.createClass({
bulkModalButtonListType: React.PropTypes.func, bulkModalButtonListType: React.PropTypes.func,
canLoadPieceList: React.PropTypes.bool, canLoadPieceList: React.PropTypes.bool,
redirectTo: React.PropTypes.string, redirectTo: React.PropTypes.string,
shouldRedirect: React.PropTypes.func,
customSubmitButton: React.PropTypes.element, customSubmitButton: React.PropTypes.element,
customThumbnailPlaceholder: React.PropTypes.func, customThumbnailPlaceholder: React.PropTypes.func,
filterParams: React.PropTypes.array, filterParams: React.PropTypes.array,
@ -52,7 +53,6 @@ let PieceList = React.createClass({
accordionListItemType: AccordionListItemWallet, accordionListItemType: AccordionListItemWallet,
bulkModalButtonListType: AclButtonList, bulkModalButtonListType: AclButtonList,
canLoadPieceList: true, canLoadPieceList: true,
orderParams: ['artist_name', 'title'],
filterParams: [{ filterParams: [{
label: getLangText('Show works I can'), label: getLangText('Show works I can'),
items: [ items: [
@ -60,7 +60,10 @@ let PieceList = React.createClass({
'acl_consign', 'acl_consign',
'acl_create_editions' 'acl_create_editions'
] ]
}] }],
orderParams: ['artist_name', 'title'],
redirectTo: '/register_piece',
shouldRedirect: () => true
}; };
}, },
@ -114,9 +117,13 @@ let PieceList = React.createClass({
}, },
componentDidUpdate() { componentDidUpdate() {
if (this.props.redirectTo && this.state.unfilteredPieceListCount === 0) { const { location: { query }, redirectTo, shouldRedirect } = this.props;
const { unfilteredPieceListCount } = this.state;
if (redirectTo && unfilteredPieceListCount === 0 &&
(typeof shouldRedirect === 'function' && shouldRedirect(unfilteredPieceListCount))) {
// FIXME: hack to redirect out of the dispatch cycle // FIXME: hack to redirect out of the dispatch cycle
window.setTimeout(() => this.history.pushState(null, this.props.redirectTo, this.props.location.query), 0); window.setTimeout(() => this.history.push({ query, pathname: redirectTo }), 0);
} }
}, },
@ -169,15 +176,16 @@ let PieceList = React.createClass({
} }
}, },
searchFor(searchTerm) { searchFor(search) {
this.loadPieceList({ const { location: { pathname } } = this.props;
page: 1,
search: searchTerm this.loadPieceList({ search, page: 1 });
}); this.history.push({ pathname, query: { page: 1 } });
this.history.pushState(null, this.props.location.pathname, {page: 1});
}, },
applyFilterBy(filterBy){ applyFilterBy(filterBy) {
const { location: { pathname } } = this.props;
this.setState({ this.setState({
isFilterDirty: true isFilterDirty: true
}); });
@ -190,31 +198,32 @@ let PieceList = React.createClass({
this.state.pieceList this.state.pieceList
.forEach((piece) => { .forEach((piece) => {
// but only if they're actually open // but only if they're actually open
if(this.state.isEditionListOpenForPieceId[piece.id].show) { const isEditionListOpenForPiece = this.state.isEditionListOpenForPieceId[piece.id];
if (isEditionListOpenForPiece && isEditionListOpenForPiece.show) {
EditionListActions.refreshEditionList({ EditionListActions.refreshEditionList({
pieceId: piece.id, pieceId: piece.id,
filterBy filterBy
}); });
} }
}); });
}); });
// we have to redirect the user always to page one as it could be that there is no page two // we have to redirect the user always to page one as it could be that there is no page two
// for filtered pieces // for filtered pieces
this.history.pushState(null, this.props.location.pathname, {page: 1}); this.history.push({ pathname, query: { page: 1 } });
}, },
applyOrderBy(orderBy) { applyOrderBy(orderBy) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, page, pageSize, search } = this.state;
orderBy, this.state.orderAsc, this.state.filterBy); PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
}, },
loadPieceList({ page, filterBy = this.state.filterBy, search = this.state.search }) { loadPieceList({ page, filterBy = this.state.filterBy, search = this.state.search }) {
const { orderAsc, pageSize } = this.state;
const orderBy = this.state.orderBy || this.props.orderBy; const orderBy = this.state.orderBy || this.props.orderBy;
return PieceListActions.fetchPieceList(page, this.state.pageSize, search, return PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
orderBy, this.state.orderAsc, filterBy);
}, },
fetchSelectedPieceEditionList() { fetchSelectedPieceEditionList() {
@ -240,8 +249,9 @@ let PieceList = React.createClass({
}, },
handleAclSuccess() { handleAclSuccess() {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderBy, orderAsc, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
this.fetchSelectedPieceEditionList() this.fetchSelectedPieceEditionList()
.forEach((pieceId) => { .forEach((pieceId) => {

View File

@ -65,26 +65,21 @@ let RegisterPiece = React.createClass( {
this.setState(state); this.setState(state);
}, },
handleSuccess(response){ handleSuccess(response) {
let notification = new GlobalNotificationModel(response.notification, 'success', 10000); const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
const notification = new GlobalNotificationModel(response.notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
// once the user was able to register a piece successfully, we need to make sure to keep // once the user was able to register a piece successfully, we need to make sure to keep
// the piece list up to date // the piece list up to date
PieceListActions.fetchPieceList( PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
this.state.page,
this.state.pageSize,
this.state.searchTerm,
this.state.orderBy,
this.state.orderAsc,
this.state.filterBy
);
this.history.pushState(null, `/pieces/${response.piece.id}`); this.history.push(`/pieces/${response.piece.id}`);
}, },
getSpecifyEditions() { getSpecifyEditions() {
if(this.state.whitelabel && this.state.whitelabel.acl_create_editions || Object.keys(this.state.whitelabel).length === 0) { if (this.state.whitelabel && this.state.whitelabel.acl_create_editions || Object.keys(this.state.whitelabel).length === 0) {
return ( return (
<Property <Property
name="num_editions" name="num_editions"
@ -94,7 +89,8 @@ let RegisterPiece = React.createClass( {
<input <input
type="number" type="number"
placeholder="(e.g. 32)" placeholder="(e.g. 32)"
min={0}/> min={1}
max={100} />
</Property> </Property>
); );
} }

View File

@ -3,24 +3,28 @@
import React from 'react'; import React from 'react';
import { History } from 'react-router'; import { History } from 'react-router';
import GlobalNotificationModel from '../../../../../../models/global_notification_model';
import GlobalNotificationActions from '../../../../../../actions/global_notification_actions';
import Form from '../../../../../ascribe_forms/form'; import Form from '../../../../../ascribe_forms/form';
import Property from '../../../../../ascribe_forms/property'; import Property from '../../../../../ascribe_forms/property';
import InputTextAreaToggable from '../../../../../ascribe_forms/input_textarea_toggable'; import InputTextAreaToggable from '../../../../../ascribe_forms/input_textarea_toggable';
import UploadButton from '../../../../../ascribe_uploader/ascribe_upload_button/upload_button';
import InputFineuploader from '../../../../../ascribe_forms/input_fineuploader'; import InputFineuploader from '../../../../../ascribe_forms/input_fineuploader';
import UploadButton from '../../../../../ascribe_uploader/ascribe_upload_button/upload_button';
import AscribeSpinner from '../../../../../ascribe_spinner'; import AscribeSpinner from '../../../../../ascribe_spinner';
import GlobalNotificationModel from '../../../../../../models/global_notification_model';
import GlobalNotificationActions from '../../../../../../actions/global_notification_actions';
import AppConstants from '../../../../../../constants/application_constants';
import ApiUrls from '../../../../../../constants/api_urls'; import ApiUrls from '../../../../../../constants/api_urls';
import AppConstants from '../../../../../../constants/application_constants';
import { validationParts, validationTypes } from '../../../../../../constants/uploader_constants';
import requests from '../../../../../../utils/requests'; import requests from '../../../../../../utils/requests';
import { getLangText } from '../../../../../../utils/lang_utils'; import { getErrorNotificationMessage } from '../../../../../../utils/error_utils';
import { setCookie } from '../../../../../../utils/fetch_api_utils'; import { setCookie } from '../../../../../../utils/fetch_api_utils';
import { validateForms } from '../../../../../../utils/form_utils';
import { getLangText } from '../../../../../../utils/lang_utils';
import { formSubmissionValidation } from '../../../../../ascribe_uploader/react_s3_fine_uploader_utils'; import { formSubmissionValidation } from '../../../../../ascribe_uploader/react_s3_fine_uploader_utils';
@ -35,7 +39,7 @@ const PRRegisterPieceForm = React.createClass({
mixins: [History], mixins: [History],
getInitialState(){ getInitialState() {
return { return {
digitalWorkKeyReady: true, digitalWorkKeyReady: true,
thumbnailKeyReady: true, thumbnailKeyReady: true,
@ -54,15 +58,15 @@ const PRRegisterPieceForm = React.createClass({
* second adding all the additional details * second adding all the additional details
*/ */
submit() { submit() {
if(!this.validateForms()) { if (!this.validateForms()) {
return; return;
} else { }
// disable the submission button right after the user // disable the submission button right after the user
// clicks on it to avoid double submission // clicks on it to avoid double submission
this.setState({ this.setState({
submitted: true submitted: true
}); });
}
const { currentUser } = this.props; const { currentUser } = this.props;
const { registerPieceForm, const { registerPieceForm,
@ -104,12 +108,20 @@ const PRRegisterPieceForm = React.createClass({
GlobalNotificationActions.appendGlobalNotification(notificationMessage); GlobalNotificationActions.appendGlobalNotification(notificationMessage);
}); });
}) })
.then(() => this.history.pushState(null, `/pieces/${this.state.piece.id}`)) .then(() => this.history.push(`/pieces/${this.state.piece.id}`))
.catch((err) => { .catch((err) => {
const notificationMessage = new GlobalNotificationModel(getLangText("Oops! We weren't able to send your submission. Contact: support@ascribe.io"), 'danger', 5000); const errMessage = (getErrorNotificationMessage(err) || getLangText("Oops! We weren't able to send your submission.")) +
getLangText(' Please contact support@ascribe.io');
const notificationMessage = new GlobalNotificationModel(errMessage, 'danger', 10000);
GlobalNotificationActions.appendGlobalNotification(notificationMessage); GlobalNotificationActions.appendGlobalNotification(notificationMessage);
console.logGlobal(new Error('Portfolio Review piece registration failed'), err); console.logGlobal(new Error('Portfolio Review piece registration failed'), err);
// Reset the submit button
this.setState({
submitted: false
});
}); });
}, },
@ -118,11 +130,7 @@ const PRRegisterPieceForm = React.createClass({
additionalDataForm, additionalDataForm,
uploadersForm } = this.refs; uploadersForm } = this.refs;
const registerPieceFormValidation = registerPieceForm.validate(); return validateForms([registerPieceForm, additionalDataForm, uploadersForm], true);
const additionalDataFormValidation = additionalDataForm.validate();
const uploaderFormValidation = uploadersForm.validate();
return registerPieceFormValidation && additionalDataFormValidation && uploaderFormValidation;
}, },
getCreateBlobRoutine() { getCreateBlobRoutine() {
@ -139,7 +147,7 @@ const PRRegisterPieceForm = React.createClass({
}, },
/** /**
* This method is overloaded so that we can track the ready-state * These two methods are overloaded so that we can track the ready-state
* of each uploader in the component * of each uploader in the component
* @param {string} uploaderKey Name of the uploader's key to track * @param {string} uploaderKey Name of the uploader's key to track
*/ */
@ -151,6 +159,14 @@ const PRRegisterPieceForm = React.createClass({
}; };
}, },
handleOptionalFileValidationFailed(uploaderKey) {
return () => {
this.setState({
[uploaderKey]: true
});
};
},
getSubmitButton() { getSubmitButton() {
const { digitalWorkKeyReady, const { digitalWorkKeyReady,
thumbnailKeyReady, thumbnailKeyReady,
@ -179,11 +195,12 @@ const PRRegisterPieceForm = React.createClass({
render() { render() {
const { location } = this.props; const { location } = this.props;
const maxThumbnailSize = validationTypes.workThumbnail.sizeLimit / 1000000;
return ( return (
<div className="register-piece--form"> <div className="register-piece--form">
<Form <Form
buttons={{}} buttons={null}
className="ascribe-form-bordered" className="ascribe-form-bordered"
ref="registerPieceForm"> ref="registerPieceForm">
<Property <Property
@ -220,7 +237,7 @@ const PRRegisterPieceForm = React.createClass({
</Property> </Property>
</Form> </Form>
<Form <Form
buttons={{}} buttons={null}
className="ascribe-form-bordered" className="ascribe-form-bordered"
ref="additionalDataForm"> ref="additionalDataForm">
<Property <Property
@ -272,7 +289,7 @@ const PRRegisterPieceForm = React.createClass({
</Property> </Property>
</Form> </Form>
<Form <Form
buttons={{}} buttons={null}
className="ascribe-form-bordered" className="ascribe-form-bordered"
ref="uploadersForm"> ref="uploadersForm">
<Property <Property
@ -290,8 +307,8 @@ const PRRegisterPieceForm = React.createClass({
fileClass: 'digitalwork' fileClass: 'digitalwork'
}} }}
validation={{ validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit, itemLimit: validationTypes.registerWork.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit, sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: ['pdf'] allowedExtensions: ['pdf']
}} }}
location={location} location={location}
@ -303,7 +320,7 @@ const PRRegisterPieceForm = React.createClass({
</Property> </Property>
<Property <Property
name="thumbnailKey" name="thumbnailKey"
label={getLangText('Featured Cover photo')}> label={`${getLangText('Featured Cover photo')} (max ${maxThumbnailSize}MB)`}>
<InputFineuploader <InputFineuploader
fileInputElement={UploadButton()} fileInputElement={UploadButton()}
createBlobRoutine={{ createBlobRoutine={{
@ -316,9 +333,9 @@ const PRRegisterPieceForm = React.createClass({
fileClass: 'thumbnail' fileClass: 'thumbnail'
}} }}
validation={{ validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit, itemLimit: validationTypes.workThumbnail.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit, sizeLimit: validationTypes.workThumbnail.sizeLimit,
allowedExtensions: ['png', 'jpg', 'jpeg', 'gif'] allowedExtensions: validationParts.allowedExtensions.images
}} }}
location={location} location={location}
fileClassToUpload={{ fileClassToUpload={{
@ -334,14 +351,15 @@ const PRRegisterPieceForm = React.createClass({
fileInputElement={UploadButton()} fileInputElement={UploadButton()}
isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile} isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile}
setIsUploadReady={this.setIsUploadReady('supportingMaterialsReady')} setIsUploadReady={this.setIsUploadReady('supportingMaterialsReady')}
onValidationFailed={this.handleOptionalFileValidationFailed('supportingMaterialsReady')}
createBlobRoutine={this.getCreateBlobRoutine()} createBlobRoutine={this.getCreateBlobRoutine()}
keyRoutine={{ keyRoutine={{
url: AppConstants.serverUrl + 's3/key/', url: AppConstants.serverUrl + 's3/key/',
fileClass: 'otherdata' fileClass: 'otherdata'
}} }}
validation={{ validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit, itemLimit: validationParts.itemLimit.single,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit sizeLimit: validationTypes.additionalData.sizeLimit
}} }}
location={location} location={location}
fileClassToUpload={{ fileClassToUpload={{
@ -362,9 +380,9 @@ const PRRegisterPieceForm = React.createClass({
fileClass: 'otherdata' fileClass: 'otherdata'
}} }}
validation={{ validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit, itemLimit: validationParts.itemLimit.single,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit, sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: ['png', 'jpg', 'jpeg', 'gif'] allowedExtensions: validationParts.allowedExtensions.images
}} }}
location={location} location={location}
fileClassToUpload={{ fileClassToUpload={{
@ -375,7 +393,7 @@ const PRRegisterPieceForm = React.createClass({
</Property> </Property>
</Form> </Form>
<Form <Form
buttons={{}} buttons={null}
className="ascribe-form-bordered"> className="ascribe-form-bordered">
<Property <Property
name="terms" name="terms"

View File

@ -14,7 +14,7 @@ import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
import UserStore from '../../../../../stores/user_store'; import UserStore from '../../../../../stores/user_store';
import UserActions from '../../../../../actions/user_actions'; import UserActions from '../../../../../actions/user_actions';
import { mergeOptions } from '../../../../../utils/general_utils'; import { mergeOptions, omitFromObject } from '../../../../../utils/general_utils';
import { getLangText } from '../../../../../utils/lang_utils'; import { getLangText } from '../../../../../utils/lang_utils';
@ -34,15 +34,18 @@ const PRLanding = React.createClass({
componentDidMount() { componentDidMount() {
const { location } = this.props; const { location } = this.props;
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
PrizeStore.listen(this.onChange); PrizeStore.listen(this.onChange);
UserActions.fetchCurrentUser();
PrizeActions.fetchPrize(); PrizeActions.fetchPrize();
if(location && location.query && location.query.redirect) { if (location && location.query && location.query.redirect) {
let queryCopy = JSON.parse(JSON.stringify(location.query)); window.setTimeout(() => this.history.replace({
delete queryCopy.redirect; pathname: `/${location.query.redirect}`,
window.setTimeout(() => this.history.replaceState(null, `/${location.query.redirect}`, queryCopy)); query: omitFromObject(location.query, ['redirect'])
}));
} }
}, },

View File

@ -39,7 +39,7 @@ const PRRegisterPiece = React.createClass({
if(currentUser && currentUser.email) { if(currentUser && currentUser.email) {
const submittedPieceId = getCookie(currentUser.email); const submittedPieceId = getCookie(currentUser.email);
if(submittedPieceId) { if(submittedPieceId) {
this.history.pushState(null, `/pieces/${submittedPieceId}`); this.history.push(`/pieces/${submittedPieceId}`);
} }
} }
}, },
@ -62,7 +62,7 @@ const PRRegisterPiece = React.createClass({
<Col xs={6}> <Col xs={6}>
<div className="register-piece--info"> <div className="register-piece--info">
<h1>Portfolio Review</h1> <h1>Portfolio Review</h1>
<h2>{getLangText('Submission closing on %s', ' 22 Dec 2015')}</h2> <h2>{getLangText('Submission closing on %s', ' 27 Dec 2015')}</h2>
<p>For more information, visit:&nbsp; <p>For more information, visit:&nbsp;
<a href="http://www.portfolio-review.de/submission/" target="_blank"> <a href="http://www.portfolio-review.de/submission/" target="_blank">
portfolio-review.de portfolio-review.de

View File

@ -17,7 +17,7 @@ export function AuthPrizeRoleRedirect({ to, when }) {
.reduce((a, b) => a || b); .reduce((a, b) => a || b);
if (exprToValidate) { if (exprToValidate) {
window.setTimeout(() => history.replaceState(null, to, query)); window.setTimeout(() => history.replace({ query, pathname: to }));
return true; return true;
} else { } else {
return false; return false;

View File

@ -12,6 +12,8 @@ import SPPieceContainer from './simple_prize/components/ascribe_detail/prize_pie
import SPSettingsContainer from './simple_prize/components/prize_settings_container'; import SPSettingsContainer from './simple_prize/components/prize_settings_container';
import SPApp from './simple_prize/prize_app'; import SPApp from './simple_prize/prize_app';
import SluicePieceContainer from './sluice/components/sluice_detail/sluice_piece_container';
import PRApp from './portfolioreview/pr_app'; import PRApp from './portfolioreview/pr_app';
import PRLanding from './portfolioreview/components/pr_landing'; import PRLanding from './portfolioreview/components/pr_landing';
import PRRegisterPiece from './portfolioreview/components/pr_register_piece'; import PRRegisterPiece from './portfolioreview/components/pr_register_piece';
@ -53,7 +55,7 @@ const ROUTES = {
path='collection' path='collection'
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPPieceList)} component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPPieceList)}
headerTitle='COLLECTION'/> headerTitle='COLLECTION'/>
<Route path='pieces/:pieceId' component={SPPieceContainer} /> <Route path='pieces/:pieceId' component={SluicePieceContainer} />
<Route path='editions/:editionId' component={EditionContainer} /> <Route path='editions/:editionId' component={EditionContainer} />
<Route path='verify' component={CoaVerifyContainer} /> <Route path='verify' component={CoaVerifyContainer} />
<Route path='*' component={ErrorNotFoundPage} /> <Route path='*' component={ErrorNotFoundPage} />

View File

@ -10,14 +10,15 @@ class PrizeRatingActions {
this.generateActions( this.generateActions(
'updatePrizeRatings', 'updatePrizeRatings',
'updatePrizeRatingAverage', 'updatePrizeRatingAverage',
'updatePrizeRating' 'updatePrizeRating',
'resetPrizeRatings'
); );
} }
fetchAverage(pieceId) { fetchAverage(pieceId, round) {
return Q.Promise((resolve, reject) => { return Q.Promise((resolve, reject) => {
PrizeRatingFetcher PrizeRatingFetcher
.fetchAverage(pieceId) .fetchAverage(pieceId, round)
.then((res) => { .then((res) => {
this.actions.updatePrizeRatingAverage(res.data); this.actions.updatePrizeRatingAverage(res.data);
resolve(res); resolve(res);
@ -29,10 +30,10 @@ class PrizeRatingActions {
}); });
} }
fetchOne(pieceId) { fetchOne(pieceId, round) {
return Q.Promise((resolve, reject) => { return Q.Promise((resolve, reject) => {
PrizeRatingFetcher PrizeRatingFetcher
.fetchOne(pieceId) .fetchOne(pieceId, round)
.then((res) => { .then((res) => {
this.actions.updatePrizeRating(res.rating.rating); this.actions.updatePrizeRating(res.rating.rating);
resolve(res); resolve(res);
@ -43,10 +44,10 @@ class PrizeRatingActions {
}); });
} }
createRating(pieceId, rating) { createRating(pieceId, rating, round) {
return Q.Promise((resolve, reject) => { return Q.Promise((resolve, reject) => {
PrizeRatingFetcher PrizeRatingFetcher
.rate(pieceId, rating) .rate(pieceId, rating, round)
.then((res) => { .then((res) => {
this.actions.updatePrizeRating(res.rating.rating); this.actions.updatePrizeRating(res.rating.rating);
resolve(res); resolve(res);
@ -70,10 +71,6 @@ class PrizeRatingActions {
}); });
}); });
} }
updateRating(rating) {
this.actions.updatePrizeRating(rating);
}
} }
export default alt.createActions(PrizeRatingActions); export default alt.createActions(PrizeRatingActions);

View File

@ -58,8 +58,9 @@ let AccordionListItemPrize = React.createClass({
}, },
handleSubmitPrizeSuccess(response) { handleSubmitPrizeSuccess(response) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
let notification = new GlobalNotificationModel(response.notification, 'success', 10000); let notification = new GlobalNotificationModel(response.notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
@ -138,8 +139,9 @@ let AccordionListItemPrize = React.createClass({
}, },
refreshPieceData() { refreshPieceData() {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
}, },
onSelectChange(){ onSelectChange(){
@ -171,23 +173,25 @@ let AccordionListItemPrize = React.createClass({
}, },
render() { render() {
const { children, className, content } = this.props;
const { currentUser } = this.state;
// Only show the artist name if you are the participant or if you are a judge and the piece is shortlisted // Only show the artist name if you are the participant or if you are a judge and the piece is shortlisted
let artistName = ((this.state.currentUser.is_jury && !this.state.currentUser.is_judge) || let artistName = ((currentUser.is_jury && !currentUser.is_judge) || (currentUser.is_judge && !content.selected )) ?
(this.state.currentUser.is_judge && !this.props.content.selected )) ? <span className="glyphicon glyphicon-eye-close" aria-hidden="true"/> : content.artist_name;
<span className="glyphicon glyphicon-eye-close" aria-hidden="true"/> : this.props.content.artist_name;
return ( return (
<div> <div>
<AccordionListItemPiece <AccordionListItemPiece
className={this.props.className} className={className}
piece={this.props.content} piece={content}
artistName={artistName} artistName={artistName}
subsubheading={ subsubheading={
<div> <div>
<span>{Moment(this.props.content.date_created, 'YYYY-MM-DD').year()}</span> <span>{Moment(content.date_created, 'YYYY-MM-DD').year()}</span>
</div>} </div>}
buttons={this.getPrizeButtons()} buttons={this.getPrizeButtons()}
badge={this.getPrizeBadge()}> badge={this.getPrizeBadge()}>
{this.props.children} {children}
</AccordionListItemPiece> </AccordionListItemPiece>
</div> </div>
); );

View File

@ -9,15 +9,16 @@ import StarRating from 'react-star-rating';
import ReactError from '../../../../../../mixins/react_error'; import ReactError from '../../../../../../mixins/react_error';
import { ResourceNotFoundError } from '../../../../../../models/errors'; import { ResourceNotFoundError } from '../../../../../../models/errors';
import PieceActions from '../../../../../../actions/piece_actions'; import PrizeActions from '../../actions/prize_actions';
import PieceStore from '../../../../../../stores/piece_store'; import PrizeStore from '../../stores/prize_store';
import PieceListStore from '../../../../../../stores/piece_list_store';
import PieceListActions from '../../../../../../actions/piece_list_actions';
import PrizeRatingActions from '../../actions/prize_rating_actions'; import PrizeRatingActions from '../../actions/prize_rating_actions';
import PrizeRatingStore from '../../stores/prize_rating_store'; import PrizeRatingStore from '../../stores/prize_rating_store';
import PieceActions from '../../../../../../actions/piece_actions';
import PieceStore from '../../../../../../stores/piece_store';
import PieceListStore from '../../../../../../stores/piece_list_store';
import PieceListActions from '../../../../../../actions/piece_list_actions';
import UserStore from '../../../../../../stores/user_store'; import UserStore from '../../../../../../stores/user_store';
import UserActions from '../../../../../../actions/user_actions'; import UserActions from '../../../../../../actions/user_actions';
@ -34,9 +35,7 @@ import CollapsibleParagraph from '../../../../../../components/ascribe_collapsib
import FurtherDetailsFileuploader from '../../../../../ascribe_detail/further_details_fileuploader'; import FurtherDetailsFileuploader from '../../../../../ascribe_detail/further_details_fileuploader';
import InputCheckbox from '../../../../../ascribe_forms/input_checkbox'; import InputCheckbox from '../../../../../ascribe_forms/input_checkbox';
import LoanForm from '../../../../../ascribe_forms/form_loan';
import ListRequestActions from '../../../../../ascribe_forms/list_form_request_actions'; import ListRequestActions from '../../../../../ascribe_forms/list_form_request_actions';
import ModalWrapper from '../../../../../ascribe_modal/modal_wrapper';
import GlobalNotificationModel from '../../../../../../models/global_notification_model'; import GlobalNotificationModel from '../../../../../../models/global_notification_model';
import GlobalNotificationActions from '../../../../../../actions/global_notification_actions'; import GlobalNotificationActions from '../../../../../../actions/global_notification_actions';
@ -52,16 +51,17 @@ import { setDocumentTitle } from '../../../../../../utils/dom_utils';
/** /**
* This is the component that implements resource/data specific functionality * This is the component that implements resource/data specific functionality
*/ */
let PieceContainer = React.createClass({ let PrizePieceContainer = React.createClass({
propTypes: { propTypes: {
params: React.PropTypes.object params: React.PropTypes.object,
selectedPrizeActionButton: React.PropTypes.func
}, },
mixins: [ReactError], mixins: [ReactError],
getInitialState() { getInitialState() {
return mergeOptions( return mergeOptions(
PieceStore.getState(), PieceStore.getInitialState(),
UserStore.getState() UserStore.getState()
); );
}, },
@ -70,28 +70,24 @@ let PieceContainer = React.createClass({
PieceStore.listen(this.onChange); PieceStore.listen(this.onChange);
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
// Every time we enter the piece detail page, just reset the piece
// store as it will otherwise display wrong/old data once the user loads
// the piece detail a second time
PieceActions.updatePiece({});
PieceActions.fetchOne(this.props.params.pieceId);
UserActions.fetchCurrentUser(); UserActions.fetchCurrentUser();
this.loadPiece();
}, },
// This is done to update the container when the user clicks on the prev or next // This is done to update the container when the user clicks on the prev or next
// button to update the URL parameter (and therefore to switch pieces) // button to update the URL parameter (and therefore to switch pieces) or
// when the user clicks on a notification while being in another piece view
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
if(this.props.params.pieceId !== nextProps.params.pieceId) { if (this.props.params.pieceId !== nextProps.params.pieceId) {
PieceActions.updatePiece({}); PieceActions.flushPiece();
PieceActions.fetchOne(nextProps.params.pieceId); this.loadPiece(nextProps.params.pieceId);
} }
}, },
componentDidUpdate() { componentDidUpdate() {
const { pieceError } = this.state; const { pieceMeta: { err: pieceErr } } = this.state;
if (pieceError && pieceError.status === 404) { if (pieceErr && pieceErr.status === 404) {
this.throws(new ResourceNotFoundError(getLangText("Oops, the piece you're looking for doesn't exist."))); this.throws(new ResourceNotFoundError(getLangText("Oops, the piece you're looking for doesn't exist.")));
} }
}, },
@ -101,26 +97,32 @@ let PieceContainer = React.createClass({
UserStore.unlisten(this.onChange); UserStore.unlisten(this.onChange);
}, },
onChange(state) { onChange(state) {
this.setState(state); this.setState(state);
}, },
getActions() { getActions() {
if (this.state.piece && const { currentUser, piece } = this.state;
this.state.piece.notifications &&
this.state.piece.notifications.length > 0) { if (piece.notifications && piece.notifications.length > 0) {
return ( return (
<ListRequestActions <ListRequestActions
pieceOrEditions={this.state.piece} pieceOrEditions={piece}
currentUser={this.state.currentUser} currentUser={currentUser}
handleSuccess={this.loadPiece} handleSuccess={this.loadPiece}
notifications={this.state.piece.notifications}/>); notifications={piece.notifications} />);
} }
}, },
loadPiece(pieceId = this.props.params.pieceId) {
PieceActions.fetchPiece(pieceId);
},
render() { render() {
if(this.state.piece && this.state.piece.id) { const { selectedPrizeActionButton } = this.props;
const { currentUser, piece } = this.state;
if (piece.id) {
/* /*
This really needs a refactor! This really needs a refactor!
@ -129,49 +131,48 @@ let PieceContainer = React.createClass({
*/ */
// Only show the artist name if you are the participant or if you are a judge and the piece is shortlisted // Only show the artist name if you are the participant or if you are a judge and the piece is shortlisted
let artistName = ((this.state.currentUser.is_jury && !this.state.currentUser.is_judge) || let artistName;
(this.state.currentUser.is_judge && !this.state.piece.selected )) ? if ((currentUser.is_jury && !currentUser.is_judge) || (currentUser.is_judge && !piece.selected )) {
null : this.state.piece.artist_name; artistName = <span className="glyphicon glyphicon-eye-close" aria-hidden="true" />;
setDocumentTitle(piece.title);
} else {
artistName = piece.artist_name;
setDocumentTitle(`${artistName}, ${piece.title}`);
}
// Only show the artist email if you are a judge and the piece is shortlisted // Only show the artist email if you are a judge and the piece is shortlisted
let artistEmail = (this.state.currentUser.is_judge && this.state.piece.selected ) ? const artistEmail = currentUser.is_judge && piece.selected ? (
<DetailProperty label={getLangText('REGISTREE')} value={ this.state.piece.user_registered } /> : null; <DetailProperty
label={getLangText('REGISTREE')}
if (artistName === null) { value={piece.user_registered} />
setDocumentTitle(this.state.piece.title); ) : null;
} else {
setDocumentTitle([artistName, this.state.piece.title].join(', '));
}
if (artistName === null) {
artistName = <span className="glyphicon glyphicon-eye-close" aria-hidden="true"/>;
}
return ( return (
<Piece <Piece
piece={this.state.piece} piece={piece}
loadPiece={this.loadPiece} currentUser={currentUser}
header={ header={
<div className="ascribe-detail-header"> <div className="ascribe-detail-header">
<NavigationHeader <NavigationHeader
piece={this.state.piece} piece={piece}
currentUser={this.state.currentUser}/> currentUser={currentUser} />
<h1 className="ascribe-detail-title">{this.state.piece.title}</h1> <h1 className="ascribe-detail-title">{piece.title}</h1>
<DetailProperty label={getLangText('BY')} value={artistName} /> <DetailProperty label={getLangText('BY')} value={artistName} />
<DetailProperty label={getLangText('DATE')} value={Moment(this.state.piece.date_created, 'YYYY-MM-DD').year()} /> <DetailProperty label={getLangText('DATE')} value={Moment(piece.date_created, 'YYYY-MM-DD').year()} />
{artistEmail} {artistEmail}
{this.getActions()} {this.getActions()}
<hr/> <hr />
</div> </div>
} }
subheader={ subheader={
<PrizePieceRatings <PrizePieceRatings
loadPiece={this.loadPiece} loadPiece={this.loadPiece}
piece={this.state.piece} piece={piece}
currentUser={this.state.currentUser}/> currentUser={currentUser}
selectedPrizeActionButton={selectedPrizeActionButton} />
}> }>
<PrizePieceDetails piece={this.state.piece} /> <PrizePieceDetails piece={piece} />
</Piece> </Piece>
); );
} else { } else {
@ -186,16 +187,15 @@ let PieceContainer = React.createClass({
let NavigationHeader = React.createClass({ let NavigationHeader = React.createClass({
propTypes: { propTypes: {
piece: React.PropTypes.object, currentUser: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object piece: React.PropTypes.object.isRequired
}, },
render() { render() {
const { currentUser, piece } = this.props; const { currentUser, piece } = this.props;
if (currentUser && currentUser.email && currentUser.is_judge && currentUser.is_jury && if (currentUser.email && currentUser.is_judge && currentUser.is_jury && !currentUser.is_admin && piece.navigation) {
!currentUser.is_admin && piece && piece.navigation) { const nav = piece.navigation;
let nav = piece.navigation;
return ( return (
<div style={{marginBottom: '1em'}}> <div style={{marginBottom: '1em'}}>
@ -215,41 +215,49 @@ let NavigationHeader = React.createClass({
<hr/> <hr/>
</div> </div>
); );
} } else {
return null; return null;
} }
}
}); });
let PrizePieceRatings = React.createClass({ let PrizePieceRatings = React.createClass({
propTypes: { propTypes: {
loadPiece: React.PropTypes.func, currentUser: React.PropTypes.object.isRequired,
piece: React.PropTypes.object, loadPiece: React.PropTypes.func.isRequired,
currentUser: React.PropTypes.object piece: React.PropTypes.object.isRequired,
selectedPrizeActionButton: React.PropTypes.func
}, },
getInitialState() { getInitialState() {
return mergeOptions( return mergeOptions(
PieceListStore.getState(), PieceListStore.getState(),
PrizeRatingStore.getState() PrizeStore.getState(),
PrizeRatingStore.getInitialState()
); );
}, },
componentDidMount() { componentDidMount() {
PrizeRatingStore.listen(this.onChange); PrizeRatingStore.listen(this.onChange);
PrizeRatingActions.fetchOne(this.props.piece.id); PrizeStore.listen(this.onChange);
PrizeRatingActions.fetchAverage(this.props.piece.id);
PieceListStore.listen(this.onChange); PieceListStore.listen(this.onChange);
PrizeActions.fetchPrize();
this.fetchRatingsIfAuthorized();
},
componentWillReceiveProps(nextProps) {
if (nextProps.currentUser.email !== this.props.currentUser.email) {
this.fetchRatingsIfAuthorized();
}
}, },
componentWillUnmount() { componentWillUnmount() {
// Every time we're leaving the piece detail page,
// just reset the piece that is saved in the piece store
// as it will otherwise display wrong/old data once the user loads
// the piece detail a second time
PrizeRatingActions.updateRating({});
PrizeRatingStore.unlisten(this.onChange);
PieceListStore.unlisten(this.onChange); PieceListStore.unlisten(this.onChange);
PrizeStore.unlisten(this.onChange);
PrizeRatingStore.unlisten(this.onChange);
}, },
// The StarRating component does not have a property that lets us set // The StarRating component does not have a property that lets us set
@ -257,7 +265,12 @@ let PrizePieceRatings = React.createClass({
// every mouseover be overridden, we need to set it ourselves initially to deal // every mouseover be overridden, we need to set it ourselves initially to deal
// with the problem. // with the problem.
onChange(state) { onChange(state) {
if (state.prize && state.prize.active_round != this.state.prize.active_round) {
this.fetchRatingsIfAuthorized(state);
}
this.setState(state); this.setState(state);
if (this.refs.rating) { if (this.refs.rating) {
this.refs.rating.state.ratingCache = { this.refs.rating.state.ratingCache = {
pos: this.refs.rating.state.pos, pos: this.refs.rating.state.pos,
@ -268,74 +281,64 @@ let PrizePieceRatings = React.createClass({
} }
}, },
fetchRatingsIfAuthorized(state = this.state) {
const {
currentUser: {
is_admin: isAdmin,
is_judge: isJudge,
is_jury: isJury
},
piece: { id: pieceId } } = this.props;
if (state.prize && 'active_round' in state.prize && (isAdmin || isJudge || isJury)) {
PrizeRatingActions.fetchOne(pieceId, state.prize.active_round);
PrizeRatingActions.fetchAverage(pieceId, state.prize.active_round);
}
},
onRatingClick(event, args) { onRatingClick(event, args) {
event.preventDefault(); event.preventDefault();
PrizeRatingActions.createRating(this.props.piece.id, args.rating).then( PrizeRatingActions
this.refreshPieceData() .createRating(this.props.piece.id, args.rating, this.state.prize.active_round)
); .then(this.refreshPieceData);
}, },
handleLoanRequestSuccess(message){ getSelectedActionButton() {
let notification = new GlobalNotificationModel(message, 'success', 4000); const { currentUser, piece, selectedPrizeActionButton: SelectedPrizeActionButton } = this.props;
GlobalNotificationActions.appendGlobalNotification(notification);
},
getLoanButton(){ if (piece.selected && SelectedPrizeActionButton) {
let today = new Moment();
let endDate = new Moment();
endDate.add(6, 'months');
return ( return (
<ModalWrapper <span className="pull-right">
trigger={ <SelectedPrizeActionButton
<button className='btn btn-default btn-sm'> piece={piece}
{getLangText('SEND LOAN REQUEST')} currentUser={currentUser} />
</button> </span>
);
} }
handleSuccess={this.handleLoanRequestSuccess}
title='REQUEST LOAN'>
<LoanForm
loanHeading={null}
message={getLangText('Congratulations,\nYou have been selected for the prize.\n' +
'Please accept the loan request to proceed.')}
id={{piece_id: this.props.piece.id}}
url={ApiUrls.ownership_loans_pieces_request}
email={this.props.currentUser.email}
gallery={this.props.piece.prize.name}
startDate={today}
endDate={endDate}
showPersonalMessage={true}
showPassword={false}
handleSuccess={this.handleLoanSuccess} />
</ModalWrapper>);
},
handleShortlistSuccess(message){
let notification = new GlobalNotificationModel(message, 'success', 2000);
GlobalNotificationActions.appendGlobalNotification(notification);
}, },
refreshPieceData() { refreshPieceData() {
const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.props.loadPiece(); this.props.loadPiece();
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
}, },
onSelectChange() { onSelectChange() {
PrizeRatingActions.toggleShortlist(this.props.piece.id) PrizeRatingActions
.then( .toggleShortlist(this.props.piece.id)
(res) => { .then((res) => {
this.refreshPieceData(); this.refreshPieceData();
return res;
}) if (res && res.notification) {
.then( const notification = new GlobalNotificationModel(res.notification, 'success', 2000);
(res) => { GlobalNotificationActions.appendGlobalNotification(notification);
this.handleShortlistSuccess(res.notification);
} }
); });
}, },
render(){ render() {
if (this.props.piece && this.props.currentUser && this.props.currentUser.is_judge && this.state.average) { if (this.props.piece.id && this.props.currentUser.is_judge && this.state.average) {
// Judge sees shortlisting, average and per-jury notes // Judge sees shortlisting, average and per-jury notes
return ( return (
<div> <div>
@ -352,9 +355,7 @@ let PrizePieceRatings = React.createClass({
</span> </span>
</InputCheckbox> </InputCheckbox>
</span> </span>
<span className="pull-right"> {this.getSelectedActionButton()}
{this.props.piece.selected ? this.getLoanButton() : null}
</span>
</div> </div>
<hr /> <hr />
</CollapsibleParagraph> </CollapsibleParagraph>
@ -369,17 +370,23 @@ let PrizePieceRatings = React.createClass({
size='md' size='md'
step={0.5} step={0.5}
rating={this.state.average} rating={this.state.average}
ratingAmount={5}/> ratingAmount={5} />
</div> </div>
<hr /> <hr />
{this.state.ratings.map((item, i) => { {this.state.ratings.map((item, i) => {
let note = item.note ? let note = item.note ? (
<div className="rating-note"> <div className="rating-note">
note: {item.note} note: {item.note}
</div> : null; </div>
) : null;
return ( return (
<div className="rating-list"> <div
<div id="list-rating" className="row no-margin"> key={item.user}
className="rating-list">
<div
id="list-rating"
className="row no-margin">
<span className="pull-right"> <span className="pull-right">
<StarRating <StarRating
ref={'rating' + i} ref={'rating' + i}
@ -388,7 +395,7 @@ let PrizePieceRatings = React.createClass({
size='sm' size='sm'
step={0.5} step={0.5}
rating={item.rating} rating={item.rating}
ratingAmount={5}/> ratingAmount={5} />
</span> </span>
<span> {item.user}</span> <span> {item.user}</span>
{note} {note}
@ -399,8 +406,7 @@ let PrizePieceRatings = React.createClass({
<hr /> <hr />
</CollapsibleParagraph> </CollapsibleParagraph>
</div>); </div>);
} } else if (this.props.currentUser.is_jury) {
else if (this.props.currentUser && this.props.currentUser.is_jury) {
// Jury can set rating and note // Jury can set rating and note
return ( return (
<CollapsibleParagraph <CollapsibleParagraph
@ -418,55 +424,58 @@ let PrizePieceRatings = React.createClass({
ratingAmount={5} /> ratingAmount={5} />
</div> </div>
<Note <Note
id={() => {return {'piece_id': this.props.piece.id}; }} id={() => ({ 'piece_id': this.props.piece.id })}
label={getLangText('Jury note')} label={getLangText('Jury note')}
defaultValue={this.props.piece && this.props.piece.note_from_user ? this.props.piece.note_from_user.note : null} defaultValue={this.props.piece.note_from_user || null}
placeholder={getLangText('Enter your comments ...')} placeholder={getLangText('Enter your comments ...')}
editable={true} editable={true}
successMessage={getLangText('Jury note saved')} successMessage={getLangText('Jury note saved')}
url={ApiUrls.notes} url={ApiUrls.notes}
currentUser={this.props.currentUser}/> currentUser={this.props.currentUser} />
</CollapsibleParagraph>); </CollapsibleParagraph>);
} } else {
return null; return null;
} }
}
}); });
let PrizePieceDetails = React.createClass({ let PrizePieceDetails = React.createClass({
propTypes: { propTypes: {
piece: React.PropTypes.object piece: React.PropTypes.object.isRequired
}, },
render() { render() {
const { piece } = this.props; const { piece } = this.props;
if (piece && if (piece.prize && piece.prize.name && Object.keys(piece.extra_data).length) {
piece.prize &&
piece.prize.name &&
Object.keys(piece.extra_data).length !== 0) {
return ( return (
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Prize Details')} title={getLangText('Prize Details')}
defaultExpanded={true}> defaultExpanded={true}>
<Form ref='form'> <Form>
{Object.keys(piece.extra_data).sort().map((data) => { {Object
.keys(piece.extra_data)
.sort()
.map((data) => {
// Remove leading number (for sorting), if any, and underscores with spaces // Remove leading number (for sorting), if any, and underscores with spaces
let label = data.replace(/^\d-/, '').replace(/_/g, ' '); const label = data.replace(/^\d-/, '').replace(/_/g, ' ');
const value = piece.extra_data[data] || 'N/A'; const value = piece.extra_data[data] || 'N/A';
return ( return (
<Property <Property
key={label}
name={data} name={data}
label={label} label={label}
editable={false} editable={false}
overrideForm={true}> overrideForm={true}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={value}/> defaultValue={value} />
</Property> </Property>
); );
})} })
}
<FurtherDetailsFileuploader <FurtherDetailsFileuploader
submitFile={() => {}} submitFile={() => {}}
setIsUploadReady={() => {}} setIsUploadReady={() => {}}
@ -479,9 +488,10 @@ let PrizePieceDetails = React.createClass({
</Form> </Form>
</CollapsibleParagraph> </CollapsibleParagraph>
); );
} } else {
return null; return null;
} }
}
}); });
export default PieceContainer; export default PrizePieceContainer;

View File

@ -46,7 +46,7 @@ let Landing = React.createClass({
// if user is already logged in, redirect him to piece list // if user is already logged in, redirect him to piece list
if(this.state.currentUser && this.state.currentUser.email) { if(this.state.currentUser && this.state.currentUser.email) {
// FIXME: hack to redirect out of the dispatch cycle // FIXME: hack to redirect out of the dispatch cycle
window.setTimeout(() => this.history.replaceState(null, '/collection'), 0); window.setTimeout(() => this.history.replace('/collection'), 0);
} }
}, },

View File

@ -48,9 +48,8 @@ let PrizePieceList = React.createClass({
}, },
getButtonSubmit() { getButtonSubmit() {
const { currentUser } = this.state; const { currentUser, prize } = this.state;
if (this.state.prize && this.state.prize.active && if (prize && prize.active && !currentUser.is_jury && !currentUser.is_admin && !currentUser.is_judge) {
!currentUser.is_jury && !currentUser.is_admin && !currentUser.is_judge){
return ( return (
<LinkContainer to="/register_piece"> <LinkContainer to="/register_piece">
<Button> <Button>
@ -76,7 +75,6 @@ let PrizePieceList = React.createClass({
<div> <div>
<PieceList <PieceList
ref="list" ref="list"
redirectTo="/register_piece"
accordionListItemType={AccordionListItemPrize} accordionListItemType={AccordionListItemPrize}
orderParams={orderParams} orderParams={orderParams}
orderBy={this.state.currentUser.is_jury ? 'rating' : null} orderBy={this.state.currentUser.is_jury ? 'rating' : null}

View File

@ -135,14 +135,15 @@ let PrizeJurySettings = React.createClass({
handleCreateSuccess(response) { handleCreateSuccess(response) {
PrizeJuryActions.fetchJury(); PrizeJuryActions.fetchJury();
let notification = new GlobalNotificationModel(response.notification, 'success', 5000); this.displayNotification(response);
GlobalNotificationActions.appendGlobalNotification(notification);
this.refs.form.refs.email.refs.input.getDOMNode().value = null; this.refs.form.refs.email.refs.input.getDOMNode().value = null;
}, },
handleActivate(event) { handleActivate(event) {
let email = event.target.getAttribute('data-id'); let email = event.target.getAttribute('data-id');
PrizeJuryActions.activateJury(email).then((response) => { PrizeJuryActions
.activateJury(email)
.then((response) => {
PrizeJuryActions.fetchJury(); PrizeJuryActions.fetchJury();
this.displayNotification(response); this.displayNotification(response);
}); });

View File

@ -4,16 +4,41 @@ import requests from '../../../../../utils/requests';
let PrizeRatingFetcher = { let PrizeRatingFetcher = {
fetchAverage(pieceId) { fetchAverage(pieceId, round) {
return requests.get('rating_average', {'piece_id': pieceId}); const params = {
'piece_id': pieceId
};
if (typeof round === 'number') {
params['prize_round'] = round;
}
return requests.get('rating_average', params);
}, },
fetchOne(pieceId) { fetchOne(pieceId, round) {
return requests.get('rating', {'piece_id': pieceId}); const params = {
'piece_id': pieceId
};
if (typeof round === 'number') {
params['prize_round'] = round;
}
return requests.get('rating', params);
}, },
rate(pieceId, rating) { rate(pieceId, rating, round) {
return requests.post('ratings', {body: {'piece_id': pieceId, 'note': rating}}); const body = {
'piece_id': pieceId,
'note': rating
};
if (typeof round === 'number') {
body['prize_round'] = round;
}
return requests.post('ratings', { body });
}, },
select(pieceId) { select(pieceId) {

View File

@ -32,7 +32,7 @@ let PrizeApp = React.createClass({
if (!path || history.isActive('/login') || history.isActive('/signup')) { if (!path || history.isActive('/login') || history.isActive('/signup')) {
header = <Hero />; header = <Hero />;
} else { } else {
header = <Header showAddWork={false} routes={routes}/>; header = <Header routes={routes}/>;
} }
return ( return (

View File

@ -6,10 +6,24 @@ import PrizeRatingActions from '../actions/prize_rating_actions';
class PrizeRatingStore { class PrizeRatingStore {
constructor() { constructor() {
this.getInitialState();
this.bindActions(PrizeRatingActions);
this.exportPublicMethods({
getInitialState: this.getInitialState.bind(this)
});
}
getInitialState() {
this.ratings = []; this.ratings = [];
this.currentRating = null; this.currentRating = null;
this.average = null; this.average = null;
this.bindActions(PrizeRatingActions);
return {
ratings: this.ratings,
currentRating: this.currentRating,
average: this.average
};
} }
onUpdatePrizeRatings(ratings) { onUpdatePrizeRatings(ratings) {
@ -24,6 +38,10 @@ class PrizeRatingStore {
this.average = data.average; this.average = data.average;
this.ratings = data.ratings; this.ratings = data.ratings;
} }
onResetPrizeRatings() {
this.getInitialState();
}
} }
export default alt.createStore(PrizeRatingStore, 'PrizeRatingStore'); export default alt.createStore(PrizeRatingStore, 'PrizeRatingStore');

View File

@ -6,7 +6,7 @@ import PrizeActions from '../actions/prize_actions';
class PrizeStore { class PrizeStore {
constructor() { constructor() {
this.prize = []; this.prize = {};
this.bindActions(PrizeActions); this.bindActions(PrizeActions);
} }

View File

@ -0,0 +1,70 @@
'use strict'
import React from 'react';
import Moment from 'moment';
import ModalWrapper from '../../../../../ascribe_modal/modal_wrapper';
import LoanForm from '../../../../../ascribe_forms/form_loan';
import GlobalNotificationModel from '../../../../../../models/global_notification_model';
import GlobalNotificationActions from '../../../../../../actions/global_notification_actions';
import ApiUrls from '../../../../../../constants/api_urls';
import { getLangText } from '../../../../../../utils/lang_utils';
const SluiceSelectedPrizeActionButton = React.createClass({
propTypes: {
piece: React.PropTypes.object,
currentUser: React.PropTypes.object,
startLoanDate: React.PropTypes.object,
endLoanDate: React.PropTypes.object,
className: React.PropTypes.string,
handleSuccess: React.PropTypes.func
},
handleSuccess(res) {
const notification = new GlobalNotificationModel(res && res.notification || getLangText('You have successfully requested the loan, pending their confirmation.'), 'success', 4000);
GlobalNotificationActions.appendGlobalNotification(notification);
if (typeof this.props.handleSuccess === 'function') {
this.props.handleSuccess(res);
}
},
render() {
const { currentUser, piece } = this.props;
// Can't use default props since those are only created once
const startLoanDate = this.props.startLoanDate || new Moment();
const endLoanDate = this.props.endLoanDate || (new Moment()).add(6, 'months');
return (
<ModalWrapper
trigger={
<button className='btn btn-default btn-sm'>
{getLangText('SEND LOAN REQUEST')}
</button>
}
handleSuccess={this.handleSuccess}
title={getLangText('REQUEST LOAN')}>
<LoanForm
loanHeading={null}
message={getLangText('Congratulations,\nYou have been selected for the prize.\n' +
'Please accept the loan request to proceed.')}
id={{ piece_id: piece.id }}
url={ApiUrls.ownership_loans_pieces_request}
email={currentUser.email}
gallery={piece.prize.name}
startDate={startLoanDate}
endDate={endLoanDate}
showPersonalMessage={true}
showPassword={false} />
</ModalWrapper>
);
}
});
export default SluiceSelectedPrizeActionButton;

View File

@ -0,0 +1,23 @@
'use strict';
import React from 'react';
import SluiceSelectedPrizeActionButton from '../sluice_buttons/sluice_selected_prize_action_button';
import PrizePieceContainer from '../../../simple_prize/components/ascribe_detail/prize_piece_container';
const SluicePieceContainer = React.createClass({
propTypes: {
params: React.PropTypes.object
},
render() {
return (
<PrizePieceContainer
{...this.props}
selectedPrizeActionButton={SluiceSelectedPrizeActionButton} />
);
}
});
export default SluicePieceContainer;

View File

@ -25,63 +25,72 @@ let WalletPieceContainer = React.createClass({
currentUser: React.PropTypes.object.isRequired, currentUser: React.PropTypes.object.isRequired,
loadPiece: React.PropTypes.func.isRequired, loadPiece: React.PropTypes.func.isRequired,
handleDeleteSuccess: React.PropTypes.func.isRequired, handleDeleteSuccess: React.PropTypes.func.isRequired,
submitButtonType: React.PropTypes.func.isRequired submitButtonType: React.PropTypes.func.isRequired,
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
])
}, },
render() { render() {
if(this.props.piece && this.props.piece.id) { const {
children,
currentUser,
handleDeleteSuccess,
loadPiece,
piece,
submitButtonType } = this.props;
if (piece && piece.id) {
return ( return (
<Piece <Piece
piece={this.props.piece} piece={piece}
loadPiece={this.props.loadPiece} currentUser={currentUser}
header={ header={
<div className="ascribe-detail-header"> <div className="ascribe-detail-header">
<hr style={{marginTop: 0}}/> <hr style={{marginTop: 0}}/>
<h1 className="ascribe-detail-title">{this.props.piece.title}</h1> <h1 className="ascribe-detail-title">{piece.title}</h1>
<DetailProperty label="BY" value={this.props.piece.artist_name} /> <DetailProperty label="BY" value={piece.artist_name} />
<DetailProperty label="DATE" value={Moment(this.props.piece.date_created, 'YYYY-MM-DD').year()} /> <DetailProperty label="DATE" value={Moment(piece.date_created, 'YYYY-MM-DD').year()} />
<hr/> <hr/>
</div> </div>
} }
subheader={ subheader={
<div className="ascribe-detail-header"> <div className="ascribe-detail-header">
<DetailProperty label={getLangText('REGISTREE')} value={ this.props.piece.user_registered } /> <DetailProperty label={getLangText('REGISTREE')} value={ piece.user_registered } />
<DetailProperty label={getLangText('ID')} value={ this.props.piece.bitcoin_id } ellipsis={true} /> <DetailProperty label={getLangText('ID')} value={ piece.bitcoin_id } ellipsis={true} />
<hr/> <hr/>
</div> </div>
}> }>
<WalletActionPanel <WalletActionPanel
piece={this.props.piece} piece={piece}
currentUser={this.props.currentUser} currentUser={currentUser}
loadPiece={this.props.loadPiece} loadPiece={loadPiece}
handleDeleteSuccess={this.props.handleDeleteSuccess} handleDeleteSuccess={handleDeleteSuccess}
submitButtonType={this.props.submitButtonType}/> submitButtonType={submitButtonType}/>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Loan History')} title={getLangText('Loan History')}
show={this.props.piece.loan_history && this.props.piece.loan_history.length > 0}> show={piece.loan_history && piece.loan_history.length > 0}>
<HistoryIterator <HistoryIterator
history={this.props.piece.loan_history}/> history={piece.loan_history}/>
</CollapsibleParagraph> </CollapsibleParagraph>
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Notes')} title={getLangText('Notes')}
show={!!(this.props.currentUser.username || this.props.piece.public_note)}> show={!!(currentUser.username || piece.public_note)}>
<Note <Note
id={() => {return {'id': this.props.piece.id}; }} id={() => {return {'id': piece.id}; }}
label={getLangText('Personal note (private)')} label={getLangText('Personal note (private)')}
defaultValue={this.props.piece.private_note || null} defaultValue={piece.private_note || null}
placeholder={getLangText('Enter your comments ...')} placeholder={getLangText('Enter your comments ...')}
editable={true} editable={true}
successMessage={getLangText('Private note saved')} successMessage={getLangText('Private note saved')}
url={ApiUrls.note_private_piece} url={ApiUrls.note_private_piece}
currentUser={this.props.currentUser}/> currentUser={currentUser}/>
</CollapsibleParagraph> </CollapsibleParagraph>
{children}
{this.props.children}
</Piece> </Piece>
); );
} } else {
else {
return ( return (
<div className="fullpage-spinner"> <div className="fullpage-spinner">
<AscribeSpinner color='dark-blue' size='lg' /> <AscribeSpinner color='dark-blue' size='lg' />

View File

@ -52,8 +52,9 @@ let CylandAccordionListItem = React.createClass({
}, },
handleSubmitSuccess(response) { handleSubmitSuccess(response) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
let notification = new GlobalNotificationModel(response.notification, 'success', 10000); let notification = new GlobalNotificationModel(response.notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);

View File

@ -40,7 +40,7 @@ let CylandPieceContainer = React.createClass({
getInitialState() { getInitialState() {
return mergeOptions( return mergeOptions(
PieceStore.getState(), PieceStore.getInitialState(),
UserStore.getState(), UserStore.getState(),
PieceListStore.getState() PieceListStore.getState()
); );
@ -51,14 +51,17 @@ let CylandPieceContainer = React.createClass({
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
PieceListStore.listen(this.onChange); PieceListStore.listen(this.onChange);
// Every time we enter the piece detail page, just reset the piece
// store as it will otherwise display wrong/old data once the user loads
// the piece detail a second time
PieceActions.updatePiece({});
this.loadPiece(); this.loadPiece();
}, },
// We need this for when the user clicks on a notification while being in another piece view
componentWillReceiveProps(nextProps) {
if (this.props.params.pieceId !== nextProps.params.pieceId) {
PieceActions.flushPiece();
this.loadPiece();
}
},
componentWillUnmount() { componentWillUnmount() {
PieceStore.unlisten(this.onChange); PieceStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange); UserStore.unlisten(this.onChange);
@ -70,31 +73,34 @@ let CylandPieceContainer = React.createClass({
}, },
loadPiece() { loadPiece() {
PieceActions.fetchOne(this.props.params.pieceId); PieceActions.fetchPiece(this.props.params.pieceId);
}, },
handleDeleteSuccess(response) { handleDeleteSuccess(response) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
// since we're deleting a piece, we just need to close // since we're deleting a piece, we just need to close
// all editions dialogs and not reload them // all editions dialogs and not reload them
EditionListActions.closeAllEditionLists(); EditionListActions.closeAllEditionLists();
EditionListActions.clearAllEditionSelections(); EditionListActions.clearAllEditionSelections();
let notification = new GlobalNotificationModel(response.notification, 'success'); const notification = new GlobalNotificationModel(response.notification, 'success');
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.history.pushState(null, '/collection'); this.history.push('/collection');
}, },
render() { render() {
if(this.state.piece && this.state.piece.id) { const { piece } = this.state;
setDocumentTitle([this.state.piece.artist_name, this.state.piece.title].join(', '));
if (piece.id) {
setDocumentTitle(`${piece.artist_name}, ${piece.title}`);
return ( return (
<WalletPieceContainer <WalletPieceContainer
piece={this.state.piece} piece={piece}
currentUser={this.state.currentUser} currentUser={this.state.currentUser}
loadPiece={this.loadPiece} loadPiece={this.loadPiece}
handleDeleteSuccess={this.handleDeleteSuccess} handleDeleteSuccess={this.handleDeleteSuccess}
@ -103,14 +109,13 @@ let CylandPieceContainer = React.createClass({
title={getLangText('Further Details')} title={getLangText('Further Details')}
defaultExpanded={true}> defaultExpanded={true}>
<CylandAdditionalDataForm <CylandAdditionalDataForm
piece={this.state.piece} piece={piece}
disabled={!this.state.piece.acl.acl_edit} disabled={!piece.acl.acl_edit}
isInline={true} /> isInline={true} />
</CollapsibleParagraph> </CollapsibleParagraph>
</WalletPieceContainer> </WalletPieceContainer>
); );
} } else {
else {
return ( return (
<div className="fullpage-spinner"> <div className="fullpage-spinner">
<AscribeSpinner color='dark-blue' size='lg' /> <AscribeSpinner color='dark-blue' size='lg' />

View File

@ -23,9 +23,10 @@ import { formSubmissionValidation } from '../../../../../ascribe_uploader/react_
let CylandAdditionalDataForm = React.createClass({ let CylandAdditionalDataForm = React.createClass({
propTypes: { propTypes: {
handleSuccess: React.PropTypes.func,
piece: React.PropTypes.object.isRequired, piece: React.PropTypes.object.isRequired,
disabled: React.PropTypes.bool, disabled: React.PropTypes.bool,
handleSuccess: React.PropTypes.func,
isInline: React.PropTypes.bool isInline: React.PropTypes.bool
}, },
@ -42,13 +43,13 @@ let CylandAdditionalDataForm = React.createClass({
}, },
handleSuccess() { handleSuccess() {
let notification = new GlobalNotificationModel(getLangText('Further details successfully updated'), 'success', 10000); const notification = new GlobalNotificationModel(getLangText('Further details successfully updated'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },
getFormData() { getFormData() {
let extradata = {}; const extradata = {};
let formRefs = this.refs.form.refs; const formRefs = this.refs.form.refs;
// Put additional fields in extra data object // Put additional fields in extra data object
Object Object
@ -71,10 +72,13 @@ let CylandAdditionalDataForm = React.createClass({
}, },
render() { render() {
let { piece, isInline, disabled, handleSuccess, location } = this.props; const { disabled, handleSuccess, isInline, piece } = this.props;
let buttons, spinner, heading;
if(!isInline) { let buttons;
let spinner;
let heading;
if (!isInline) {
buttons = ( buttons = (
<button <button
type="submit" type="submit"
@ -87,7 +91,7 @@ let CylandAdditionalDataForm = React.createClass({
spinner = ( spinner = (
<div className="modal-footer"> <div className="modal-footer">
<p className="pull-right"> <p className="pull-right">
<AscribeSpinner color='dark-blue' size='md'/> <AscribeSpinner color='dark-blue' size='md' />
</p> </p>
</div> </div>
); );
@ -101,13 +105,15 @@ let CylandAdditionalDataForm = React.createClass({
); );
} }
if(piece && piece.id) { if (piece.id) {
const { extra_data: extraData = {} } = piece;
return ( return (
<Form <Form
disabled={disabled} disabled={disabled}
className="ascribe-form-bordered" className="ascribe-form-bordered"
ref='form' ref='form'
url={requests.prepareUrl(ApiUrls.piece_extradata, {piece_id: piece.id})} url={requests.prepareUrl(ApiUrls.piece_extradata, { piece_id: piece.id })}
handleSuccess={handleSuccess || this.handleSuccess} handleSuccess={handleSuccess || this.handleSuccess}
getFormData={this.getFormData} getFormData={this.getFormData}
buttons={buttons} buttons={buttons}
@ -116,65 +122,66 @@ let CylandAdditionalDataForm = React.createClass({
<Property <Property
name='artist_bio' name='artist_bio'
label={getLangText('Artist Biography')} label={getLangText('Artist Biography')}
expanded={!disabled || !!piece.extra_data.artist_bio}> expanded={!disabled || !!extraData.artist_bio}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={piece.extra_data.artist_bio} defaultValue={extraData.artist_bio}
placeholder={getLangText('Enter the artist\'s biography...')}/> placeholder={getLangText('Enter the artist\'s biography...')} />
</Property> </Property>
<Property <Property
name='artist_contact_information' name='artist_contact_information'
label={getLangText('Artist Contact Information')} label={getLangText('Artist Contact Information')}
expanded={!disabled || !!piece.extra_data.artist_contact_information}> expanded={!disabled || !!extraData.artist_contact_information}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={piece.extra_data.artist_contact_information} convertLinks
placeholder={getLangText('Enter the artist\'s contact information...')}/> defaultValue={extraData.artist_contact_information}
placeholder={getLangText('Enter the artist\'s contact information...')} />
</Property> </Property>
<Property <Property
name='conceptual_overview' name='conceptual_overview'
label={getLangText('Conceptual Overview')} label={getLangText('Conceptual Overview')}
expanded={!disabled || !!piece.extra_data.conceptual_overview}> expanded={!disabled || !!extraData.conceptual_overview}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={piece.extra_data.conceptual_overview} defaultValue={extraData.conceptual_overview}
placeholder={getLangText('Enter a conceptual overview...')}/> placeholder={getLangText('Enter a conceptual overview...')} />
</Property> </Property>
<Property <Property
name='medium' name='medium'
label={getLangText('Medium (technical specifications)')} label={getLangText('Medium (technical specifications)')}
expanded={!disabled || !!piece.extra_data.medium}> expanded={!disabled || !!extraData.medium}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={piece.extra_data.medium} defaultValue={extraData.medium}
placeholder={getLangText('Enter the medium (and other technical specifications)...')}/> placeholder={getLangText('Enter the medium (and other technical specifications)...')} />
</Property> </Property>
<Property <Property
name='size_duration' name='size_duration'
label={getLangText('Size / Duration')} label={getLangText('Size / Duration')}
expanded={!disabled || !!piece.extra_data.size_duration}> expanded={!disabled || !!extraData.size_duration}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={piece.extra_data.size_duration} defaultValue={extraData.size_duration}
placeholder={getLangText('Enter the size / duration...')}/> placeholder={getLangText('Enter the size / duration...')} />
</Property> </Property>
<Property <Property
name='display_instructions' name='display_instructions'
label={getLangText('Display instructions')} label={getLangText('Display instructions')}
expanded={!disabled || !!piece.extra_data.display_instructions}> expanded={!disabled || !!extraData.display_instructions}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={piece.extra_data.display_instructions} defaultValue={extraData.display_instructions}
placeholder={getLangText('Enter the display instructions...')}/> placeholder={getLangText('Enter the display instructions...')} />
</Property> </Property>
<Property <Property
name='additional_details' name='additional_details'
label={getLangText('Additional details')} label={getLangText('Additional details')}
expanded={!disabled || !!piece.extra_data.additional_details}> expanded={!disabled || !!extraData.additional_details}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={piece.extra_data.additional_details} defaultValue={extraData.additional_details}
placeholder={getLangText('Enter additional details...')}/> placeholder={getLangText('Enter additional details...')} />
</Property> </Property>
<FurtherDetailsFileuploader <FurtherDetailsFileuploader
label={getLangText('Additional files (e.g. still images, pdf)')} label={getLangText('Additional files (e.g. still images, pdf)')}
@ -189,7 +196,7 @@ let CylandAdditionalDataForm = React.createClass({
} else { } else {
return ( return (
<div className="ascribe-loading-position"> <div className="ascribe-loading-position">
<AscribeSpinner color='dark-blue' size='md'/> <AscribeSpinner color='dark-blue' size='md' />
</div> </div>
); );
} }

View File

@ -49,7 +49,7 @@ let CylandLanding = React.createClass({
// if user is already logged in, redirect him to piece list // if user is already logged in, redirect him to piece list
if(this.state.currentUser && this.state.currentUser.email) { if(this.state.currentUser && this.state.currentUser.email) {
// FIXME: hack to redirect out of the dispatch cycle // FIXME: hack to redirect out of the dispatch cycle
window.setTimeout(() => this.history.replaceState(null, '/collection'), 0); window.setTimeout(() => this.history.replace('/collection'), 0);
} }
}, },

View File

@ -52,7 +52,7 @@ let CylandRegisterPiece = React.createClass({
return mergeOptions( return mergeOptions(
UserStore.getState(), UserStore.getState(),
PieceListStore.getState(), PieceListStore.getState(),
PieceStore.getState(), PieceStore.getInitialState(),
WhitelabelStore.getState(), WhitelabelStore.getState(),
{ {
step: 0 step: 0
@ -67,7 +67,7 @@ let CylandRegisterPiece = React.createClass({
UserActions.fetchCurrentUser(); UserActions.fetchCurrentUser();
WhitelabelActions.fetchWhitelabel(); WhitelabelActions.fetchWhitelabel();
let queryParams = this.props.location.query; const queryParams = this.props.location.query;
// Since every step of this register process is atomic, // Since every step of this register process is atomic,
// we may need to enter the process at step 1 or 2. // we may need to enter the process at step 1 or 2.
@ -76,8 +76,8 @@ let CylandRegisterPiece = React.createClass({
// //
// We're using 'in' here as we want to know if 'piece_id' is present in the url, // We're using 'in' here as we want to know if 'piece_id' is present in the url,
// we don't care about the value. // we don't care about the value.
if(queryParams && 'piece_id' in queryParams) { if ('piece_id' in queryParams) {
PieceActions.fetchOne(queryParams.piece_id); PieceActions.fetchPiece(queryParams.piece_id);
} }
}, },
@ -92,64 +92,50 @@ let CylandRegisterPiece = React.createClass({
this.setState(state); this.setState(state);
}, },
handleRegisterSuccess(response){ handleRegisterSuccess(response) {
this.refreshPieceList(); this.refreshPieceList();
// also start loading the piece for the next step // Also load the newly registered piece for the next step
if(response && response.piece) { if (response && response.piece) {
PieceActions.updatePiece({});
PieceActions.updatePiece(response.piece); PieceActions.updatePiece(response.piece);
} }
this.incrementStep(); this.nextSlide({ piece_id: response.piece.id });
this.refs.slidesContainer.nextSlide({ piece_id: response.piece.id });
}, },
handleAdditionalDataSuccess() { handleAdditionalDataSuccess() {
// We need to refetch the piece again after submitting the additional data // We need to refetch the piece again after submitting the additional data
// since we want it's otherData to be displayed when the user choses to click // since we want its otherData to be displayed when the user choses to click
// on the browsers back button. // on the browsers back button.
PieceActions.fetchOne(this.state.piece.id); PieceActions.fetchPiece(this.state.piece.id);
this.refreshPieceList(); this.refreshPieceList();
this.incrementStep(); this.nextSlide();
this.refs.slidesContainer.nextSlide();
}, },
handleLoanSuccess(response) { handleLoanSuccess(response) {
let notification = new GlobalNotificationModel(response.notification, 'success', 10000); const notification = new GlobalNotificationModel(response.notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.refreshPieceList(); this.refreshPieceList();
PieceActions.fetchOne(this.state.piece.id); this.history.push(`/pieces/${this.state.piece.id}`);
this.history.pushState(null, `/pieces/${this.state.piece.id}`);
}, },
nextSlide(queryParams) {
// We need to increase the step to lock the forms that are already filled out // We need to increase the step to lock the forms that are already filled out
incrementStep() {
// also increase step
let newStep = this.state.step + 1;
this.setState({ this.setState({
step: newStep step: this.state.step + 1
}); });
this.refs.slidesContainer.nextSlide(queryParams);
}, },
refreshPieceList() { refreshPieceList() {
PieceListActions.fetchPieceList( const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.page,
this.state.pageSize, PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
this.state.searchTerm,
this.state.orderBy,
this.state.orderAsc,
this.state.filterBy
);
}, },
render() { render() {
@ -157,8 +143,7 @@ let CylandRegisterPiece = React.createClass({
const { currentUser, piece, step, whitelabel } = this.state; const { currentUser, piece, step, whitelabel } = this.state;
const today = new Moment(); const today = new Moment();
const datetimeWhenWeAllWillBeFlyingCoolHoverboardsAndDinosaursWillLiveAgain = new Moment(); const datetimeWhenWeAllWillBeFlyingCoolHoverboardsAndDinosaursWillLiveAgain = new Moment().add(1000, 'years');
datetimeWhenWeAllWillBeFlyingCoolHoverboardsAndDinosaursWillLiveAgain.add(1000, 'years');
const loanHeading = getLangText('Loan to Cyland archive'); const loanHeading = getLangText('Loan to Cyland archive');
const loanButtons = ( const loanButtons = (
@ -201,7 +186,7 @@ let CylandRegisterPiece = React.createClass({
submitMessage={getLangText('Submit')} submitMessage={getLangText('Submit')}
isFineUploaderActive={true} isFineUploaderActive={true}
handleSuccess={this.handleRegisterSuccess} handleSuccess={this.handleRegisterSuccess}
location={location}/> location={location} />
</Col> </Col>
</Row> </Row>
</div> </div>

View File

@ -53,8 +53,9 @@ let IkonotvAccordionListItem = React.createClass({
}, },
handleSubmitSuccess(response) { handleSubmitSuccess(response) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
let notification = new GlobalNotificationModel(response.notification, 'success', 10000); let notification = new GlobalNotificationModel(response.notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);

View File

@ -106,28 +106,33 @@ let IkonotvContractNotifications = React.createClass({
handleConfirm() { handleConfirm() {
let contractAgreement = this.state.contractAgreementListNotifications[0].contract_agreement; let contractAgreement = this.state.contractAgreementListNotifications[0].contract_agreement;
OwnershipFetcher.confirmContractAgreement(contractAgreement).then( OwnershipFetcher
() => this.handleConfirmSuccess() .confirmContractAgreement(contractAgreement)
); .then(this.handleConfirmSuccess);
}, },
handleConfirmSuccess() { handleConfirmSuccess() {
let notification = new GlobalNotificationModel(getLangText('You have accepted the conditions'), 'success', 5000); let notification = new GlobalNotificationModel(getLangText('You have accepted the conditions'), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.history.pushState(null, '/collection');
// Flush contract notifications and refetch
NotificationActions.flushContractAgreementListNotifications();
NotificationActions.fetchContractAgreementListNotifications();
this.history.push('/collection');
}, },
handleDeny() { handleDeny() {
let contractAgreement = this.state.contractAgreementListNotifications[0].contract_agreement; let contractAgreement = this.state.contractAgreementListNotifications[0].contract_agreement;
OwnershipFetcher.denyContractAgreement(contractAgreement).then( OwnershipFetcher
() => this.handleDenySuccess() .denyContractAgreement(contractAgreement)
); .then(this.handleDenySuccess);
}, },
handleDenySuccess() { handleDenySuccess() {
let notification = new GlobalNotificationModel(getLangText('You have denied the conditions'), 'success', 5000); let notification = new GlobalNotificationModel(getLangText('You have denied the conditions'), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.history.pushState(null, '/collection'); this.history.push('/collection');
}, },
getCopyrightAssociationForm(){ getCopyrightAssociationForm(){

View File

@ -41,7 +41,7 @@ let IkonotvPieceContainer = React.createClass({
getInitialState() { getInitialState() {
return mergeOptions( return mergeOptions(
PieceStore.getState(), PieceStore.getInitialState(),
UserStore.getState(), UserStore.getState(),
PieceListStore.getState() PieceListStore.getState()
); );
@ -52,19 +52,14 @@ let IkonotvPieceContainer = React.createClass({
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
PieceListStore.listen(this.onChange); PieceListStore.listen(this.onChange);
// Every time we enter the piece detail page, just reset the piece
// store as it will otherwise display wrong/old data once the user loads
// the piece detail a second time
PieceActions.updatePiece({});
this.loadPiece(); this.loadPiece();
}, },
// We need this for when the user clicks on a notification while being in another piece view // We need this for when the user clicks on a notification while being in another piece view
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
if(this.props.params.pieceId !== nextProps.params.pieceId) { if (this.props.params.pieceId !== nextProps.params.pieceId) {
PieceActions.updatePiece({}); PieceActions.flushPiece();
PieceActions.fetchOne(nextProps.params.pieceId); this.loadPiece();
} }
}, },
@ -79,25 +74,28 @@ let IkonotvPieceContainer = React.createClass({
}, },
loadPiece() { loadPiece() {
PieceActions.fetchOne(this.props.params.pieceId); PieceActions.fetchPiece(this.props.params.pieceId);
}, },
handleDeleteSuccess(response) { handleDeleteSuccess(response) {
PieceListActions.fetchPieceList(this.state.page, this.state.pageSize, this.state.search, const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.orderBy, this.state.orderAsc, this.state.filterBy);
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
// since we're deleting a piece, we just need to close // since we're deleting a piece, we just need to close
// all editions dialogs and not reload them // all editions dialogs and not reload them
EditionListActions.closeAllEditionLists(); EditionListActions.closeAllEditionLists();
EditionListActions.clearAllEditionSelections(); EditionListActions.clearAllEditionSelections();
let notification = new GlobalNotificationModel(response.notification, 'success'); const notification = new GlobalNotificationModel(response.notification, 'success');
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.history.pushState(null, '/collection'); this.history.push('/collection');
}, },
render() { render() {
const { piece } = this.state;
let furtherDetails = ( let furtherDetails = (
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Further Details')} title={getLangText('Further Details')}
@ -106,28 +104,29 @@ let IkonotvPieceContainer = React.createClass({
</CollapsibleParagraph> </CollapsibleParagraph>
); );
if(this.state.piece.extra_data && Object.keys(this.state.piece.extra_data).length > 0 && this.state.piece.acl) { if (piece.extra_data && Object.keys(piece.extra_data).length && piece.acl) {
furtherDetails = ( furtherDetails = (
<CollapsibleParagraph <CollapsibleParagraph
title={getLangText('Further Details')} title={getLangText('Further Details')}
defaultExpanded={true}> defaultExpanded={true}>
<IkonotvArtistDetailsForm <IkonotvArtistDetailsForm
piece={this.state.piece} piece={piece}
isInline={true} isInline={true}
disabled={!this.state.piece.acl.acl_edit} /> disabled={!piece.acl.acl_edit} />
<IkonotvArtworkDetailsForm <IkonotvArtworkDetailsForm
piece={this.state.piece} piece={piece}
isInline={true} isInline={true}
disabled={!this.state.piece.acl.acl_edit} /> disabled={!piece.acl.acl_edit} />
</CollapsibleParagraph> </CollapsibleParagraph>
); );
} }
if(this.state.piece && this.state.piece.id) { if (piece.id) {
setDocumentTitle([this.state.piece.artist_name, this.state.piece.title].join(', ')); setDocumentTitle(`${piece.artist_name}, ${piece.title}`);
return ( return (
<WalletPieceContainer <WalletPieceContainer
piece={this.state.piece} piece={piece}
currentUser={this.state.currentUser} currentUser={this.state.currentUser}
loadPiece={this.loadPiece} loadPiece={this.loadPiece}
handleDeleteSuccess={this.handleDeleteSuccess} handleDeleteSuccess={this.handleDeleteSuccess}
@ -135,8 +134,7 @@ let IkonotvPieceContainer = React.createClass({
{furtherDetails} {furtherDetails}
</WalletPieceContainer> </WalletPieceContainer>
); );
} } else {
else {
return ( return (
<div className="fullpage-spinner"> <div className="fullpage-spinner">
<AscribeSpinner color='dark-blue' size='lg' /> <AscribeSpinner color='dark-blue' size='lg' />

View File

@ -20,11 +20,10 @@ import { getLangText } from '../../../../../../utils/lang_utils';
let IkonotvArtistDetailsForm = React.createClass({ let IkonotvArtistDetailsForm = React.createClass({
propTypes: { propTypes: {
handleSuccess: React.PropTypes.func,
piece: React.PropTypes.object.isRequired, piece: React.PropTypes.object.isRequired,
disabled: React.PropTypes.bool, disabled: React.PropTypes.bool,
handleSuccess: React.PropTypes.func,
isInline: React.PropTypes.bool isInline: React.PropTypes.bool
}, },
@ -35,8 +34,8 @@ let IkonotvArtistDetailsForm = React.createClass({
}, },
getFormData() { getFormData() {
let extradata = {}; const extradata = {};
let formRefs = this.refs.form.refs; const formRefs = this.refs.form.refs;
// Put additional fields in extra data object // Put additional fields in extra data object
Object Object
@ -53,21 +52,23 @@ let IkonotvArtistDetailsForm = React.createClass({
}, },
handleSuccess() { handleSuccess() {
let notification = new GlobalNotificationModel('Artist details successfully updated', 'success', 10000); const notification = new GlobalNotificationModel(getLangText('Artist details successfully updated'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },
render() { render() {
let buttons, spinner, heading; const { disabled, isInline, handleSuccess, piece } = this.props;
let { isInline, handleSuccess } = this.props;
let buttons;
let spinner;
let heading;
if(!isInline) { if (!isInline) {
buttons = ( buttons = (
<button <button
type="submit" type="submit"
className="btn btn-default btn-wide" className="btn btn-default btn-wide"
disabled={this.props.disabled}> disabled={disabled}>
{getLangText('Proceed to loan')} {getLangText('Proceed to loan')}
</button> </button>
); );
@ -75,7 +76,7 @@ let IkonotvArtistDetailsForm = React.createClass({
spinner = ( spinner = (
<div className="modal-footer"> <div className="modal-footer">
<p className="pull-right"> <p className="pull-right">
<AscribeSpinner color='dark-blue' size='md'/> <AscribeSpinner color='dark-blue' size='md' />
</p> </p>
</div> </div>
); );
@ -89,13 +90,15 @@ let IkonotvArtistDetailsForm = React.createClass({
); );
} }
if(this.props.piece && this.props.piece.id && this.props.piece.extra_data) { if (piece.id) {
const { extra_data: extraData = {} } = piece;
return ( return (
<Form <Form
disabled={this.props.disabled} disabled={disabled}
className="ascribe-form-bordered" className="ascribe-form-bordered"
ref='form' ref='form'
url={requests.prepareUrl(ApiUrls.piece_extradata, {piece_id: this.props.piece.id})} url={requests.prepareUrl(ApiUrls.piece_extradata, { piece_id: piece.id })}
handleSuccess={handleSuccess || this.handleSuccess} handleSuccess={handleSuccess || this.handleSuccess}
getFormData={this.getFormData} getFormData={this.getFormData}
buttons={buttons} buttons={buttons}
@ -104,39 +107,41 @@ let IkonotvArtistDetailsForm = React.createClass({
<Property <Property
name='artist_website' name='artist_website'
label={getLangText('Artist Website')} label={getLangText('Artist Website')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.artist_website}> expanded={!disabled || !!extraData.artist_website}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.artist_website} convertLinks
placeholder={getLangText('The artist\'s website if present...')}/> defaultValue={extraData.artist_website}
placeholder={getLangText('The artist\'s website if present...')} />
</Property> </Property>
<Property <Property
name='gallery_website' name='gallery_website'
label={getLangText('Website of related Gallery, Museum, etc.')} label={getLangText('Website of related Gallery, Museum, etc.')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.gallery_website}> expanded={!disabled || !!extraData.gallery_website}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.gallery_website} convertLinks
placeholder={getLangText('The website of any related Gallery or Museum')}/> defaultValue={extraData.gallery_website}
placeholder={getLangText('The website of any related Gallery or Museum')} />
</Property> </Property>
<Property <Property
name='additional_websites' name='additional_websites'
label={getLangText('Additional Websites/Publications/Museums/Galleries')} label={getLangText('Additional Websites/Publications/Museums/Galleries')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.additional_websites}> expanded={!disabled || !!extraData.additional_websites}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.additional_websites} convertLinks
placeholder={getLangText('Enter additional Websites/Publications if any')}/> defaultValue={extraData.additional_websites}
placeholder={getLangText('Enter additional Websites/Publications if any')} />
</Property> </Property>
<Property <Property
name='conceptual_overview' name='conceptual_overview'
label={getLangText('Short text about the Artist')} label={getLangText('Short text about the Artist')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.conceptual_overview}> expanded={!disabled || !!extraData.conceptual_overview}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.conceptual_overview} defaultValue={extraData.conceptual_overview}
placeholder={getLangText('Enter a short bio about the Artist')} placeholder={getLangText('Enter a short bio about the Artist')} />
/>
</Property> </Property>
</Form> </Form>
); );

View File

@ -20,11 +20,10 @@ import { getLangText } from '../../../../../../utils/lang_utils';
let IkonotvArtworkDetailsForm = React.createClass({ let IkonotvArtworkDetailsForm = React.createClass({
propTypes: { propTypes: {
handleSuccess: React.PropTypes.func,
piece: React.PropTypes.object.isRequired, piece: React.PropTypes.object.isRequired,
disabled: React.PropTypes.bool, disabled: React.PropTypes.bool,
handleSuccess: React.PropTypes.func,
isInline: React.PropTypes.bool isInline: React.PropTypes.bool
}, },
@ -35,8 +34,8 @@ let IkonotvArtworkDetailsForm = React.createClass({
}, },
getFormData() { getFormData() {
let extradata = {}; const extradata = {};
let formRefs = this.refs.form.refs; const formRefs = this.refs.form.refs;
// Put additional fields in extra data object // Put additional fields in extra data object
Object Object
@ -53,20 +52,23 @@ let IkonotvArtworkDetailsForm = React.createClass({
}, },
handleSuccess() { handleSuccess() {
let notification = new GlobalNotificationModel('Artwork details successfully updated', 'success', 10000); const notification = new GlobalNotificationModel(getLangText('Artwork details successfully updated'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
}, },
render() { render() {
let buttons, spinner, heading; const { disabled, isInline, handleSuccess, piece } = this.props;
let { isInline, handleSuccess } = this.props;
if(!isInline) { let buttons;
let spinner;
let heading;
if (!isInline) {
buttons = ( buttons = (
<button <button
type="submit" type="submit"
className="btn btn-default btn-wide" className="btn btn-default btn-wide"
disabled={this.props.disabled}> disabled={disabled}>
{getLangText('Proceed to artist details')} {getLangText('Proceed to artist details')}
</button> </button>
); );
@ -74,7 +76,7 @@ let IkonotvArtworkDetailsForm = React.createClass({
spinner = ( spinner = (
<div className="modal-footer"> <div className="modal-footer">
<p className="pull-right"> <p className="pull-right">
<AscribeSpinner color='dark-blue' size='md'/> <AscribeSpinner color='dark-blue' size='md' />
</p> </p>
</div> </div>
); );
@ -88,13 +90,15 @@ let IkonotvArtworkDetailsForm = React.createClass({
); );
} }
if(this.props.piece && this.props.piece.id && this.props.piece.extra_data) { if (piece.id && piece.extra_data) {
const { extra_data: extraData = {} } = piece;
return ( return (
<Form <Form
disabled={this.props.disabled} disabled={disabled}
className="ascribe-form-bordered" className="ascribe-form-bordered"
ref='form' ref='form'
url={requests.prepareUrl(ApiUrls.piece_extradata, {piece_id: this.props.piece.id})} url={requests.prepareUrl(ApiUrls.piece_extradata, { piece_id: piece.id })}
handleSuccess={handleSuccess || this.handleSuccess} handleSuccess={handleSuccess || this.handleSuccess}
getFormData={this.getFormData} getFormData={this.getFormData}
buttons={buttons} buttons={buttons}
@ -103,56 +107,56 @@ let IkonotvArtworkDetailsForm = React.createClass({
<Property <Property
name='medium' name='medium'
label={getLangText('Medium')} label={getLangText('Medium')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.medium}> expanded={!disabled || !!extraData.medium}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.medium} defaultValue={extraData.medium}
placeholder={getLangText('The medium of the file (i.e. photo, video, other, ...)')}/> placeholder={getLangText('The medium of the file (i.e. photo, video, other, ...)')} />
</Property> </Property>
<Property <Property
name='size_duration' name='size_duration'
label={getLangText('Size/Duration')} label={getLangText('Size/Duration')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.size_duration}> expanded={!disabled || !!extraData.size_duration}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.size_duration} defaultValue={extraData.size_duration}
placeholder={getLangText('Size in centimeters. Duration in minutes.')}/> placeholder={getLangText('Size in centimeters. Duration in minutes.')} />
</Property> </Property>
<Property <Property
name='copyright' name='copyright'
label={getLangText('Copyright')} label={getLangText('Copyright')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.copyright}> expanded={!disabled || !!extraData.copyright}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.copyright} defaultValue={extraData.copyright}
placeholder={getLangText('Which copyright is attached to this work?')}/> placeholder={getLangText('Which copyright is attached to this work?')} />
</Property> </Property>
<Property <Property
name='courtesy_of' name='courtesy_of'
label={getLangText('Courtesy of')} label={getLangText('Courtesy of')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.courtesy_of}> expanded={!disabled || !!extraData.courtesy_of}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.courtesy_of} defaultValue={extraData.courtesy_of}
placeholder={getLangText('The current owner of the artwork')}/> placeholder={getLangText('The current owner of the artwork')} />
</Property> </Property>
<Property <Property
name='copyright_of_photography' name='copyright_of_photography'
label={getLangText('Copyright of Photography')} label={getLangText('Copyright of Photography')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.copyright_of_photography}> expanded={!disabled || !!extraData.copyright_of_photography}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.copyright_of_photography} defaultValue={extraData.copyright_of_photography}
placeholder={getLangText('Who should be attributed for the photography?')}/> placeholder={getLangText('Who should be attributed for the photography?')} />
</Property> </Property>
<Property <Property
name='additional_details' name='additional_details'
label={getLangText('Additional Details about the artwork')} label={getLangText('Additional Details about the artwork')}
expanded={!this.props.disabled || !!this.props.piece.extra_data.additional_details}> expanded={!disabled || !!extraData.additional_details}>
<InputTextAreaToggable <InputTextAreaToggable
rows={1} rows={1}
defaultValue={this.props.piece.extra_data.additional_details} defaultValue={extraData.additional_details}
placeholder={getLangText('Insert artwork overview')}/> placeholder={getLangText('Insert artwork overview')} />
</Property> </Property>
</Form> </Form>
); );

View File

@ -1,15 +1,18 @@
'use strict'; 'use strict';
import React from 'react'; import React from 'react';
import PieceList from '../../../../piece_list'; import PieceList from '../../../../piece_list';
import UserActions from '../../../../../actions/user_actions'; import UserActions from '../../../../../actions/user_actions';
import UserStore from '../../../../../stores/user_store'; import UserStore from '../../../../../stores/user_store';
import NotificationStore from '../../../../../stores/notification_store';
import IkonotvAccordionListItem from './ikonotv_accordion_list/ikonotv_accordion_list_item'; import IkonotvAccordionListItem from './ikonotv_accordion_list/ikonotv_accordion_list_item';
import { getLangText } from '../../../../../utils/lang_utils';
import { setDocumentTitle } from '../../../../../utils/dom_utils'; import { setDocumentTitle } from '../../../../../utils/dom_utils';
import { mergeOptions } from '../../../../../utils/general_utils';
import { getLangText } from '../../../../../utils/lang_utils';
let IkonotvPieceList = React.createClass({ let IkonotvPieceList = React.createClass({
@ -18,20 +21,33 @@ let IkonotvPieceList = React.createClass({
}, },
getInitialState() { getInitialState() {
return UserStore.getState(); return mergeOptions(
NotificationStore.getState(),
UserStore.getState()
);
}, },
componentDidMount() { componentDidMount() {
NotificationStore.listen(this.onChange);
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
UserActions.fetchCurrentUser(); UserActions.fetchCurrentUser();
}, },
componentWillUnmount() { componentWillUnmount() {
NotificationStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange); UserStore.unlisten(this.onChange);
}, },
onChange(state) { onChange(state) {
this.setState(state); this.setState(state);
},
redirectIfNoContractNotifications() {
const { contractAgreementListNotifications } = this.state;
return contractAgreementListNotifications && !contractAgreementListNotifications.length;
}, },
render() { render() {
@ -41,6 +57,7 @@ let IkonotvPieceList = React.createClass({
<div> <div>
<PieceList <PieceList
redirectTo="/register_piece?slide_num=0" redirectTo="/register_piece?slide_num=0"
shouldRedirect={this.redirectIfNoContractNotifications}
accordionListItemType={IkonotvAccordionListItem} accordionListItemType={IkonotvAccordionListItem}
filterParams={[{ filterParams={[{
label: getLangText('Show works I have'), label: getLangText('Show works I have'),

View File

@ -49,7 +49,7 @@ let IkonotvRegisterPiece = React.createClass({
return mergeOptions( return mergeOptions(
UserStore.getState(), UserStore.getState(),
PieceListStore.getState(), PieceListStore.getState(),
PieceStore.getState(), PieceStore.getInitialState(),
WhitelabelStore.getState(), WhitelabelStore.getState(),
{ {
step: 0, step: 0,
@ -65,11 +65,7 @@ let IkonotvRegisterPiece = React.createClass({
UserActions.fetchCurrentUser(); UserActions.fetchCurrentUser();
WhitelabelActions.fetchWhitelabel(); WhitelabelActions.fetchWhitelabel();
// Before we load the new piece, we reset the piece store to delete old data that we do const queryParams = this.props.location.query;
// not want to display to the user.
PieceActions.updatePiece({});
let queryParams = this.props.location.query;
// Since every step of this register process is atomic, // Since every step of this register process is atomic,
// we may need to enter the process at step 1 or 2. // we may need to enter the process at step 1 or 2.
@ -78,8 +74,8 @@ let IkonotvRegisterPiece = React.createClass({
// //
// We're using 'in' here as we want to know if 'piece_id' is present in the url, // We're using 'in' here as we want to know if 'piece_id' is present in the url,
// we don't care about the value. // we don't care about the value.
if (queryParams && 'piece_id' in queryParams) { if ('piece_id' in queryParams) {
PieceActions.fetchOne(queryParams.piece_id); PieceActions.fetchPiece(queryParams.piece_id);
} }
}, },
@ -95,72 +91,62 @@ let IkonotvRegisterPiece = React.createClass({
}, },
handleRegisterSuccess(response){ handleRegisterSuccess(response) {
this.refreshPieceList(); this.refreshPieceList();
// also start loading the piece for the next step // Also load the newly registered piece for the next step
if(response && response.piece) { if (response && response.piece) {
PieceActions.updatePiece(response.piece); PieceActions.updatePiece(response.piece);
} }
if (!this.canSubmit()) { if (!this.canSubmit()) {
this.history.pushState(null, '/collection'); this.history.push('/collection');
} } else {
else { this.nextSlide({ piece_id: response.piece.id });
this.incrementStep();
this.refs.slidesContainer.nextSlide();
} }
}, },
handleAdditionalDataSuccess() { handleAdditionalDataSuccess() {
// We need to refetch the piece again after submitting the additional data // We need to refetch the piece again after submitting the additional data
// since we want it's otherData to be displayed when the user choses to click // since we want it's otherData to be displayed when the user choses to click
// on the browsers back button. // on the browsers back button.
PieceActions.fetchOne(this.state.piece.id); PieceActions.fetchPiece(this.state.piece.id);
this.refreshPieceList(); this.refreshPieceList();
this.incrementStep(); this.nextSlide();
this.refs.slidesContainer.nextSlide();
}, },
handleLoanSuccess(response) { handleLoanSuccess(response) {
this.setState({ pageExitWarning: null }); this.setState({ pageExitWarning: null });
let notification = new GlobalNotificationModel(response.notification, 'success', 10000); const notification = new GlobalNotificationModel(response.notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification); GlobalNotificationActions.appendGlobalNotification(notification);
this.refreshPieceList(); this.refreshPieceList();
PieceActions.fetchOne(this.state.piece.id); this.history.push(`/pieces/${this.state.piece.id}`);
this.history.pushState(null, `/pieces/${this.state.piece.id}`);
}, },
nextSlide(queryParams) {
// We need to increase the step to lock the forms that are already filled out // We need to increase the step to lock the forms that are already filled out
incrementStep() {
// also increase step
let newStep = this.state.step + 1;
this.setState({ this.setState({
step: newStep step: this.state.step + 1
}); });
this.refs.slidesContainer.nextSlide(queryParams);
}, },
refreshPieceList() { refreshPieceList() {
PieceListActions.fetchPieceList( const { filterBy, orderAsc, orderBy, page, pageSize, search } = this.state;
this.state.page,
this.state.pageSize, PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
this.state.searchTerm,
this.state.orderBy,
this.state.orderAsc,
this.state.filterBy
);
}, },
canSubmit() { canSubmit() {
let currentUser = this.state.currentUser; let currentUser = this.state.currentUser;
let whitelabel = this.state.whitelabel; let whitelabel = this.state.whitelabel;
return currentUser && currentUser.acl && currentUser.acl.acl_wallet_submit && whitelabel && whitelabel.user; return currentUser.acl && currentUser.acl.acl_wallet_submit && whitelabel.user;
}, },
getSlideArtistDetails() { getSlideArtistDetails() {
@ -171,13 +157,14 @@ let IkonotvRegisterPiece = React.createClass({
<Col xs={12} sm={10} md={8} smOffset={1} mdOffset={2}> <Col xs={12} sm={10} md={8} smOffset={1} mdOffset={2}>
<IkonotvArtistDetailsForm <IkonotvArtistDetailsForm
handleSuccess={this.handleAdditionalDataSuccess} handleSuccess={this.handleAdditionalDataSuccess}
piece={this.state.piece}/> piece={this.state.piece} />
</Col> </Col>
</Row> </Row>
</div> </div>
); );
} } else {
return null; return null;
}
}, },
getSlideArtworkDetails() { getSlideArtworkDetails() {
@ -188,21 +175,21 @@ let IkonotvRegisterPiece = React.createClass({
<Col xs={12} sm={10} md={8} smOffset={1} mdOffset={2}> <Col xs={12} sm={10} md={8} smOffset={1} mdOffset={2}>
<IkonotvArtworkDetailsForm <IkonotvArtworkDetailsForm
handleSuccess={this.handleAdditionalDataSuccess} handleSuccess={this.handleAdditionalDataSuccess}
piece={this.state.piece}/> piece={this.state.piece} />
</Col> </Col>
</Row> </Row>
</div> </div>
); );
} } else {
return null; return null;
}
}, },
getSlideLoan() { getSlideLoan() {
if (this.canSubmit()) { if (this.canSubmit()) {
const { piece, whitelabel } = this.state; const { piece, whitelabel } = this.state;
let today = new Moment(); const today = new Moment();
let endDate = new Moment(); const endDate = new Moment().add(2, 'years');
endDate.add(2, 'years');
return ( return (
<div data-slide-title={getLangText('Loan')}> <div data-slide-title={getLangText('Loan')}>
@ -225,8 +212,9 @@ let IkonotvRegisterPiece = React.createClass({
</Row> </Row>
</div> </div>
); );
} } else {
return null; return null;
}
}, },
render() { render() {
@ -252,7 +240,7 @@ let IkonotvRegisterPiece = React.createClass({
submitMessage={getLangText('Register')} submitMessage={getLangText('Register')}
isFineUploaderActive={true} isFineUploaderActive={true}
handleSuccess={this.handleRegisterSuccess} handleSuccess={this.handleRegisterSuccess}
location={this.props.location}/> location={this.props.location} />
</Col> </Col>
</Row> </Row>
</div> </div>

View File

@ -30,7 +30,7 @@ let MarketAclButtonList = React.createClass({
componentDidMount() { componentDidMount() {
UserStore.listen(this.onChange); UserStore.listen(this.onChange);
UserActions.fetchCurrentUser(); UserActions.fetchCurrentUser.defer();
}, },
componentWillUnmount() { componentWillUnmount() {

View File

@ -3,6 +3,11 @@
import React from 'react'; import React from 'react';
import classNames from 'classnames'; import classNames from 'classnames';
import EditionActions from '../../../../../../actions/edition_actions';
import WhitelabelActions from '../../../../../../actions/whitelabel_actions';
import WhitelabelStore from '../../../../../../stores/whitelabel_store';
import MarketAdditionalDataForm from '../market_forms/market_additional_data_form'; import MarketAdditionalDataForm from '../market_forms/market_additional_data_form';
import AclFormFactory from '../../../../../ascribe_forms/acl_form_factory'; import AclFormFactory from '../../../../../ascribe_forms/acl_form_factory';
@ -11,10 +16,7 @@ import ConsignForm from '../../../../../ascribe_forms/form_consign';
import ModalWrapper from '../../../../../ascribe_modal/modal_wrapper'; import ModalWrapper from '../../../../../ascribe_modal/modal_wrapper';
import AclProxy from '../../../../../acl_proxy'; import AclProxy from '../../../../../acl_proxy';
import AscribeSpinner from '../../../../../ascribe_spinner';
import PieceActions from '../../../../../../actions/piece_actions';
import WhitelabelActions from '../../../../../../actions/whitelabel_actions';
import WhitelabelStore from '../../../../../../stores/whitelabel_store';
import ApiUrls from '../../../../../../constants/api_urls'; import ApiUrls from '../../../../../../constants/api_urls';
@ -26,8 +28,9 @@ let MarketSubmitButton = React.createClass({
availableAcls: React.PropTypes.object.isRequired, availableAcls: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object, currentUser: React.PropTypes.object,
editions: React.PropTypes.array.isRequired, editions: React.PropTypes.array.isRequired,
handleSuccess: React.PropTypes.func.isRequired,
className: React.PropTypes.string, className: React.PropTypes.string,
handleSuccess: React.PropTypes.func
}, },
getInitialState() { getInitialState() {
@ -50,22 +53,21 @@ let MarketSubmitButton = React.createClass({
canEditionBeSubmitted(edition) { canEditionBeSubmitted(edition) {
if (edition && edition.extra_data && edition.other_data) { if (edition && edition.extra_data && edition.other_data) {
const { extra_data, other_data } = edition; const {
extra_data: {
artist_bio: artistBio,
display_instructions: displayInstructions,
technology_details: technologyDetails,
work_description: workDescription
},
other_data: otherData } = edition;
if (extra_data.artist_bio && extra_data.work_description && return artistBio && displayInstructions && technologyDetails && workDescription && otherData.length;
extra_data.technology_details && extra_data.display_instructions &&
other_data.length > 0) {
return true;
}
} }
return false; return false;
}, },
getFormDataId() {
return getAclFormDataId(false, this.props.editions);
},
getAggregateEditionDetails() { getAggregateEditionDetails() {
const { editions } = this.props; const { editions } = this.props;
@ -82,13 +84,20 @@ let MarketSubmitButton = React.createClass({
}); });
}, },
handleAdditionalDataSuccess(pieceId) { getFormDataId() {
// Fetch newly updated piece to update the views return getAclFormDataId(false, this.props.editions);
PieceActions.fetchOne(pieceId); },
handleAdditionalDataSuccess() {
this.refs.consignModal.show(); this.refs.consignModal.show();
}, },
refreshEdition() {
if (this.props.editions.length === 1) {
EditionActions.fetchEdition(this.props.editions[0].bitcoin_id);
}
},
render() { render() {
const { availableAcls, currentUser, className, editions, handleSuccess } = this.props; const { availableAcls, currentUser, className, editions, handleSuccess } = this.props;
const { whitelabel: { name: whitelabelName = 'Market', user: whitelabelAdminEmail } } = this.state; const { whitelabel: { name: whitelabelName = 'Market', user: whitelabelAdminEmail } } = this.state;
@ -101,6 +110,10 @@ let MarketSubmitButton = React.createClass({
senderName: currentUser.username senderName: currentUser.username
}); });
// If only a single piece is selected, all the edition's extra_data and other_data will
// be the same, so we just take the first edition's
const { extra_data: extraData, other_data: otherData } = solePieceId ? editions[0] : {};
const triggerButton = ( const triggerButton = (
<button className={classNames('btn', 'btn-default', 'btn-sm', className)}> <button className={classNames('btn', 'btn-default', 'btn-sm', className)}>
{getLangText('CONSIGN TO %s', whitelabelName.toUpperCase())} {getLangText('CONSIGN TO %s', whitelabelName.toUpperCase())}
@ -126,16 +139,25 @@ let MarketSubmitButton = React.createClass({
aclName='acl_consign'> aclName='acl_consign'>
<ModalWrapper <ModalWrapper
trigger={triggerButton} trigger={triggerButton}
handleSuccess={this.handleAdditionalDataSuccess.bind(this, solePieceId)} handleSuccess={this.handleAdditionalDataSuccess}
title={getLangText('Add additional information')}> title={getLangText('Add additional information')}>
<MarketAdditionalDataForm <MarketAdditionalDataForm
extraData={extraData}
otherData={otherData}
pieceId={solePieceId} pieceId={solePieceId}
submitLabel={getLangText('Continue to consignment')} /> submitLabel={getLangText('Continue to consignment')} />
</ModalWrapper> </ModalWrapper>
<ModalWrapper <ModalWrapper
ref="consignModal" ref="consignModal"
handleSuccess={handleSuccess} handleCancel={this.refreshEdition}
handleSuccess={(...params) => {
if (typeof handleSuccess === 'function') {
handleSuccess(...params);
}
this.refreshEdition();
}}
title={getLangText('Consign artwork')}> title={getLangText('Consign artwork')}>
{consignForm} {consignForm}
</ModalWrapper> </ModalWrapper>

View File

@ -6,8 +6,12 @@ import MarketAdditionalDataForm from '../market_forms/market_additional_data_for
let MarketFurtherDetails = React.createClass({ let MarketFurtherDetails = React.createClass({
propTypes: { propTypes: {
pieceId: React.PropTypes.number, pieceId: React.PropTypes.number.isRequired,
editable: React.PropTypes.bool,
extraData: React.PropTypes.object,
handleSuccess: React.PropTypes.func, handleSuccess: React.PropTypes.func,
otherData: React.PropTypes.arrayOf(React.PropTypes.object)
}, },
render() { render() {

Some files were not shown because too many files have changed in this diff Show More