InvoicingDrawerForm.tsx 19.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
// import { PlusOutlined } from '@ant-design/icons';
import InvoiceModal from '@/pages/Invoice/waitProcessRecord/components/InvoiceModal';
import {
  postServiceConstGetPayeeEnum,
  postServiceConstInitInvoiceDetailNames,
  postServiceConstInvoiceType,
  postServiceConstInvoicingType,
  postServiceConstListInvoiceDetailNames,
  postServiceInvoiceApplyInvoice,
  postServiceInvoiceQueryCompanyInfo,
  postServiceInvoiceWaitReissueInvoices,
} from '@/services';
import {
  FloatAdd,
  FloatMul,
  FloatSub,
  enum2ReverseSelect,
  enumToSelect,
} from '@/utils';
import { convertCurrency } from '@/utils/numberUtil';
import {
  DrawerForm,
  FormListActionType,
  ProCard,
  ProFormDigit,
  ProFormGroup,
  ProFormInstance,
  ProFormList,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Divider, Form, Space, Tooltip, message } from 'antd';
import { useEffect, useRef, useState } from 'react';

export default ({
  dataList,
  setVisible,
  mainOrder,
  onClose,
  type = 'applyInvoicing',
}) => {
  // let subOrderIds = dataList?.map((item) => {
  //   return item.id;
  // })
  const [form] = Form.useForm();
  const [projectOptions] = useState();
  const [dataListCopy] = useState(dataList);
  const listActionRef = useRef<FormListActionType>();
  const formRef = useRef<ProFormInstance>();
  useEffect(() => {
    const initOptions = async () => {
      const res = await postServiceConstInitInvoiceDetailNames({
        data: dataListCopy.map((item) => {
          return item.productName;
        }),
      });
      const options = res.data;
      const datas = dataListCopy.map((item) => {
        return {
          ...item,
          projectName: options[item.productName],
        };
      });
      const initialValue = datas.map((item) => {
        return {
          productName: item.productName,
          projectName: item.projectName,
          subOrderId: item.id,
          specification: item.parameters,
          unit: item.unit,
          quantity: item.quantity,
          price: item.productPrice,
          totalPrice: item.quantity * item.productPrice,
        };
      });
      form.setFieldValue('invoiceDetails', initialValue);
      form.setFieldValue('contacts', mainOrder.customerName);
    };
    initOptions();
  }, []);

  useEffect(() => {}, [projectOptions]);
  const types = new Map();
  types.set('applyInvoicing', {
    title: '申请开票',
    subOrderIdsName: '开票订单',
  });
  types.set('reissue', { title: '重新申请', subOrderIdsName: '重开订单' });
  function copyToClipboard(text: string) {
    // 创建一个临时的textarea元素
    const textarea = document.createElement('textarea');
    textarea.value = text;

    // 将textarea元素添加到DOM中
    document.body.appendChild(textarea);

    // 选中textarea中的文本
    textarea.select();

    try {
      // 尝试执行复制命令
      document.execCommand('copy');
      return true;
    } catch (err) {
      return false;
    } finally {
      // 移除临时的textarea元素
      document.body.removeChild(textarea);
    }
  }
  // 定义一个计算总金额的函数
  const calculateTotalPrice = (index: number) => {
    const invoiceDetails = form.getFieldValue('invoiceDetails');
    if (invoiceDetails && invoiceDetails[index]) {
      const quantity = invoiceDetails[index].quantity || 0;
      const price = invoiceDetails[index].price || 0;
      const totalPrice = FloatMul(quantity, price);
      const newInvoiceDetails = [...invoiceDetails];
      newInvoiceDetails[index] = { ...newInvoiceDetails[index], totalPrice };
      form.setFieldsValue({ invoiceDetails: newInvoiceDetails });
    }
    const totalPrice = invoiceDetails.reduce((accumulator, currentValue) => {
      return FloatAdd(accumulator, currentValue.quantity * currentValue.price);
    }, 0);
    form.setFieldValue('price', totalPrice);
  };
  useEffect(() => {}, []);
  return (
    <DrawerForm
      open
      title={types.get(type).title}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 500,
      }}
      form={form}
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            <InvoiceModal
              key={'invoicePreview'}
              button={<Button type="primary"> 发票预览 </Button>}
              getRecord={() => {
                const totalPrice = form
                  .getFieldValue('invoiceDetails')
                  .reduce((accumulator, currentValue) => {
                    return FloatAdd(accumulator, currentValue.totalPrice);
                  }, 0);
                const partyBName = form.getFieldValue('partyBName');
                const openBank = form.getFieldValue('openBank');
                const bankAccount = form.getFieldValue('bankAccount');
                const bankCode = form.getFieldValue('bankCode');
                return {
                  ...form.getFieldsValue(),
                  totalPrice: totalPrice,
                  totalPriceText: convertCurrency(totalPrice),
                  comment:
                    '开户名称: ' +
                    partyBName +
                    '\n' +
                    '开户行: ' +
                    openBank +
                    '\n' +
                    '账号: ' +
                    bankAccount +
                    '\n' +
                    '银行联行号: ' +
                    bankCode,
                };
              }}
            />,
            ...defaultDoms,
          ];
        },
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        postServiceInvoiceApplyInvoice({
          data: {
            ...values,
            subOrderIds: dataListCopy.map((item) => {
              return item.id;
            }),
            applyType: type,
          },
        });
        onClose();
      }}
      onOpenChange={(val) => {
        return !val && setVisible();
      }}
    >
      <ProFormList
        name="subOrderIdObjs"
        readonly={true}
        label={types.get(type).subOrderIdsName}
        initialValue={dataListCopy.map((item) => {
          return {
            value: item.id,
          };
        })}
        deleteIconProps={false}
        copyIconProps={false}
      >
        <ProFormGroup key="group">
          <ProFormText readonly={true} name="value" label="" />
        </ProFormGroup>
      </ProFormList>
      <ProFormSelect
        name="ReissueInvoiceRecordIds"
        label="重开的发票"
        fieldProps={{
          mode: 'multiple',
        }}
        placeholder="请选择重开发票"
        request={async () => {
          let reissueIds = dataListCopy.map((item) => {
            return item.id;
          });
          let res = await postServiceInvoiceWaitReissueInvoices({
            data: reissueIds,
          });
          return enum2ReverseSelect(res.data);
        }}
        rules={
          type === 'reissue'
            ? [{ required: true, message: '重开发票必填' }]
            : []
        }
      />
      {type === 'reissue' && (
        <ProFormTextArea
          name="reissueNotes"
          label="重开原因"
          rules={[{ required: true, message: '重开原因必填' }]}
          placeholder="请输入重新开票的原因"
        />
      )}

      <ProFormSelect
        key="key"
        label="购方名称"
        width="lg"
        showSearch
        name="partyAName"
        placeholder="请搜索购方"
        rules={[{ required: true, message: '购方名称必填' }]}
        onChange={(_, option) => {
          form.setFieldValue('partyATaxid', option.taxId);
        }}
        fieldProps={{
          optionItemRender(item) {
            if (item.type === 'add') {
              return <>{item.name}</>;
            }
            return (
              <>
                {item.name}
                <Divider type="vertical" />
                {item.taxId}
              </>
            );
          },
        }}
        debounceTime={1000}
        request={async (value) => {
          const keywords = value.keyWords;
          const res = await postServiceInvoiceQueryCompanyInfo({
            data: {
              nameLike: keywords,
              taxIdIsNotNull: true,
            },
          });
          let options = res?.data?.map((company) => {
            return {
              ...company,
              label: company.name,
              value: company.name,
              key: company.id,
            };
          });

          //第一个商品默认为要新增的商品
          if (keywords.trim() !== '') {
            options.unshift({
              name: keywords,
              type: 'add',
              label: keywords,
              value: keywords,
              key: keywords,
            });
          }
          return options;
        }}
      />
      <ProFormText
        width="md"
        name="partyATaxid"
        label="购方税号"
        rules={[{ required: true, message: '购方税号必填' }]}
        placeholder="请输入名称"
      />
      <ProFormText
        width="md"
        name="partyAOpenBank"
        label="开户银行"
        placeholder="请输入名称"
      />
      <ProFormText
        width="md"
        name="partyABankAccount"
        label="开户行账号"
        placeholder="请输入名称"
      />
      <ProFormText
        name="contacts"
        label="联系人"
        rules={[{ required: true, message: '请选择银行联行号!' }]}
      />
      <ProFormSelect
        name="invoicingType"
        label="开具类型"
        request={async () => {
          let invoicingTypeRet = await postServiceConstInvoicingType();
          let options = enumToSelect(invoicingTypeRet.data);
          return options;
        }}
        placeholder="请选择开具类型"
        rules={[{ required: true, message: '请选择开具类型!' }]}
      />
      <ProFormSelect
        name="type"
        label="开票类型"
        placeholder="请选择开票类型"
        rules={[{ required: true, message: '请选择开票类型!' }]}
        request={async () => {
          let invoiceTypeRet = await postServiceConstInvoiceType();
          let options = enumToSelect(invoiceTypeRet.data);
          return options;
        }}
      />
      <ProFormSelect
        name="partyB"
        label="开票收款单位"
        request={async () => {
          const res = await postServiceConstGetPayeeEnum();
          let options = res?.data?.map((payee: any) => {
            return {
              ...payee,
              label: payee.payeeName,
              value: payee.name,
            };
          });
          return options;
        }}
        onChange={(_, option) => {
          if (option) {
            form.setFieldsValue({
              partyBName: option.payeeName,
              partyBTaxid: option.taxId,
              bankAccount: option.bankAccount,
              openBank: option.openBank,
              bankCode: option.bankCode,
            });
          }
        }}
        placeholder="请选择收款单位"
        rules={[{ required: true, message: '请选择收款单位!' }]}
      />
      <ProFormText
        name="partyBName"
        label="开票收款单位名称"
        hidden
        rules={[{ required: true, message: '请选择收款单位!' }]}
      />
      <ProFormText
        name="partyBTaxid"
        label="开票收款单位税号"
        hidden
        rules={[{ required: true, message: '请选择收款单位!' }]}
      />
      <ProFormText
        name="bankAccount"
        label="账号"
        hidden
        rules={[{ required: true, message: '请选择账号!' }]}
      />
      <ProFormText
        name="openBank"
        label="开户行"
        hidden
        rules={[{ required: true, message: '请选择开户行!' }]}
      />
      <ProFormText
        name="bankCode"
        label="银行联行号"
        hidden
        rules={[{ required: true, message: '请选择银行联行号!' }]}
      />
      <ProFormSelect
        name="isUrgent"
        label="是否加急"
        valueEnum={{
          true: '是',
          false: '否',
        }}
        placeholder="请选择是否加急"
        rules={[{ required: true, message: '请选择是否加急!' }]}
      />
      <ProFormMoney
        label="开票金额"
        name="price"
        locale="zh-CN"
        disabled={true}
        rules={[{ required: true, message: '请填写开票金额!' }]}
        initialValue={dataListCopy.reduce((accumulator, currentValue) => {
          return accumulator + currentValue.subOrderPayment;
        }, 0)}
      />
      <ProFormList
        name="invoiceDetails"
        label="开票明细"
        actionRef={listActionRef}
        actionGuard={{
          beforeRemoveRow: async (index) => {
            const list = listActionRef.current?.getList();
            const totalPrice = list[index].totalPrice;
            form.setFieldValue(
              'price',
              FloatSub(form.getFieldValue('price'), totalPrice),
            );
            return true;
          },
        }}
        rules={[
          {
            required: true,
            validator: async (_, value) => {
              if (value && value.length > 0) {
                return;
              }
              throw new Error('至少要有一项!');
            },
          },
        ]}
        itemRender={(doms, listMeta) => {
          return (
            <ProCard
              bordered
              extra={doms.action}
              title={'明细' + (listMeta.index + 1)}
              style={{
                marginBlockEnd: 8,
              }}
            >
              <Tooltip title="点击复制商品名称">
                <Space
                  className="hover:cursor-pointer"
                  style={{
                    margin: 16,
                    marginTop: 4,
                    marginLeft: 0,
                    fontSize: 15,
                  }}
                  onClick={() => {
                    copyToClipboard(listMeta.record.productName);
                    message.info('商品名称复制成功!');
                  }}
                >
                  商品名称:{listMeta.record.productName}
                </Space>
              </Tooltip>
              <ProFormSelect
                key={'projectName' + listMeta.index}
                width="md"
                showSearch
                name="projectName"
                rules={[{ required: true, message: '请输入开票项目名称!' }]}
                request={async (value) => {
                  const keywords = value.keyWords;
                  const res = await postServiceConstListInvoiceDetailNames({
                    data: {
                      nameLike: keywords,
                    },
                  });
                  let options = res?.data?.map((c: any) => {
                    return {
                      ...c,
                      label:
                        '*' +
                        c.productAndServiceCatagoryAbbreviation +
                        '*' +
                        c.name,
                      value:
                        '*' +
                        c.productAndServiceCatagoryAbbreviation +
                        '*' +
                        c?.name,
                      key: c.id,
                    };
                  });
                  return options;
                }}
                fieldProps={{
                  filterOption() {
                    return true;
                  },
                }}
                onChange={(_, option) => {
                  let index = listMeta.index;
                  let copyList = form.getFieldValue('invoiceDetails');
                  let currentData = copyList[index];
                  currentData.projectName =
                    '*' +
                    option.productAndServiceCatagoryAbbreviation +
                    '*' +
                    option.name;
                  form.setFieldValue('invoiceDetails', copyList);
                }}
                debounceTime={1000}
                label="项目名称"
                initialValue={listMeta.record.projectName}
                placeholder="请输入名称"
              />
              <ProFormText
                key={'specification' + listMeta.index}
                name="specification"
                label="规格型号"
                rules={[
                  {
                    message: '规格型号不能为空!',
                    required: true,
                  },
                  {
                    validator: (_, value) => {
                      let len = 0;
                      // 判断是否为全角字符
                      for (let i = 0; i < value.length; i++) {
                        // 获取字符的Unicode值
                        const code = value.charCodeAt(i);
                        // 判断是否为全角字符
                        if (
                          (code >= 0xff01 && code <= 0xff5e) ||
                          (code >= 0x4e00 && code <= 0x9fff)
                        ) {
                          len += 2; // 全角字符
                        } else {
                          len += 1; // 半角字符
                        }
                      }
                      if (len <= 40) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error('规格型号不能超过40个字符!'),
                      );
                    },
                  },
                ]}
                placeholder="请输入名称"
              />
              <ProFormText
                key={'unit' + listMeta.index}
                name="unit"
                label="单位"
                placeholder="请输入名称"
              />
              <ProFormDigit
                key={'quantity' + listMeta.index}
                label="数量"
                name="quantity"
                rules={[
                  {
                    validator: (_, value) => {
                      if (value === undefined || value > 0) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('数量必须大于0'));
                    },
                  },
                ]}
                onChange={() => calculateTotalPrice(listMeta.index)}
              />

              <ProFormDigit
                key={'price' + listMeta.index}
                label="单价"
                name="price"
                rules={[
                  {
                    validator: (_, value) => {
                      if (value === undefined || value > 0) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('单价必须大于0'));
                    },
                  },
                ]}
                onChange={() => calculateTotalPrice(listMeta.index)}
              />

              <ProFormMoney
                key={'totalPrice' + listMeta.index}
                label="金额"
                name="totalPrice"
                rules={[
                  {
                    validator: (_, value) => {
                      if (value === undefined || value > 0) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('金额必须大于0'));
                    },
                  },
                ]}
                readonly={true}
                locale="zh-CN"
              />
            </ProCard>
          );
        }}
      ></ProFormList>
      <ProFormTextArea
        name="applyInvoicingNotes"
        label="备注"
        placeholder="请输入名称"
      />
    </DrawerForm>
  );
};