Commit dc0a92be authored by Alex Buijs's avatar Alex Buijs

Add payment method component for paid signup flow

This is part of the paid signup flow
parent 954431f3
......@@ -3,9 +3,10 @@ import { s__ } from '~/locale';
import ProgressBar from './checkout/progress_bar.vue';
import SubscriptionDetails from './checkout/subscription_details.vue';
import BillingAddress from './checkout/billing_address.vue';
import PaymentMethod from './checkout/payment_method.vue';
export default {
components: { ProgressBar, SubscriptionDetails, BillingAddress },
components: { ProgressBar, SubscriptionDetails, BillingAddress, PaymentMethod },
i18n: {
checkout: s__('Checkout|Checkout'),
},
......@@ -19,6 +20,7 @@ export default {
<h2 class="mt-4 mb-3 mb-lg-5">{{ $options.i18n.checkout }}</h2>
<subscription-details />
<billing-address />
<payment-method />
</div>
</div>
</template>
<script>
import { GlLoadingIcon } from '@gitlab/ui';
import { mapState, mapActions } from 'vuex';
import { ZUORA_SCRIPT_URL } from 'ee/subscriptions/new/constants';
export default {
components: {
GlLoadingIcon,
},
props: {
active: {
type: Boolean,
required: true,
},
},
data() {
return {
loading: true,
overrideParams: {
style: 'inline',
submitEnabled: 'true',
retainValues: 'true',
},
};
},
computed: {
...mapState(['paymentFormParams', 'paymentMethodId', 'creditCardDetails']),
},
watch: {
// The Zuora script has loaded and the parameters for rendering the iframe have been fetched.
paymentFormParams() {
this.renderZuoraIframe();
},
// The Zuora form has been submitted successfully and credit card details are being fetched.
paymentMethodId() {
this.toggleLoading();
},
// The credit card details have been fetched.
creditCardDetails() {
this.toggleLoading();
},
},
mounted() {
this.loadZuoraScript();
},
methods: {
...mapActions(['fetchPaymentFormParams', 'paymentFormSubmitted']),
loadZuoraScript() {
if (typeof window.Z === 'undefined') {
const zuoraScript = document.createElement('script');
zuoraScript.type = 'text/javascript';
zuoraScript.async = true;
zuoraScript.onload = this.fetchPaymentFormParams;
zuoraScript.src = ZUORA_SCRIPT_URL;
document.head.appendChild(zuoraScript);
} else {
this.fetchPaymentFormParams();
}
},
renderZuoraIframe() {
const params = { ...this.paymentFormParams, ...this.overrideParams };
window.Z.runAfterRender(this.toggleLoading);
window.Z.render(params, {}, this.paymentFormSubmitted);
},
toggleLoading() {
this.loading = !this.loading;
},
},
};
</script>
<template>
<div>
<gl-loading-icon v-if="loading" size="lg" />
<div v-show="active && !loading" id="zuora_payment"></div>
</div>
</template>
<script>
import _ from 'underscore';
import { GlSprintf } from '@gitlab/ui';
import { s__ } from '~/locale';
import { mapState } from 'vuex';
import Step from './components/step.vue';
import Zuora from './components/zuora.vue';
export default {
components: {
GlSprintf,
Step,
Zuora,
},
computed: {
...mapState(['paymentMethodId', 'creditCardDetails']),
isValid() {
return !_.isEmpty(this.paymentMethodId);
},
},
i18n: {
stepTitle: s__('Checkout|Payment method'),
creditCardDetails: s__('Checkout|%{cardType} ending in %{lastFourDigits}'),
expirationDate: s__('Checkout|Exp %{expirationMonth}/%{expirationYear}'),
},
};
</script>
<template>
<step step="paymentMethod" :title="$options.i18n.stepTitle" :is-valid="isValid">
<template #body="props">
<zuora :active="props.active" />
</template>
<template #summary>
<div class="js-summary-line-1">
<gl-sprintf :message="$options.i18n.creditCardDetails">
<template #cardType>
{{ creditCardDetails.cardType }}
</template>
<template #lastFourDigits>
<strong>{{ creditCardDetails.lastFourDigits }}</strong>
</template>
</gl-sprintf>
</div>
<div class="js-summary-line-2">
{{
sprintf($options.i18n.expirationDate, {
expirationMonth: creditCardDetails.expirationMonth,
expirationYear: creditCardDetails.expirationYear,
})
}}
</div>
</template>
</step>
</template>
export const STEPS = ['subscriptionDetails', 'billingAddress'];
export const STEPS = ['subscriptionDetails', 'billingAddress', 'paymentMethod'];
export const COUNTRIES_URL = '/-/countries';
export const STATES_URL = '/-/country_states';
export const ZUORA_SCRIPT_URL = 'https://static.zuora.com/Resources/libs/hosted/1.3.1/zuora-min.js';
export const PAYMENT_FORM_URL = '/-/subscriptions/payment_form';
export const PAYMENT_FORM_ID = 'paid_signup_flow';
export const PAYMENT_METHOD_URL = '/-/subscriptions/payment_method';
export const TAX_RATE = 0;
import * as types from './mutation_types';
import axios from '~/lib/utils/axios_utils';
import { s__ } from '~/locale';
import { sprintf, s__ } from '~/locale';
import createFlash from '~/flash';
import { STEPS, COUNTRIES_URL, STATES_URL } from '../constants';
import {
STEPS,
COUNTRIES_URL,
STATES_URL,
PAYMENT_FORM_URL,
PAYMENT_FORM_ID,
PAYMENT_METHOD_URL,
} from '../constants';
export const activateStep = ({ commit }, currentStep) => {
if (STEPS.includes(currentStep)) {
......@@ -104,3 +111,75 @@ export const updateCountryState = ({ commit }, countryState) => {
export const updateZipCode = ({ commit }, zipCode) => {
commit(types.UPDATE_ZIP_CODE, zipCode);
};
export const fetchPaymentFormParams = ({ dispatch }) => {
axios
.get(PAYMENT_FORM_URL, { params: { id: PAYMENT_FORM_ID } })
.then(({ data }) => dispatch('fetchPaymentFormParamsSuccess', data))
.catch(() => dispatch('fetchPaymentFormParamsError'));
};
export const fetchPaymentFormParamsSuccess = ({ commit }, data) => {
if (data.errors) {
createFlash(
sprintf(s__('Checkout|Credit card form failed to load: %{message}'), {
message: data.errors,
}),
);
} else {
commit(types.UPDATE_PAYMENT_FORM_PARAMS, data);
}
};
export const fetchPaymentFormParamsError = () => {
createFlash(s__('Checkout|Credit card form failed to load. Please try again.'));
};
export const paymentFormSubmitted = ({ dispatch }, response) => {
if (response.success) {
dispatch('paymentFormSubmittedSuccess', response.refId);
} else {
dispatch('paymentFormSubmittedError', response);
}
};
export const paymentFormSubmittedSuccess = ({ commit, dispatch }, paymentMethodId) => {
commit(types.UPDATE_PAYMENT_METHOD_ID, paymentMethodId);
dispatch('fetchPaymentMethodDetails');
};
export const paymentFormSubmittedError = (_, response) => {
createFlash(
sprintf(
s__(
'Checkout|Submitting the credit card form failed with code %{errorCode}: %{errorMessage}',
),
response,
),
);
};
export const fetchPaymentMethodDetails = ({ state, dispatch }) => {
axios
.get(PAYMENT_METHOD_URL, { params: { id: state.paymentMethodId } })
.then(({ data }) => dispatch('fetchPaymentMethodDetailsSuccess', data))
.catch(() => dispatch('fetchPaymentMethodDetailsError'));
};
export const fetchPaymentMethodDetailsSuccess = ({ commit, dispatch }, data) => {
const creditCardDetails = {
cardType: data.credit_card_type,
lastFourDigits: data.credit_card_mask_number.slice(-4),
expirationMonth: data.credit_card_expiration_month,
expirationYear: data.credit_card_expiration_year % 100,
};
commit(types.UPDATE_CREDIT_CARD_DETAILS, creditCardDetails);
dispatch('activateNextStep');
};
export const fetchPaymentMethodDetailsError = () => {
createFlash(s__('Checkout|Failed to register credit card. Please try again.'));
};
......@@ -23,3 +23,9 @@ export const UPDATE_CITY = 'UPDATE_CITY';
export const UPDATE_COUNTRY_STATE = 'UPDATE_COUNTRY_STATE';
export const UPDATE_ZIP_CODE = 'UPDATE_ZIP_CODE';
export const UPDATE_PAYMENT_FORM_PARAMS = 'UPDATE_PAYMENT_FORM_PARAMS';
export const UPDATE_PAYMENT_METHOD_ID = 'UPDATE_PAYMENT_METHOD_ID';
export const UPDATE_CREDIT_CARD_DETAILS = 'UPDATE_CREDIT_CARD_DETAILS';
......@@ -52,4 +52,16 @@ export default {
[types.UPDATE_ZIP_CODE](state, zipCode) {
state.zipCode = zipCode;
},
[types.UPDATE_PAYMENT_FORM_PARAMS](state, paymentFormParams) {
state.paymentFormParams = paymentFormParams;
},
[types.UPDATE_PAYMENT_METHOD_ID](state, paymentMethodId) {
state.paymentMethodId = paymentMethodId;
},
[types.UPDATE_CREDIT_CARD_DETAILS](state, creditCardDetails) {
state.creditCardDetails = creditCardDetails;
},
};
......@@ -35,6 +35,9 @@ export default ({ planData = '[]', planId, setupForCompany, fullName }) => {
zipCode: null,
countryOptions: [],
stateOptions: [],
paymentFormParams: {},
paymentMethodId: null,
creditCardDetails: {},
taxRate: TAX_RATE,
startDate: new Date(Date.now()),
};
......
......@@ -133,6 +133,20 @@ $subscriptions-full-width-lg: 541px;
}
}
#zuora_payment {
margin-right: -8px;
@media(min-width: map-get($grid-breakpoints, lg)) {
margin-right: 0;
}
iframe {
background-color: $white-light;
margin: -4px;
width: 100% !important;
}
}
.order-summary {
max-width: $subscriptions-full-width-md;
......
import Vuex from 'vuex';
import { shallowMount, createLocalVue } from '@vue/test-utils';
import createStore from 'ee/subscriptions/new/store';
import * as types from 'ee/subscriptions/new/store/mutation_types';
import { GlLoadingIcon } from '@gitlab/ui';
import Component from 'ee/subscriptions/new/components/checkout/components/zuora.vue';
describe('Zuora', () => {
const localVue = createLocalVue();
localVue.use(Vuex);
let wrapper;
const store = createStore();
const createComponent = (opts = {}) => {
wrapper = shallowMount(Component, {
localVue,
sync: false,
store,
...opts,
});
};
const methodMocks = {
loadZuoraScript: jest.fn(),
renderZuoraIframe: jest.fn(),
};
beforeEach(() => {
createComponent({ methods: methodMocks, propsData: { active: true } });
});
afterEach(() => {
wrapper.destroy();
});
describe('mounted', () => {
it('should call loadZuoraScript', () => {
expect(methodMocks.loadZuoraScript).toHaveBeenCalled();
});
});
describe('when active and loading', () => {
it('the loading indicator should not be shown', () => {
expect(wrapper.find(GlLoadingIcon).exists()).toBe(true);
});
it('the zuora_payment selector should be visible', () => {
expect(wrapper.find('#zuora_payment').element.style.display).toEqual('none');
});
});
describe('when active and not loading', () => {
beforeEach(() => {
wrapper.vm.toggleLoading();
});
it('the loading indicator should not be shown', () => {
expect(wrapper.find(GlLoadingIcon).exists()).toBe(false);
});
it('the zuora_payment selector should be visible', () => {
expect(wrapper.find('#zuora_payment').element.style.display).toEqual('');
});
});
describe('not active and not loading', () => {
beforeEach(() => {
createComponent({ methods: methodMocks, propsData: { active: false } });
wrapper.vm.toggleLoading();
});
it('the zuora_payment selector should not be visible', () => {
expect(wrapper.find('#zuora_payment').element.style.display).toEqual('none');
});
});
describe('toggleLoading', () => {
let spy;
beforeEach(() => {
spy = jest.spyOn(wrapper.vm, 'toggleLoading');
});
afterEach(() => {
spy.mockClear();
});
it('is called when the paymentMethodId is updated', () => {
store.commit(types.UPDATE_PAYMENT_METHOD_ID, 'foo');
return localVue.nextTick().then(() => {
expect(spy).toHaveBeenCalled();
});
});
it('is called when the creditCardDetails are updated', () => {
store.commit(types.UPDATE_CREDIT_CARD_DETAILS, {});
return localVue.nextTick().then(() => {
expect(spy).toHaveBeenCalled();
});
});
});
describe('renderZuoraIframe', () => {
it('is called when the paymentFormParams are updated', () => {
store.commit(types.UPDATE_PAYMENT_FORM_PARAMS, {});
return localVue.nextTick().then(() => {
expect(methodMocks.renderZuoraIframe).toHaveBeenCalled();
});
});
});
});
import Vuex from 'vuex';
import { mount, createLocalVue } from '@vue/test-utils';
import createStore from 'ee/subscriptions/new/store';
import * as types from 'ee/subscriptions/new/store/mutation_types';
import Step from 'ee/subscriptions/new/components/checkout/components/step.vue';
import Component from 'ee/subscriptions/new/components/checkout/payment_method.vue';
describe('Payment Method', () => {
const localVue = createLocalVue();
localVue.use(Vuex);
let wrapper;
const store = createStore();
const createComponent = (opts = {}) => {
wrapper = mount(Component, {
localVue,
sync: false,
store,
...opts,
});
};
beforeEach(() => {
createComponent();
});
afterEach(() => {
wrapper.destroy();
});
describe('validations', () => {
const isStepValid = () => wrapper.find(Step).props('isValid');
it('should be valid when paymentMethodId is defined', () => {
store.commit(types.UPDATE_PAYMENT_METHOD_ID, 'paymentMethodId');
return localVue.nextTick().then(() => {
expect(isStepValid()).toBe(true);
});
});
it('should be invalid when paymentMethodId is undefined', () => {
store.commit(types.UPDATE_PAYMENT_METHOD_ID, null);
return localVue.nextTick().then(() => {
expect(isStepValid()).toBe(false);
});
});
});
describe('showing the summary', () => {
beforeEach(() => {
store.commit(types.UPDATE_PAYMENT_METHOD_ID, 'paymentMethodId');
store.commit(types.UPDATE_CREDIT_CARD_DETAILS, {
cardType: 'Visa',
lastFourDigits: '4242',
expirationMonth: 12,
expirationYear: 19,
});
});
it('should show the entered credit card details', () => {
expect(
wrapper
.find('.js-summary-line-1')
.html()
.replace(/\s+/g, ' '),
).toContain('Visa ending in <strong>4242</strong>');
});
it('should show the entered credit card expiration date', () => {
expect(wrapper.find('.js-summary-line-2').text()).toEqual('Exp 12/19');
});
});
});
......@@ -341,4 +341,218 @@ describe('Subscriptions Actions', () => {
);
});
});
describe('fetchPaymentFormParams', () => {
beforeEach(() => {
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
});
it('fetches paymentFormParams and calls fetchPaymentFormParamsSuccess with the returned data on success', done => {
mock
.onGet(constants.PAYMENT_FORM_URL, { params: { id: constants.PAYMENT_FORM_ID } })
.replyOnce(200, { token: 'x' });
testAction(
actions.fetchPaymentFormParams,
null,
{},
[],
[{ type: 'fetchPaymentFormParamsSuccess', payload: { token: 'x' } }],
done,
);
});
it('calls fetchPaymentFormParamsError on error', done => {
mock.onGet(constants.PAYMENT_FORM_URL).replyOnce(500);
testAction(
actions.fetchPaymentFormParams,
null,
{},
[],
[{ type: 'fetchPaymentFormParamsError' }],
done,
);
});
});
describe('fetchPaymentFormParamsSuccess', () => {
it('updates paymentFormParams to the provided value when no errors are present', done => {
testAction(
actions.fetchPaymentFormParamsSuccess,
{ token: 'x' },
{},
[{ type: 'UPDATE_PAYMENT_FORM_PARAMS', payload: { token: 'x' } }],
[],
done,
);
});
it('creates a flash when errors are present', done => {
testAction(
actions.fetchPaymentFormParamsSuccess,
{ errors: 'error message' },
{},
[],
[],
() => {
expect(createFlash).toHaveBeenCalledWith(
'Credit card form failed to load: error message',
);
done();
},
);
});
});
describe('fetchPaymentFormParamsError', () => {
it('creates a flash', done => {
testAction(actions.fetchPaymentFormParamsError, null, {}, [], [], () => {
expect(createFlash).toHaveBeenCalledWith(
'Credit card form failed to load. Please try again.',
);
done();
});
});
});
describe('paymentFormSubmitted', () => {
describe('on success', () => {
it('calls paymentFormSubmittedSuccess with the refID from the response', done => {
testAction(
actions.paymentFormSubmitted,
{ success: true, refId: 'id' },
{},
[],
[{ type: 'paymentFormSubmittedSuccess', payload: 'id' }],
done,
);
});
});
describe('on failure', () => {
it('calls paymentFormSubmittedError with the response', done => {
testAction(
actions.paymentFormSubmitted,
{ error: 'foo' },
{},
[],
[{ type: 'paymentFormSubmittedError', payload: { error: 'foo' } }],
done,
);
});
});
});
describe('paymentFormSubmittedSuccess', () => {
it('updates paymentMethodId to the provided value and calls fetchPaymentMethodDetails', done => {
testAction(
actions.paymentFormSubmittedSuccess,
'id',
{},
[{ type: 'UPDATE_PAYMENT_METHOD_ID', payload: 'id' }],
[{ type: 'fetchPaymentMethodDetails' }],
done,
);
});
});
describe('paymentFormSubmittedError', () => {
it('creates a flash', done => {
testAction(
actions.paymentFormSubmittedError,
{ errorCode: 'codeFromResponse', errorMessage: 'messageFromResponse' },
{},
[],
[],
() => {
expect(createFlash).toHaveBeenCalledWith(
'Submitting the credit card form failed with code codeFromResponse: messageFromResponse',
);
done();
},
);
});
});
describe('fetchPaymentMethodDetails', () => {
beforeEach(() => {
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
});
it('fetches paymentMethodDetails and calls fetchPaymentMethodDetailsSuccess with the returned data on success', done => {
mock
.onGet(constants.PAYMENT_METHOD_URL, { params: { id: 'paymentMethodId' } })
.replyOnce(200, { token: 'x' });
testAction(
actions.fetchPaymentMethodDetails,
null,
{ paymentMethodId: 'paymentMethodId' },
[],
[{ type: 'fetchPaymentMethodDetailsSuccess', payload: { token: 'x' } }],
done,
);
});
it('calls fetchPaymentMethodDetailsError on error', done => {
mock.onGet(constants.PAYMENT_METHOD_URL).replyOnce(500);
testAction(
actions.fetchPaymentMethodDetails,
null,
{},
[],
[{ type: 'fetchPaymentMethodDetailsError' }],
done,
);
});
});
describe('fetchPaymentMethodDetailsSuccess', () => {
it('updates creditCardDetails to the provided data and calls activateNextStep', done => {
testAction(
actions.fetchPaymentMethodDetailsSuccess,
{
credit_card_type: 'cc_type',
credit_card_mask_number: '4242424242424242',
credit_card_expiration_month: 12,
credit_card_expiration_year: 2019,
},
{},
[
{
type: 'UPDATE_CREDIT_CARD_DETAILS',
payload: {
cardType: 'cc_type',
lastFourDigits: '4242',
expirationMonth: 12,
expirationYear: 19,
},
},
],
[{ type: 'activateNextStep' }],
done,
);
});
});
describe('fetchPaymentMethodDetailsError', () => {
it('creates a flash', done => {
testAction(actions.fetchPaymentMethodDetailsError, null, {}, [], [], () => {
expect(createFlash).toHaveBeenCalledWith(
'Failed to register credit card. Please try again.',
);
done();
});
});
});
});
......@@ -43,3 +43,27 @@ describe('ee/subscriptions/new/store/mutation', () => {
});
});
});
describe('UPDATE_PAYMENT_FORM_PARAMS', () => {
it('should set the paymentFormParams to the given paymentFormParams', () => {
mutations[types.UPDATE_PAYMENT_FORM_PARAMS](stateCopy, { token: 'x' });
expect(stateCopy.paymentFormParams).toEqual({ token: 'x' });
});
});
describe('UPDATE_PAYMENT_METHOD_ID', () => {
it('should set the paymentMethodId to the given paymentMethodId', () => {
mutations[types.UPDATE_PAYMENT_METHOD_ID](stateCopy, 'paymentMethodId');
expect(stateCopy.paymentMethodId).toEqual('paymentMethodId');
});
});
describe('UPDATE_CREDIT_CARD_DETAILS', () => {
it('should set the creditCardDetails to the given creditCardDetails', () => {
mutations[types.UPDATE_CREDIT_CARD_DETAILS](stateCopy, { type: 'x' });
expect(stateCopy.creditCardDetails).toEqual({ type: 'x' });
});
});
......@@ -137,4 +137,16 @@ describe('projectsSelector default state', () => {
it('sets the startDate to the current date', () => {
expect(state.startDate).toEqual(currentDate);
});
it('sets the paymentFormParams to an empty object', () => {
expect(state.paymentFormParams).toEqual({});
});
it('sets the paymentMethodId to null', () => {
expect(state.paymentMethodId).toBeNull();
});
it('sets the creditCardDetails to an empty object', () => {
expect(state.creditCardDetails).toEqual({});
});
});
......@@ -3338,6 +3338,9 @@ msgstr ""
msgid "Checkout|$%{selectedPlanPrice} per user per year"
msgstr ""
msgid "Checkout|%{cardType} ending in %{lastFourDigits}"
msgstr ""
msgid "Checkout|%{name}'s GitLab subscription"
msgstr ""
......@@ -3377,15 +3380,27 @@ msgstr ""
msgid "Checkout|Country"
msgstr ""
msgid "Checkout|Credit card form failed to load. Please try again."
msgstr ""
msgid "Checkout|Credit card form failed to load: %{message}"
msgstr ""
msgid "Checkout|Edit"
msgstr ""
msgid "Checkout|Exp %{expirationMonth}/%{expirationYear}"
msgstr ""
msgid "Checkout|Failed to load countries. Please try again."
msgstr ""
msgid "Checkout|Failed to load states. Please try again."
msgstr ""
msgid "Checkout|Failed to register credit card. Please try again."
msgstr ""
msgid "Checkout|GitLab plan"
msgstr ""
......@@ -3401,6 +3416,9 @@ msgstr ""
msgid "Checkout|Number of users"
msgstr ""
msgid "Checkout|Payment method"
msgstr ""
msgid "Checkout|Please select a country"
msgstr ""
......@@ -3413,6 +3431,9 @@ msgstr ""
msgid "Checkout|Street address"
msgstr ""
msgid "Checkout|Submitting the credit card form failed with code %{errorCode}: %{errorMessage}"
msgstr ""
msgid "Checkout|Subscription details"
msgstr ""
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment