Skip to content

Commit

Permalink
refactor(core): update order page to use slug
Browse files Browse the repository at this point in the history
  • Loading branch information
bc-alexsaiannyi committed Nov 26, 2024
1 parent a82faf0 commit 520cbd1
Show file tree
Hide file tree
Showing 8 changed files with 305 additions and 274 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import { Link } from '~/components/link';
import { Button } from '~/components/ui/button';
import { cn } from '~/lib/utils';

import { OrderDetailsDataType } from '../page-data';
import { assembleProductData, ProductSnippet } from '../../../orders/_components/product-snippet';
import { OrderDataType } from '../page';

import { assembleProductData, ProductSnippet } from './product-snippet';

const OrderState = async ({ orderState }: { orderState: OrderDetailsDataType['orderState'] }) => {
const OrderState = async ({ orderState }: { orderState: OrderDataType['orderState'] }) => {
const t = await getTranslations('Account.Orders');
const format = await getFormatter();
const { orderId, orderDate, status } = orderState;
Expand All @@ -35,11 +34,7 @@ const OrderState = async ({ orderState }: { orderState: OrderDetailsDataType['or
);
};

const OrderSummaryInfo = async ({
summaryInfo,
}: {
summaryInfo: OrderDetailsDataType['summaryInfo'];
}) => {
const OrderSummaryInfo = async ({ summaryInfo }: { summaryInfo: OrderDataType['summaryInfo'] }) => {
const t = await getTranslations('Account.Orders');
const format = await getFormatter();
const { subtotal, shipping, tax, discounts, grandTotal } = summaryInfo;
Expand Down Expand Up @@ -117,7 +112,7 @@ const OrderSummaryInfo = async ({
);
};
const combineAddressInfo = (
address: NonNullable<OrderDetailsDataType['consignments']['shipping']>[number]['shippingAddress'],
address: NonNullable<OrderDataType['consignments']['shipping']>[number]['shippingAddress'],
) => {
const { firstName, lastName, address1, city, stateOrProvince, postalCode, country } = address;
const fullName = `${firstName ?? ''} ${lastName ?? ''}`;
Expand All @@ -129,7 +124,7 @@ const combineAddressInfo = (
};
const combineShippingMethodInfo = async (
shipment?: NonNullable<
NonNullable<OrderDetailsDataType['consignments']['shipping']>[number]['shipments']
NonNullable<OrderDataType['consignments']['shipping']>[number]['shipments']
>[number],
) => {
if (!shipment) {
Expand All @@ -154,7 +149,7 @@ const ShippingInfo = async ({
isMultiConsignments,
shippingNumber,
}: {
consignments: OrderDetailsDataType['consignments'];
consignments: OrderDataType['consignments'];
isMultiConsignments: boolean;
shippingNumber?: number;
}) => {
Expand Down Expand Up @@ -232,7 +227,7 @@ const ShippingInfo = async ({
);
};

export const OrderDetails = async ({ data }: { data: OrderDetailsDataType }) => {
export const OrderDetails = async ({ data }: { data: OrderDataType }) => {
const t = await getTranslations('Account.Orders');
const { orderState, summaryInfo, consignments } = data;
const shippingConsignments = consignments.shipping;
Expand Down
199 changes: 199 additions & 0 deletions core/app/[locale]/(default)/account/(tabs)/order/[slug]/page-data.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import { removeEdgesAndNodes } from '@bigcommerce/catalyst-client';
import { cache } from 'react';

import { getSessionCustomerAccessToken } from '~/auth';
import { client } from '~/client';
import { graphql, ResultOf, VariablesOf } from '~/client/graphql';
import { revalidate } from '~/client/revalidate-target';
import { ExistingResultType } from '~/client/util';

import {
OrderItemFragment,
ProductAttributes,
ProductAttributesVariables,
} from '../../orders/_components/product-snippet';

export const OrderShipmentFragment = graphql(`
fragment OrderShipmentFragment on OrderShipment {
shippingMethodName
shippingProviderName
tracking {
__typename
... on OrderShipmentNumberAndUrlTracking {
number
url
}
... on OrderShipmentUrlOnlyTracking {
url
}
... on OrderShipmentNumberOnlyTracking {
number
}
}
}
`);

const CustomerOrderDetails = graphql(
`
query CustomerOrderDetails($filter: OrderFilterInput) {
site {
order(filter: $filter) {
entityId
orderedAt {
utc
}
status {
label
value
}
totalIncTax {
value
currencyCode
}
subTotal {
value
currencyCode
}
discounts {
nonCouponDiscountTotal {
value
currencyCode
}
couponDiscounts {
couponCode
discountedAmount {
value
currencyCode
}
}
}
shippingCostTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
billingAddress {
firstName
lastName
address1
city
stateOrProvince
postalCode
country
}
consignments {
shipping {
edges {
node {
entityId
shippingAddress {
firstName
lastName
address1
city
stateOrProvince
postalCode
country
}
shipments {
edges {
node {
entityId
shippedAt {
utc
}
...OrderShipmentFragment
}
}
}
lineItems {
edges {
node {
...OrderItemFragment
}
}
}
}
}
}
}
}
}
}
`,
[OrderItemFragment, OrderShipmentFragment],
);

export const getProductAttributes = cache(async (variables: ProductAttributesVariables) => {
const response = await client.fetch({
document: ProductAttributes,
variables,
fetchOptions: { next: { revalidate } },
});

return response.data.site.product;
});

type ShippingConsignments = NonNullable<
NonNullable<ResultOf<typeof CustomerOrderDetails>['site']['order']>['consignments']
>['shipping'];

export const addProductAttributesToShippingConsignments = async (
consignments: ShippingConsignments,
) => {
const shipping = removeEdgesAndNodes(consignments);

const shippingConsignments = await Promise.all(
shipping.map(async (consignment) => {
const { lineItems, shipments, ...otherItems } = consignment;
const extendedLineItems = await Promise.all(
removeEdgesAndNodes(lineItems).map(async ({ productEntityId, ...otherAttributes }) => {
const productAtrributes = await getProductAttributes({
entityId: productEntityId,
});

const { path = '' } = productAtrributes ?? {};

return {
productEntityId,
path,
...otherAttributes,
};
}),
);

return {
lineItems: extendedLineItems,
shipments: removeEdgesAndNodes(shipments),
...otherItems,
};
}),
);

return shippingConsignments;
};

type OrderVariables = VariablesOf<typeof CustomerOrderDetails>;

export const getOrderDetails = cache(async (variables: OrderVariables) => {
const customerAccessToken = await getSessionCustomerAccessToken();

const response = await client.fetch({
document: CustomerOrderDetails,
variables,
fetchOptions: { cache: 'no-store' },
customerAccessToken,
});
const order = response.data.site.order;

if (!order) {
return undefined;
}

return order;
});

export type OrderDetailsType = ExistingResultType<typeof getOrderDetails>;
68 changes: 68 additions & 0 deletions core/app/[locale]/(default)/account/(tabs)/order/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { notFound } from 'next/navigation';

import { ExistingResultType } from '~/client/util';

import { OrderDetails } from './_components/order-details';
import {
addProductAttributesToShippingConsignments,
getOrderDetails,
OrderDetailsType,
} from './page-data';

interface Props {
params: Promise<{
slug: string;
locale: string;
}>;
}

const mapOrderData = async (order: OrderDetailsType) => {
const shipping =
order.consignments?.shipping &&
(await addProductAttributesToShippingConsignments(order.consignments.shipping));

return {
orderState: {
orderId: order.entityId,
status: order.status,
orderDate: order.orderedAt,
},
summaryInfo: {
subtotal: order.subTotal,
discounts: order.discounts,
shipping: order.shippingCostTotal,
tax: order.taxTotal,
grandTotal: order.totalIncTax,
},
paymentInfo: {
billingAddress: order.billingAddress,
// TODO: add payments data
},
consignments: {
shipping,
},
};
};

export type OrderDataType = ExistingResultType<typeof mapOrderData>;

export default async function Order(props: Props) {
const { slug } = await props.params;
const entityId = Number(slug);

const order = await getOrderDetails({
filter: {
entityId,
},
});

if (!order) {
notFound();
}

const data = await mapOrderData(order);

return <OrderDetails data={data} />;
}

export const runtime = 'edge';
Original file line number Diff line number Diff line change
@@ -1,32 +1,24 @@
import { notFound } from 'next/navigation';
import { getTranslations } from 'next-intl/server';

import { ExistingResultType } from '~/client/util';
import { Pagination } from '~/components/ui/pagination';

import { TabHeading } from '../../_components/tab-heading';
import { getCustomerOrders, getOrderDetails } from '../page-data';
import { getCustomerOrders } from '../page-data';

import { OrderDetails } from './order-details';
import { OrdersList } from './orders-list';

type CustomerOrders = NonNullable<Awaited<ReturnType<typeof getCustomerOrders>>>;
type CustomerOrders = ExistingResultType<typeof getCustomerOrders>;

interface Props {
orderId?: string;
orders: CustomerOrders['orders'];
pageInfo: CustomerOrders['pageInfo'];
}

export const OrdersContent = async ({ orderId, orders, pageInfo }: Props) => {
export const OrdersContent = async ({ orders, pageInfo }: Props) => {
const t = await getTranslations('Account.Orders');
const { hasNextPage, hasPreviousPage, startCursor, endCursor } = pageInfo;

if (orderId) {
const orderData = await getOrderDetails({ orderId });

return orderData ? <OrderDetails data={orderData} /> : notFound();
}

return (
<>
<TabHeading heading="orders" />
Expand Down
Loading

0 comments on commit 520cbd1

Please sign in to comment.