60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
import { BUSINESS_ORIGIN, CUSTOMER_ORIGIN } from "./site";
|
|
|
|
export const GUEST_CART_URL_PARAM = "guestCart";
|
|
|
|
export type GuestCartLine = {
|
|
id: string;
|
|
name: string;
|
|
slug?: string;
|
|
price: number;
|
|
quantity: number;
|
|
image?: string | null;
|
|
};
|
|
|
|
export function encodeGuestCartForUrl(items: GuestCartLine[]): string {
|
|
const payload = items.map(({ id, name, slug, price, quantity, image }) => ({
|
|
id,
|
|
name,
|
|
...(slug ? { slug } : {}),
|
|
price,
|
|
quantity,
|
|
image: image ?? null,
|
|
}));
|
|
const json = JSON.stringify(payload);
|
|
return btoa(unescape(encodeURIComponent(json)))
|
|
.replace(/\+/g, "-")
|
|
.replace(/\//g, "_")
|
|
.replace(/=+$/, "");
|
|
}
|
|
|
|
export function customerDashboardUrl(path = "/"): string {
|
|
const normalized = path.startsWith("/") ? path : `/${path}`;
|
|
return `${CUSTOMER_ORIGIN}${normalized}`;
|
|
}
|
|
|
|
export function businessDashboardUrl(): string {
|
|
return `${BUSINESS_ORIGIN}/`;
|
|
}
|
|
|
|
export function customerLoginUrl(redirectPath = "/", cartItems?: GuestCartLine[]): string {
|
|
let redirect = redirectPath.startsWith("/") ? redirectPath : `/${redirectPath}`;
|
|
if (cartItems && cartItems.length > 0) {
|
|
const join = redirect.includes("#") ? "&" : "#";
|
|
redirect = `${redirect}${join}${GUEST_CART_URL_PARAM}=${encodeGuestCartForUrl(cartItems)}`;
|
|
}
|
|
const url = new URL("/login", CUSTOMER_ORIGIN);
|
|
url.searchParams.set("redirect", redirect);
|
|
return url.toString();
|
|
}
|
|
|
|
export function customerContinueCheckoutUrl(isAuthenticated: boolean, cartItems: GuestCartLine[] = []): string {
|
|
if (isAuthenticated) {
|
|
const url = new URL("/checkout/cart", CUSTOMER_ORIGIN);
|
|
if (cartItems.length > 0) {
|
|
url.hash = `${GUEST_CART_URL_PARAM}=${encodeGuestCartForUrl(cartItems)}`;
|
|
}
|
|
return url.toString();
|
|
}
|
|
return customerLoginUrl("/checkout/cart", cartItems);
|
|
}
|