@springmicro/cart 0.5.1 → 0.5.2

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.
@@ -1,165 +1,165 @@
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
- import { FormikConfig } from "formik";
10
-
11
- export default function Checkout({
12
- apiBaseUrl,
13
- taxProvider,
14
- emptyCartLink = "",
15
- disableProductLink = false,
16
- disableMissingImage = false,
17
- CollectExtraInfo,
18
- }: {
19
- apiBaseUrl: string;
20
- taxProvider: string;
21
- emptyCartLink?: string;
22
- disableProductLink?: boolean;
23
- disableMissingImage?: boolean;
24
- CollectExtraInfo?: React.FC<{ formik: FormikConfig<any> }>;
25
- }) {
26
- const cart = JSON.parse(useStore(cartStore));
27
-
28
- const [prices, setPrices] = useState({});
29
- const [subtotal, setSubtotal] = useState("Loading prices...");
30
- const taxState = useState({ tax_amount: "TBD" });
31
- const shipping = 0;
32
- const discount = 0;
33
-
34
- const [status, setStatus] = useState(0);
35
- const [order, setOrder] = useState(undefined);
36
- const [successData, setSuccessData] = useState(null);
37
-
38
- useEffect(() => {
39
- const params = new URLSearchParams(window.location.search);
40
-
41
- const sr = params.get("showReceipt");
42
- const oid = params.get("orderId");
43
- const or = params.get("orderRef");
44
- if (oid && or) {
45
- fetch(`${apiBaseUrl}/api/ecommerce/orders/${oid}/reference/${or}`).then(
46
- async (res) =>
47
- await res.json().then((order) => {
48
- setOrder(order);
49
- setStatus(
50
- order.charge_id ||
51
- !["pending", "awaiting_payment"].includes(order.status)
52
- ? 2
53
- : 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.
54
- );
55
- })
56
- );
57
- }
58
- }, []);
59
-
60
- // build pricing list
61
- useEffect(() => {
62
- // filter out prices that have already been queried
63
- const pricesToGet = cart.items
64
- .map((c) => c.price_id)
65
- .filter(
66
- (pId) => Object.keys(prices).findIndex((pKey) => pKey == pId) === -1
67
- );
68
- if (pricesToGet.length === 0) return;
69
-
70
- const url = `${apiBaseUrl}/api/ecommerce/price?filter={'ids':[${pricesToGet.join(
71
- ","
72
- )}]}`;
73
- fetch(url, {
74
- method: "GET",
75
- headers: {
76
- "Content-Type": "application/json",
77
- },
78
- })
79
- .then((res) =>
80
- res.json().then((data) => {
81
- const pricingData = { ...prices };
82
-
83
- data.forEach((p) => {
84
- pricingData[p.id] = p;
85
- });
86
- setPrices(pricingData);
87
- })
88
- )
89
- .catch(() => {});
90
- }, [cart]);
91
-
92
- useEffect(() => {
93
- setSubtotal(
94
- cart.items
95
- .map((product) => prices[product.price_id]?.unit_amount)
96
- .reduce((p, c) => (c ? p + c : p), 0)
97
- );
98
- }, [cart, prices]);
99
-
100
- if (status === 0 && cart.items.length === 0)
101
- return (
102
- <div
103
- style={{
104
- width: "100%",
105
- display: "flex",
106
- alignItems: "center",
107
- flexDirection: "column",
108
- gap: 8,
109
- }}
110
- >
111
- <Typography style={{ fontSize: 32, fontWeight: 600 }}>
112
- Cart is empty
113
- </Typography>
114
- <a className="shopping-button" href={`/${emptyCartLink}`}>
115
- <Typography>BACK</Typography>
116
- </a>
117
- </div>
118
- );
119
-
120
- return (
121
- <div>
122
- <StatusBar status={status} />
123
- <div>
124
- {/**
125
- *
126
- * status === 0
127
- * Manage cart and enter in payment details
128
- *
129
- * status === 1
130
- * Review taxes and shipping
131
- *
132
- * status === 2
133
- * Order has been place. Invoice for printing.
134
- *
135
- */}
136
-
137
- {status != 2 && (
138
- <ReviewAndCalculateTaxes
139
- subtotal={subtotal}
140
- discount={discount}
141
- shipping={shipping}
142
- taxProvider={taxProvider}
143
- taxState={taxState}
144
- statusState={[status, setStatus]}
145
- cart={cart}
146
- prices={prices}
147
- apiBaseUrl={apiBaseUrl}
148
- orderState={[order, setOrder]}
149
- disableProductLink={disableProductLink}
150
- disableMissingImage={disableMissingImage}
151
- setSuccessData={setSuccessData}
152
- onPlacement={() => {
153
- clearCart();
154
- setStatus(2);
155
- }}
156
- CollectExtraInfo={CollectExtraInfo}
157
- />
158
- )}
159
- {status === 2 && order !== undefined && (
160
- <Invoice order={order} successData={successData} />
161
- )}
162
- </div>
163
- </div>
164
- );
165
- }
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
+ import { FormikConfig } from "formik";
10
+
11
+ export default function Checkout({
12
+ apiBaseUrl,
13
+ taxProvider,
14
+ emptyCartLink = "",
15
+ disableProductLink = false,
16
+ disableMissingImage = false,
17
+ CollectExtraInfo,
18
+ }: {
19
+ apiBaseUrl: string;
20
+ taxProvider: string;
21
+ emptyCartLink?: string;
22
+ disableProductLink?: boolean;
23
+ disableMissingImage?: boolean;
24
+ CollectExtraInfo?: React.FC<{ formik: FormikConfig<any> }>;
25
+ }) {
26
+ const cart = JSON.parse(useStore(cartStore));
27
+
28
+ const [prices, setPrices] = useState({});
29
+ const [subtotal, setSubtotal] = useState("Loading prices...");
30
+ const taxState = useState({ tax_amount: "TBD" });
31
+ const shipping = 0;
32
+ const discount = 0;
33
+
34
+ const [status, setStatus] = useState(0);
35
+ const [order, setOrder] = useState(undefined);
36
+ const [successData, setSuccessData] = useState(null);
37
+
38
+ useEffect(() => {
39
+ const params = new URLSearchParams(window.location.search);
40
+
41
+ const sr = params.get("showReceipt");
42
+ const oid = params.get("orderId");
43
+ const or = params.get("orderRef");
44
+ if (oid && or) {
45
+ fetch(`${apiBaseUrl}/api/ecommerce/orders/${oid}/reference/${or}`).then(
46
+ async (res) =>
47
+ await res.json().then((order) => {
48
+ setOrder(order);
49
+ setStatus(
50
+ order.charge_id ||
51
+ !["pending", "awaiting_payment"].includes(order.status)
52
+ ? 2
53
+ : 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.
54
+ );
55
+ })
56
+ );
57
+ }
58
+ }, []);
59
+
60
+ // build pricing list
61
+ useEffect(() => {
62
+ // filter out prices that have already been queried
63
+ const pricesToGet = cart.items
64
+ .map((c) => c.price_id)
65
+ .filter(
66
+ (pId) => Object.keys(prices).findIndex((pKey) => pKey == pId) === -1
67
+ );
68
+ if (pricesToGet.length === 0) return;
69
+
70
+ const url = `${apiBaseUrl}/api/ecommerce/price?filter={'ids':[${pricesToGet.join(
71
+ ","
72
+ )}]}`;
73
+ fetch(url, {
74
+ method: "GET",
75
+ headers: {
76
+ "Content-Type": "application/json",
77
+ },
78
+ })
79
+ .then((res) =>
80
+ res.json().then((data) => {
81
+ const pricingData = { ...prices };
82
+
83
+ data.forEach((p) => {
84
+ pricingData[p.id] = p;
85
+ });
86
+ setPrices(pricingData);
87
+ })
88
+ )
89
+ .catch(() => {});
90
+ }, [cart]);
91
+
92
+ useEffect(() => {
93
+ setSubtotal(
94
+ cart.items
95
+ .map((product) => prices[product.price_id]?.unit_amount)
96
+ .reduce((p, c) => (c ? p + c : p), 0)
97
+ );
98
+ }, [cart, prices]);
99
+
100
+ if (status === 0 && cart.items.length === 0)
101
+ return (
102
+ <div
103
+ style={{
104
+ width: "100%",
105
+ display: "flex",
106
+ alignItems: "center",
107
+ flexDirection: "column",
108
+ gap: 8,
109
+ }}
110
+ >
111
+ <Typography style={{ fontSize: 32, fontWeight: 600 }}>
112
+ Cart is empty
113
+ </Typography>
114
+ <a className="shopping-button" href={`/${emptyCartLink}`}>
115
+ <Typography>BACK</Typography>
116
+ </a>
117
+ </div>
118
+ );
119
+
120
+ return (
121
+ <div>
122
+ <StatusBar status={status} />
123
+ <div>
124
+ {/**
125
+ *
126
+ * status === 0
127
+ * Manage cart and enter in payment details
128
+ *
129
+ * status === 1
130
+ * Review taxes and shipping
131
+ *
132
+ * status === 2
133
+ * Order has been place. Invoice for printing.
134
+ *
135
+ */}
136
+
137
+ {status != 2 && (
138
+ <ReviewAndCalculateTaxes
139
+ subtotal={subtotal}
140
+ discount={discount}
141
+ shipping={shipping}
142
+ taxProvider={taxProvider}
143
+ taxState={taxState}
144
+ statusState={[status, setStatus]}
145
+ cart={cart}
146
+ prices={prices}
147
+ apiBaseUrl={apiBaseUrl}
148
+ orderState={[order, setOrder]}
149
+ disableProductLink={disableProductLink}
150
+ disableMissingImage={disableMissingImage}
151
+ setSuccessData={setSuccessData}
152
+ onPlacement={() => {
153
+ clearCart();
154
+ setStatus(2);
155
+ }}
156
+ CollectExtraInfo={CollectExtraInfo}
157
+ />
158
+ )}
159
+ {status === 2 && order !== undefined && (
160
+ <Invoice order={order} successData={successData} />
161
+ )}
162
+ </div>
163
+ </div>
164
+ );
165
+ }
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,36 +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/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
- };
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
+ }