useVehicle.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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({ only: ['typeMember'], data: { id: form.type_member_id } })
  18. }
  19. )
  20. const vehicleClear = () => {
  21. listVehicle.splice(0)
  22. }
  23. const vehicleOnDelete = (index) => {
  24. listVehicle.splice(index, 1)
  25. usePage().props.value.errors = {}
  26. }
  27. const vehicleAddValidation = () => {
  28. if (!form.plat_number) {
  29. throw new FormValidationError('Plat kendaraan tidak boleh kosong', 'plat_number')
  30. }
  31. if (!form.max_vehicle_id) {
  32. throw new FormValidationError('Tidak boleh kosong', 'max_vehicle_id')
  33. }
  34. const platNumberExist = listVehicle.filter((vehicle) => vehicle.platNumber === form.plat_number.toUpperCase())
  35. if (platNumberExist.length) {
  36. throw new FormValidationError('Nomor plat kendaraan tidak boleh sama', 'plat_number')
  37. }
  38. const maxVehicles = listVehicle.filter((vehicle) => vehicle.maxVehicleId === form.max_vehicle_id)
  39. if (maxVehicles.length) {
  40. if (maxVehicles.length + 1 > maxVehicles[0].maxVehicle) {
  41. throw new FormValidationError('Melibihi batas maksimal kendaraan', 'plat_number')
  42. }
  43. }
  44. }
  45. const vehicleOnAdd = () => {
  46. try {
  47. form.clearErrors('plat_number', 'max_vehicle_id')
  48. vehicleAddValidation()
  49. const typeVehicle = props.typeMember.maxVehicles.filter(
  50. (maxVehicle) => maxVehicle.value === form.max_vehicle_id
  51. )[0]
  52. listVehicle.push({
  53. platNumber: form.plat_number.toUpperCase(),
  54. typeVehicle: typeVehicle.label,
  55. typeVehicleId: typeVehicle.typeVehicleId,
  56. maxVehicleId: typeVehicle.value,
  57. maxVehicle: typeVehicle.maxVehicle,
  58. })
  59. form.reset('plat_number', 'max_vehicle_id')
  60. } catch (err) {
  61. form.setError(err.field, err.message)
  62. }
  63. }
  64. return {
  65. listVehicle,
  66. vehicleClear,
  67. vehicleOnDelete,
  68. vehicleOnAdd,
  69. }
  70. }