Browse Source

请求处理

HW 4 years ago
parent
commit
c87bbba6f7

+ 1 - 1
config/proxy.ts

@@ -9,7 +9,7 @@ export default {
   dev: {
     '/api/': {
       target: 'http://uat.jishutao.com',
-      changeOrigin: true,
+      changeOrigin: true,                //target为域名时设为true
       pathRewrite: { '/api/login': '' },
     },
   },

+ 62 - 31
src/app.tsx

@@ -87,44 +87,75 @@ const codeMessage = {
 
 /**
  * 异常处理程序
+ * {
+ *  "name":"BizError",        //name 为BizError是因为success为false
+ *  "data":{
+ *    "error":[{"field":"","message":"账号或密码不匹配。"}],
+ *    "token":"90c77e0f-cd3b-4555-89bf-21b69dc8b454"
+ *  },
+ *  "info":{
+ *    "success":false,
+ *    "data":null,
+ *    "errorCode":"",
+ *    "errorMessage":"账号或密码不匹配。",
+ *    "showType":2,
+ *    "traceId":"-1",
+ *    "host":"-1"
+ *  }
+ * }
  */
 const errorHandler = (error: ResponseError) => {
-  // const { response } = error;
-  // if (response && response.status) {
-  //   const errorText = codeMessage[response.status] || response.statusText;
-  //   const { status, url } = response;
-  //
-  //   notification.error({
-  //     message: `请求错误 ${status}: ${url}`,
-  //     description: errorText,
-  //   });
-  // }
-  //
-  // if (!response) {
-  //   notification.error({
-  //     description: '您的网络发生异常,无法连接服务器',
-  //     message: '网络异常',
-  //   });
-  // }
-  // throw error;
+  const { info } = error;
+  if (error.name === 'BizError') {
+    // const { errorCode } = info;
+    // notification.warning({
+    //   message: `请求错误`,
+    //   description: '111111',
+    // });
+    console.log(info)
+    if(info.errorCode === '403'){
+      message.warning('登录超时请重新登录');
+      history.push('/user/login');
+    }else{
+      message.warning(info.errorMessage);
+    }
+  }
+  if (!info) {
+    notification.error({
+      description: '您的网络发生异常,无法连接服务器',
+      message: '网络异常',
+    });
+  }
+  throw info;
 };
 
 export const request: RequestConfig = {
   errorHandler,
+  errorConfig: {
+    adaptor: (resData)=>{
+      console.log(resData,'resData')
+      return {
+        success: resData.error && resData.error.length === 0,
+          data: resData.data || null,
+        errorCode: (resData.error && resData.error.length > 0) ? resData.error[0].field : 0,
+        errorMessage: (resData.error && resData.error.length > 0) ? resData.error[0].message : '',
+        showType: (resData.error && resData.error.length > 0) ? (resData.error[0].field === '403' ? 9 : 2) : 0,
+        traceId: '-1',
+        host: '-1',
+      };
+    },
+    errorPage: '/user/login',       //showType为9是跳这个地址
+  },
   requestInterceptors: [
     (url, config) => {
-      if (config.method === 'get') {
-        url = url + '?' + qs.stringify({
-          token: cookies.get('token'),
-        });
-      } else {
+      if (config.method === 'post') {
         config.data = qs.stringify({
           ...(config.data || {}),
-          token: cookies.get('token'),
         });
       }
       config.headers = {
-        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
+        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;',
+        'X-Requested-With' : 'XMLHttpRequest',
       }
       return {
         url: `${url}`,
@@ -132,15 +163,15 @@ export const request: RequestConfig = {
       };
     },
   ],
+  middlewares: [
+    async function middlewareA(ctx, next) {
+      await next();
+    }
+  ],
   responseInterceptors: [
     async (config) => {
-      const response = await config.clone().json();
-      if (response.error && response.error.length > 0 && response.error[0].field === '403') {
-        message.warning('登录超时请重新登录');
-        history.push('/user/login');
-      }
-      cookies.set('token',response.token);
       return config;
+
     }
   ]
 };

+ 4 - 4
src/components/common/DataTable/index.tsx

@@ -19,8 +19,7 @@ export interface DataTable {
   params?: {},                      // 额外的请求参数
 }
 
-const DataTable: React.FC<DataTable> =  (props) => {
-  const actionRef = useRef<ActionType>();
+const DataTable: React.FC<DataTable> =  React.forwardRef((props, ref) => {
 
   return (
     <ProTable
@@ -34,7 +33,7 @@ const DataTable: React.FC<DataTable> =  (props) => {
           return v
         })
       }
-      actionRef={actionRef}
+      actionRef={ref}
       params={props.params || {}}
       request={async (params = {}) =>{
           params.pageNo = params.current;
@@ -42,6 +41,7 @@ const DataTable: React.FC<DataTable> =  (props) => {
           const msg = await request(props.url, {
             params: props.requestProcess?props.requestProcess(params):params,
           });
+          console.log(msg,'msg')
           if(msg.error.length > 0){
             return {
               success: false,
@@ -74,6 +74,6 @@ const DataTable: React.FC<DataTable> =  (props) => {
       onHeaderRow={props.onHeaderRow}
       />
   );
-};
+});
 
 export default DataTable;

+ 1 - 1
src/locales/zh-CN/pages.ts

@@ -1,7 +1,7 @@
 export default {
   'pages.layouts.userLayout.title': 'Ant Design 是西湖区最具影响力的 Web 设计规范',
   'pages.login.accountLogin.tab': '账户密码登录',
-  'pages.login.accountLogin.errorMessage': '错误的用户名和密码(admin/ant.design)',
+  'pages.login.accountLogin.errorMessage': '错误的用户名和密码',
   'pages.login.username.placeholder': '用户名: admin or user',
   'pages.login.username.required': '用户名是必填项!',
   'pages.login.password.placeholder': '密码: ant.design',

+ 146 - 0
src/pages/Order/Billing/components/createOrder.jsx

@@ -0,0 +1,146 @@
+import React, { Component } from 'react';
+import { PlusOutlined } from "@ant-design/icons";
+import {
+  Button,
+  message,
+  AutoComplete,
+  Form,
+  Select,
+} from "antd";
+import ProForm, {
+  DrawerForm,
+  ProFormText,
+  ProFormDateRangePicker,
+  ProFormSelect,
+} from '@ant-design/pro-form';
+import {
+  orderTypes,
+  customerType,
+} from "@/utils/dataDic";
+import {getCustomerByName, createOrder} from '../services/API';
+
+const { Option } = Select;
+
+class CreateOrder extends Component{
+  constructor(props) {
+    super(props);
+    this.state={
+      customerOptions: [],
+      customType: '',
+      uid: '',
+    }
+    this.selectCustomerType = this.selectCustomerType.bind(this);
+    this.onSearch = this.onSearch.bind(this);
+    this.handleSubmit = this.handleSubmit.bind(this);
+  }
+
+  selectCustomerType=(v)=>{
+    this.setState({
+      customType: v,
+    })
+  }
+
+  onSearch= async (v)=>{
+    if(!this.state.customType){
+      message.warning('请先选择客户所属类型!')
+      return;
+    }
+    const msg = await getCustomerByName(v,this.state.customType);
+    if(msg.error.length === 0){
+      (msg.data || []).map((v)=>{
+        v.label = v.name;
+        v.value = v.name;
+        return v
+      })
+      this.setState({
+        customerOptions: msg.data || [],
+      })
+    }else{
+      message.info(msg.error[0].message)
+    }
+  }
+
+  handleSubmit= async (v)=>{
+    const msg = await createOrder(this.state.uid,v.orderType);
+    if(msg.error.length === 0){
+      message.success('创建成功');
+      return true;
+    }else{
+      message.info(msg.error[0].message)
+    }
+    return false;
+  }
+
+  render() {
+    return (
+      <>
+        <DrawerForm
+          title="创建订单"
+          trigger={
+            <Button key="button" icon={<PlusOutlined />} type="primary">
+              开单
+            </Button>
+          }
+          onFinish={this.handleSubmit}
+        >
+          <ProForm.Group>
+            <ProFormSelect
+              options={
+                orderTypes.map((v)=>{
+                  v.label = v.key;
+                  return v;
+                })
+              }
+              width="xl"
+              name="orderType"
+              label="订单类型"
+              rules={[{ required: true }]}
+              placeholder='请选择订单类型'
+            />
+          </ProForm.Group>
+          <ProForm.Group>
+            <Form.Item
+              name="customType"
+              label="客户所属类型"
+              rules={[{ required: true }]}
+            >
+              <Select
+                placeholder='请选择客户所属类型'
+                style={{ width: 552 }}
+                onChange={this.selectCustomerType}
+              >
+                {
+                  customerType.map((value,key)=>(
+                    <Option value={value.value} key={key}>{value.key}</Option>
+                  ))
+                }
+
+              </Select>
+            </Form.Item>
+          </ProForm.Group>
+          <ProForm.Group>
+            <Form.Item
+              name="uid"
+              label="客户名称"
+              rules={[{ required: true }]}
+            >
+              <AutoComplete
+                options={this.state.customerOptions}
+                style={{ width: 552 }}
+                onSelect={(v)=>{
+                  this.setState({
+                    uid: this.state.customerOptions.filter(item=> item.name === v)[0]['id'],
+                  })
+                }}
+                onSearch={this.onSearch}
+                placeholder="请输入名称"
+              />
+            </Form.Item>
+          </ProForm.Group>
+        </DrawerForm>
+      </>
+    )
+  }
+}
+
+export default CreateOrder;

+ 12 - 6
src/pages/Order/Billing/index.jsx

@@ -10,11 +10,12 @@ import {
   message,
   Popconfirm
 } from "antd";
-import {EllipsisOutlined, PlusOutlined} from "@ant-design/icons";
+import {EllipsisOutlined} from "@ant-design/icons";
 import { TableDropdown } from '@ant-design/pro-table';
 import { ProFormSelect } from '@ant-design/pro-form';
 import TableModal from './components/TableModal';
 import BillingHistory from './components/billingHistory';
+import CreateOrder from './components/createOrder';
 
 import {
   getSelectSuperId,
@@ -65,18 +66,21 @@ class Billing extends Component{
         {
           title: '合同编号',
           dataIndex: 'contractNo',
+          key: 'contractNo',
           width: 200,
           searchBool: true,
         },
         {
           title: '订单编号',
           dataIndex: 'orderNo',
+          key: 'orderNo',
           width: 200,
           searchBool: true,
         },
         {
           title: '客户名称',
           dataIndex: 'userName',
+          key: 'userName',
           searchBool: true,
           render: text => {
             return text && text.length > 9 ? text.substr(0, 9) + '...' : text;
@@ -107,6 +111,7 @@ class Billing extends Component{
         {
           title: '合同签订时间',
           dataIndex: 'signDate',
+          key: 'signDate',
           width: 200,
         },
         {
@@ -120,6 +125,7 @@ class Billing extends Component{
         {
           title: '签单金额(万元)',
           dataIndex: 'totalAmount',
+          key: 'totalAmount',
           width: 200,
           searchBool: true,
           renderFormItem: () => {
@@ -248,6 +254,7 @@ class Billing extends Component{
               开票
             </a>,
             <Popconfirm
+              key="view"
               title="是否结项?"
               onConfirm={(e) => {
                 e.stopPropagation();
@@ -260,7 +267,6 @@ class Billing extends Component{
               <a
                 target="_blank"
                 rel="noopener noreferrer"
-                key="view"
                 onClick={(e)=>{
                   e.stopPropagation();
                 }}
@@ -306,10 +312,12 @@ class Billing extends Component{
   }
 
   render() {
+    const ref = React.createRef();
+
     return (
       <>
         <DataTable
-          ref={res => this.dataTableRef = res}
+          ref={ref}
           headerTitle='开单与签单'
           url='/api/admin/newOrder/orderNewList'
           rowKey='orderNo'
@@ -348,9 +356,7 @@ class Billing extends Component{
             };
           }}
           toolBarRender={[
-            <Button key="button" icon={<PlusOutlined />} type="primary">
-              开单
-            </Button>,
+            <CreateOrder key='createOrder' dataTableRef={ref}/>,
             <Dropdown key="menu" overlay={menu}>
               <Button>
                 <EllipsisOutlined />

+ 16 - 0
src/pages/Order/Billing/services/API.ts

@@ -11,3 +11,19 @@ export async function getFakeCaptcha(orderNo: string) {
     params:{orderNo}
   });
 }
+
+// 客户名称自动补全
+export async function getCustomerByName(name: string,type: string) {
+  return request('/api/admin/customer/getCustomerByName',{
+    params:{name,type}
+  });
+}
+
+// 添加订单
+export async function createOrder(uid: string,orderType: string) {
+  return request('/api/admin/newOrder/createOrder',{
+    method: 'POST',
+    data:{uid,orderType}
+  });
+}
+

+ 9 - 11
src/pages/user/login/index.tsx

@@ -65,18 +65,16 @@ const Login: React.FC<{}> = () => {
     try {
       // 登录
       const msg = await fakeAccountLogin({ ...values, type });
-      if(msg.error.length === 0){
-        message.success('登录成功!');
-        await fetchUserInfo();
-        goto();
-        return;
-      }else{
-        message.info(msg.error[0].message)
-      }
-      // 如果失败去设置用户错误信息
-      setUserLoginState(msg);
+      message.success('登录成功!');
+      await fetchUserInfo();
+      goto();
     } catch (error) {
-      message.error('登录失败,请重试!');
+      console.log(error)
+      // 如果失败去设置用户错误信息
+      setUserLoginState({
+        status: 'error',
+        type: 'account',
+      });
     }
     setSubmitting(false);
   };