summaryrefslogtreecommitdiff
path: root/js/backoffice.js
blob: eeac8f37ca9f413a72d7bf33e8d75a1401a23c4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/*
  @licstart  The following is the entire license notice for the
  JavaScript code in this page.

  Copyright (C) 2015, 2016 INRIA

  The JavaScript code in this page is free software: you can
  redistribute it and/or modify it under the terms of the GNU
  Lesser General Public License (GNU LGPL) as published by the
  Free Software Foundation, either version 2.1 of the License, or
  (at your option) any later version.  The code is distributed
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU LGPL for more details.

  As additional permission under GNU LGPL version 2.1 section 7,
  you may distribute non-source (e.g., minimized or compacted)
  forms of that code without the copy of the GNU LGPL normally
  required by section 4, provided you include this license notice
  and a URL through which recipients can access the Corresponding
  Source.

  @licend  The above is the entire license notice
  for the JavaScript code in this page.
 
  @author Marcello Stanisci
*/
"use strict";

var FRACTION = 100000000;
var START = 0;
var DELTA = 5
var LAST = 0;

/**
 * This function *could* "type check" 'amount',
 * but once 'amount' got here it is already "too late",
 * because this means that the merchant *backend* gave
 * it wrong.
 */
function amount_to_string(amount){
  var number = Number(amount.value) +
              (Number(amount.fraction)/FRACTION);
  return `${number.toFixed(2)} ${amount.currency}`;
}

function close_popup(){

  var ctx = document.getElementsByClassName("track-content")[0];
  var tbody = xpath_get("table/tbody", ctx).snapshotItem(0);
  var tbody_children = xpath_get("table/tbody/tr", ctx);

  for(var i=1; i<tbody_children.snapshotLength; i++){
    tbody.removeChild(tbody_children.snapshotItem(i));
  }

  toggle_overlay(true);
}

function amount_sum(a1, a2){
  if(a1.currency != a2.currency)
    throw "Currency mismatch, terminating.";
  var ret = {currency: a2.currency,
             value: 0,
             fraction: 0};
  ret.value = a1.value + a2.value;
  var fraction = a1.fraction + a2.fraction;
  ret.value += Math.floor(fraction / FRACTION);
  ret.fraction = fraction % FRACTION;
  return ret;
}

/**
 * Parse Taler /Date(x)/ into human-friendly format.
 */
function parse_date(date){

  var split = date.match(/Date\(([0-9]+)\)/);
  if (!split){
    console.error("Malformed date gotten from backend");
  }
  var seconds;
  if(isNaN(seconds = Number(split[1]))){
    console.error("Malformed date: no secs given");
    return;
  }
  var d = new Date(seconds * 1000);
  var months = ["Jan", "Feb", "Mar", "Apr", "May",
                "Jun", "Jul", "Aug", "Sep", "Oct",
                "Nov", "Dec"];
  var hours = ("0" + d.getHours()).slice(-2);
  var minutes = ("0" + d.getMinutes()).slice(-2);
  return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}, ${hours}:${minutes}`;
}

/**
 * Make screen-centerd box (which show a order's tracks)
 * appear/disappear.
 */
function toggle_overlay(force_close){
  var overlay = document.getElementsByClassName("overlay")[0];
  if(overlay.style.visibility == "visible" || force_close){
    overlay.style.visibility = "hidden";
    overlay.style.opacity = 0;
  }
  else
  {
    overlay.style.visibility = "visible";
    overlay.style.opacity = 1;
  }

}

/**
 * Draws a line at the bottom of a orders list to indicate
 * they have all being paid out by the same WTID.
 */
function make_marker(wtid){
  var tr = document.createElement("tr");
  var td = document.createElement("td");
  var p = document.createElement("p");
  td.setAttribute("colspan", 3);
  p.textContent = wtid.substr(0, 20) + "...";
  p.setAttribute("id", "marker");
  td.appendChild(p);
  tr.appendChild(td);
  return tr;
}


/**
 * Use the /track/transfer API from the frontend.  Once data
 * arrives, it calls a UI function which lists all the entries
 * in the page.
 *
 * 'cb' is a UI transforming function.  Typically, it is set to
 * 'fill_table()'.
 */
var track_transfer = function(exchange, wtid, cb){
  var qs = `/track/transfer?` +
           `exchange=${exchange}&` +
           `wtid=${wtid}&` +
           `instance=${get_instance()}`;
  var req = new XMLHttpRequest();
  req.open("GET", qs, true);
  req.onload = function(){
    if(4 == req.readyState){
      switch(req.status){
      case 200:
        var tracks = JSON.parse(req.responseText);
        cb(true, tracks.deposits_sums, tracks.execution_time, wtid);
        break;
      default:
        show_error(req.responseText);
      }
    }
  }
  req.send();
}


/* Fill the information bar on the top of the page with
 * error messages.  */
var show_error = function(response_text){
  var msg = response_text;

  try{
    var parse = JSON.parse(response_text);
    console.log("Response was at least JSON");
    if (parse['error'])
      msg = parse['error'];

    /* Give precedence to 'hint' as it is usually
     * human-friendlier */
    if (parse['hint'])
      msg = parse['hint'];

  } catch (e) {
    console.log("Must keep raw HTML-ish response");
  }
  
  /* msg is ready here.  */

  /* Get hold of the info bar.  */
  var info_bar = document.getElementById("information-bar");
  info_bar.innerHTML = `<p>${msg}</p>`; 
  info_bar.style.visibility = "visible"; 

  /* Info bar will disappear at next page load/reload.  */
}

/**
 * Call /track/order API offered by the frontend.  Once data
 * arrives it calls a UI routine which fills the "entries table"
 * in the page.
 */
var track_order = function(order_id, cb){
  var req = new XMLHttpRequest();
  var url = `/track/order?` +
            `order_id=${order_id}&` +
            `instance=${get_instance()}`;
  req.open("GET", url, true);
  req.onload = function(){
    if (4 == req.readyState){
      if ((200 == req.status) || (202 == req.status))
        cb(JSON.parse(req.responseText), req.status);
      else
        show_error(req.responseText);
      return;
    }
  }
  req.send();
}

/**
 * Fill the screen-centered box with data from /track/order.
 */
function fill_box(tracks, http_code)
{

  if (http_code == 404){
    alert("No tracks for that order.");
    return;
  }

  if (http_code == 202){
    console.log("Pending order.");
    var overlay = document.getElementsByClassName("overlay")[0];
    var track_content = document
      .getElementsByClassName("track-content")[0];
    track_content.innerHTML = "This order is still" +
      "waiting to be paid back.";
    return;
  }

  if(!tracks)
    console.log("Got invalid JSON");
    if(0 == tracks.length || !tracks.length){
      console.log(`Got no tracks and status == ${http_code}.  ` +
                  `Should not be here.`);
      return;
    }


  for(var i=0; i<tracks.length; i++){
    var entry = tracks[i];
    /**
     * 'track_content' contains the tracks (WTID/Amount/Date)
     * about *one* order.  It is contained in the 'overlay',
     * which renders it in a "box" in the middle of the
     * screen.  This "box" is then toggleable as visible/hidden.
     */
    var overlay = document.getElementsByClassName("overlay")[0];
    var track_content = document.getElementsByClassName
      ("track-content")[0];
    var table = document.evaluate
      ("table/tbody",
       track_content,
       null,
       XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
       null).snapshotItem(0);
    var row = document.createElement("tr");
    var subject = `${entry.wtid} ${entry.exchange_url}`;
    console.log("Subject", subject);
    row.innerHTML = `` +
      `<td class="wtid">` +
        `<a onclick="track_transfer(\'${entry.exchange_url}\', ` +
                                   `\'${entry.wtid}\')"` +
            `href="#${i}">${subject.substring(0, 20)}...` +
        `</a>` +
      `</td>`
      `<td class="amount">` +
        `${amount_to_string(entry.amount)}` +
      `</td>` +
      `<td class="date">` +
        `${parse_date(entry.execution_time)}` +
      `</td>`;
    table.appendChild(row);
    toggle_overlay();
  }
}

/**
 * Helper function which abstracts the hard-to-remember
 * API offered by document.evaluate().
 */
function xpath_get(xpath, ctx){
  var ret = document.evaluate
    (xpath,
     ctx,
     null,
     XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
     null);
  return ret;
}

/**
 * Modify the table showing orders.  Those orders could be
 * either from /history or /track/transfer.  If data is _not_
 * to be appended to previous results in the table, this
 * function will erase previous results and either show new
 * data or make the "no results" message available.  Otherwise,
 * it will just append data to what already exists in the table.
 *
 * Data is non-appending if (1) the page has been (re)loaded,
 * (2) the user queried /track/transfer, (3) the user changed
 * the instance being tracked.  Those 1-3 cases will all have
 * the 'refresh' parameter set to true.
 *
 * 'wtid_marker' - set to <WTID> - serves to show a line at the
 * bottom of the lines being added in the table which indicates
 * that all those entries - orders - have been paid out by the
 * same WTID.
 *
 * FIXME: 'execution_time' is a problematic field: when showing
 * /history results, it shows the order timestamp.  When instead
 * /track/tranfer results are being shown, it indicates the time
 * the exchange wire transferred this order's amount.
 */
function fill_table(refresh, data, execution_time, wtid_marker){
  toggle_loader();
  var table = document.getElementById("history");
  var tbody = xpath_get("tbody", table).snapshotItem(0);
  var nr = xpath_get("tr[@class='no-records']", tbody)
  .snapshotItem(0)
  if (refresh){
    clean_results();
    if(0 == data.length){
      nr.style.display = "block";
      xpath_get("tr[@class='headers']", tbody)
        .snapshotItem(0).style.visibility = "hidden";
      window.setTimeout(remove_loader, 900);
      console.log("Nothing gotten!");
      return;
    }
  }

  /* hide "no records" message */
  nr.style.display = "none";

  /* Make table's header visible */
  xpath_get("tr[@class='headers']", tbody)
    .snapshotItem(0).style.visibility = "";

  for (var i=0; i<data.length; i++){
    var entry = data[i];
    var row = document.createElement("tr");
    row.className = "even";
    var row_summary = document.createElement("tr");
    row_summary.className = "odd";
    var td_order_id = document.createElement("td");
    td_order_id.className = "order-id";
    var td_summary = document.createElement("td");
    td_summary.setAttribute("colspan", 3);
    td_summary.className += "summary";
    var td_amount = document.createElement("td");
    td_amount.className = "amount";
    var td_date = document.createElement("td");
    td_date.className = "date";
    td_order_id.innerHTML = `<a href="#${i}"
      onclick="track_order('${entry.order_id}', fill_box);">
      ${entry.order_id}</a>`;
    td_summary.className = "summary";
    td_summary.innerHTML = entry.summary;
    td_amount.innerHTML = entry.amount;
    td_date.innerHTML = parse_date
      (entry.timestamp || execution_time);
    row.appendChild(td_order_id);
    row.appendChild(td_summary);
    row.appendChild(td_amount);
    row.appendChild(td_date);
    row_summary.appendChild(td_summary);
    tbody.appendChild(row);
    tbody.appendChild(row_summary);
    }
  if (wtid_marker){
    // close popup showing wire transfer information
    close_popup();
    // draw a line @ the bottom, mentioning the WTID.
    var marker = make_marker(wtid_marker);
    tbody.appendChild(marker);
  }

  window.setTimeout(function(){
    toggle_loader();
    table.style.visibility = ""; 
  }, 900);
}

/**
 * Make the spinning wheel appear if it is not shown,
 * and viceversa.
 */
function toggle_loader(){
  var loader = document.getElementsByClassName("loader")[0]; 
  if (loader.style.visibility == "hidden")
    loader.style.visibility = ""
  else
    loader.style.visibility = "hidden";
  }

/**
 * Issue a /track/order (/track/transfer) depending on
 * whether the user selected "order" ("transfer") on the
 * given form.
 */
function track_cherry_pick(form){
  var types = xpath_get("input[@type='radio']", form);
  for(var i in [0, 1]){
    if (!types.snapshotItem(i).checked)
      continue;
    var type = types.snapshotItem(i).value;
    if ("order" == type){
      var order_id = xpath_get("input[@class='order']", form)
        .snapshotItem(0);
      track_order(order_id.value);
    }
    else{
      var data = xpath_get("input[@class='transfer']", form);
      var wtid = data.snapshotItem(0);
      var exchange = data.snapshotItem(1);
      track_transfer(exchange.value, wtid.value, fill_table);
    }  
  }
}

/**
 * The "cherry pick" form allows the user to track a particular
 * order or wire transfer by entering its "id" in the input field.
 *
 * The UI is such that a radio button can switch the form "type"
 * to query for a order or for a wire transfer;  the following two
 * functions help to switch the form appearance according to this
 * order/wire-transfer switch.
 */

/**
 * Make the "cherry pick" form be suitable to query /track/order.
 */
function cherry_pick_form_order(form){
  var input_order = xpath_get("input[@class='order']", form)
    .snapshotItem(0);
  input_order.style.visibility = "";
  var input_transfer = xpath_get("input[@class='transfer']", form);
  for(var i in [0, 1])
    input_transfer.snapshotItem(i).style.visibility = "hidden";
}

/**
 * Make the "cherry pick" form be suitable to query /track/transfer.
 */
function cherry_pick_form_transfer(form){
  var input_order = xpath_get("input[@class='order']", form)
  .snapshotItem(0);
  input_order.style.visibility = "hidden";
  var input_transfer = xpath_get("input[@class='transfer']", form);
  for(var i in [0, 1])
    input_transfer.snapshotItem(i).style.visibility = "";
}

/**
 * Retrieve current istance being tracked.
 */
function get_instance(){
  var select = document.getElementById("instance");
  return select.value;
}

/**
 * Remove tracks from the main page table.
 */
function clean_results(){
  var table = document.getElementById("history");
  var tbody = xpath_get("tbody", table).snapshotItem(0);
  var tbody_children = xpath_get("tbody/*[position() > 2]", table);
  for(var i=0; i<tbody_children.snapshotLength; i++){
    tbody.removeChild(tbody_children.snapshotItem(i));
  }
}
/**
 * Nullify curreny instance and triggers history for newly
 * selected one.
 */
function change_instance(){
  get_history(false, cb);
}

/**
 * If 'scroll' is true, the logic tries to retrieve the
 * "next page" of all the proposals known to the merchant.
 * Otherwise, it gets the merchant's history from the beginning
 * of their business.
 *
 * 'cb' is a UI transforming function.  Typically, it is set
 * to 'fill_table()'.
 */
function get_history(refresh, cb){
  var qs = `/history?instance=${get_instance()}&delta=${DELTA}`;
  if(!refresh){
    START = LAST;
    qs += `&start=${START}`;
  }
  var req = new XMLHttpRequest();
  req.open("GET", qs, true);
  req.onload = function(){
    if(4 == req.readyState){
      if(200 == req.status){
        var history = JSON.parse(req.responseText); 
        if(!history){
          console.log("Got invalid JSON");
          return;
        }
        if(0 < history.length){
          console.log(history);
          LAST = history[history.length - 1].row_id;
        }
        cb(refresh, history);
      }
      else{
        console.log("error: status != 200");
        console.log("response", req.responseText);
      }
    }
  }
  req.send();
}

document.addEventListener
  ("DOMContentLoaded",
   function(){
     toggle_loader();
     get_history(true, fill_table);});
document.addEventListener("scroll", function(){
  /* If page bottom is hit */
  if(window.innerHeight + window.scrollY
       >= document.body.offsetHeight)
    window.setTimeout(function(){
      toggle_loader();
      get_history(false, fill_table);},
      400);});

/* Close dialog on ESC press */
document.onkeydown = function(e) {
  if(!e)
    e = event;
  if(e.keyCode == 27){
    close_popup();
  }
}

if (typeof(module) != "undefined"){
  module.exports.track_transfer = track_transfer;
  module.exports.track_order = track_order;
}