Skip to content
This repository has been archived by the owner on May 21, 2020. It is now read-only.

Commit

Permalink
Add orders list to my account
Browse files Browse the repository at this point in the history
  • Loading branch information
Qrzy committed Feb 26, 2020
1 parent 7e5ff8b commit f9e19e0
Show file tree
Hide file tree
Showing 11 changed files with 181 additions and 98 deletions.
7 changes: 6 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,12 @@
"no-mixed-operators": 2,
"no-multi-assign": 2,
"no-unneeded-ternary": 2,
"object-property-newline": 2,
"object-property-newline": [
2,
{
"allowAllPropertiesOnSameLine": true
}
],
"operator-linebreak": 2,
"quote-props": [
2,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import gql from 'graphql-tag';
import { CartFragment, CustomerFragment } from './../../fragments';
import { CartFragment, CustomerFragment, OrderFragment } from './../../fragments';

const basicProfile = gql`
${CartFragment}
Expand All @@ -16,6 +16,7 @@ const basicProfile = gql`
const fullProfile = gql`
${CartFragment}
${CustomerFragment}
${OrderFragment}
query getMe($locale: Locale!) {
me {
Expand All @@ -25,6 +26,11 @@ const fullProfile = gql`
customer {
...DefaultCustomer
}
orders {
results {
...DefaultOrder
}
}
}
}
`;
Expand Down
1 change: 1 addition & 0 deletions packages/commercetools/api-client/src/fragments/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ export const OrderFragment = `
orderState
id
version
createdAt
}
`;

Expand Down
13 changes: 8 additions & 5 deletions packages/commercetools/composables/src/useUser/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ref, Ref, watch, computed } from '@vue/composition-api';
import { UseUser, AgnosticUserLogin, AgnosticUserRegister } from '@vue-storefront/interfaces';
import { Customer, CustomerSignMeUpDraft, CustomerSignMeInDraft } from '@vue-storefront/commercetools-api/lib/src/types/GraphQL';
import { Customer, CustomerSignMeUpDraft, CustomerSignMeInDraft, Order } from '@vue-storefront/commercetools-api/lib/src/types/GraphQL';
import {
customerSignMeUp,
customerSignMeIn,
Expand All @@ -9,13 +9,13 @@ import {
} from '@vue-storefront/commercetools-api';
import { cart } from './../useCart';

type UserRef = Ref<Customer>
type RegisterFn = (userData: AgnosticUserRegister) => Promise<void>
type LoginFn = (userData: AgnosticUserLogin) => Promise<void>
type LogoutFn = () => Promise<void>
type UserData = CustomerSignMeUpDraft | CustomerSignMeInDraft

const user: UserRef = ref({});
const user: Ref<Customer> = ref({});
const orders: Ref<Order[]> = ref([]);
const loading = ref(false);
const error = ref(null);
const isAuthenticated = computed(() => user.value && Object.keys(user.value).length > 0);
Expand All @@ -33,7 +33,7 @@ const authenticate = async (userData: UserData, fn) => {
loading.value = false;
};

export default function useUser(): UseUser<UserRef, RegisterFn, LoginFn, LogoutFn> {
export default function useUser(): UseUser<Ref<Customer>, RegisterFn, LoginFn, LogoutFn, Ref<Order[]>> {
watch(user, async () => {
if (isAuthenticated.value) {
return;
Expand All @@ -44,7 +44,9 @@ export default function useUser(): UseUser<UserRef, RegisterFn, LoginFn, LogoutF
try {
const profile = await getMe({ customer: true });
user.value = profile.data.me.customer;
} catch (err) {} // eslint-disable-line
orders.value = profile.data.me.orders.results;
// eslint-disable-next-line no-empty
} catch (err) {}

loading.value = false;
});
Expand All @@ -67,6 +69,7 @@ export default function useUser(): UseUser<UserRef, RegisterFn, LoginFn, LogoutF

return {
user,
orders,
register,
login,
logout,
Expand Down
45 changes: 37 additions & 8 deletions packages/commercetools/composables/tests/useUser/useUser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,19 @@ jest.mock('@vue-storefront/commercetools-api', () => ({
customerSignMeUp: jest.fn(),
customerSignMeIn: jest.fn(),
customerSignOut: jest.fn(),
getMe: () => ({ data: { me: { customer: { firstName: 'loaded customer',
lastName: 'loaded customer' } } } })
getMe: () => ({
data: {
me: {
customer: {
firstName: 'loaded customer',
lastName: 'loaded customer'
},
orders: {
results: []
}
}
}
})
}));

describe('[commercetools-composables] useUser', () => {
Expand All @@ -16,8 +27,12 @@ describe('[commercetools-composables] useUser', () => {
});

it('registers new customer', async () => {
const user = { customer: { firstName: 'john',
lastName: 'doe' } };
const user = {
customer: {
firstName: 'john',
lastName: 'doe'
}
};
(customerSignMeUp as any).mockReturnValue(Promise.resolve({ data: { user } }));

const wrapper = mountComposable(useUser);
Expand All @@ -33,16 +48,22 @@ describe('[commercetools-composables] useUser', () => {
});

it('login customer and log out', async () => {
const user = { customer: { firstName: 'john',
lastName: 'doe' } };
const user = {
customer: {
firstName: 'john',
lastName: 'doe'
}
};
(customerSignMeIn as any).mockReturnValue(Promise.resolve({ data: { user } }));

const wrapper = mountComposable(useUser);
await wrapper.vm.$nextTick();
await wrapper.vm.$nextTick();

wrapper.vm.$data.login({ email: '[email protected]',
password: '123' });
wrapper.vm.$data.login({
email: '[email protected]',
password: '123'
});

expect(wrapper.vm.$data.loading).toBeTruthy();
await wrapper.vm.$nextTick();
Expand Down Expand Up @@ -71,4 +92,12 @@ describe('[commercetools-composables] useUser', () => {
lastName: 'loaded customer'
});
});

it('loads current customer with orders', async () => {
const wrapper = mountComposable(useUser);
await wrapper.vm.$nextTick();
await wrapper.vm.$nextTick();
expect(wrapper.vm.$data.orders).toEqual([]);
});

});
38 changes: 31 additions & 7 deletions packages/commercetools/helpers/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import {
UiMediaGalleryItem,
UiCategory,
AgnosticProductAttribute,
AgnosticTotals
AgnosticTotals,
UiCategory,
UiMediaGalleryItem
} from '@vue-storefront/interfaces';
import { ProductVariant, Image, Category, Cart, LineItem, ShippingMethod, Customer } from './types/GraphQL';
import { formatAttributeList, getVariantByAttributes } from './_utils';
import {
Cart,
Category,
Customer,
Image,
LineItem,
Order,
ProductVariant,
ShippingMethod
} from './types/GraphQL';
import {
formatAttributeList,
getVariantByAttributes
} from './_utils';

interface ProductVariantFilters {
master?: boolean;
Expand Down Expand Up @@ -76,8 +88,10 @@ export const getProductAttributes = (products: ProductVariant[] | ProductVariant
...prev,
[curr.name]: isSingleProduct ? curr.value : [
...(prev[curr.name] || []),
{ value: curr.value,
label: curr.label }
{
value: curr.value,
label: curr.label
}
]
});

Expand Down Expand Up @@ -201,3 +215,13 @@ export const getUserFirstName = (user: Customer): string => user ? user.firstNam
export const getUserLastName = (user: Customer): string => user ? user.lastName : '';

export const getUserFullName = (user: Customer): string => user ? `${user.firstName} ${user.lastName}` : '';

// Order

export const getOrderDate = (order: Order): string => order?.createdAt || '';

export const getOrderNumber = (order: Order): string => order?.id || '';

export const getOrderStatus = (order: Order): string => order?.orderState || '';

export const getOrderTotal = (order: Order): number | null => order ? order.totalPrice.centAmount / 100 : null;
42 changes: 42 additions & 0 deletions packages/commercetools/helpers/tests/orderHelpers.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
getOrderDate,
getOrderNumber,
getOrderStatus,
getOrderTotal
} from '../src';
import { OrderState, Order } from '../src/types/GraphQL';

const order: Order = {
createdAt: 123456789,
id: '645ygdf',
orderState: OrderState.Complete,
totalPrice: {
centAmount: 12345,
currencyCode: 'USD'
}
} as any;

describe('[commercetools-helpers] order helpers', () => {
it('returns default values', () => {
expect(getOrderDate(null)).toBe('');
expect(getOrderNumber(null)).toBe('');
expect(getOrderStatus(null)).toBe('');
expect(getOrderTotal(null)).toBe(null);
});

it('returns date', () => {
expect(getOrderDate(order)).toEqual(123456789);
});

it('returns order number', () => {
expect(getOrderNumber(order)).toEqual('645ygdf');
});

it('returns status', () => {
expect(getOrderStatus(order)).toEqual(OrderState.Complete);
});

it('returns total gross', () => {
expect(getOrderTotal(order)).toEqual(123.45);
});
});
2 changes: 1 addition & 1 deletion packages/commercetools/theme/pages/Checkout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default {
CartPreview,
OrderReview
},
setup(context) {
setup(props, context) {
const showCartPreview = ref(true);
const currentStep = ref(0);
Expand Down
2 changes: 2 additions & 0 deletions packages/core/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ export interface UseUser
REGISTER,
LOGIN,
LOGOUT,
ORDERS
> {
user: USER;
orders: ORDERS;
register: REGISTER;
login: LOGIN;
logout: LOGOUT;
Expand Down
Loading

0 comments on commit f9e19e0

Please sign in to comment.