useVehicle.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { reactive, onMounted, watch } from 'vue'
  2. import { Inertia } from '@inertiajs/inertia'
  3. import { usePage } from '@inertiajs/inertia-vue3'
  4. import FormValidationError from '@/utils/formValidationError'
  5. export function useVehicle(props, form) {
  6. const listVehicle = reactive([])
  7. onMounted(() => {
  8. if (props.initialVehicles) {
  9. props.initialVehicles.forEach((val) => listVehicle.push(val))
  10. }
  11. })
  12. watch(
  13. () => form.type_member_id,
  14. () => {
  15. vehicleClear()
  16. form.reset('plat_number', 'max_vehicle_id')
  17. Inertia.reload({
  18. only: ['typeMember'],
  19. data: { id: form.type_member_id },
  20. })
  21. }
  22. )
  23. const vehicleClear = () => {
  24. listVehicle.splice(0)
  25. }
  26. const vehicleOnDelete = (index) => {
  27. listVehicle.splice(index, 1)
  28. usePage().props.value.errors = {}
  29. }
  30. const vehicleAddValidation = () => {
  31. if (!form.plat_number) {
  32. throw new FormValidationError(
  33. 'Plat kendaraan tidak boleh kosong',
  34. 'plat_number'
  35. )
  36. }
  37. if (!form.max_vehicle_id) {
  38. throw new FormValidationError('Tidak boleh kosong', 'max_vehicle_id')
  39. }
  40. const platNumberExist = listVehicle.filter(
  41. (vehicle) => vehicle.platNumber === form.plat_number.toUpperCase()
  42. )
  43. if (platNumberExist.length) {
  44. throw new FormValidationError(
  45. 'Nomor plat kendaraan tidak boleh sama',
  46. 'plat_number'
  47. )
  48. }
  49. const maxVehicles = listVehicle.filter(
  50. (vehicle) => vehicle.maxVehicleId === form.max_vehicle_id
  51. )
  52. if (maxVehicles.length) {
  53. if (maxVehicles.length + 1 > maxVehicles[0].maxVehicle) {
  54. throw new FormValidationError(
  55. 'Melibihi batas maksimal kendaraan',
  56. 'plat_number'
  57. )
  58. }
  59. }
  60. }
  61. const vehicleOnAdd = () => {
  62. try {
  63. form.clearErrors('plat_number', 'max_vehicle_id')
  64. vehicleAddValidation()
  65. const typeVehicle = props.typeMember.maxVehicles.filter(
  66. (maxVehicle) => maxVehicle.value === form.max_vehicle_id
  67. )[0]
  68. listVehicle.push({
  69. platNumber: form.plat_number.toUpperCase(),
  70. typeVehicle: typeVehicle.label,
  71. typeVehicleId: typeVehicle.typeVehicleId,
  72. maxVehicleId: typeVehicle.value,
  73. maxVehicle: typeVehicle.maxVehicle,
  74. })
  75. form.reset('plat_number', 'max_vehicle_id')
  76. } catch (err) {
  77. form.setError(err.field, err.message)
  78. }
  79. }
  80. return {
  81. listVehicle,
  82. vehicleClear,
  83. vehicleOnDelete,
  84. vehicleOnAdd,
  85. }
  86. }