summaryrefslogtreecommitdiff
path: root/js/backoffice.js
blob: e22c1a1bda49ba473d5a5b25736dd3bb0d1a1fda (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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/*
  @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";

/**
 * The precision of the amount's fraction, when
 * it comes objectified.
 */
var FRACTION = 100000000;

/**
 * Default 'start' URL argument used when querying for /history.
 */
var START = 0;

/**
 * Fixed 'delta' URL argument used when querying for /history.
 */
var DELTA = 5

/**
 * Row id of the _oldest_ /history record that's shown on the
 * screen; will be used as the next 'delta' argument if scrolling
 * down occurs.
 */
var LAST = 0;

/**
 * Flag controlling whether the scrolling of the page is enabled
 * or not; for example, after /track/transfer results are shown
 * on page, the semantics of "scrolling down towards older records"
 * disappears because former results aren't arranged regarding of
 * time.
 */
var SCROLL = true;

/**
 * Maps error codes from https://git.taler.net/exchange.git/tree/src/include/taler_error_codes.h
 * to friendlier messages.
 */
function error_map(code){
  switch (Number(code)){

  /* /history errors.  */
  case 2200:
    return "The timestamp used to query the history overflowed.";
  case 2201:
    return "Merchant had serious problems in its history database";
  case 2202:
    return "The instance used to query the history is unknown";

  /* /track/order errors.  */
  case 2307:
    /* Such errors should provide full proof to the user.  */
    return "One of the coin was untraceable";
  case 2308:
  case 2408:
    return "Conflicting reports from the Exchange";
  case 2301:
    return "Instance is unknown to track this order";
  case 2303:
  case 2304:
  case 2305:
  case 1801:
    return "Merchant database failed, code:" + code;
  case 2306:
    return "One of the coin failed at getting its WTID";

  /* /track/transfer errors.  */
  case 2410:
    return "Exchange charged a higher wire fee than what " +
           " it was originally advertised.";
  case 2405:
    return "Error from the exchange, no proof received!";
  case 2404:
  case 2402:
    return "Database failure, could not store results: " + code;
  case 2406:
    return "Database failure, could not retrieve previous results";
  case 2407:
    return "Database failure, internal logic error";
  case 2409:
    return "Merchant could not pack the JSON response";
  case 2403:
    return "Merchant failed to request /track/transfer to \
            the exchange";
  case 2400:
    return "Exchange timed out..";
  case 2503:
    return "Proposal not found.";

  default:
    return "Error code not given.";
  } 

}

/**
 * Convert Taler-compliant amount to human-friendly string.
 * The amount may be both a string or object type.
 */
function amount_to_string(amount){
  if (typeof amount === 'string' || amount instanceof String)
  {
    var split = amount.match(/([A-Z]+):([0-9]+)\.?([0-9]+)?/);
    if (!split)
      return "Bad amount given: " + amount;
    if (split[3])
      return `${split[2]}.${split[3]} ${split[1]}`;
    return `${split[2]}.00 ${split[1]}`;
  }
  var number = Number(amount.value) +
              (Number(amount.fraction)/FRACTION);
  return `${number.toFixed(2)} ${amount.currency}`;
}


/**
 * Close the center-box that shows results from /track/transaction
 * Note that this function first *empties* the results, and then
 * closes the box.
 */
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);
}


/**
 * 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.  Note, this function does NOT check if
 * the box has content or not.
 */
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.  Results will be shown in the same style of
 * /history's.
 */
var track_transfer = function(exchange, wtid, cb){

  /* Remove potential information bar.  */
  var info_bar = document.getElementById("information-bar");
  info_bar.style.visibility = "hidden"; 

  toggle_loader();
  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:
        /* Scroll is disabled after showing /track/transfer
         * results on the page; that's because those results
         * are not guaranteed to be sorted any how, so there
         * is little to no point in scrolling towards "older"
         * results: older than what?  The scroll feature will
         * be re-enabled from the /history callback.  */
        SCROLL = false;
        clear_results();
        var tracks = JSON.parse(req.responseText);
        cb(tracks.deposits_sums,
           tracks.execution_time,
           wtid);
        break;
      default:
        show_error(req.responseText, true);
      }
    }
  }
  req.send();
}


/**
 * Fill the information bar on the top of the page with
 * error messages.  The same orange bar is used for warnings.
 */
var show_warning;
var show_error = show_warning = function(response_text){

  toggle_loader();
  close_popup();

  var msg;
  var hint = "";
  try{
    var parse = JSON.parse(response_text);
    console.log("Response was at least JSON");
    /* handles undefined codes too.  */
    msg = error_map(parse['code']);

    if (parse['hint'])
      hint = parse['hint'];

  } catch (e) {
    msg = response_text;
    console.log("Must keep raw response");
  }
  
  /* Get hold of the info bar.  */
  var info_bar = document.getElementById("information-bar");
  info_bar.innerHTML = `<p>${msg} ${hint}</p>`; 
  info_bar.style.visibility = "visible"; 
}

/**
 * Call /track/order API offered by the frontend.  It will make
 * results shown in a centered box that overlays the page.
 */
var track_order = function(order_id, cb){
  
  /* Remove potential information bar.  */
  var info_bar = document.getElementById("information-bar");
  info_bar.style.visibility = "hidden"; 

  toggle_loader();
  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, true);
      return;
    }
  }
  req.send();
}

/**
 * Fill the screen-centered box with data from /track/order.
 * This box will overlay the ordinary page, and disappear when
 * the user clicks the close button or Esc key.
 */
function fill_box(tracks, http_code)
{
  toggle_loader();

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

  if (http_code == 202){
    console.log("Pending order.");
    toggle_loader();
    show_warning("This order is still waiting to be paid back");
    return;
  }

  if(!tracks)
    show_error("/track/transfer returned EMPTY!  Very bad.");
    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];
    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}`;
    console.log("Subject", subject);
    row.innerHTML = `` +
      `<td class="wtid">` +
        `<a onclick="track_transfer(\'${entry.exchange}\', ` +
                                   `\'${entry.wtid}\', ` +
                                   `fill_table)"` +
            `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;
}


/**
 * Fill the page with orders rows.
 */
function fill_table(data, execution_time, wtid_marker){
  var table = document.getElementById("history");
  var tbody = xpath_get("tbody", table).snapshotItem(0);

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

  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 || "deposited";
    td_amount.innerHTML = amount_to_string(
      entry.amount || entry.deposit_value);
    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 at the bottom, mentioning the WTID.
    var marker = make_marker(wtid_marker);
    tbody.appendChild(marker);
  }
  toggle_loader();
}

/**
 * Make the spinning wheel appear/disappear.
 */
function toggle_loader(){
  var loader = document.getElementsByClassName("loader")[0]; 
  if (loader.style.visibility != "hidden")
  {
    loader.style.visibility = "hidden";
    console.log("toggle_loader: visible>hidden");
  }
  else
  {
    loader.style.visibility = "visible";
    console.log("toggle_loader: hidden>visible");
  }
} 

/**
 * Issue a /track/order (/track/transfer) depending on
 * whether the user selected "order" ("transfer") on the
 * dedicated 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, fill_box);
    }
    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);
    }  
  }
}

/**
 * Make the /track/order form visible.
 */
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 /track/transaction form visible.
 */
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 the selected instance.
 */
function get_instance(){
  var select = document.getElementById("instance");
  return select.value;
}

/**
 * Remove tracks from the main page table, but
 * do NOT remove the table headers; it hides them though.
 */
function clear_results(){
  var table = document.getElementById("history");
  var tbody = xpath_get("tbody", table).snapshotItem(0);
  var tbody_children = xpath_get("tbody/*[position() > 1]", table);
  for(var i=0; i<tbody_children.snapshotLength; i++){
    tbody.removeChild(tbody_children.snapshotItem(i));
  }

  xpath_get("tr[@class='headers']", tbody)
    .snapshotItem(0).style.visibility = "hidden";

}


/**
 * Make the instance selected effective.  In particular, it
 * triggers history retrieval for it.
 */
function change_instance(){
  /* Restore values.  Changing instance should have
   * the same effect of reloading the whole page.  */
  START = 0;
  LAST = 0;
  clear_results();

  /* Remove error info bar, if any exist.  */
  var info_bar = document.getElementById("information-bar");
  info_bar.style.visibility = "hidden"; 

  get_history(false, fill_table);
}

/**
 * Query the /history API.
 */
function get_history(scroll, cb){
  SCROLL = true;
  var qs = `/history?instance=${get_instance()}&delta=${DELTA}`;
  if(scroll){
    START = LAST;
    qs += `&start=${START}`;
  }
  /* Will be untoggled by the 'cb' */
  toggle_loader();
  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){
          show_warning("No more records.."); 
          return;
        }
        if(0 < history.length){
          console.log(history);
          LAST = history[history.length - 1].row_id;
          cb(history);
        }
      }
      else{
        console.log("error: status != 200");
        console.log("response", req.responseText);
        show_error(req.responseText, true);
      }
    }
  }
  req.send();
}

/**
 * Trigger /history as soon as the page loads.
 */
document.addEventListener
  ("DOMContentLoaded",
   function(){
     get_history(false, fill_table);});

/**
 * Implement scrolling down of history.  When the user
 * scrolls down, older results from /history will be requested.
 */
document.addEventListener
  ("scroll", function(){
  /* If page bottom is hit */
  if((window.innerHeight + window.scrollY
       >= document.body.offsetHeight) && SCROLL)
    get_history(true, fill_table);
  });

/**
 * Close the centered box that (typically) shows /track/transfer
 * results.
 */
document.onkeydown = function(e) {
  if(!e)
    e = event;
  if(e.keyCode == 27){
    close_popup();
  }
}

/**
 * export functions to be tested by AVA.
 */
if (typeof(module) != "undefined"){
  module.exports.track_transfer = track_transfer;
  module.exports.track_order = track_order;
}