diff --git a/data-layer.lock.md b/data-layer.lock.md
index 5cbd13c7c2..b793a57a14 100644
--- a/data-layer.lock.md
+++ b/data-layer.lock.md
@@ -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 |
diff --git a/messages/en.json b/messages/en.json
index 94a1cf3be7..06ab40398d 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -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})",
diff --git a/src/app/(storefront)/[locale]/[channel]/(main)/account/orders/page.tsx b/src/app/(storefront)/[locale]/[channel]/(main)/account/orders/page.tsx
index 29daa840d0..e6fc3d9888 100644
--- a/src/app/(storefront)/[locale]/[channel]/(main)/account/orders/page.tsx
+++ b/src/app/(storefront)/[locale]/[channel]/(main)/account/orders/page.tsx
@@ -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) {
@@ -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" });
@@ -63,20 +68,55 @@ async function AccountOrdersContent({ params, searchParams }: Props) {
) : (
<>
-
+ {requestedView && (
+
+ )}
+
{orders.map(({ node: order }) => (
-
+
+
+
+
))}
{pageInfo?.hasNextPage && pageInfo.endCursor && (
-
+
diff --git a/src/app/buy-again/actions.test.ts b/src/app/buy-again/actions.test.ts
new file mode 100644
index 0000000000..a29c83ca2e
--- /dev/null
+++ b/src/app/buy-again/actions.test.ts
@@ -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();
+});
diff --git a/src/app/buy-again/actions.ts b/src/app/buy-again/actions.ts
new file mode 100644
index 0000000000..8dd86a6d90
--- /dev/null
+++ b/src/app/buy-again/actions.ts
@@ -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 };
+}
diff --git a/src/config/data-extensions.ts b/src/config/data-extensions.ts
index 98b7f2f476..2c266bb911 100644
--- a/src/config/data-extensions.ts
+++ b/src/config/data-extensions.ts
@@ -36,5 +36,5 @@ export const dataExtensions: {
} = {
profiles: {},
webhookScopes: {},
- operations: {},
+ operations: { BuyAgainAdd: { access: "mutate", auth: "session" } },
};
diff --git a/src/graphql/CurrentUserOrdersPaginated.graphql b/src/graphql/CurrentUserOrdersPaginated.graphql
index 4194d56482..9090ef2ead 100644
--- a/src/graphql/CurrentUserOrdersPaginated.graphql
+++ b/src/graphql/CurrentUserOrdersPaginated.graphql
@@ -5,6 +5,7 @@ query CurrentUserOrdersPaginated($first: Int, $after: String, $languageCode: Lan
edges {
node {
...OrderDetails
+ ...BuyAgainOrder
}
cursor
}
diff --git a/src/graphql/extensions/BuyAgain.graphql b/src/graphql/extensions/BuyAgain.graphql
new file mode 100644
index 0000000000..81305ba795
--- /dev/null
+++ b/src/graphql/extensions/BuyAgain.graphql
@@ -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
+ }
+ }
+}
diff --git a/src/lib/custom/buy-again.test.ts b/src/lib/custom/buy-again.test.ts
new file mode 100644
index 0000000000..56d2213851
--- /dev/null
+++ b/src/lib/custom/buy-again.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+import { planReorder, reorderItems } from "./buy-again";
+
+const order = {
+ channel: { slug: "retail" },
+ lines: [
+ {
+ id: "1",
+ productName: "Tee",
+ variantName: "S",
+ quantity: 4,
+ variant: { id: "s", quantityAvailable: 3, product: { isAvailableForPurchase: true } },
+ },
+ { id: "2", productName: "Retired", variantName: "", quantity: 1, variant: null },
+ {
+ id: "3",
+ productName: "Hidden",
+ variantName: "",
+ quantity: 2,
+ variant: { id: "h", quantityAvailable: 8, product: { isAvailableForPurchase: false } },
+ },
+ {
+ id: "4",
+ productName: "Mug",
+ variantName: "",
+ quantity: 2,
+ variant: { id: "m", quantityAvailable: null, product: { isAvailableForPurchase: true } },
+ },
+ ],
+};
+describe("buy again", () => {
+ it("keeps the historical names and excludes deleted, unlisted, and excess units", () => {
+ expect(reorderItems(order, "retail").map(({ name, available }) => [name, available])).toEqual([
+ ["Tee", 3],
+ ["Retired", 0],
+ ["Hidden", 0],
+ ["Mug", 2],
+ ]);
+ });
+ it("does not reorder products into a different channel", () => {
+ expect([...planReorder(reorderItems(order, "outlet"), [])]).toEqual([]);
+ });
+ it("adds only remaining capacity across existing cart lines and duplicate past lines", () => {
+ const items = reorderItems(order, "retail");
+ expect([
+ ...planReorder(
+ [...items, items[0]],
+ [
+ { variant: { id: "s" }, quantity: 1 },
+ { variant: { id: "s" }, quantity: 1 },
+ ],
+ ),
+ ]).toEqual([
+ ["s", 1],
+ ["m", 2],
+ ]);
+ });
+ it("never substitutes a variant or adds units already at the stock limit", () => {
+ expect([
+ ...planReorder(reorderItems(order, "retail").slice(0, 3), [{ variant: { id: "s" }, quantity: 3 }]),
+ ]).toEqual([]);
+ });
+});
diff --git a/src/lib/custom/buy-again.ts b/src/lib/custom/buy-again.ts
new file mode 100644
index 0000000000..8daeba7d51
--- /dev/null
+++ b/src/lib/custom/buy-again.ts
@@ -0,0 +1,35 @@
+import { type BuyAgainOrderFragment } from "@/gql/graphql";
+
+export function reorderItems(order: BuyAgainOrderFragment, channel: string) {
+ return order.lines.map(({ id, productName, variantName, quantity, variant }) => ({
+ id,
+ name: productName,
+ option: variantName && variantName !== variant?.id ? variantName : "",
+ variantId: variant?.id ?? null,
+ requested: quantity,
+ available:
+ channel === order.channel.slug && variant?.product.isAvailableForPurchase
+ ? Math.min(quantity, variant.quantityAvailable ?? quantity)
+ : 0,
+ limit: variant?.quantityAvailable,
+ }));
+}
+
+export type ReorderItem = ReturnType
[number];
+
+export function planReorder(items: ReorderItem[], cart: { variant: { id: string }; quantity: number }[]) {
+ const quantities = new Map();
+ for (const { variant, quantity } of cart) {
+ quantities.set(variant.id, (quantities.get(variant.id) ?? 0) + quantity);
+ }
+ const additions = new Map();
+ for (const { variantId, available, limit } of items) {
+ if (!variantId || !available) continue;
+ const inCart = quantities.get(variantId) ?? 0;
+ const quantity = Math.min(available, Math.max(0, (limit ?? Infinity) - inCart));
+ if (!quantity) continue;
+ quantities.set(variantId, inCart + quantity);
+ additions.set(variantId, (additions.get(variantId) ?? 0) + quantity);
+ }
+ return additions;
+}
diff --git a/src/ui/components/account/buy-again.tsx b/src/ui/components/account/buy-again.tsx
new file mode 100644
index 0000000000..83b18a0610
--- /dev/null
+++ b/src/ui/components/account/buy-again.tsx
@@ -0,0 +1,158 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { Check, ListChecks, ReceiptText, RotateCcw, ShoppingBag } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { buyAgain } from "@/app/buy-again/actions";
+import { bumpChromeVersion } from "@/lib/chrome-sync";
+import { type ReorderItem } from "@/lib/custom/buy-again";
+import { useCart } from "@/ui/components/cart/cart-context";
+import { Button } from "@/ui/components/ui/button";
+
+export type ReorderView = "quick" | "receipt" | "choose";
+
+export function BuyAgain({
+ view,
+ items,
+ orderId,
+ locale,
+ channel,
+ after,
+}: {
+ view: ReorderView;
+ items: ReorderItem[];
+ orderId: string;
+ locale: string;
+ channel: string;
+ after?: string;
+}) {
+ const t = useTranslations("account.buyAgain");
+ const { openCart } = useCart();
+ const [excluded, setExcluded] = useState([]);
+ const [result, setResult] = useState> | null>(null);
+ const [pending, startTransition] = useTransition();
+ const choices = items.filter((item) => item.available > 0 && !excluded.includes(item.id));
+ const count = choices.reduce((sum, item) => sum + item.available, 0);
+ const all = items.reduce((sum, item) => sum + item.requested, 0);
+ const Icon = view === "choose" ? ListChecks : view === "receipt" ? ReceiptText : RotateCcw;
+ const submit = () =>
+ startTransition(async () => {
+ try {
+ const response = await buyAgain({
+ orderId,
+ locale,
+ channel,
+ after,
+ selected: view === "choose" ? choices.map((item) => item.id) : undefined,
+ });
+ setResult(response);
+ if (response.added || response.failed) bumpChromeVersion();
+ } catch {
+ setResult({ added: 0, skipped: 0, failed: true });
+ }
+ });
+ const addButton = (
+
+ );
+ return (
+
+ {view === "quick" ? (
+
+ {t("ready", { count, all })}
+ {addButton}
+
+ ) : (
+ <>
+
+
+ {t(view === "receipt" ? "receiptTitle" : "chooseTitle")}
+
+ {view === "choose" && {t("chooseHint")}
}
+
+
+ {t("prices")}
+ {addButton}
+
+ >
+ )}
+
+ {result && (
+
+
+ {result.added > 0 && t("addedCount", { count: result.added })}{" "}
+ {result.failed
+ ? t("failed")
+ : result.skipped > 0
+ ? t("skipped", { count: result.skipped })
+ : null}
+
+ {(result.added > 0 || result.failed) && (
+
+ )}
+
+ )}
+
+
+ );
+}
diff --git a/src/ui/components/account/order-row.tsx b/src/ui/components/account/order-row.tsx
index b1bc1588fb..653c016cde 100644
--- a/src/ui/components/account/order-row.tsx
+++ b/src/ui/components/account/order-row.tsx
@@ -12,9 +12,10 @@ type Props = {
order: OrderDetailsFragment;
localeSlug: string;
labels: OrderRowLabels;
+ grouped?: boolean;
};
-export function OrderRow({ order, localeSlug, labels }: Props) {
+export function OrderRow({ order, localeSlug, labels, grouped }: Props) {
const intlLocale = resolveLocaleFromSlug(localeSlug).bcp47;
const thumbnails = order.lines
@@ -28,13 +29,13 @@ export function OrderRow({ order, localeSlug, labels }: Props) {
return (
{thumbnails.map((thumb, i) => (