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

refactor!: moved customer pages to subroutes #991

Merged
merged 19 commits into from
May 13, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default gql`
items {
order_number
id
created_at
order_date
grand_total
total {
discounts {
Expand Down
2 changes: 1 addition & 1 deletion packages/theme/components/AppHeader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export default defineComponent({

const handleAccountClick = async () => {
if (isAuthenticated.value) {
await router.push(`${app.localePath('/my-account/my-profile')}`);
await router.push(app.localeRoute({ name: 'customer-my-profile' }));
} else {
toggleLoginModal();
}
Expand Down
2 changes: 1 addition & 1 deletion packages/theme/components/BottomNavigation.vue
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export default defineComponent({
const { app } = useContext();
const handleAccountClick = async () => {
if (isAuthenticated.value) {
await router.push(`${app.localePath('/my-account')}`);
await router.push(app.localeRoute({ name: 'customer' }));
} else {
toggleLoginModal();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/theme/modules/catalog/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import path from 'node:path';
import url from 'node:url';
import { Module } from '@nuxt/types';
import type { Module } from '@nuxt/types';
import type { NuxtRouteConfig } from '@nuxt/types/config/router';

const nuxtModule : Module = function categoryModule() {
const themeDir = path.dirname(url.fileURLToPath(import.meta.url));

this.extendRoutes((routes) => {
this.extendRoutes((routes: NuxtRouteConfig[]) => {
routes.unshift({
name: 'category',
path: '/c/:slug_1/:slug_2?/:slug_3?/:slug_4?/:slug_5?',
Expand Down
2 changes: 1 addition & 1 deletion packages/theme/modules/checkout/getters/orderGetters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { CustomerOrder, OrderItemInterface } from '~/modules/GraphQL/types';

export const getDate = (order: CustomerOrder): string => new Date(order?.order_date).toLocaleDateString() || '';

export const getId = (order: CustomerOrder): string => String(Number.parseInt(order?.number, 10) || Math.floor(Math.random() * 100));
export const getId = (order: CustomerOrder): string => String(Number.parseInt(order?.number, 10) || '');

export const getStatus = (order: CustomerOrder): string => order?.status || 'Failed';

Expand Down
12 changes: 6 additions & 6 deletions packages/theme/modules/customer/composables/useUser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import type { Ref } from '@nuxtjs/composition-api';
import mask from '~/composables/utils/mask';
import { Logger } from '~/helpers/logger';
import { useCustomerStore } from '~/stores/customer';
import useCart from '~/modules/checkout/composables/useCart';
import { useCart } from '~/modules/checkout/composables/useCart';
import { generateUserData } from '~/modules/customer/helpers/generateUserData';
import { Customer } from '~/modules/GraphQL/types';
import type {
User,
UseUserInterface,
UseUserLoadParams,
UseUserLoginParams,
Expand Down Expand Up @@ -41,7 +41,7 @@ export function useUser(): UseUserInterface {
});
const error: Ref = ref(errorsFactory());

const setUser = (newUser: User) => {
const setUser = (newUser: Customer) => {
customerStore.user = newUser;
Logger.debug('useUserFactory.setUser', newUser);
};
Expand Down Expand Up @@ -81,9 +81,9 @@ export function useUser(): UseUserInterface {
Logger.debug('[Result]:', { data });

if (errors) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
Logger.error(errors.map((e) => e.message).join(','));
error.value.updateUser = errors.map((e) => e.message).join(',');
const allErrorMessages = errors.map((e) => e.message).join(',');
Logger.error(allErrorMessages);
error.value.updateUser = allErrorMessages;
}

customerStore.user = data?.updateCustomerV2?.customer || {};
Expand Down
21 changes: 5 additions & 16 deletions packages/theme/modules/customer/composables/useUser/useUser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Ref, ComputedRef } from '@nuxtjs/composition-api';
import type { ComposableFunctionArgs } from '~/composables/types';
import type { Customer, ChangeCustomerPasswordMutation } from '~/modules/GraphQL/types';

/**
* Errors that occured in the `useUser` composable
Expand All @@ -13,23 +14,11 @@ export interface UseUserErrors {
load: Error | null;
}

export interface User {
id: string
email: string
firstname: string
password: string
is_subscribed: boolean
middlename? : string
prefix?: string
suffix?: string
taxvat?: string
}

/**
* Parameters accepted by the `updateUser` method in the `useUser` composable
*/
export type UseUserUpdateUserParams = ComposableFunctionArgs<{
user: User;
user: ChangeCustomerPasswordMutation['changeCustomerPassword'] & { email?: string, password?: string }
}>;

/**
Expand Down Expand Up @@ -71,7 +60,7 @@ export interface UseUserInterface {
/**
* Overrides the `user` property with the data passed as a parameter
*/
setUser(newUser: User): void;
setUser(newUser: Customer): void;

/**
* Updates the current customer and saves the details returned from the API in the `user` property
Expand Down Expand Up @@ -101,7 +90,7 @@ export interface UseUserInterface {
/**
* Fetches the information about the current customer and saves results from the API in the `user` property
*/
load(params?: UseUserLoadParams): Promise<User>;
load(params?: UseUserLoadParams): Promise<Customer>;

/**
* Indicates whether any of the methods is in progress
Expand All @@ -116,7 +105,7 @@ export interface UseUserInterface {
/**
* Main data object populated by the `load()` method and updated by other methods in this composable
*/
user: ComputedRef<User | null>;
user: ComputedRef<Customer | null>;

/**
* Indicates whether the customer is authenticated or not
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Ref, DeepReadonly } from '@nuxtjs/composition-api';
import type { User } from '~/modules/customer/composables/useUser/useUser';
import type { CustomerAddress } from '~/modules/GraphQL/types';
import type { ComposableFunctionArgs } from '~/composables/types';
import { Customer } from '~/modules/GraphQL/types';

/**
* Errors that occured in the `useUserAddress` composable
Expand Down Expand Up @@ -57,7 +57,7 @@ export interface UseUserAddressInterface {
/**
* Loads addresses from the profile of the current user
*/
load(force?: boolean): Promise<User>; // TODO: Should accept custom queries
load(force?: boolean): Promise<Customer>; // TODO: Should accept custom queries

/**
* Sets an existing address as the default for the current user
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Ref } from '@nuxtjs/composition-api';
import type { ComposableFunctionArgs } from '~/composables/types';
import type {
Maybe,
CustomerOrdersQuery,
CustomerOrders,
CustomerOrdersQueryVariables,
} from '~/modules/GraphQL/types';

Expand All @@ -25,7 +25,7 @@ export interface UseUserOrderInterface {
/**
* Fetches orders of the current customer
*/
search(params: UseUserOrderSearchParams) : Promise<Maybe<Array<CustomerOrdersQuery['customer']['orders']['items']>>>;
search(params: UseUserOrderSearchParams) : Promise<Maybe<CustomerOrders>>;

/**
* Indicates whether any of the methods is in progress
Expand Down
43 changes: 22 additions & 21 deletions packages/theme/modules/customer/getters/userAddressesGetters.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
import { CustomerAddress } from '~/composables';
import { TransformedCustomerAddress } from '~/modules/customer/composables/types';
import { transformUserGetter } from '~/modules/customer/helpers/userAddressManipulator';

export interface UserAddressesGetters<USER_ADDRESS, USER_ADDRESS_ITEM> {
getAddresses: (shipping: USER_ADDRESS, criteria?: Record<string, any>) => USER_ADDRESS_ITEM[];
getTotal: (shipping: USER_ADDRESS) => number;
getPostCode: (address: USER_ADDRESS_ITEM) => string;
getStreetName: (address: USER_ADDRESS_ITEM) => string;
getCity: (address: USER_ADDRESS_ITEM) => string;
getFirstName: (address: USER_ADDRESS_ITEM) => string;
getLastName: (address: USER_ADDRESS_ITEM) => string;
getCountry: (address: USER_ADDRESS_ITEM) => string;
getPhone: (address: USER_ADDRESS_ITEM) => string;
getEmail: (address: USER_ADDRESS_ITEM) => string;
getProvince: (address: USER_ADDRESS_ITEM) => string;
getCompanyName: (address: USER_ADDRESS_ITEM) => string;
getTaxNumber: (address: USER_ADDRESS_ITEM) => string;
getId: (address: USER_ADDRESS_ITEM) => string | number;
getApartmentNumber: (address: USER_ADDRESS_ITEM) => string | number;
isDefault: (address: USER_ADDRESS_ITEM) => boolean;
isDefaultShipping: (address: USER_ADDRESS_ITEM) => boolean;
isDefaultBilling: (address: USER_ADDRESS_ITEM) => boolean;
export interface UserAddressesGetters<GENERIC_USER_ADDRESS_ITEM, SPECIFIC_USER_ADDRESS_ITEM> {
getAddresses: (shipping: GENERIC_USER_ADDRESS_ITEM[], criteria?: Record<string, any>) => GENERIC_USER_ADDRESS_ITEM[];
getTotal: (shipping: GENERIC_USER_ADDRESS_ITEM[]) => number;
getPostCode: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getStreetName: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getCity: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getFirstName: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getLastName: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getCountry: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getPhone: (address: SPECIFIC_USER_ADDRESS_ITEM) => string;
getEmail: (address: SPECIFIC_USER_ADDRESS_ITEM) => string;
getApartmentNumber: (address: SPECIFIC_USER_ADDRESS_ITEM) => string | number;
getProvince: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getCompanyName: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getTaxNumber: (address: GENERIC_USER_ADDRESS_ITEM) => string;
getId: (address: GENERIC_USER_ADDRESS_ITEM) => string | number;
isDefault: (address: GENERIC_USER_ADDRESS_ITEM) => boolean;
isDefaultShipping: (address: GENERIC_USER_ADDRESS_ITEM) => boolean;
isDefaultBilling: (address: GENERIC_USER_ADDRESS_ITEM) => boolean;
getNeighborhood: (address: any) => string
getAddressExtra: (address: any) => string
}

const userAddressesGetters: UserAddressesGetters<Array<TransformedCustomerAddress>, TransformedCustomerAddress> = {
const userAddressesGetters: UserAddressesGetters<CustomerAddress, TransformedCustomerAddress> = {
getAddresses: (addresses, criteria?: Record<string, any>) => {
if (!addresses || addresses.length === 0 || !Array.isArray(addresses)) return [];

Expand All @@ -49,12 +50,12 @@ const userAddressesGetters: UserAddressesGetters<Array<TransformedCustomerAddres
getCountry: (address) => address?.country_code || '',
getPhone: (address) => address?.phone || '',
getEmail: (address) => address?.email || '',
getApartmentNumber: (address) => (Array.isArray(address?.street) ? address?.street[1] : address?.apartment),
getProvince: (address) => (address?.region?.region_code || address?.region?.region) || '',
getCompanyName: (address) => address?.company || '',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getTaxNumber: (address) => address?.vat_id || '',
getId: (address) => address?.id || '',
getApartmentNumber: (address) => (Array.isArray(address?.street) ? address?.street[1] : address?.apartment),
getNeighborhood: (address) => (Array.isArray(address?.street) ? address?.street[2] : address?.neighborhood),
getAddressExtra: (address) => (Array.isArray(address?.street) ? address?.street[3] : address?.extra),
isDefault: (address) => (address?.default_shipping || address?.default_billing) || false,
Expand Down
85 changes: 73 additions & 12 deletions packages/theme/modules/customer/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,80 @@
import path from 'node:path';
import url from 'node:url';
import { Module } from '@nuxt/types';
import type { Module } from '@nuxt/types';
import type { NuxtRouteConfig } from '@nuxt/types/config/router';

const nuxtModule : Module = function customerModule() {
this.extendRoutes((routes) => {
const component = path.resolve(
path.dirname(url.fileURLToPath(import.meta.url)),
'pages/MyAccount.vue',
);
const moduleDir = path.dirname(url.fileURLToPath(import.meta.url));

const moduleRoutes : NuxtRouteConfig = {
name: 'customer',
path: '/customer',
component: path.resolve(moduleDir, 'pages/MyAccount/MyAccount.vue'),
meta: { titleLabel: 'My Account' },
children: [
{
name: 'customer-my-profile',
path: 'my-profile',
component: path.resolve(moduleDir, 'pages/MyAccount/MyProfile/MyProfile.vue'),
meta: { titleLabel: 'My profile' },
},
{
name: 'customer-addresses-details',
path: 'addresses-details',
component: path.resolve(moduleDir, 'pages/MyAccount/AddressesDetails/AddressesDetails.vue'),
meta: { titleLabel: 'Addresses details' },
},
{
name: 'customer-addresses-details-new',
path: 'addresses-details/create',
component: path.resolve(moduleDir, 'pages/MyAccount/AddressesDetails/AddressNew.vue'),
meta: { titleLabel: 'Addresses details' },
},
{
name: 'customer-addresses-details-edit',
path: 'addresses-details/edit/:addressId',
component: path.resolve(moduleDir, 'pages/MyAccount/AddressesDetails/AddressEdit.vue'),
// @ts-expect-error NuxtRouteConfig and RouteConfig conflict
props: true,
meta: { titleLabel: 'Addresses details' },
},
{
name: 'customer-my-newsletter',
path: 'my-newsletter',
component: path.resolve(moduleDir, 'pages/MyAccount/MyNewsletter.vue'),
meta: { titleLabel: 'My newsletter' },
},
{
name: 'customer-my-wishlist',
path: 'my-wishlist',
component: path.resolve(moduleDir, 'pages/MyAccount/MyWishlist.vue'),
meta: { titleLabel: 'My wishlist' },
},
{
name: 'customer-order-history',
path: 'order-history',
component: path.resolve(moduleDir, 'pages/MyAccount/OrderHistory/OrderHistory.vue'),
meta: { titleLabel: 'Order history' },
},
{
name: 'customer-single-order',
path: 'order-history/:orderId',
component: path.resolve(moduleDir, 'pages/MyAccount/OrderHistory/SingleOrder.vue'),
// @ts-expect-error NuxtRouteConfig and RouteConfig conflict
props: true,
meta: { titleLabel: 'Order history' },
},
{
name: 'customer-my-reviews',
path: 'my-reviews',
component: path.resolve(moduleDir, 'pages/MyAccount/MyReviews.vue'),
meta: { titleLabel: 'My reviews' },
},
],
};

routes.unshift({
name: 'my-account',
path: '/my-account/:pageName?',
component,
});
const nuxtModule : Module = function customerModule() {
this.extendRoutes((routes: NuxtRouteConfig[]) => {
routes.unshift(moduleRoutes);
});
};

Expand Down
Loading