var DBG = DBG || false;
var DBG1 = true;
if (!HTML_ID) throw "Missing HTML_ID"
if (!URL_BASE) throw "Missing URL_BASE"
if (!URL_SEARCH_TABLE_LIST) throw "Missing URL_SEARCH_TABLE_LIST"
if (!URL_SEARCH_USER_LIST) throw "Missing URL_SEARCH_USER_LIST"
if (!URL_FETCH_INFO) throw "Missing URL_FETCH_INFO"
if (!CHANGE_OWNER_POST_TASK_NAME) throw "Missing CHANGE_OWNER_POST_TASK_NAME"
var SELECTED_TABLE_ID = SELECTED_TABLE_ID || null
var SELECTED_TABLE_INFO = SELECTED_TABLE_INFO || null
var SELECTED_FROM_OWNER_ID = SELECTED_FROM_OWNER_ID || null
var SELECTED_FROM_OWNER_INFO = SELECTED_FROM_OWNER_INFO || null
var SELECTED_TO_OWNER_ID = SELECTED_TO_OWNER_ID || null
var SELECTED_TO_OWNER_INFO = SELECTED_TO_OWNER_INFO || null
if (!global.fetch) throw "Missing fetch";
if (!global.p5VendorJs) throw "Missing p5VendorJs";
if (!global.p5VendorJs.Typeahead) throw "Missing Typeahead";
if (!global.p5VendorJs.AsyncTypeahead) throw "Missing AsyncTypeahead";
var createReactClass = global.p5VendorJs.createReactClass;
var h = global.p5VendorJs.React.createElement;
var React = global.p5VendorJs.React;
var ReactDOM = global.p5VendorJs.ReactDOM;
var Redux = global.p5VendorJs.Redux;
var ReduxThunk = global.p5VendorJs.ReduxThunk;
var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
var Typeahead = global.p5VendorJs.Typeahead;
var AsyncTypeahead = window.p5VendorJs.AsyncTypeahead;
function makeJsonRequest(url, props) {
return global.fetch(url, {
method: 'POST',
header: { 'contentType': 'applications/json' },
credentials: 'same-origin',
body: JSON.stringify(props.body)
})
.then(function (response) {
return response.text();
})
.then(function (responseText) {
try {
return JSON.parse(responseText);
} catch (e) {
throw responseText;
}
})
.then(function (result) {
DBG1 && console.log('DBG:makeJsonRequest: result', result);
if (result.type == 'success') {
return result.body;
}
})
}
function filterByLabelHelper(listItem, node) { // previous: filterByHelper
// DBG && console.log("DBG:filterByLabelHelper", { listItem, node })
var query = (node && node.text) ? node.text : '';
var label = listItem.label.toLowerCase();
var words = (
(query.indexOf(' ') > 0) ? query.split(' ') : [ query ]
).map(function (word) { return word.trim().replace(/^[0]+/g, '').toLowerCase(); })
.filter(function (word) { return word.length > 2; });
var foundWords = words.filter(function (word) {
return (label.indexOf(word) > -1);
})
return (foundWords.length === words.length);
}
function filterByAllHelper(listItem, node) {
// DBG && console.log("DBG:filterByAllHelper", { listItem, node })
var query = (node && node.text) ? node.text : '';
var label = listItem.label.toLowerCase();
var id = listItem.id.toLowerCase();
var words = (
(query.indexOf(' ') > 0) ? query.split(' ') : [ query ]
).map(function (word) { return word.trim().replace(/^[0]+/g, '').toLowerCase(); })
.filter(function (word) { return word.length > 2; });
var foundWords = words.filter(function (word) {
return (label.indexOf(word) > -1 || id.indexOf(word) > -1);
})
return (foundWords.length === words.length);
}
var p5UI__ChangeOwner_SearchTableWidget = createReactClass({
getInitialState: function () {
return {
isSearching: false,
options: this.props.selected || [],
}
},
handleSearch: function (query) {
this.setState({ isSearching: true });
var _setState = this.setState.bind(this);
makeJsonRequest(URL_SEARCH_TABLE_LIST, {
body: {
query: query,
}
})
.then(function (responseBody) {
var items = (responseBody && responseBody.items && responseBody.items.length) ? responseBody.items : []
if (!items.length) p5UI__notifyAjaxCallback({ type: 'warning', msg: "Brak danych pasujących do kryteriów wyszukiwania" });
DBG1 && console.log('items fetched:', items);
_setState({ isSearching: false, options: items });
})
.catch(function (error) {
DBG1 && console.log('request failed', error);
})
},
render: function () {
DBG1 && console.log("DBG:ChangeOwner:SearchTable:render", { props: this.props, state: this.state });
return h('div', {}, [
h(AsyncTypeahead, {
isLoading: this.state.isSearching,
allowNew: false,
multiple: false,
options: this.state.options || [],
selected: this.props.selected || [],
labelKey: "label",
emptyLabel: "Brak danych pasujących do kryteriów wyszukiwania",
searchText: "Wyszukiwanie...",
// labelKey: function (option) {
// return [
// option.nazwa.replace('"', ''),
// option.nip,
// option.krs,
// option.regon,
// option.S_miejscowosc,
// ].join(' ')
// },
minLength: 3,
onSearch: this.handleSearch,
placeholder: "Wyszukaj...",
autoFocus: false,
filterBy: filterByLabelHelper,
renderMenuItemChildren: function (option, props) {
return h(p5UI__ChangeOwner_SearchTableItem, { key: option.id, data: option });
},
onChange: this.props.onChange,
})
])
}
});
var p5UI__ChangeOwner_SearchTableItem = createReactClass({
// this.props: { key: option.ID, baza: selectedBaza, data: option }
render: function () {
return h('div', {}, [
h('em', {}, "[" + this.props.data.id + "]"),
" ",
this.props.data.label,
]);
}
});
var p5UI__ChangeOwner_SearchUserWidget = createReactClass({
getInitialState: function () {
return {
isSearching: false,
options: (this.props.selected && this.props.selected.length > 0) ? this.props.selected : [],
}
},
handleSearch: function (query) {
this.setState({ isSearching: true });
var _setState = this.setState.bind(this);
makeJsonRequest(URL_SEARCH_USER_LIST, {
body: {
id_table: this.props.id_table,
query: query,
}
})
.then(function (responseBody) {
var items = (responseBody && responseBody.items && responseBody.items.length) ? responseBody.items : []
if (!items.length) p5UI__notifyAjaxCallback({ type: 'warning', msg: "Brak danych pasujących do kryteriów wyszukiwania" });
DBG1 && console.log('items fetched:', items);
_setState({ isSearching: false, options: items });
})
.catch(function (error) {
DBG1 && console.log('request failed', error);
})
},
render: function () {
DBG1 && console.log("DBG:ChangeOwner:SearchUser:render", { props: this.props, state: this.state });
return h('div', {}, [
h(AsyncTypeahead, {
isLoading: this.state.isSearching,
allowNew: false,
multiple: false,
options: this.state.options,
selected: this.props.selected || [],
labelKey: "label",
emptyLabel: "Brak danych pasujących do kryteriów wyszukiwania",
searchText: "Wyszukiwanie...",
// labelKey: function (option) {
// return [
// option.nazwa.replace('"', ''),
// option.nip,
// option.krs,
// option.regon,
// option.S_miejscowosc,
// ].join(' ')
// },
minLength: 3,
onSearch: this.handleSearch,
placeholder: "Wyszukaj...",
autoFocus: false,
filterBy: filterByAllHelper,
renderMenuItemChildren: function (option, props) {
return h(p5UI__ChangeOwner_SearchUserItem, { key: option.id, data: option });
},
onChange: this.props.onChange,
})
])
}
});
var p5UI__ChangeOwner_SearchUserItem = createReactClass({
// this.props: { key: option.ID, baza: selectedBaza, data: option }
render: function () {
return h('div', {}, [
h('em', {}, "[" + this.props.data.id + "]"),
" ",
this.props.data.label,
]);
}
});
var p5UI__ChangeOwnerWidget = createReactClass({
getInitialState: function () {
return {
selectedTableID: SELECTED_TABLE_ID,
selectedFromOwnerLogin: SELECTED_FROM_OWNER_ID,
selectedToOwnerLogin: SELECTED_TO_OWNER_ID,
selectedTableInfo: SELECTED_TABLE_INFO,
selectedFromOwnerInfo: SELECTED_FROM_OWNER_INFO,
selectedToOwnerInfo: SELECTED_TO_OWNER_INFO,
isSearchingInfo: false,
info: null,
}
},
componentDidMount: function () {
if (this.state.selectedTableID > 0) {
this.fetchInfo()
}
},
makeUrl: function (args) {
var queryArgs = Object.assign({
id_table: this.state.selectedTableID,
id_from: this.state.selectedFromOwnerLogin,
id_to: this.state.selectedToOwnerLogin,
}, args);
return [ URL_BASE ].concat(
Object.keys(queryArgs).reduce(function (ret, argName) {
if (!queryArgs[argName]) return ret;
ret.push(argName + '=' + queryArgs[argName])
return ret;
}, [])
).join("&")
},
handleChangeTableID: function (selected) {
DBG1 && console.log("DBG:ChangeOwner:handleChangeTableID", { selected })
var tableID = (selected.length > 0) ? selected[0].id : ''
this.setState({
selectedTableID: tableID,
selectedTableInfo: (selected.length > 0) ? [ selected[0] ] : null,
})
if (global.history && global.history.pushState) history.pushState({}, global.document.title, this.makeUrl({ id_table: tableID }));
},
handleChangeFromOwnerID: function (selected) {
DBG1 && console.log("DBG:ChangeOwner:handleChangeFromOwnerID", { selected })
var fromLogin = (selected.length > 0) ? selected[0].id : ''
// if (global.history && global.history.pushState) history.pushState({}, global.document.title, this.makeUrl({ id_from: fromLogin }));
this.setState({
selectedFromOwnerLogin: fromLogin,
selectedFromOwnerInfo: (selected.length > 0) ? [ selected[0] ] : null,
}, (function () {
if (global.history && global.history.pushState) history.pushState({}, global.document.title, this.makeUrl());
this.fetchInfo()
}).bind(this))
},
handleChangeToOwnerID: function (selected) {
DBG1 && console.log("DBG:ChangeOwner:handleChangeToOwnerID", { selected })
var toLogin = (selected.length > 0) ? selected[0].id : ''
this.setState({
selectedToOwnerLogin: toLogin,
selectedToOwnerInfo: (selected.length > 0) ? [ selected[0] ] : null,
}, (function () {
if (global.history && global.history.pushState) history.pushState({}, global.document.title, this.makeUrl());
this.fetchInfo()
}).bind(this))
},
fetchInfo: function () {
DBG1 && console.log("TODO:ChangeOwner:fetchInfo", { state: this.state })
// TODO: fetch info if id_table, and id_from, optional id_to
// TODO: handle race condition, skip old responses
this.setState({ isSearchingInfo: true });
var _setState = this.setState.bind(this);
makeJsonRequest(URL_FETCH_INFO, {
body: {
id_table: this.state.selectedTableID,
id_from: this.state.selectedFromOwnerLogin,
id_to: this.state.selectedToOwnerLogin,
}
})
.then(function (info) {
// if (!info.length) p5UI__notifyAjaxCallback({ type: 'warning', msg: "Brak danych pasujących do kryteriów wyszukiwania" });
DBG1 && console.log('DBG:ChangeOwner:handleChangeTableID info fetched:', info);
_setState({ isSearchingInfo: false, info: info });
})
.catch(function (error) {
DBG1 && console.log('DBG:ChangeOwner:handleChangeTableID request failed', error);
})
},
renderInfo: function () {
if (!this.state.info) return null;
if (!this.state.selectedTableID) return null;
if (!this.state.selectedFromOwnerLogin) return null;
if (!this.state.selectedToOwnerLogin) return null;
if (this.state.info && this.state.info.error_missing_owner_field) {
return h('div', { className: "alert alert-danger" }, "Brak pola Osoba odpowiedzialana w wybranej tabeli");
}
if (this.state.info && this.state.info.errors && this.state.info.errors.length) {
return h('div', {}, this.state.info.errors.map(function (err) {
return h('div', { className: "alert alert-danger" }, err);
}));
}
// "fromInfo": {
// "id": "wolczynskit",
// "name": "Tomasz Wólczyński",
// "type": "Pracownik",
// "status": "NORMAL",
// "total": "1793"
// },
// "toInfo": {
// "id": "michal.podejko",
// "name": "Michał Podejko",
// "type": "Pracownik",
// "status": "NORMAL",
// "total": "5940"
// },
var fromInfo = this.state.info.fromInfo
var toInfo = this.state.info.toInfo
var totalToUpdate = fromInfo.total || 0
return h('div', {}, [
h('table', { style: { width: "100%" } }, [
h('tbody', {}, [
h('tr', {}, [
h('td', { style: { width: "5%" } }, ""),
h('td', { style: { width: "40%" } }, [
(fromInfo) ? this.renderOwnerInfo(fromInfo) : h('div', { className: "alert alert-warning" }, "Brak danych"),
]),
h('td', {}, ""),
h('td', { style: { width: "40%" } }, [
(toInfo) ? this.renderOwnerInfo(toInfo) : h('div', { className: "alert alert-warning" }, "Brak danych"),
]),
])
])
]),
(totalToUpdate)
? h('form', { method: "post", style: { textAlign: "center" } }, [
h('input', { type: "hidden", name: "id_table", value: this.state.selectedTableID }),
h('input', { type: "hidden", name: "id_from", value: this.state.selectedFromOwnerLogin }),
h('input', { type: "hidden", name: "id_to", value: this.state.selectedToOwnerLogin }),
h('input', { type: "hidden", name: "_postTask", value: CHANGE_OWNER_POST_TASK_NAME }),
h('button', { className: "btn btn-lg btn-primary" }, "Zmień " + totalToUpdate + " rekordów"),
])
: null
,
// h('pre', {}, [
// JSON.stringify(this.state.info, null, "\t")
// ]),
]);
},
renderOwnerInfo: function (userInfo) {
return h('div', {}, [
h('p', {}, [
h('em', {}, "[" + userInfo.id + "]"),
" ",
h('span', {}, userInfo.name),
h('br'),
h('span', {}, "Status: " + userInfo.status),
h('br'),
h('span', {}, "Typ: " + userInfo.type),
]),
h('p', {}, [
h('span', {}, "Odnaleziono " + userInfo.total + " rekordów"),
]),
]);
},
render: function () {
DBG1 && console.log("DBG:ChangeOwner:render", { props: this.props, state: this.state });
return h('form', { method: "get", style: { fontSize: "14px", lineHeight: "2em" } }, [
h('input', { type: "hidden", name: "_route", value: "UrlAction_ChangeOwner" }),
h('input', { type: "hidden", name: "id_table", value: this.state.selectedTableID }),
h('input', { type: "hidden", name: "id_from", value: this.state.selectedFromOwnerLogin }),
h('input', { type: "hidden", name: "id_to", value: this.state.selectedToOwnerLogin }),
h('table', { style: { width: "100%", margin: "12px 0" } }, [
h('tbody', {}, [
h('tr', {}, [
h('td', { style: { width: "5%" } }, [
"Tabela: ",
]),
h('td', {}, [
h(p5UI__ChangeOwner_SearchTableWidget, {
selected: this.state.selectedTableInfo,
onChange: this.handleChangeTableID,
})
]),
h('td', {}, [
h('a', {
'title': "Usuń zaznaczenie",
'href': URL_BASE,
'class': "btn btn-link",
}, "usuń"),
]),
]),
]),
]),
(this.state.selectedTableID > 0 && this.state.selectedTableInfo.length > 0) && h(React.Fragment, {}, [
h('p', {}, [
"Zmień osobę odpowiedzialną w tabeli ",
h('em', {}, "[" + this.state.selectedTableID + "]"),
" " + this.state.selectedTableInfo[0].label
]),
h('table', { style: { width: "100%", margin: "12px 0" } }, [
h('tbody', {}, [
h('tr', {}, [
h('td', { style: { width: "5%", textAlign: "right", paddingRight: "3px" } }, [
"z: ",
]),
h('td', { style: { width: "40%" } }, [
h(p5UI__ChangeOwner_SearchUserWidget, {
id_table: this.state.selectedTableID,
selected: this.state.selectedFromOwnerInfo,
onChange: this.handleChangeFromOwnerID,
})
]),
h('td', {}, ""),
h('td', { style: { width: "5%", textAlign: "right", paddingRight: "3px" } }, [
"na: ",
]),
h('td', { style: { width: "40%" } }, [
h(p5UI__ChangeOwner_SearchUserWidget, {
id_table: this.state.selectedTableID,
selected: this.state.selectedToOwnerInfo,
onChange: this.handleChangeToOwnerID,
})
]),
]),
]),
]),
(this.state.isSearchingInfo)
? h('div', {}, [
"Pobieranie informacji ..."
])
: this.renderInfo()
,
]),
]);
}
})
ReactDOM.render(
h(p5UI__ChangeOwnerWidget, {
// store: createStoreWithThunkMiddleware(NetworkGraph.store),
// storeActions: NetworkGraph.createActions(),
}),
document.getElementById(HTML_ID)
);