useCart.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { reactive } from 'vue'
  2. import { FormValidationError } 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. } else {
  32. cart.push({
  33. label: 'add',
  34. number: form.product.number,
  35. name: form.product.name,
  36. price: form.price,
  37. qty: Number(form.qty),
  38. unit: form.product.unit,
  39. })
  40. }
  41. form.reset('product', 'price', 'qty')
  42. } catch (e) {
  43. e.errors.forEach((error) => {
  44. form.setError(error.field, error.message)
  45. })
  46. }
  47. }
  48. const onDeleteCart = (index) => {
  49. if (cart[index]?.id) {
  50. cartDeleted.push({
  51. ...cart[index],
  52. label: 'delete',
  53. })
  54. }
  55. cart.splice(index, 1)
  56. }
  57. const onClearCart = () => {
  58. cart.splice(0)
  59. }
  60. const onClearCartDelete = () => {
  61. cartDeleted.splice(0)
  62. }
  63. const onClearCartErrors = () => {
  64. cartErrors.splice(0)
  65. }
  66. const totalCartPrice = () => {
  67. const itemPrices = cart.map((product) => {
  68. if (form.checkedPpn) {
  69. return product.price + product.price * (form.ppn / 100)
  70. } else {
  71. return product.price
  72. }
  73. })
  74. return itemPrices.reduce(
  75. (prevPrice, currentPrice) => prevPrice + currentPrice,
  76. 0
  77. )
  78. }
  79. return {
  80. cart,
  81. cartDeleted,
  82. cartErrors,
  83. onClearCart,
  84. onClearCartDelete,
  85. onAddCart,
  86. onDeleteCart,
  87. totalCartPrice,
  88. }
  89. }