@springmicro/cart 0.3.0 → 0.3.4

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,264 +1,272 @@
1
- import "./CheckoutList.css";
2
- import { useStore } from "@nanostores/react";
3
- import { CartProductCard } from "./components/CartProductCard";
4
- import React from "react";
5
- import { Button, Tooltip, Typography } from "@mui/material";
6
- import {
7
- cartStore,
8
- clearCart,
9
- setOrder as cartSetOrder,
10
- } from "../utils/storage";
11
- import Checkout from "./components";
12
-
13
- export default function CheckoutList({
14
- apiBaseUrl,
15
- emptyCartLink = "",
16
- disableProductLink = false,
17
- }: {
18
- apiBaseUrl: string;
19
- emptyCartLink?: string;
20
- disableProductLink?: boolean;
21
- }) {
22
- const cart = JSON.parse(useStore(cartStore));
23
-
24
- const [prices, setPrices] = React.useState({});
25
- const [total, setTotal] = React.useState("Loading prices...");
26
-
27
- const [status, setStatus] = React.useState(0);
28
- const [order, setOrder] = React.useState(undefined);
29
-
30
- React.useEffect(() => {
31
- const params = new URLSearchParams(window.location.search);
32
-
33
- const sr = params.get("showReceipt");
34
- const oid = params.get("orderId");
35
- const or = params.get("orderRef");
36
- if (oid && or) {
37
- fetch(`${apiBaseUrl}/api/ecommerce/orders/${oid}/reference/${or}`).then(
38
- async (res) =>
39
- await res.json().then((order) => {
40
- setOrder(order);
41
- setStatus(
42
- order.charge_id ||
43
- !["pending", "awaiting_payment"].includes(order.status)
44
- ? 2
45
- : 1
46
- );
47
- })
48
- );
49
- }
50
- }, []);
51
-
52
- // build pricing list
53
- React.useEffect(() => {
54
- // filter out prices that have already been queried
55
- const pricesToGet = cart.items
56
- .map((c) => c.price_id)
57
- .filter(
58
- (pId) => Object.keys(prices).findIndex((pKey) => pKey == pId) === -1
59
- );
60
- if (pricesToGet.length === 0) return;
61
-
62
- const url = `${apiBaseUrl}/api/ecommerce/price?filter={'ids':[${pricesToGet.join(
63
- ","
64
- )}]}`;
65
- fetch(url, {
66
- method: "GET",
67
- headers: {
68
- "Content-Type": "application/json",
69
- },
70
- })
71
- .then((res) =>
72
- res.json().then((data) => {
73
- const pricingData = { ...prices };
74
-
75
- data.forEach((p) => {
76
- pricingData[p.id] = p;
77
- });
78
- setPrices(pricingData);
79
- })
80
- )
81
- .catch(() => {});
82
- }, [cart]);
83
-
84
- React.useEffect(() => {
85
- setTotal(
86
- `$${(
87
- cart.items
88
- .map((product) => prices[product.price_id]?.unit_amount)
89
- .reduce((p, c) => (c ? p + c : p), 0) / 100
90
- ).toFixed(2)}`
91
- );
92
- }, [cart, prices]);
93
-
94
- if (status === 0 && cart.items.length === 0)
95
- return (
96
- <div
97
- style={{
98
- width: "100%",
99
- display: "flex",
100
- alignItems: "center",
101
- flexDirection: "column",
102
- gap: 8,
103
- }}
104
- >
105
- <Typography style={{ fontSize: 32, fontWeight: 600 }}>
106
- Cart is empty
107
- </Typography>
108
- <a className="shopping-button" href={`/${emptyCartLink}`}>
109
- <Typography>BACK</Typography>
110
- </a>
111
- </div>
112
- );
113
-
114
- return (
115
- <div>
116
- <StatusBar status={status} />
117
- <div>
118
- {status === 0 && (
119
- <CartSection
120
- total={total}
121
- setStatus={setStatus}
122
- cart={cart}
123
- prices={prices}
124
- apiBaseUrl={apiBaseUrl}
125
- setOrder={setOrder}
126
- disableProductLink={disableProductLink}
127
- />
128
- )}
129
- {status > 0 && order && (
130
- <Checkout
131
- apiBaseUrl={apiBaseUrl}
132
- order={order}
133
- onPlacement={() => {
134
- clearCart();
135
- setStatus(2);
136
- }}
137
- />
138
- )}
139
- </div>
140
- </div>
141
- );
142
- }
143
-
144
- function CartSection({
145
- total,
146
- setStatus,
147
- cart,
148
- prices,
149
- apiBaseUrl,
150
- setOrder,
151
- disableProductLink,
152
- }) {
153
- function createOrder() {
154
- // If an order has already been created and hasn't been changed, get the previous order.
155
- if (cart.order && cart.order.id && cart.order.reference) {
156
- fetch(
157
- `${apiBaseUrl}/api/ecommerce/orders/${cart.order.id}/reference/${cart.order.reference}`
158
- ).then((res) =>
159
- res.json().then((order) => {
160
- setOrder(order);
161
- const currentUrl = new URL(window.location.href);
162
- currentUrl.searchParams.set("orderId", order.id);
163
- currentUrl.searchParams.set("orderRef", order.reference);
164
- window.history.pushState({}, "", currentUrl);
165
- setStatus(1);
166
- })
167
- );
168
- return;
169
- }
170
-
171
- // Otherwise, create a new order.
172
- fetch(apiBaseUrl + "/api/ecommerce/orders", {
173
- method: "POST",
174
- headers: {
175
- "Content-Type": "application/json",
176
- },
177
- body: JSON.stringify({
178
- customer_id: 1,
179
- cart_data: {
180
- items: cart.items.map((li) => ({
181
- ...li,
182
- name: undefined,
183
- image: undefined,
184
- })),
185
- },
186
- }),
187
- }).then((res) =>
188
- res.json().then((order) => {
189
- if (!order) throw "Missing order";
190
- setOrder(order);
191
- cartSetOrder({ id: order.id, reference: order.reference });
192
- const currentUrl = new URL(window.location.href);
193
- currentUrl.searchParams.set("orderId", order.id);
194
- currentUrl.searchParams.set("orderRef", order.reference);
195
- window.history.pushState({}, "", currentUrl);
196
- setStatus(1);
197
- })
198
- );
199
- }
200
-
201
- return (
202
- <div style={{ display: "flex", justifyContent: "center" }}>
203
- <div
204
- style={{
205
- display: "flex",
206
- flexDirection: "column",
207
- width: 600,
208
- alignItems: "center",
209
- boxShadow: "0px 2px 5px 2px #dfdfdfff",
210
- margin: "4px",
211
- padding: "2rem 0",
212
- borderRadius: "8px",
213
- }}
214
- >
215
- <Typography style={{ fontSize: "30px", fontWeight: "bold" }}>
216
- Checkout
217
- </Typography>
218
- <Tooltip title="Total is pre-tax and includes the first payment for recurring payments.">
219
- <Typography style={{ fontSize: "20px" }}>Total: {total}</Typography>
220
- </Tooltip>
221
- {/* <Button variant="contained" sx={{ mt: 2 }} onClick={createOrder}>
222
- Confirm Order
223
- </Button> */}
224
- <div className="checkout-list">
225
- {cart.items.map((p, i) => (
226
- <CartProductCard
227
- product={p}
228
- i={i}
229
- price={prices[p.price_id]}
230
- disableProductLink={disableProductLink}
231
- />
232
- ))}
233
- </div>
234
- <Button variant="contained" sx={{ mt: 2 }} onClick={createOrder}>
235
- Confirm Order
236
- </Button>
237
- </div>
238
- </div>
239
- );
240
- }
241
-
242
- function StatusBar({ status }) {
243
- return (
244
- <div
245
- style={{
246
- display: "flex",
247
- alignItems: "center",
248
- flexDirection: "column",
249
- }}
250
- >
251
- <div id="status-bar">
252
- <Typography className="status-text active">REVIEW</Typography>
253
- <div className={"status-bar" + (status > 0 ? " active" : "")}></div>
254
- <Typography className={"status-text" + (status > 0 ? " active" : "")}>
255
- PAYMENT
256
- </Typography>
257
- <div className={"status-bar" + (status > 1 ? " active" : "")}></div>
258
- <Typography className={"status-text" + (status > 1 ? " active" : "")}>
259
- ORDER PLACED
260
- </Typography>
261
- </div>
262
- </div>
263
- );
264
- }
1
+ import "./CheckoutList.css";
2
+ import { useStore } from "@nanostores/react";
3
+ import { CartProductCard } from "./components/CartProductCard";
4
+ import React from "react";
5
+ import { Button, Tooltip, Typography } from "@mui/material";
6
+ import {
7
+ cartStore,
8
+ clearCart,
9
+ setOrder as cartSetOrder,
10
+ } from "../utils/storage";
11
+ import Checkout from "./components";
12
+
13
+ export default function CheckoutList({
14
+ apiBaseUrl,
15
+ emptyCartLink = "",
16
+ disableProductLink = false,
17
+ tax_rate_id,
18
+ }: {
19
+ apiBaseUrl: string;
20
+ emptyCartLink?: string;
21
+ disableProductLink?: boolean;
22
+ tax_rate_id?: number | string;
23
+ }) {
24
+ const cart = JSON.parse(useStore(cartStore));
25
+
26
+ const [prices, setPrices] = React.useState({});
27
+ const [total, setTotal] = React.useState("Loading prices...");
28
+
29
+ const [status, setStatus] = React.useState(0);
30
+ const [order, setOrder] = React.useState(undefined);
31
+
32
+ React.useEffect(() => {
33
+ const params = new URLSearchParams(window.location.search);
34
+
35
+ const sr = params.get("showReceipt");
36
+ const oid = params.get("orderId");
37
+ const or = params.get("orderRef");
38
+ if (oid && or) {
39
+ fetch(`${apiBaseUrl}/api/ecommerce/orders/${oid}/reference/${or}`).then(
40
+ async (res) =>
41
+ await res.json().then((order) => {
42
+ setOrder(order);
43
+ setStatus(
44
+ order.charge_id ||
45
+ !["pending", "awaiting_payment"].includes(order.status)
46
+ ? 2
47
+ : 1
48
+ );
49
+ })
50
+ );
51
+ }
52
+ }, []);
53
+
54
+ // build pricing list
55
+ React.useEffect(() => {
56
+ // filter out prices that have already been queried
57
+ const pricesToGet = cart.items
58
+ .map((c) => c.price_id)
59
+ .filter(
60
+ (pId) => Object.keys(prices).findIndex((pKey) => pKey == pId) === -1
61
+ );
62
+ if (pricesToGet.length === 0) return;
63
+
64
+ const url = `${apiBaseUrl}/api/ecommerce/price?filter={'ids':[${pricesToGet.join(
65
+ ","
66
+ )}]}`;
67
+ fetch(url, {
68
+ method: "GET",
69
+ headers: {
70
+ "Content-Type": "application/json",
71
+ },
72
+ })
73
+ .then((res) =>
74
+ res.json().then((data) => {
75
+ const pricingData = { ...prices };
76
+
77
+ data.forEach((p) => {
78
+ pricingData[p.id] = p;
79
+ });
80
+ setPrices(pricingData);
81
+ })
82
+ )
83
+ .catch(() => {});
84
+ }, [cart]);
85
+
86
+ React.useEffect(() => {
87
+ setTotal(
88
+ `$${(
89
+ cart.items
90
+ .map((product) => prices[product.price_id]?.unit_amount)
91
+ .reduce((p, c) => (c ? p + c : p), 0) / 100
92
+ ).toFixed(2)}`
93
+ );
94
+ }, [cart, prices]);
95
+
96
+ if (status === 0 && cart.items.length === 0)
97
+ return (
98
+ <div
99
+ style={{
100
+ width: "100%",
101
+ display: "flex",
102
+ alignItems: "center",
103
+ flexDirection: "column",
104
+ gap: 8,
105
+ }}
106
+ >
107
+ <Typography style={{ fontSize: 32, fontWeight: 600 }}>
108
+ Cart is empty
109
+ </Typography>
110
+ <a className="shopping-button" href={`/${emptyCartLink}`}>
111
+ <Typography>BACK</Typography>
112
+ </a>
113
+ </div>
114
+ );
115
+
116
+ return (
117
+ <div>
118
+ <StatusBar status={status} />
119
+ <div>
120
+ {status === 0 && (
121
+ <CartSection
122
+ total={total}
123
+ setStatus={setStatus}
124
+ cart={cart}
125
+ prices={prices}
126
+ apiBaseUrl={apiBaseUrl}
127
+ setOrder={setOrder}
128
+ disableProductLink={disableProductLink}
129
+ tax_rate_id={tax_rate_id}
130
+ />
131
+ )}
132
+ {status > 0 && order && (
133
+ <Checkout
134
+ apiBaseUrl={apiBaseUrl}
135
+ order={order}
136
+ onPlacement={() => {
137
+ clearCart();
138
+ setStatus(2);
139
+ }}
140
+ />
141
+ )}
142
+ </div>
143
+ </div>
144
+ );
145
+ }
146
+
147
+ function CartSection({
148
+ total,
149
+ setStatus,
150
+ cart,
151
+ prices,
152
+ apiBaseUrl,
153
+ tax_rate_id,
154
+ setOrder,
155
+ disableProductLink,
156
+ }) {
157
+ function createOrder() {
158
+ // If an order has already been created and hasn't been changed, get the previous order.
159
+ if (cart.order && cart.order.id && cart.order.reference) {
160
+ fetch(
161
+ `${apiBaseUrl}/api/ecommerce/orders/${cart.order.id}/reference/${cart.order.reference}`
162
+ ).then((res) =>
163
+ res.json().then((order) => {
164
+ setOrder(order);
165
+ const currentUrl = new URL(window.location.href);
166
+ currentUrl.searchParams.set("orderId", order.id);
167
+ currentUrl.searchParams.set("orderRef", order.reference);
168
+ window.history.pushState({}, "", currentUrl);
169
+ setStatus(1);
170
+ })
171
+ );
172
+ return;
173
+ }
174
+
175
+ // Otherwise, create a new order.
176
+ fetch(apiBaseUrl + "/api/ecommerce/orders", {
177
+ method: "POST",
178
+ headers: {
179
+ "Content-Type": "application/json",
180
+ },
181
+ body: JSON.stringify({
182
+ customer_id: 1,
183
+ cart_data: {
184
+ tax_rate_id:
185
+ typeof tax_rate_id === "string"
186
+ ? Number.parseInt(tax_rate_id)
187
+ : tax_rate_id,
188
+ items: cart.items.map((li) => ({
189
+ ...li,
190
+ name: undefined,
191
+ image: undefined,
192
+ })),
193
+ },
194
+ }),
195
+ }).then((res) =>
196
+ res.json().then((order) => {
197
+ if (!order) throw "Missing order";
198
+ setOrder(order);
199
+ cartSetOrder({ id: order.id, reference: order.reference });
200
+ const currentUrl = new URL(window.location.href);
201
+ currentUrl.searchParams.set("orderId", order.id);
202
+ currentUrl.searchParams.set("orderRef", order.reference);
203
+ window.history.pushState({}, "", currentUrl);
204
+ setStatus(1);
205
+ })
206
+ );
207
+ }
208
+
209
+ return (
210
+ <div style={{ display: "flex", justifyContent: "center" }}>
211
+ <div
212
+ style={{
213
+ display: "flex",
214
+ flexDirection: "column",
215
+ width: 600,
216
+ alignItems: "center",
217
+ boxShadow: "0px 2px 5px 2px #dfdfdfff",
218
+ margin: "4px",
219
+ padding: "2rem 0",
220
+ borderRadius: "8px",
221
+ }}
222
+ >
223
+ <Typography style={{ fontSize: "30px", fontWeight: "bold" }}>
224
+ Checkout
225
+ </Typography>
226
+ <Tooltip title="Total is pre-tax and includes the first payment for recurring payments.">
227
+ <Typography style={{ fontSize: "20px" }}>Total: {total}</Typography>
228
+ </Tooltip>
229
+ {/* <Button variant="contained" sx={{ mt: 2 }} onClick={createOrder}>
230
+ Confirm Order
231
+ </Button> */}
232
+ <div className="checkout-list">
233
+ {cart.items.map((p, i) => (
234
+ <CartProductCard
235
+ product={p}
236
+ i={i}
237
+ price={prices[p.price_id]}
238
+ disableProductLink={disableProductLink}
239
+ />
240
+ ))}
241
+ </div>
242
+ <Button variant="contained" sx={{ mt: 2 }} onClick={createOrder}>
243
+ Confirm Order
244
+ </Button>
245
+ </div>
246
+ </div>
247
+ );
248
+ }
249
+
250
+ function StatusBar({ status }) {
251
+ return (
252
+ <div
253
+ style={{
254
+ display: "flex",
255
+ alignItems: "center",
256
+ flexDirection: "column",
257
+ }}
258
+ >
259
+ <div id="status-bar">
260
+ <Typography className="status-text active">REVIEW</Typography>
261
+ <div className={"status-bar" + (status > 0 ? " active" : "")}></div>
262
+ <Typography className={"status-text" + (status > 0 ? " active" : "")}>
263
+ PAYMENT
264
+ </Typography>
265
+ <div className={"status-bar" + (status > 1 ? " active" : "")}></div>
266
+ <Typography className={"status-text" + (status > 1 ? " active" : "")}>
267
+ ORDER PLACED
268
+ </Typography>
269
+ </div>
270
+ </div>
271
+ );
272
+ }