Skip to content
Open
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
1 change: 1 addition & 0 deletions data-layer.lock.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Rows are keyed by file and enclosing function, not line, so formatting does not
| mutate | CheckoutLinesUpdateDocument | — | src/app/actions.ts › updateCartLineQuantity |
| rawMutation | — | — | src/app/api/auth/register/route.ts › POST |
| rawMutation | — | — | src/app/api/auth/reset-password/route.ts › POST |
| mutate | BuyAgainAddDocument | — | src/app/buy-again/actions.ts › buyAgain |
| mutate | checkoutMetadataUpdateDocument | — | src/checkout/lib/server/enrich-commerce-context.ts › enrichCheckoutCommerceContext |
| liveQuery | checkoutCommerceContextDocument | — | src/checkout/lib/server/enrich-commerce-context.ts › readCheckoutMetadata |
| liveQuery | channelQueryDocument | — | src/checkout/lib/server/fetch-channel-countries.ts › fetchChannelCountriesOnServer |
Expand Down
22 changes: 22 additions & 0 deletions messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,28 @@
"signInRequired": "Sign in to view your orders.",
"orderNumber": "ORD-{number}"
},
"buyAgain": {
"compare": "Compare approaches",
"quick": "Quick repeat",
"receipt": "Itemized receipt",
"choose": "Pick your items",
"quickButton": "Buy again",
"ready": "{count} of {all} available to buy again",
"receiptTitle": "Buy this order again",
"chooseTitle": "Pick your items",
"chooseHint": "Available items are selected. Uncheck anything you don’t need.",
"prices": "Current prices apply in your cart.",
"quantity": "Qty {count}",
"limited": "{count} of {all} available",
"unavailable": "No longer available",
"adding": "Adding…",
"added": "Added to cart",
"addCount": "{count, plural, one {Add # item} other {Add # items}}",
"addedCount": "{count, plural, one {# item added.} other {# items added.}}",
"skipped": "{count, plural, one {# unavailable item skipped.} other {# unavailable items skipped.}}",
"failed": "Couldn’t confirm the full update. Check your cart before trying again.",
"viewCart": "View cart"
},
"orderDetail": {
"placedOn": "Placed on {date}",
"items": "Items ({count})",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ import { LinkWithChannel } from "@/ui/atoms/link-with-channel";
import { Button } from "@/ui/components/ui/button";
import { accountRoutes } from "@/ui/components/account/routes";
import { AccountOrdersListSkeleton } from "@/ui/components/account/account-skeleton";
import { BuyAgain } from "@/ui/components/account/buy-again";
import { reorderItems } from "@/lib/custom/buy-again";
import { buttonClassName } from "@/ui/components/ui/button";

const ORDERS_PER_PAGE = 10;

type Props = {
params: Promise<{ locale: string }>;
searchParams: Promise<{ after?: string }>;
params: Promise<{ locale: string; channel: string }>;
searchParams: Promise<{ after?: string; view?: string }>;
};

export default function AccountOrdersPage({ params, searchParams }: Props) {
Expand All @@ -25,7 +28,9 @@ export default function AccountOrdersPage({ params, searchParams }: Props) {
}

async function AccountOrdersContent({ params, searchParams }: Props) {
const [{ locale }, { after }] = await Promise.all([params, searchParams]);
const [{ locale, channel }, { after, view: requestedView }] = await Promise.all([params, searchParams]);
const view = requestedView === "receipt" || requestedView === "choose" ? requestedView : "quick";
const tBuy = await getTranslations({ locale, namespace: "account.buyAgain" });
const t = await getTranslations({ locale, namespace: "account.orders" });
const tErrors = await getTranslations({ locale, namespace: "account.errors" });
const tOrder = await getTranslations({ locale, namespace: "account" });
Expand Down Expand Up @@ -63,20 +68,55 @@ async function AccountOrdersContent({ params, searchParams }: Props) {
</div>
) : (
<>
<div className="space-y-2">
{requestedView && (
<nav
aria-label={tBuy("compare")}
className="flex flex-wrap items-center gap-2 rounded-lg bg-secondary/50 p-3"
>
<span className="mr-1 text-xs font-semibold text-muted-foreground">{tBuy("compare")}</span>
{(["quick", "receipt", "choose"] as const).map((option) => (
<LinkWithChannel
key={option}
href={`${accountRoutes.orders}?${new URLSearchParams({ view: option, ...(after ? { after } : {}) })}`}
aria-current={view === option ? "page" : undefined}
className={buttonClassName({
size: "sm",
variant: view === option ? "default" : "ghost",
asLink: true,
})}
>
{tBuy(option)}
</LinkWithChannel>
))}
</nav>
)}
<div className="space-y-4">
{orders.map(({ node: order }) => (
<OrderRow
key={order.id}
order={order}
localeSlug={locale}
labels={buildOrderRowLabels(tOrder, tStatus, order)}
/>
<article key={order.id} className="rounded-lg border">
<OrderRow
order={order}
localeSlug={locale}
labels={buildOrderRowLabels(tOrder, tStatus, order)}
grouped
/>
<BuyAgain
key={view}
view={view}
items={reorderItems(order, channel)}
orderId={order.id}
channel={channel}
locale={locale}
after={after}
/>
</article>
))}
</div>

{pageInfo?.hasNextPage && pageInfo.endCursor && (
<div className="flex justify-center pt-2">
<LinkWithChannel href={`${accountRoutes.orders}?after=${pageInfo.endCursor}`}>
<LinkWithChannel
href={`${accountRoutes.orders}?${new URLSearchParams({ after: pageInfo.endCursor, ...(requestedView ? { view } : {}) })}`}
>
<Button variant="outline-solid">{t("loadMore")}</Button>
</LinkWithChannel>
</div>
Expand Down
97 changes: 97 additions & 0 deletions src/app/buy-again/actions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { beforeEach, expect, it, vi } from "vitest";
import { buyAgain } from "./actions";

const api = vi.hoisted(() => ({
getCurrentUserOrders: vi.fn(),
getIdFromCookies: vi.fn(),
find: vi.fn(),
findOrCreate: vi.fn(),
saveIdToCookie: vi.fn(),
mutate: vi.fn(),
refresh: vi.fn(),
}));
vi.mock("@/lib/account/get-orders", () => api);
vi.mock("@/lib/checkout", () => api);
vi.mock("@/lib/saleor", () => api);
vi.mock("next/cache", () => api);

const input = { channel: "retail", locale: "en", orderId: "order" };
const order = {
id: "order",
channel: { slug: "retail" },
lines: [
{
id: "tee",
quantity: 2,
productName: "Tee",
variantName: "S",
variant: { id: "small", quantityAvailable: 10, product: { isAvailableForPurchase: true } },
},
{
id: "mug",
quantity: 1,
productName: "Mug",
variantName: "",
variant: { id: "blue", quantityAvailable: 1, product: { isAvailableForPurchase: true } },
},
{ id: "retired", quantity: 1, productName: "Tote", variantName: "", variant: null },
],
};

beforeEach(() => {
vi.resetAllMocks();
api.getCurrentUserOrders.mockResolvedValue({
ok: true,
data: { me: { orders: { edges: [{ node: order }] } } },
});
api.getIdFromCookies.mockResolvedValue("my-cart");
api.find.mockResolvedValue({ id: "my-cart", lines: [] });
api.mutate.mockResolvedValue({
ok: true,
data: { checkoutLinesAdd: { checkout: { id: "my-cart" }, errors: [] } },
});
});

it("does not touch a checkout for an order outside the customer's history", async () => {
expect(await buyAgain({ ...input, orderId: "another-order" })).toEqual({
added: 0,
skipped: 0,
failed: true,
});
expect(api.getIdFromCookies).not.toHaveBeenCalled();
expect(api.mutate).not.toHaveBeenCalled();
});

it("appends only the shopper's selected order line to the existing checkout", async () => {
expect(await buyAgain({ ...input, selected: ["tee", "not-an-order-line"] })).toEqual({
added: 2,
skipped: 0,
failed: false,
});
expect(api.mutate).toHaveBeenCalledTimes(1);
expect(api.mutate.mock.calls[0][1].variables).toEqual({
id: "my-cart",
line: { variantId: "small", quantity: 2 },
});
expect(api.findOrCreate).not.toHaveBeenCalled();
});

it("keeps later available lines when an earlier line sells out during the click", async () => {
api.mutate.mockResolvedValueOnce({
ok: true,
data: { checkoutLinesAdd: { checkout: null, errors: [{ code: "INSUFFICIENT_STOCK" }] } },
});
expect(await buyAgain(input)).toEqual({ added: 1, skipped: 3, failed: false });
expect(api.mutate).toHaveBeenCalledTimes(2);
expect(api.refresh).toHaveBeenCalledOnce();
});

it("does not create a checkout for an all-unavailable selection", async () => {
expect(await buyAgain({ ...input, selected: ["retired"] })).toEqual({
added: 0,
skipped: 1,
failed: false,
});
expect(api.findOrCreate).not.toHaveBeenCalled();
expect(api.mutate).not.toHaveBeenCalled();
});
69 changes: 69 additions & 0 deletions src/app/buy-again/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"use server";

import { refresh } from "next/cache";
import { BuyAgainAddDocument } from "@/gql/graphql";
import { getCurrentUserOrders } from "@/lib/account/get-orders";
import * as Checkout from "@/lib/checkout";
import { planReorder, reorderItems } from "@/lib/custom/buy-again";
import { mutate } from "@/lib/saleor";

export async function buyAgain(input: {
orderId: string;
channel: string;
locale: string;
after?: string;
selected?: string[];
}) {
const failed = { added: 0, skipped: 0, failed: true };
const result = await getCurrentUserOrders(input.locale, 10, input.after);
if (!result.ok || result.partialErrors?.length) return failed;
const order = result.data.me?.orders?.edges.find(({ node }) => node.id === input.orderId)?.node;
if (!order || order.channel.slug !== input.channel) return failed;

const items = reorderItems(order, input.channel).filter(
(item) => !input.selected || input.selected.includes(item.id),
);
const requested = items.reduce((sum, item) => sum + item.requested, 0);
if (!items.some((item) => item.available)) return { added: 0, skipped: requested, failed: false };

const cartId = await Checkout.getIdFromCookies(input.channel);
const cart = cartId
? await Checkout.find(cartId, input.locale)
: await Checkout.findOrCreate({ channel: input.channel, localeSlug: input.locale });
if (!cart) return failed;
let added = 0;
let skipped = requested;
let uncertain = false;
for (const [variantId, quantity] of planReorder(items, cart.lines)) {
const write = await mutate(BuyAgainAddDocument, {
variables: { id: cart.id, line: { variantId, quantity } },
});
if (!write.ok || !write.data.checkoutLinesAdd) {
uncertain = true;
break;
}
const { checkout, errors } = write.data.checkoutLinesAdd;
if (!errors.length && checkout) {
added += quantity;
skipped -= quantity;
} else if (
!errors.every(({ code }) =>
[
"INSUFFICIENT_STOCK",
"PRODUCT_UNAVAILABLE_FOR_PURCHASE",
"PRODUCT_NOT_PUBLISHED",
"UNAVAILABLE_VARIANT_IN_CHANNEL",
"QUANTITY_GREATER_THAN_LIMIT",
].includes(code),
)
) {
uncertain = true;
break;
}
}
if (added || uncertain) {
if (!cartId) await Checkout.saveIdToCookie(input.channel, cart.id);
refresh();
}
return { added, skipped, failed: uncertain };
}
2 changes: 1 addition & 1 deletion src/config/data-extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,5 @@ export const dataExtensions: {
} = {
profiles: {},
webhookScopes: {},
operations: {},
operations: { BuyAgainAdd: { access: "mutate", auth: "session" } },
};
1 change: 1 addition & 0 deletions src/graphql/CurrentUserOrdersPaginated.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ query CurrentUserOrdersPaginated($first: Int, $after: String, $languageCode: Lan
edges {
node {
...OrderDetails
...BuyAgainOrder
}
cursor
}
Expand Down
29 changes: 29 additions & 0 deletions src/graphql/extensions/BuyAgain.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
fragment BuyAgainOrder on Order {
channel {
slug
}
lines {
id
productName
variantName
quantity
variant {
id
quantityAvailable
product {
isAvailableForPurchase
}
}
}
}

mutation BuyAgainAdd($id: ID!, $line: CheckoutLineInput!) {
checkoutLinesAdd(id: $id, lines: [$line]) {
checkout {
id
}
errors {
code
}
}
}
Loading