useProductCart.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { reactive } from 'vue'
  2. import { FormValidationError } from '@/utils/helpers'
  3. export function useProductCart(form, initialProducts = []) {
  4. const productCart = reactive(initialProducts)
  5. const productCartDeleted = reactive([])
  6. const productErrors = reactive([])
  7. const productValidation = () => {
  8. onClearProductErrors()
  9. const productExists = productCart.find(
  10. (product) => product.number === form.product.number
  11. )
  12. if (productExists) {
  13. productErrors.push({
  14. message: 'Produk sudah ada dikeranjang',
  15. field: 'product',
  16. })
  17. }
  18. if (productErrors.length) {
  19. throw new FormValidationError('form error', productErrors)
  20. }
  21. }
  22. const onAddProduct = () => {
  23. try {
  24. form.clearErrors('product', 'qty')
  25. productValidation()
  26. productCart.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 onDeleteProduct = (index) => {
  42. if (productCart[index]?.id) {
  43. productCartDeleted.push({
  44. ...productCart[index],
  45. label: 'delete',
  46. })
  47. }
  48. productCart.splice(index, 1)
  49. }
  50. const onClearProductCart = () => {
  51. productCart.splice(0)
  52. }
  53. const onClearProductCartDelete = () => {
  54. productCartDeleted.splice(0)
  55. }
  56. const onClearProductErrors = () => {
  57. productErrors.splice(0)
  58. }
  59. const totalProductPrice = () => {
  60. const productPrices = productCart.map((product) => {
  61. if (form.checkedPpn) {
  62. return product.price + product.price * (form.ppn / 100)
  63. } else {
  64. return product.price
  65. }
  66. })
  67. return productPrices.reduce((prev, current) => prev + current, 0)
  68. }
  69. const onEditProduct = (event) => {
  70. const { newData, index } = event
  71. productCart[index] = {
  72. ...newData,
  73. label: 'edit',
  74. }
  75. }
  76. return {
  77. productCart,
  78. productCartDeleted,
  79. productErrors,
  80. onClearProductCart,
  81. onClearProductCartDelete,
  82. onAddProduct,
  83. onDeleteProduct,
  84. onEditProduct,
  85. totalProductPrice,
  86. }
  87. }