guestShop.spec.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /* eslint-env jest */
  2. import Vue from 'vue'
  3. import behavior, { cartTotals, paymentOrder, validItem } from '@/ui-refactor/views/guest-shop/guestPurchase'
  4. import * as shop from '@/api/shop'
  5. import { getGuestRegionList } from '@/api/config'
  6. jest.mock('@/api/shop', () => ({ fetchGuestProducts: jest.fn(), fetchGuestCart: jest.fn(), createGuestOrder: jest.fn() }))
  7. jest.mock('@/api/config', () => ({ getGuestRegionList: jest.fn() }))
  8. jest.mock('@/router', () => ({ push: jest.fn(), replace: jest.fn() }))
  9. const product = { ID: 'P1', GOODS_NAME: 'Product', SELL_PRICE: 100, MARKET_PRICE: 120, DISCOUNT: 80, STORE_NUMS: 5, TAX_RATE: 7.5, COIN: 'NGN' }
  10. const instances = []
  11. const shipping = { consignee: 'Recipient', acceptMobile: '123456789', province: ['R1'], lgaName: 'District', cityName: 'City', detailaddress: 'Street', email: 'guest@example.test' }
  12. async function settle() { for (let i = 0; i < 12; i++) { await Promise.resolve(); await Vue.nextTick() } }
  13. async function instance(market = 'ng', stage = 'catalog') {
  14. const vm = new (Vue.extend(behavior))({ propsData: { market, stage }})
  15. vm.$router = { push: jest.fn(), replace: jest.fn() }
  16. vm.$message = { error: jest.fn(), info: jest.fn() }
  17. vm.$refs.paystack = { payWithPaystack: jest.fn() }
  18. instances.push(vm)
  19. await vm.reload()
  20. await settle()
  21. return vm
  22. }
  23. async function checkout() {
  24. const vm = await instance()
  25. vm.toggleProduct(vm.products[0])
  26. Object.assign(vm.form, shipping)
  27. vm.stage = 'checkout'
  28. await settle()
  29. vm.openEmail()
  30. return vm
  31. }
  32. beforeEach(() => {
  33. jest.clearAllMocks()
  34. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [product], totalCount: 1 }})
  35. shop.fetchGuestCart.mockResolvedValue({ data: { sellType: [{ id: 1, sell_type: [{ label: 'pay_stack', name: 'Paystack' }] }], freight: 10, freeShipping: 500, coin: 'NGN' }})
  36. getGuestRegionList.mockResolvedValue({ data: [{ value: 'R1', label: 'Region' }] })
  37. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'ORDER1', amount: 130, currency: 'NGN' }})
  38. })
  39. afterEach(() => { instances.splice(0).forEach(vm => vm.$destroy()) })
  40. it.each([['ng', '620699181539139625'], ['ae', '620699181539139643']])('loads %s using string country IDs on both anonymous endpoints', async(market, countryId) => {
  41. const vm = await instance(market)
  42. expect(shop.fetchGuestProducts).toHaveBeenLastCalledWith({ countryId, categoryType: 1, page: 1, limit: 50 })
  43. expect(shop.fetchGuestCart).toHaveBeenLastCalledWith({ countryId, categoryType: 1 })
  44. await vm.loadRegions()
  45. expect(getGuestRegionList).toHaveBeenLastCalledWith({ countryId })
  46. expect(vm.payType).toBe('pay_stack')
  47. })
  48. it.each([
  49. ['ng', 'NGN', 'AED', 'products'], ['ng', 'NGN', 'AED', 'settings'],
  50. ['ae', 'AED', 'NGN', 'products'], ['ae', 'AED', 'NGN', 'settings']
  51. ])('uses %s product currency %s over settings currency %s when %s arrives first', async(market, coin, settingsCoin, first) => {
  52. const resolve = {}
  53. shop.fetchGuestProducts.mockReturnValueOnce(new Promise(done => { resolve.products = done }))
  54. shop.fetchGuestCart.mockReturnValueOnce(new Promise(done => { resolve.settings = done }))
  55. const responses = {
  56. products: { data: { list: [{ ...product, COIN: coin }], totalCount: 1 }},
  57. settings: { data: { sellType: [{ id: 1, sell_type: [{ label: 'pay_stack', name: 'Paystack' }] }], freight: 10, freeShipping: 500, coin: settingsCoin }}
  58. }
  59. const loading = instance(market)
  60. resolve[first](responses[first])
  61. await settle()
  62. const last = first === 'products' ? 'settings' : 'products'
  63. resolve[last](responses[last])
  64. const vm = await loading
  65. expect(vm.currency).toBe(coin)
  66. expect(vm.displayProducts[0].CODE).toBe(coin)
  67. })
  68. it('uses market price without member discount and does not add included tax again', () => {
  69. expect(cartTotals([{ ...product, quantity: 2 }], 500, 10)).toEqual({ subtotal: 240, shipping: 10, total: 250, tax: 16.74 })
  70. expect(cartTotals([{ ...product, quantity: 5 }], 600, 10).total).toBe(600)
  71. expect(cartTotals([], 500, 10)).toEqual({ subtotal: 0, shipping: 0, total: 0, tax: 0 })
  72. })
  73. it('holds quantity and total invariants over a range of stock and prices', () => {
  74. for (let cents = 1; cents < 130; cents += 7) {
  75. for (let quantity = 1; quantity <= product.STORE_NUMS; quantity++) {
  76. for (const price of [cents / 100, (cents / 100).toFixed(2)]) {
  77. const row = { ...product, MARKET_PRICE: price, quantity }
  78. const result = cartTotals([row], 0, 0)
  79. expect(result.total).toBe(cents * quantity / 100)
  80. expect(result.tax).toBeGreaterThanOrEqual(0)
  81. expect(result.tax).toBeLessThanOrEqual(result.total)
  82. }
  83. }
  84. }
  85. })
  86. it.each([null, undefined, '', ' ', -1, 'bad', Infinity, true, []])('rejects invalid market price %s instead of falling back to sales price', price => {
  87. expect(validItem({ ...product, MARKET_PRICE: price, quantity: 1 })).toBe(false)
  88. })
  89. it.each([0, '0', '120.50'])('validates market price %s without requiring sales price or discount', price => {
  90. expect(validItem({ ...product, MARKET_PRICE: price, SELL_PRICE: undefined, DISCOUNT: undefined, quantity: 1 })).toBe(true)
  91. })
  92. it('uses original market prices for product details, cart unit and line prices', async() => {
  93. const vm = await instance()
  94. const row = vm.displayProducts[0]
  95. expect(row.SELL_PRICE).toBe(100)
  96. vm.toggleProduct(row)
  97. vm.changeQuantity({ row, value: 2 })
  98. expect(vm.cartRows[0]).toMatchObject({ unitPrice: 120, linePrice: 240 })
  99. vm.showProduct(row)
  100. expect(vm.product).toMatchObject({ SELL_PRICE: 100, MARKET_PRICE: 120, taxAmount: 8.37 })
  101. expect(product).not.toHaveProperty('taxAmount')
  102. })
  103. it.each([null, '', ' ', 0, -1, 'abc', Infinity, true, ['100'], 1e20])('rejects invalid payment amount %s', amount => {
  104. expect(() => paymentOrder({ SN: 'O1', amount, currency: 'NGN' })).toThrow()
  105. })
  106. it('converts the server major amount once, without imposing the catalog currency', () => {
  107. expect(paymentOrder({ SN: 'O1', amount: 0.29, currency: 'USD' })).toMatchObject({ SN: 'O1', amount: 0.29, currency: 'USD', subunits: 29 })
  108. })
  109. it.each([{}, { SN: 'O1', amount: 100 }, { amount: 100, currency: 'NGN' }])('rejects incomplete payment data %j', data => {
  110. expect(() => paymentOrder(data)).toThrow()
  111. })
  112. it('keeps selections across pages and rejects unavailable or fractional quantities', async() => {
  113. const vm = await instance()
  114. vm.toggleProduct(product)
  115. for (const value of [0, -1, 1.5, 6, NaN]) vm.changeQuantity({ row: product, value })
  116. expect(vm.items[0].quantity).toBe(1)
  117. vm.changeQuantity({ row: product, value: 2 })
  118. vm.products = [{ ...product, ID: 'P2' }]
  119. vm.toggleProduct(vm.products[0])
  120. expect(vm.items.map(item => item.ID)).toEqual(['P1', 'P2'])
  121. vm.toggleProduct({ ...product, ID: 'P3', STORE_NUMS: 0 })
  122. expect(vm.items).toHaveLength(2)
  123. })
  124. it('requires shipping and email before calling the order API, with no passwords or member identity', async() => {
  125. const vm = await instance()
  126. vm.toggleProduct(product)
  127. vm.stage = 'checkout'
  128. await settle()
  129. vm.openEmail()
  130. expect(vm.emailVisible).toBe(false)
  131. Object.assign(vm.form, shipping, { email: 'invalid' })
  132. vm.openEmail()
  133. await vm.continuePayment()
  134. expect(shop.createGuestOrder).not.toHaveBeenCalled()
  135. vm.form.email = shipping.email
  136. await vm.continuePayment()
  137. expect(shop.createGuestOrder).toHaveBeenCalledWith({ ...shipping, countryId: '620699181539139625', goodsId: ['P1'], goodsNum: [1], payType: 'pay_stack' })
  138. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  139. })
  140. it('blocks duplicate submit and retains the same unpaid order after cancellation', async() => {
  141. const vm = await checkout()
  142. let resolve
  143. shop.createGuestOrder.mockReturnValue(new Promise(done => { resolve = done }))
  144. const first = vm.continuePayment()
  145. await vm.continuePayment()
  146. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  147. resolve({ data: { SN: 'ORDER1', amount: 130, currency: 'NGN' }})
  148. await first
  149. const callback = vm.paymentCallback
  150. vm.closePayment()
  151. expect(vm.pending.SN).toBe('ORDER1')
  152. vm.changeQuantity({ row: product, value: 2 })
  153. expect(vm.items[0].quantity).toBe(1)
  154. vm.openEmail()
  155. await vm.continuePayment()
  156. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  157. callback()
  158. expect(vm.$router.push).not.toHaveBeenCalled()
  159. vm.paymentCallback()
  160. vm.paymentCallback()
  161. expect(vm.$router.push).toHaveBeenCalledTimes(1)
  162. expect(vm.$router.push).toHaveBeenCalledWith({ path: '/guest-order', query: { order: 'ORDER1' }})
  163. })
  164. it('requires review of a changed server payment amount and currency before starting the SDK', async() => {
  165. const vm = await checkout()
  166. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'ORDER1', amount: 10, currency: 'USD' }})
  167. await vm.continuePayment()
  168. expect(vm.pending.currency).toBe('USD')
  169. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  170. await vm.continuePayment()
  171. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  172. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  173. })
  174. it.each([
  175. ['ng', '620699181539139625', '104', 'NGN'],
  176. ['ae', '620699181539139643', '148', 'AED']
  177. ])('starts and resumes %s payment using the returned order record and matching product currency', async(market, countryId, currencyId, currency) => {
  178. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: currencyId, COIN: currency }], totalCount: 1 }})
  179. const vm = await instance(market)
  180. vm.toggleProduct(vm.products[0])
  181. Object.assign(vm.form, shipping)
  182. vm.stage = 'checkout'
  183. await settle()
  184. vm.openEmail()
  185. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', DEC_SN: 'DECLARATION1', COUNTRY_ID: countryId, CURRENCY_ID: currencyId, PAY_AMOUNT: 130, ORDER_AMOUNT: 150, PAY_AMOUNT_STANDARD: 0.075, EXCHANGE_RATE: '1200', EMAIL: '', STATUS: 1 }})
  186. await vm.continuePayment()
  187. expect(vm.pending).toEqual({ SN: 'RECORD1', amount: 130, currency, subunits: 13000 })
  188. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  189. expect(vm.metadata.cart_id).toBe('RECORD1')
  190. expect(vm.form.email).toBe(shipping.email)
  191. expect(vm.$router.push).not.toHaveBeenCalled()
  192. vm.closePayment()
  193. vm.openEmail()
  194. await vm.continuePayment()
  195. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  196. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(2)
  197. })
  198. it('accepts ORDER_AMOUNT when the returned order record has no PAY_AMOUNT', async() => {
  199. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  200. const vm = await checkout()
  201. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: '620699181539139625', CURRENCY_ID: '104', ORDER_AMOUNT: 130 }})
  202. await vm.continuePayment()
  203. expect(vm.pending).toEqual({ SN: 'RECORD1', amount: 130, currency: 'NGN', subunits: 13000 })
  204. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  205. })
  206. it('updates the email amount and requests confirmation when the order record changes the total', async() => {
  207. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  208. const vm = await checkout()
  209. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: '620699181539139625', CURRENCY_ID: '104', PAY_AMOUNT: 95 }})
  210. await vm.continuePayment()
  211. expect(vm.pending.amount).toBe(95)
  212. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  213. await vm.continuePayment()
  214. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  215. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  216. })
  217. it.each([
  218. ['620699181539139643', '104'], ['620699181539139625', '148'], ['620699181539139625', undefined]
  219. ])('retains the order without starting payment for unmatched country/currency %s / %s', async(countryId, currencyId) => {
  220. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  221. const vm = await checkout()
  222. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: countryId, CURRENCY_ID: currencyId, PAY_AMOUNT: 90 }})
  223. await vm.continuePayment()
  224. expect(vm.pending.SN).toBe('RECORD1')
  225. expect(vm.sdkActive).toBe(false)
  226. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  227. await vm.continuePayment()
  228. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  229. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  230. })
  231. it.each([0, '', -1])('does not replace an invalid PAY_AMOUNT %s with another order amount', async(amount) => {
  232. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  233. const vm = await checkout()
  234. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: '620699181539139625', CURRENCY_ID: '104', PAY_AMOUNT: amount, ORDER_AMOUNT: 90 }})
  235. await vm.continuePayment()
  236. expect(vm.pending.SN).toBe('RECORD1')
  237. expect(vm.pending.amount).toBe(amount)
  238. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  239. })
  240. it('recovers after a failed request without starting payment', async() => {
  241. const vm = await checkout()
  242. shop.createGuestOrder.mockRejectedValue(new Error('Unavailable'))
  243. await vm.continuePayment()
  244. expect(vm.submitting).toBe(false)
  245. expect(vm.pending).toBeNull()
  246. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  247. expect(vm.$message.error).toHaveBeenCalled()
  248. })
  249. it('routes non-Paystack successful orders directly to the public skeleton', async() => {
  250. const vm = await checkout()
  251. vm.payList = [{ label: 'transfer', name: 'Bank transfer' }]
  252. vm.payType = 'transfer'
  253. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'BANK1' }})
  254. await vm.continuePayment()
  255. expect(vm.$router.push).toHaveBeenCalledWith({ path: '/guest-order', query: { order: 'BANK1' }})
  256. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  257. })
  258. it('ignores an order response after its country flow has been destroyed', async() => {
  259. const vm = await checkout()
  260. let resolve
  261. shop.createGuestOrder.mockReturnValue(new Promise(done => { resolve = done }))
  262. const submit = vm.continuePayment()
  263. vm.$destroy()
  264. resolve({ data: { SN: 'OLD', amount: 90, currency: 'NGN' }})
  265. await submit
  266. expect(vm.pending).toBeNull()
  267. expect(vm.$router.push).not.toHaveBeenCalled()
  268. })
  269. it('ignores product data from a destroyed country and the older of two pagination requests', async() => {
  270. const vm = await instance()
  271. let old
  272. shop.fetchGuestProducts.mockReturnValueOnce(new Promise(done => { old = done }))
  273. const first = vm.loadProducts()
  274. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, ID: 'CURRENT' }], totalCount: 1 }})
  275. await vm.loadProducts()
  276. old({ data: { list: [{ ...product, ID: 'OLD' }], totalCount: 1 }})
  277. await first
  278. expect(vm.products[0].ID).toBe('CURRENT')
  279. let late
  280. shop.fetchGuestProducts.mockReturnValueOnce(new Promise(done => { late = done }))
  281. const loading = vm.loadProducts()
  282. vm.$destroy()
  283. late({ data: { list: [{ ...product, ID: 'OTHER-COUNTRY' }], totalCount: 1 }})
  284. await loading
  285. expect(vm.products[0].ID).toBe('CURRENT')
  286. })
  287. it('blocks checkout on failed settings and recovers by reloading', async() => {
  288. const vm = await instance()
  289. vm.toggleProduct(product)
  290. shop.fetchGuestCart.mockRejectedValueOnce(new Error('Shipping unavailable'))
  291. await vm.reload()
  292. expect(vm.canCheckout).toBe(false)
  293. expect(vm.settingsLoading).toBe(false)
  294. await vm.reload()
  295. expect(vm.canCheckout).toBe(true)
  296. })
  297. it('keeps an existing SN when payment fields are invalid and never creates a replacement on retry', async() => {
  298. const vm = await checkout()
  299. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'CREATED', amount: null, currency: 'NGN' }})
  300. await vm.continuePayment()
  301. expect(vm.pending.SN).toBe('CREATED')
  302. expect(vm.submitting).toBe(false)
  303. expect(vm.sdkActive).toBe(false)
  304. await vm.continuePayment()
  305. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  306. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  307. })
  308. it('restores a usable checkout after SDK failure and locks the created order fields', async() => {
  309. const vm = await checkout()
  310. await vm.continuePayment()
  311. vm.changeForm({ consignee: 'Changed' })
  312. vm.clearCart()
  313. vm.navigate('catalog')
  314. expect(vm.form.consignee).toBe('Recipient')
  315. expect(vm.items).toHaveLength(1)
  316. expect(vm.$router.push).not.toHaveBeenCalled()
  317. vm.paymentError(new Error('SDK unavailable'))
  318. expect(vm.sdkActive).toBe(false)
  319. expect(vm.pending.SN).toBe('ORDER1')
  320. await vm.continuePayment()
  321. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  322. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(2)
  323. })
  324. it('redirects a direct empty checkout to the empty public cart', async() => {
  325. const vm = await instance('ae', 'checkout')
  326. expect(vm.$router.replace).toHaveBeenCalledWith({ path: '/guest-shop/ae/cart' })
  327. })