summaryrefslogtreecommitdiffstats
path: root/browser/components/payments/res/paymentRequest.js
blob: 1a0818461595227a6bceef84446cbfef394dc945 (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Loaded in the unprivileged frame of each payment dialog.
 *
 * Communicates with privileged code via DOM Events.
 */

/* import-globals-from unprivileged-fallbacks.js */

var paymentRequest = {
  _nextMessageID: 1,
  domReadyPromise: null,

  init() {
    // listen to content
    window.addEventListener("paymentChromeToContent", this);

    window.addEventListener("keydown", this);

    this.domReadyPromise = new Promise(function dcl(resolve) {
      window.addEventListener("DOMContentLoaded", resolve, { once: true });
    }).then(this.handleEvent.bind(this));

    // This scope is now ready to listen to the initialization data
    this.sendMessageToChrome("initializeRequest");
  },

  handleEvent(event) {
    switch (event.type) {
      case "DOMContentLoaded": {
        this.onPaymentRequestLoad();
        break;
      }
      case "keydown": {
        if (event.code != "KeyD" || !event.altKey || !event.ctrlKey) {
          break;
        }
        this.toggleDebuggingConsole();
        break;
      }
      case "unload": {
        this.onPaymentRequestUnload();
        break;
      }
      case "paymentChromeToContent": {
        this.onChromeToContent(event);
        break;
      }
      default: {
        throw new Error("Unexpected event type");
      }
    }
  },

  /**
   * @param {string} messageType
   * @param {[object]} detail
   * @returns {number} message ID to be able to identify a reply (where applicable).
   */
  sendMessageToChrome(messageType, detail = {}) {
    let messageID = this._nextMessageID++;
    log.debug("sendMessageToChrome:", messageType, messageID, detail);
    let event = new CustomEvent("paymentContentToChrome", {
      bubbles: true,
      detail: Object.assign(
        {
          messageType,
          messageID,
        },
        detail
      ),
    });
    document.dispatchEvent(event);
    return messageID;
  },

  toggleDebuggingConsole() {
    let debuggingConsole = document.getElementById("debugging-console");
    if (debuggingConsole.hidden && !debuggingConsole.src) {
      debuggingConsole.src = "debugging.html";
    }
    debuggingConsole.hidden = !debuggingConsole.hidden;
  },

  onChromeToContent({ detail }) {
    let { messageType } = detail;
    log.debug("onChromeToContent:", messageType);

    switch (messageType) {
      case "responseSent": {
        let { request } = document
          .querySelector("payment-dialog")
          .requestStore.getState();
        document.querySelector("payment-dialog").requestStore.setState({
          changesPrevented: true,
          request: Object.assign({}, request, { completeStatus: "processing" }),
        });
        break;
      }
      case "showPaymentRequest": {
        this.onShowPaymentRequest(detail);
        break;
      }
      case "updateState": {
        document.querySelector("payment-dialog").setStateFromParent(detail);
        break;
      }
    }
  },

  onPaymentRequestLoad() {
    log.debug("onPaymentRequestLoad");
    window.addEventListener("unload", this, { once: true });

    // Automatically show the debugging console if loaded with a truthy `debug` query parameter.
    if (new URLSearchParams(location.search).get("debug")) {
      this.toggleDebuggingConsole();
    }
  },

  async onShowPaymentRequest(detail) {
    // Handle getting called before the DOM is ready.
    log.debug("onShowPaymentRequest:", detail);
    await this.domReadyPromise;

    log.debug("onShowPaymentRequest: domReadyPromise resolved");
    log.debug("onShowPaymentRequest, isPrivate?", detail.isPrivate);

    let paymentDialog = document.querySelector("payment-dialog");
    let state = {
      request: detail.request,
      savedAddresses: detail.savedAddresses,
      savedBasicCards: detail.savedBasicCards,
      // Temp records can exist upon a reload during development.
      tempAddresses: detail.tempAddresses,
      tempBasicCards: detail.tempBasicCards,
      isPrivate: detail.isPrivate,
      page: {
        id: "payment-summary",
      },
    };

    let hasSavedAddresses = !!Object.keys(this.getAddresses(state)).length;
    let hasSavedCards = !!Object.keys(this.getBasicCards(state)).length;
    let shippingRequested = state.request.paymentOptions.requestShipping;

    // Onboarding wizard flow.
    if (!hasSavedAddresses && shippingRequested) {
      state.page = {
        id: "shipping-address-page",
        onboardingWizard: true,
      };

      state["shipping-address-page"] = {
        guid: null,
      };
    } else if (!hasSavedAddresses && !hasSavedCards) {
      state.page = {
        id: "billing-address-page",
        onboardingWizard: true,
      };

      state["billing-address-page"] = {
        guid: null,
      };
    } else if (!hasSavedCards) {
      state.page = {
        id: "basic-card-page",
        onboardingWizard: true,
      };
      state["basic-card-page"] = {
        selectedStateKey: "selectedPaymentCard",
      };
    }

    await paymentDialog.setStateFromParent(state);

    this.sendMessageToChrome("paymentDialogReady");
  },

  openPreferences() {
    this.sendMessageToChrome("openPreferences");
  },

  cancel() {
    this.sendMessageToChrome("paymentCancel");
  },

  pay(data) {
    this.sendMessageToChrome("pay", data);
  },

  closeDialog() {
    this.sendMessageToChrome("closeDialog");
  },

  changePaymentMethod(data) {
    this.sendMessageToChrome("changePaymentMethod", data);
  },

  changeShippingAddress(data) {
    this.sendMessageToChrome("changeShippingAddress", data);
  },

  changeShippingOption(data) {
    this.sendMessageToChrome("changeShippingOption", data);
  },

  changePayerAddress(data) {
    this.sendMessageToChrome("changePayerAddress", data);
  },

  /**
   * Add/update an autofill storage record.
   *
   * If the the `guid` argument is provided update the record; otherwise, add it.
   * @param {string} collectionName The autofill collection that record belongs to.
   * @param {object} record The autofill record to add/update
   * @param {string} [guid] The guid of the autofill record to update
   * @returns {Promise} when the update response is received
   */
  updateAutofillRecord(collectionName, record, guid) {
    return new Promise((resolve, reject) => {
      let messageID = this.sendMessageToChrome("updateAutofillRecord", {
        collectionName,
        guid,
        record,
      });

      window.addEventListener("paymentChromeToContent", function onMsg({
        detail,
      }) {
        if (
          detail.messageType != "updateAutofillRecord:Response" ||
          detail.messageID != messageID
        ) {
          return;
        }
        log.debug("updateAutofillRecord: response:", detail);
        window.removeEventListener("paymentChromeToContent", onMsg);
        document
          .querySelector("payment-dialog")
          .setStateFromParent(detail.stateChange);
        if (detail.error) {
          reject(detail);
        } else {
          resolve(detail);
        }
      });
    });
  },

  /**
   * @param {object} state object representing the UI state
   * @param {string} selectedMethodID (GUID) uniquely identifying the selected payment method
   * @returns {object?} the applicable modifier for the payment method
   */
  getModifierForPaymentMethod(state, selectedMethodID) {
    let basicCards = this.getBasicCards(state);
    let selectedMethod = basicCards[selectedMethodID] || null;
    if (selectedMethod && selectedMethod.methodName !== "basic-card") {
      throw new Error(
        `${selectedMethod.methodName} (${selectedMethodID}) ` +
          `is not a supported payment method`
      );
    }
    let modifiers = state.request.paymentDetails.modifiers;
    if (!selectedMethod || !modifiers || !modifiers.length) {
      return null;
    }
    let appliedModifier = modifiers.find(modifier => {
      // take the first matching modifier
      if (
        modifier.supportedMethods &&
        modifier.supportedMethods != selectedMethod.methodName
      ) {
        return false;
      }
      let supportedNetworks =
        (modifier.data && modifier.data.supportedNetworks) || [];
      return (
        !supportedNetworks.length ||
        supportedNetworks.includes(selectedMethod["cc-type"])
      );
    });
    return appliedModifier || null;
  },

  /**
   * @param {object} state object representing the UI state
   * @returns {object} in the shape of `nsIPaymentItem` representing the total
   *                   that applies to the selected payment method.
   */
  getTotalItem(state) {
    let methodID = state.selectedPaymentCard;
    if (methodID) {
      let modifier = paymentRequest.getModifierForPaymentMethod(
        state,
        methodID
      );
      if (modifier && modifier.hasOwnProperty("total")) {
        return modifier.total;
      }
    }
    return state.request.paymentDetails.totalItem;
  },

  onPaymentRequestUnload() {
    // remove listeners that may be used multiple times here
    window.removeEventListener("paymentChromeToContent", this);
  },

  _sortObjectsByTimeLastUsed(objects) {
    let sortedValues = Object.values(objects).sort((a, b) => {
      let aLastUsed = a.timeLastUsed || a.timeLastModified;
      let bLastUsed = b.timeLastUsed || b.timeLastModified;
      return bLastUsed - aLastUsed;
    });
    let sortedObjects = {};
    for (let obj of sortedValues) {
      sortedObjects[obj.guid] = obj;
    }
    return sortedObjects;
  },

  getAddresses(state) {
    let addresses = Object.assign(
      {},
      state.savedAddresses,
      state.tempAddresses
    );
    return this._sortObjectsByTimeLastUsed(addresses);
  },

  getBasicCards(state) {
    let cards = Object.assign({}, state.savedBasicCards, state.tempBasicCards);
    return this._sortObjectsByTimeLastUsed(cards);
  },

  maybeCreateFieldErrorElement(container) {
    let span = container.querySelector(".error-text");
    if (!span) {
      span = document.createElement("span");
      span.className = "error-text";
      container.appendChild(span);
    }
    return span;
  },
};

paymentRequest.init();

export default paymentRequest;