@springmicro/cart 0.5.5 → 0.5.7

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.7",
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.7",
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": "b2df84fd444de6a50ca70ebd8cdbd6196ef0eda4"
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
  };
@@ -18,30 +18,83 @@ function cartProductToCartDataItemIds(product: CartProduct) {
18
18
  return {
19
19
  ...product,
20
20
  image: undefined,
21
- name: undefined,
22
21
  };
23
22
  }
24
23
 
25
- apiPathDetails.listen((pathDetails) => {
24
+ function cartToApiCart(pathDetails, cart) {
25
+ return JSON.stringify({
26
+ user_id: pathDetails.userId,
27
+ items: cart.items.map((p) => cartProductToCartDataItemIds(p)),
28
+ order: cart.order ? JSON.stringify(cart.order) : undefined,
29
+ });
30
+ }
31
+
32
+ function apiCartToLocalCart(cart) {
33
+ return JSON.stringify({
34
+ items: cart.items ?? [],
35
+ authentication: { loggedIn: !!cart.user_id, user_id: cart.user_id },
36
+ order: cart.order,
37
+ });
38
+ }
39
+
40
+ apiPathDetails.listen((pathDetails, oldPathDetails) => {
41
+ const localCartData = JSON.parse(cartStore.get());
26
42
  if (pathDetailsIsFullyDefined(pathDetails)) {
27
43
  // 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
- );
44
+ fetchFromCartApi("GET", pathDetails).then(async ({ status, json }) => {
45
+ if (status === 200) {
46
+ const cart = await json();
47
+ cartStore.set(
48
+ JSON.stringify({
49
+ authentication: { loggedIn: true, user_id: cart.user_id },
50
+ items: JSON.parse((cart as any).items),
51
+ order: cart.order ? JSON.parse((cart as any).order) : undefined,
52
+ })
53
+ );
54
+ } else if (status === 404 && localCartData.items.length > 0) {
55
+ fetchFromCartApi(
56
+ "PUT",
57
+ pathDetails,
58
+ cartToApiCart(pathDetails, localCartData)
59
+ ).then(async ({ ok, json }) => {
60
+ if (!ok) return;
61
+ const cart = await json();
62
+ cartStore.set(
63
+ JSON.stringify({
64
+ authentication: { loggedIn: true, user_id: cart.user_id },
65
+ items: JSON.parse((cart as any).items),
66
+ order: cart.order ? JSON.parse((cart as any).order) : undefined,
67
+ })
68
+ );
69
+ });
70
+ } else {
71
+ cartStore.set(
72
+ JSON.stringify({
73
+ ...defaultCartValue,
74
+ authentication: { loggedIn: true, user_id: pathDetails.userId },
75
+ })
76
+ );
77
+ }
37
78
  });
38
- } else {
39
- const localCartData = JSON.parse(cartStore.get());
40
- if (localCartData.authentication.loggedIn)
41
- cartStore.set(JSON.stringify(defaultCartValue));
79
+ } else if (pathDetailsIsFullyDefined(oldPathDetails)) {
80
+ cartStore.set(JSON.stringify(defaultCartValue));
42
81
  }
43
82
  });
44
83
 
84
+ export function login(apiBaseUrl, user) {
85
+ apiPathDetails.set({
86
+ baseUrl: apiBaseUrl,
87
+ userId: user ? user.id : undefined,
88
+ });
89
+ }
90
+
91
+ export function logout(apiBaseUrl: string | undefined) {
92
+ apiPathDetails.set({
93
+ baseUrl: apiBaseUrl,
94
+ userId: undefined,
95
+ });
96
+ }
97
+
45
98
  export function addToCart(p: CartProduct) {
46
99
  const cart: Cart = JSON.parse(cartStore.get());
47
100
  const newCart: Cart = {
@@ -50,6 +103,10 @@ export function addToCart(p: CartProduct) {
50
103
  order: undefined,
51
104
  };
52
105
 
106
+ // Update local cart
107
+ cartStore.set(JSON.stringify(newCart));
108
+
109
+ // Update db cart if enabled
53
110
  const pathDetails = apiPathDetails.get();
54
111
  if (pathDetailsIsFullyDefined(pathDetails)) {
55
112
  fetchFromCartApi(
@@ -59,11 +116,13 @@ export function addToCart(p: CartProduct) {
59
116
  user_id: pathDetails.userId,
60
117
  items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
61
118
  })
62
- ).then(async () => {
63
- cartStore.set(JSON.stringify(newCart));
119
+ ).then(async (res) => {
120
+ if (!res.ok) return;
121
+
122
+ // Update cart based on server info.
123
+ const cart = await res.json();
124
+ cartStore.set(apiCartToLocalCart(cart));
64
125
  });
65
- } else {
66
- cartStore.set(JSON.stringify(newCart));
67
126
  }
68
127
  }
69
128
 
@@ -74,6 +133,10 @@ export function removeFromCart(i: number) {
74
133
  products.splice(i, 1);
75
134
  const newCart: Cart = { ...cart, items: products, order: undefined };
76
135
 
136
+ // Update local cart
137
+ cartStore.set(JSON.stringify(newCart));
138
+
139
+ // Update db cart if enabled
77
140
  const pathDetails = apiPathDetails.get();
78
141
  if (pathDetailsIsFullyDefined(pathDetails)) {
79
142
  // If products.length is 0, delete cart. Otheriwise, update cart.
@@ -88,11 +151,13 @@ export function removeFromCart(i: number) {
88
151
  cartIsEmpty ? "PUT" : "DELETE",
89
152
  pathDetails,
90
153
  cartIsEmpty ? JSON.stringify(body) : undefined
91
- ).then(async () => {
92
- cartStore.set(JSON.stringify(newCart));
154
+ ).then(async (res) => {
155
+ if (!res.ok) return;
156
+
157
+ // Update cart based on server info.
158
+ const cart = await res.json();
159
+ cartStore.set(apiCartToLocalCart(cart));
93
160
  });
94
- } else {
95
- cartStore.set(JSON.stringify(newCart));
96
161
  }
97
162
  }
98
163
 
@@ -100,13 +165,14 @@ export function clearCart() {
100
165
  const cart: Cart = JSON.parse(cartStore.get());
101
166
  const newCart: Cart = { ...cart, items: [], order: undefined };
102
167
 
168
+ // Update local first
169
+ cartStore.set(JSON.stringify(newCart));
170
+
103
171
  const pathDetails = apiPathDetails.get();
104
172
  if (pathDetailsIsFullyDefined(pathDetails)) {
105
173
  fetchFromCartApi("DELETE", pathDetails).then(async () => {
106
174
  cartStore.set(JSON.stringify(newCart));
107
175
  });
108
- } else {
109
- cartStore.set(JSON.stringify(newCart));
110
176
  }
111
177
  }
112
178