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

Commit

Permalink
Add orders history to my account
Browse files Browse the repository at this point in the history
  • Loading branch information
Qrzy committed Feb 28, 2020
1 parent c08a0bf commit 149c5c1
Show file tree
Hide file tree
Showing 12 changed files with 221 additions and 68 deletions.
7 changes: 6 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,12 @@
"no-mixed-operators": 2,
"no-multi-assign": 2,
"no-unneeded-ternary": 2,
"object-property-newline": 0,
"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
16 changes: 13 additions & 3 deletions packages/commercetools/composables/src/useUser/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { ref, Ref, watch, computed } from '@vue/composition-api';
import { UseUser } 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 @@ -12,8 +17,10 @@ import { cart } from './../useCart';
type UserData = CustomerSignMeUpDraft | CustomerSignMeInDraft

const user: Ref<Customer> = ref({});
const orders: Ref<Order[]> = ref([]);
const loading: Ref<boolean> = ref(false);
const error: Ref<any> = ref(null);

const isAuthenticated = computed(() => user.value && Object.keys(user.value).length > 0);

const authenticate = async (userData: UserData, fn) => {
Expand All @@ -29,7 +36,7 @@ const authenticate = async (userData: UserData, fn) => {
loading.value = false;
};

export default function useUser(): UseUser<Customer> {
export default function useUser(): UseUser<Customer, Order> {
watch(user, async () => {
if (isAuthenticated.value) {
return;
Expand All @@ -40,7 +47,9 @@ export default function useUser(): UseUser<Customer> {
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 @@ -63,6 +72,7 @@ export default function useUser(): UseUser<Customer> {

return {
user: computed(() => user.value),
orders: computed(() => orders.value),
register,
login,
logout,
Expand Down
48 changes: 39 additions & 9 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,15 +27,20 @@ describe('[commercetools-composables] useUser', () => {
});

it('creates properties', () => {
const { loading, error } = useUser();
const { loading, error, orders } = useUser();

expect(loading.value).toEqual(true);
expect(error.value).toEqual(null);
expect(orders.value).toEqual([]);
});

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 @@ -40,16 +56,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 @@ -78,4 +100,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([]);
});

});
47 changes: 40 additions & 7 deletions packages/commercetools/helpers/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
import {
UiMediaGalleryItem,
UiCategory,
AgnosticOrderStatus,
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,
OrderState,
ProductVariant,
ShippingMethod
} from './types/GraphQL';
import {
formatAttributeList,
getVariantByAttributes
} from './_utils';

interface ProductVariantFilters {
master?: boolean;
Expand Down Expand Up @@ -71,8 +85,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 @@ -196,3 +212,20 @@ 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 || '';

const orderStatusMap = {
[OrderState.Open]: AgnosticOrderStatus.Open,
[OrderState.Confirmed]: AgnosticOrderStatus.Confirmed,
[OrderState.Complete]: AgnosticOrderStatus.Complete,
[OrderState.Cancelled]: AgnosticOrderStatus.Cancelled
};

export const getOrderStatus = (order: Order): AgnosticOrderStatus | '' => order?.orderState ? orderStatusMap[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);
});
});
14 changes: 13 additions & 1 deletion packages/core/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ export interface UseProduct<PRODUCT> {

export interface UseUser
<
USER
USER,
ORDER
> {
user: Readonly<Ref<Readonly<USER>>>;
orders: Readonly<Ref<Readonly<ORDER[]>>>;
register: (user: {
email: string;
password: string;
Expand Down Expand Up @@ -176,3 +178,13 @@ export interface AgnosticProductAttribute {
value: string | Record<string, any>;
label: string;
}

export enum AgnosticOrderStatus {
Open = 'Open',
Pending = 'Pending',
Confirmed = 'Confirmed',
Shipped = 'Shipped',
Complete = 'Complete',
Cancelled = 'Cancelled',
Refunded = 'Refunded'
}
2 changes: 1 addition & 1 deletion packages/core/theme-module/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: 1 addition & 1 deletion packages/core/theme-module/theme/pages/MyAccount.vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
</SfContentCategory>
<SfContentCategory title="Order details">
<SfContentPage title="Order history">
<OrderHistory :account="account" />
<OrderHistory />
</SfContentPage>
<SfContentPage title="My reviews">
<MyReviews />
Expand Down
Loading

0 comments on commit 149c5c1

Please sign in to comment.