@springmicro/cart 0.5.5 → 0.5.6

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@springmicro/cart",
3
3
  "private": false,
4
- "version": "0.5.5",
4
+ "version": "0.5.6",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -24,7 +24,7 @@
24
24
  "@nanostores/persistent": "^0.10.1",
25
25
  "@nanostores/query": "^0.3.3",
26
26
  "@nanostores/react": "^0.7.2",
27
- "@springmicro/utils": "0.5.5",
27
+ "@springmicro/utils": "0.5.6",
28
28
  "dotenv": "^16.4.5",
29
29
  "nanostores": "^0.10.3",
30
30
  "react": "^18.2.0",
@@ -49,5 +49,5 @@
49
49
  "vite-plugin-css-injected-by-js": "^3.5.1",
50
50
  "yup": "^1.4.0"
51
51
  },
52
- "gitHead": "9ccb87063f4e9e3a6b51bf48c27c1323b3de2858"
52
+ "gitHead": "26f6ece178f8cd1818b4edea235e1564b7825a7b"
53
53
  }
@@ -111,6 +111,7 @@ export default function ReviewAndCalculateTaxes({
111
111
  invoiceId = undefined,
112
112
  onPlacement = undefined,
113
113
  CollectExtraInfo = undefined,
114
+ defaultValues = {},
114
115
  }) {
115
116
  const [formDisabled, setFormDisabled] = useState(true);
116
117
  const [formError, setFormError] = useState(undefined);
@@ -180,7 +181,7 @@ export default function ReviewAndCalculateTaxes({
180
181
  setFormDisabled(false);
181
182
  })
182
183
  .catch(() => {
183
- console.log("ERROR");
184
+ // console.log("ERROR");
184
185
  setFormError(true);
185
186
  });
186
187
  }
@@ -213,9 +214,12 @@ export default function ReviewAndCalculateTaxes({
213
214
  postal_code: getPostalCodeDefault(initialCountry),
214
215
  } as AddressValues;
215
216
 
216
- const initialValues: CreditCardValues & Partial<AddressValues> = address
217
- ? { ...initialValuesBase, ...initialValuesAddress }
218
- : initialValuesBase;
217
+ const initialValues: CreditCardValues & Partial<AddressValues> & any = {
218
+ ...(address
219
+ ? { ...initialValuesBase, ...initialValuesAddress }
220
+ : initialValuesBase),
221
+ ...defaultValues,
222
+ };
219
223
 
220
224
  const validationSchemaBase = {
221
225
  expiry: Yup.string()
@@ -15,6 +15,7 @@ export default function Checkout({
15
15
  disableProductLink = false,
16
16
  disableMissingImage = false,
17
17
  CollectExtraInfo,
18
+ defaultValues,
18
19
  }: {
19
20
  apiBaseUrl: string;
20
21
  taxProvider: string;
@@ -22,6 +23,7 @@ export default function Checkout({
22
23
  disableProductLink?: boolean;
23
24
  disableMissingImage?: boolean;
24
25
  CollectExtraInfo?: React.FC<{ formik: FormikConfig<any> }>;
26
+ defaultValues?: Record<string, any>;
25
27
  }) {
26
28
  const cart = JSON.parse(useStore(cartStore));
27
29
 
@@ -154,6 +156,7 @@ export default function Checkout({
154
156
  setStatus(2);
155
157
  }}
156
158
  CollectExtraInfo={CollectExtraInfo}
159
+ defaultValues={defaultValues}
157
160
  />
158
161
  )}
159
162
  {status === 2 && order !== undefined && (
package/src/index.ts CHANGED
@@ -5,6 +5,8 @@ import {
5
5
  removeFromCart,
6
6
  clearCart,
7
7
  setOrder,
8
+ login,
9
+ logout,
8
10
  } from "./utils/storage";
9
11
  import type { Cart, CartProduct } from "./types";
10
12
  import AddToCartForm from "./AddToCartForm";
@@ -33,4 +35,6 @@ export {
33
35
  setOrder,
34
36
  ProductCard,
35
37
  ReviewCartAndCalculateTaxes,
38
+ login,
39
+ logout,
36
40
  };
@@ -22,26 +22,80 @@ function cartProductToCartDataItemIds(product: CartProduct) {
22
22
  };
23
23
  }
24
24
 
25
- apiPathDetails.listen((pathDetails) => {
25
+ function cartToApiCart(pathDetails, cart) {
26
+ return JSON.stringify({
27
+ user_id: pathDetails.userId,
28
+ items: cart.items.map((p) => cartProductToCartDataItemIds(p)),
29
+ order: cart.order ? JSON.stringify(cart.order) : undefined,
30
+ });
31
+ }
32
+
33
+ function apiCartToLocalCart(cart) {
34
+ return JSON.stringify({
35
+ items: cart.items ?? [],
36
+ authentication: { loggedIn: !!cart.user_id, user_id: cart.user_id },
37
+ order: cart.order,
38
+ });
39
+ }
40
+
41
+ apiPathDetails.listen((pathDetails, oldPathDetails) => {
42
+ const localCartData = JSON.parse(cartStore.get());
26
43
  if (pathDetailsIsFullyDefined(pathDetails)) {
27
44
  // Runs on init if there is a user id and api key. Automatically logs in if userId is updated from undefined.
28
- fetchFromCartApi("GET", pathDetails).then(async (c) => {
29
- const cart = await c.json();
30
- cartStore.set(
31
- JSON.stringify({
32
- authentication: { loggedIn: true, user_id: cart.user_id },
33
- items: JSON.parse((cart as any).items),
34
- order: cart.order ? JSON.parse((cart as any).order) : undefined,
35
- })
36
- );
45
+ fetchFromCartApi("GET", pathDetails).then(async ({ status, json }) => {
46
+ if (status === 200) {
47
+ const cart = await json();
48
+ cartStore.set(
49
+ JSON.stringify({
50
+ authentication: { loggedIn: true, user_id: cart.user_id },
51
+ items: JSON.parse((cart as any).items),
52
+ order: cart.order ? JSON.parse((cart as any).order) : undefined,
53
+ })
54
+ );
55
+ } else if (status === 404 && localCartData.items.length > 0) {
56
+ fetchFromCartApi(
57
+ "PUT",
58
+ pathDetails,
59
+ cartToApiCart(pathDetails, localCartData)
60
+ ).then(async ({ ok, json }) => {
61
+ if (!ok) return;
62
+ const cart = await json();
63
+ cartStore.set(
64
+ JSON.stringify({
65
+ authentication: { loggedIn: true, user_id: cart.user_id },
66
+ items: JSON.parse((cart as any).items),
67
+ order: cart.order ? JSON.parse((cart as any).order) : undefined,
68
+ })
69
+ );
70
+ });
71
+ } else {
72
+ cartStore.set(
73
+ JSON.stringify({
74
+ ...defaultCartValue,
75
+ authentication: { loggedIn: true, user_id: pathDetails.userId },
76
+ })
77
+ );
78
+ }
37
79
  });
38
- } else {
39
- const localCartData = JSON.parse(cartStore.get());
40
- if (localCartData.authentication.loggedIn)
41
- cartStore.set(JSON.stringify(defaultCartValue));
80
+ } else if (pathDetailsIsFullyDefined(oldPathDetails)) {
81
+ cartStore.set(JSON.stringify(defaultCartValue));
42
82
  }
43
83
  });
44
84
 
85
+ export function login(apiBaseUrl, user) {
86
+ apiPathDetails.set({
87
+ baseUrl: apiBaseUrl,
88
+ userId: user ? user.id : undefined,
89
+ });
90
+ }
91
+
92
+ export function logout(apiBaseUrl: string | undefined) {
93
+ apiPathDetails.set({
94
+ baseUrl: apiBaseUrl,
95
+ userId: undefined,
96
+ });
97
+ }
98
+
45
99
  export function addToCart(p: CartProduct) {
46
100
  const cart: Cart = JSON.parse(cartStore.get());
47
101
  const newCart: Cart = {
@@ -50,6 +104,10 @@ export function addToCart(p: CartProduct) {
50
104
  order: undefined,
51
105
  };
52
106
 
107
+ // Update local cart
108
+ cartStore.set(JSON.stringify(newCart));
109
+
110
+ // Update db cart if enabled
53
111
  const pathDetails = apiPathDetails.get();
54
112
  if (pathDetailsIsFullyDefined(pathDetails)) {
55
113
  fetchFromCartApi(
@@ -59,11 +117,13 @@ export function addToCart(p: CartProduct) {
59
117
  user_id: pathDetails.userId,
60
118
  items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
61
119
  })
62
- ).then(async () => {
63
- cartStore.set(JSON.stringify(newCart));
120
+ ).then(async (res) => {
121
+ if (!res.ok) return;
122
+
123
+ // Update cart based on server info.
124
+ const cart = await res.json();
125
+ cartStore.set(apiCartToLocalCart(cart));
64
126
  });
65
- } else {
66
- cartStore.set(JSON.stringify(newCart));
67
127
  }
68
128
  }
69
129
 
@@ -74,6 +134,10 @@ export function removeFromCart(i: number) {
74
134
  products.splice(i, 1);
75
135
  const newCart: Cart = { ...cart, items: products, order: undefined };
76
136
 
137
+ // Update local cart
138
+ cartStore.set(JSON.stringify(newCart));
139
+
140
+ // Update db cart if enabled
77
141
  const pathDetails = apiPathDetails.get();
78
142
  if (pathDetailsIsFullyDefined(pathDetails)) {
79
143
  // If products.length is 0, delete cart. Otheriwise, update cart.
@@ -88,11 +152,13 @@ export function removeFromCart(i: number) {
88
152
  cartIsEmpty ? "PUT" : "DELETE",
89
153
  pathDetails,
90
154
  cartIsEmpty ? JSON.stringify(body) : undefined
91
- ).then(async () => {
92
- cartStore.set(JSON.stringify(newCart));
155
+ ).then(async (res) => {
156
+ if (!res.ok) return;
157
+
158
+ // Update cart based on server info.
159
+ const cart = await res.json();
160
+ cartStore.set(apiCartToLocalCart(cart));
93
161
  });
94
- } else {
95
- cartStore.set(JSON.stringify(newCart));
96
162
  }
97
163
  }
98
164
 
@@ -100,13 +166,14 @@ export function clearCart() {
100
166
  const cart: Cart = JSON.parse(cartStore.get());
101
167
  const newCart: Cart = { ...cart, items: [], order: undefined };
102
168
 
169
+ // Update local first
170
+ cartStore.set(JSON.stringify(newCart));
171
+
103
172
  const pathDetails = apiPathDetails.get();
104
173
  if (pathDetailsIsFullyDefined(pathDetails)) {
105
174
  fetchFromCartApi("DELETE", pathDetails).then(async () => {
106
175
  cartStore.set(JSON.stringify(newCart));
107
176
  });
108
- } else {
109
- cartStore.set(JSON.stringify(newCart));
110
177
  }
111
178
  }
112
179