Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

card add #1373

Merged
merged 1 commit into from
Oct 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions assets/icons/lock.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion assets/img/icon-sprite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const pageClasses = {
account_saved_return: getAccount,
account_returns: getAccount,
account_paymentmethods: getAccount,
account_addpaymentmethod: getAccount,
account_editpaymentmethod: getAccount,
login: getLogin,
createaccount_thanks: getLogin,
Expand Down
173 changes: 173 additions & 0 deletions assets/js/test-unit/theme/common/payment-method.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import { creditCardType, storeInstrument, Formatters, Validators } from '../../../theme/common/payment-method';

describe('PaymentMethod', () => {
describe('creditCardType', () => {
it('should return a credit card type from the first six caracters of a given string', () => {
expect(creditCardType('370000')).toEqual('American Express');
expect(creditCardType('388000')).toEqual('Diners Club');
expect(creditCardType('601100')).toEqual('Discover');
expect(creditCardType('516300')).toEqual('Mastercard');
expect(creditCardType('411100')).toEqual('Visa');
});
});

describe('Formatters', () => {
let $form;

beforeEach(() => {
$form = $(
`<form>
<input name="credit_card_number" />
<input name="expiration" />
'</form>`
);
$form.appendTo(document.body);
});

afterEach(() => {
$form.remove();
});

describe('setCreditCardNumberFormat', () => {
it('should be formatting the credit card number in a corresponding credit card type format', () => {
Formatters.setCreditCardNumberFormat('form input[name="credit_card_number"]');
const input = $('form input[name="credit_card_number"]');

expect(input.val('370000000000000').trigger('keyup').val()).toEqual('3700 000000 00000');
expect(input.val('38000000000000').trigger('keyup').val()).toEqual('3800 000000 0000');
expect(input.val('6011000000000000').trigger('keyup').val()).toEqual('6011 0000 0000 0000');
expect(input.val('5163000000000000').trigger('keyup').val()).toEqual('5163 0000 0000 0000');
expect(input.val('4111000000000000').trigger('keyup').val()).toEqual('4111 0000 0000 0000');
});
});

describe('setExpirationFormat', () => {
it('should be formatting the expiration as month/year', () => {
Formatters.setExpirationFormat('form input[name="expiration"]');
const input = $('form input[name="expiration"]');

expect(input.val('1120').trigger('keyup').val()).toEqual('11/20');
expect(input.val('0120').trigger('keyup').val()).toEqual('01/20');
});

it('should be adding a separator after month in two digits', () => {
Formatters.setExpirationFormat('form input[name="expiration"]');
const event = $.Event('keyup');
const input = $('form input[name="expiration"]');
input.val('11').trigger(event);

expect(event.target.value).toEqual('11/');
});

it('should be removing a separator after month on delete', () => {
Formatters.setExpirationFormat('form input[name="expiration"]');
const event = $.Event('keyup', { which: 8, ctrlKey: false });
const input = $('form input[name="expiration"]');
input.val('11/').trigger(event);

expect(event.target.value).toEqual('11');
});

it('should be completing month for intergers superior to one', () => {
Formatters.setExpirationFormat('form input[name="expiration"]');
const event = $.Event('keyup');
const input = $('form input[name="expiration"]');
input.val('2').trigger(event);

expect(event.target.value).toEqual('02/');
});

it('should not have more than two separators', () => {
Formatters.setExpirationFormat('form input[name="expiration"]');
const event = $.Event('keyup');
const input = $('form input[name="expiration"]');
input.val('11//').trigger(event);

expect(event.target.value).toEqual('11/');
});

it('should not have more than two zero', () => {
Formatters.setExpirationFormat('form input[name="expiration"]');
const event = $.Event('keyup');
const input = $('form input[name="expiration"]');
input.val('00').trigger(event);

expect(event.target.value).toEqual('0');
});
});
});

describe('Validators', () => {
describe('setCreditCardNumberValidation', () => {
it('should have invalid input credit card number', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, '4444 3333 2222') };
Validators.setCreditCardNumberValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(false);
});

it('should have valid input credit card number', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, '4444 3333 2222 1111') };
Validators.setCreditCardNumberValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(true);
});
});

describe('setExpirationValidation', () => {
it('should have invalid input expiration date', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, '01/17') };
Validators.setExpirationValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(false);
});

it('should have valid input expiration date', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, '12/20') };
Validators.setExpirationValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(true);
});
});

describe('setNameOnCardValidation', () => {
it('should have invalid input name on card', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, '') };
Validators.setNameOnCardValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(false);
});

it('should have valid input name on card', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, 'Foo Bar') };
Validators.setNameOnCardValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(true);
});
});

describe('setCvvValidation', () => {
it('should have invalid input cvv', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, '12') };
Validators.setCvvValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(false);
});

it('should have valid input cvv', () => {
const callback = jasmine.createSpy();
const validator = { add: ({ validate }) => validate(callback, '123') };
Validators.setCvvValidation(validator, 'selector');

expect(callback).toHaveBeenCalledWith(true);
});
});
});
});
104 changes: 104 additions & 0 deletions assets/js/theme/account.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import PageManager from './page-manager';
import _ from 'lodash';
import $ from 'jquery';
import nod from './common/nod';
import Wishlist from './wishlist';
import validation from './common/form-validation';
import stateCountry from './common/state-country';
import { classifyForm, Validators, insertStateHiddenField } from './common/form-utils';
import { creditCardType, storeInstrument, Validators as CCValidators, Formatters as CCFormatters } from './common/payment-method';
import swal from 'sweetalert2';

export default class Account extends PageManager {
Expand All @@ -20,6 +22,7 @@ export default class Account extends PageManager {
const $addressForm = classifyForm('form[data-address-form]');
const $inboxForm = classifyForm('form[data-inbox-form]');
const $accountReturnForm = classifyForm('[data-account-return-form]');
const $paymentMethodForm = classifyForm('form[data-payment-method-form]');
const $reorderForm = classifyForm('[data-account-reorder-form]');
const $invoiceButton = $('[data-print-invoice]');

Expand Down Expand Up @@ -62,6 +65,10 @@ export default class Account extends PageManager {
this.initAccountReturnFormValidation($accountReturnForm);
}

if ($paymentMethodForm.length) {
this.initPaymentMethodFormValidation($paymentMethodForm);
}

if ($reorderForm.length) {
this.initReorderForm($reorderForm);
}
Expand Down Expand Up @@ -201,6 +208,103 @@ export default class Account extends PageManager {
});
}

initPaymentMethodFormValidation($paymentMethodForm) {
// Inject validations into form fields before validation runs
$paymentMethodForm.find('#first_name.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.firstNameLabel}", "required": true, "maxlength": 0 }`);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @junedkazi , we have removed the dynamic input fields for the static components. however, I had to inject the validation through javascript because it was breaking the template engine.

$paymentMethodForm.find('#last_name.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.lastNameLabel}", "required": true, "maxlength": 0 }`);
$paymentMethodForm.find('#company.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.companyLabel}", "required": false, "maxlength": 0 }`);
$paymentMethodForm.find('#phone.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.phoneLabel}", "required": false, "maxlength": 0 }`);
$paymentMethodForm.find('#address1.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.address1Label}", "required": true, "maxlength": 0 }`);
$paymentMethodForm.find('#address2.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.address2Label}", "required": false, "maxlength": 0 }`);
$paymentMethodForm.find('#city.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.cityLabel}", "required": true, "maxlength": 0 }`);
$paymentMethodForm.find('#country.form-field').attr('data-validation', `{ "type": "singleselect", "label": "${this.context.countryLabel}", "required": true, prefix: "" }`);
$paymentMethodForm.find('#state.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.stateLabel}", "required": true, "maxlength": 0 }`);
$paymentMethodForm.find('#postal_code.form-field').attr('data-validation', `{ "type": "singleline", "label": "${this.context.postalCodeLabel}", "required": true, "maxlength": 0 }`);

const validationModel = validation($paymentMethodForm);
const paymentMethodSelector = 'form[data-payment-method-form]';
const paymentMethodValidator = nod({ submit: `${paymentMethodSelector} input[type="submit"]` });
const $stateElement = $(`${paymentMethodSelector} [data-field-type="State"]`);

let $last;
// Requests the states for a country with AJAX
stateCountry($stateElement, this.context, (err, field) => {
if (err) {
throw new Error(err);
}

const $field = $(field);

if (paymentMethodValidator.getStatus($stateElement) !== 'undefined') {
paymentMethodValidator.remove($stateElement);
}

if ($last) {
paymentMethodValidator.remove($last);
}

if ($field.is('select')) {
$last = field;
Validators.setStateCountryValidation(paymentMethodValidator, field);
} else {
Validators.cleanUpStateValidation(field);
}
});

// Use credit card number input listener to highlight credit card type
$(`${paymentMethodSelector} input[name="credit_card_number"]`).on('keyup', ({ target }) => {
const cardType = creditCardType(target.value);
if (cardType) {
$(`${paymentMethodSelector} img[alt="${cardType}"`).siblings().css('opacity', '.2');
} else {
$(`${paymentMethodSelector} img`).css('opacity', '1');
}
});

// Set of credit card validation
CCValidators.setCreditCardNumberValidation(paymentMethodValidator, `${paymentMethodSelector} input[name="credit_card_number"]`, this.context.creditCardNumber);
CCValidators.setExpirationValidation(paymentMethodValidator, `${paymentMethodSelector} input[name="expiration"]`, this.context.expiration);
CCValidators.setNameOnCardValidation(paymentMethodValidator, `${paymentMethodSelector} input[name="name_on_card"]`, this.context.nameOnCard);
CCValidators.setCvvValidation(paymentMethodValidator, `${paymentMethodSelector} input[name="cvv"]`, this.context.cvv);

// Set of credit card format
CCFormatters.setCreditCardNumberFormat(`${paymentMethodSelector} input[name="credit_card_number"]`);
CCFormatters.setExpirationFormat(`${paymentMethodSelector} input[name="expiration"`);

// Billing address validation
paymentMethodValidator.add(validationModel);

$paymentMethodForm.on('submit', event => {
event.preventDefault();
// Perform final form validation
paymentMethodValidator.performCheck();
if (paymentMethodValidator.areAll('valid')) {
// Serialize form data and reduce it to object
const data = _.reduce($paymentMethodForm.serializeArray(), (obj, item) => {
const refObj = obj;
refObj[item.name] = item.value;
return refObj;
}, {});

// Assign country and state code
const country = _.find(this.context.countries, ({ value }) => value === data.country);
const state = country && _.find(country.states, ({ value }) => value === data.state);
data.country_code = country ? country.code : data.country;
data.state_or_province_code = state ? state.code : data.state;

// Store credit card
storeInstrument(this.context, data, () => {
window.location.href = this.context.paymentMethodsUrl;
}, () => {
swal({
text: this.context.generic_error,
type: 'error',
});
});
}
});
}

registerEditAccountValidation($editAccountForm) {
const validationModel = validation($editAccountForm);
const formEditSelector = 'form[data-edit-account-form]';
Expand Down
Loading