123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { reactive } from 'vue'
  2. import { FormValidationError } from '@/utils/helpers'
  3. export function useCart(form, initialProducts = []) {
  4. const cart = reactive(initialProducts)
  5. const cartDeleted = reactive([])
  6. const cartErrors = reactive([])
  7. const cartValidation = () => {
  8. onClearCartErrors()
  9. const itemExists = cart.find(
  10. (product) => product.number === form.product.number
  11. )
  12. if (itemExists) {
  13. cartErrors.push({
  14. message: 'Produk sudah ada dikeranjang',
  15. field: 'product',
  16. })
  17. }
  18. if (cartErrors.length) {
  19. throw new FormValidationError('form error', cartErrors)
  20. }
  21. }
  22. const onAddCart = () => {
  23. try {
  24. form.clearErrors('product', 'qty')
  25. cartValidation()
  26. cart.push({
  27. label: 'add',
  28. number: form.product.number,
  29. name: form.product.name,
  30. price: form.price,
  31. qty: Number(form.qty),
  32. unit: form.product.unit,
  33. })
  34. form.reset('product', 'price', 'qty')
  35. } catch (e) {
  36. e.errors.forEach((error) => {
  37. form.setError(error.field, error.message)
  38. })
  39. }
  40. }
  41. const onDeleteCart = (index) => {
  42. if (cart[index]?.id) {
  43. cartDeleted.push({
  44. ...cart[index],
  45. label: 'delete',
  46. })
  47. }
  48. cart.splice(index, 1)
  49. }
  50. const onClearCart = () => {
  51. cart.splice(0)
  52. }
  53. const onClearCartDelete = () => {
  54. cartDeleted.splice(0)
  55. }
  56. const onClearCartErrors = () => {
  57. cartErrors.splice(0)
  58. }
  59. const totalCartPrice = () => {
  60. const itemPrices = cart.map((product) => {
  61. if (form.checkedPpn) {
  62. return product.price + product.price * (form.ppn / 100)
  63. } else {
  64. return product.price
  65. }
  66. })
  67. return itemPrices.reduce((prev, current) => prev + current, 0)
  68. }
  69. const onEditCart = (event) => {
  70. const { newData, index } = event
  71. cart[index] = {
  72. ...newData,
  73. label: 'edit',
  74. }
  75. }
  76. return {
  77. cart,
  78. cartDeleted,
  79. cartErrors,
  80. onClearCart,
  81. onClearCartDelete,
  82. onAddCart,
  83. onEditCart,
  84. onDeleteCart,
  85. totalCartPrice,
  86. }
  87. }