useProductCart.js 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { reactive } from 'vue'
  2. import FormValidationError from '@/utils/FormValidationError'
  3. export function useProductCart(form, initialProducts = []) {
  4. const productCart = reactive(initialProducts)
  5. const productCartDeleted = reactive([])
  6. const productValidation = () => {
  7. const existProduct = productCart.find(
  8. (product) => product.number === form.product.number
  9. )
  10. if (existProduct) {
  11. throw new FormValidationError('Produk sudah ada dikeranjang', 'product')
  12. }
  13. }
  14. const onAddProduct = () => {
  15. try {
  16. form.clearErrors('product', 'price', 'qty')
  17. productValidation()
  18. productCart.push({
  19. label: 'add',
  20. number: form.product.number,
  21. name: form.product.name,
  22. price: form.price,
  23. qty: form.qty,
  24. unit: form.product.unit,
  25. })
  26. form.reset('product', 'price', 'qty')
  27. } catch (e) {
  28. form.setError(e.field, e.message)
  29. }
  30. }
  31. const onDeleteProduct = (index) => {
  32. if (productCart[index]?.id) {
  33. productCartDeleted.push({
  34. ...productCart[index],
  35. label: 'delete',
  36. })
  37. }
  38. productCart.splice(index, 1)
  39. }
  40. const onClearProductCart = () => {
  41. productCart.splice(0)
  42. }
  43. const onClearProductCartDelete = () => {
  44. productCartDeleted.splice(0)
  45. }
  46. const totalProductPrice = () => {
  47. const productPrices = productCart.map((product) => {
  48. if (form.checkedPpn) {
  49. return product.price + product.price * (form.ppn / 100)
  50. } else {
  51. return product.price
  52. }
  53. })
  54. return productPrices.reduce((prev, current) => prev + current, 0)
  55. }
  56. const onEditProduct = (event) => {
  57. const { newData, index } = event
  58. productCart[index] = {
  59. ...newData,
  60. label: 'edit',
  61. }
  62. }
  63. return {
  64. productCart,
  65. productCartDeleted,
  66. onClearProductCart,
  67. onClearProductCartDelete,
  68. onAddProduct,
  69. onDeleteProduct,
  70. onEditProduct,
  71. totalProductPrice,
  72. }
  73. }