Commit 589f75df authored by Tristan Cavelier's avatar Tristan Cavelier

Merge branch 'erp5storage'

parents c844e2f1 0e46db8c
...@@ -6,6 +6,10 @@ ...@@ -6,6 +6,10 @@
</head> </head>
<body> <body>
<table border="1" style="width: 100%;"> <table border="1" style="width: 100%;">
<tr>
<th style="text-align: center;" id="script_injection_space">
</th>
</tr>
<tr style="font-style:italic;"> <tr style="font-style:italic;">
<th>Storage Description</th> <th>Storage Description</th>
</tr> </tr>
...@@ -20,9 +24,10 @@ ...@@ -20,9 +24,10 @@
<button onclick="fillMemoryDescription()">Memory</button> <button onclick="fillMemoryDescription()">Memory</button>
<button onclick="fillLocalDescription()">Local</button> <button onclick="fillLocalDescription()">Local</button>
<button onclick="fillDavDescription()">WebDAV</button> <button onclick="fillDavDescription()">WebDAV</button>
<button onclick="fillDavBasicDescription()">WebDAV Basic</button>
<button onclick="fillERP5Description()">ERP5</button> <button onclick="fillERP5Description()">ERP5</button>
<button onclick="fillCustomDescription()">Custom</button> - <button onclick="fillCustomDescription()">Custom</button>
<button onclick="fillLastDescription()">Last</button> <br /><button onclick="fillLastDescription()">Last</button>
<button onclick="loadDescription()">Load</button> <button onclick="loadDescription()">Load</button>
<button onclick="saveDescription()">Save</button> <button onclick="saveDescription()">Save</button>
</td> </td>
...@@ -48,7 +53,7 @@ ...@@ -48,7 +53,7 @@
<button onclick="post()">post</button> <button onclick="post()">post</button>
<button onclick="put()">put</button> <button onclick="put()">put</button>
<button onclick="get()">get</button> <button onclick="get()">get</button>
<button onclick="remove()">remove</button> <button onclick="window.remove()">remove</button>
- <button onclick="putAttachment()">putAttachment</button> - <button onclick="putAttachment()">putAttachment</button>
<button onclick="getAttachment()">getAttachment</button> <button onclick="getAttachment()">getAttachment</button>
<button onclick="removeAttachment()">removeAttachment</button> <button onclick="removeAttachment()">removeAttachment</button>
...@@ -68,11 +73,14 @@ ...@@ -68,11 +73,14 @@
</table> </table>
<br /> <br />
<div style="text-align: center;"> <div style="text-align: center;">
<button onclick="printLocalStorage()">print localStorage</button> Useful functions:
<button onclick="localStorage.clear()">clear localStorage</button><br /> <button onclick="scriptLogLocalStorage()">log localStorage</button>
<button onclick="clearlog()">Clear Log</button> <button onclick="localStorage.clear()">clear localStorage</button>
<button onclick="scriptRemoveAllDocs()">removeAllDocs</button>
</div> </div>
<hr /> <hr />
<button onclick="clearlog()">Clear Log</button>
<hr />
<div id="log"> <div id="log">
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
...@@ -121,6 +129,56 @@ function error(o) { ...@@ -121,6 +129,56 @@ function error(o) {
function clearlog() { function clearlog() {
select("#log").innerHTML = ""; select("#log").innerHTML = "";
} }
function injectScript(url) {
var script = document.createElement("script");
script.setAttribute("src", url);
document.body.appendChild(script);
}
function injectLastScripts() {
var i, scripts = JSON.parse(localStorage.getItem("jio_dashboard_injected_scripts") || "{}");
for (i in scripts) {
if (i) {
injectScript(i);
}
}
}
function saveScripts() {
var scripts = {};
[].forEach.call(document.querySelectorAll("#script_injection_space input[type=\"text\"]"), function (input) {
return scripts[input.value] = true;
});
localStorage.setItem("jio_dashboard_injected_scripts", JSON.stringify(scripts));
location.href = location.href;
}
function buildScriptFields() {
var space, el, i, count = 0, scripts;
function createInput(value) {
var e = document.createElement("input");
e.setAttribute("type", "text");
e.setAttribute("style", "width: 98%;");
if (value) { e.value = value; }
count += 1;
return e;
}
scripts = JSON.parse(localStorage.getItem("jio_dashboard_injected_scripts") || "{}");
space = select("#script_injection_space");
el = document.createElement("div");
el.textContent = "Additional scripts:";
space.appendChild(el);
for (i in scripts) {
if (i) {
space.appendChild(createInput(i));
}
}
space.appendChild(createInput());
el = document.createElement("input");
el.setAttribute("type", "button");
el.value = "Save scripts and refresh page";
el.onclick = saveScripts;
space.appendChild(el);
}
// clear log on Alt+L // clear log on Alt+L
document.addEventListener("keypress", function (event) { document.addEventListener("keypress", function (event) {
if (event.altKey === true && event.charCode === 108) { if (event.altKey === true && event.charCode === 108) {
...@@ -133,6 +191,7 @@ document.addEventListener("keypress", function (event) { ...@@ -133,6 +191,7 @@ document.addEventListener("keypress", function (event) {
<script src="../src/sha256.amd.js"></script> <script src="../src/sha256.amd.js"></script>
<script src="../jio.js"></script> <script src="../jio.js"></script>
<script src="../src/jio.storage/localstorage.js"></script> <script src="../src/jio.storage/localstorage.js"></script>
<script src="../src/jio.storage/davstorage.js"></script>
<script src="http://git.erp5.org/gitweb/uritemplate-js.git/blob_plain/HEAD:/bin/uritemplate-min.js"></script> <script src="http://git.erp5.org/gitweb/uritemplate-js.git/blob_plain/HEAD:/bin/uritemplate-min.js"></script>
<script src="../lib/uri/URI.js"></script> <script src="../lib/uri/URI.js"></script>
<script src="../src/jio.storage/erp5storage.js"></script> <script src="../src/jio.storage/erp5storage.js"></script>
...@@ -141,6 +200,9 @@ document.addEventListener("keypress", function (event) { ...@@ -141,6 +200,9 @@ document.addEventListener("keypress", function (event) {
var my_jio = null; var my_jio = null;
injectLastScripts();
buildScriptFields();
function fillMemoryDescription() { function fillMemoryDescription() {
select("#storagedescription").value = JSON.stringify({ select("#storagedescription").value = JSON.stringify({
"type": "local", "type": "local",
...@@ -159,15 +221,20 @@ function fillLocalDescription() { ...@@ -159,15 +221,20 @@ function fillLocalDescription() {
function fillDavDescription() { function fillDavDescription() {
select("#storagedescription").value = JSON.stringify({ select("#storagedescription").value = JSON.stringify({
"type": "dav", "type": "dav",
"auth_type": "basic", "url": "<url>"
"username": "<username>", }, null, " ")
"password": "<password>" }
function fillDavBasicDescription() {
select("#storagedescription").value = JSON.stringify({
"type": "dav",
"url": "<url>",
"basic_login": "<btoa(username + ':' + password)>"
}, null, " ") }, null, " ")
} }
function fillERP5Description() { function fillERP5Description() {
select("#storagedescription").value = JSON.stringify({ select("#storagedescription").value = JSON.stringify({
"type": "erp5", "type": "erp5",
"url": "<url/hateoas>" "url": "<url to hateoas web site>"
}, null, " ") }, null, " ")
} }
function fillCustomDescription() { function fillCustomDescription() {
...@@ -204,48 +271,55 @@ function createJIO() { ...@@ -204,48 +271,55 @@ function createJIO() {
} }
} }
function printLocalStorage() { function logError(begin_date, err) {
log("localStorage content\n" + JSON.stringify(localStorage, null, " ")); log('time : ' + (Date.now() - begin_date));
error('return :' + JSON.stringify(err, null, " "));
throw err;
} }
function callback(err, val, begin_date) { function logAnswer(begin_date, val) {
log('time : ' + (Date.now() - begin_date)); log('time : ' + (Date.now() - begin_date));
if (err) {
return error('return :' + JSON.stringify(err, null, " "));
}
log('return : ' + JSON.stringify(val, null, " ")); log('return : ' + JSON.stringify(val, null, " "));
return val;
} }
function command(method) { function command(method, num) {
var begin_date = Date.now(), doc = {}, opts = {}; var begin_date = Date.now(), doc = {}, opts = {};
if (!my_jio) { if (!my_jio) {
return error('no jio set'); error('no jio set');
return;
} }
doc = JSON.parse(select('#metadata').value); doc = select('#metadata').value;
opts = JSON.parse(select("#options").value); opts = select("#options").value;
if (num !== undefined) {
doc = doc.replace(/\\u0000/g, num);
opts = opts.replace(/\\u0000/g, num);
}
doc = JSON.parse(doc);
opts = JSON.parse(opts);
log(method + '\ndoc: ' + JSON.stringify(doc, null, " ") + log(method + '\ndoc: ' + JSON.stringify(doc, null, " ") +
'\nopts: ' + JSON.stringify(opts, null, " ")); '\nopts: ' + JSON.stringify(opts, null, " "));
if (method === "allDocs") { if (method === "allDocs") {
my_jio.allDocs(opts).then(function (answer) { return my_jio.allDocs(opts).then(
callback(undefined, answer, begin_date); logAnswer.bind(null, begin_date),
}, function (error) { logError.bind(null, begin_date)
callback(error, undefined, begin_date); );
});
} else { } else {
my_jio[method](doc, opts).then(function (answer) { return my_jio[method](doc, opts).then(
callback(undefined, answer, begin_date); logAnswer.bind(null, begin_date),
}, function (error) { logError.bind(null, begin_date)
callback(error, undefined, begin_date); );
});
} }
} }
function doCommandNTimes(method) { function doCommandNTimes(method) {
var i = -1, n = 0, lock; var i = -1, n = 0, lock, promise_list = [];
n = parseInt(select("#times").value, 10); n = parseInt(select("#times").value, 10);
lock = select("#times-lock").checked; lock = select("#times-lock").checked;
if (!lock) { if (!lock) {
...@@ -255,39 +329,59 @@ function doCommandNTimes(method) { ...@@ -255,39 +329,59 @@ function doCommandNTimes(method) {
n = 1; n = 1;
} }
while (++i < n) { while (++i < n) {
command(method); promise_list.push(command(method, i));
} }
return RSVP.all(promise_list);
} }
function post() { function post() {
doCommandNTimes("post"); return doCommandNTimes("post");
} }
function put() { function put() {
doCommandNTimes("put"); return doCommandNTimes("put");
} }
function get() { function get() {
doCommandNTimes("get"); return doCommandNTimes("get");
} }
function remove() { function remove() {
doCommandNTimes("remove"); return doCommandNTimes("remove");
} }
function putAttachment() { function putAttachment() {
doCommandNTimes("putAttachment"); return doCommandNTimes("putAttachment");
} }
function getAttachment() { function getAttachment() {
doCommandNTimes("getAttachment"); return doCommandNTimes("getAttachment");
} }
function removeAttachment() { function removeAttachment() {
doCommandNTimes("removeAttachment"); return doCommandNTimes("removeAttachment");
} }
function allDocs() { function allDocs() {
doCommandNTimes("allDocs"); return doCommandNTimes("allDocs");
} }
function check() { function check() {
doCommandNTimes("check"); return doCommandNTimes("check");
} }
function repair() { function repair() {
doCommandNTimes("repair"); return doCommandNTimes("repair");
}
//////////////////////////////////////////////////////////////////////
// scripts
function scriptLogLocalStorage() {
log("localStorage content\n" + JSON.stringify(localStorage, null, " "));
}
function scriptRemoveAllDocs() {
var original_metadata_value = select('#metadata').value;
return command("allDocs").then(function (answer) {
return RSVP.all(answer.data.rows.map(function (row) {
select("#metadata").value = JSON.stringify({"_id": row.id});
return command("remove");
}));;
}).then(function () {
select('#metadata').value = original_metadata_value;
});
} }
//--> //-->
</script> </script>
......
...@@ -7,99 +7,271 @@ ...@@ -7,99 +7,271 @@
// { // {
// type: "erp5" // type: "erp5"
// url: {string} // url: {string}
// default_view: {string} (optional)
// } // }
/*jslint indent: 2, nomen: true, unparam: true */ /*jslint indent: 2, nomen: true, unparam: true */
/*global jIO, console, UriTemplate, FormData, RSVP, URI, /*global jIO, UriTemplate, FormData, RSVP, URI, DOMParser, Blob,
ProgressEvent, define */ ProgressEvent, define */
(function (dependencies, module) { (function (root, dependencies, module) {
"use strict"; "use strict";
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
return define(dependencies, module); return define(dependencies, module);
} }
module(RSVP, jIO, URI); var namespace = module(RSVP, jIO, URI, UriTemplate);
}([ if (namespace !== undefined) { root.ERP5Storage = namespace; }
'rsvp', }(this, [
'jio', "rsvp",
'uri' "jio",
], function (RSVP, jIO, URI) { "uri",
"uritemplate"
], function (RSVP, jIO, URI, UriTemplate) {
"use strict"; "use strict";
var hasOwnProperty = Function.prototype.call.bind(
Object.prototype.hasOwnProperty
), constant = {};
constant.method_notification_message_obj = {
"get": "Getting document.",
"post": "Posting document.",
"put": "Putting document.",
"remove": "Removing document.",
"getAttachment": "Getting attachment.",
"putAttachment": "Putting attachment.",
"removeAttacment": "Removing attachment.",
"allDocs": "Getting document list."
};
// XXX docstring
function formatGetSuccessAnswer(answer) {
if (answer === undefined || answer === null) { throw answer; }
var result;
if (typeof answer.data === "object" && answer.data) {
return answer;
}
if (answer.target &&
typeof answer.target.status === "number" &&
typeof answer.target.statusText === "string") {
result = {
"status": answer.target.status
};
if (typeof answer.target.response === "object" &&
answer.target.response !== null) {
if (typeof answer.target.response.toJSON === "function") {
result.data = answer.target.response.toJSON();
} else {
result.data = answer.target.response;
}
} else if (answer.target.response instanceof Blob) {
return jIO.util.readBlobAsText(answer.target.response).
then(function (text) {
result.data = JSON.parse(text);
return result;
}, null, function () {
throw null; // dont propagate blob notifications
});
}
return result;
}
return answer;
}
// XXX docstring
function formatUpdateSuccessAnswer(answer) {
if (answer === undefined || answer === null) { throw answer; }
var result;
if (typeof answer.target === "object" && answer.target !== null &&
typeof answer.target.status === "number") {
result = {
"status": answer.target.status
};
return result;
}
return answer;
}
// XXX docstring
function formatErrorAnswer(answer) {
if (answer === undefined || answer === null) { throw answer; }
var result, dom;
if (answer.target &&
typeof answer.target.status === "number" &&
typeof answer.target.statusText === "string") {
// seams to be a ProgressEvent
result = {
"status": answer.target.status
};
if (typeof answer.target.response === "object" &&
answer.target.response !== null) {
if (typeof answer.target.response.toJSON === "function") {
result.data = answer.target.response.toJSON();
} else {
result.data = answer.target.response;
}
} else if (typeof answer.target.responseText === "string") {
dom = new DOMParser().parseFromString(
answer.target.responseText,
"text/html"
);
result.message = (dom.querySelector('#master') ||
dom.firstElementChild).textContent;
if (!result.message) { delete result.message; }
}
throw result;
}
throw answer;
}
// XXX docstring
function formatNotification(method, notif) {
var result;
if (notif) {
if (typeof notif.loaded === "number" &&
typeof notif.total === "number") {
result = {};
// can be a ProgressEvent or a jIO notification
if (notif.method !== method) {
result = {
"method": method,
"loaded": notif.loaded,
"total": notif.total
};
if (typeof notif.percentage === "number") {
result.percentage = notif.percentage;
}
}
if (typeof notif.message === "string") {
result.message = notif.message;
} else {
result.message = constant.method_notification_message_obj[method];
}
return result;
}
}
throw null; // stop propagation
}
constant.formatSuccessAnswerFor = {
"post": formatUpdateSuccessAnswer,
"put": formatUpdateSuccessAnswer,
"get": formatGetSuccessAnswer
};
//////////////////////////////////////////////////////////////////////
// XXX docstring
function ERP5Storage(spec) { function ERP5Storage(spec) {
if (typeof spec.url !== 'string' && !spec.url) { if (typeof spec.url !== "string" || !spec.url) {
throw new TypeError("ERP5 'url' must be a string " + throw new TypeError("ERP5 'url' must be a string " +
"which contains more than one character."); "which contains more than one character.");
} }
this._url = spec.url; this._url = spec.url;
this._default_view = spec.default_view;
}
// XXX docstring
function methodGenerator(method) {
return function (command, param, options) {
RSVP.resolve().
then(function () {
var view = ERP5Storage.onView[options._view || this._default_view] ||
ERP5Storage.onView["default"];
if (typeof view[method] !== "function") {
view = ERP5Storage.onView["default"];
}
return view[method].call(this, param, options);
}.bind(this)).
then(constant.formatSuccessAnswerFor[method]).
then(null, formatErrorAnswer, formatNotification.bind(null, method)).
then(command.success, command.error, command.progress);
};
} }
ERP5Storage.prototype._getSiteDocument = function () { // XXX docstring
[
"post",
"put",
"get",
"remove",
"putAttachment",
"getAttachment",
"removeAttachment",
"allDocs",
"check",
"repair"
].forEach(function (method) {
ERP5Storage.prototype[method] = methodGenerator(method);
});
// XXX docstring
function getSiteDocument(url) {
if (typeof url !== "string" &&
typeof (this && this._url) !== "string") {
throw new TypeError("ERP5Storage.getSiteDocument(): Argument 1 `url` " +
"or `this._url` are not of type string.");
}
return jIO.util.ajax({ return jIO.util.ajax({
"type": "GET", "type": "GET",
"url": this._url, "url": url || this._url,
"xhrFields": { "xhrFields": {
withCredentials: true withCredentials: true
} }
}).then(function (response) { }).then(function (event) {
return JSON.parse(response.target.responseText); return JSON.parse(event.target.responseText);
}); });
}; }
ERP5Storage.getSiteDocument = getSiteDocument;
ERP5Storage.prototype._get = function (param, options) { // XXX docstring
return this._getSiteDocument() function getDocumentAndHatoas(param, options) {
.then(function (site_hal) { var this_ = this;
return ERP5Storage.getSiteDocument(this._url).
then(function (site_hal) {
// XXX need to get modified metadata
return jIO.util.ajax({ return jIO.util.ajax({
"type": "GET", "type": "GET",
"url": UriTemplate.parse(site_hal._links.traverse.href) "url": UriTemplate.parse(site_hal._links.traverse.href)
.expand({ .expand({
relative_url: param._id, relative_url: param._id,
view: options._view view: options._view || this_._default_view || "view"
}), }),
"xhrFields": { "xhrFields": {
withCredentials: true withCredentials: true
} }
}); });
})
.then(function (response) {
var result = JSON.parse(response.target.responseText);
result._id = param._id;
return result;
}); });
}; }
ERP5Storage.prototype.get = function (command, param, options) { ERP5Storage.onView = {};
this._get(param, options) ERP5Storage.onView["default"] = {};
.then(function (response) {
command.success({"data": response}); // XXX docstring
}) ERP5Storage.onView["default"].get = function (param, options) {
.fail(function (event) { return getDocumentAndHatoas.call(this, param, options).
console.error(event); then(function (response) {
if (event instanceof ProgressEvent) { var result = JSON.parse(response.target.responseText);
command.error( result._id = param._id;
event.target.status, result.portal_type = result._links.type.name;
event.target.statusText, delete result._embedded;
"Cannot find document" delete result._links;
); delete result._debug;
} new jIO.Metadata(result).format();
// XXX How to propagate the error return {"data": result};
command.error(event);
}); });
}; };
ERP5Storage.prototype.post = function (command, metadata, options) { // XXX docstring
return this._getSiteDocument() ERP5Storage.onView["default"].post = function (metadata, options) {
var final_response;
return getSiteDocument(this._url)
.then(function (site_hal) { .then(function (site_hal) {
/*jslint forin: true */
var post_action = site_hal._actions.add, var post_action = site_hal._actions.add,
data = new FormData(), data = new FormData();
key;
data.append("portal_type", metadata.portal_type);
for (key in metadata) {
if (metadata.hasOwnProperty(key)) {
// XXX Not a form dialog in this case but distant script
data.append(key, metadata[key]);
}
}
return jIO.util.ajax({ return jIO.util.ajax({
"type": post_action.method, "type": post_action.method,
"url": post_action.href, "url": post_action.href,
...@@ -108,26 +280,25 @@ ...@@ -108,26 +280,25 @@
withCredentials: true withCredentials: true
} }
}); });
}).then(function (doc) { }).then(function (event) {
// XXX Really depend on server response... final_response = {"status": event.target.status};
var uri = new URI(doc.target.getResponseHeader("X-Location")); if (!metadata._id) {
command.success({"id": uri.segment(2)}); // XXX Really depend on server response...
}).fail(function (event) { var uri = new URI(event.target.getResponseHeader("X-Location"));
console.error(event); final_response.id = uri.segment(2);
if (event instanceof ProgressEvent) { metadata._id = final_response.id;
return command.error(
event.target.status,
event.target.statusText,
"Unable to post doc"
);
} }
command.error(event); }).
}); then(ERP5Storage.onView["default"].put.bind(this, metadata, options)).
then(function () { return final_response; });
}; };
ERP5Storage.prototype.put = function (command, metadata, options) { // XXX docstring
return this._get(metadata, options) ERP5Storage.onView["default"].put = function (metadata, options) {
.then(function (result) { return getDocumentAndHatoas.call(this, metadata, options).
then(function (result) {
/*jslint forin: true */
result = JSON.parse(result.target.responseText);
var put_action = result._embedded._view._actions.put, var put_action = result._embedded._view._actions.put,
renderer_form = result._embedded._view, renderer_form = result._embedded._view,
data = new FormData(), data = new FormData(),
...@@ -135,13 +306,11 @@ ...@@ -135,13 +306,11 @@
data.append(renderer_form.form_id.key, data.append(renderer_form.form_id.key,
renderer_form.form_id['default']); renderer_form.form_id['default']);
for (key in metadata) { for (key in metadata) {
if (metadata.hasOwnProperty(key)) { if (hasOwnProperty(metadata, key)) {
if (key !== "_id") { if (key !== "_id") {
// Hardcoded my_ ERP5 behaviour // Hardcoded my_ ERP5 behaviour
if (renderer_form.hasOwnProperty("my_" + key)) { if (hasOwnProperty(renderer_form, "my_" + key)) {
data.append(renderer_form["my_" + key].key, metadata[key]); data.append(renderer_form["my_" + key].key, metadata[key]);
} else {
throw new Error("Can not save property " + key);
} }
} }
} }
...@@ -154,31 +323,16 @@ ...@@ -154,31 +323,16 @@
withCredentials: true withCredentials: true
} }
}); });
})
.then(function (result) {
command.success(result);
})
.fail(function (event) {
console.error(event);
if (event instanceof ProgressEvent) {
return command.error(
event.target.status,
event.target.statusText,
"Unable to call put"
);
}
command.error(event);
}); });
}; };
ERP5Storage.prototype.allDocs = function (command, param, options) { ERP5Storage.onView["default"].allDocs = function (param, options) {
if (typeof options.query !== "string") { if (typeof options.query !== "string") {
options.query = (options.query ? options.query = (options.query ?
jIO.Query.objectToSearchText(options.query) : jIO.Query.objectToSearchText(options.query) :
undefined); undefined);
} }
return this._getSiteDocument() return getSiteDocument(this._url)
.then(function (site_hal) { .then(function (site_hal) {
return jIO.util.ajax({ return jIO.util.ajax({
"type": "GET", "type": "GET",
...@@ -223,24 +377,13 @@ ...@@ -223,24 +377,13 @@
return RSVP.all(promise_list); return RSVP.all(promise_list);
}) })
.then(function (promise_list) { .then(function (promise_list) {
var result = promise_list[0], var result = promise_list[0];
count = result.length; return {"data": {"rows": result, "total_rows": result.length}};
command.success({"data": {"rows": result, "total_rows": count}});
})
.fail(function (event) {
console.error(event);
if (event instanceof ProgressEvent) {
return command.error(
event.target.status,
event.target.statusText,
"Cannot get list of document"
);
}
command.error(event);
}); });
}; };
jIO.addStorage("erp5", ERP5Storage); jIO.addStorage("erp5", ERP5Storage);
return ERP5Storage;
})); }));
/*
* Copyright 2013, Nexedi SA
* Released under the LGPL license.
* http://www.gnu.org/licenses/lgpl.html
*/
/*jslint indent: 2, maxlen: 80, nomen: true */
/*global jIO, UriTemplate, FormData, RSVP, URI, DOMParser, Blob,
ProgressEvent, define, ERP5Storage */
(function (dependencies, module) {
"use strict";
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
module(RSVP, jIO, URI, UriTemplate, ERP5Storage);
}([
"rsvp",
"jio",
"uri",
"uritemplate",
"erp5storage"
], function (RSVP, jIO, URI, UriTemplate, ERP5Storage) {
"use strict";
var hasOwnProperty = Function.prototype.call.bind(
Object.prototype.hasOwnProperty
), constant = {};
constant.task_state_to_action = {
// Auto Planned : ?
"Cancelled": "cancel",
"Confirmed": "confirm",
// Draft : ?
"Deleted": "delete",
"Ordered": "order",
"Planned": "plan"
};
constant.allDocsState = {"data": {
"total_rows": 7,
"rows": [{
"id": "taskmanager:state_module/1",
"doc": {
"type": "State",
"title": "Auto Planned"
//"state": "Auto Planned"
},
"values": {}
}, {
"id": "taskmanager:state_module/2",
"doc": {
"type": "State",
"title": "Cancelled",
//"state": "Cancelled",
"action": constant.task_state_to_action.Cancelled
},
"values": {}
}, {
"id": "taskmanager:state_module/3",
"doc": {
"type": "State",
"title": "Confirmed",
//"state": "Confirmed",
"action": constant.task_state_to_action.Confirmed
},
"values": {}
}, {
"id": "taskmanager:state_module/4",
"doc": {
"type": "State",
"title": "Deleted",
//"state": "Deleted",
"action": constant.task_state_to_action.Deleted
},
"values": {}
}, {
"id": "taskmanager:state_module/5",
"doc": {
"type": "State",
"title": "Draft"
//"state": "Draft"
},
"values": {}
}, {
"id": "taskmanager:state_module/6",
"doc": {
"type": "State",
"title": "Ordered",
//"state": "Ordered",
"action": constant.task_state_to_action.Ordered
},
"values": {}
}, {
"id": "taskmanager:state_module/7",
"doc": {
"type": "State",
"title": "Planned",
//"state": "Planned",
"action": constant.task_state_to_action.Planned
},
"values": {}
}]
}};
constant.mapping_jio_to_erp5 = {};
constant.mapping_erp5_to_jio = {};
// XXX docstring
function addMetadataMapping(jio_type, erp5_type) {
if (typeof jio_type !== "string" || typeof erp5_type !== "string" ||
!jio_type || !erp5_type) {
throw new TypeError("addMetadataMapping(): The two arguments " +
"must be non empty strings");
}
if (constant.mapping_jio_to_erp5[jio_type]) {
throw new TypeError("A mapping already exists for jIO metadata '" +
jio_type + "'");
}
if (constant.mapping_erp5_to_jio[erp5_type]) {
throw new TypeError("A mapping already exists for ERP5 metadata '" +
erp5_type + "'");
}
constant.mapping_jio_to_erp5[jio_type] = erp5_type;
constant.mapping_erp5_to_jio[erp5_type] = jio_type;
}
addMetadataMapping("type", "portal_type");
addMetadataMapping("state", "translated_simulation_state_title_text");
addMetadataMapping("project", "source_project_title_text");
addMetadataMapping("start", "start_date");
addMetadataMapping("stop", "stop_date");
addMetadataMapping("modified", "modification_date");
addMetadataMapping("date", "creation_date");
// addMetadataMapping("location", "destination_title");
// addMetadataMapping("source", "source_title");
// addMetadataMapping("requester", "destination_decision_title");
// addMetadataMapping("contributor", "contributor_list");
// addMetadataMapping("category", "category_list");
// XXX docstring
function toERP5Metadata(jio_type) {
/*jslint forin: true */
if (typeof jio_type === "string") {
return constant.mapping_jio_to_erp5[jio_type] || jio_type;
}
var result = {}, key;
if (typeof jio_type === "object" && jio_type) {
for (key in jio_type) {
if (hasOwnProperty(jio_type, key)) {
result[toERP5Metadata(key)] = jio_type[key];
}
}
}
return result;
}
// XXX docstring
function toJIOMetadata(erp5_type) {
/*jslint forin: true */
if (typeof erp5_type === "string") {
return constant.mapping_erp5_to_jio[erp5_type] || erp5_type;
}
var result = {}, key;
if (typeof erp5_type === "object" && erp5_type) {
for (key in erp5_type) {
if (hasOwnProperty(erp5_type, key)) {
result[toJIOMetadata(key)] = erp5_type[key];
}
}
}
return result;
}
ERP5Storage.onView.taskmanager = {};
ERP5Storage.onView.taskmanager.get = function (param, options) {
options._view = "taskmanrecord";
return ERP5Storage.onView["default"].get.call(this, param, options).
then(function (answer) {
answer.data = toJIOMetadata(answer.data);
return answer;
});
};
ERP5Storage.onView.taskmanager.post = function (metadata, options) {
metadata = toERP5Metadata(metadata);
options._view = "taskmanrecord";
return ERP5Storage.onView["default"].post.call(this, metadata, options);
};
ERP5Storage.onView.taskmanager.put = function (metadata, options) {
metadata = toERP5Metadata(metadata);
options._view = "taskmanrecord";
return ERP5Storage.onView["default"].put.call(this, metadata, options);
};
ERP5Storage.onView.taskmanager.allDocs = function (param, options) {
var that = this;
/*jslint unparam: true */
function changeQueryKeysToERP5Metadata() {
if (Array.isArray(options.select_list)) {
options.select_list = options.select_list.map(toERP5Metadata);
}
try {
options.query = jIO.QueryFactory.create(options.query);
options.query.onParseSimpleQuery = function (object) {
object.parsed.key = toERP5Metadata(object.parsed.key);
};
return options.query.parse().then(function (query) {
options.query = jIO.QueryFactory.create(query).toString();
});
} catch (e) {
delete options.query;
return RSVP.resolve();
}
}
function requestERP5(site_hal) {
return jIO.util.ajax({
"type": "GET",
"url": UriTemplate.parse(site_hal._links.raw_search.href)
.expand({
query: options.query,
// XXX Force erp5 to return embedded document
select_list: options.select_list || [
"portal_type",
"title",
"reference",
"translated_simulation_state_title_text",
"description"
],
limit: options.limit
}),
"xhrFields": {
withCredentials: true
}
});
}
function formatAnswer(event) {
var catalog_json = JSON.parse(event.target.responseText),
data = catalog_json._embedded.contents,
count = data.length,
i,
uri,
item,
result = [];
for (i = 0; i < count; i += 1) {
item = data[i];
uri = new URI(item._links.self.href);
delete item._links;
item = toJIOMetadata(item);
result.push({
id: uri.segment(2),
doc: item,
value: item
});
}
return {"data": {"rows": result, "total_rows": result.length}};
}
function continueAllDocs() {
// Hard code for states
if (options.query === "portal_type: \"State\"") {
return constant.allDocsState;
}
return ERP5Storage.getSiteDocument(that._url).
then(requestERP5).
then(formatAnswer);
}
return changeQueryKeysToERP5Metadata().then(continueAllDocs);
};
}));
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment