useProductCart.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import FormValidationError from '@/utils/FormValidationError'
  2. import { reactive } from 'vue'
  3. export function useProductCart(form) {
  4. const productCart = reactive([])
  5. const productValidation = () => {
  6. const existProduct = productCart.find(
  7. (product) => product.number === form.product.number
  8. )
  9. if (existProduct) {
  10. throw new FormValidationError('Produk sudah ada dikeranjang', 'product')
  11. }
  12. }
  13. const onAddProduct = () => {
  14. try {
  15. form.clearErrors('product', 'price', 'qty')
  16. productValidation()
  17. productCart.push({
  18. number: form.product.number,
  19. name: form.product.name,
  20. price: form.price,
  21. qty: form.qty,
  22. unit: form.product.unit,
  23. ppn: form.ppn,
  24. })
  25. form.reset('product', 'price', 'qty')
  26. } catch (e) {
  27. form.setError(e.field, e.message)
  28. }
  29. }
  30. const onDeleteProduct = (index) => {
  31. productCart.splice(index, 1)
  32. }
  33. const onClearProduct = () => {
  34. productCart.splice(0)
  35. }
  36. const totalProductPrice = () => {
  37. const productPrices = productCart.map(
  38. (product) => product.price + product.price * (form.ppn / 100)
  39. )
  40. return productPrices.reduce((prev, current) => prev + current, 0)
  41. }
  42. return {
  43. productCart,
  44. onAddProduct,
  45. onDeleteProduct,
  46. onClearProduct,
  47. totalProductPrice,
  48. }
  49. }