useProductCart.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. console.info('this is running')
  46. }
  47. const totalProductPrice = () => {
  48. const productPrices = productCart.map((product) => {
  49. if (form.checkedPpn) {
  50. return product.price + product.price * (form.ppn / 100)
  51. } else {
  52. return product.price
  53. }
  54. })
  55. return productPrices.reduce((prev, current) => prev + current, 0)
  56. }
  57. const onEditProduct = (event) => {
  58. const { newData, index } = event
  59. productCart[index] = {
  60. ...newData,
  61. label: 'edit',
  62. }
  63. }
  64. return {
  65. productCart,
  66. productCartDeleted,
  67. onClearProductCart,
  68. onClearProductCartDelete,
  69. onAddProduct,
  70. onDeleteProduct,
  71. onEditProduct,
  72. totalProductPrice,
  73. }
  74. }