This repository was archived by the owner on Sep 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.js
461 lines (404 loc) · 13.5 KB
/
index.js
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
import API from "micro-api-client";
import {calculatePrices} from "./calculator";
import {checkClaims} from './claims';
const HTTPRegexp = /^http:\/\//;
const cartKey = "gocommerce.shopping-cart";
const vatnumbers = {};
function getPrice(prices, currency, user) {
return prices
.filter((price) => currency == (price.currency || "USD").toUpperCase())
.filter((price) => price.claims ? checkClaims(user && user.claims && user.claims(), price.claims) : true)
.map((price) => {
price.cents = price.cents || parseInt(parseFloat(price.amount) * 100);
return price;
})
.sort((a, b) => a.cents - b.cents)[0];
}
function priceObject(cents, currency) {
return {cents, amount: centsToAmount(cents), currency};
}
function addPrices(...prices) {
const result = {
cents: 0,
};
prices.forEach((price) => {
if (price) {
if (!price.hasOwnProperty("cents")) {
price.cents = parseInt(parseFloat(price.amount) * 100);
}
result.cents += price.cents;
result.currency = price.currency;
}
});
result.amount = centsToAmount(result.cents);
return result;
}
function centsToAmount(cents) {
return `${(Math.round(cents) / 100).toFixed(2)}`;
}
function pathWithQuery(path, params) {
if (params) {
const query = [];
for (const key in params) {
query.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
}
return `${path}?${query.join("&")}`;
}
return path;
}
export default class GoCommerce {
constructor(options) {
if (!options.APIUrl) {
throw('You must specify an APIUrl of your GoCommerce instance');
}
if (options.APIUrl.match(HTTPRegexp)) {
console.log('Warning:\n\nDO NOT USE HTTP IN PRODUCTION FOR GOCOMMERCE EVER!\GOCOMMERCE REQUIRES HTTPS to work securely.')
}
this.cartKey = options.cartKey || cartKey;
this.api = new API(options.APIUrl);
this.currency = options.currency || "USD";
this.billing_country = options.country;
this.settings_path = "/gocommerce/settings.json";
this.settings_refresh_period = options.settingsRefreshPeriod || (10 * 60 * 1000);
this.loadCart();
}
setUser(user) {
this.user = user;
}
addToCart(item) {
const {path, quantity, meta} = item;
if (quantity && path) {
return fetch(path).then((response) => {
if (!response.ok) { return Promise.reject(`Failed to fetch ${path}`); }
return response.text().then((html) => {
const doc = document.implementation.createHTMLDocument("product");
doc.documentElement.innerHTML = html;
const products = Array.from(doc.getElementsByClassName("gocommerce-product"))
.map((el) => JSON.parse(el.innerHTML));
if (products.length === 0) {
return Promise.reject("No .gocommerce-product found in product path");
}
const sku = products.length === 1 ? (item.sku || products[0].sku) : item.sku;
const product = products.find((prod) => prod.sku === sku);
if (!product) {
return Promise.reject(`No .gocommerce-product matching sku=${sku} found in product path`);
}
const {title, prices, description, type, vat} = product;
if (sku && title && prices) {
if (this.line_items[sku]) {
this.line_items[sku].quantity += quantity;
if (meta) {
this.line_items[sku].meta = Object.assign({}, this.line_items[sku].meta, meta);
}
} else {
this.line_items[sku] = Object.assign(product, {path, meta, quantity});
}
if (item.addons && product.addons) {
this.line_items[sku].addons = product.addons.filter((addon) => item.addons.indexOf(addon.sku) !== -1);
this.line_items[sku].addonPrice = addPrices(...this.line_items[sku].addons.map((addon) => addon.price));
} else {
delete this.line_items[sku].addons;
}
return this.loadSettings().then(() => {
this.persistCart();
return this.getCart();
});
} else {
return Promise.reject("Failed to read sku, title and price from product path: %o", {sku, title, prices});
}
});
});
} else {
return Promise.reject("Invalid item - must have path and quantity");
}
}
getCartItem(item_data) {
const item = Object.assign({}, item_data, {
price: getPrice(item_data.prices, this.currency, this.user)
});
(item.price.items || []).forEach((priceItem) => {
priceItem.cents = (parseFloat(priceItem.amount) * 100).toFixed(0);
});
if (item_data.addons) {
item.addons = [];
item_data.addons.forEach((addon) => {
item.addons.push(Object.assign({}, addon, {
price: getPrice(addon.prices, this.currency, this.user)
}));
});
}
if (item.addons) {
item.addonPrice = priceObject(
item.addons.reduce((sum, addon) => sum + parseFloat(addon.price.amount) * 100, 0),
this.currency
);
}
return item;
}
calculatePrice(item_data) {
const item = this.getCartItem(item_data);
const claims = this.user && this.user.claims && this.user.claims();
return calculatePrices(this.settings, claims, this.billing_country, this.currency, this.coupon, [item]);
}
getCart() {
const cart = {items: {}};
const items = [];
for (const key in this.line_items) {
const item = cart.items[key] = this.getCartItem(this.line_items[key]);
items.push(item);
}
const claims = this.user && this.user.claims && this.user.claims();
const price = calculatePrices(this.settings, claims, this.billing_country, this.currency, this.coupon, items);
cart.subtotal = priceObject(price.subtotal, this.currency);
cart.discount = priceObject(price.discount, this.currency);
cart.couponDiscount = priceObject(price.couponDiscount, this.currency);
cart.memberDiscount = priceObject(price.memberDiscount, this.currency);
cart.taxes = priceObject(price.taxes, this.currency);
cart.total = priceObject(price.total, this.currency);
return cart;
}
setCurrency(currency) {
this.currency = currency;
return Promise.resolve(this.getCart());
}
setCountry(country) {
this.billing_country = country;
return Promise.resolve(this.getCart());
}
setVatnumber(vatnumber) {
this.vatnumber = vatnumber;
return this.verifyVatnumber(vatnumber).then(() => this.getCart());
}
setCoupon(code) {
if (code == null) {
this.coupon = null;
return Promise.resolve(null);
}
return this.verifyCoupon(code).then((coupon) => {
this.coupon = coupon;
return coupon;
});
}
updateCart(sku, quantity) {
if (this.line_items[sku]) {
if (quantity > 0) {
this.line_items[sku].quantity = quantity;
} else {
delete this.line_items[sku];
}
this.persistCart();
} else {
throw(`Item ${sku} not found in cart`);
}
}
clearCart() {
this.line_items = {};
this.persistCart();
}
order(orderDetails) {
const {
email,
shipping_address, shipping_address_id,
billing_address, billing_address_id,
data
} = orderDetails;
if (email && (shipping_address || shipping_address_id)) {
const line_items = [];
for (const id in this.line_items) {
line_items.push(this.line_items[id]);
}
return this.authHeaders().then((headers) => this.api.request("/orders", {
method: "POST",
headers: headers,
body: JSON.stringify({
email,
shipping_address, shipping_address_id,
billing_address, billing_address_id,
vatnumber: this.vatnumber_valid ? this.vatnumber : null,
currency: this.currency,
coupon: this.coupon ? this.coupon.code : null,
data,
line_items
})
})).then((order) => {
const cart = this.getCart();
return {cart, order};
});
} else {
return Promise.reject(
"Invalid orderDetails - must have an email and either a shipping_address or shipping_address_id"
);
}
}
payment(paymentDetails) {
const {order_id, amount, provider, stripe_token, paypal_payment_id, paypal_user_id} = paymentDetails;
if (order_id && amount && provider && (stripe_token || (paypal_payment_id && paypal_user_id))) {
const cart = this.getCart();
return this.authHeaders().then((headers) => this.api.request(`/orders/${order_id}/payments`, {
method: "POST",
headers: headers,
body: JSON.stringify({
amount,
order_id,
provider,
stripe_token,
paypal_payment_id,
paypal_user_id,
currency: this.currency
})
}));
} else {
return Promise.reject(
"Invalid paymentDetails - must have an order_id, an amount, a provider, and a stripe_token or a paypal_payment_id and paypal_user_id"
);
}
}
resendConfirmation(orderID, email) {
const path = `/orders/${orderID}/receipt`;
return this.authHeaders().then((headers) => this.api.request(path, {
headers,
method: "POST",
body: JSON.stringify({email})
}));
}
claimOrders() {
if (this.user) {
return this.authHeaders().then((headers) => this.api.request("/claim", {
headers,
method: "POST"
}));
}
return Promise.resolve(null);
}
updateOrder(orderId, attributes) {
return this.authHeaders(true).then((headers) => this.api.request(`/orders/${orderId}`, {
headers,
method: "PUT",
body: JSON.stringify(attributes)
}));
}
orderHistory(params) {
let path = "/orders";
if (params && params.user_id) {
path = `/users/${params.user_id}/orders`;
delete params.user_id;
}
path = pathWithQuery(path, params);
return this.authHeaders(true).then((headers) => this.api.request(path, {
headers
})).then(({items, pagination}) => ({orders: items, pagination}));
}
orderDetails(orderID) {
return this.authHeaders(true).then((headers) => this.api.request(`/orders/${orderID}`, {
headers
}));
}
orderReceipt(orderID, template) {
let path = `/orders/${orderID}/receipt`;
if (template) {
path += `?template=${template}`;
}
return this.authHeaders(true).then((headers) => this.api.request(path, {
headers
}));
}
userDetails(userId) {
userId = userId || (this.user && this.user.id);
return this.authHeaders(true).then((headers) => this.api.request(`/users/${userId}`, {
headers
}));
}
downloads(params) {
let path = "/downloads";
if (params && params.order_id) {
path = `/orders/${params.order_id}/downloads`;
delete params.order_id;
}
path = pathWithQuery(path, params);
return this.authHeaders().then((headers) => this.api.request(path, {
headers
})).then(({items, pagination}) => ({downloads: items, pagination}));
}
downloadURL(downloadId) {
const path = `/downloads/${downloadId}`;
return this.authHeaders().then((headers) => this.api.request(path, {
headers
})).then((response) => response.url);
}
users(params) {
const path = pathWithQuery("/users", params);
return this.authHeaders(true).then((headers) => this.api.request(path, {
headers
})).then(({items, pagination}) => ({users: items, pagination}));
}
report(name, params) {
const path = pathWithQuery(`/reports/${name}`, params);
return this.authHeaders(true).then((headers) => this.api.request(path, {
headers
}));
}
authHeaders(required) {
if (this.user) {
return this.user.jwt().then((token) => ({Authorization: `Bearer ${token}`}));
}
return required ? Promise.reject(
"The API action requires authentication"
) : Promise.resolve({});
}
loadCart() {
const json = localStorage.getItem(this.cartKey);
if (json) {
const cart = JSON.parse(json);
this.settings = cart.settings;
this.line_items = cart.line_items || {};
} else {
this.settings = null;
this.line_items = {};
}
}
loadSettings() {
if (this.settingsAreFresh()) { return Promise.resolve(); }
return fetch(this.settings_path).then((response) => {
if (!response.ok) { return; }
return response.json().then((json) => {
this.settings = Object.assign(json, {ts: new Date().getTime()});
});
});
}
settingsAreFresh() {
if (this.settings_path == null) { return true; }
if (this.settings) {
const diff = new Date().getTime() - this.settings.ts;
return diff < this.settings_refresh_period;
}
return false;
}
verifyVatnumber(vatnumber) {
this.vatnumber_valid = false;
if (!vatnumber) {
this.vatnumber_valid = false;
return Promise.resolve(false);
}
if (vatnumbers[vatnumber]) {
this.vatnumber_valid = vatnumbers[vatnumber].valid;
return Promise.resolve(false);
}
return this.api.request(`/vatnumbers/${vatnumber}`).then((response) => {
vatnumbers[vatnumber] = response;
this.vatnumber_valid = response.valid;
return response.valid;
});
}
verifyCoupon(code) {
return this.authHeaders(false).then((headers) => this.api.request(`/coupons/${code}`, {
headers
}));
}
persistCart() {
const json = JSON.stringify({line_items: this.line_items, settings: this.settings});
localStorage.setItem(this.cartKey, json);
}
}
if (typeof window !== "undefined") {
window.GoCommerce = GoCommerce
}