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 25, 2020
1 parent 7e5ff8b commit 313fd32
Show file tree
Hide file tree
Showing 17 changed files with 437 additions and 294 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
2 changes: 2 additions & 0 deletions packages/commercetools/api-client/src/fragments/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,12 @@ export const OrderFragment = `
}
totalPrice {
centAmount
currencyCode
}
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([]);
});

});
58 changes: 58 additions & 0 deletions packages/commercetools/helpers/src/cart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import {
AgnosticTotals
} from '@vue-storefront/interfaces';
import {
Cart,
LineItem
} from './types/GraphQL';
import { getProductAttributes } from './product';

// Cart

export const getCartProducts = (cart: Cart): LineItem[] => {
if (!cart) {
return [];
}

return cart.lineItems;
};

export const getCartProductName = (product: LineItem): string => product.name;

export const getCartProductImage = (product: LineItem): string => product.variant.images[0].url;

export const getCartProductPrice = (product: LineItem): number => product.price.value.centAmount / 100;

export const getCartProductQty = (product: LineItem): number => product.quantity;

export const getCartProductAttributes = (product: LineItem, filterByAttributeName?: Array<string>) =>
getProductAttributes(product.variant, filterByAttributeName);

export const getCartProductSku = (product: LineItem): string => product.variant.sku;

export const getCartTotals = (cart: Cart): AgnosticTotals => {
if (!cart) {
return {
total: 0,
subtotal: 0
};
}

const subtotalPrice = cart.totalPrice.centAmount;
const shipping = cart.shippingInfo ? cart.shippingInfo.price.centAmount : 0;

return {
total: (shipping + subtotalPrice) / 100,
subtotal: subtotalPrice / 100
};
};

export const getCartShippingPrice = (cart: Cart): number => cart && cart.shippingInfo ? cart.shippingInfo.price.centAmount / 100 : 0;

export const getCartTotalItems = (cart: Cart): number => {
if (!cart) {
return 0;
}

return cart.lineItems.reduce((previous, current) => previous + current.quantity, 0);
};
37 changes: 37 additions & 0 deletions packages/commercetools/helpers/src/category.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import {
UiCategory
} from '@vue-storefront/interfaces';
import {
ProductVariant,
Category
} from './types/GraphQL';

// Category
export const getCategoryProducts = (category: Category, options: any = {}): ProductVariant[] => {
if (!category || !(category as any)._products) {
return [];
}

const { _products } = category as any;

if (options.master) {
return _products.filter((v) => (v as any)._master);
}

return _products;
};

export const getCategoryTree = (category: Category): UiCategory | null => {
const getRoot = (category: Category): Category => (category.parent ? getRoot(category.parent) : category);
const buildTree = (rootCategory: Category) => ({
label: rootCategory.name,
slug: rootCategory.slug,
items: rootCategory.children.map(buildTree)
});

if (!category) {
return null;
}

return buildTree(getRoot(category));
};
Loading

0 comments on commit 313fd32

Please sign in to comment.