hooks.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import {getSemiManufacturesDrawList, semiManufacturesOut} from '@apis';
  2. import {yupResolver} from '@hookform/resolvers/yup';
  3. import {SemiDrawListData} from '@models';
  4. import {userStore} from '@stores';
  5. import {useMutation, useQueryClient} from '@tanstack/react-query';
  6. import {message} from 'antd';
  7. import {useEffect, useMemo} from 'react';
  8. import {useForm} from 'react-hook-form';
  9. import {number, object, string} from 'yup';
  10. import {useStore} from 'zustand';
  11. type FormState = {
  12. /** 仓库id */
  13. warehouse: string;
  14. /** 库位id */
  15. location: string;
  16. /** 出库数量 */
  17. outNum: number;
  18. };
  19. const validate = object({
  20. warehouse: string().required('请选择仓库'),
  21. location: string().required('请选择库位'),
  22. outNum: number()
  23. .typeError('请输入数字')
  24. .required('请输入出库数量')
  25. .min(1, '出库数量不能小于1个'),
  26. });
  27. function useData(id: string) {
  28. const client = useQueryClient();
  29. return useMemo(
  30. function () {
  31. const data = client.getQueryData<SemiDrawListData[]>(
  32. [getSemiManufacturesDrawList.name],
  33. {
  34. exact: false,
  35. },
  36. );
  37. if (!data) return void 0;
  38. return data.find(val => val.id === id);
  39. },
  40. [client, id],
  41. );
  42. }
  43. export function useFormState({
  44. visible,
  45. onClose,
  46. onFetch,
  47. id,
  48. }: {
  49. id: string;
  50. visible: boolean;
  51. onClose: () => void;
  52. onFetch: () => void;
  53. }) {
  54. const {control, handleSubmit, reset, clearErrors, watch, setValue} =
  55. useForm<FormState>({
  56. resolver: yupResolver(validate),
  57. defaultValues: {warehouse: '', outNum: 0, location: ''},
  58. });
  59. useEffect(
  60. function () {
  61. if (visible) {
  62. clearErrors();
  63. reset();
  64. }
  65. },
  66. [clearErrors, reset, visible],
  67. );
  68. const data = useData(id);
  69. const {isLoading, mutate} = useMutation({
  70. mutationFn: semiManufacturesOut,
  71. onSuccess({msg}) {
  72. if (msg === '200') {
  73. onClose();
  74. onFetch();
  75. message.success('出库完成');
  76. }
  77. },
  78. });
  79. const userId = useStore(userStore, state => String(state.id));
  80. const onSubmit = handleSubmit(function ({location, outNum}) {
  81. if (!data) return message.error('未获取到领料单信息');
  82. const {companyNumber, wbs, materialId, askGoodsId, materialCode} = data;
  83. mutate({
  84. companyNumber,
  85. wbs,
  86. materialId,
  87. warehousingNum: String(outNum),
  88. askGoodsId,
  89. wllbCode: materialCode,
  90. storageLocationCode: location,
  91. userId,
  92. });
  93. });
  94. return [
  95. {control, isLoading},
  96. {onSubmit, watch, setValue},
  97. ] as const;
  98. }