MTurk HIT Database Mk.II

Keep track of the HITs you've done (and more!). Cross browser compatible.

目前为 2015-12-13 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name MTurk HIT Database Mk.II
  3. // @author feihtality
  4. // @namespace https://greasyfork.org/en/users/12709
  5. // @version 1.0.035
  6. // @description Keep track of the HITs you've done (and more!). Cross browser compatible.
  7. // @include /^https://www\.mturk\.com/mturk/(dash|view|sort|find|prev|search|accept|cont).*/
  8. // @exclude https://www.mturk.com/mturk/findhits?*hit_scraper
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. /**\
  13. **
  14. ** This is a complete rewrite of the MTurk HIT Database script from the ground up, which
  15. ** eliminates obsolete methods, fixes many bugs, and brings this script up-to-date
  16. ** with the modern browser environment.
  17. **
  18. \**/
  19.  
  20.  
  21.  
  22. /*globals self*/
  23.  
  24. const DB_VERSION = 7;
  25. const DB_NAME = 'HITDB';
  26. const MTURK_BASE = 'https://www.mturk.com/mturk/';
  27.  
  28. /*************************** Native code modifications *******************************/
  29. if (!NodeList.prototype[Symbol.iterator]) NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  30. Number.prototype.toPadded = function(length) { // format leading zeros
  31. 'use strict';
  32. length = length || 2;
  33. return ("0000000"+this).substr(-length);
  34. };
  35. Math.decRound = function(v, shift) { // decimal rounding
  36. 'use strict';
  37. v = Math.round(+(v+"e"+shift));
  38. return +(v+"e"+-shift);
  39. };
  40. Date.prototype.toLocalISOString = function() { // ISOString by local timezone
  41. 'use strict';
  42. var pad = function(num) { return Number(num).toPadded(); },
  43. offset = pad(Math.floor(this.getTimezoneOffset()/60)) + pad(this.getTimezoneOffset()%60),
  44. timezone = this.getTimezoneOffset() > 0 ? "-" + offset : "+" + offset;
  45. return this.getFullYear() + "-" + pad(this.getMonth()+1) + "-" + pad(this.getDate()) +
  46. "T" + pad(this.getHours()) + ":" + pad(this.getMinutes()) + ":" + pad(this.getSeconds()) + timezone;
  47. };
  48. /***********************************************************************************************/
  49.  
  50. (function() { // simplify strict scoping
  51. 'use strict';
  52.  
  53. var qc = {
  54. extraDays: !!localStorage.getItem("hitdb_extraDays") || false,
  55. fetchData: document.location.pathname === "/mturk/dashboard" ? JSON.parse(localStorage.getItem("hitdb_fetchData") || "{}") : null,
  56. seen: {},
  57. aat: ~document.location.pathname.search(/(dash|accept|cont)/) ? JSON.parse(localStorage.getItem("hitdb_autoAppTemp") || "{}") : null,
  58. save: function(key, name, isObj) {
  59. if (isObj)
  60. localStorage.setItem(name, JSON.stringify(this[key]));
  61. else
  62. localStorage.setItem(name, this[key]);
  63. }
  64. },
  65. metrics = {};
  66.  
  67. var
  68. HITStorage = { //{{{
  69. data: {}, db: null,
  70.  
  71. versionChange: function hsversionChange() { //{{{
  72. var db = this.result;
  73. db.onversionchange = function(e) { console.log("detected version change??",console.dir(e)); db.close(); };
  74. var dbo;
  75.  
  76. console.groupCollapsed("HITStorage.versionChange::onupgradeneeded");
  77.  
  78. if (!db.objectStoreNames.contains("HIT")) {
  79. console.log("creating HIT OS");
  80. dbo = db.createObjectStore("HIT", { keyPath: "hitId" });
  81. dbo.createIndex("date", "date", { unique: false });
  82. dbo.createIndex("requesterName", "requesterName", { unique: false});
  83. dbo.createIndex("title", "title", { unique: false });
  84. dbo.createIndex("reward", "reward", { unique: false });
  85. dbo.createIndex("status", "status", { unique: false });
  86. dbo.createIndex("requesterId", "requesterId", { unique: false });
  87.  
  88. //localStorage.setItem("hitdb_extraDays", true);
  89. //qc.extraDays = true;
  90. }
  91. if (!db.objectStoreNames.contains("STATS")) {
  92. console.log("creating STATS OS");
  93. dbo = db.createObjectStore("STATS", { keyPath: "date" });
  94. }
  95. if (this.transaction.objectStore("STATS").indexNames.length < 5) { // new in v5: schema additions
  96. this.transaction.objectStore("STATS").createIndex("approved", "approved", { unique: false });
  97. this.transaction.objectStore("STATS").createIndex("earnings", "earnings", { unique: false });
  98. this.transaction.objectStore("STATS").createIndex("pending", "pending", { unique: false });
  99. this.transaction.objectStore("STATS").createIndex("rejected", "rejected", { unique: false });
  100. this.transaction.objectStore("STATS").createIndex("submitted", "submitted", { unique: false });
  101. }
  102.  
  103. if (db.objectStoreNames.contains("NOTES") && this.transaction.objectStore("NOTES").indexNames.length < 3)
  104. db.deleteObjectStore("NOTES");
  105.  
  106. if (!db.objectStoreNames.contains("NOTES")) { // new in v5; schema change
  107. console.log("creating NOTES OS");
  108. dbo = db.createObjectStore("NOTES", { keyPath: "id", autoIncrement: true });
  109. dbo.createIndex("hitId", "hitId", { unique: false });
  110. dbo.createIndex("requesterId", "requesterId", { unique: false });
  111. dbo.createIndex("tags", "tags", { unique: false, multiEntry: true });
  112. dbo.createIndex("date", "date", { unique: false });
  113. }
  114.  
  115. if (db.objectStoreNames.contains("BLOCKS"))
  116. db.deleteObjectStore("BLOCKS");
  117.  
  118. console.groupEnd();
  119. }, // }}} versionChange
  120.  
  121. parseDOM: function(doc) {//{{{
  122. Status.color = "black";
  123.  
  124. var errorCheck = doc.querySelector('td[class="error_title"]'),
  125. extraInfo = [];
  126.  
  127. if (doc.title.search(/Status$/) > 0) // status overview
  128. parseStatus();
  129. else if (doc.querySelector('td[colspan="4"]')) // valid status detail, but no data
  130. parseMisc("next");
  131. else if (doc.title.search(/Status Detail/) > 0) // status detail with data
  132. parseDetail();
  133. else if (errorCheck) { // encountered an error page
  134. // hit max request rate
  135. if (~errorCheck.textContent.indexOf("page request rate")) {
  136. var _d = doc.documentURI.match(/\d{8}/)[0],
  137. _p = doc.documentURI.match(/ber=(\d+)/)[1];
  138. metrics.dbupdate.mark("[PRE]"+_d+"p"+_p, "start");
  139. console.log("exceeded max requests; refetching %sp%s", _d, _p);
  140. Status.node.innerHTML = "Exceeded maximum server requests; retrying "+Utils.ISODate(_d)+" page "+_p+"."+
  141. "<br>Please wait...";
  142. setTimeout(HITStorage.fetch, 950, doc.documentURI);
  143. return;
  144. }
  145. // no more staus details left in range
  146. else if (qc.extraDays)
  147. parseMisc("end");
  148. else
  149. Utils.errorHandler(new Error("Failed to parse '" + doc.documentURI + "'"));
  150. }
  151. else
  152. Utils.errorHandler(new Error("Unhandled document '" + doc.docuemntURI + "'"));
  153.  
  154.  
  155. function parseStatus() {//{{{
  156. HITStorage.data = { HIT: [], STATS: [] };
  157. qc.seen = {};
  158. ProjectedEarnings.clear();
  159.  
  160. // reload auto-approval data to cover not refreshing the dashboard before running an update
  161. qc.aat = JSON.parse(localStorage.getItem("hitdb_autoAppTemp") || "{}");
  162. var _pastDataExists = Boolean(Object.keys(qc.fetchData).length),
  163. timeout = 0,
  164. raw = {
  165. day: doc.querySelectorAll(".statusDateColumnValue"),
  166. sub: doc.querySelectorAll(".statusSubmittedColumnValue"),
  167. app: doc.querySelectorAll(".statusApprovedColumnValue"),
  168. rej: doc.querySelectorAll(".statusRejectedColumnValue"),
  169. pen: doc.querySelectorAll(".statusPendingColumnValue"),
  170. pay: doc.querySelectorAll(".statusEarningsColumnValue")
  171. };
  172. for (var i=0;i<raw.day.length;i++) {
  173. var d = {};
  174. var _date = raw.day[i].childNodes[1].href.substr(53);
  175. d.date = Utils.ISODate(_date);
  176. d.submitted = +raw.sub[i].textContent;
  177. d.approved = +raw.app[i].textContent;
  178. d.rejected = +raw.rej[i].textContent;
  179. d.pending = +raw.pen[i].textContent;
  180. d.earnings = +raw.pay[i].textContent.substr(1);
  181. HITStorage.data.STATS.push(d);
  182.  
  183. // bonus received on date with 0 HITs
  184. if (!d.submitted && !d.pending) { if (_date in qc.fetchData) delete qc.fetchData[_date]; continue; }
  185. // check whether or not we need to get status detail pages for date, then
  186. // fetch status detail pages per date in range and slightly slow
  187. // down GET requests to avoid making too many in too short an interval
  188. var payload = { encodedDate: _date, pageNumber: 1, sortType: "All" };
  189. if (_pastDataExists) {
  190. // date not in range but is new date (or old date but we need updates)
  191. // lastDate stored in ISO format, fetchData date keys stored in mturk's URI ecnodedDate format
  192. if ( (d.date >= qc.fetchData.lastDate) || ~(Object.keys(qc.fetchData).indexOf(_date)) ||
  193. (d.pending && !~Object.keys(qc.fetchData).indexOf(_date))) {
  194. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  195. timeout += 380;
  196.  
  197. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  198. }
  199. } else { // get everything
  200. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  201. timeout += 380;
  202.  
  203. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  204. }
  205. } // for
  206. qc.fetchData.expectedTotal = _calcTotals(qc.fetchData);
  207.  
  208. // try for extra days
  209. if (qc.extraDays === true) {
  210. localStorage.removeItem("hitdb_extraDays");
  211. d = _decDate(HITStorage.data.STATS[HITStorage.data.STATS.length-1].date);
  212. qc.extraDays = d; // repurpose extraDays for QC
  213. payload = { encodedDate: d, pageNumber: 1, sortType: "All" };
  214. setTimeout(HITStorage.fetch, 1000, MTURK_BASE+"statusdetail", payload);
  215. }
  216. qc.fetchData.lastDate = HITStorage.data.STATS[0].date; // most recent date seen
  217. qc.save("fetchData", "hitdb_fetchData", true);
  218.  
  219. }//}}} parseStatus
  220.  
  221. function parseDetail() {//{{{
  222. var _date = doc.documentURI.replace(/.+(\d{8}).+/, "$1"),
  223. _page = doc.documentURI.replace(/.+ber=(\d+).+/, "$1"),
  224. getExtras = function(entry) {
  225. return new Promise( function(y) {
  226. HITStorage.db.transaction('HIT', 'readonly').objectStore('HIT').get(entry.hitId).onsuccess = function() {
  227. if (this.result && isNaN(this.result.reward))
  228. entry.reward = { pay: entry.reward, bonus: this.result.reward.bonus };
  229. if (this.result && +this.result.autoAppTime)
  230. entry.autoAppTime = this.result.autoAppTime;
  231. HITStorage.data.HIT.push(entry); y(1);
  232. };
  233. });
  234. };
  235.  
  236. metrics.dbupdate.mark("[PRE]"+_date+"p"+_page, "end");
  237. Status.message = "Processing "+Utils.ISODate(_date)+" page "+_page;
  238. var raw = {
  239. req: doc.querySelectorAll(".statusdetailRequesterColumnValue"),
  240. title: doc.querySelectorAll(".statusdetailTitleColumnValue"),
  241. pay: doc.querySelectorAll(".statusdetailAmountColumnValue"),
  242. status: doc.querySelectorAll(".statusdetailStatusColumnValue"),
  243. feedback: doc.querySelectorAll(".statusdetailRequesterFeedbackColumnValue")
  244. };
  245.  
  246. for (var i=0;i<raw.req.length;i++) {
  247. var d = {};
  248. d.date = Utils.ISODate(_date);
  249. d.feedback = raw.feedback[i].textContent.trim().replace(/[\n\t]/g, ' ');
  250. d.hitId = raw.req[i].childNodes[1].href.replace(/.+HIT\+(.+)/, "$1");
  251. d.requesterId = raw.req[i].childNodes[1].href.replace(/.+rId=(.+?)&.+/, "$1");
  252. d.requesterName = raw.req[i].textContent.trim();
  253. d.reward = +raw.pay[i].textContent.substr(1);
  254. d.status = raw.status[i].textContent.replace(/\s/g, " "); // replace char160 spaces with char32 spaces
  255. d.title = raw.title[i].textContent.trim();
  256.  
  257. // mturk apparently never marks $0.00 HITs as 'Paid' so we fix that
  258. if (!d.reward && ~d.status.search(/approved/i)) d.status = "Paid";
  259. // insert autoApproval times
  260. d.autoAppTime = HITStorage.autoApprovals.getTime(_date,d.hitId);
  261.  
  262. extraInfo.push(getExtras(d));
  263.  
  264. if (!qc.seen[_date]) qc.seen[_date] = {};
  265. qc.seen[_date] = {
  266. submitted: qc.seen[_date].submitted + 1 || 1,
  267. pending: ~d.status.search(/pending/i) ?
  268. (qc.seen[_date].pending + 1 || 1) : (qc.seen[_date].pending || 0)
  269. };
  270.  
  271. ProjectedEarnings.updateValues(d);
  272. } //for
  273.  
  274. // additional pages remain; get them
  275. var morePages = doc.querySelector('img[src="/media/right_dbl_arrow.gif"]')/* || doc.querySelector('a[href*="&pageNumber='+(_page+1)+'"]')*/;
  276. if (morePages) {
  277. var payload = { encodedDate: _date, pageNumber: +_page+1, sortType: "All" };
  278. setTimeout(HITStorage.fetch, 380, MTURK_BASE+"statusdetail", payload);
  279. return;
  280. } else if (Utils.ISODate(_date) !== qc.fetchData.lastDate &&
  281. qc.seen[_date].submitted === qc.fetchData[_date].submitted && qc.seen[_date].pending === 0) {
  282. console.log("no more pending hits, removing",_date,"from fetchData");
  283. delete qc.fetchData[_date];
  284. qc.save("fetchData", "hitdb_fetchData", true);
  285. }
  286.  
  287. if (!qc.extraDays) { // not fetching extra days
  288. console.log("date:", _date, "pages:", _page, "totals:", _calcTotals(qc.seen), "of", qc.fetchData.expectedTotal);
  289. Status.message += " [ "+_calcTotals(qc.seen)+"/"+ qc.fetchData.expectedTotal+" ]";
  290. if (_calcTotals(qc.seen) === qc.fetchData.expectedTotal) {
  291. Status.message = "Writing to database...";
  292. HITStorage.autoApprovals.purge();
  293. Promise.all(extraInfo).then(function() { HITStorage.write(HITStorage.data, cbUpdate); });
  294. }
  295. } else if (_date <= qc.extraDays) { // day is older than default range and still fetching extra days
  296. parseMisc("next");
  297. console.log("fetchrequest for", _decDate(Utils.ISODate(_date)));
  298. }
  299. }//}}} parseDetail
  300.  
  301. function parseMisc(type) {//{{{
  302. var _d = doc.documentURI.match(/\d{8}/)[0],
  303. _p = doc.documentURI.match(/ber=(\d+)/)[1];
  304. metrics.dbupdate.mark("[PRE]"+_d+"p"+_p, "end");
  305. var payload = { encodedDate: _decDate(Utils.ISODate(_d)), pageNumber: 1, sortType: "All" };
  306.  
  307. if (type === "next" && +qc.extraDays > 1) {
  308. setTimeout(HITStorage.fetch, 250, MTURK_BASE+"statusdetail", payload);
  309. console.log("going to next page", payload.encodedDate);
  310. } else if (type === "end" && +qc.extraDays > 1) {
  311. Status.message = "Writing to database...";
  312. Promise.all(extraInfo).then(function() { HITStorage.write(HITStorage.data, cbUpdate); });
  313. } else
  314. Utils.errorHandler(new TypeError("Failed to execute '"+type+"' in '"+doc.documentURI+"'"));
  315. }//}}}
  316.  
  317. function _decDate(date) {//{{{
  318. var y = date.substr(0,4);
  319. var m = date.substr(5,2);
  320. var d = date.substr(8,2);
  321. date = new Date(y,m-1,d-1);
  322. return Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded() + date.getFullYear();
  323. }//}}}
  324.  
  325. function _calcTotals(obj) {//{{{
  326. var sum = 0;
  327. for (var k in obj){
  328. if (obj.hasOwnProperty(k) && !isNaN(+k))
  329. sum += obj[k].submitted;
  330. }
  331. return sum;
  332. }//}}}
  333. },//}}} parseDOM
  334. autoApprovals: {//{{{
  335. getTime : function(date, hitId) {
  336. if (qc.extraDays || !Object.keys(qc.aat).length) return "";
  337. var found = false,
  338. autoApp = "";
  339.  
  340. if (!found && Object.keys(qc.aat).length) {
  341. for (var key in qc.aat) { if (qc.aat.hasOwnProperty(key)) { // for all dates in aat
  342. var id = Object.keys(qc.aat[key]).filter(id => id === hitId)[0];
  343. autoApp = qc.aat[key][id] || "";
  344. if (autoApp) {
  345. found = true;
  346. delete qc.aat[key][id];
  347. qc.save("aat", "hitdb_autoAppTemp", true);
  348. break;
  349. }
  350. }} // for key (dates)
  351. } // if !found && aat not empty
  352. return autoApp;
  353. },// getTime
  354. purge : function() {
  355. if (!Object.keys(qc.aat).length) return; // nothing here
  356. var pad = function(num) { return Number(num).toPadded(); },
  357. _date = Date.parse(new Date().getFullYear() + "-" + pad(new Date().getMonth()+1) + "-" + pad(new Date().getDate()));
  358.  
  359. for (var key of Object.keys(qc.aat)) {
  360. if (_date - key > 169200000) delete qc.aat[key]; // at least 2 days old, no need to keep it around
  361. }
  362. qc.save("aat", "hitdb_autoAppTemp", true);
  363. } // purge
  364. },//}}} autoApprovals
  365.  
  366. fetch: function(url, payload) { //{{{
  367. //format GET request with query payload
  368. if (payload) {
  369. var args = 0;
  370. url += "?";
  371. for (var k in payload) {
  372. if (payload.hasOwnProperty(k)) {
  373. if (args++) url += "&";
  374. url += k + "=" + payload[k];
  375. }
  376. }
  377. }
  378. // defer XHR to a promise
  379. var fetch = new Promise( function(fulfill, deny) {
  380. var urlreq = new XMLHttpRequest();
  381. urlreq.open("GET", url, true);
  382. urlreq.responseType = "document";
  383. urlreq.send();
  384. urlreq.onload = function() {
  385. if (this.status === 200) {
  386. fulfill(this.response);
  387. } else {
  388. deny(new Error(this.status + " - " + this.statusText));
  389. }
  390. };
  391. urlreq.onerror = function() { deny(new Error(this.status + " - " + this.statusText)); };
  392. urlreq.ontimeout = function() { deny(new Error(this.status + " - " + this.statusText)); };
  393. } );
  394. fetch.then( HITStorage.parseDOM, Utils.errorHandler );
  395.  
  396. }, //}}} fetch
  397. write: function(input, callback) { //{{{
  398. var counts = { requests: 0, total: 0 },
  399. os = Object.keys(input),
  400. dbo = [],
  401. dbt = HITStorage.db.transaction(os, "readwrite");
  402. for (var i=0;i<os.length;i++) { // cycle object stores
  403. dbo[i] = dbt.objectStore(os[i]);
  404. for (var k of input[os[i]]) { // cycle entries to put into object stores
  405. if (typeof callback === 'function' && ++counts.requests)
  406. dbo[i].put(k).onsuccess = callback.bind(counts);
  407. else
  408. dbo[i].put(k);
  409. }
  410. }
  411. }, //}}} write
  412.  
  413. recall: function(store, options) {//{{{
  414. if (options) {
  415. var index = options.index || null,
  416. range = options.range || null,
  417. dir = options.dir || "next",
  418. limit = options.limit || Infinity;
  419. if (options.filter) {
  420. var fs = options.filter.status !== "*" ? new RegExp(options.filter.status, "i") : false,
  421. fq = options.filter.query !== "*" ? new RegExp(options.filter.query,"i") : false,
  422. fd = options.filter.date || null;
  423. }
  424. if (options.progress)
  425. Progress.show();
  426. } // if options
  427.  
  428. var sr = new DBResult(), matches = 0, total = 0;
  429. return new Promise( function(resolve) {
  430. var dbo = HITStorage.db.transaction(store, "readonly").objectStore(store), dbq = null;
  431. if (index)
  432. dbq = dbo.index(index).openCursor(range, dir);
  433. else
  434. dbq = dbo.openCursor(range, dir);
  435. dbq.onsuccess = function() {
  436. var c = this.result;
  437. if (c && matches < limit) {
  438. try { Status.message = "Retrieving data... [ " + matches + " / " + (++total) + " ]"; } catch(e) {}
  439. if ( fd && (c.value.date < (fd[0] || "0000") || c.value.date > (fd[1] || "9999")) ) {
  440. c.continue();
  441. return;
  442. }
  443. if ( (!fs && !fq) || // no query filter and no status filter OR
  444. (fs && !fq && ~c.value.status.search(fs)) || // status match and no query filter OR
  445. (!fs && fq && // query match and no status filter OR
  446. (~c.value.title.search(fq) || ~c.value.requesterName.search(fq) || ~c.value.hitId.search(fq))) ||
  447. (fs && fq && ~c.value.status.search(fs) && // status match and query match
  448. (~c.value.title.search(fq) || ~c.value.requesterName.search(fq) || ~c.value.hitId.search(fq))) ) {
  449. sr.include(c.value);
  450. try { Status.message = "Retrieving data... [ " + (++matches) + " / " + total + " ]"; } catch(e) {}
  451. }
  452. c.continue();
  453. } else {
  454. try { Status.message = "Done."; } catch(e) {}
  455. resolve(sr);
  456. }
  457. }; // IDBCursor
  458. }); // promise
  459. },//}}} HITStorage::recall
  460.  
  461. backup: function(internal) {//{{{
  462. var bData = {},
  463. os = ["STATS", "NOTES", "HIT"],
  464. count = 0;
  465.  
  466. Progress.show();
  467. Status.push("Preparing backup...", "black");
  468.  
  469. for (var store of os)
  470. HITStorage.db.transaction(os, "readonly").objectStore(store).openCursor().onsuccess = populateBackup;
  471.  
  472. function populateBackup(e) {
  473. var cursor = e.target.result;
  474. if (cursor) {
  475. if (!bData[cursor.source.name]) bData[cursor.source.name] = [];
  476. bData[cursor.source.name].push(cursor.value);
  477. cursor.continue();
  478. } else
  479. if (++count === 3)
  480. finalizeBackup();
  481. }
  482. function finalizeBackup() {
  483. if (typeof internal === 'function') { qc.merge = bData; internal(true); return; }
  484. var backupblob = new Blob([JSON.stringify(bData)], {type:"application/json"});
  485. var date = new Date();
  486. var dl = document.createElement("A");
  487. date = date.getFullYear() + Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded();
  488. dl.href = URL.createObjectURL(backupblob);
  489. console.log(dl.href);
  490. dl.download = "hitdb_"+date+".bak";
  491. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  492. dl.click(); // so we make it so and click,
  493. dl.remove(); // then immediately remove it
  494. Progress.hide();
  495. Status.push("Done!", "green");
  496. }
  497.  
  498. }//}}} backup
  499.  
  500. }, //}}} HITStorage
  501.  
  502. Utils = { //{{{
  503. disableButtons: function(arr, status) { //{{{
  504. for (var b of arr) document.getElementById(b).disabled = status;
  505. }, //}}}
  506.  
  507. ftime : function(t) {//{{{
  508. if (String(t).length && +t === 0) return "0s";
  509. if (!t) return "n/a";
  510. var d = Math.floor(t/86400),
  511. h = Math.floor(t%86400/3600),
  512. m = Math.floor(t%86400%3600/60),
  513. s = t%86400%3600%60;
  514. return ((d>0) ? d+" day"+(d>1 ? "s " : " ") : "") + ((h>0) ? h+"h " : "") + ((m>0) ? m+"m " : "") + ((s>0) ? s+"s" : "");
  515. },//}}}ftime
  516.  
  517. ISODate: function(date) { //{{{ MMDDYYYY <-> YYYY-MM-DD
  518. if (date.length === 10)
  519. return date.substr(5,2)+date.substr(-2)+date.substr(0,4);
  520. else
  521. return date.substr(4)+"-"+date.substr(0,2)+"-"+date.substr(2,2);
  522. },//}}} ISODate
  523.  
  524. getPosition: function(element, includeHeight) {//{{{
  525. var offsets = { x: 0, y: includeHeight ? element.offsetHeight : 0 };
  526. do {
  527. offsets.x += element.offsetLeft;
  528. offsets.y += element.offsetTop;
  529. element = element.offsetParent;
  530. } while (element);
  531. return offsets;
  532. },//}}} getPosition
  533.  
  534. errorHandler: function(err) {//{{{
  535. try { Status.push(err.name + ": " + err.message, "red"); }
  536. catch(e) {}
  537. finally { console.error(err); }
  538. }//}}}
  539.  
  540. }, //}}} Utils
  541.  
  542. ProjectedEarnings = {//{{{
  543. data: JSON.parse(localStorage.getItem("hitdb_projectedEarnings") || "{}"),
  544. updateDate: function() {//{{{
  545. var tableList = document.querySelectorAll(".metrics-table"), el, date;
  546. try {
  547. el = tableList[5].rows[1].cells[0].children[0];
  548. date = el.href.match(/\d{8}/)[0];
  549. } catch(e1) {
  550. try {
  551. el = tableList[3].rows[1].cells[0].children[0];
  552. date = el.href.match(/\d{8}/)[0];
  553. } catch(e2) {
  554. for (var tbl of tableList) {
  555. if (tbl.rows.length < 2 || tbl.rows[1].cells.length < 6) continue;
  556. el = tbl.rows[1].cells[0].children[0];
  557. date = el.href.match(/\d{8}/)[0];
  558. } //for
  559. }//catch
  560. }//catch
  561. var day = el.textContent,
  562. isToday = day === "Today",
  563. _date = new Date(),
  564. weekEnd = null,
  565. weekStart = null;
  566.  
  567. _date.setDate(_date.getDate() - _date.getDay()); // sunday
  568. weekStart = Date.parse(_date.toLocalISOString().slice(0,10));
  569. _date.setDate(_date.getDate() + 7); // next sunday
  570. weekEnd = Date.parse(_date.toLocalISOString().slice(0,10));
  571.  
  572. if (!Object.keys(this.data).length) {
  573. this.data = {
  574. today: date, weekStart: weekStart, weekEnd: weekEnd, day: new Date().getDay(), dbUpdated: "n/a",
  575. pending: 0, approved: 0, earnings: {}, target: { day: 0, week: 0 }
  576. };
  577. }
  578.  
  579. if ( (Date.parse(Utils.ISODate(date)) >= this.data.weekEnd) ||
  580. (!isToday && new Date().getDay() < this.data.day) ) { // new week
  581. this.data.earnings = {};
  582. this.data.weekEnd = weekEnd;
  583. this.data.weekStart = weekStart;
  584. }
  585. if ( (this.data.today === null && isToday) || (this.data.today !== null && (date !== this.data.today || !isToday)) ) { // new day
  586. this.data.today = date === this.data.today ? null : date;
  587. this.data.day = new Date().getDay();
  588. }
  589.  
  590. this.saveState();
  591. },//}}} updateDate
  592. draw: function(init) {//{{{
  593. var parentTable = document.querySelector("#total_earnings_amount").offsetParent,
  594. rowPending = init ? parentTable.insertRow(-1) : parentTable.rows[4],
  595. rowProjectedDay = init ? parentTable.insertRow(-1) : parentTable.rows[5],
  596. rowProjectedWeek = init ? parentTable.insertRow(-1) : parentTable.rows[6],
  597. title = "Click to set/change the target value",
  598. weekTotal = this.getWeekTotal(),
  599. dayTotal = this.data.earnings[this.data.today] || 0;
  600.  
  601. if (init) {
  602. rowPending.insertCell(-1);rowPending.insertCell(-1);rowPending.className = "even";
  603. rowProjectedDay.insertCell(-1);rowProjectedDay.insertCell(-1);rowProjectedDay.className = "odd";
  604. rowProjectedWeek.insertCell(-1);rowProjectedWeek.insertCell(-1);rowProjectedWeek.className = "even";
  605. for (var i=0;i<rowPending.cells.length;i++) rowPending.cells[i].style.borderTop = "dotted 1px black";
  606. rowPending.cells[0].className = "metrics-table-first-value";
  607. rowProjectedDay.cells[0].className = "metrics-table-first-value";
  608. rowProjectedWeek.cells[0].className = "metrics-table-first-value";
  609. }
  610.  
  611. rowPending.cells[1].title = "This value includes all earnings that are not yet fully cleared as 'Paid'\n\n" +
  612. ` Pending Approval: $${(this.data.pending-this.data.approved).toFixed(2)}\n Pending Payment: $${this.data.approved.toFixed(2)}\n` +
  613. ` Total Pending: $${this.data.pending.toFixed(2)}`;
  614. rowPending.cells[0].innerHTML = 'Pending earnings '+
  615. '<span style="font-family:arial;font-size:10px;" title="Timestamp of last database update">[ ' + this.data.dbUpdated + ' ]</span>';
  616. rowPending.cells[1].textContent = "$" + this.data.pending.toFixed(2);
  617. rowProjectedDay.cells[0].innerHTML = 'Projected earnings for the day<br>'+
  618. '<meter id="projectedDayProgress" style="width:220px;" title="'+title+
  619. '" value="'+dayTotal+'" max="'+this.data.target.day+'"></meter>'+
  620. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + (dayTotal-this.data.target.day).toFixed(2) + '</span>';
  621. rowProjectedDay.cells[1].textContent = "$"+ dayTotal.toFixed(2);
  622. rowProjectedWeek.cells[0].innerHTML = 'Projected earnings for the week<br>' +
  623. '<meter id="projectedWeekProgress" style="width:220px;" title="'+title+
  624. '" value="'+weekTotal+'" max="'+this.data.target.week+'"></meter>' +
  625. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + (weekTotal-this.data.target.week).toFixed(2) + '</span>';
  626. rowProjectedWeek.cells[1].textContent = "$" + weekTotal.toFixed(2);
  627. document.querySelector("#projectedDayProgress").onclick = updateTargets.bind(this, "day");
  628. document.querySelector("#projectedWeekProgress").onclick = updateTargets.bind(this, "week");
  629.  
  630. function updateTargets(span, e) {
  631. /*jshint validthis:true*/
  632. var goal = prompt("Set your " + (span === "day" ? "daily" : "weekly") + " target:",
  633. this.data.target[span === "day" ? "day" : "week"]);
  634. if (goal && !isNaN(goal)) {
  635. this.data.target[span === "day" ? "day" : "week"] = goal;
  636. e.target.max = goal;
  637. e.target.nextSibling.textContent = " " + ((span === "day" ? dayTotal : weekTotal) - goal).toFixed(2);
  638. this.saveState();
  639. }
  640. }
  641. },//}}} draw
  642.  
  643. getWeekTotal: function() {
  644. var totals = 0;
  645. for (var k of Object.keys(this.data.earnings))
  646. totals += this.data.earnings[k];
  647.  
  648. return Math.decRound(totals, 2);
  649. },
  650. saveState: function() {
  651. localStorage.setItem("hitdb_projectedEarnings", JSON.stringify(this.data));
  652. },
  653.  
  654. clear: function() {
  655. this.data.pending = 0;
  656. this.data.approved = 0;
  657. for (var day of Object.keys(this.data.earnings))
  658. if (day in qc.fetchData || day === this.data.today) this.data.earnings[day] = 0;
  659. },
  660.  
  661. updateValues: function(obj) {
  662. var vDate = Date.parse(obj.date), iDate = Utils.ISODate(obj.date);
  663.  
  664. if (~obj.status.search(/pending/i)) // sum pending earnings (include approved until fully cleared as paid)
  665. this.data.pending = Math.decRound(obj.reward+this.data.pending, 2);
  666. if (~obj.status.search(/approved/i))
  667. this.data.approved = Math.decRound(obj.reward+this.data.approved, 2);
  668. if (vDate < this.data.weekEnd && vDate >= this.data.weekStart && !~obj.status.search(/rejected/i)){ // sum weekly earnings by day
  669. this.data.earnings[iDate] = Math.decRound(obj.reward+(this.data.earnings[iDate] || 0), 2 );
  670. }
  671. }
  672. },//}}} ProjectedEarnings
  673.  
  674. DBResult = function(resArr, colObj) {//{{{
  675. this.results = resArr || [];
  676. this.collation = colObj || null;
  677. this.formatHTML = function(type, simple) {//{{{
  678. simple = simple || false;
  679. var count = 0, htmlTxt = [], entry = null, _trClass = null;
  680.  
  681. if (this.results.length < 1) return "<h2>No entries found matching your query.</h2>";
  682.  
  683. if (type === "daily") {
  684. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th></th>'+
  685. '<th>Date</th><th>Submitted</th><th>Approved</th><th>Rejected</th><th>Pending</th><th>Earnings</th></tr></thead><tbody>');
  686. var r = this.collate(this.results,"stats");
  687. for (entry of this.results) {
  688. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  689. htmlTxt.push('<tr '+_trClass+' style="text-align:right">' +
  690. '<td><span class="hdbExpandRow">[+]</span></td>'+
  691. '<td style="text-align:center;">' + entry.date + '</td><td>' + entry.submitted + '</td>' +
  692. '<td>' + entry.approved + '</td><td>' + entry.rejected + '</td><td>' + entry.pending + '</td>' +
  693. '<td>' + Number(entry.earnings).toFixed(2) + '</td></tr>');
  694. }
  695. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow" style="text-align:right;"><td>Totals:</td>' +
  696. '<td>' + r.totalEntries + ' days</td><td>' + r.totalSub + '</td>' +
  697. '<td>' + r.totalApp + '</td><td>' + r.totalRej + '</td>' +
  698. '<td>' + r.totalPen + '</td><td>$' +
  699. Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  700. } else if (type === "pending" || type === "requester") {
  701. htmlTxt.push('<thead><tr data-sort="99999" class="hdbHeaderRow"><th width="160">Requester ID</th>' +
  702. '<th>Requester</th><th>' + (type === "pending" ? 'Pending' : 'HITs') + '</th><th>Rewards</th></tr></thead><tbody>');
  703. r = this.collate(this.results,"requesterId");
  704. for (var k in r) {
  705. if (!~k.search(/total/) && r.hasOwnProperty(k)) {
  706. var tr = ['<tr data-sort="'+Math.decRound(r[k].pay,2)+'"><td>' +
  707. '<span class="hdbExpandRow" title="Display all pending HITs from this requester">' +
  708. '[+]</span> ' + r[k][0].requesterId + '</td><td>' + r[k][0].requesterName + '</td>' +
  709. '<td style="text-align:center;">' + r[k].length + '</td><td>' + Number(Math.decRound(r[k].pay,2)).toFixed(2) + '</td></tr>'];
  710.  
  711. for (var hit of r[k]) { // hits in range per requester id
  712. tr.push('<tr data-rid="'+r[k][0].requesterId+'" style="color:#c60000;display:none;"><td style="text-align:right">' +
  713. hit.date + '</td><td width="500" colspan="2" class="nowrap" style="max-width:520" title="'+hit.title+'">' +
  714. '[ <span class="helpSpan" title="Auto-approval time">AA: '+Utils.ftime(hit.autoAppTime).trim()+'</span> ] '+
  715. hit.title + '</td><td style="text-align:right">' + _parseRewards(hit.reward,"pay") + '</td></tr>');
  716. }
  717. htmlTxt.push(tr.join(''));
  718. }
  719. }
  720. htmlTxt.sort(function(a,b) { return +b.substr(15,5).match(/\d+\.?\d*/) - +a.substr(15,5).match(/\d+\.?\d*/); });
  721. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td style="text-align:right;">Totals:</td>' +
  722. '<td style="text-align:center;">' + (Object.keys(this.collation || r).length-7) + ' Requesters</td>' +
  723. '<td style="text-align:right;">' + (this.collation || r).totalEntries + '</td>'+
  724. '<td style="text-align:right;">$' + Number(Math.decRound((this.collation || r).totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  725. } else { // default
  726. if (!simple)
  727. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th colspan="3"></th>' +
  728. '<th colspan="2" title="Bonuses must be added in manually.\n\nClick inside' +
  729. 'the cell to edit, click out of the cell to save">Reward</th><th colspan="3"></th></tr>'+
  730. '<tr class="hdbHeaderRow">' +
  731. '<th style="min-width:65">Date</th><th>Requester</th><th>HIT title</th><th style="font-size:10px;">Pay</th>'+
  732. '<th style="font-size:10px;"><span class="helpSpan" title="Click the cell to edit.\nIts value is automatically saved">'+
  733. 'Bonus</span></th><th>Status</th><th>'+
  734. '<span class="helpSpan" title="Auto-approval times">AA</span></th><th>Feedback</th></tr></thead><tbody>');
  735.  
  736. this.results.sort(function(a,b) { return a.date === b.date ?
  737. (a.requesterName.toLowerCase() > b.requesterName.toLowerCase() ? 1 : -1) : a.date < b.date ? -1 : 1; });
  738. for (entry of this.results) {
  739. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  740. var _stColor = ~entry.status.search(/(paid|approved)/i) ? "green" :
  741. entry.status === "Pending Approval" ? "orange" : "red";
  742. var href = MTURK_BASE+'contact?requesterId='+entry.requesterId+'&requesterName='+entry.requesterName+
  743. '&subject=Regarding+Amazon+Mechanical+Turk+HIT+'+entry.hitId;
  744.  
  745. if (!simple)
  746. htmlTxt.push('<tr '+_trClass+' data-id="'+entry.hitId+'">'+
  747. '<td width="74px">' + entry.date + '</td><td style="max-width:145px;">' +
  748. '<a target="_blank" title="Contact this requester" href="'+href+'">' + entry.requesterName + '</a></td>' +
  749. '<td width="375px" title="HIT ID: '+entry.hitId+'">' +
  750. '<span title="Add a note" id="note-'+entry.hitId+'" style="cursor:pointer;">&nbsp;&#128221;&nbsp;</span>' +
  751. entry.title + '</td><td style="text-align:right">' + _parseRewards(entry.reward,"pay") + '</td>' +
  752. '<td style="text-align:right" class="bonusCell" title="Click to add/edit" contenteditable="true" data-hitid="'+entry.hitId+'">' +
  753. (+_parseRewards(entry.reward,"bonus") ? _parseRewards(entry.reward,"bonus") : "") +
  754. '</td><td style="color:'+_stColor+';text-align:center">' + entry.status + '</td>' +
  755. '<td>' + Utils.ftime(entry.autoAppTime) + '</td><td>' + entry.feedback + '</td></tr>');
  756. else
  757. htmlTxt.push('<tr>' + '<td class="nowrap" title="'+entry.requesterName+'" style="max-width:130">'+entry.requesterName+'</td>' +
  758. '<td class="nowrap" title="'+entry.title+'" style="max-width:520">'+entry.title+'</td><td>'+ _parseRewards(entry.reward,"pay") +
  759. '</td><td class="nowrap" title="'+entry.status+'" style="max-width:60">'+ entry.status+'</td></tr>');
  760. }
  761.  
  762. if (!simple) {
  763. r = this.collation || this.collate(this.results,"requesterId");
  764. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td></td>' +
  765. '<td style="text-align:right">Totals:</td><td style="text-align:center;">' + r.totalEntries + ' HITs</td>' +
  766. '<td style="text-align:right">$' + Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td>' +
  767. '<td style="text-align:right">$' + Number(Math.decRound(r.totalBonus,2)).toFixed(2) + '</td>' +
  768. '<td colspan="3"></td></tr></tfoot>');
  769. }
  770. }
  771. return htmlTxt.join('');
  772. };//}}} formatHTML
  773. this.formatCSV = function(type) {//{{{
  774. var csvTxt = [], entry = null, delimiter="\t";
  775. if (type === "daily") {
  776. csvTxt.push( ["Date", "Submitted", "Approved", "Rejected", "Pending", "Earnings\n"].join(delimiter) );
  777. for (entry of this.results) {
  778. csvTxt.push( [entry.date, entry.submitted, entry.approved, entry.rejected,
  779. entry.pending, Number(entry.earnings).toFixed(2)+"\n"].join(delimiter) );
  780. }
  781. csvToFile(csvTxt, "hitdb_dailyOverview.csv");
  782. } else if (type === "pending" || type === "requester") {
  783. csvTxt.push( ["RequesterId","Requester", (type === "pending" ? "Pending" : "HITs"), "Rewards\n"].join(delimiter) );
  784. var r = this.collation || this.collate(this.results,"requesterId");
  785. for (var k in r) {
  786. if (!~k.search(/total/) && r.hasOwnProperty(k))
  787. csvTxt.push( [k, r[k][0].requesterName, r[k].length, Number(Math.decRound(r[k].pay,2)).toFixed(2)+"\n"].join(delimiter) );
  788. }
  789. csvToFile(csvTxt, "hitdb_"+type+"Overview.csv");
  790. } else {
  791. csvTxt.push(["hitId","date","requesterName","requesterId","title","pay","bonus","status","autoAppTime","feedback\n"].join(delimiter));
  792. for (entry of this.results) {
  793. csvTxt.push([entry.hitId, entry.date, entry.requesterName, entry.requesterId, entry.title, _parseRewards(entry.reward,"pay"),
  794. (+_parseRewards(entry.reward,"bonus") ? _parseRewards(entry.reward,"bonus") : ""),
  795. entry.status, entry.autoAppTime, entry.feedback.replace(/[\t\n]/g,' ')+"\n"].join(delimiter));
  796. }
  797. csvToFile(csvTxt, "hitdb_queryResults.csv");
  798. }
  799.  
  800. return '';//"<pre>"+csvTxt.join('')+"</pre>";
  801.  
  802. function csvToFile(csv, filename) {
  803. var blob = new Blob(csv, {type: "text/csv", endings: "native"}),
  804. dl = document.createElement("A");
  805. dl.href = URL.createObjectURL(blob);
  806. dl.download = filename;
  807. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  808. dl.click(); // so we make it so and click,
  809. dl.remove(); // then immediately remove it
  810. return dl;
  811. }
  812. };//}}} formatCSV
  813. this.include = function(value) {
  814. this.results.push(value);
  815. };
  816. this.collate = function(data, index) {//{{{
  817. var r = {
  818. totalPay: 0, totalBonus: 0, totalEntries: data.length,
  819. totalSub: 0, totalApp: 0, totalRej: 0, totalPen: 0
  820. };
  821. for (var e of data) {
  822. if (!r[e[index]]) {
  823. r[e[index]] = [];
  824. Object.defineProperty(r[e[index]], "pay", {value: 0, enumerable: false, configurable: true, writable: true});
  825. }
  826. r[e[index]].push(e);
  827.  
  828. if (index === "stats") {
  829. r.totalSub += e.submitted;
  830. r.totalApp += e.approved;
  831. r.totalRej += e.rejected;
  832. r.totalPen += e.pending;
  833. r.totalPay += e.earnings;
  834. } else {
  835. r[e[index]].pay += (+_parseRewards(e.reward,"pay"));
  836. r.totalPay += (+_parseRewards(e.reward,"pay"));
  837. r.totalBonus += (+_parseRewards(e.reward,"bonus"));
  838. }
  839. }
  840. return r;
  841. };//}}} _collate
  842.  
  843. function _parseRewards(rewards,value) {//{{{
  844. if (!isNaN(rewards)) {
  845. if (value === "pay")
  846. return Number(rewards).toFixed(2);
  847. else
  848. return "0.00";
  849. } else {
  850. if (value === "pay")
  851. return Number(rewards.pay).toFixed(2);
  852. else
  853. return Number(rewards.bonus).toFixed(2);
  854. }
  855. } //}}} _parse
  856. },//}}} databaseresult
  857.  
  858. DashboardUI = {//{{{
  859. draw: function() {//{{{
  860. var controlPanel = document.createElement("TABLE"),
  861. insertionNode = document.querySelector(".footer_separator").previousSibling;
  862. document.body.insertBefore(controlPanel, insertionNode);
  863. controlPanel.width = "760";
  864. controlPanel.align = "center";
  865. controlPanel.id = "hdbControlPanel";
  866. controlPanel.cellSpacing = "0";
  867. controlPanel.cellPadding = "0";
  868. controlPanel.innerHTML = '<tr height="25px"><td width="10" bgcolor="#7FB448" style="padding-left: 10px;"></td>' +
  869. '<td class="white_text_14_bold" style="padding-left:10px; background-color:#7FB448;">' +
  870. 'HIT Database Mk. II&nbsp;<a href="https://greasyfork.org/en/scripts/11733-mturk-hit-database-mk-ii#userGuide" '+
  871. 'class="whatis" target="turkPopUp" onclick="customPopup(this, 500, 400)">' +
  872. '(What\'s this?)</a></td></tr>' +
  873. '<tr><td class="container-content" colspan="2">' +
  874. '<div style="text-align:center;" id="hdbDashboardInterface">' +
  875. '<button id="hdbBackup" title="Export your entire database!\nPerfect for moving between computers or as a periodic backup">Create Backup</button>' +
  876. '<button id="hdbRestore" title="Import data from an external file" style="margin:5px">Import</button>' +
  877. '<button id="hdbUpdate" title="Update... the database" style="color:green;">Update Database</button>' +
  878. '<input id="hdbFileInput" type="file" style="display:none"/>' +
  879. '<br>' +
  880. '<button id="hdbPending" title="Summary of all pending HITs\n Can be exported as CSV" style="margin: 0px 5px 5px;">Pending Overview</button>' +
  881. '<button id="hdbRequester" title="Summary of all requesters\n Can be exported as CSV" style="margin: 0px 5px 5px;">Requester Overview</button>' +
  882. '<button id="hdbDaily" title="Summary of each day you\'ve worked\nCan be exported as CSV" style="margin:0px 5px 5px;">Daily Overview</button>' +
  883. '<br>' +
  884. '<label>Find </label>' +
  885. '<select id="hdbStatusSelect"><option value="*">ALL</option>' +
  886. '<option value="Pending Approval" style="color: orange;">Pending Approval</option>' +
  887. '<option value="Rejected" style="color: red;">Rejected</option>' +
  888. '<option value="Approved - Pending Payment" style="color:green;">Approved - Pending Payment</option>' +
  889. '<option value="(Paid|Approved)" style="color:green;">Paid OR Approved</option></select>' +
  890. '<label> HITs matching: </label><input id="hdbSearchInput" title="Query can be HIT title, HIT ID, or requester name" />' +
  891. '<button id="hdbSearch">Search</button>' +
  892. '<br>' +
  893. '<label>from date </label><input id="hdbMinDate" type="date" size="10" title="Specify a date, or leave blank">' +
  894. '<label> to </label><input id="hdbMaxDate" type="date" size="10" title="Specify a date, or leave blank">' +
  895. '<label for="hdbCSVInput" title="Export results as CSV file" style="margin-left:50px; vertical-align:middle;">export CSV</label>' +
  896. '<input id="hdbCSVInput" title="Export results as CSV file" type="checkbox" style="vertical-align:middle;">' +
  897. '<br>' +
  898. '<label id="hdbStatusText"></label>' +
  899. '<div id="hdbProgressBar">' +
  900. '<div id="hdbB1" class="ball"></div><div id="hdbB2" class="ball"></div>' +
  901. '<div id="hdbB3" class="ball"></div><div id="hdbB4" class="ball"></div>' +
  902. '</div>' +
  903. '</div></td></tr>';
  904.  
  905. var searchResults = document.createElement("DIV");
  906. searchResults.align = "center";
  907. searchResults.id = "hdbSearchResults";
  908. searchResults.style.display = "block";
  909. searchResults.innerHTML =
  910. '<span class="hdbResControl" id="hdbResClear">[ clear results ]</span>' +
  911. '<span class="hdbTablePagination" id="hdbPageTop"></span><br>' +
  912. '<table cellSpacing="0" cellpadding="2" width="760" id="hdbResultsTable"></table>' +
  913. '<span class="hdbResControl" id="hdbVpTop">Back to top</span>' +
  914. '<span class="hdbTablePagination" id="hdbPageBot"></span><br>';
  915. document.body.insertBefore(searchResults, insertionNode);
  916. },//}}} dashboardUI::draw
  917.  
  918. initClickables: function() {//{{{
  919. var updateBtn = document.getElementById("hdbUpdate"),
  920. backupBtn = document.getElementById("hdbBackup"),
  921. restoreBtn = document.getElementById("hdbRestore"),
  922. fileInput = document.getElementById("hdbFileInput"),
  923. exportCSVInput = document.getElementById("hdbCSVInput"),
  924. searchBtn = document.getElementById("hdbSearch"),
  925. searchInput = document.getElementById("hdbSearchInput"),
  926. pendingBtn = document.getElementById("hdbPending"),
  927. reqBtn = document.getElementById("hdbRequester"),
  928. dailyBtn = document.getElementById("hdbDaily"),
  929. fromdate = document.getElementById("hdbMinDate"),
  930. todate = document.getElementById("hdbMaxDate"),
  931. statusSelect = document.getElementById("hdbStatusSelect"),
  932. searchResults = document.getElementById("hdbSearchResults"),
  933. resultsTable = document.getElementById("hdbResultsTable"),
  934. isGecko = /Gecko\/\d+/.test(navigator.userAgent);
  935.  
  936. searchResults.firstChild.onclick = function() { //{{{ clear results
  937. resultsTable.innerHTML = null; qc.sr = [];
  938. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  939. if (~d.search(/page/i)) searchResults.querySelector('#'+d).innerHTML = "";
  940. document.getElementById(d).style.display = "none";
  941. }
  942. };//}}}
  943. document.getElementById("hdbVpTop").onclick = function() { autoScroll("#hdbControlPanel"); };
  944.  
  945. updateBtn.onclick = function() { //{{{
  946. if (!HITStorage.db) { Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); return; }
  947. Utils.disableButtons(['hdbUpdate'], true);
  948. Progress.show();
  949. metrics.dbupdate = new Metrics("database_update");
  950. HITStorage.fetch(MTURK_BASE+"status");
  951. Status.message = "fetching status page....";
  952. };//}}}
  953. exportCSVInput.addEventListener("click", function() {//{{{
  954. var a = document.getElementById('hdbAnalytics');
  955. if (a && a.checked) a.click();
  956. if (exportCSVInput.checked) {
  957. searchBtn.textContent = "Export CSV";
  958. pendingBtn.textContent += " (csv)";
  959. reqBtn.textContent += " (csv)";
  960. dailyBtn.textContent += " (csv)";
  961. }
  962. else {
  963. searchBtn.textContent = "Search";
  964. pendingBtn.textContent = pendingBtn.textContent.replace(" (csv)","");
  965. reqBtn.textContent = reqBtn.textContent.replace(" (csv)","");
  966. dailyBtn.textContent = dailyBtn.textContent.replace(" (csv)", "");
  967. }
  968. });//}}}
  969. if (isGecko) {//{{{
  970. fromdate.addEventListener("focus", function() {
  971. var offsets = Utils.getPosition(this, true);
  972. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  973. });
  974. todate.addEventListener("focus", function() {
  975. var offsets = Utils.getPosition(this, true);
  976. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  977. });
  978. }//}}}
  979.  
  980. backupBtn.onclick = HITStorage.backup;
  981. restoreBtn.onclick = function() { fileInput.value = ''; fileInput.click(); };
  982. fileInput.onchange = FileHandler.delegate;//processFile;
  983. searchInput.onkeydown = function(e) { if (e.keyCode === 13) searchBtn.click(); };
  984.  
  985. searchBtn.addEventListener('click', function(e) {//{{{
  986. if (!/^[se]/i.test(e.target.textContent)) return;
  987. var r = this.getRange(), query = searchInput.value.trim().split(':');
  988. // make searching faster and more efficient in large databases
  989. if (!/(req|id|hitid)$/i.test(query[0])) {
  990. query = query.join('');
  991. if (query.length === 30 && !/\s/.test(query)) {
  992. r.range = window.IDBKeyRange.only(query.toUpperCase());
  993. r.index = null;
  994. }
  995. } else {
  996. query[1] = /req/.test(query[0]) ? query[1].trimLeft() : query[1].trimLeft().toUpperCase();
  997. r.index = /req/.test(query[0]) ? 'requesterName' : null;
  998. r.range = window.IDBKeyRange
  999. .bound(query[1], query[1].slice(0,query[1].length-1) + String.fromCharCode(query[1].charCodeAt(query[1].length-1)+1));
  1000. query = query[0].split(/(req|id|hitid)$/)[0].trimRight();
  1001. }
  1002.  
  1003. var _filter = { status: statusSelect.value, query: query.length > 0 ? query : "*" };
  1004. var _opt = { index: r.index, range: r.range, dir: r.dir, filter: _filter, progress: true };
  1005.  
  1006. _dbaccess("search", ["HIT", _opt], function(r) {
  1007. var limiter = 500,
  1008. _cb = function(slice) {
  1009. for (var _r of slice)
  1010. HITStorage.recall("NOTES", { index: "hitId", range: window.IDBKeyRange.only(_r.hitId) }).then(noteHandler.bind(null,"attach"));
  1011. var _nodes = [document.querySelectorAll(".bonusCell"), document.querySelectorAll('span[id^="note-"]')];
  1012. for (var i=0;i<_nodes[0].length;i++) {
  1013. var bonus = _nodes[0][i],
  1014. note = _nodes[1][i];
  1015. bonus.dataset.initial = bonus.textContent;
  1016. bonus.onkeydown = updateBonus;
  1017. bonus.onblur = updateBonus;
  1018. note.onclick = noteHandler.bind(null,"new");
  1019. }
  1020. };
  1021. if (exportCSVInput.checked)
  1022. resultsTable.innerHTML = r.formatCSV();
  1023. else if (r.results.length > limiter) {
  1024. var collation = r.collate(r.results, "requesterId");
  1025. do { qc.sr.push(new DBResult(r.results.splice(0,limiter), collation)) } while (r.results.length);
  1026. resultConstrain(qc.sr, 0, "default", _cb);
  1027. } else
  1028. resultConstrain(r, 0, "default", _cb);
  1029. });
  1030. }.bind(this)); //}}} search button click event
  1031. //{{{ overview buttons
  1032. pendingBtn.onclick = function() {
  1033. var _filter = { date: [fromdate.value, todate.value], query: searchInput.value.trim().length > 0 ? searchInput.value : "*" },
  1034. _opt = { index: "status", dir: "prev", range: window.IDBKeyRange.only("Pending Approval"), filter: _filter, progress: true };
  1035.  
  1036. _dbaccess("pending", ["HIT", _opt], function(r) {
  1037. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("pending") : r.formatHTML("pending");
  1038. var expands = document.querySelectorAll(".hdbExpandRow");
  1039. for (var el of expands)
  1040. el.onclick = showHiddenRows;
  1041. });
  1042. }.bind(this); //pending overview click event
  1043. reqBtn.onclick = function() {
  1044. var r = this.getRange();
  1045. var _opt = { index: r.index, range: r.range, progress: true };
  1046.  
  1047. _dbaccess("requester", ["HIT", _opt], function(r) {
  1048. var limiter = 100,
  1049. _cb = function() {
  1050. var expands = document.querySelectorAll(".hdbExpandRow");
  1051. for (var el of expands)
  1052. el.onclick = showHiddenRows;
  1053. };
  1054. if (exportCSVInput.checked)
  1055. resultsTable.innerHTML = r.formatCSV("requester");
  1056. else if (r.results.length > limiter) {
  1057. var collation = r.collate(r.results, "requesterId"), _r = [], count = 0;
  1058. var keys = Object.keys(collation)
  1059. .filter(function(e) { return !/total/.test(e); })
  1060. .sort(function(a,b) { return collation[b].pay - collation[a].pay; });
  1061. keys.forEach(function(key){
  1062. if (++count > limiter) {
  1063. qc.sr.push(new DBResult(_r, collation));
  1064. count = 0; _r = [];
  1065. } else _r = _r.concat(collation[key]);
  1066. });
  1067. qc.sr.push(new DBResult(_r, collation));
  1068. resultConstrain(qc.sr, 0, "requester", _cb);
  1069. } else
  1070. resultConstrain(r, 0, "requester", _cb);
  1071. });
  1072. }.bind(this); //requester overview click event
  1073. dailyBtn.onclick = function() {
  1074. var r = this.getRange("*");
  1075. _dbaccess("daily", ["STATS", { range: r.range, dir: "prev", progress: true }], function(r) {
  1076. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("daily") : r.formatHTML("daily");
  1077. var expands = document.querySelectorAll(".hdbExpandRow");
  1078. for (var el of expands)
  1079. el.onclick = showHitsByDate;
  1080. });
  1081. }.bind(this); //daily overview click event
  1082. //}}}
  1083.  
  1084. function _dbaccess(method, rargs, tfn) {//{{{
  1085. if (!HITStorage.db) { Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); return; }
  1086. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], true);
  1087. searchResults.firstChild.click();
  1088. Status.push("Preparing database...", "black");
  1089. metrics.dbrecall = new Metrics("database_recall::"+method);
  1090. metrics.dbrecall.mark("data retrieval", "start");
  1091.  
  1092. HITStorage.recall(rargs[0],rargs[1]).then(function(r) {
  1093. metrics.dbrecall.mark("data retrieval", "end");
  1094. Status.message = "Building HTML...";
  1095. try {
  1096. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  1097. if (exportCSVInput.checked || (~d.search(/page/i) && !/^[sr]/.test(method))) continue;
  1098. document.getElementById(d).style.display = "initial";
  1099. }
  1100. metrics.dbrecall.mark("HTML construction", "start");
  1101. tfn(r);
  1102. metrics.dbrecall.mark("HTML construction", "end");
  1103. } catch(e) {
  1104. Utils.errorHandler(e);
  1105. } finally {
  1106. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], false);
  1107. autoScroll("#hdbSearchResults");
  1108. Status.push("Done!", "green");
  1109. Progress.hide();
  1110. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1111. }
  1112. });
  1113. }//}}} _dbaccess
  1114. },//}}} dashboardUI::initClickables
  1115.  
  1116. getRange: function(status) {//{{{
  1117. var fromdate = document.getElementById("hdbMinDate"),
  1118. todate = document.getElementById("hdbMaxDate"),
  1119. statusSelect = document.getElementById("hdbStatusSelect");
  1120. var _min = fromdate.value.length > 3 ? fromdate.value : undefined,
  1121. _max = todate.value.length > 3 ? todate.value : undefined;
  1122. status = status || statusSelect.value;
  1123. var _range =
  1124. (_min === undefined && _max === undefined) ?
  1125. (status.length > 1 && !~status.search(/\(/) ? window.IDBKeyRange.only(status) : null) :
  1126. (_min === undefined) ? window.IDBKeyRange.upperBound(_max) :
  1127. (_max === undefined) ? window.IDBKeyRange.lowerBound(_min) :
  1128. (_max < _min) ? window.IDBKeyRange.bound(_max,_min) : window.IDBKeyRange.bound(_min,_max),
  1129. _index = _min === undefined && _max === undefined && status.length > 1 && !~status.search(/\(/) ? "status" : "date";
  1130. return { min: _min, max: _max, range: _range, dir: _max < _min ? "prev" : "next", index: _index };
  1131. }//}}} dashboardUI::getRange
  1132. },//}}} dashboard
  1133. FileHandler = { //{{{
  1134. //
  1135. // TODO: JSON integrity check
  1136. //
  1137. delegate: function(e) {//{{{
  1138. var f = e.target.files;
  1139. if (f.length && ~f[0].name.search(/\.(bak|csv|json)$/i)/* && ~f[0].type.search(/(text|json)/)*/) {
  1140. var reader = new FileReader(), testing = true, isCsv = false;
  1141. metrics.dbimport = new Metrics("file_import");
  1142.  
  1143. reader.readAsText(f[0].slice(0,10));
  1144. reader.onload = function(e) {
  1145. var r = e.target.result;
  1146. if (testing && !~r.search(/(STATS|NOTES|HIT)/)) { // failed json check, test if csv
  1147. console.log("failed json integrity:", r, "\nchecking csv schema...");
  1148. if (!~r.search(/hitId/)) { // failed csv check, return error
  1149. console.log("failed csv integrity:", r, "\naborting");
  1150. return Utils.errorHandler(new TypeError("Invalid data structure"));
  1151. } else { // passed initial csv check, parse full file
  1152. console.log("deferring to csv parser");
  1153. isCsv = true;
  1154. testing = false;
  1155. Progress.show();
  1156. reader.readAsText(f[0]);
  1157. }
  1158. } else if (testing) {
  1159. testing = false;
  1160. Progress.show();
  1161. reader.readAsText(f[0]);
  1162. } else {
  1163. if (isCsv) this.csv.fromFile(r);
  1164. else HITStorage.write(JSON.parse(r), cbImport);
  1165. }
  1166. }.bind(FileHandler); // reader.onload
  1167. } else if (f.length)
  1168. Utils.errorHandler(new TypeError("Unsupported file format"));
  1169. },//}}}
  1170. csv: {//{{{
  1171. fromFile: function(r) {//{{{
  1172. var validKeys = ["autoAppTime","date","feedback","hitId","requesterId","requesterName","reward","pay","bonus","status","title"],
  1173. //lines = r.replace(/\r?\n^(?!"?[A-Z0-9]{30})/gm,' ').split(/\r?\n/);
  1174. lines = r.split(/\r?\n(?="?[A-Z0-9]{30})/);
  1175. this.delimiter = /^"/.test(lines[0]) ? r.substr(7,1) : r.substr(5,1);
  1176. this.header = lines.splice(0,1)[0].replace(new RegExp(`([" ]|${this.delimiter}$)`,'g'),'').split(this.delimiter);
  1177. this.data = { HIT:[] };
  1178.  
  1179. console.log('delimiter:',this.delimiter==='\t'?'tab':this.delimiter,'\nlines:',lines.length,'\nheader:',this.header);
  1180. if (!lines.length) return Utils.errorHandler(new Error("CSV file must contain at least one record"));
  1181. // make sure header keys are valid
  1182. for (var key of this.header)
  1183. if (!~validKeys.indexOf(key)) {
  1184. Progress.hide();
  1185. return Utils.errorHandler(new TypeError("Invalid key '"+key+"' found in column header"));
  1186. }
  1187. this.core(lines);
  1188. },//}}}
  1189. core: function(lr, syn) {//{{{
  1190. syn = syn || false;
  1191. var badLines = [],
  1192. deq = function(str) { if (/^"/.test(str) && /"$/.test(str)) return str.replace(/(^"|"$)/g,''); else return str;},
  1193. qfix = arr => arr.reduce((a,b) => {
  1194. if (a.length && /^".+[^"]$/.test(a[a.length-1])) {
  1195. a[a.length-1] = a[a.length-1] + this.delimiter + b;
  1196. return a;
  1197. } else return a.concat(b);
  1198. }, []);
  1199. for (var line of lr) {
  1200. var record = {};
  1201. line = line.split(this.delimiter);
  1202. if (line.length <= 1) continue;
  1203. if (line.length !== this.header.length) {
  1204. // attempt to resolve delimiter conflicts within field values
  1205. line = qfix(line);
  1206. while (line.length > this.header.length) {
  1207. var datum = line.pop();
  1208. if (/\S/.test(deq(datum))) { line.push(datum); break; }
  1209. }
  1210. if (line.length !== this.header.length) {
  1211. badLines.push({record: line, reason: "SyntaxError: Number of field do not match number of columns"}); continue; }
  1212. }
  1213. // convert into usable JSON
  1214. for (var i=0;i<line.length;i++) {
  1215. if (/(pay|bonus|reward|autoAppTime)/.test(this.header[i]) && isNaN(+line[i])) {
  1216. badLines.push({record: line, reason: `TypeError: Value in '${this.header[i]}' is not a number.`}); break; }
  1217. if (this.header[i] === 'hitId' && (/\W/.test(deq(line[i])) || deq(line[i]).length !== 30)) {
  1218. badLines.push({record: line, reason: "TypeError: Invalid hitId."}); break; }
  1219. if (this.header[i] === 'date' && !/\d{4}-\d{2}-\d{2}/.test(line[i])) {
  1220. badLines.push({record: line, reason: "TypeError: Invalid date. Dates must be in ISO format (YYYY-MM-DD)."}); break; }
  1221.  
  1222. if (this.header[i] === 'pay' || this.header[i] === 'bonus') {
  1223. record.reward = record.reward || {};
  1224. record.reward[this.header[i]] = +line[i];
  1225. continue;
  1226. } else if (this.header[i] === 'reward')
  1227. record[this.header[i]] = +line[i];
  1228. else
  1229. record[this.header[i]] = deq(line[i]);
  1230. } // for each field
  1231. if (!syn && !badLines.find(v => v.record === line)) this.data.HIT.push(record);
  1232. } // for each record
  1233. if (syn) return !badLines.length;
  1234. else if (badLines.length) { console.warn('SyntaxError'); console.dir(badLines); this.manualFix(badLines); }
  1235. else HITStorage.write(this.data, cbImport);
  1236. },//}}}
  1237. manualFix: function(lr) {//{{{
  1238. var div = document.body.appendChild(document.createElement('DIV')),
  1239. title = div.appendChild(document.createElement('P')),
  1240. divInner = div.appendChild(document.createElement('DIV')),
  1241. buttons = div.appendChild(document.createElement('P')),
  1242. trimSansTab = function(str) {
  1243. var c = "[ \f\n\r\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+";
  1244. return str.replace(new RegExp("^"+c),'').replace(new RegExp(c+"$"),'');
  1245. },
  1246. kdFn = function(e) {
  1247. if (e.keyCode === 9) {// tab
  1248. e.preventDefault();
  1249. var zs = e.target.selectionStart,
  1250. ze = e.target.selectionEnd;
  1251. e.target.value = e.target.value.substr(0,zs) + '\t' + e.target.value.substr(ze);
  1252. }
  1253. e.target.style.height = '1px';
  1254. e.target.style.height = e.target.scrollHeight + 10 +'px';
  1255. },
  1256. blurFn = function(e) {
  1257. var check = this.core([trimSansTab(e.target.value)],true);
  1258. if (check) e.target.style.background = '#9EFF9E'; else e.target.style.background = 'white';
  1259. }.bind(this);
  1260. title.outerHTML = '<p style="margin:0;text-align:center;font-weight:bold;font-size:1.2em">Failed lines</p>' +
  1261. '<p style="text-align:center;font-weight:bold;font-size:0.9em;margin:1%">' + this.header.join(this.delimiter)+'</p>';
  1262. div.style.cssText = "z-index:5; position:fixed; top:50%;left:50%; padding:0.7%; width:650px; resize:both; overflow:auto;" +
  1263. "background:rgba(204,204,204,0.88); box-shadow: 0px 0px 15px 2px #000; margin-right:-50%; transform:translate(-50%, -50%);";
  1264. divInner.style.cssText = "position:relative; max-height:350px; overflow:auto;";
  1265. for (var v of lr) {
  1266. divInner.appendChild(document.createTextNode(v.reason));
  1267. var ta = divInner.appendChild(document.createElement('TEXTAREA'));
  1268. ta.style.cssText = "resize:none; overflow:hidden; width:100%; display:block";
  1269. ta.onkeydown = kdFn;
  1270. ta.onblur = blurFn;
  1271. ta.value = v.record.join(this.delimiter);
  1272. ta.style.height = ta.scrollHeight + 10 + 'px';
  1273. }
  1274. buttons.style.cssText = "margin:1% auto; text-align:center;";
  1275. buttons.innerHTML = '<button id="fretry" title="Retry failed lines.")">Retry</button> ' +
  1276. '<button id="fskip" title="Skip these failed lines and import the rest to the database.">Skip</button> ' +
  1277. '<button id="fcancel" title="Cancel the entire import process">Cancel</button><br>' +
  1278. 'Modify the above entries and retry, or skip them, or cancel the entire import.';
  1279. buttons.querySelector('#fretry').onclick = function() {
  1280. var l = [];
  1281. for (var el of div.querySelectorAll('textarea')) l.push(trimSansTab(el.value));
  1282. this.core(l);
  1283. div.remove();
  1284. }.bind(this);
  1285. buttons.querySelector('#fskip').onclick = function() { div.remove(); HITStorage.write(this.data, cbImport); }.bind(this);
  1286. buttons.querySelector('#fcancel').onclick = function() { div.remove(); this.data = null; Progress.hide();}.bind(this);
  1287. }//}}}
  1288. }//}}} FileHandler::csv
  1289. },//}}}
  1290.  
  1291. WorkingTime = {//{{{
  1292. //
  1293. // TODO
  1294. //
  1295. record: function(data) {
  1296. var group = Date.now(), times = JSON.parse(localStorage.getItem('hitdb_workTime')) || {};
  1297. if (Object.keys(times).length) { // times has entries
  1298. for (var k in times) { if (times.hasOwnProperty(k)) {
  1299. if (times[k].active) { group = k; break; }
  1300. }}
  1301. } else times[group] = { active: true, hits: [] }; // times empty or newly created
  1302. times[group].hits.push({ hitId: data.hitId, start: Date.now(), end: null, duration: null, next: data.next });
  1303. },
  1304. report: function() {
  1305. var times = JSON.parse(localStorage.getItem('hitdb_workTime')), hit,
  1306. node = document.querySelector('#alertBox'),
  1307. p = node.appendChild(document.createElement('P'));
  1308.  
  1309. if (!times) return;
  1310. for (var k in times) { if (times.hasOwnProperty(k)) {
  1311. hit = times[k].hits.find(v => ~document.location.search.indexOf(v.next));
  1312. }}
  1313. p.style.paddingLeft = '35px';
  1314. },
  1315. };//}}}
  1316.  
  1317. /*
  1318. *
  1319. *
  1320. *
  1321. *
  1322. *///{{{
  1323. if (document.location.pathname === "/mturk/dashboard") {
  1324. DashboardUI.draw();
  1325. DashboardUI.initClickables();
  1326. var dbh = window.indexedDB.open(DB_NAME, DB_VERSION);
  1327. dbh.onerror = function(e) { Utils.errorHandler(e.target.error); };
  1328. dbh.onupgradeneeded = HITStorage.versionChange;
  1329. dbh.onsuccess = INITDB;
  1330.  
  1331. ProjectedEarnings.updateDate();
  1332. ProjectedEarnings.draw(true);
  1333.  
  1334. var Status = {
  1335. node: document.getElementById("hdbStatusText"),
  1336. get message() { return this.node.textContent; },
  1337. set message(str) { this.node.textContent = str; },
  1338. get color() { return this.node.style.color; },
  1339. set color(c) { this.node.style.color = c; },
  1340. push: function(m,c) { c = c || "black"; this.message = m; this.color = c; }
  1341. }, Progress = {
  1342. node: document.getElementById("hdbProgressBar"),
  1343. hide: function() { this.node.style.display = "none"; },
  1344. show: function() { this.node.style.display = "block"; }
  1345. };
  1346. // export some variables for external extensions
  1347. self.Status = Status; self.Progress = Progress; self.Metrics = Metrics; self.Math.decRound = Math.decRound;
  1348. } else { // page is not dashboard
  1349. window.indexedDB.open(DB_NAME).onsuccess = function() { HITStorage.db = this.result; beenThereDoneThat(); };
  1350. }
  1351. /*}}}
  1352. *
  1353. *
  1354. *
  1355. *
  1356. */
  1357.  
  1358. // {{{ css injection
  1359. var css = "<style type='text/css'>" +
  1360. "#hdbProgressBar {margin:auto; width:250px; height:15px; position:relative; display:none;}" +
  1361. ".ball {position:absolute; left:0; width:12px; height:12px; border-radius:5px;" +
  1362. "animation:kfpballs 2s cubic-bezier(0.24,0.77,0.68,1) infinite;" +
  1363. "background:linear-gradient(222deg, rgba(208,69,247,0), rgba(208,69,247,1), rgba(69,197,247,1), rgba(69,197,247,0))}" +
  1364. "#hdbB2{animation-delay:.19s} #hdbB3{animation-delay:.38s} #hdbB4{animation-delay:.55s}" +
  1365. "@keyframes kfpballs {0% {left:0%;opacity:1} 50% {left:98%;opacity:0.2} 100% {left:0%;opacity:1}}" +
  1366. ".hitdbRTButtons {border:1px solid; font-size: 10px; height: 18px; padding-left: 5px; padding-right: 5px; background: pink;}" +
  1367. ".hitdbRTButtons-green {background: lightgreen;}" +
  1368. ".hitdbRTButtons-large {width:80px;}" +
  1369. ".hdbCalControls {cursor:pointer;} .hdbCalControls:hover {color:#c27fcf;}" +
  1370. ".hdbCalCells {background:#f0f6f9; height:19px}" +
  1371. ".hdbCalDays {cursor:pointer; text-align:center;} .hdbCalDays:hover {background:#7fb4cf; color:white;}" +
  1372. ".hdbDayHeader {width:26px; text-align:center; font-weight:bold; font-size:12px; background:#f0f6f9;}" +
  1373. ".hdbCalHeader {background:#7fb4cf; color:white; font-weight:bold; text-align:center; font-size:11px; padding:3px 0px;}" +
  1374. "#hdbCalendarPanel {position:absolute; z-index:10; box-shadow:-2px 3px 5px 0px rgba(0,0,0,0.68);}" +
  1375. ".hdbExpandRow {cursor:pointer; color:blue;}" +
  1376. ".hdbTotalsRow {background:#CCC; color:#369; font-weight:bold;}" +
  1377. ".hdbHeaderRow {background:#7FB448; font-size:12px; color:white;}" +
  1378. ".helpSpan {border-bottom:1px dotted; cursor:help;}" +
  1379. ".hdbResControl {border-bottom:1px solid; color:#c60; cursor:pointer; display:none;}" +
  1380. ".hdbTablePagination {margin-left:15em; color:#c60; display:none;}" +
  1381. ".spin {animation: kfspin 0.7s infinite linear; font-weight:bold;}" +
  1382. "@keyframes kfspin { 0% { transform: rotate(0deg) } 100% { transform: rotate(359deg) } }" +
  1383. ".spin:before{content:'*'}" +
  1384. ".nowrap {white-space:nowrap; overflow:hidden; text-overflow:ellipsis}" +
  1385. "</style>";
  1386. document.head.innerHTML += css;
  1387. // }}}
  1388.  
  1389. function resultConstrain(data, index, type, callback) {//{{{
  1390. data = data || qc.sr;
  1391.  
  1392. var table = document.getElementById("hdbResultsTable"),
  1393. rslice = data.length ? data[index].results : data.results,
  1394. pager = [document.getElementById("hdbPageTop"), document.getElementById("hdbPageBot")],
  1395. sopt = [],
  1396. _f = function(e) { resultConstrain(null,e.target.value,type,callback); };
  1397. pager[0].innerHTML = ''; pager[1].innerHTML = '';
  1398.  
  1399. if (data instanceof DBResult)
  1400. table.innerHTML = data.formatHTML(type);
  1401. else {
  1402. table.innerHTML = data[index].formatHTML(type);
  1403. pager[0].innerHTML = '<span style="cursor:pointer;">' + (index > 0 ? '&#9664; Prev' : '') + '</span> ' +
  1404. '<span style="cursor:pointer;">' + (+index+1 === data.length ? '' : 'Next &#9654;') + '</span> &nbsp; || &nbsp; '+
  1405. '<label>Select page: </label><select></select>';
  1406. for (var i=0;i<data.length;i++) {
  1407. if (i === +index)
  1408. sopt.push('<option value="' + i + '" selected="selected">' + (i+1) + '</option>');
  1409. else
  1410. sopt.push('<option value="' + i + '">' + (i+1) + '</option>');
  1411. }
  1412. pager[0].lastChild.innerHTML = sopt.join('');
  1413. pager[2] = pager[0].cloneNode(true);
  1414. pager[2].id = "hdbPageBot";
  1415. for (i of [0,2]) {
  1416. pager[i].children[0].onclick = resultConstrain.bind(null,null,+index-1,type,callback);
  1417. pager[i].children[1].onclick = resultConstrain.bind(null,null,+index+1,type,callback);
  1418. pager[i].children[3].onchange = _f;
  1419. }
  1420. pager[0].parentNode.replaceChild(pager[2], pager[1]);
  1421. }
  1422.  
  1423. callback(rslice);
  1424. }//}}} resultConstrain
  1425.  
  1426. function beenThereDoneThat() {//{{{
  1427. if (~document.location.pathname.search(/(accept|continue)/)) {
  1428. if (!document.querySelector('input[name="hitAutoAppDelayInSeconds"]')) return;
  1429.  
  1430. // capture autoapproval times
  1431. var _aa = document.querySelector('input[name="hitAutoAppDelayInSeconds"]').value,
  1432. _hid = document.querySelectorAll('input[name="hitId"]')[1].value,
  1433. pad = function(num) { return Number(num).toPadded(); },
  1434. _d = Date.parse(new Date().getFullYear() + "-" + pad(new Date().getMonth()+1) + "-" + pad(new Date().getDate()));
  1435.  
  1436. if (!qc.aat[_d]) qc.aat[_d] = {};
  1437. qc.aat[_d][_hid] = _aa;
  1438. qc.save("aat", "hitdb_autoAppTemp", true);
  1439. return;
  1440. }
  1441. var qualNode = document.querySelector('td[colspan="11"]');
  1442. if (qualNode) { // we're on the preview page!
  1443. var requesterid = document.querySelector('input[name="requesterId"]').value,
  1444. requestername = document.querySelector('input[name="prevRequester"]').value,
  1445. autoApproval = document.querySelector('input[name="hitAutoAppDelayInSeconds"]').value,
  1446. hitTitle = document.querySelector('div[style*="ellipsis"]').textContent.trim(),
  1447. insertionNode = qualNode.parentNode.parentNode;
  1448. var row = document.createElement("TR"), cellL = document.createElement("TD"), cellR = document.createElement("TD");
  1449. var resultsTableR = document.createElement("TABLE"),
  1450. resultsTableT = document.createElement("TABLE");
  1451. resultsTableR.dataset.rid = requesterid;
  1452. resultsTableT.dataset.title = hitTitle;
  1453. insertionNode.parentNode.parentNode.appendChild(resultsTableR);
  1454. insertionNode.parentNode.parentNode.appendChild(resultsTableT);
  1455.  
  1456. cellR.innerHTML = '<span class="capsule_field_title">Auto-Approval:</span>&nbsp;&nbsp;'+Utils.ftime(autoApproval);
  1457. var rbutton = document.createElement("BUTTON");
  1458. rbutton.classList.add("hitdbRTButtons","hitdbRTButtons-large");
  1459. rbutton.textContent = "Requester";
  1460. rbutton.onclick = function(e) { e.preventDefault(); showResults.call(resultsTableR, "req", hitTitle); };
  1461. var tbutton = rbutton.cloneNode(false);
  1462. rbutton.title = "Show HITs completed from this requester";
  1463. tbutton.textContent = "HIT Title";
  1464. tbutton.onclick = function(e) { e.preventDefault(); showResults.call(resultsTableT, "title", requestername) };
  1465. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(requesterid), limit: 1})
  1466. .then(processResults.bind(rbutton,resultsTableR));
  1467. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(hitTitle), limit: 1})
  1468. .then(processResults.bind(tbutton,resultsTableT));
  1469. row.appendChild(cellL);
  1470. row.appendChild(cellR);
  1471. cellL.appendChild(rbutton);
  1472. cellL.appendChild(tbutton);
  1473. cellL.colSpan = "3";
  1474. cellR.colSpan = "8";
  1475. insertionNode.appendChild(row);
  1476. } else { // browsing HITs n sutff
  1477. var titleNodes = document.querySelectorAll('a[class="capsulelink"]');
  1478. if (titleNodes.length < 1) return; // nothing left to do here!
  1479. var requesterNodes = document.querySelectorAll('a[href*="hitgroups&requester"]');
  1480. var insertionNodes = [];
  1481.  
  1482. for (var i=0;i<titleNodes.length;i++) {
  1483. var _title = titleNodes[i].textContent.trim();
  1484. var _tbutton = document.createElement("BUTTON");
  1485. var _id = requesterNodes[i].href.replace(/.+Id=(.+)/, "$1");
  1486. var _name = requesterNodes[i].textContent;
  1487. var _rbutton = document.createElement("BUTTON");
  1488. var _div = document.createElement("DIV"), _tr = document.createElement("TR");
  1489. resultsTableR = document.createElement("TABLE");
  1490. resultsTableR.dataset.rid = _id;
  1491. resultsTableT = document.createElement("TABLE");
  1492. resultsTableT.dataset.title = _title;
  1493. insertionNodes.push(requesterNodes[i].parentNode.parentNode.parentNode);
  1494. insertionNodes[i].offsetParent.offsetParent.offsetParent.offsetParent.appendChild(resultsTableR);
  1495. insertionNodes[i].offsetParent.offsetParent.offsetParent.offsetParent.appendChild(resultsTableT);
  1496.  
  1497. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(_title), limit: 1} )
  1498. .then(processResults.bind(_tbutton,resultsTableT));
  1499. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(_id), limit: 1} )
  1500. .then(processResults.bind(_rbutton,resultsTableR));
  1501.  
  1502. _tr.appendChild(_div);
  1503. _div.id = "hitdbRTInjection-"+i;
  1504. _div.appendChild(_rbutton);
  1505. _rbutton.textContent = 'R';
  1506. _rbutton.classList.add("hitdbRTButtons");
  1507. _rbutton.onclick = showResults.bind(resultsTableR, "req", _title);
  1508. _rbutton.title = "Show HITs completed from this requester";
  1509. _div.appendChild(_tbutton);
  1510. _tbutton.textContent = 'T';
  1511. _tbutton.classList.add("hitdbRTButtons");
  1512. _tbutton.onclick = showResults.bind(resultsTableT, "title", _name);
  1513. insertionNodes[i].appendChild(_tr);
  1514. }
  1515. } // else
  1516.  
  1517. function showResults(type, match) {//{{{
  1518. /*jshint validthis: true*/
  1519. if (!this.dataset.hasResults) return;
  1520. if (this.children.length) // table is populated
  1521. this.innerHTML = '';
  1522. else { // need to populate table
  1523. var head = this.createTHead(),
  1524. body = this.createTBody(),
  1525. capt = this.createCaption(),
  1526. style= "font-size:10px;font-weight:bold;text-align:center",
  1527. validKeys = function(obj) { return Object.keys(obj).filter(function(v) { return !~v.search(/total[A-Z]/); }); };
  1528.  
  1529. capt.innerHTML = '<span style="'+style+'">Loading...<label class="spin"></label></span>';
  1530.  
  1531. if (type === "req") {
  1532. HITStorage.recall("HIT", {index:"requesterId", range:window.IDBKeyRange.only(this.dataset.rid)})
  1533. .then( function(r) {
  1534. var cbydate = r.collate(r.results, "date"),
  1535. kbydate = validKeys(cbydate),
  1536. cbydatextitle, kbytitle, bodyHTML = [];
  1537. kbydate.forEach(function(date) {
  1538. cbydatextitle = r.collate(cbydate[date], "title");
  1539. kbytitle = validKeys(cbydatextitle);
  1540. kbytitle.forEach(function(title) {
  1541. bodyHTML.push('<tr style="text-align:center;"><td>'+date+'</td>' +
  1542. '<td style="text-align:left">'+title.trim()+'</td><td>'+cbydatextitle[title].length+'</td>' +
  1543. '<td>'+Number(Math.decRound(cbydatextitle[title].pay,2)).toFixed(2)+'</td></tr>');
  1544. });
  1545. });
  1546. var help = "Total number of HITs submitted for a given date with the same title\n" +
  1547. "(aggregates results with the same title to simplify the table and reduce unnecessary spam for batch workers)";
  1548. head.innerHTML = '<tr style="'+style+'"><th>Date</th><th>Title</th>' +
  1549. '<th><span class="helpSpan" title="'+help+'">#HITs</span></th><th>Total Rewards</th></tr>';
  1550. body.innerHTML = bodyHTML.sort(function(a,b) {
  1551. return a.match(/\d{4}-\d{2}-\d{2}/)[0] < b.match(/\d{4}-\d{2}-\d{2}/)[0] ? 1 : -1;
  1552. }).join('');
  1553. capt.innerHTML = '<label style="'+style+'">HITs Matching This Requester</label>';
  1554.  
  1555. var mrows = Array.prototype.filter.call(body.rows, function(v) {return v.cells[1].textContent === match});
  1556. for (var row of mrows)
  1557. row.style.background = "lightgreen";
  1558. });
  1559. }
  1560. else if (type === "title") {
  1561. HITStorage.recall("HIT", {index:"title", range:window.IDBKeyRange.only(this.dataset.title)})
  1562. .then( function(r) {
  1563. var cbyreq = r.collate(r.results, "requesterName"),
  1564. kbyreq = validKeys(cbyreq),
  1565. bodyHTML = [];
  1566. for (var key of kbyreq)
  1567. bodyHTML.push('<tr style="text-align:center;"><td>'+key+'</td><td>'+cbyreq[key].length+'</td>' +
  1568. '<td>'+Number(Math.decRound(cbyreq[key].pay,2)).toFixed(2)+'</td></tr>');
  1569. var help = "Total number of HITs matching this title submitted for a given requester\n" +
  1570. "(aggregates results with the same requester name to simplify the table and reduce unnecessary spam for batch workers)";
  1571. head.innerHTML = '<tr style="'+style+'"><th>Requester Name</th>' +
  1572. '<th><span class="helpSpan" title="'+help+'">#HITs</span></th><th>Total Rewards</th></tr>';
  1573. body.innerHTML = bodyHTML.join('');
  1574. capt.innerHTML = '<label style="'+style+'">Reqesters With HITs Matching This Title</label>';
  1575.  
  1576. var mrows = Array.prototype.filter.call(body.rows, function(v) {return v.cells[0].textContent === match});
  1577. for (var row of mrows)
  1578. row.style.background = "lightgreen";
  1579. });
  1580. } //if type === 'title'
  1581. }//populate table
  1582. }//}}} showResults
  1583.  
  1584. function processResults(table, r) {
  1585. /*jshint validthis: true*/
  1586. if (r.results.length) {
  1587. table.dataset.hasResults = "true";
  1588. this.classList.add("hitdbRTButtons-green");
  1589. }
  1590. }
  1591. }//}}} btdt
  1592.  
  1593. function showHiddenRows(e) {//{{{
  1594. var rid = e.target.parentNode.textContent.substr(4);
  1595. var nodes = document.querySelectorAll('tr[data-rid="'+rid+'"]'), el = null;
  1596. if (e.target.textContent === "[+]") {
  1597. for (el of nodes)
  1598. el.style.display="table-row";
  1599. e.target.textContent = "[-]";
  1600. } else {
  1601. for (el of nodes)
  1602. el.style.display="none";
  1603. e.target.textContent = "[+]";
  1604. }
  1605. }//}}}
  1606.  
  1607. function showHitsByDate(e) {//{{{
  1608. var date = e.target.parentNode.nextSibling.textContent,
  1609. row = e.target.parentNode.parentNode,
  1610. table= row.parentNode;
  1611.  
  1612. if (e.target.textContent === "[+]") {
  1613. e.target.textContent = "[-]";
  1614. var nrow = table.insertBefore(document.createElement("TR"), row.nextSibling);
  1615. nrow.className = row.className;
  1616. nrow.innerHTML = '<td><b>Loading...<label class="spin"></label></b></td>';
  1617. HITStorage.recall("HIT", {index: "date", range: window.IDBKeyRange.only(date)}).then( function(r) {
  1618. nrow.innerHTML = '<td colspan="7"><table style="width:760;color:#c60;">' + r.formatHTML(null,true) + '</table></td>';
  1619. });
  1620. } else {
  1621. e.target.textContent = "[+]";
  1622. table.removeChild(row.nextSibling);
  1623. }
  1624. }//}}} showHitsByDate
  1625.  
  1626. function updateBonus(e) {//{{{
  1627. if (e instanceof window.KeyboardEvent && e.keyCode === 13) {
  1628. e.target.blur();
  1629. return false;
  1630. } else if (e instanceof window.FocusEvent) {
  1631. var _bonus = +e.target.textContent.replace(/[^\d.]/g,""),
  1632. _tBonusCell = e.target.offsetParent.tFoot.rows[0].cells[4],
  1633. _tBonus = +_tBonusCell.textContent.replace(/\$/,"");
  1634. e.target.textContent = Number(_bonus).toFixed(2);
  1635. _tBonusCell.textContent = '$'+Number(_tBonus-e.target.dataset.initial+_bonus).toFixed(2);
  1636. if (_bonus !== +e.target.dataset.initial) {
  1637. console.log("updating bonus to",_bonus,"from",e.target.dataset.initial,"("+e.target.dataset.hitid+")");
  1638. e.target.dataset.initial = _bonus;
  1639. var _pay = +e.target.previousSibling.textContent,
  1640. _range = window.IDBKeyRange.only(e.target.dataset.hitid);
  1641.  
  1642. HITStorage.db.transaction("HIT", "readwrite").objectStore("HIT").openCursor(_range).onsuccess = function() {
  1643. var c = this.result;
  1644. if (c) {
  1645. var v = c.value;
  1646. v.reward = { pay: _pay, bonus: _bonus };
  1647. c.update(v);
  1648. }
  1649. }; // idbcursor
  1650. } // bonus is new value
  1651. } // keycode
  1652. } //}}} updateBonus
  1653.  
  1654. function noteHandler(type, e) {//{{{
  1655. //
  1656. // TODO restructure event handling/logic tree
  1657. // combine save and delete; it's ugly :(
  1658. // actually this whole thing is messy and in need of refactoring
  1659. //
  1660. if (e instanceof window.KeyboardEvent) {
  1661. if (e.keyCode === 13) {
  1662. e.target.blur();
  1663. return false;
  1664. }
  1665. return;
  1666. }
  1667.  
  1668. if (e instanceof window.FocusEvent) {
  1669. if (e.target.textContent.trim() !== e.target.dataset.initial) {
  1670. if (!e.target.textContent.trim()) { e.target.previousSibling.previousSibling.firstChild.click(); return; }
  1671. var note = e.target.textContent.trim(),
  1672. _range = window.IDBKeyRange.only(e.target.dataset.id),
  1673. inote = e.target.dataset.initial,
  1674. hitId = e.target.dataset.id,
  1675. date = e.target.previousSibling.textContent;
  1676.  
  1677. e.target.dataset.initial = note;
  1678. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1679. if (this.result) {
  1680. var r = this.result.value;
  1681. if (r.note === inote) { // note already exists in database, so we update its value
  1682. r.note = note;
  1683. this.result.update(r);
  1684. return;
  1685. }
  1686. this.result.continue();
  1687. } else {
  1688. if (this.source instanceof window.IDBObjectStore)
  1689. this.source.put({ note:note, date:date, hitId:hitId });
  1690. else
  1691. this.source.objectStore.put({ note:note, date:date, hitId:hitId });
  1692. }
  1693. };
  1694. }
  1695. return; // end of save event; no need to proceed
  1696. }
  1697.  
  1698. if (type === "delete") {
  1699. var tr = e.target.parentNode.parentNode,
  1700. noteCell = tr.lastChild;
  1701. _range = window.IDBKeyRange.only(noteCell.dataset.id);
  1702. if (!noteCell.dataset.initial) tr.remove();
  1703. else {
  1704. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1705. if (this.result) {
  1706. if (this.result.value.note === noteCell.dataset.initial) {
  1707. this.result.delete();
  1708. tr.remove();
  1709. return;
  1710. }
  1711. this.result.continue();
  1712. }
  1713. };
  1714. }
  1715. return; // end of deletion event; no need to proceed
  1716. } else {
  1717. if (type === "attach" && !e.results.length) return;
  1718.  
  1719. var trow = e instanceof window.MouseEvent ? e.target.parentNode.parentNode : null,
  1720. tbody = trow ? trow.parentNode : null,
  1721. row = document.createElement("TR"),
  1722. c1 = row.insertCell(0),
  1723. c2 = row.insertCell(1),
  1724. c3 = row.insertCell(2);
  1725. date = new Date();
  1726. hitId = e instanceof window.MouseEvent ? e.target.id.substr(5) : null;
  1727.  
  1728. c1.innerHTML = '<span class="removeNote" title="Delete this note" style="cursor:pointer;color:crimson;">[x]</span>';
  1729. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1730. c1.style.textAlign = "right";
  1731. c2.title = "Date on which the note was added";
  1732. c3.style.color = "crimson";
  1733. c3.colSpan = "6";
  1734. c3.contentEditable = "true";
  1735. c3.onblur = noteHandler.bind(null,"blur");
  1736. c3.onkeydown = noteHandler.bind(null, "kb");
  1737. if (type === "new") {
  1738. row.classList.add(trow.classList);
  1739. tbody.insertBefore(row, trow.nextSibling);
  1740. c2.textContent = date.getFullYear()+"-"+Number(date.getMonth()+1).toPadded()+"-"+Number(date.getDate()).toPadded();
  1741. c3.dataset.initial = "";
  1742. c3.dataset.id = hitId;
  1743. c3.focus();
  1744. return;
  1745. }
  1746.  
  1747. for (var entry of e.results) {
  1748. trow = document.querySelector('tr[data-id="'+entry.hitId+'"]');
  1749. tbody = trow.parentNode;
  1750. row = row.cloneNode(true);
  1751. c1 = row.firstChild;
  1752. c2 = c1.nextSibling;
  1753. c3 = row.lastChild;
  1754. row.classList.add(trow.classList);
  1755. tbody.insertBefore(row, trow.nextSibling);
  1756.  
  1757. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1758. c2.textContent = entry.date;
  1759. c3.textContent = entry.note;
  1760. c3.dataset.initial = entry.note;
  1761. c3.dataset.id = entry.hitId;
  1762. c3.onblur = noteHandler.bind(null,"blur");
  1763. c3.onkeydown = noteHandler.bind(null, "kb");
  1764. }
  1765. } // new/attach
  1766. }//}}} noteHandler
  1767.  
  1768. // writing callback functions {{{
  1769. function cbImport() {
  1770. /*jshint validthis:true*/
  1771. Status.push("Importing " + this.total + " entries");
  1772. if (++this.total !== this.requests) return;
  1773. Status.push("Importing " + this.total + " entries... Done!", "green");
  1774. try { Progress.hide(); metrics.dbimport.stop(); metrics.dbimport.report(); } catch(err) {}
  1775. }
  1776. function cbUpdate() {
  1777. /*jshint validthis:true*/
  1778. if (++this.total !== this.requests) return;
  1779. if (qc.extraDays) qc.extraDays = false;
  1780. Status.push("Update Complete!", "green");
  1781. ProjectedEarnings.data.dbUpdated = new Date().toLocalISOString();
  1782. ProjectedEarnings.saveState();
  1783. ProjectedEarnings.draw(false);
  1784. Utils.disableButtons(['hdbUpdate'], false);
  1785. Progress.hide(); metrics.dbupdate.stop(); metrics.dbupdate.report();
  1786. }
  1787. //}}}
  1788.  
  1789. function autoScroll(location, dt) {//{{{
  1790. var target = document.querySelector(location).offsetTop,
  1791. pos = window.scrollY,
  1792. dpos = Math.ceil((target - pos)/3);
  1793. dt = dt ? dt-1 : 25; // time step/max recursions
  1794.  
  1795. if (target === pos || dpos === 0 || dt === 0) return;
  1796.  
  1797. window.scrollBy(0, dpos);
  1798. setTimeout(function() { autoScroll(location, dt); }, dt);
  1799. }//}}}
  1800.  
  1801. function Calendar(offsetX, offsetY, caller) {//{{{
  1802. this.date = new Date();
  1803. this.offsetX = offsetX;
  1804. this.offsetY = offsetY;
  1805. this.caller = caller;
  1806. this.drawCalendar = function(year,month,day) {//{{{
  1807. year = year || this.date.getFullYear();
  1808. month = month || this.date.getMonth()+1;
  1809. day = day || this.date.getDate();
  1810. var longMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  1811. var date = new Date(year,month-1,day);
  1812. var anchors = _getAnchors(date);
  1813.  
  1814. //make new container if one doesn't already exist
  1815. var container = null;
  1816. if (document.querySelector("#hdbCalendarPanel")) {
  1817. container = document.querySelector("#hdbCalendarPanel");
  1818. container.removeChild( container.getElementsByTagName("TABLE")[0] );
  1819. }
  1820. else {
  1821. container = document.createElement("DIV");
  1822. container.id = "hdbCalendarPanel";
  1823. document.body.appendChild(container);
  1824. }
  1825. container.style.left = this.offsetX;
  1826. container.style.top = this.offsetY;
  1827. var cal = document.createElement("TABLE");
  1828. cal.cellSpacing = "0";
  1829. cal.cellPadding = "0";
  1830. cal.border = "0";
  1831. container.appendChild(cal);
  1832. cal.innerHTML = '<tr>' +
  1833. '<th class="hdbCalHeader hdbCalControls" title="Previous month" style="text-align:right;"><span>&lt;</span></th>' +
  1834. '<th class="hdbCalHeader hdbCalControls" title="Previous year" style="text-align:center;"><span>&#8810;</span></th>' +
  1835. '<th colspan="3" id="hdbCalTableTitle" class="hdbCalHeader">'+date.getFullYear()+'<br>'+longMonths[date.getMonth()]+'</th>' +
  1836. '<th class="hdbCalHeader hdbCalControls" title="Next year" style="text-align:center;"><span>&#8811;</span></th>' +
  1837. '<th class="hdbCalHeader hdbCalControls" title="Next month" style="text-align:left;"><span>&gt;</span></th>' +
  1838. '</tr><tr><th class="hdbDayHeader" style="color:red;">S</th><th class="hdbDayHeader">M</th>' +
  1839. '<th class="hdbDayHeader">T</th><th class="hdbDayHeader">W</th><th class="hdbDayHeader">T</th>' +
  1840. '<th class="hdbDayHeader">F</th><th class="hdbDayHeader">S</th></tr>';
  1841. document.querySelector('th[title="Previous month"]').addEventListener( "click", function() {
  1842. this.drawCalendar(date.getFullYear(), date.getMonth(), 1);
  1843. }.bind(this) );
  1844. document.querySelector('th[title="Previous year"]').addEventListener( "click", function() {
  1845. this.drawCalendar(date.getFullYear()-1, date.getMonth()+1, 1);
  1846. }.bind(this) );
  1847. document.querySelector('th[title="Next month"]').addEventListener( "click", function() {
  1848. this.drawCalendar(date.getFullYear(), date.getMonth()+2, 1);
  1849. }.bind(this) );
  1850. document.querySelector('th[title="Next year"]').addEventListener( "click", function() {
  1851. this.drawCalendar(date.getFullYear()+1, date.getMonth()+1, 1);
  1852. }.bind(this) );
  1853.  
  1854. var hasDay = false, thisDay = 1;
  1855. for (var i=0;i<6;i++) { // cycle weeks
  1856. var row = document.createElement("TR");
  1857. for (var j=0;j<7;j++) { // cycle days
  1858. if (!hasDay && j === anchors.first && thisDay < anchors.total)
  1859. hasDay = true;
  1860. else if (hasDay && thisDay > anchors.total)
  1861. hasDay = false;
  1862.  
  1863. var cell = document.createElement("TD");
  1864. cell.classList.add("hdbCalCells");
  1865. row.appendChild(cell);
  1866. if (hasDay) {
  1867. cell.classList.add("hdbCalDays");
  1868. cell.textContent = thisDay;
  1869. cell.addEventListener("click", _clickHandler.bind(this));
  1870. cell.dataset.year = date.getFullYear();
  1871. cell.dataset.month = date.getMonth()+1;
  1872. cell.dataset.day = thisDay++;
  1873. }
  1874. } // for j
  1875. cal.appendChild(row);
  1876. } // for i
  1877. var controls = cal.insertRow(-1);
  1878. controls.insertCell(0);
  1879. controls.cells[0].colSpan = "7";
  1880. controls.cells[0].classList.add("hdbCalCells");
  1881. controls.cells[0].innerHTML = ' &nbsp; &nbsp; <a href="javascript:void(0)" style="font-weight:bold;text-decoration:none;">Clear</a>' +
  1882. ' &nbsp; <a href="javascript:void(0)" style="font-weight:bold;text-decoration:none;">Close</a>';
  1883. controls.cells[0].children[0].onclick = function() { this.caller.value = ""; }.bind(this);
  1884. controls.cells[0].children[1].onclick = this.die;
  1885.  
  1886. function _clickHandler(e) {
  1887. /*jshint validthis:true*/
  1888.  
  1889. var y = e.target.dataset.year;
  1890. var m = Number(e.target.dataset.month).toPadded();
  1891. var d = Number(e.target.dataset.day).toPadded();
  1892. this.caller.value = y+"-"+m+"-"+d;
  1893. this.die();
  1894. }
  1895.  
  1896. function _getAnchors(date) {
  1897. var _anchors = {};
  1898. date.setMonth(date.getMonth()+1);
  1899. date.setDate(0);
  1900. _anchors.total = date.getDate();
  1901. date.setDate(1);
  1902. _anchors.first = date.getDay();
  1903. return _anchors;
  1904. }
  1905. };//}}} drawCalendar
  1906.  
  1907. this.die = function() { document.getElementById('hdbCalendarPanel').remove(); };
  1908.  
  1909. }//}}} Calendar
  1910.  
  1911. // instance metrics apart from window scoped PerformanceTiming API
  1912. function Metrics(name) {//{{{
  1913. this.name = name || "undefined";
  1914. this.marks = {};
  1915. this.start = window.performance.now();
  1916. this.end = null;
  1917. this.stop = function(){
  1918. if (!this.end)
  1919. this.end = window.performance.now();
  1920. else
  1921. Utils.errorHandler(new Error("Metrics::AccessViolation - end point cannot be overwritten"));
  1922. };
  1923. this.mark = function(name,position) {
  1924. if (position === "end" && (!this.marks[name] || this.marks[name].end)) return;
  1925.  
  1926. if (!this.marks[name])
  1927. this.marks[name] = {};
  1928.  
  1929. this.marks[name][position] = window.performance.now();
  1930. };
  1931. this.report = function() {
  1932. console.group("Metrics for",this.name.toUpperCase());
  1933. console.log("Process completed in",+Number((this.end-this.start)/1000).toFixed(3),"seconds");
  1934. for (var k in this.marks) {
  1935. if (this.marks.hasOwnProperty(k)) {
  1936. console.log(k,"occurred after",+Number((this.marks[k].start-this.start)/1000).toFixed(3),"seconds,",
  1937. "resolving in", +Number((this.marks[k].end-this.marks[k].start)/1000).toFixed(3), "seconds");
  1938. }
  1939. }
  1940. console.groupEnd();
  1941. };
  1942. }//}}}
  1943.  
  1944. function INITDB() {//{{{
  1945. if (localStorage.getItem('hitdb_merge')) localStorage.removeItem('hitdb_merge');
  1946. HITStorage.db = this.result;
  1947. self.HITStorage = {db: this.result};
  1948. }//}}}
  1949. })(); //scoping
  1950.  
  1951. // vim: ts=2:sw=2:et:fdm=marker:noai