useCart.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import { reactive } from 'vue'
  2. import { FormValidationError, ppn } from '@/utils/helpers'
  3. export function useCart(form, initialProducts = []) {
  4. const cart = reactive(initialProducts)
  5. const cartDeleted = reactive([])
  6. const cartErrors = reactive([])
  7. const cartValidation = () => {
  8. onClearCartErrors()
  9. const itemExists = cart.find(
  10. (product) => product.number === form.product.number
  11. )
  12. if (Number(form.qty) + (itemExists?.qty ?? 0) > form.product.qty) {
  13. cartErrors.push({
  14. message: 'Stok tidak mencukupi',
  15. field: 'qty',
  16. })
  17. }
  18. if (cartErrors.length) {
  19. throw new FormValidationError('form error', cartErrors)
  20. }
  21. }
  22. const onAddCart = () => {
  23. try {
  24. form.clearErrors('product', 'qty')
  25. cartValidation()
  26. const itemExists = cart.find(
  27. (product) => product.number === form.product.number
  28. )
  29. if (itemExists) {
  30. itemExists.qty += Number(form.qty)
  31. if (initialProducts.length && itemExists?.label === undefined) {
  32. itemExists['label'] = 'edit'
  33. }
  34. } else {
  35. cart.push({
  36. label: 'add',
  37. number: form.product.number,
  38. name: form.product.name,
  39. price: form.price,
  40. qty: Number(form.qty),
  41. unit: form.product.unit,
  42. })
  43. }
  44. form.reset('product', 'price', 'qty')
  45. } catch (e) {
  46. e.errors.forEach((error) => {
  47. form.setError(error.field, error.message)
  48. })
  49. }
  50. }
  51. const onDeleteCart = (index) => {
  52. if (cart[index]?.id) {
  53. cartDeleted.push({
  54. ...cart[index],
  55. label: 'delete',
  56. })
  57. }
  58. cart.splice(index, 1)
  59. }
  60. const onClearCart = () => {
  61. cart.splice(0)
  62. }
  63. const onClearCartDelete = () => {
  64. cartDeleted.splice(0)
  65. }
  66. const onClearCartErrors = () => {
  67. cartErrors.splice(0)
  68. }
  69. const totalCartPrice = () => {
  70. const itemPrices = cart.map((product) => {
  71. return form.checkedPpn
  72. ? ppn(product.price, form.ppn) * product.qty
  73. : product.price * product.qty
  74. })
  75. return itemPrices.reduce(
  76. (prevPrice, currentPrice) => prevPrice + currentPrice,
  77. 0
  78. )
  79. }
  80. return {
  81. cart,
  82. cartDeleted,
  83. cartErrors,
  84. onClearCart,
  85. onClearCartDelete,
  86. onAddCart,
  87. onDeleteCart,
  88. totalCartPrice,
  89. }
  90. }