@springmicro/cart 0.3.2 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.eslintrc.cjs +21 -21
  2. package/README.md +64 -64
  3. package/dist/index.js +9778 -9696
  4. package/dist/index.umd.cjs +66 -92
  5. package/package.json +5 -3
  6. package/src/AddToCartForm.tsx +16 -16
  7. package/src/CartButton.tsx +249 -249
  8. package/src/ProductCard.css +106 -106
  9. package/src/ProductCard.tsx +165 -165
  10. package/src/checkout/{CheckoutList.css → ReviewCartAndCalculateTaxes.css} +93 -93
  11. package/src/checkout/ReviewCartAndCalculateTaxes.tsx +366 -0
  12. package/src/checkout/components/AddCard.tsx +267 -0
  13. package/src/checkout/components/Address.tsx +261 -265
  14. package/src/checkout/components/CartList.tsx +151 -0
  15. package/src/checkout/components/CartProductCard.css +67 -67
  16. package/src/checkout/components/CartProductCard.tsx +90 -80
  17. package/src/checkout/components/Invoice.tsx +145 -0
  18. package/src/checkout/components/ProviderLogos.tsx +93 -93
  19. package/src/checkout/components/StatusBar.tsx +32 -0
  20. package/src/checkout/index.tsx +161 -0
  21. package/src/index.css +5 -5
  22. package/src/index.ts +36 -35
  23. package/src/types.d.ts +56 -56
  24. package/src/utils/api.ts +67 -67
  25. package/src/utils/cartAuthHandler.ts +50 -50
  26. package/src/utils/index.ts +28 -28
  27. package/src/utils/storage.ts +133 -133
  28. package/tsconfig.json +24 -24
  29. package/tsconfig.node.json +11 -11
  30. package/vite.config.ts +25 -25
  31. package/springmicro-cart-0.2.3.tgz +0 -0
  32. package/src/checkout/CheckoutList.tsx +0 -264
  33. package/src/checkout/components/Billing.tsx +0 -353
  34. package/src/checkout/components/Order.tsx +0 -93
  35. package/src/checkout/components/index.tsx +0 -104
@@ -0,0 +1,161 @@
1
+ import "./ReviewCartAndCalculateTaxes.css";
2
+ import { useStore } from "@nanostores/react";
3
+ import { useEffect, useState } from "react";
4
+ import { Typography } from "@mui/material";
5
+ import { cartStore, clearCart } from "../utils/storage";
6
+ import { StatusBar } from "./components/StatusBar";
7
+ import ReviewAndCalculateTaxes from "./ReviewCartAndCalculateTaxes";
8
+ import Invoice from "./components/Invoice";
9
+
10
+ export default function Checkout({
11
+ apiBaseUrl,
12
+ taxProvider,
13
+ emptyCartLink = "",
14
+ disableProductLink = false,
15
+ disableMissingImage = false,
16
+ }: {
17
+ apiBaseUrl: string;
18
+ taxProvider: string;
19
+ emptyCartLink?: string;
20
+ disableProductLink?: boolean;
21
+ disableMissingImage?: boolean;
22
+ }) {
23
+ const cart = JSON.parse(useStore(cartStore));
24
+
25
+ const [prices, setPrices] = useState({});
26
+ const [subtotal, setSubtotal] = useState("Loading prices...");
27
+ const taxState = useState({ tax_amount: "TBD" });
28
+ const shipping = 0;
29
+ const discount = 0;
30
+
31
+ const [status, setStatus] = useState(0);
32
+ const [order, setOrder] = useState(undefined);
33
+ const [successData, setSuccessData] = useState(null);
34
+
35
+ useEffect(() => {
36
+ const params = new URLSearchParams(window.location.search);
37
+
38
+ const sr = params.get("showReceipt");
39
+ const oid = params.get("orderId");
40
+ const or = params.get("orderRef");
41
+ if (oid && or) {
42
+ fetch(`${apiBaseUrl}/api/ecommerce/orders/${oid}/reference/${or}`).then(
43
+ async (res) =>
44
+ await res.json().then((order) => {
45
+ setOrder(order);
46
+ setStatus(
47
+ order.charge_id ||
48
+ !["pending", "awaiting_payment"].includes(order.status)
49
+ ? 2
50
+ : 0 // normally this should be set to 1 but we need to ensure it sends card data to the payment provider and that data is likely lost on refresh.
51
+ );
52
+ })
53
+ );
54
+ }
55
+ }, []);
56
+
57
+ // build pricing list
58
+ useEffect(() => {
59
+ // filter out prices that have already been queried
60
+ const pricesToGet = cart.items
61
+ .map((c) => c.price_id)
62
+ .filter(
63
+ (pId) => Object.keys(prices).findIndex((pKey) => pKey == pId) === -1
64
+ );
65
+ if (pricesToGet.length === 0) return;
66
+
67
+ const url = `${apiBaseUrl}/api/ecommerce/price?filter={'ids':[${pricesToGet.join(
68
+ ","
69
+ )}]}`;
70
+ fetch(url, {
71
+ method: "GET",
72
+ headers: {
73
+ "Content-Type": "application/json",
74
+ },
75
+ })
76
+ .then((res) =>
77
+ res.json().then((data) => {
78
+ const pricingData = { ...prices };
79
+
80
+ data.forEach((p) => {
81
+ pricingData[p.id] = p;
82
+ });
83
+ setPrices(pricingData);
84
+ })
85
+ )
86
+ .catch(() => {});
87
+ }, [cart]);
88
+
89
+ useEffect(() => {
90
+ setSubtotal(
91
+ cart.items
92
+ .map((product) => prices[product.price_id]?.unit_amount)
93
+ .reduce((p, c) => (c ? p + c : p), 0)
94
+ );
95
+ }, [cart, prices]);
96
+
97
+ if (status === 0 && cart.items.length === 0)
98
+ return (
99
+ <div
100
+ style={{
101
+ width: "100%",
102
+ display: "flex",
103
+ alignItems: "center",
104
+ flexDirection: "column",
105
+ gap: 8,
106
+ }}
107
+ >
108
+ <Typography style={{ fontSize: 32, fontWeight: 600 }}>
109
+ Cart is empty
110
+ </Typography>
111
+ <a className="shopping-button" href={`/${emptyCartLink}`}>
112
+ <Typography>BACK</Typography>
113
+ </a>
114
+ </div>
115
+ );
116
+
117
+ return (
118
+ <div>
119
+ <StatusBar status={status} />
120
+ <div>
121
+ {/**
122
+ *
123
+ * status === 0
124
+ * Manage cart and enter in payment details
125
+ *
126
+ * status === 1
127
+ * Review taxes and shipping
128
+ *
129
+ * status === 2
130
+ * Order has been place. Invoice for printing.
131
+ *
132
+ */}
133
+
134
+ {status != 2 && (
135
+ <ReviewAndCalculateTaxes
136
+ subtotal={subtotal}
137
+ discount={discount}
138
+ shipping={shipping}
139
+ taxProvider={taxProvider}
140
+ taxState={taxState}
141
+ statusState={[status, setStatus]}
142
+ cart={cart}
143
+ prices={prices}
144
+ apiBaseUrl={apiBaseUrl}
145
+ orderState={[order, setOrder]}
146
+ disableProductLink={disableProductLink}
147
+ disableMissingImage={disableMissingImage}
148
+ setSuccessData={setSuccessData}
149
+ onPlacement={() => {
150
+ clearCart();
151
+ setStatus(2);
152
+ }}
153
+ />
154
+ )}
155
+ {status === 2 && order !== undefined && (
156
+ <Invoice order={order} successData={successData} />
157
+ )}
158
+ </div>
159
+ </div>
160
+ );
161
+ }
package/src/index.css CHANGED
@@ -1,5 +1,5 @@
1
- @media print {
2
- #paymentMethodForm {
3
- display: none !important;
4
- }
5
- }
1
+ @media print {
2
+ #paymentMethodForm {
3
+ display: none !important;
4
+ }
5
+ }
package/src/index.ts CHANGED
@@ -1,35 +1,36 @@
1
- import CartButton from "./CartButton";
2
- import {
3
- cartStore,
4
- addToCart,
5
- removeFromCart,
6
- clearCart,
7
- setOrder,
8
- } from "./utils/storage";
9
- import type { Cart, CartProduct } from "./types";
10
- import AddToCartForm from "./AddToCartForm";
11
- import { AddCard, AddCardProps } from "./checkout/components/Billing";
12
- import Order from "./checkout/components/Order";
13
- import Checkout from "./checkout/components";
14
- import "react-credit-cards-2/dist/es/styles-compiled.css";
15
- import "./index.css";
16
- import ProductCard from "./ProductCard";
17
- import CheckoutList from "./checkout/CheckoutList";
18
-
19
- export {
20
- Checkout,
21
- Order,
22
- AddCard,
23
- type AddCardProps,
24
- cartStore,
25
- CartButton,
26
- type Cart,
27
- type CartProduct,
28
- addToCart,
29
- removeFromCart,
30
- clearCart,
31
- AddToCartForm,
32
- setOrder,
33
- ProductCard,
34
- CheckoutList,
35
- };
1
+ import CartButton from "./CartButton";
2
+ import {
3
+ cartStore,
4
+ addToCart,
5
+ removeFromCart,
6
+ clearCart,
7
+ setOrder,
8
+ } from "./utils/storage";
9
+ import type { Cart, CartProduct } from "./types";
10
+ import AddToCartForm from "./AddToCartForm";
11
+ import { AddCard, AddCardProps } from "./checkout/components/AddCard";
12
+ // import Order from "./checkout/components/Order";
13
+ import Invoice from "./checkout/components/Invoice";
14
+ import "react-credit-cards-2/dist/es/styles-compiled.css";
15
+ import "./index.css";
16
+ import ProductCard from "./ProductCard";
17
+ import ReviewCartAndCalculateTaxes from "./checkout/ReviewCartAndCalculateTaxes";
18
+ import Checkout from "./checkout";
19
+
20
+ export {
21
+ Checkout,
22
+ Invoice,
23
+ AddCard,
24
+ type AddCardProps,
25
+ cartStore,
26
+ CartButton,
27
+ type Cart,
28
+ type CartProduct,
29
+ addToCart,
30
+ removeFromCart,
31
+ clearCart,
32
+ AddToCartForm,
33
+ setOrder,
34
+ ProductCard,
35
+ ReviewCartAndCalculateTaxes,
36
+ };
package/src/types.d.ts CHANGED
@@ -1,56 +1,56 @@
1
- export interface Cart {
2
- authentication: {
3
- loggedIn: boolean;
4
- user_id?: number | string;
5
- };
6
- items: CartProduct[];
7
- order?: {
8
- id: number;
9
- reference: string;
10
- };
11
- }
12
- export type CartProduct = {
13
- product_id: number | string;
14
- price_id: number | string;
15
- quantity?: number;
16
- // Used in local cart, delete when sent to api
17
- name: string;
18
- image?: string;
19
- };
20
-
21
- type CartContextType = {
22
- cart: Cart;
23
- addToCart: (p: CartProduct) => void;
24
- removeFromCart: (i: number) => void;
25
- clearCart: () => void;
26
- };
27
-
28
- type ApiCartResponse = {
29
- cart: string;
30
- id: any;
31
- user_id: number | string;
32
- };
33
-
34
- export type PathDetailsType = {
35
- baseUrl?: string;
36
- userId?: string | number;
37
- };
38
-
39
- export type Product = {
40
- id: string | number;
41
- name: string;
42
- /** v Parses to @type {ProductPricing} v */
43
- pricing: string;
44
- description?: string;
45
- } & unknown;
46
-
47
- export type ProductPricing = {
48
- id: number | string;
49
- unit_amount: number; // in cents
50
- recurring?: {
51
- interval: "month" | "week" | "day";
52
- interval_count: number;
53
- };
54
- tier_label?: string;
55
- tier_description?: string;
56
- };
1
+ export interface Cart {
2
+ authentication: {
3
+ loggedIn: boolean;
4
+ user_id?: number | string;
5
+ };
6
+ items: CartProduct[];
7
+ order?: {
8
+ id: number;
9
+ reference: string;
10
+ };
11
+ }
12
+ export type CartProduct = {
13
+ product_id: number | string;
14
+ price_id: number | string;
15
+ quantity?: number;
16
+ // Used in local cart, delete when sent to api
17
+ name: string;
18
+ image?: string;
19
+ };
20
+
21
+ type CartContextType = {
22
+ cart: Cart;
23
+ addToCart: (p: CartProduct) => void;
24
+ removeFromCart: (i: number) => void;
25
+ clearCart: () => void;
26
+ };
27
+
28
+ type ApiCartResponse = {
29
+ cart: string;
30
+ id: any;
31
+ user_id: number | string;
32
+ };
33
+
34
+ export type PathDetailsType = {
35
+ baseUrl?: string;
36
+ userId?: string | number;
37
+ };
38
+
39
+ export type Product = {
40
+ id: string | number;
41
+ name: string;
42
+ /** v Parses to @type {ProductPricing} v */
43
+ pricing: string;
44
+ description?: string;
45
+ } & unknown;
46
+
47
+ export type ProductPricing = {
48
+ id: number | string;
49
+ unit_amount: number; // in cents
50
+ recurring?: {
51
+ interval: "month" | "week" | "day";
52
+ interval_count: number;
53
+ };
54
+ tier_label?: string;
55
+ tier_description?: string;
56
+ };
package/src/utils/api.ts CHANGED
@@ -1,67 +1,67 @@
1
- function postInit(body: any): RequestInit {
2
- const init: RequestInit = {
3
- method: "POST",
4
- headers: { "Content-Type": "application/json" },
5
- };
6
- if (typeof body === "string") {
7
- return { ...init, body };
8
- }
9
- return { ...init, body: JSON.stringify(body) };
10
- }
11
-
12
- async function dataOrResponse(res: Response) {
13
- if (res.status === 200) {
14
- return await res.json();
15
- } else {
16
- return res;
17
- }
18
- }
19
-
20
- async function dataOr404(res: Response) {
21
- if (res.status === 200) {
22
- return await res.json();
23
- } else {
24
- return new Response(null, { status: 404 });
25
- }
26
- }
27
-
28
- export async function getOrder(
29
- apiBaseUrl: string,
30
- id: string,
31
- orderReference: string
32
- ) {
33
- const res = await fetch(
34
- `${apiBaseUrl}/api/ecommerce/orders/${id}/reference/${orderReference}`
35
- );
36
- return await dataOr404(res);
37
- }
38
-
39
- export async function getInvoice(
40
- apiBaseUrl: string,
41
- id: string,
42
- orderReference: string
43
- ) {
44
- const res = await fetch(
45
- `${apiBaseUrl}/api/ecommerce/invoice/${id}/reference/${orderReference}`
46
- );
47
- return await dataOr404(res);
48
- }
49
-
50
- export async function postCheckout(
51
- apiBaseUrl: string,
52
- id: string,
53
- orderReference: string,
54
- body: object,
55
- paymentProvider: string,
56
- invoiceId?: string
57
- ): Promise<object | Response> {
58
- const url = new URL(
59
- `${apiBaseUrl}/api/ecommerce/checkout/${id}/${orderReference}`
60
- );
61
- url.searchParams.set("payment_provider", paymentProvider);
62
- if (invoiceId !== undefined) {
63
- url.searchParams.set("invoice_id", invoiceId);
64
- }
65
- const res = await fetch(url, postInit(body));
66
- return await dataOrResponse(res);
67
- }
1
+ function postInit(body: any): RequestInit {
2
+ const init: RequestInit = {
3
+ method: "POST",
4
+ headers: { "Content-Type": "application/json" },
5
+ };
6
+ if (typeof body === "string") {
7
+ return { ...init, body };
8
+ }
9
+ return { ...init, body: JSON.stringify(body) };
10
+ }
11
+
12
+ async function dataOrResponse(res: Response) {
13
+ if (res.status === 200) {
14
+ return await res.json();
15
+ } else {
16
+ return res;
17
+ }
18
+ }
19
+
20
+ async function dataOr404(res: Response) {
21
+ if (res.status === 200) {
22
+ return await res.json();
23
+ } else {
24
+ return new Response(null, { status: 404 });
25
+ }
26
+ }
27
+
28
+ export async function getOrder(
29
+ apiBaseUrl: string,
30
+ id: string,
31
+ orderReference: string
32
+ ) {
33
+ const res = await fetch(
34
+ `${apiBaseUrl}/api/ecommerce/orders/${id}/reference/${orderReference}`
35
+ );
36
+ return await dataOr404(res);
37
+ }
38
+
39
+ export async function getInvoice(
40
+ apiBaseUrl: string,
41
+ id: string,
42
+ orderReference: string
43
+ ) {
44
+ const res = await fetch(
45
+ `${apiBaseUrl}/api/ecommerce/invoice/${id}/reference/${orderReference}`
46
+ );
47
+ return await dataOr404(res);
48
+ }
49
+
50
+ export async function postCheckout(
51
+ apiBaseUrl: string,
52
+ id: string,
53
+ orderReference: string,
54
+ body: object,
55
+ paymentProvider: string,
56
+ invoiceId?: string
57
+ ): Promise<object | Response> {
58
+ const url = new URL(
59
+ `${apiBaseUrl}/api/ecommerce/checkout/${id}/${orderReference}`
60
+ );
61
+ url.searchParams.set("payment_provider", paymentProvider);
62
+ if (invoiceId !== undefined) {
63
+ url.searchParams.set("invoice_id", invoiceId);
64
+ }
65
+ const res = await fetch(url, postInit(body));
66
+ return await dataOrResponse(res);
67
+ }
@@ -1,50 +1,50 @@
1
- import { defaultCartValue } from ".";
2
- import { ApiCartResponse, Cart } from "../types";
3
- import { Storage } from "unstorage";
4
-
5
- export function cartAuthHandler(
6
- cartState: [Cart, React.Dispatch<React.SetStateAction<Cart>>],
7
- storage: {
8
- api: Storage<any>;
9
- local: Storage<any>;
10
- } | null,
11
- userId: number | string | undefined,
12
- prevUserId: number | string | undefined
13
- ) {
14
- const [cart, setCart] = cartState;
15
- if (storage === null) return () => {}; // storage can be null.
16
-
17
- if (userId === prevUserId) return;
18
-
19
- if (userId === undefined) {
20
- // logout
21
- setCart(defaultCartValue);
22
- return;
23
- }
24
-
25
- // login
26
- if (cart.items.length > 0) {
27
- setCart((c) => ({
28
- ...c,
29
- authentication: {
30
- loggedIn: true,
31
- user_id: userId,
32
- },
33
- }));
34
- return;
35
- }
36
- storage.api
37
- .getItem(`${userId}`)
38
- .then((c2: ApiCartResponse) => {
39
- if (!c2) return;
40
-
41
- setCart({
42
- items: JSON.parse(c2.cart),
43
- authentication: {
44
- loggedIn: true,
45
- user_id: c2.user_id,
46
- },
47
- });
48
- })
49
- .catch(() => {});
50
- }
1
+ import { defaultCartValue } from ".";
2
+ import { ApiCartResponse, Cart } from "../types";
3
+ import { Storage } from "unstorage";
4
+
5
+ export function cartAuthHandler(
6
+ cartState: [Cart, React.Dispatch<React.SetStateAction<Cart>>],
7
+ storage: {
8
+ api: Storage<any>;
9
+ local: Storage<any>;
10
+ } | null,
11
+ userId: number | string | undefined,
12
+ prevUserId: number | string | undefined
13
+ ) {
14
+ const [cart, setCart] = cartState;
15
+ if (storage === null) return () => {}; // storage can be null.
16
+
17
+ if (userId === prevUserId) return;
18
+
19
+ if (userId === undefined) {
20
+ // logout
21
+ setCart(defaultCartValue);
22
+ return;
23
+ }
24
+
25
+ // login
26
+ if (cart.items.length > 0) {
27
+ setCart((c) => ({
28
+ ...c,
29
+ authentication: {
30
+ loggedIn: true,
31
+ user_id: userId,
32
+ },
33
+ }));
34
+ return;
35
+ }
36
+ storage.api
37
+ .getItem(`${userId}`)
38
+ .then((c2: ApiCartResponse) => {
39
+ if (!c2) return;
40
+
41
+ setCart({
42
+ items: JSON.parse(c2.cart),
43
+ authentication: {
44
+ loggedIn: true,
45
+ user_id: c2.user_id,
46
+ },
47
+ });
48
+ })
49
+ .catch(() => {});
50
+ }
@@ -1,28 +1,28 @@
1
- import { Cart, PathDetailsType } from "../types";
2
-
3
- export const defaultCartValue: Cart = {
4
- authentication: {
5
- loggedIn: false,
6
- },
7
- items: [],
8
- };
9
-
10
- export function fetchFromCartApi(
11
- method: "GET" | "PUT" | "DELETE",
12
- { baseUrl, userId }: PathDetailsType,
13
- body?: string
14
- ) {
15
- return fetch(`${baseUrl}/api/ecommerce/cart/${userId}`, {
16
- method,
17
- body,
18
- headers: {
19
- "Content-Type": "application/json",
20
- },
21
- });
22
- }
23
-
24
- export function pathDetailsIsFullyDefined(pathDetails: PathDetailsType) {
25
- if (pathDetails.userId === undefined) return false;
26
- if (pathDetails.baseUrl === undefined) return false;
27
- return true;
28
- }
1
+ import { Cart, PathDetailsType } from "../types";
2
+
3
+ export const defaultCartValue: Cart = {
4
+ authentication: {
5
+ loggedIn: false,
6
+ },
7
+ items: [],
8
+ };
9
+
10
+ export function fetchFromCartApi(
11
+ method: "GET" | "PUT" | "DELETE",
12
+ { baseUrl, userId }: PathDetailsType,
13
+ body?: string
14
+ ) {
15
+ return fetch(`${baseUrl}/api/ecommerce/cart/${userId}`, {
16
+ method,
17
+ body,
18
+ headers: {
19
+ "Content-Type": "application/json",
20
+ },
21
+ });
22
+ }
23
+
24
+ export function pathDetailsIsFullyDefined(pathDetails: PathDetailsType) {
25
+ if (pathDetails.userId === undefined) return false;
26
+ if (pathDetails.baseUrl === undefined) return false;
27
+ return true;
28
+ }