guestShop.spec.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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', email: 'guest@example.test', province: ['R1'], lgaName: 'District', cityName: 'City', detailaddress: 'Street' }
  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', EMAIL: 'guest@example.test' }})
  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.paymentCurrency).toBe(settingsCoin)
  67. expect(vm.displayProducts[0].CODE).toBe(coin)
  68. })
  69. it('uses market price without member discount and does not add included tax again', () => {
  70. expect(cartTotals([{ ...product, quantity: 2 }], 500, 10)).toEqual({ subtotal: 240, shipping: 10, total: 250, tax: 16.74 })
  71. expect(cartTotals([{ ...product, quantity: 5 }], 600, 10).total).toBe(600)
  72. expect(cartTotals([], 500, 10)).toEqual({ subtotal: 0, shipping: 0, total: 0, tax: 0 })
  73. })
  74. it('holds quantity and total invariants over a range of stock and prices', () => {
  75. for (let cents = 1; cents < 130; cents += 7) {
  76. for (let quantity = 1; quantity <= product.STORE_NUMS; quantity++) {
  77. for (const price of [cents / 100, (cents / 100).toFixed(2)]) {
  78. const row = { ...product, MARKET_PRICE: price, quantity }
  79. const result = cartTotals([row], 0, 0)
  80. expect(result.total).toBe(cents * quantity / 100)
  81. expect(result.tax).toBeGreaterThanOrEqual(0)
  82. expect(result.tax).toBeLessThanOrEqual(result.total)
  83. }
  84. }
  85. }
  86. })
  87. it.each([null, undefined, '', ' ', -1, 'bad', Infinity, true, []])('rejects invalid market price %s instead of falling back to sales price', price => {
  88. expect(validItem({ ...product, MARKET_PRICE: price, quantity: 1 })).toBe(false)
  89. })
  90. it.each([0, '0', '120.50'])('validates market price %s without requiring sales price or discount', price => {
  91. expect(validItem({ ...product, MARKET_PRICE: price, SELL_PRICE: undefined, DISCOUNT: undefined, quantity: 1 })).toBe(true)
  92. })
  93. it('uses original market prices for product details, cart unit and line prices', async() => {
  94. const vm = await instance()
  95. const row = vm.displayProducts[0]
  96. expect(row.SELL_PRICE).toBe(100)
  97. vm.toggleProduct(row)
  98. vm.changeQuantity({ row, value: 2 })
  99. expect(vm.cartRows[0]).toMatchObject({ unitPrice: 120, linePrice: 240 })
  100. vm.showProduct(row)
  101. expect(vm.product).toMatchObject({ SELL_PRICE: 100, MARKET_PRICE: 120, taxAmount: 8.37 })
  102. expect(product).not.toHaveProperty('taxAmount')
  103. })
  104. it.each([null, '', ' ', 0, -1, 'abc', Infinity, true, ['100'], 1e20])('rejects invalid payment amount %s', amount => {
  105. expect(() => paymentOrder({ SN: 'O1', amount, currency: 'NGN' })).toThrow()
  106. })
  107. it('converts the server major amount once, without imposing the catalog currency', () => {
  108. expect(paymentOrder({ SN: 'O1', amount: 0.29, currency: 'USD' })).toMatchObject({ SN: 'O1', amount: 0.29, currency: 'USD', subunits: 29 })
  109. })
  110. it.each([{}, { SN: 'O1', amount: 100 }, { amount: 100, currency: 'NGN' }])('rejects incomplete payment data %j', data => {
  111. expect(() => paymentOrder(data)).toThrow()
  112. })
  113. it('keeps selections across pages and rejects unavailable or fractional quantities', async() => {
  114. const vm = await instance()
  115. vm.toggleProduct(product)
  116. for (const value of [0, -1, 1.5, 6, NaN]) vm.changeQuantity({ row: product, value })
  117. expect(vm.items[0].quantity).toBe(1)
  118. vm.changeQuantity({ row: product, value: 2 })
  119. vm.products = [{ ...product, ID: 'P2' }]
  120. vm.toggleProduct(vm.products[0])
  121. expect(vm.items.map(item => item.ID)).toEqual(['P1', 'P2'])
  122. vm.toggleProduct({ ...product, ID: 'P3', STORE_NUMS: 0 })
  123. expect(vm.items).toHaveLength(2)
  124. })
  125. it('submits the checkout email and shipping with no passwords or member identity', async() => {
  126. const vm = await instance()
  127. vm.toggleProduct(product)
  128. vm.stage = 'checkout'
  129. await settle()
  130. vm.openEmail()
  131. expect(vm.emailVisible).toBe(false)
  132. Object.assign(vm.form, shipping)
  133. vm.openEmail()
  134. await vm.continuePayment()
  135. expect(shop.createGuestOrder).toHaveBeenCalledWith({ ...shipping, countryId: '620699181539139625', goodsId: ['P1'], goodsNum: [1], payType: 'pay_stack' })
  136. expect(vm.form.email).toBe('guest@example.test')
  137. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  138. })
  139. it.each(['', ' ', 'invalid', 'buyer@', 'buyer@host'])('blocks missing or invalid checkout email %s before placing an order', async email => {
  140. const vm = await checkout()
  141. vm.closePayment()
  142. vm.form.email = email
  143. vm.openEmail()
  144. expect(vm.emailVisible).toBe(false)
  145. expect(vm.$message.error).toHaveBeenCalled()
  146. vm.emailVisible = true
  147. await vm.continuePayment()
  148. expect(shop.createGuestOrder).not.toHaveBeenCalled()
  149. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  150. })
  151. it.each([undefined, '', 'invalid', null, 123, 'another@example.test'])('keeps the entered email when the server returns %s without duplicate orders', async email => {
  152. const vm = await checkout()
  153. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'ORDER1', amount: 130, currency: 'NGN', EMAIL: email }})
  154. await vm.continuePayment()
  155. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  156. expect(vm.pending.SN).toBe('ORDER1')
  157. expect(vm.sdkActive).toBe(true)
  158. expect(vm.submitting).toBe(false)
  159. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  160. expect(vm.form.email).toBe(shipping.email)
  161. expect(vm.$message.error).not.toHaveBeenCalled()
  162. vm.closePayment()
  163. vm.openEmail()
  164. await vm.continuePayment()
  165. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  166. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(2)
  167. })
  168. it('blocks duplicate submit and retains the same unpaid order after cancellation', async() => {
  169. const vm = await checkout()
  170. let resolve
  171. shop.createGuestOrder.mockReturnValue(new Promise(done => { resolve = done }))
  172. const first = vm.continuePayment()
  173. await vm.continuePayment()
  174. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  175. resolve({ data: { SN: 'ORDER1', amount: 130, currency: 'NGN', EMAIL: 'guest@example.test' }})
  176. await first
  177. const callback = vm.paymentCallback
  178. vm.closePayment()
  179. expect(vm.pending.SN).toBe('ORDER1')
  180. vm.changeQuantity({ row: product, value: 2 })
  181. expect(vm.items[0].quantity).toBe(1)
  182. vm.openEmail()
  183. await vm.continuePayment()
  184. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  185. callback()
  186. expect(vm.$router.push).not.toHaveBeenCalled()
  187. vm.paymentCallback()
  188. vm.paymentCallback()
  189. expect(vm.$router.push).toHaveBeenCalledTimes(1)
  190. expect(vm.$router.push).toHaveBeenCalledWith({ path: '/guest-order', query: { order: 'ORDER1' }})
  191. })
  192. it('starts the SDK immediately with the returned amount and currency without another confirmation', async() => {
  193. const vm = await checkout()
  194. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'ORDER1', amount: 10, currency: 'USD', EMAIL: 'guest@example.test' }})
  195. await vm.continuePayment()
  196. expect(vm.pending.currency).toBe('USD')
  197. expect(vm.pending.subunits).toBe(1000)
  198. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  199. expect(vm.$message.info).not.toHaveBeenCalled()
  200. await vm.continuePayment()
  201. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  202. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  203. })
  204. it.each([
  205. ['ng', '620699181539139625', '104', 'NGN'],
  206. ['ae', '620699181539139643', '148', 'AED']
  207. ])('starts and resumes %s payment using the returned order record and matching product currency', async(market, countryId, currencyId, currency) => {
  208. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: currencyId, COIN: currency }], totalCount: 1 }})
  209. const vm = await instance(market)
  210. vm.toggleProduct(vm.products[0])
  211. Object.assign(vm.form, shipping)
  212. vm.stage = 'checkout'
  213. await settle()
  214. vm.openEmail()
  215. 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: ' guest@example.test ', STATUS: 1 }})
  216. await vm.continuePayment()
  217. expect(vm.pending).toEqual({ SN: 'RECORD1', amount: 130, currency, subunits: 13000 })
  218. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  219. expect(vm.metadata.cart_id).toBe('RECORD1')
  220. expect(vm.form.email).toBe('guest@example.test')
  221. expect(vm.$router.push).not.toHaveBeenCalled()
  222. vm.closePayment()
  223. vm.openEmail()
  224. await vm.continuePayment()
  225. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  226. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(2)
  227. })
  228. it('accepts ORDER_AMOUNT when the returned order record has no PAY_AMOUNT', async() => {
  229. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  230. const vm = await checkout()
  231. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: '620699181539139625', CURRENCY_ID: '104', ORDER_AMOUNT: 130, EMAIL: 'guest@example.test' }})
  232. await vm.continuePayment()
  233. expect(vm.pending).toEqual({ SN: 'RECORD1', amount: 130, currency: 'NGN', subunits: 13000 })
  234. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  235. })
  236. it('starts payment using the final order amount without requesting another confirmation', async() => {
  237. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  238. const vm = await checkout()
  239. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: '620699181539139625', CURRENCY_ID: '104', PAY_AMOUNT: 95, EMAIL: 'guest@example.test' }})
  240. await vm.continuePayment()
  241. expect(vm.pending.amount).toBe(95)
  242. expect(vm.pending.subunits).toBe(9500)
  243. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  244. expect(vm.$message.info).not.toHaveBeenCalled()
  245. await vm.continuePayment()
  246. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(1)
  247. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  248. })
  249. it.each([
  250. ['620699181539139643', '104'], ['620699181539139625', '148'], ['620699181539139625', undefined]
  251. ])('retains the order without starting payment for unmatched country/currency %s / %s', async(countryId, currencyId) => {
  252. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  253. const vm = await checkout()
  254. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: countryId, CURRENCY_ID: currencyId, PAY_AMOUNT: 90 }})
  255. await vm.continuePayment()
  256. expect(vm.pending.SN).toBe('RECORD1')
  257. expect(vm.sdkActive).toBe(false)
  258. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  259. await vm.continuePayment()
  260. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  261. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  262. })
  263. it.each([0, '', -1])('does not replace an invalid PAY_AMOUNT %s with another order amount', async(amount) => {
  264. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, LOCAL_CURRENCY_ID: '104' }], totalCount: 1 }})
  265. const vm = await checkout()
  266. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'RECORD1', COUNTRY_ID: '620699181539139625', CURRENCY_ID: '104', PAY_AMOUNT: amount, ORDER_AMOUNT: 90 }})
  267. await vm.continuePayment()
  268. expect(vm.pending.SN).toBe('RECORD1')
  269. expect(vm.pending.amount).toBe(amount)
  270. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  271. })
  272. it('recovers after a failed request without starting payment', async() => {
  273. const vm = await checkout()
  274. shop.createGuestOrder.mockRejectedValue(new Error('Unavailable'))
  275. await vm.continuePayment()
  276. expect(vm.submitting).toBe(false)
  277. expect(vm.pending).toBeNull()
  278. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  279. expect(vm.$message.error).toHaveBeenCalled()
  280. })
  281. it('routes non-Paystack successful orders directly to the public skeleton', async() => {
  282. const vm = await checkout()
  283. vm.payList = [{ label: 'transfer', name: 'Bank transfer' }]
  284. vm.payType = 'transfer'
  285. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'BANK1' }})
  286. await vm.continuePayment()
  287. expect(vm.$router.push).toHaveBeenCalledWith({ path: '/guest-order', query: { order: 'BANK1' }})
  288. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  289. })
  290. it('ignores an order response after its country flow has been destroyed', async() => {
  291. const vm = await checkout()
  292. let resolve
  293. shop.createGuestOrder.mockReturnValue(new Promise(done => { resolve = done }))
  294. const submit = vm.continuePayment()
  295. vm.$destroy()
  296. resolve({ data: { SN: 'OLD', amount: 90, currency: 'NGN' }})
  297. await submit
  298. expect(vm.pending).toBeNull()
  299. expect(vm.$router.push).not.toHaveBeenCalled()
  300. })
  301. it('ignores product data from a destroyed country and the older of two pagination requests', async() => {
  302. const vm = await instance()
  303. let old
  304. shop.fetchGuestProducts.mockReturnValueOnce(new Promise(done => { old = done }))
  305. const first = vm.loadProducts()
  306. shop.fetchGuestProducts.mockResolvedValue({ data: { list: [{ ...product, ID: 'CURRENT' }], totalCount: 1 }})
  307. await vm.loadProducts()
  308. old({ data: { list: [{ ...product, ID: 'OLD' }], totalCount: 1 }})
  309. await first
  310. expect(vm.products[0].ID).toBe('CURRENT')
  311. let late
  312. shop.fetchGuestProducts.mockReturnValueOnce(new Promise(done => { late = done }))
  313. const loading = vm.loadProducts()
  314. vm.$destroy()
  315. late({ data: { list: [{ ...product, ID: 'OTHER-COUNTRY' }], totalCount: 1 }})
  316. await loading
  317. expect(vm.products[0].ID).toBe('CURRENT')
  318. })
  319. it('blocks checkout on failed settings and recovers by reloading', async() => {
  320. const vm = await instance()
  321. vm.toggleProduct(product)
  322. shop.fetchGuestCart.mockRejectedValueOnce(new Error('Shipping unavailable'))
  323. await vm.reload()
  324. expect(vm.canCheckout).toBe(false)
  325. expect(vm.settingsLoading).toBe(false)
  326. await vm.reload()
  327. expect(vm.canCheckout).toBe(true)
  328. })
  329. it('keeps an existing SN when payment fields are invalid and never creates a replacement on retry', async() => {
  330. const vm = await checkout()
  331. shop.createGuestOrder.mockResolvedValue({ data: { SN: 'CREATED', amount: null, currency: 'NGN' }})
  332. await vm.continuePayment()
  333. expect(vm.pending.SN).toBe('CREATED')
  334. expect(vm.submitting).toBe(false)
  335. expect(vm.sdkActive).toBe(false)
  336. await vm.continuePayment()
  337. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  338. expect(vm.$refs.paystack.payWithPaystack).not.toHaveBeenCalled()
  339. })
  340. it('restores a usable checkout after SDK failure and locks the created order fields', async() => {
  341. const vm = await checkout()
  342. await vm.continuePayment()
  343. vm.changeForm({ consignee: 'Changed' })
  344. vm.clearCart()
  345. vm.navigate('catalog')
  346. expect(vm.form.consignee).toBe('Recipient')
  347. expect(vm.items).toHaveLength(1)
  348. expect(vm.$router.push).not.toHaveBeenCalled()
  349. vm.paymentError(new Error('SDK unavailable'))
  350. expect(vm.sdkActive).toBe(false)
  351. expect(vm.pending.SN).toBe('ORDER1')
  352. await vm.continuePayment()
  353. expect(shop.createGuestOrder).toHaveBeenCalledTimes(1)
  354. expect(vm.$refs.paystack.payWithPaystack).toHaveBeenCalledTimes(2)
  355. })
  356. it('redirects a direct empty checkout to the empty public cart', async() => {
  357. const vm = await instance('ae', 'checkout')
  358. expect(vm.$router.replace).toHaveBeenCalledWith({ path: '/guest-shop/ae/cart' })
  359. })