/
orders.js
500 lines (403 loc) · 17.7 KB
/
orders.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
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
// ---------------------------------------------------------
// Security (well, not really security, but a helper to
// redirect the user if they're not logged in. Security
// is handled by the REST API.
// ---------------------------------------------------------
var redirectToLogin = function () {
var location_href = "index.html";
if (location.hash && location.hash.length > 0) {
location_href += "?hash=" + location.hash.substring(1);
}
location.href = location_href;
};
var theDocument = jQuery(document);
theDocument.ajaxSend(function (event, xhr) {
var cartId = getCookie('UltraCartShoppingCartID');
var merchantId = window.merchantId || getCookie('UltraCartMerchantID');
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("X-UC-Merchant-Id", merchantId);
xhr.setRequestHeader("X-UC-Shopping-Cart-Id", cartId);
});
theDocument.ajaxError(function (event, xhr) {
if (xhr.status === 401)
redirectToLogin();
});
jQuery.ajaxSetup({cache: false});
// ---------------------------------------------------------
// app skeleton
// ---------------------------------------------------------
var app = {
models: {}, // The M in MVC
collections: {}, // Also the M in MVC, just collections of them.
views: {}, // The V in MVC
templates: [],
zombieHunters: {}, // extensions that clean up event binding to avoid zombie event handlers
commonFunctions: {}, // functions that are used in numerous places
// the router is kind-of the C in MVC, but not in the traditional sense. It's more of a helper controller,
// which takes a look at the url (and fragments), and does additional things based on what it is.
// the router is created during document.ready
router: null,
data: {} // this will hold *instances* of collections and models. This is actual data, not definitions
};
// ---------------------------------------------------------------------
// --- zombie hunters (prevent orphaned event handlers)
// ---------------------------------------------------------------------
app.zombieHunters.appView = uc.commonFunctions.createAppView('orders');
// ---------------------------------------------------------
// common functions
// ---------------------------------------------------------
// ---------------------------------------------------------
// data models
// ---------------------------------------------------------
app.models.Order = Backbone.Model.extend({
'idAttribute': 'orderId',
url: function () {
// restUrl is defined in myaccount_rest_X.X.js
return restUrl + '/orders/' + this.get('orderId')
}
});
app.collections.Orders = uc.collections.PagedCollection.extend({
model: app.models.Order,
// restUrl is defined in myaccount_rest_X.X.js
url: restUrl + '/orders',
everBeenFetched: false
});
// an empty disconnected model used to prevent the same query from running multiple times simultaneously. (i.e. user clicks button numerous times)
app.models.StateManager = Backbone.Model.extend();
// ---------------------------------------------------------
// views
// ---------------------------------------------------------
// ---------------------------------------------------------------------
// --- Order ---
// ---------------------------------------------------------------------
app.views.Order = Backbone.View.extend({
tagName: 'article',
events: {
"click .reviewButton": 'showReviewItems',
"click .reviewItemSelector": 'redirectToReview',
"click .trackingButton": 'showTracking',
"click .commentButton": 'showComments',
"click .case-message-button": 'sendFeedback'
},
single: false, // if true, this model should listen to its own model event triggers
'onClose': function () {
if (this.single) {
this.model.on('sync', this.render, this);
}
},
initialize: function (attributes, options) {
if (options && options.single) {
this.model.on('sync', this.render, this);
this.single = true;
}
_.bindAll(this);
},
render: function () {
// console.log('order ' + this.model.get('orderId') + ' render');
var context = this.model.attributes;
this.$el.html(app.templates.order(context));
this.$el.addClass('order');
return this;
},
'redirectToReview': function (event) {
var element = jQuery(event.target);
// noinspection SpellCheckingInspection
var itemId = element.attr('data-itemid');
location.href = "https://secure.ultracart.com/cgi-bin/UCReviewItem?merchantId=" + encodeURIComponent(this.model.get('merchantId')) + "&itemId=" + encodeURIComponent(itemId);
},
'showReviewItems': function () {
// check to see if there's only one item. If so, just redirect to that.
var items = this.model.get('items');
if (items && items.length === 1) {
var itemId = items[0].itemId;
location.href = "https://secure.ultracart.com/cgi-bin/UCReviewItem?merchantId=" + encodeURIComponent(this.model.get('merchantId')) + "&itemId=" + encodeURIComponent(itemId);
} else {
jQuery('.reviewItemsPanel', this.$el).show();
}
},
'showComments': function () {
var that = this;
if (this.model.get('orderCase')) {
// load up all the messages.
ultracart.myAccount.getOrderCaseMessages(this.model.get('orderId'), {
success: function (messages) {
that.model.get('orderCase').messages = messages;
that.render();
jQuery('.case-container', that.$el).show();
}, failure: function () {
alert('Your comments for this order cannot be loaded at this time. Please try again later. Sorry.');
}
});
} else {
jQuery('.case-container', this.$el).show();
}
},
'sendFeedback': function () {
var that = this;
var message = jQuery.trim(jQuery('.case-message-field', this.$el).val());
if (!message) {
alert('Please enter a message before continuing.');
return;
}
var subject = jQuery.trim(jQuery('.case-subject-field').val());
if (!subject) {
subject = "Feedback for Order #" + this.model.get('orderId');
}
var hasCase = !!this.model.get('orderCase');
if (hasCase) {
ultracart.myAccount.insertOrderCaseMessage(this.model.get('orderId'), message, {
'success': function (caseMessage) {
var messages = that.model.get('orderCase').messages || [];
messages.push(caseMessage);
that.model.get('orderCase').messages = messages;
that.render();
jQuery('.case-container', that.$el).show();
}, 'failure': function () {
alert('Your comments failed to send. Please try again later. Sorry.');
}
});
} else {
// need to create the case as well.
var orderCase = {
subject: subject,
messages: [
{message: message}
]
};
ultracart.myAccount.insertOrderCase(this.model.get('orderId'), orderCase, {
'success': function (result) {
that.model.set({'orderCase': result}, {silent: true});
that.render();
jQuery('.case-container', that.$el).show();
}, 'failure': function () {
alert('Your comments failed to send. Please try again later. Sorry.');
}
});
}
},
'showTracking': function () {
jQuery('.tracking-container', this.$el).show();
var that = this;
var orderId = this.model.get('orderId');
ultracart.myAccount.getOrderTracking(orderId, {
success: function (tracking) {
if (tracking && tracking.length === 0) {
alert('Sorry. There is no tracking information available for this order at this time.');
} else {
var html = app.templates.tracking({tracking: tracking});
jQuery('.tracking-container', that.$el).html(html);
}
},
failure: function () {
alert('Sorry. Tracking Information could not be loaded at this time.');
}
});
}
});
// ---------------------------------------------------------------------
// --- Orders ---
// ---------------------------------------------------------------------
app.views.Orders = Backbone.View.extend({
tagName: 'div',
childViews: [],
events: {
"click a.orderNavCell": "gotoPage"
},
'onClose': function () {
this.collection.off('sync reset change', this.render, this);
this.closeChildren();
// dispose of the children
_.each(this.childViews, function (view) {
view.close();
});
},
initialize: function () {
this.collection.on('sync reset change', this.render, this);
_.bindAll(this);
},
render: function () {
// console.log('orders.render');
// these pagination variables are set auto-magically by the PagedCollection model based on headers returned in the query
var firstRecordOnPage = ((this.collection.pageNumber - 1) * this.collection.pageSize) + 1;
var lastRecordOnPage = Math.min(this.collection.pageNumber * this.collection.pageSize, this.collection.totalRecords);
var duration = 'this time period';
var timeFilter = document.getElementById('timeFilter');
if (timeFilter && timeFilter.selectedIndex > 0) {
duration = timeFilter.options[timeFilter.selectedIndex].text;
}
var context = null;
if (this.collection.everBeenFetched) {
context = {
'isFilterByTime': !!this.isFilterByTime,
'isSearch': !!this.isSearch,
'loading': false,
'showPagination': this.collection.length > 0,
'totalRecords': this.collection.totalRecords,
'pageNumber': this.collection.pageNumber,
'totalPages': this.collection.totalPages,
'timePeriod': duration,
'firstRecordOnPage': firstRecordOnPage,
'lastRecordOnPage': lastRecordOnPage,
'showGotoPage': this.collection.totalPages > 1,
'showPrevious': this.collection.pageNumber > 1,
'showNext': this.collection.pageNumber < this.collection.totalPages
};
} else {
context = {
'loading': true,
'showPagination': false
};
}
this.$el.html(app.templates.orders(context));
var that = this;
// the first time, we don't need to do any clean up. but subsequent render() calls need to close down any
// existing views to avoid zombie event handlers.
this.closeChildren();
this.childViews = []; // re-init on each render so we capture any and all changed.
this.collection.each(function (model) {
that.childViews.push(new app.views.Order({model: model}));
});
var ordersDiv = jQuery('#orders', this.el);
_.each(this.childViews, function (view) {
view.render();
ordersDiv.append(view.el);
});
if (this.childViews.length === 0) {
ordersDiv.append("No orders found.");
}
return this;
},
'closeChildren': function () {
_.each(this.childViews, function (view) {
view.close();
});
},
'gotoPage': function (event) {
event.preventDefault();
var anchor = jQuery(event.target);
var page = anchor.text();
var currentPage = this.collection.pageNumber;
if (page === 'Previous') {
this.collection.queryParameters[this.collection.paginationParameters['pageNumber']] = currentPage - 1;
} else if (page === 'Next') {
this.collection.queryParameters[this.collection.paginationParameters['pageNumber']] = currentPage + 1;
}
// apply the time filter if there is one.
var options = {};
if (this.isSearch) {
var search = jQuery.trim(jQuery('#searchOrdersField').val());
if (search) {
options['data'] = {'search': search}
}
} else {
var filter = jQuery('#timeFilter').val();
if (filter) {
options['data'] = {'_filterTime': filter}
}
}
if (!app.data.stateManager.get('orderQuery')) {
app.data.stateManager.set({'orderQuery': true});
this.collection.fetch(options).always(function () {
app.data.stateManager.set({'orderQuery': false});
});
}
}
});
// ---------------------------------------------------------------------
// --- router (a kind of controller) ---
// ---------------------------------------------------------------------
app.Router = Backbone.Router.extend({
routes: {
"": "defaultRoute",
"filter/:timeFrame": "filterByTime",
"search/:phrase": "search",
"order/:orderId": "loadSingleOrder"
},
'defaultRoute': function () {
// console.log('router:defaultRoute');
jQuery('#timeFilter').val("last6months");
var ordersView = new app.views.Orders({'collection': app.data.orders});
ordersView.isFilterByTime = true;
ordersView.isSearch = false;
app.data.orders.everBeenFetched = false; // reset the fetch so the 'please wait' shows again.
app.zombieHunters.appView.showView(ordersView);
// everBeenFetched is a collection property used to distinguish between an initial page load and when there are no records
// returned from the server. The former should show 'please wait, loading records', the latter should show 'no records found'
app.data.orders.fetch({
success: function (collection) {
collection.everBeenFetched = true;
}
});
},
'filterByTime': function (timeFrame) {
// console.log('router:filterByTime');
// update the select box appropriately. It may already be this values if it triggered the hash change. doesn't matter.
jQuery('#timeFilter').val(timeFrame);
var ordersView = new app.views.Orders({'collection': app.data.orders});
ordersView.isFilterByTime = true;
ordersView.isSearch = false;
app.data.orders.everBeenFetched = false; // reset the fetch so the 'please wait' shows again.
app.zombieHunters.appView.showView(ordersView);
// everBeenFetched is a collection property used to distinguish between an initial page load and when there are no records
// returned from the server. The former should show 'please wait, loading records', the latter should show 'no records found'
app.data.orders.fetch({
data: {'_filterTime': timeFrame},
success: function (collection) {
collection.everBeenFetched = true;
}
});
},
'search': function (phrase) {
var ordersView = new app.views.Orders({'collection': app.data.orders});
ordersView.isSearch = true;
ordersView.isFilterByTime = false;
app.data.orders.everBeenFetched = false; // reset the fetch so the 'please wait' shows again.
app.zombieHunters.appView.showView(ordersView);
// everBeenFetched is a collection property used to distinguish between an initial page load and when there are no records
// returned from the server. The former should show 'please wait, loading records', the latter should show 'no records found'
app.data.orders.fetch({
data: {'search': phrase},
success: function (collection) {
collection.everBeenFetched = true;
}
});
},
'loadSingleOrder': function (orderId) {
// console.log('router:loadSingleOrder');
var model = new app.models.Order({'orderId': orderId});
var orderView = new app.views.Order({'model': model}, {single: true});
app.zombieHunters.appView.showView(orderView);
model.fetch();
}
});
jQuery(document).ready(function () {
enablePleaseWaitMessage();
// fill in the date search with the last 10 years.
var dt = new Date();
var year = dt.getFullYear();
var html = '';
for (var i = 0; i < 10; i++) {
html += "<option value='year-" + (year - i) + "'>" + (year - i) + "</option>";
}
jQuery('#timeFilter').append(html);
// bind any non-backbone js events
jQuery('#filterOrdersButton').bind('click', function () {
var timeFrame = jQuery('#timeFilter').val();
if (timeFrame) {
app.router.navigate('#filter/' + timeFrame, {trigger: true});
}
});
jQuery('#searchOrdersButton').unbind().bind('click', function () {
var search = jQuery.trim(jQuery('#searchOrdersField').val());
if (search) {
app.router.navigate('#search/' + encodeURIComponent(search), {trigger: true});
}
});
app.data.stateManager = new app.models.StateManager();
app.data.orders = new app.collections.Orders();
app.templates.order = Handlebars.compile(jQuery('#order-template').html());
app.templates.orders = Handlebars.compile(jQuery('#orders-template').html());
app.templates.tracking = Handlebars.compile(jQuery('#tracking-template').html());
app.router = new app.Router();
Backbone.history.start({root: document.location.pathname});
});