useProductCart.js 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import { reactive } from 'vue'
  2. import { FormValidationError } from '@/utils/helpers'
  3. export function useProductCart(form, initialProducts = []) {
  4. const productCart = reactive(initialProducts)
  5. const productCartDeleted = reactive([])
  6. const productErrors = reactive([])
  7. const productValidation = () => {
  8. onClearProductErrors()
  9. const productExists = productCart.find(
  10. (product) => product.number === form.product.number
  11. )
  12. if (Number(form.qty) + (productExists?.qty ?? 0) > form.product.qty) {
  13. productErrors.push({
  14. message: 'Stok tidak mencukupi',
  15. field: 'qty',
  16. })
  17. }
  18. if (productErrors.length) {
  19. throw new FormValidationError('form error', productErrors)
  20. }
  21. }
  22. const onAddProduct = () => {
  23. try {
  24. form.clearErrors('product', 'qty')
  25. productValidation()
  26. const productExists = productCart.find(
  27. (product) => product.number === form.product.number
  28. )
  29. if (productExists) {
  30. productExists.qty += Number(form.qty)
  31. } else {
  32. productCart.push({
  33. label: 'add',
  34. number: form.product.number,
  35. name: form.product.name,
  36. price: form.price,
  37. qty: Number(form.qty),
  38. unit: form.product.unit,
  39. })
  40. }
  41. form.reset('product', 'price', 'qty')
  42. } catch (e) {
  43. e.errors.forEach((error) => {
  44. form.setError(error.field, error.message)
  45. })
  46. }
  47. }
  48. const onDeleteProduct = (index) => {
  49. if (productCart[index]?.id) {
  50. productCartDeleted.push({
  51. ...productCart[index],
  52. label: 'delete',
  53. })
  54. }
  55. productCart.splice(index, 1)
  56. }
  57. const onClearProductCart = () => {
  58. productCart.splice(0)
  59. }
  60. const onClearProductCartDelete = () => {
  61. productCartDeleted.splice(0)
  62. }
  63. const onClearProductErrors = () => {
  64. productErrors.splice(0)
  65. }
  66. const totalProductPrice = () => {
  67. const productPrices = productCart.map((product) => {
  68. if (form.checkedPpn) {
  69. return product.price + product.price * (form.ppn / 100)
  70. } else {
  71. return product.price
  72. }
  73. })
  74. return productPrices.reduce(
  75. (prevPrice, currentPrice) => prevPrice + currentPrice,
  76. 0
  77. )
  78. }
  79. const onEditProduct = (event) => {
  80. const { newData, index } = event
  81. productCart[index] = {
  82. ...newData,
  83. label: 'edit',
  84. }
  85. }
  86. return {
  87. productCart,
  88. productCartDeleted,
  89. productErrors,
  90. onClearProductCart,
  91. onClearProductCartDelete,
  92. onAddProduct,
  93. onDeleteProduct,
  94. onEditProduct,
  95. totalProductPrice,
  96. }
  97. }