useProductCart.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. })
  24. form.reset('product', 'price', 'qty')
  25. } catch (e) {
  26. form.setError(e.field, e.message)
  27. }
  28. }
  29. const onDeleteProduct = (index) => {
  30. productCart.splice(index, 1)
  31. }
  32. const onClearProduct = () => {
  33. productCart.splice(0)
  34. }
  35. const totalProductPrice = () => {
  36. const productPrices = productCart.map((product) => {
  37. if (form.checkedPpn) {
  38. return product.price + product.price * (form.ppn / 100)
  39. } else {
  40. return product.price
  41. }
  42. })
  43. return productPrices.reduce((prev, current) => prev + current, 0)
  44. }
  45. return {
  46. productCart,
  47. onAddProduct,
  48. onDeleteProduct,
  49. onClearProduct,
  50. totalProductPrice,
  51. }
  52. }