-
Notifications
You must be signed in to change notification settings - Fork 3
/
Dynamo_Client_Store_web_store.war_shared_js_pageLayout_user.js.html
executable file
·1702 lines (1555 loc) · 72.8 KB
/
Dynamo_Client_Store_web_store.war_shared_js_pageLayout_user.js.html
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: Dynamo/Client/Store/web/store.war/shared/js/pageLayout/user.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: Dynamo/Client/Store/web/store.war/shared/js/pageLayout/user.js</h1>
<section>
<article>
<pre class="prettyprint source"><code>/**
* @fileoverview Defines a UserViewModel used to register and
* login a user to the site.
*
*/
/*global $ */
/*global define */
define(
//-------------------------------------------------------------------
// PACKAGE NAME
//-------------------------------------------------------------------
'pageLayout/user',
//-------------------------------------------------------------------
// DEPENDENCIES
//-------------------------------------------------------------------
['knockout', 'pubsub', 'notifier', 'notifications', 'CCi18n', 'ccLogger',
'ccRestClient', 'ccConstants', 'koValidate', 'ccKoValidateRules',
'storeKoExtensions', 'navigation', 'storageApi', 'pageLayout/parent-organisation'],
//-------------------------------------------------------------------
// MODULE DEFINITION
//-------------------------------------------------------------------
function (ko, pubSub, notifier, notifications, CCi18n, log, ccRestClient,
CCConstants, koValidate, rules, storeKoExtensions, navigation, storageApi, ParentOrganisation) {
'use strict';
/**
* Creates a user view model.
* <p>
* The User View Model is a singleton class that provides the context for logged in
* user data, e.g. Profile data, Preferences, Shipping information.
*
* @param {RestAdapter} pAdapter REST adapter.
* @param {Object} pUserData Additional user data.
*
* @public
* @class Represents a user.
* @name UserViewModel
* @property {observable<string>} firstName First part of name
* @property {observable<string>} lastName Last part of name
* @property {observable<string>} loggedInUserName Logged in username.
* @property {observable<string>} emailAddress Primary communication email address.
* @property {observable<string>} emailAddressForForgottenPwd Email address to use for password retrieval.
* @property {observable<string>} emailMarketingMails Email address to use for marketing messages.
* @property {observable<boolean>} emailMarketingModified Flag showing if the marketing email field is modified.
* @property {observable<string>} password Password.
* @property {observable<string>} oldPassword Existing password field on change password form.
* @property {observable<string>} newPassword New password field on change password form.
* @property {observable<string>} confirmPassword Confirm password field on change password form.
* @property {observableArray<Address>} shippingAddressBook Shipping addresses associated with user.
* @property {observable<Address>} defaultShippingAddress helper for default address selection.
* @property {observable<Address>} editShippingAddress Address object shown on editable address form.
* @property {observable<boolean>} deleteShippingAddress Flag set to true if an address is being deleted.
* @property {observable<string>} locale User locale.
* @property {observable<boolean>} loggedinAtCheckout Flag to determine if user is logged in on the checkout page.
* @property {observable<boolean>} loggedoutAtCheckout Flag to determine if user if logged out on the checkout page.
* @property {observable<Object>} persistedOrder Saved recent, or in progress order.
* @property {observable<string>} orderId ID of recent, or in progress order.
* @property {observable<number>} countOfSubmittedOrders Track number of orders created by user.
* @property {observable<boolean>} ignoreEmailValidation Flag to temporarily ignore validation on email address field.
* @property {observable<boolean>} ignorePasswordValidation Flag to temporarily ignore validation on password field.
* @property {observable<boolean>} isUserProfileEdited Whether the User profile has unsaved changes.
* @property {observable<boolean>} delaySuccessNotification Whether to delay the notification popup.
* @property {observable<boolean>} isSearchInitiatedWithUnsavedChanges Whether there are unsaved changes when a search is initiated.
* @property {observable<boolean>} isUserSessionExpired True if the user's session has expired.
* @property {observable<string>} pageToRedirect Hash code for page redirection
* @property {observable<boolean>} isSessionExpiredDuringSave True if the user's session expires when a save operation is in progress.
* @property {observable<boolean>} isUserLoggedOut True if user has logged out.
* @property {observable<boolean>} isPageRedirected True if page was redirected.
* @property {observable<boolean>} isResourcesLoaded True when resources are loaded.
* @property {observable<string>} errorMessageKey Resource key to look up current error notification message.
* @property {observable<string>} successMessageKey Resource key to look up current success notification message.
* @property {observable<Object[]>} passwordPolicies List of store specific password rules enabled for user accounts.
* @property {observable<boolean>} isChangePassword Flag to determine if we need to display the password change fields.
* @property {observable<boolean>} showCreateNewPasswordMsg Flag to determine whether to display the new password prompt.
* @property {observable<string>} createNewPasswordError Message to display if password creation failed.
* @property {observable<boolean>} isPasswordExpired True if password has expired.
* @property {observable<boolean>} hasFieldLevelError True if any of the fields on the profile has an error.
* @property {observable<boolean>} ignoreConfirmPasswordValidation Flag to temporarily ignore validation on the confirm password field.
* @property {observable<string>} forgotPasswordMsg Localisable message for 'forgotten password' link.
* @property {observable<Object[]>} myWishLists List of owned wish lists
* @property {observable<Object[]>} joinedWishLists List of joined wish lists
*/
function UserViewModel(pAdapter, pUserData) {
if (UserViewModel.singleInstance) {
throw new Error("Cannot instantiate more than one UserViewModel, use getInstance(pAdapter, pUserData)");
}
var self = this;
// Adding user data from server to the view model
// Currently ignoring the 'links' property as it is not being used and causing problems in ccLink custom binding
ko.mapping.fromJS(pUserData, {'ignore': ["links"]}, self);
// Values from context
self.id = ko.observable('');
self.login = ko.observable('');
self.adapter = pAdapter;
// Flags
self.resetAll = ko.observable(false);
// Values to be entered
self.emailAddress = ko.observable('');
self.emailAddressForForgottenPwd = ko.observable('');
self.emailMarketingMails = ko.observable(false);
self.emailMarketingModified = ko.observable(false);
self.firstName = ko.observable('');
self.loggedInUserName = ko.observable('');
self.lastName = ko.observable('');
self.password = ko.observable('');
self.newPassword = ko.observable('');
self.confirmPassword = ko.observable('');
self.shippingAddressBook = ko.observableArray().extend({ deferred: true });
self.defaultShippingAddress = ko.observable(); // For default address radio selection.
self.editShippingAddress = ko.observable(); // Used when the edit address form is displayed.
self.deleteShippingAddress = ko.observable(false);
self.locale = ko.observable('');
self.client = ko.observable(ccRestClient);
self.loginError = ko.observable('');
self.loggedIn = ko.observable(self.client().loggedIn);
self.isLoginFailed = ko.observable(false);
self.readyToDisplay = ko.observable(true);
self.oldPassword = ko.observable('');
self.emailAddress.isData = true;
self.firstName.isData = true;
self.lastName.isData = true;
self.password.isData = true;
self.newPassword.isData = true;
self.confirmPassword.isData = true;
self.oldPassword.isData = true;
self.emailAddressForForgottenPwd.isData = true;
self.locale.isData = true;
self.loggedinAtCheckout = ko.observable(false);
self.loggedoutAtCheckout = ko.observable(false);
self.persistedOrder = ko.observable();
self.orderId = ko.observable('');
self.countOfSubmittedOrders = ko.observable(0);
self.ignoreEmailValidation = ko.observable(true);
self.ignorePasswordValidation = ko.observable(true);
self.isUserProfileEdited = ko.observable(false);
self.delaySuccessNotification = ko.observable(false);
self.isSearchInitiatedWithUnsavedChanges = ko.observable(false);
self.isUserSessionExpired = ko.observable(false);
self.pageToRedirect = ko.observable();
self.isSessionExpiredDuringSave = ko.observable(false);
self.isUserLoggedOut = ko.observable(true);
self.isPageRedirected = ko.observable(false);
self.isResourcesLoaded = ko.observable(false);
self.errorMessageKey = ko.observable('');
self.successMessageKey = ko.observable('');
// Sets the password policies
self.passwordPolicies = ko.observable();
// Checks whether the case is a change password
self.isChangePassword = ko.observable(false);
self.showCreateNewPasswordMsg = ko.observable(false);
self.createNewPasswordError = ko.observable('');
self.isPasswordExpired = ko.observable(false);
self.hasFieldLevelError = ko.observable(false);
self.ignoreConfirmPasswordValidation = ko.observable(true);
self.forgotPasswordMsg = ko.observable('');
// Social Wish List
self.myWishLists = ko.observableArray();
self.joinedWishLists = ko.observableArray();
self.isSesExpDuringPlaceOrder = ko.observable(false);
// B2B ViewModel
self.parentOrganization = new ParentOrganisation();
self.refreshPageAfterContactLogout = ko.observable(false);
self.catalogId = ko.observable('');
/**
* Callback invoked when email address field receives focus. Disables email validation.
*
* @function
* @name UserViewModel#emailAddressFocused
*/
self.emailAddressFocused = function() {
self.ignoreEmailValidation(true);
return true;
};
/**
* Callback invoked when email address field loses focus. Re-enable email validation.
*
* @function
* @name UserViewModel#emailAddressLostFocus
*/
self.emailAddressLostFocus = function() {
self.ignoreEmailValidation(false);
return true;
};
self.updatedShippingAddress = null;
self.updatedShippingAddressBook = null;
/*
* Callback invoked when confirm password field is modified.
*/
self.confirmPassword.subscribe(function(newValue) {
self.newPassword.isModified(true);
});
/*
* Callback invoked when marketing emails field is modified.
*/
self.emailMarketingMails.subscribe(function(newValue) {
self.emailMarketingModified(true);
});
/**
* Callback to update shipping address if modified from other parts of the site. Invoked on
* receiving a CHECKOUT_SAVE_SHIPPING_ADDRESS pubsub event.
*
* @private
* @function
* @name UserViewModel#updateShippingAddress
*/
self.updateShippingAddress = function(opts) {
// Now if any other module is updating a shipping address on the User Profile, it will just be
// adding a secondary address.
if (self.shippingAddressBook()) {
this.isDefaultAddress(self.shippingAddressBook().length === 0);
if (!self.isAddressSaved(this) && this.isValid()) {
self.shippingAddressBook.push(this);
}
}
};
/**
* Updates the locale associated to this user. Invoked on receiving
* a CHECKOUT_USER_LOCALE pubsub event.
*
* @private
* @function
* @name UserViewModel#updateLocale
*/
self.updateLocale = function() {
self.locale(this);
};
/**
* Updates the user locale when it is not part of supported locales. Invoked on receiving
* a USER_LOCALE_NOT_SUPPORTED pubsub event.
*
* @private
* @function
* @name UserViewModel#updateLocaleToSupported
*/
self.updateLocaleToSupported = function() {
if (self.locale.isModified !== undefined) {
var currentLocale = ccRestClient.getStoredValue(CCConstants.LOCAL_STORAGE_USER_CONTENT_LOCALE);
if (currentLocale) {
self.locale(JSON.parse(currentLocale)[0].name);
} else {
self.locale(self.contextData.global.locale);
}
self.locale.isModified(true);
$.Topic(pubSub.topicNames.USER_PROFILE_UPDATE_SUBMIT).publishWith(self, [{message: "success"}]);
self.locale.isModified(false);
$.Topic(pubSub.topicNames.UPDATE_USER_LOCALE_NOT_SUPPORTED_ERROR).publish();
}
};
/*
* This computed will return whether the error message on the
* create new password modal should be visible or not.
*/
self.showExpiredPasswordErrorMsg = ko.computed(function() {
if (self.isPasswordExpired() &&
((self.oldPassword.isModified() && !self.oldPassword.isValid()) ||
(self.newPassword.isModified() && !self.newPassword.isValid()) ||
(self.confirmPassword.isModified() && !self.confirmPassword.isValid()) ||
self.hasFieldLevelError())) {
return false;
}
return true;
}, self);
/**
* Handle the validation of the user data entered while creating an account.
*
* @function
* @name UserViewModel#validateUser
* @returns {boolean} <code>true</code> if the user details are valid, and
* <code>false</code> otherwise.
*/
self.validateUser = function() {
self.ignoreEmailValidation(false);
self.ignorePasswordValidation(false);
self.ignoreConfirmPasswordValidation(false);
self.emailAddress.isModified(true);
self.firstName.isModified(true);
self.lastName.isModified(true);
self.newPassword.isModified(true);
self.confirmPassword.isModified(true);
return self.isValid();
};
/**
* Check if the complete user profile is valid by checking the components.
*
* @function
* @name UserViewModel#isValid
* @returns {boolean} true if the user profile is valid, otherwise false.
*/
self.isValid = function() {
return (self.emailAddress.isValid() &&
self.firstName.isValid() &&
self.lastName.isValid() &&
self.newPassword.isValid() &&
self.confirmPassword.isValid()
);
};
/**
* Reset all registration details.
*
* @function
* @name UserViewModel#reset
*/
self.reset = function() {
if (self.isUserLoggedOut() || (!self.loggedIn() && !self.isUserSessionExpired())) {
self.login('');
if (self.isResourcesLoaded()) {
self.login.isModified(false);
}
self.loggedInUserName('');
}
self.emailAddress('');
self.firstName('');
self.lastName('');
self.loginError('');
self.resetPassword();
self.isLoginFailed(false);
self.emailMarketingMails(false);
if (self.isResourcesLoaded()) {
self.lastName.isModified(false);
self.emailAddress.isModified(false);
self.firstName.isModified(false);
}
};
/**
* Reset the password field.
*
* @function
* @name UserViewModel#resetPassword
*/
self.resetPassword = function() {
self.password('');
self.newPassword('');
self.confirmPassword('');
self.oldPassword('');
if (self.isResourcesLoaded()) {
self.password.isModified(false);
self.newPassword.isModified(false);
self.confirmPassword.isModified(false);
self.oldPassword.isModified(false);
}
self.isChangePassword(false);
};
/**
* Reset all the details from the registration fields without
* resetting the email address.
*
* @function
* @name UserViewModel#resetDetails
*/
self.resetDetails = function() {
self.firstName('');
self.lastName('');
self.resetPassword();
self.emailMarketingMails(false);
self.firstName.isModified(false);
self.lastName.isModified(false);
self.emailMarketingModified(false);
};
/**
* Handle the validation of login.
*
* @function
* @name UserViewModel#isLoginValid
* @returns {boolean} true if login is valid, otherwise false.
*/
self.isLoginValid = function() {
self.ignoreEmailValidation(false);
return (this.login.isValid()
&& this.password.isValid());
};
/**
* Handle the validation of user data entered during login. Also raises the modified flags on
* login and password fields.
*
* @function
* @name UserViewModel#validateLogin
* @returns {boolean} true if login is valid, otherwise false.
*/
self.validateLogin = function() {
var self = this;
self.login.isModified(true);
self.password.isModified(true);
return self.isLoginValid();
};
/**
* Reset login details.
*
* @function
* @name UserViewModel#resetLoginData
*/
self.resetLoginData = function() {
var self = this;
self.login('');
self.password('');
self.loginError('');
self.isLoginFailed(false);
if (self.isResourcesLoaded()) {
self.login.isModified(false);
self.password.isModified(false);
}
};
/**
* Reset modified flags on knockout observables.
*
* @function
* @name UserViewModel#resetModified
*/
self.resetModified = function() {
var self = this;
self.emailAddress.isModified(false);
self.firstName.isModified(false);
self.lastName.isModified(false);
self.oldPassword.isModified(false);
self.newPassword.isModified(false);
self.confirmPassword.isModified(false);
self.emailMarketingModified(false);
};
/**
* Reset modified flags of address objects in the address book.
*
* @function
* @name UserViewModel#resetShippingAddressBookModified
*/
self.resetShippingAddressBookModified = function() {
var self = this;
ko.utils.arrayForEach(self.shippingAddressBook(), function (shippingAddress) {
shippingAddress.resetModified();
});
};
/**
* Check whether profile is modified.
*
* @function
* @name UserViewModel#isProfileModified
* @returns {boolean} true if profile has been modified, otherwise false.
*/
self.isProfileModified = function() {
// Checking whether user basic profile has been modified.
if (self.firstName.isModified() || self.lastName.isModified() ||
self.emailAddress.isModified() || self.emailMarketingModified() || self.locale.isModified()) {
return true;
}
return false;
};
/**
* Check whether any of the password fields have been
* modified: oldPassword, newPassword, confirmPassword.
*
* @function
* @name UserViewModel#isPasswordModified
* @returns {boolean} true if any password fields are modified, otherwise false.
*/
self.isPasswordModified = function() {
if (self.oldPassword.isModified() || self.newPassword.isModified() || self.confirmPassword.isModified()) {
return true;
}
return false;
};
/**
* Check whether all password fields are valid.
*
* @function
* @name UserViewModel#isPasswordValid
* @returns {boolean} true if all password fields are valid, otherwise false.
*/
self.isPasswordValid = function () {
self.oldPassword.isModified(true);
self.newPassword.isModified(true);
self.confirmPassword.isModified(true);
// Checking whether user password fields are valid.
if (self.oldPassword.isValid() && self.newPassword.isValid() &&
self.confirmPassword.isValid()) {
return true;
}
return false;
};
/**
* Check whether profile is valid.
*
* @function
* @name UserViewModel#isProfileValid
* @returns {boolean} true if the profile is valid, otherwise false.
*/
self.isProfileValid = function () {
self.firstName.isModified(true);
self.lastName.isModified(true);
self.emailAddress.isModified(true);
self.ignoreEmailValidation(false);
// Checking whether user basic profile has been modified.
if (self.firstName.isValid() && self.lastName.isValid() &&
self.emailAddress.isValid()) {
return true;
}
return false;
};
/**
* Checks if the supplied address already exists in the profile address book.
*
* @function
* @name UserViewModel#isAddressSaved
* @param {Address} addr An address object.
* @returns {boolean} true if the address is already present, otherwise false.
*/
self.isAddressSaved = function (addr) {
for (var k = 0; k < self.shippingAddressBook().length; k++) {
if (addr.compare(self.shippingAddressBook()[k]))
{
return true;
}
}
return false;
};
/**
* Returns true if current user is b2b user.
*/
self.isB2BUser = function(){
if(self.parentOrganization && self.parentOrganization.name()) {
return true;
}
return false;
}
/**
* Check if the shipping address book contains any addresses which have been modified.
*
* @function
* @name UserViewModel#isShippingAddressBookModified
* @returns true if any shipping addresses are modified, otherwise false.
*/
self.isShippingAddressBookModified = function() {
if (self.deleteShippingAddress())
{
return true;
}
for (var k = 0; k < self.shippingAddressBook().length; k++) {
if (self.shippingAddressBook()[k].isModified())
{
return true;
}
}
return false;
};
/**
* Check if all the addresses in the shipping address book are valid.
*
* @function
* @name UserViewModel#isShippingAddressBookValid
* @returns true if all shipping addresses are valid, otherwise false.
*/
self.isShippingAddressBookValid = function() {
for (var k = 0; k < self.shippingAddressBook().length; k++) {
if (!self.shippingAddressBook()[k].isValid())
{
return false;
}
}
return true;
};
/**
* Select a default shipping address from the shipping address book.
* Assumes that addr is a reference to an Address object that already exists in the address book.
*
* @function
* @name UserViewModel#selectDefaultAddress
* @param {Address} addr An address object.
*/
self.selectDefaultAddress = function(addr) {
for (var k = 0; k < self.shippingAddressBook().length; k++) {
var shippingAddress = self.shippingAddressBook()[k];
shippingAddress.isDefaultAddress(shippingAddress === addr);
}
};
/**
* Sort the addresses in shipping address book by the following requirements:
*
* <ol>
* <li>Default Shipping Address should always be first.</li>
* <li>Then sort addresses by Last Name in ascending order.</li>
* <li>Then sort addresses by Address Line 1 in ascending order.</li>
* </ol>
*
* @private
* @function
* @name UserViewModel#sortShippingAddresses
*/
self.sortShippingAddresses = function () {
if (self.updatedShippingAddressBook && self.updatedShippingAddressBook.length) {
self.updatedShippingAddressBook.sort(function(left, right) {
// Default Address has the highest sort priority.
if (left.isDefaultAddress)
return -1;
if (right.isDefaultAddress)
return 1;
if (left.lastName.toLowerCase() == right.lastName.toLowerCase()) {
return left.address1.toLowerCase() == right.address1.toLowerCase() ? 0
: (left.address1.toLowerCase() < right.address1.toLowerCase() ? -1 : 1);
} else if (left.lastName.toLowerCase() < right.lastName.toLowerCase()) {
return -1;
} else {
return 1;
}
});
}
};
/**
* Successful Login Callback invoked on receiving a success response from the login service.
*
* @private
* @function
* @name UserViewModel#loginSuccessFunc
* @param {boolean} isAutoLogin Flag to track if user was logged in automatically, or
* if we need to reset user data.
*/
self.loginSuccessFunc = function(isAutoLogin) {
self.loggedIn(self.client().loggedIn);
self.isUserSessionExpired(false);
self.isLoginFailed(false);
self.isSesExpDuringPlaceOrder(false);
self.isUserLoggedOut(false);
self.password('');
self.password.isModified(false);
notifier.clearError(self.WIDGET_ID);
self.id(self.client().profileId);
if (self.pageToRedirect() && self.pageToRedirect()!= '' && self.pageToRedirect() != self.checkoutHash) {
var hash = self.pageToRedirect();
self.pageToRedirect(null);
if (navigation.isPathEqualTo(hash)) {
var localData = self.getLocalData();
//if the session expired during the save on my profile page and if the user logs in with the same user, then do not reload the user data
if (localData.login == self.login() && navigation.isPathEqualTo(self.myAccountHash) && !self.isPasswordExpired() && self.isSessionExpiredDuringSave()) {
//self.isSessionExpiredDuringSave(false); this is set to false on the profile page
} else {
self.getCurrentUser(isAutoLogin, true);
//if the session expired during the save on my profile page and if the user logs in with different login, then reset the user data
if (navigation.isPathEqualTo(self.myAccountHash)) {
self.isSessionExpiredDuringSave(false);
$.Topic(pubSub.topicNames.USER_PROFILE_SESSION_RESET).publish();
}
}
}
self.isPageRedirected(true);
navigation.goTo(hash);
} else {
self.getCurrentUser(isAutoLogin , true);
}
self.isPasswordExpired(false);
};
/**
* Failed Login Callback invoked on receiving an error from the login service.
*
* @private
* @function
* @name UserViewModel#loginErrorFunc
*/
self.loginErrorFunc = function() {
self.isLoginFailed(true);
self.loginError(CCi18n.t('ns.common:resources.loginError'));
self.password('');
self.password.isModified(false);
};
self.populateUserFromLocalData(false);
//section for calling the subscriptions
$.Topic(pubSub.topicNames.USER_REGISTRATION_SUBMIT).subscribe(self.registerUser);
$.Topic(pubSub.topicNames.USER_LOGIN_SUBMIT).subscribe(self.handleLogin);
$.Topic(pubSub.topicNames.USER_LOGIN_CANCEL).subscribe(self.handleCancel);
// Custom extensions for registration fields
// Wait until i18n is ready before attempting to resolve any resource bundles
// This isn't strictly required because locale *should* be ready before
// any view models are created, but just to be safe, subscribe anyway
$.Topic(pubSub.topicNames.LOCALE_READY).subscribe(self.loadResources.bind(self));
$.Topic(pubSub.topicNames.USER_PROFILE_UPDATE_SUBMIT).subscribe(self.handleUpdateProfile);
$.Topic(pubSub.topicNames.USER_PROFILE_UPDATE_CANCEL).subscribe(self.handleUpdateCancel);
$.Topic(pubSub.topicNames.PAGE_LAYOUT_LOADED).subscribe(self.handlePageChanged.bind(self));
$.Topic(pubSub.topicNames.PAGE_METADATA_CHANGED).subscribe(self.handlePageChanged.bind(self));
$.Topic(pubSub.topicNames.USER_LOGOUT_SUBMIT).subscribe(self.handleLogout.bind(self));
$.Topic(pubSub.topicNames.USER_SESSION_VALID).subscribe(self.handleSessionValid.bind(self));
$.Topic(pubSub.topicNames.USER_SESSION_EXPIRED).subscribe(self.handleSessionExpired.bind(self));
$.Topic(pubSub.topicNames.CHECKOUT_SAVE_SHIPPING_ADDRESS).subscribe(self.updateShippingAddress);
$.Topic(pubSub.topicNames.CHECKOUT_USER_LOCALE).subscribe(self.updateLocale);
$.Topic(pubSub.topicNames.USER_LOCALE_NOT_SUPPORTED).subscribe(self.updateLocaleToSupported);
return (self);
};
/**
* Intialize localized validations and error messages. Invoked on receiving a .LOCALE_READY pubsub event.
*
* @private
* @function
* @name UserViewModel#loadResources
*/
UserViewModel.prototype.loadResources = function() {
var self = this;
self.firstName.extend({ required: { params: true, message: CCi18n.t('ns.common:resources.firstNameRequired')}});
self.lastName.extend({ required: { params: true, message: CCi18n.t('ns.common:resources.lastNameRequired')}});
self.locale.extend({ required: { params: true, message: CCi18n.t('ns.common:resources.localeRequired')}});
self.emailAddressForForgottenPwd.extend({
required: { params: true, message: CCi18n.t('ns.common:resources.emailAddressRequired')},
maxLength: { params: CCConstants.CYBERSOURCE_EMAIL_MAXIMUM_LENGTH, message: CCi18n.t('ns.common:resources.maxLengthEmailAdd', {maxLength: CCConstants.CYBERSOURCE_EMAIL_MAXIMUM_LENGTH})},
email: { params: true, onlyIf: function () { return (!self.ignoreEmailValidation()); }, message: CCi18n.t('ns.common:resources.emailAddressInvalid')}
});
self.emailAddress.extend({
required: { params: true, message: CCi18n.t('ns.common:resources.emailAddressRequired')},
maxLength: { params: CCConstants.CYBERSOURCE_EMAIL_MAXIMUM_LENGTH, message: CCi18n.t('ns.common:resources.maxLengthEmailAdd', {maxLength: CCConstants.CYBERSOURCE_EMAIL_MAXIMUM_LENGTH})},
email:{ params: true, onlyIf: function () { return (!self.ignoreEmailValidation()); }, message: CCi18n.t('ns.common:resources.emailAddressInvalid')}});
self.login.extend({
required: { params: true, message: CCi18n.t('ns.common:resources.emailAddressRequired')},
maxLength: { params: CCConstants.CYBERSOURCE_EMAIL_MAXIMUM_LENGTH, message: CCi18n.t('ns.common:resources.maxLengthEmailAdd', {maxLength: CCConstants.CYBERSOURCE_EMAIL_MAXIMUM_LENGTH})},
email: { params: true, onlyIf: function () { return (!self.ignoreEmailValidation()); }, message: CCi18n.t('ns.common:resources.emailAddressInvalid')}});
self.password.extend({ required: { params: true, message: CCi18n.t('ns.common:resources.passwordRequired')}});
self.newPassword.extend({
password: { params: { policies: self.passwordPolicies, login: self.emailAddress, observable: self.newPassword, includePreviousNPasswordRule: self.isChangePassword},
onlyIf: function () { return ( (!self.ignoreEmailValidation() || self.newPassword.isModified()) && !self.ignorePasswordValidation() ); },
message: CCi18n.t('ns.common:resources.passwordPoliciesErrorText')},
required: { params: true, message: CCi18n.t('ns.common:resources.passwordRequired')}
});
self.oldPassword.extend({ required: { params: true, message: CCi18n.t('ns.common:resources.currentPasswordRequired')}});
self.confirmPassword.extend({
required: { params: true, message: CCi18n.t('ns.common:resources.confirmPasswordRequired')},
match: { params: self.newPassword, onlyIf: function () { return (!self.ignoreConfirmPasswordValidation()); }, message: CCi18n.t('ns.common:resources.passwordUnmatched')}});
self.isResourcesLoaded(true);
};
/**
* Read and populate the view model with loggedinAtCheckout, loggedoutAtCheckout,
* OrderID, loggedInUserName, login and isUserSessionExpired flags.
*
* @function
* @name UserViewModel#populateUserFromLocalData
* @param {boolean} loadAll Flag to control whether we load all data.
*/
UserViewModel.prototype.populateUserFromLocalData = function (loadAll) {
var self = this;
//load the data from local storage
var cookieData = self.getLocalData();
if (cookieData != null) {
self.loggedinAtCheckout(cookieData.loggedinAtCheckout);
self.loggedoutAtCheckout(cookieData.loggedoutAtCheckout);
self.orderId(cookieData.orderId);
if (loadAll && cookieData.login) {
self.loggedInUserName(cookieData.loggedInUserName);
self.login(cookieData.login);
self.isUserSessionExpired(cookieData.isUserSessionExpired);
self.isUserLoggedOut(cookieData.isUserLoggedOut);
}
}
};
/**
* Read loggedinAtCheckout, loggedoutAtCheckout, OrderID, loggedInUserName, login
* and isUserSessionExpired flags from the user local storage.
*
* @private
* @function
* @name UserViewModel#getLocalData
* @returns {Object} cookieData Parsed local storage data.
*/
UserViewModel.prototype.getLocalData = function () {
var self = this;
//load the data from local storage
var cookieData = null;
try {
cookieData = storageApi.getInstance().getItem("user");
if (cookieData) {
cookieData = JSON.parse(cookieData);
}
}
catch (pError) {
}
return cookieData;
};
/**
* Write the loggedinAtCheckout, loggedoutAtCheckout, OrderID, loggedInUserName, login and
* isUserSessionExpired flags to user local storage. The argument 'setParam' is a string which
* may be one of the following:
*
* <ul>
* <li><b>all</b> - Save all parameters.</li>
* <li><b>checkoutFlag</b> - Save loggedInAtCheckout and loggedOutAtCheckout.</li>
* <li><b>orderId</b> - Save orderID.</li>
* <li><b>sessionExpiry</b> - Save isUserSessionExpired and isUserLoggedOut.</li>
* </ul>
*
* @private
* @function
* @name UserViewModel#setLocalData
* @param {string} setParam Enumerated string to select parameters saved to local storage.
* @returns {boolean} true if setParam is falsey or empty, otherwise implicit return.
*/
UserViewModel.prototype.setLocalData = function (setParam) {
var self = this;
if (!setParam && setParam == '') {
return true;
}
var userCookieData = self.getLocalData();
if (userCookieData == null) {
userCookieData = {};
}
switch (setParam) {
case 'all':
userCookieData = {
loggedinAtCheckout: self.loggedinAtCheckout(),
loggedoutAtCheckout: self.loggedoutAtCheckout(),
orderId: self.orderId(),
loggedInUserName: self.loggedInUserName(),
login: self.login(),
isUserSessionExpired: self.isUserSessionExpired(),
isUserLoggedOut: self.isUserLoggedOut()
};
break;
case 'checkoutFlag':
userCookieData.loggedinAtCheckout = self.loggedinAtCheckout();
userCookieData.loggedoutAtCheckout = self.loggedoutAtCheckout();
break;
case 'orderId':
userCookieData.orderId = self.orderId();
break;
case 'sessionExpiry':
userCookieData.isUserSessionExpired = self.isUserSessionExpired();
userCookieData.isUserLoggedOut = self.isUserLoggedOut();
break;
}
// Write the user to local storage
try {
storageApi.getInstance().setItem("user", JSON.stringify(userCookieData));
}
catch(pError) {
}
};
/**
* Update the values of loggedinAtCheckout, and loggedoutAtCheckout and write them to
* user local storage.
*
* @function
* @name UserViewModel#updateLocalData
* @param {boolean} loggedinAtCheckout Whether the user is logged in on the checkout page.
* @param {boolean} loggedoutAtCheckout Whether the user is logged out on the checkout page.
*/
UserViewModel.prototype.updateLocalData = function(loggedinAtCheckout, loggedoutAtCheckout) {
var self = this;
self.loggedinAtCheckout(loggedinAtCheckout);
self.loggedoutAtCheckout(loggedoutAtCheckout);
self.setLocalData('checkoutFlag');
};
/**
* Remove user local storage on logout.
*
* @function
* @name UserViewModel#removeLocalData
*/
UserViewModel.prototype.removeLocalData = function() {
try {
storageApi.getInstance().removeItem("user");
}
catch(pError) {
}
};
/**
* Send a reset password email.
*
* @function
* @name #UserViewModel#resetForgotPassword
*/
UserViewModel.prototype.resetForgotPassword = function() {
var self = this;
var inputParams = {};
inputParams[CCConstants.LOGIN] = self.emailAddressForForgottenPwd();
self.adapter.persistCreate(CCConstants.ENDPOINT_FORGOT_PASSWORD, 'id', inputParams, null,
//success callback
function(data) {
$.Topic(pubSub.topicNames.USER_RESET_PASSWORD_SUCCESS).publish(data);
},
//error callback when an internal error occurs.
function(data) {
$.Topic(pubSub.topicNames.USER_RESET_PASSWORD_FAILURE).publish(data);
}
);
};
/**
* Handle user login. Invoked on receiving a USER_LOGIN_SUBMIT pubsub event.
*
* @private
* @function
* @name UserViewModel#handleLogin
*/
UserViewModel.prototype.handleLogin = function() {
var self = this;
if (!self.isLoginValid()) {
self.login.isModified(true);
self.password.isModified(true);
return false;
}
self.client().login(this.login(), this.password(),
// Success Function
function() {
self.loginSuccessFunc(false);
$.Topic(pubSub.topicNames.USER_LOGIN_SUCCESSFUL).publish();
},
// Error function
function(pResult) {
if (pResult.error == CCConstants.PASSWORD_EXPIRED) {
self.isPasswordExpired(true);
$.Topic(pubSub.topicNames.USER_PASSWORD_EXPIRED).publish();
} else if (pResult.error == CCConstants.PASSWORD_GENERATED) {
self.isPasswordExpired(true);