SFRA Server-side Javascript - Source: app_storefront_base/cartridge/controllers/Address.js menu

SFRA / Server-side JS / Source: app_storefront_base/cartridge/controllers/Address.js

  1. 'use strict';
  2. /**
  3. * @namespace Address
  4. */
  5. var server = require('server');
  6. var URLUtils = require('dw/web/URLUtils');
  7. var Resource = require('dw/web/Resource');
  8. var csrfProtection = require('*/cartridge/scripts/middleware/csrf');
  9. var userLoggedIn = require('*/cartridge/scripts/middleware/userLoggedIn');
  10. var consentTracking = require('*/cartridge/scripts/middleware/consentTracking');
  11. /**
  12. * Creates a list of address model for the logged in user
  13. * @param {string} customerNo - customer number of the current customer
  14. * @returns {List} a plain list of objects of the current customer's addresses
  15. */
  16. function getList(customerNo) {
  17. var CustomerMgr = require('dw/customer/CustomerMgr');
  18. var AddressModel = require('*/cartridge/models/address');
  19. var collections = require('*/cartridge/scripts/util/collections');
  20. var customer = CustomerMgr.getCustomerByCustomerNumber(customerNo);
  21. var rawAddressBook = customer.addressBook.getAddresses();
  22. var addressBook = collections.map(rawAddressBook, function (rawAddress) {
  23. var addressModel = new AddressModel(rawAddress);
  24. addressModel.address.UUID = rawAddress.UUID;
  25. return addressModel;
  26. });
  27. return addressBook;
  28. }
  29. /**
  30. * Address-List : Used to show a list of address created by a registered shopper
  31. * @name Base/Address-List
  32. * @function
  33. * @memberof Address
  34. * @param {middleware} - userLoggedIn.validateLoggedIn
  35. * @param {middleware} - consentTracking.consent
  36. * @param {category} - sensitive
  37. * @param {renders} - isml
  38. * @param {serverfunction} - get
  39. */
  40. server.get('List', userLoggedIn.validateLoggedIn, consentTracking.consent, function (req, res, next) {
  41. var actionUrls = {
  42. deleteActionUrl: URLUtils.url('Address-DeleteAddress').toString(),
  43. listActionUrl: URLUtils.url('Address-List').toString()
  44. };
  45. res.render('account/addressBook', {
  46. addressBook: getList(req.currentCustomer.profile.customerNo),
  47. actionUrls: actionUrls,
  48. breadcrumbs: [
  49. {
  50. htmlValue: Resource.msg('global.home', 'common', null),
  51. url: URLUtils.home().toString()
  52. },
  53. {
  54. htmlValue: Resource.msg('page.title.myaccount', 'account', null),
  55. url: URLUtils.url('Account-Show').toString()
  56. }
  57. ]
  58. });
  59. next();
  60. });
  61. /**
  62. * Address-AddAddress : A link to a page to create a new address
  63. * @name Base/Address-AddAddress
  64. * @function
  65. * @memberof Address
  66. * @param {middleware} - csrfProtection.generateToken
  67. * @param {middleware} - consentTracking.consent
  68. * @param {middleware} - userLoggedIn.validateLoggedIn
  69. * @param {category} - sensitive
  70. * @param {renders} - isml
  71. * @param {serverfunction} - get
  72. */
  73. server.get(
  74. 'AddAddress',
  75. csrfProtection.generateToken,
  76. consentTracking.consent,
  77. userLoggedIn.validateLoggedIn,
  78. function (req, res, next) {
  79. var addressForm = server.forms.getForm('address');
  80. addressForm.clear();
  81. res.render('account/editAddAddress', {
  82. addressForm: addressForm,
  83. breadcrumbs: [
  84. {
  85. htmlValue: Resource.msg('global.home', 'common', null),
  86. url: URLUtils.home().toString()
  87. },
  88. {
  89. htmlValue: Resource.msg('page.title.myaccount', 'account', null),
  90. url: URLUtils.url('Account-Show').toString()
  91. },
  92. {
  93. htmlValue: Resource.msg('label.addressbook', 'account', null),
  94. url: URLUtils.url('Address-List').toString()
  95. }
  96. ]
  97. });
  98. next();
  99. }
  100. );
  101. /**
  102. * Address-EditAddress : A link to edit and existing address
  103. * @name Base/Address-EditAddress
  104. * @function
  105. * @memberof Address
  106. * @param {middleware} - csrfProtection.generateToken
  107. * @param {middleware} - userLoggedIn.validateLoggedIn
  108. * @param {middleware} - consentTracking.consent
  109. * @param {querystringparameter} - addressId - a string used to identify the address record
  110. * @param {category} - sensitive
  111. * @param {renders} - isml
  112. * @param {serverfunction} - get
  113. */
  114. server.get(
  115. 'EditAddress',
  116. csrfProtection.generateToken,
  117. userLoggedIn.validateLoggedIn,
  118. consentTracking.consent,
  119. function (req, res, next) {
  120. var CustomerMgr = require('dw/customer/CustomerMgr');
  121. var AddressModel = require('*/cartridge/models/address');
  122. var addressId = req.querystring.addressId;
  123. var customer = CustomerMgr.getCustomerByCustomerNumber(
  124. req.currentCustomer.profile.customerNo
  125. );
  126. var addressBook = customer.getProfile().getAddressBook();
  127. var rawAddress = addressBook.getAddress(addressId);
  128. var addressModel = new AddressModel(rawAddress);
  129. var addressForm = server.forms.getForm('address');
  130. addressForm.clear();
  131. addressForm.copyFrom(addressModel.address);
  132. res.render('account/editAddAddress', {
  133. addressForm: addressForm,
  134. addressId: addressId,
  135. breadcrumbs: [
  136. {
  137. htmlValue: Resource.msg('global.home', 'common', null),
  138. url: URLUtils.home().toString()
  139. },
  140. {
  141. htmlValue: Resource.msg('page.title.myaccount', 'account', null),
  142. url: URLUtils.url('Account-Show').toString()
  143. },
  144. {
  145. htmlValue: Resource.msg('label.addressbook', 'account', null),
  146. url: URLUtils.url('Address-List').toString()
  147. }
  148. ]
  149. });
  150. next();
  151. }
  152. );
  153. /**
  154. * Address-SaveAddress : Save a new or existing address
  155. * @name Base/Address-SaveAddress
  156. * @function
  157. * @memberof Address
  158. * @param {middleware} - csrfProtection.validateAjaxRequest
  159. * @param {querystringparameter} - addressId - a string used to identify the address record
  160. * @param {httpparameter} - dwfrm_address_addressId - An existing address id (unless new record)
  161. * @param {httpparameter} - dwfrm_address_firstName - A person’s first name
  162. * @param {httpparameter} - dwfrm_address_lastName - A person’s last name
  163. * @param {httpparameter} - dwfrm_address_address1 - A person’s street name
  164. * @param {httpparameter} - dwfrm_address_address2 - A person’s apartment number
  165. * @param {httpparameter} - dwfrm_address_country - A person’s country
  166. * @param {httpparameter} - dwfrm_address_states_stateCode - A person’s state
  167. * @param {httpparameter} - dwfrm_address_city - A person’s city
  168. * @param {httpparameter} - dwfrm_address_postalCode - A person’s united states postel code
  169. * @param {httpparameter} - dwfrm_address_phone - A person’s phone number
  170. * @param {httpparameter} - csrf_token - hidden input field CSRF token
  171. * @param {category} - sensitive
  172. * @param {returns} - json
  173. * @param {serverfunction} - post
  174. */
  175. server.post('SaveAddress', csrfProtection.validateAjaxRequest, function (req, res, next) {
  176. var CustomerMgr = require('dw/customer/CustomerMgr');
  177. var Transaction = require('dw/system/Transaction');
  178. var formErrors = require('*/cartridge/scripts/formErrors');
  179. var accountHelpers = require('*/cartridge/scripts/helpers/accountHelpers');
  180. var addressHelpers = require('*/cartridge/scripts/helpers/addressHelpers');
  181. var addressForm = server.forms.getForm('address');
  182. var addressFormObj = addressForm.toObject();
  183. addressFormObj.addressForm = addressForm;
  184. var customer = CustomerMgr.getCustomerByCustomerNumber(
  185. req.currentCustomer.profile.customerNo
  186. );
  187. var addressBook = customer.getProfile().getAddressBook();
  188. if (addressForm.valid) {
  189. res.setViewData(addressFormObj);
  190. this.on('route:BeforeComplete', function () { // eslint-disable-line no-shadow
  191. var formInfo = res.getViewData();
  192. Transaction.wrap(function () {
  193. var address = null;
  194. if (formInfo.addressId.equals(req.querystring.addressId) || !addressBook.getAddress(formInfo.addressId)) {
  195. address = req.querystring.addressId
  196. ? addressBook.getAddress(req.querystring.addressId)
  197. : addressBook.createAddress(formInfo.addressId);
  198. }
  199. if (address) {
  200. if (req.querystring.addressId) {
  201. address.setID(formInfo.addressId);
  202. }
  203. // Save form's address
  204. addressHelpers.updateAddressFields(address, formInfo);
  205. // Send account edited email
  206. accountHelpers.sendAccountEditedEmail(customer.profile);
  207. res.json({
  208. success: true,
  209. redirectUrl: URLUtils.url('Address-List').toString()
  210. });
  211. } else {
  212. formInfo.addressForm.valid = false;
  213. formInfo.addressForm.addressId.valid = false;
  214. formInfo.addressForm.addressId.error =
  215. Resource.msg('error.message.idalreadyexists', 'forms', null);
  216. res.json({
  217. success: false,
  218. fields: formErrors.getFormErrors(addressForm)
  219. });
  220. }
  221. });
  222. });
  223. } else {
  224. res.json({
  225. success: false,
  226. fields: formErrors.getFormErrors(addressForm)
  227. });
  228. }
  229. return next();
  230. });
  231. /**
  232. * Address-DeleteAddress : Delete an existing address
  233. * @name Base/Address-DeleteAddress
  234. * @function
  235. * @memberof Address
  236. * @param {middleware} - userLoggedIn.validateLoggedInAjax
  237. * @param {querystringparameter} - addressId - a string used to identify the address record
  238. * @param {querystringparameter} - isDefault - true if this is the default address. false otherwise
  239. * @param {category} - sensitive
  240. * @param {returns} - json
  241. * @param {serverfunction} - get
  242. */
  243. server.get('DeleteAddress', userLoggedIn.validateLoggedInAjax, function (req, res, next) {
  244. var CustomerMgr = require('dw/customer/CustomerMgr');
  245. var Transaction = require('dw/system/Transaction');
  246. var accountHelpers = require('*/cartridge/scripts/helpers/accountHelpers');
  247. var data = res.getViewData();
  248. if (data && !data.loggedin) {
  249. res.json();
  250. return next();
  251. }
  252. var addressId = req.querystring.addressId;
  253. var isDefault = req.querystring.isDefault;
  254. var customer = CustomerMgr.getCustomerByCustomerNumber(
  255. req.currentCustomer.profile.customerNo
  256. );
  257. var addressBook = customer.getProfile().getAddressBook();
  258. var address = addressBook.getAddress(addressId);
  259. var UUID = address.getUUID();
  260. this.on('route:BeforeComplete', function () { // eslint-disable-line no-shadow
  261. var length;
  262. Transaction.wrap(function () {
  263. addressBook.removeAddress(address);
  264. length = addressBook.getAddresses().length;
  265. if (isDefault && length > 0) {
  266. var newDefaultAddress = addressBook.getAddresses()[0];
  267. addressBook.setPreferredAddress(newDefaultAddress);
  268. }
  269. });
  270. // Send account edited email
  271. accountHelpers.sendAccountEditedEmail(customer.profile);
  272. if (length === 0) {
  273. res.json({
  274. UUID: UUID,
  275. defaultMsg: Resource.msg('label.addressbook.defaultaddress', 'account', null),
  276. message: Resource.msg('msg.no.saved.addresses', 'address', null)
  277. });
  278. } else {
  279. res.json({ UUID: UUID,
  280. defaultMsg: Resource.msg('label.addressbook.defaultaddress', 'account', null)
  281. });
  282. }
  283. });
  284. return next();
  285. });
  286. /**
  287. * Address-SetDefault : Set an address the be the default address
  288. * @name Base/Address-SetDefault
  289. * @function
  290. * @memberof Address
  291. * @param {middleware} - userLoggedIn.validateLoggedIn
  292. * @param {querystringparameter} - addressId - a string used to identify the address record
  293. * @param {category} - sensitive
  294. * @param {serverfunction} - get
  295. */
  296. server.get('SetDefault', userLoggedIn.validateLoggedIn, function (req, res, next) {
  297. var CustomerMgr = require('dw/customer/CustomerMgr');
  298. var Transaction = require('dw/system/Transaction');
  299. var accountHelpers = require('*/cartridge/scripts/helpers/accountHelpers');
  300. var addressId = req.querystring.addressId;
  301. var customer = CustomerMgr.getCustomerByCustomerNumber(
  302. req.currentCustomer.profile.customerNo
  303. );
  304. var addressBook = customer.getProfile().getAddressBook();
  305. var address = addressBook.getAddress(addressId);
  306. this.on('route:BeforeComplete', function () { // eslint-disable-line no-shadow
  307. Transaction.wrap(function () {
  308. addressBook.setPreferredAddress(address);
  309. });
  310. // Send account edited email
  311. accountHelpers.sendAccountEditedEmail(customer.profile);
  312. res.redirect(URLUtils.url('Address-List'));
  313. });
  314. next();
  315. });
  316. /**
  317. * Address-Header : The endpoint Address-Header renders an isml
  318. * @name Base/Address-Header
  319. * @function
  320. * @memberof Address
  321. * @param {middleware} - server.middleware.include
  322. * @param {category} - sensitive
  323. * @param {renders} - isml
  324. * @param {serverfunction} - get
  325. */
  326. server.get('Header', server.middleware.include, function (req, res, next) {
  327. if (!req.currentCustomer.profile) {
  328. res.render('account/header-anon', {});
  329. } else {
  330. res.render('account/header-logged', { name: req.currentCustomer.profile.firstName });
  331. }
  332. next();
  333. });
  334. module.exports = server.exports();