useCart.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 (itemExists) {
  13. cartErrors.push({
  14. message: 'Produk sudah ada dikeranjang',
  15. field: 'product',
  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. cart.push({
  27. label: 'add',
  28. number: form.product.number,
  29. name: form.product.name,
  30. price: form.price,
  31. qty: Number(form.qty),
  32. unit: form.product.unit,
  33. })
  34. form.reset('product', 'price', 'qty')
  35. } catch (e) {
  36. e.errors.forEach((error) => {
  37. form.setError(error.field, error.message)
  38. })
  39. }
  40. }
  41. const onDeleteCart = (index) => {
  42. if (cart[index]?.id) {
  43. cartDeleted.push({
  44. ...cart[index],
  45. label: 'delete',
  46. })
  47. }
  48. cart.splice(index, 1)
  49. }
  50. const onClearCart = () => {
  51. cart.splice(0)
  52. }
  53. const onClearCartDelete = () => {
  54. cartDeleted.splice(0)
  55. }
  56. const onClearCartErrors = () => {
  57. cartErrors.splice(0)
  58. }
  59. const totalCartPrice = () => {
  60. const itemPrices = cart.map((product) => {
  61. return form.checkedPpn
  62. ? ppn(product.price, form.ppn) * product.qty
  63. : product.price * product.qty
  64. })
  65. return itemPrices.reduce((prev, current) => prev + current, 0)
  66. }
  67. const onEditCart = (event) => {
  68. const { newData, index } = event
  69. cart[index] = {
  70. ...newData,
  71. label: 'edit',
  72. }
  73. }
  74. return {
  75. cart,
  76. cartDeleted,
  77. cartErrors,
  78. onClearCart,
  79. onClearCartDelete,
  80. onAddCart,
  81. onEditCart,
  82. onDeleteCart,
  83. totalCartPrice,
  84. }
  85. }