Advertisement
Guest User

Shopping Saga Samples

a guest
Apr 24th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.11 KB | None | 0 0
  1. import {takeEvery, put, select, call} from 'redux-saga/effects';
  2.  
  3. import {
  4. requestAddToCart,
  5. setCart,
  6. setCartError,
  7. requestCreateCart,
  8. requestRemoveToCart,
  9. requestSetGift,
  10. decriceProductQuantity,
  11. requestUpdateCart,
  12. requestAddCouponToProduct,
  13. requestAddAddressToCart,
  14. requestAddCardToCart,
  15. requestResetCart,
  16. requestCreateCartSuccess,
  17. successAddAddressToCart,
  18. successAddCardToCart
  19. } from './actions';
  20.  
  21. import {getCart} from './selectors';
  22. import {getCustomerEmail} from '../customerProfile/selectors';
  23.  
  24. import {alertShow, updateSelectedShippingCompany} from '../../utils/helpers';
  25. import {checkIncludes} from '../../utils/helpers';
  26. import * as network from '../../API/APIFunctions';
  27. import * as path from '../../API/APIConstants';
  28. import NavigationService from '../../utils/navigation/NavigationService';
  29.  
  30. //Adding new product to cart if it is not there already
  31. export function* addToCart({payload}) {
  32. const id_product = payload.id_product;
  33. const id_person = payload.id_person;
  34. try {
  35. //getting cart data from store
  36. const cart = yield select(getCart);
  37.  
  38.  
  39. if (!checkIncludes(cart, payload.id_product, payload.id_person)) {
  40. //adding new item to cart from the store it it does not exist already, modifying selection
  41. cart.push({
  42. ...payload,
  43. count: 1,
  44. coupon: '',
  45. isGift: false,
  46. carrier: payload.carrier.filter((c) => +c.active).map((item) => ({...item, selected: false}))
  47. });
  48. } else {
  49. //increasing amount if each item by one if it already exists in out cart
  50. cart.map(item =>
  51. {if (item.id_person === id_person && item.id_product === id_product) {item.count = ++item.count; }});
  52. }
  53. yield put(setCart(cart));
  54.  
  55. } catch (error) {
  56. yield put(setCartError(error.message));
  57. alertShow(error);
  58. }
  59. }
  60. /*
  61. clears up cart from removed cart on user click
  62. */
  63. function* removeFromCartFlow({payload}) {
  64. const id_product = payload.id_product;
  65. try {
  66. const cart = yield select(getCart);
  67. //filtering out removed item
  68. const newCart = cart.filter(item => item.id_product !== id_product);
  69.  
  70. yield put(setCart(newCart));
  71. } catch (error) {
  72. alertShow(error);
  73. yield put(setCartError(error.message));
  74. }
  75. }
  76.  
  77. /*
  78. user can create coupons for his own products
  79. so each tapped item is modified to be either with or without coupon
  80. later in makes two different flows for user to use it
  81. */
  82. function* setGiftFlow({payload}) {
  83. const id_product = payload.id_product;
  84. const id_person = payload.id_person;
  85. try {
  86. const cart = yield select(getCart);
  87.  
  88. let withGift = cart.map(item =>
  89. (item.id_product === id_product && item.id_person === id_person) && ({...item, isGift: !item.isGift}));
  90.  
  91. yield put(setCart(withGift));
  92. } catch (error) {
  93. yield put(setCartError(error.message));
  94. }
  95. }
  96.  
  97. //decreasing amount of same items
  98. export function* updateCartProductQuantity({payload}) {
  99. const id_product = payload.id_product;
  100. const id_person = payload.id_person;
  101. try {
  102. //getting cart from application's store
  103. let cart = yield select(getCart);
  104.  
  105. //if current item exists in out cart, then we decrease amount of same items by one on each click and replace the object with correct amount of items inside cart
  106.  
  107. if (checkIncludes(cart, payload.id_product, payload.id_person)) {
  108. cart = cart.map((item) => {
  109. if (item.id_person === id_person && item.id_product === id_product && +item.count > 1) {
  110. return {
  111. ...item,
  112. count: --item.count
  113. };
  114. }
  115. return item;
  116. });
  117. }
  118. yield put(setCart(cart));
  119.  
  120. } catch (error) {
  121. yield put(setCartError(error.message));
  122. alertShow(error);
  123. }
  124. }
  125.  
  126. //adding new field to product that will have different purchase option with coupon
  127. function* addProductCoupon({payload}) {
  128. const id_product = payload.id_product;
  129. const id_person = payload.id_person;
  130. try {
  131. let cart = yield select(getCart);
  132.  
  133. cart = cart.map(item => {
  134. if (item.id_product === id_product && item.id_person === id_person) {
  135. return {
  136. ...item,
  137. coupon: payload.coupon
  138. };
  139. }
  140. return item;
  141. });
  142.  
  143. yield put(setCart(cart));
  144. } catch (error) {
  145. yield put(setCartError(error.message));
  146. }
  147. }
  148.  
  149. //modifying field of cart
  150. /*
  151. or more specifically, we change either seller name, item data (name, description or photos),
  152. and submit the changes to server, then if request succeeded we receive updated cart with correct items
  153. and we replace previous one with new
  154. */
  155. function* updateCart({payload}) {
  156. try {
  157. const cart = yield select(getCart);
  158. const newCart = yield updateSelectedShippingCompany(cart, payload.productId, payload.item, payload.seller);
  159.  
  160. yield put(setCart(newCart));
  161. } catch (error) {
  162. alertShow('Something went wrong.\nPlease try again later.');
  163. yield put(setCartError(error.message));
  164. }
  165. }
  166.  
  167. /*
  168. Initiations of new users cart
  169. Then navigating user to screen where
  170. he can fill up billing information
  171. for specific cart
  172. */
  173.  
  174. export function* createACart({payload}) {
  175. const body = JSON.stringify(payload);
  176. try {
  177. const resp = yield call(network.apiPost, path.API_URL + path.CREATE_CART, body);
  178.  
  179. if (resp.status === 200) {
  180. yield put(requestCreateCartSuccess());
  181. NavigationService.navigate('BuyBillingView');
  182. } else {
  183. yield put(setCartError(''));
  184. alertShow('Something went wrong.\nPlease try again later.');
  185. }
  186. } catch (e) {
  187. console.error('Error', e);
  188. }
  189. }
  190.  
  191. //Saving user address with cart data, then moving to check out flow
  192. /*
  193. Here user initiates process of buying something,
  194. we save his address to server with current
  195. stage of payment process
  196. */
  197. export function* addAddressToCart({payload}) {
  198. const body = JSON.stringify(payload);
  199. try {
  200. const resp = yield call(network.apiPost, path.API_URL + path.CERT_ADD_ADDRESS, body);
  201.  
  202. if (resp.status === 200) {
  203. yield put(successAddAddressToCart());
  204. //after request succeeded we move user to other screen to fill his Credit Card credentials
  205. NavigationService.navigate('CardPaymentDetails');
  206. } else {
  207. yield put(setCartError(''));
  208. alertShow('Something went wrong.\nPlease try again later.');
  209. }
  210. } catch (e) {
  211. console.error('Error', e);
  212. }
  213. }
  214.  
  215. //adding credit card and proceeding with payment depending on server callback
  216. /*
  217. When user fills out credit card credentials
  218. we make a post request to initiate payment process
  219. */
  220. export function* addCardToCart({payload}) {
  221. const body = JSON.stringify(payload);
  222.  
  223. try {
  224. const userEmail = yield select(getCustomerEmail);
  225. const resp = yield call(network.apiPostToken, path.CART_ADD_CARD, body);
  226.  
  227. if (resp.status === 200) {
  228. //here we calling another action to save user credit card data inside keychain
  229. yield put(successAddCardToCart());
  230. const object = yield resp.json();
  231. if (object.resultCode === 'Authorised') {
  232. //payment succeeded, here we reset user cart and greet him on other screen
  233. yield put(requestResetCart());
  234. NavigationService.navigate('ThankYou', {email: userEmail});
  235. } else {
  236. alertShow(object.refusalReason);
  237. }
  238. } else {
  239. yield put(setCartError(''));
  240. alertShow('Something went wrong.\nPlease try again later.');
  241. }
  242. } catch (e) {
  243. console.error('Error', e);
  244. }
  245. }
  246.  
  247. /*
  248. each saga is watching over specific action
  249. (or group of actions) with payload to fire up
  250. */
  251. export default function* () {
  252. yield takeEvery(requestAddToCart, addToCart);
  253. yield takeEvery(requestUpdateCart, updateCart);
  254. yield takeEvery(requestRemoveToCart, removeFromCartFlow);
  255. yield takeEvery(requestSetGift, setGiftFlow);
  256. yield takeEvery(decriceProductQuantity, updateCartProductQuantity);
  257. yield takeEvery(requestAddCouponToProduct, addProductCoupon);
  258. yield takeEvery(requestCreateCart, createACart);
  259. yield takeEvery(requestAddAddressToCart, addAddressToCart);
  260. yield takeEvery(requestAddCardToCart, addCardToCart);
  261. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement