useProductCart.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 onClearProduct = () => {
  41. productCart.splice(0)
  42. }
  43. const totalProductPrice = () => {
  44. const productPrices = productCart.map((product) => {
  45. if (form.checkedPpn) {
  46. return product.price + product.price * (form.ppn / 100)
  47. } else {
  48. return product.price
  49. }
  50. })
  51. return productPrices.reduce((prev, current) => prev + current, 0)
  52. }
  53. const onEditProduct = (event) => {
  54. const { newData, index } = event
  55. productCart[index] = {
  56. ...newData,
  57. label: 'edit',
  58. }
  59. }
  60. return {
  61. productCart,
  62. productCartDeleted,
  63. onAddProduct,
  64. onDeleteProduct,
  65. onEditProduct,
  66. onClearProduct,
  67. totalProductPrice,
  68. }
  69. }