creditCards.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /* eslint-disable
  2. max-len,
  3. no-undef,
  4. no-useless-escape,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS101: Remove unnecessary use of Array.from
  11. * DS102: Remove unnecessary code created because of implicit returns
  12. * DS103: Rewrite code to no longer use __guard__
  13. * DS207: Consider shorter variations of null checks
  14. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  15. */
  16. define(['base'], function(App) {
  17. App.factory('ccUtils', function() {
  18. const defaultFormat = /(\d{1,4})/g
  19. const defaultInputFormat = /(?:^|\s)(\d{4})$/
  20. const cards = [
  21. // Credit cards
  22. {
  23. type: 'visa',
  24. patterns: [4],
  25. format: defaultFormat,
  26. length: [13, 16],
  27. cvcLength: [3],
  28. luhn: true
  29. },
  30. {
  31. type: 'mastercard',
  32. patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27],
  33. format: defaultFormat,
  34. length: [16],
  35. cvcLength: [3],
  36. luhn: true
  37. },
  38. {
  39. type: 'amex',
  40. patterns: [34, 37],
  41. format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/,
  42. length: [15],
  43. cvcLength: [3, 4],
  44. luhn: true
  45. },
  46. {
  47. type: 'dinersclub',
  48. patterns: [30, 36, 38, 39],
  49. format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/,
  50. length: [14],
  51. cvcLength: [3],
  52. luhn: true
  53. },
  54. {
  55. type: 'discover',
  56. patterns: [60, 64, 65, 622],
  57. format: defaultFormat,
  58. length: [16],
  59. cvcLength: [3],
  60. luhn: true
  61. },
  62. {
  63. type: 'unionpay',
  64. patterns: [62, 88],
  65. format: defaultFormat,
  66. length: [16, 17, 18, 19],
  67. cvcLength: [3],
  68. luhn: false
  69. },
  70. {
  71. type: 'jcb',
  72. patterns: [35],
  73. format: defaultFormat,
  74. length: [16],
  75. cvcLength: [3],
  76. luhn: true
  77. }
  78. ]
  79. const cardFromNumber = function(num) {
  80. num = (num + '').replace(/\D/g, '')
  81. for (let card of Array.from(cards)) {
  82. for (let pattern of Array.from(card.patterns)) {
  83. const p = pattern + ''
  84. if (num.substr(0, p.length) === p) {
  85. return card
  86. }
  87. }
  88. }
  89. }
  90. const cardFromType = function(type) {
  91. for (let card of Array.from(cards)) {
  92. if (card.type === type) {
  93. return card
  94. }
  95. }
  96. }
  97. const cardType = function(num) {
  98. if (!num) {
  99. return null
  100. }
  101. return __guard__(cardFromNumber(num), x => x.type) || null
  102. }
  103. const formatCardNumber = function(num) {
  104. num = num.replace(/\D/g, '')
  105. const card = cardFromNumber(num)
  106. if (!card) {
  107. return num
  108. }
  109. const upperLength = card.length[card.length.length - 1]
  110. num = num.slice(0, upperLength)
  111. if (card.format.global) {
  112. return __guard__(num.match(card.format), x => x.join(' '))
  113. } else {
  114. let groups = card.format.exec(num)
  115. if (groups == null) {
  116. return
  117. }
  118. groups.shift()
  119. groups = $.grep(groups, n => n) // Filter empty groups
  120. return groups.join(' ')
  121. }
  122. }
  123. const formatExpiry = function(expiry) {
  124. const parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/)
  125. if (!parts) {
  126. return ''
  127. }
  128. let mon = parts[1] || ''
  129. let sep = parts[2] || ''
  130. const year = parts[3] || ''
  131. if (year.length > 0) {
  132. sep = ' / '
  133. } else if (sep === ' /') {
  134. mon = mon.substring(0, 1)
  135. sep = ''
  136. } else if (mon.length === 2 || sep.length > 0) {
  137. sep = ' / '
  138. } else if (mon.length === 1 && !['0', '1'].includes(mon)) {
  139. mon = `0${mon}`
  140. sep = ' / '
  141. }
  142. return mon + sep + year
  143. }
  144. const parseExpiry = function(value) {
  145. if (value == null) {
  146. value = ''
  147. }
  148. let [month, year] = Array.from(value.split(/[\s\/]+/, 2))
  149. // Allow for year shortcut
  150. if (
  151. (year != null ? year.length : undefined) === 2 &&
  152. /^\d+$/.test(year)
  153. ) {
  154. let prefix = new Date().getFullYear()
  155. prefix = prefix.toString().slice(0, 2)
  156. year = prefix + year
  157. }
  158. month = parseInt(month, 10)
  159. year = parseInt(year, 10)
  160. if (!!isNaN(month) || !!isNaN(year)) {
  161. return
  162. }
  163. return { month, year }
  164. }
  165. return {
  166. fromNumber: cardFromNumber,
  167. fromType: cardFromType,
  168. cardType,
  169. formatExpiry,
  170. formatCardNumber,
  171. defaultFormat,
  172. defaultInputFormat,
  173. parseExpiry
  174. }
  175. })
  176. App.factory('ccFormat', function(ccUtils, $filter) {
  177. const hasTextSelected = function($target) {
  178. // If some text is selected
  179. if (
  180. $target.prop('selectionStart') != null &&
  181. $target.prop('selectionStart') !== $target.prop('selectionEnd')
  182. ) {
  183. return true
  184. }
  185. // If some text is selected in IE
  186. if (
  187. __guard__(
  188. typeof document !== 'undefined' && document !== null
  189. ? document.selection
  190. : undefined,
  191. x => x.createRange
  192. ) != null
  193. ) {
  194. if (document.selection.createRange().text) {
  195. return true
  196. }
  197. }
  198. return false
  199. }
  200. const safeVal = function(value, $target) {
  201. let cursor
  202. try {
  203. cursor = $target.prop('selectionStart')
  204. } catch (error) {
  205. cursor = null
  206. }
  207. const last = $target.val()
  208. $target.val(value)
  209. if (cursor !== null && $target.is(':focus')) {
  210. if (cursor === last.length) {
  211. cursor = value.length
  212. }
  213. // This hack looks for scenarios where we are changing an input's value such
  214. // that "X| " is replaced with " |X" (where "|" is the cursor). In those
  215. // scenarios, we want " X|".
  216. //
  217. // For example:
  218. // 1. Input field has value "4444| "
  219. // 2. User types "1"
  220. // 3. Input field has value "44441| "
  221. // 4. Reformatter changes it to "4444 |1"
  222. // 5. By incrementing the cursor, we make it "4444 1|"
  223. //
  224. // This is awful, and ideally doesn't go here, but given the current design
  225. // of the system there does not appear to be a better solution.
  226. //
  227. // Note that we can't just detect when the cursor-1 is " ", because that
  228. // would incorrectly increment the cursor when backspacing, e.g. pressing
  229. // backspace in this scenario: "4444 1|234 5".
  230. if (last !== value) {
  231. const prevPair = last.slice(cursor - 1, +cursor + 1 || undefined)
  232. const currPair = value.slice(cursor - 1, +cursor + 1 || undefined)
  233. const digit = value[cursor]
  234. if (
  235. /\d/.test(digit) &&
  236. prevPair === `${digit} ` &&
  237. currPair === ` ${digit}`
  238. ) {
  239. cursor = cursor + 1
  240. }
  241. }
  242. $target.prop('selectionStart', cursor)
  243. return $target.prop('selectionEnd', cursor)
  244. }
  245. }
  246. // Replace Full-Width Chars
  247. const replaceFullWidthChars = function(str) {
  248. if (str == null) {
  249. str = ''
  250. }
  251. const fullWidth =
  252. '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19'
  253. const halfWidth = '0123456789'
  254. let value = ''
  255. const chars = str.split('')
  256. // Avoid using reserved word `char`
  257. for (let chr of Array.from(chars)) {
  258. const idx = fullWidth.indexOf(chr)
  259. if (idx > -1) {
  260. chr = halfWidth[idx]
  261. }
  262. value += chr
  263. }
  264. return value
  265. }
  266. // Format Numeric
  267. const reFormatNumeric = function(e) {
  268. const $target = $(e.currentTarget)
  269. return setTimeout(function() {
  270. let value = $target.val()
  271. value = replaceFullWidthChars(value)
  272. value = value.replace(/\D/g, '')
  273. return safeVal(value, $target)
  274. })
  275. }
  276. // Format Card Number
  277. const reFormatCardNumber = function(e) {
  278. const $target = $(e.currentTarget)
  279. return setTimeout(function() {
  280. let value = $target.val()
  281. value = replaceFullWidthChars(value)
  282. value = ccUtils.formatCardNumber(value)
  283. return safeVal(value, $target)
  284. })
  285. }
  286. const formatCardNumber = function(e) {
  287. // Only format if input is a number
  288. let re
  289. const digit = String.fromCharCode(e.which)
  290. if (!/^\d+$/.test(digit)) {
  291. return
  292. }
  293. const $target = $(e.currentTarget)
  294. const value = $target.val()
  295. const card = ccUtils.fromNumber(value + digit)
  296. const { length } = value.replace(/\D/g, '') + digit
  297. let upperLength = 16
  298. if (card) {
  299. upperLength = card.length[card.length.length - 1]
  300. }
  301. if (length >= upperLength) {
  302. return
  303. }
  304. // Return if focus isn't at the end of the text
  305. if (
  306. $target.prop('selectionStart') != null &&
  307. $target.prop('selectionStart') !== value.length
  308. ) {
  309. return
  310. }
  311. if (card && card.type === 'amex') {
  312. // AMEX cards are formatted differently
  313. re = /^(\d{4}|\d{4}\s\d{6})$/
  314. } else {
  315. re = /(?:^|\s)(\d{4})$/
  316. }
  317. // If '4242' + 4
  318. if (re.test(value)) {
  319. e.preventDefault()
  320. return setTimeout(() => $target.val(value + ' ' + digit))
  321. // If '424' + 2
  322. } else if (re.test(value + digit)) {
  323. e.preventDefault()
  324. return setTimeout(() => $target.val(value + digit + ' '))
  325. }
  326. }
  327. const formatBackCardNumber = function(e) {
  328. const $target = $(e.currentTarget)
  329. const value = $target.val()
  330. // Return unless backspacing
  331. if (e.which !== 8) {
  332. return
  333. }
  334. // Return if focus isn't at the end of the text
  335. if (
  336. $target.prop('selectionStart') != null &&
  337. $target.prop('selectionStart') !== value.length
  338. ) {
  339. return
  340. }
  341. // Remove the digit + trailing space
  342. if (/\d\s$/.test(value)) {
  343. e.preventDefault()
  344. return setTimeout(() => $target.val(value.replace(/\d\s$/, '')))
  345. // Remove digit if ends in space + digit
  346. } else if (/\s\d?$/.test(value)) {
  347. e.preventDefault()
  348. return setTimeout(() => $target.val(value.replace(/\d$/, '')))
  349. }
  350. }
  351. const getFormattedCardNumber = function(num) {
  352. num = num.replace(/\D/g, '')
  353. const card = ccUtils.fromNumber(num)
  354. if (!card) {
  355. return num
  356. }
  357. const upperLength = card.length[card.length.length - 1]
  358. num = num.slice(0, upperLength)
  359. if (card.format.global) {
  360. return __guard__(num.match(card.format), x => x.join(' '))
  361. } else {
  362. let groups = card.format.exec(num)
  363. if (groups == null) {
  364. return
  365. }
  366. groups.shift()
  367. groups = $.grep(groups, n => n) // Filter empty groups
  368. return groups.join(' ')
  369. }
  370. }
  371. const parseCardNumber = function(value) {
  372. if (value != null) {
  373. return value.replace(/\s/g, '')
  374. } else {
  375. return value
  376. }
  377. }
  378. // Format Expiry
  379. const reFormatExpiry = function(e) {
  380. const $target = $(e.currentTarget)
  381. return setTimeout(function() {
  382. let value = $target.val()
  383. value = replaceFullWidthChars(value)
  384. value = ccUtils.formatExpiry(value)
  385. return safeVal(value, $target)
  386. })
  387. }
  388. const formatExpiry = function(e) {
  389. // Only format if input is a number
  390. const digit = String.fromCharCode(e.which)
  391. if (!/^\d+$/.test(digit)) {
  392. return
  393. }
  394. const $target = $(e.currentTarget)
  395. const val = $target.val() + digit
  396. if (/^\d$/.test(val) && !['0', '1'].includes(val)) {
  397. e.preventDefault()
  398. return setTimeout(() => $target.val(`0${val} / `))
  399. } else if (/^\d\d$/.test(val)) {
  400. e.preventDefault()
  401. return setTimeout(function() {
  402. // Split for months where we have the second digit > 2 (past 12) and turn
  403. // that into (m1)(m2) => 0(m1) / (m2)
  404. const m1 = parseInt(val[0], 10)
  405. const m2 = parseInt(val[1], 10)
  406. if (m2 > 2 && m1 !== 0) {
  407. return $target.val(`0${m1} / ${m2}`)
  408. } else {
  409. return $target.val(`${val} / `)
  410. }
  411. })
  412. }
  413. }
  414. const formatForwardExpiry = function(e) {
  415. const digit = String.fromCharCode(e.which)
  416. if (!/^\d+$/.test(digit)) {
  417. return
  418. }
  419. const $target = $(e.currentTarget)
  420. const val = $target.val()
  421. if (/^\d\d$/.test(val)) {
  422. return $target.val(`${val} / `)
  423. }
  424. }
  425. const formatForwardSlash = function(e) {
  426. const which = String.fromCharCode(e.which)
  427. if (which !== '/' && which !== ' ') {
  428. return
  429. }
  430. const $target = $(e.currentTarget)
  431. const val = $target.val()
  432. if (/^\d$/.test(val) && val !== '0') {
  433. return $target.val(`0${val} / `)
  434. }
  435. }
  436. const formatBackExpiry = function(e) {
  437. const $target = $(e.currentTarget)
  438. const value = $target.val()
  439. // Return unless backspacing
  440. if (e.which !== 8) {
  441. return
  442. }
  443. // Return if focus isn't at the end of the text
  444. if (
  445. $target.prop('selectionStart') != null &&
  446. $target.prop('selectionStart') !== value.length
  447. ) {
  448. return
  449. }
  450. // Remove the trailing space + last digit
  451. if (/\d\s\/\s$/.test(value)) {
  452. e.preventDefault()
  453. return setTimeout(() => $target.val(value.replace(/\d\s\/\s$/, '')))
  454. }
  455. }
  456. const parseExpiry = function(value) {
  457. if (value != null) {
  458. const dateAsObj = ccUtils.parseExpiry(value)
  459. if (dateAsObj == null) {
  460. return
  461. }
  462. const expiry = new Date(dateAsObj.year, dateAsObj.month - 1)
  463. return $filter('date')(expiry, 'MM/yyyy')
  464. }
  465. }
  466. // Format CVC
  467. const reFormatCVC = function(e) {
  468. const $target = $(e.currentTarget)
  469. return setTimeout(function() {
  470. let value = $target.val()
  471. value = replaceFullWidthChars(value)
  472. value = value.replace(/\D/g, '').slice(0, 4)
  473. return safeVal(value, $target)
  474. })
  475. }
  476. // Restrictions
  477. const restrictNumeric = function(e) {
  478. // Key event is for a browser shortcut
  479. if (e.metaKey || e.ctrlKey) {
  480. return true
  481. }
  482. // If keycode is a space
  483. if (e.which === 32) {
  484. return false
  485. }
  486. // If keycode is a special char (WebKit)
  487. if (e.which === 0) {
  488. return true
  489. }
  490. // If char is a special char (Firefox)
  491. if (e.which < 33) {
  492. return true
  493. }
  494. const input = String.fromCharCode(e.which)
  495. // Char is a number or a space
  496. return !!/[\d\s]/.test(input)
  497. }
  498. const restrictCardNumber = function(e) {
  499. const $target = $(e.currentTarget)
  500. const digit = String.fromCharCode(e.which)
  501. if (!/^\d+$/.test(digit)) {
  502. return
  503. }
  504. if (hasTextSelected($target)) {
  505. return
  506. }
  507. // Restrict number of digits
  508. const value = ($target.val() + digit).replace(/\D/g, '')
  509. const card = ccUtils.fromNumber(value)
  510. if (card) {
  511. return value.length <= card.length[card.length.length - 1]
  512. } else {
  513. // All other cards are 16 digits long
  514. return value.length <= 16
  515. }
  516. }
  517. const restrictExpiry = function(e) {
  518. const $target = $(e.currentTarget)
  519. const digit = String.fromCharCode(e.which)
  520. if (!/^\d+$/.test(digit)) {
  521. return
  522. }
  523. if (hasTextSelected($target)) {
  524. return
  525. }
  526. let value = $target.val() + digit
  527. value = value.replace(/\D/g, '')
  528. if (value.length > 6) {
  529. return false
  530. }
  531. }
  532. const restrictCVC = function(e) {
  533. const $target = $(e.currentTarget)
  534. const digit = String.fromCharCode(e.which)
  535. if (!/^\d+$/.test(digit)) {
  536. return
  537. }
  538. if (hasTextSelected($target)) {
  539. return
  540. }
  541. const val = $target.val() + digit
  542. return val.length <= 4
  543. }
  544. const setCardType = function(e) {
  545. const $target = $(e.currentTarget)
  546. const val = $target.val()
  547. const cardType = ccUtils.cardType(val) || 'unknown'
  548. if (!$target.hasClass(cardType)) {
  549. const allTypes = Array.from(cards).map(card => card.type)
  550. $target.removeClass('unknown')
  551. $target.removeClass(allTypes.join(' '))
  552. $target.addClass(cardType)
  553. $target.toggleClass('identified', cardType !== 'unknown')
  554. return $target.trigger('payment.cardType', cardType)
  555. }
  556. }
  557. return {
  558. hasTextSelected,
  559. replaceFullWidthChars,
  560. reFormatNumeric,
  561. reFormatCardNumber,
  562. formatCardNumber,
  563. formatBackCardNumber,
  564. getFormattedCardNumber,
  565. parseCardNumber,
  566. reFormatExpiry,
  567. formatExpiry,
  568. formatForwardExpiry,
  569. formatForwardSlash,
  570. formatBackExpiry,
  571. parseExpiry,
  572. reFormatCVC,
  573. restrictNumeric,
  574. restrictCardNumber,
  575. restrictExpiry,
  576. restrictCVC,
  577. setCardType
  578. }
  579. })
  580. App.directive('ccFormatExpiry', ccFormat => ({
  581. restrict: 'A',
  582. require: 'ngModel',
  583. link(scope, el, attrs, ngModel) {
  584. el.on('keypress', ccFormat.restrictNumeric)
  585. el.on('keypress', ccFormat.restrictExpiry)
  586. el.on('keypress', ccFormat.formatExpiry)
  587. el.on('keypress', ccFormat.formatForwardSlash)
  588. el.on('keypress', ccFormat.formatForwardExpiry)
  589. el.on('keydown', ccFormat.formatBackExpiry)
  590. el.on('change', ccFormat.reFormatExpiry)
  591. el.on('input', ccFormat.reFormatExpiry)
  592. el.on('paste', ccFormat.reFormatExpiry)
  593. ngModel.$parsers.push(ccFormat.parseExpiry)
  594. return ngModel.$formatters.push(ccFormat.parseExpiry)
  595. }
  596. }))
  597. App.directive('ccFormatCardNumber', ccFormat => ({
  598. restrict: 'A',
  599. require: 'ngModel',
  600. link(scope, el, attrs, ngModel) {
  601. el.on('keypress', ccFormat.restrictNumeric)
  602. el.on('keypress', ccFormat.restrictCardNumber)
  603. el.on('keypress', ccFormat.formatCardNumber)
  604. el.on('keydown', ccFormat.formatBackCardNumber)
  605. el.on('paste', ccFormat.reFormatCardNumber)
  606. ngModel.$parsers.push(ccFormat.parseCardNumber)
  607. return ngModel.$formatters.push(ccFormat.getFormattedCardNumber)
  608. }
  609. }))
  610. return App.directive('ccFormatSecCode', ccFormat => ({
  611. restrict: 'A',
  612. require: 'ngModel',
  613. link(scope, el, attrs, ngModel) {
  614. el.on('keypress', ccFormat.restrictNumeric)
  615. el.on('keypress', ccFormat.restrictCVC)
  616. el.on('paste', ccFormat.reFormatCVC)
  617. el.on('change', ccFormat.reFormatCVC)
  618. return el.on('input', ccFormat.reFormatCVC)
  619. }
  620. }))
  621. })
  622. function __guard__(value, transform) {
  623. return typeof value !== 'undefined' && value !== null
  624. ? transform(value)
  625. : undefined
  626. }