hooks.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import {otherIn, otherInGetStockInfo} from '@apis';
  2. import {yupResolver} from '@hookform/resolvers/yup';
  3. import {GetOtherInGetStockInfoParams, OtherStockInParams} from '@models';
  4. import {userStore} from '@stores';
  5. import {useMutation} from '@tanstack/react-query';
  6. import {message} from 'antd';
  7. import {FormEvent} from 'react';
  8. import {useForm} from 'react-hook-form';
  9. import {number, object, string} from 'yup';
  10. type FormState = {
  11. /** 物料编号 */
  12. materialCode: string;
  13. /** 所属公司 */
  14. accountSleeve: string;
  15. /** wbs */
  16. wbs: string;
  17. /** 数量 */
  18. num: number;
  19. /** 库位信息 */
  20. storageLocationCode: string;
  21. /** 仓库信息 */
  22. warehouse: string;
  23. };
  24. async function submitQuery(params: GetOtherInGetStockInfoParams & {amount: string}) {
  25. const data = await otherInGetStockInfo(params);
  26. if (data.msg === '200') {
  27. /**
  28. * 获取库存信息
  29. * 如果有库存使用第一个库存入库
  30. * 如果没有库存传入库位信息进行新增入库
  31. */
  32. const {department} = userStore.getState();
  33. const inParams: OtherStockInParams = {
  34. ...params,
  35. departmentId: department,
  36. id: data.list.length > 0 ? data.list[0].id : null,
  37. producDate: '',
  38. };
  39. const result = await otherIn(inParams);
  40. return result;
  41. }
  42. return data;
  43. }
  44. const validate = object({
  45. materialCode: string().required('请输入物料编号'),
  46. accountSleeve: string().required('请选择公司'),
  47. wbs: string().required('请输入WBS编号'),
  48. num: number().typeError('请输入数字').required('请输入数量').min(1, '数量不能小于1个'),
  49. storageLocationCode: string().required('请选择入库库位'),
  50. warehouse: string().required('请选择入库仓库'),
  51. });
  52. export function useFormState() {
  53. const {control, clearErrors, reset, handleSubmit, watch} = useForm<FormState>({
  54. resolver: yupResolver(validate),
  55. defaultValues: {
  56. materialCode: '',
  57. accountSleeve: '',
  58. wbs: '',
  59. num: 1,
  60. storageLocationCode: '',
  61. warehouse: '',
  62. },
  63. });
  64. const {isLoading, mutate} = useMutation({
  65. mutationFn: submitQuery,
  66. onSuccess({msg}) {
  67. if (msg === '200') {
  68. message.success('入库成功');
  69. clearErrors();
  70. reset();
  71. }
  72. },
  73. });
  74. const onSubmit = handleSubmit(function ({
  75. wbs,
  76. storageLocationCode,
  77. materialCode,
  78. accountSleeve,
  79. num,
  80. }) {
  81. mutate({
  82. wllbCode: materialCode,
  83. accountSleeve,
  84. wbs,
  85. storageLocationCode,
  86. amount: String(num),
  87. });
  88. });
  89. function onReset(e: FormEvent) {
  90. e.preventDefault();
  91. reset();
  92. }
  93. return [
  94. {control, isLoading},
  95. {onSubmit, watch, onReset},
  96. ] as const;
  97. }