其他分享
首页 > 其他分享> > 西电MES项目-NCR-缺陷等级

西电MES项目-NCR-缺陷等级

作者:互联网

NCR-缺陷等级表

后端

xd-qm包xd-qm-api下:com.crrcdt.xd.qm.model.Qde0010

package com.crrcdt.xd.qm.model;

import com.baomidou.mybatisplus.annotations.TableField;
import com.crrcdt.common.annotation.TableSearch;
import com.crrcdt.common.base.BaseModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * <p>
 * 质量模块-质量等级代码
 * </p>
 *
 * @author chova
 */
public class Qde0010 extends BaseModel {

    private static final long serialVersionUID = 1L;

    /**
     * 租户id
     */
	@TableField("TENANT_ID")
	@ApiModelProperty(value = "租户id")
	protected String tenantId;
    /**
     * 等级
     */
	@TableSearch(type = "like")
	@TableField("LEVELS")
	@ApiModelProperty(value = "等级")
	protected String levels;
    /**
     * 名称
     */
	@TableSearch(type = "like")
	@TableField("NAME")
	@ApiModelProperty(value = "名称")
	protected String name;
    /**
     * 不合格类别
     */
	@TableField("UNQUALIFIED_TYPE")
	@ApiModelProperty(value = "不合格类别")
	protected String unqualifiedType;
    /**
     * 编号
     */
    @TableSearch(type = "like")
	@TableField("SERIAL_NUMBER")
	@ApiModelProperty(value = "编号")
	protected String serialNumber;
	/**
	 * 数量
	 */
	@TableField(exist = false)
	@ApiModelProperty(value = "缺陷数量,报表用")
	protected Integer num;

	public Qde0010(){
	}
	public Qde0010(String id){
			this.id=id;
	}

	public Integer getNum() {
		return num;
	}

	public void setNum(Integer num) {
		this.num = num;
	}

	public String getTenantId() {
		return tenantId;
	}

	public void setTenantId(String tenantId) {
		this.tenantId = tenantId;
	}

	public String getLevels() {
		return levels;
	}

	public void setLevels(String level) {
		this.levels = level;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUnqualifiedType() {
		return unqualifiedType;
	}

	public void setUnqualifiedType(String unqualifiedType) {
		this.unqualifiedType = unqualifiedType;
	}

	public String getSerialNumber() {
		return serialNumber;
	}

	public void setSerialNumber(String serialNumber) {
		this.serialNumber = serialNumber;
	}

	@Override
	public String toString() {
		return "Qde0010{" +
			"tenantId=" + tenantId +
			", levels=" + levels +
			", name=" + name +
			", unqualifiedType=" + unqualifiedType +
			", serialNumber=" + serialNumber +
			"}";
	}
}

分析:

1.定义质量缺陷等级的实体类,与数据库数据相对应.
2.引入了MybatisPlus框架
3.@TableField("TENANT_ID")-MybatisPlus的注解数据表中的TENANT_ID属性

xd-qm包xd-qm-api下:com.crrcdt.xd.qm.api.Qde0010Service

package com.crrcdt.xd.qm.api;

import com.crrcdt.common.base.BaseService;
import com.crrcdt.xd.qm.model.Qde0010;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 质量模块-质量缺陷代码 服务类
 * </p>
 *
 * @author chova
 */
public interface Qde0010Service extends BaseService<Qde0010, Map<String,Object>> {

     List<Qde0010> getDataMap(String startDateString, String endDateString);

}

分析:

1.Qde0010Service继承BaseService<Qde0010, Map<String,Object>>类,BaseService类是由Generator代码生成器生成在com.crrcdt.common.base.BaseService中
2.定义getDataMap方法接口,在com.crrcdt.xd.qm.service.impl.Qde0010ServiceImpl中实现

xd-qm包xd-qm-service下:com.crrcdt.xd.qm.service.impl.Qde0010ServiceImpl

package com.crrcdt.xd.qm.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.crrcdt.common.base.BaseServiceImpl;
import com.crrcdt.xd.qm.api.Qde0010Service;
import com.crrcdt.xd.qm.mapper.Qde0010Mapper;
import com.crrcdt.xd.qm.model.Qde0010;
import com.xiaoleilu.hutool.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 质量模块-质量缺陷等级 服务实现类
 * </p>
 */
@Service
@org.springframework.stereotype.Service
@Transactional
public class Qde0010ServiceImpl extends BaseServiceImpl<Qde0010Mapper, Qde0010, Map<String,Object>> implements Qde0010Service {
    private static Logger logger = LoggerFactory.getLogger(Qde0010ServiceImpl.class);

    @Override
    public List<Qde0010> getDataMap(String startDateString, String endDateString) {
        Date startDate = null;
        Date endDate = null;
        if (StringUtils.isNotEmpty(startDateString) && StringUtils.isNotEmpty(endDateString)) {
            startDate = DateUtil.parse(startDateString, "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            endDate = DateUtil.parse(endDateString, "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        }
       return baseMapper.selectDataMap(startDate,endDate);
    }


}

分析:

1.服务实现类,实现xd-qm包xd-qm-api下:com.crrcdt.xd.qm.api.Qde0010Service中的方法接口
2.Qde0010ServiceImpl继承BaseServiceImpl<Qde0010Mapper, Qde0010, Map<String,Object>>类,BaseServiceImpl类由Generator代码生成器生成在com.crrcdt.common.base.BaseServiceImpl中
3.多参数时使用Map,返回值调用com.crrcdt.xd.qm.mapper.Qde0010Mapper中的selectDataMap()方法,com.crrcdt.xd.qm.mapper.Qde0010Mapper

xd-qm包xd-qm-service下:com.crrcdt.xd.qm.mapper.Qde0010Mapper

package com.crrcdt.xd.qm.mapper;

import com.crrcdt.common.base.BaseMapper;
import com.crrcdt.xd.qm.model.Qde0010;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;

/**
 * <p>
  * 质量模块-质量缺陷等级 Mapper 接口
 * </p>
 *
 * @author Chova
 */
public interface Qde0010Mapper extends BaseMapper<Qde0010> {

    List<Qde0010> selectDataMap(@Param(value = "startDate") Date startDate, @Param(value = "endDate") Date endDate);
}

分析:

1.定义selectDataMap方法,类继承BaseMapper类由Generator代码生成器生成在com.crrcdt.common.base.BaseMapper中,这个类是继承MybatisPlus框架的BaseMapper类
2.通过标注@Param注解获取数据库中QDE0010表startDate和endDate的值(Mybatis框架)

xd-qm包xd-qm-service下:com.crrcdt.xd.qm.mapper.xml.Qde0010Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.crrcdt.xd.qm.mapper.Qde0010Mapper">

	<!-- 开启二级缓存 -->
	<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

	<!-- 通用查询映射结果 -->
	<resultMap id="BaseResultMap" type="com.crrcdt.xd.qm.model.Qde0010">
	<result column="ID" property="id" />
	<result column="DEL_FLAG" property="delFlag" />
	<result column="REMARKS" property="remarks" />
	<result column="CREATE_BY" property="createBy" />
	<result column="CREATE_DATE" property="createDate" />
	<result column="UPDATE_BY" property="updateBy" />
	<result column="UPDATE_DATE" property="updateDate" />
		<result column="TENANT_ID" property="tenantId" />
		<result column="LEVELS" property="levels" />
		<result column="NAME" property="name" />
		<result column="UNQUALIFIED_TYPE" property="unqualifiedType" />
		<result column="SERIAL_NUMBER" property="serialNumber" />
	</resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
	ID AS id,
	DEL_FLAG AS delFlag,
	REMARKS AS remarks,
	CREATE_BY AS createBy,
	CREATE_DATE AS createDate,
	UPDATE_BY AS updateBy,
	UPDATE_DATE AS updateDate,
        TENANT_ID, LEVELS, NAME, UNQUALIFIED_TYPE, SERIAL_NUMBER
    </sql>
	<select id="selectDataMap" resultType="com.crrcdt.xd.qm.model.Qde0010">
		SELECT n.DEFECT_LEVELS AS  serialNumber, COUNT(1) AS num
		FROM NCR0020 n
		WHERE n.DEL_FLAG='0'
		<if test="startDate != null and endDate != null">
			AND  n.CREATE_DATE BETWEEN #{startDate} AND #{endDate}
		</if>
		GROUP BY n.DEFECT_LEVELS
	</select>
</mapper>

分析:

1.定义Mapper空间
2.开启二级缓存,定义通用查询的映射结果
3.定义通用查询结果列
<select id="selectDataMap" resultType="com.crrcdt.xd.qm.model.Qde0010">
		SELECT n.DEFECT_LEVELS AS  serialNumber, COUNT(1) AS num
		FROM NCR0020 n
		WHERE n.DEL_FLAG='0'
		<if test="startDate != null and endDate != null">
			AND  n.CREATE_DATE BETWEEN #{startDate} AND #{endDate}
		</if>
		GROUP BY n.DEFECT_LEVELS
</select>

xd-qm包xd-qm-service下:com.crrcdt.xd.qm.controller.Qde0010Controller

package com.crrcdt.xd.qm.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.crrcdt.common.base.BaseController;
import com.crrcdt.common.base.BaseModelBuilder;
import com.crrcdt.common.base.PageResult;
import com.crrcdt.common.base.Pagination;
import com.crrcdt.common.validator.ListSizeValidator;
import com.crrcdt.common.validator.Valid;
import com.crrcdt.sys.util.WebUtil;
import com.crrcdt.xd.qm.api.Qde0010Service;
import com.crrcdt.xd.qm.common.constant.XdResult;
import com.crrcdt.xd.qm.common.constant.XdResultConstant;
import com.crrcdt.xd.qm.model.Qde0010;
import com.google.common.base.Optional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.*;
import org.testng.collections.Lists;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 质量模块-质量缺陷等级管理 Controller
 * </p>
 *
 * @author chova
 */
@EnableEurekaClient
@RestController
@Api(value = "质量模块-质量缺陷等级管理", description = "质量模块-质量缺陷等级管理")
@RequestMapping("/v1/xd/qde0010")
public class Qde0010Controller extends BaseController {

        private static Logger logger = LoggerFactory.getLogger(Qde0010Controller.class);

        @Reference
        private Qde0010Service qde0010Service;


        /**
         * Create object.
         * @return the object
         */
        @ApiOperation(value = "新增质量模块-质量缺陷等级信息",response = Qde0010.class)
        @RequestMapping(value = "/", method = RequestMethod.POST)
        public Object create(@RequestBody Qde0010 qde0010) {
            qde0010.setCurrentUserId(WebUtil.getCurrentUserId());
            return qde0010Service.addOne(qde0010);
        }


        /**
         * Delete object.
         * @return the object
         */
        @ApiOperation(value = "删除质量模块-质量缺陷等级信息")
        @RequestMapping(value = "/{qde0010Id}", method = RequestMethod.DELETE)
        public Object delete(@PathVariable("qde0010Id") String qde0010Id) {
            int count = qde0010Service.removeAll(
                    Lists.newArrayList(qde0010Id),
                    BaseModelBuilder.create(Qde0010.class, WebUtil.getCurrentUserId())
            );
            return new XdResult(count);
        }


        /**
         * Batch delete objects.
         * @return the object
         */
        @ApiOperation(value = "批量删除质量模块-质量缺陷等级信息")
        @RequestMapping(value = "/", method = RequestMethod.DELETE)
        public Object batchDelete(String[] qde0010Ids) {
            Valid valid = new Valid().on(qde0010Ids, new ListSizeValidator("质量模块-质量缺陷等级"));
            if (valid.isError()) {
                    return valid.errorInfo();
            }
            int count = qde0010Service.removeAll(
                    Lists.newArrayList(qde0010Ids),
                    BaseModelBuilder.create(Qde0010.class,WebUtil.getCurrentUserId())
            );
            return XdResult.batchResultCreate(count, qde0010Ids.length);
        }

        /**
         * Update object.
         * @return the object
         */
        @ApiOperation(value = "修改质量模块-质量缺陷等级信息",response = Qde0010.class)
        @RequestMapping(value = "/", method = RequestMethod.PUT)
        public Object update(@RequestBody Qde0010 qde0010) {
            qde0010.setCurrentUserId(WebUtil.getCurrentUserId());
            int count = qde0010Service.updateSelective(qde0010);
            return new XdResult(XdResultConstant.SUCCESS, count);
        }

        /**
         * Select list of object.
         * @return the object
         */
        @ApiOperation(value = "质量模块-质量缺陷等级列表--分页",response = Qde0010.class)
        @RequestMapping(value = "/", method = RequestMethod.GET)
        public Object list(Pagination pagination, Qde0010 qde0010) {
            PageResult<Qde0010> lsResult = qde0010Service.selectList(qde0010, pagination);
            return new XdResult(XdResultConstant.SUCCESS, lsResult);
        }

        /**
         * Get one som overhaul eneity.
         * @return the Qdc 0010
         */
        @ApiOperation(value = "质量模块-质量缺陷等级信息")
        @RequestMapping(value = "/{qde0010Id}", method = RequestMethod.GET)
        public Object getQde0010(@PathVariable("qde0010Id") String qde0010Id) {
            Optional<Qde0010> qde0010 = qde0010Service.getById(qde0010Id);
            return new XdResult(
                    qde0010.isPresent() ? XdResultConstant.SUCCESS : XdResultConstant.FAILED,
                    qde0010.or(new Qde0010())
            );
        }

        /**
         * Get one som overhaul eneity.
         * @return the isTrue
         */
        @ApiOperation(value = "验证重复key为数据库字段(下划线命名),value为要验证的值")
        @RequestMapping(value = "/count", method = RequestMethod.GET)
        public Object getQde0010Count(String key, String value,String recordId) {
            int count = qde0010Service.selectCount(key,value ,recordId);
            return count > 0 ? super.ResultValidator("该值已存在") : super.ResultSuccess("该值不存在");
        }

        /**
         * Get one som overhaul eneity.
         * @return the isTrue
         */
        @ApiOperation(value = "下拉选(只返回编码--名称)")
        @RequestMapping(value = "/select", method = RequestMethod.GET)
        public Object select() {
            List<String> lsResult = new ArrayList<>();
            qde0010Service.selectListNoPageInfo(new Qde0010()).forEach(qde0010 ->
                  lsResult.add(qde0010.getLevels()+"--"+qde0010.getName()));
            return new XdResult(XdResultConstant.SUCCESS, JSON.toJSONString(lsResult));
        }
    /**
     * Get one som overhaul eneity.
     *
     * @param startDate the Ncr 0020 DataSourceKey
     * @param endDate the Ncr 0020 Value
     * @return the isTrue
     */
    @ApiOperation(value = "获取缺陷统计报表")
    @RequestMapping(value = "/dataMap", method = RequestMethod.GET)
    public Object dataMap(String startDate ,String endDate) {
        return super.ResultSuccess(qde0010Service.getDataMap(startDate,endDate));
    }

}

分析:

1.@EnableEurekaClient	开启EureKa客户端,服务治理与注册中心
2.@Reference引入service接口
3.创建质量模块中的缺陷等级信息
@ApiOperation(value = "新增质量模块-质量缺陷等级信息",response = Qde0010.class)
        @RequestMapping(value = "/", method = RequestMethod.POST)
        public Object create(@RequestBody Qde0010 qde0010) {
            qde0010.setCurrentUserId(WebUtil.getCurrentUserId());
            return qde0010Service.addOne(qde0010);
        }

-----------------------------------------------------------------------------

    public BaseResult addOne(Record record) {
        if (record != null) {
            Date nowDate = new Date();
            record.setUpdateDate(nowDate);
            record.setCreateDate(nowDate);
            record.setCreateBy(record.currentUserId);
            record.setUpdateBy(record.currentUserId);
            record.setDelFlag("0");

            try {
                DynamicDataSource.setDataSource("masterDataSource");
                int result = ((BaseMapper)this.baseMapper).insert(record);
                if (result > 0) {
                    return BaseResult.succe***esultCreate(record);
                }
            } catch (Exception var4) {
                this.logger.error(var4.toString());
            }
        }

        DynamicDataSource.clearDataSource();
        return BaseResult.failResultCreate("错误!请刷新重试");
    }

@ApiOperation(value = "删除质量模块-质量缺陷等级信息")
        @RequestMapping(value = "/{qde0010Id}", method = RequestMethod.DELETE)
        public Object delete(@PathVariable("qde0010Id") String qde0010Id) {
            int count = qde0010Service.removeAll(
                    Lists.newArrayList(qde0010Id),
                    BaseModelBuilder.create(Qde0010.class, WebUtil.getCurrentUserId())
            );
            return new XdResult(count);
        }
-----------------------------------------------------------------------------------------------------------------------------------------------
public int removeAll(List<String> ids, Record record) {
        if (ids != null && !ids.isEmpty()) {
            try {
                record.setDelFlag("1");
                record.setUpdateDate(new Date());
                record.setUpdateBy(record.getCurrentUserId());
                DynamicDataSource.setDataSource("masterDataSource");
                return ((BaseMapper)this.baseMapper).update(record, Condition.create().in("id", ids));
            } catch (Exception var4) {
                this.logger.error(var4.toString());
                DynamicDataSource.clearDataSource();
                return 0;
            }
        } else {
            return 0;
        }
    }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
	// 调用XdResult()方法
	public XdResult(int successCount) {
        super();
        if(successCount>0){
            this.setCode(1);
            this.setMessage("成功");
        }else {
            this.setCode(0);
            this.setMessage("失败");
        }

        this.setData("");
    }
@ApiOperation(value = "批量删除质量模块-质量缺陷等级信息")
        @RequestMapping(value = "/", method = RequestMethod.DELETE)
        public Object batchDelete(String[] qde0010Ids) {
            Valid valid = new Valid().on(qde0010Ids, new ListSizeValidator("质量模块-质量缺陷等级"));
            if (valid.isError()) {
                    return valid.errorInfo();
            }
            int count = qde0010Service.removeAll(
                    Lists.newArrayList(qde0010Ids),
                    BaseModelBuilder.create(Qde0010.class,WebUtil.getCurrentUserId())
            );
            return XdResult.batchResultCreate(count, qde0010Ids.length);
        }
--------------------------------------------------------------------------------------------------------------------------------------------------------
public int removeAll(List<String> ids, Record record) {
        if (ids != null && !ids.isEmpty()) {
            try {
                record.setDelFlag("1");
                record.setUpdateDate(new Date());
                record.setUpdateBy(record.getCurrentUserId());
                DynamicDataSource.setDataSource("masterDataSource");
                return ((BaseMapper)this.baseMapper).update(record, Condition.create().in("id", ids));
            } catch (Exception var4) {
                this.logger.error(var4.toString());
                DynamicDataSource.clearDataSource();
                return 0;
            }
        } else {
            return 0;
        }
    }
@ApiOperation(value = "修改质量模块-质量缺陷等级信息",response = Qde0010.class)
        @RequestMapping(value = "/", method = RequestMethod.PUT)
        public Object update(@RequestBody Qde0010 qde0010) {
            qde0010.setCurrentUserId(WebUtil.getCurrentUserId());
            int count = qde0010Service.updateSelective(qde0010);
            return new XdResult(XdResultConstant.SUCCESS, count);
        }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
public int updateSelective(Record record) {
        try {
            DynamicDataSource.setDataSource("masterDataSource");
            record.setUpdateDate(new Date());
            record.setUpdateBy(record.currentUserId);
            record.setCreateDate((Date)null);
            record.setCreateBy((String)null);
            return ((BaseMapper)this.baseMapper).updateById(record);
        } catch (Exception var3) {
            this.logger.error(var3.toString());
            DynamicDataSource.clearDataSource();
            return 0;
        }
    }
@ApiOperation(value = "质量模块-质量缺陷等级列表--分页",response = Qde0010.class)
        @RequestMapping(value = "/", method = RequestMethod.GET)
        public Object list(Pagination pagination, Qde0010 qde0010) {
            PageResult<Qde0010> lsResult = qde0010Service.selectList(qde0010, pagination);
            return new XdResult(XdResultConstant.SUCCESS, lsResult);
        }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
public PageResult<Record> selectList(Record record, Pagination pagination) {
        BaseModelSearch baseModelSearch = BaseModelSearch.create(record, pagination);
        return this.doSelectCore(baseModelSearch);
    }
 @ApiOperation(value = "质量模块-质量缺陷等级信息")
        @RequestMapping(value = "/{qde0010Id}", method = RequestMethod.GET)
        public Object getQde0010(@PathVariable("qde0010Id") String qde0010Id) {
            Optional<Qde0010> qde0010 = qde0010Service.getById(qde0010Id);
            return new XdResult(
                    qde0010.isPresent() ? XdResultConstant.SUCCESS : XdResultConstant.FAILED,
                    qde0010.or(new Qde0010())
            );
        }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
public Optional<Record> getById(String id) {
        if (StringUtils.isBlank(id)) {
            return Optional.absent();
        } else {
            try {
                DynamicDataSource.setDataSource("slaveDataSource");

                try {
                    Record result = ((BaseMapper)this.baseMapper).getByPK(id);
                    if (result != null) {
                        SysRefConvertFactory.getSysRefConvert().convertSysRef(result);
                    }

                    return Optional.fromNullable(result);
                } catch (BindingException var4) {
                    Record result = (BaseModel)((BaseMapper)this.baseMapper).selectById(id);
                    if (result != null) {
                        SysRefConvertFactory.getSysRefConvert().convertSysRef(result);
                    }

                    return Optional.fromNullable(result);
                }
            } catch (Exception var5) {
                this.logger.error(var5.toString());
                DynamicDataSource.clearDataSource();
                return Optional.absent();
            }
        }
    }
 @ApiOperation(value = "验证重复key为数据库字段(下划线命名),value为要验证的值")
        @RequestMapping(value = "/count", method = RequestMethod.GET)
        public Object getQde0010Count(String key, String value,String recordId) {
            int count = qde0010Service.selectCount(key,value ,recordId);
            return count > 0 ? super.ResultValidator("该值已存在") : super.ResultSuccess("该值不存在");
        }
-----------------------------------------------------------------------------------------------------------------------------
public int selectCount(String key, String value, String recordId) {
        if (StringUtils.isEmpty(recordId)) {
            return this.selectCount(key, value);
        } else {
            try {
                DynamicDataSource.setDataSource("slaveDataSource");
                return ((BaseMapper)this.baseMapper).selectCount((new EntityWrapper()).eq(key, value).ne("ID", recordId));
            } catch (Exception var5) {
                this.logger.error(var5.toString());
                DynamicDataSource.clearDataSource();
                return 0;
            }
        }
    }
@ApiOperation(value = "下拉选(只返回编码--名称)")
        @RequestMapping(value = "/select", method = RequestMethod.GET)
        public Object select() {
            List<String> lsResult = new ArrayList<>();
            qde0010Service.selectListNoPageInfo(new Qde0010()).forEach(qde0010 ->
                  lsResult.add(qde0010.getLevels()+"--"+qde0010.getName()));
            return new XdResult(XdResultConstant.SUCCESS, JSON.toJSONString(lsResult));
        }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
public List<Record> selectListNoPageInfo(Record record) {
        BaseModelSearch baseModelSearch = BaseModelSearch.create(record, new Pagination(-1, -1));
        return this.doSelectCoreNoPage(baseModelSearch);
    }
前端(web-ui)

mock包下面的:mock.QM.QDE0010.js

mock包下面的:mock.QM.QDE0010.js

import { mock } from 'mockjs';
import { dataList } from '../../src/utils/PageResult';

const getQde0010 = {
  params: {},
  body: dataList(
    mock({
      'data|10': [
        {
          id: '@id',
          distCode: '123',
          distName: '名称',
        },
      ],
    })
  ),
};

export { getQde0010 };

分析:

1.分页数据结果,dataList调用src/utils/PageResult中的方法
2.export修饰的表示该方法可以被外部调用
export function dataList(mockData) {
  return Object.assign(mockData, {
    data: {
      dataList: mockData.data,
      pageNum: 1,
      pageSize: 10,
      total: 10,
      pages: 1,
      offsetIndex: 0,
    },
  });
}

src包下面的:src.models.qm.qde0010.js

src包下面的models包:src.models.qm.qde0010.js

import { pagination } from '../../utils/PageResult';
import { searchAllocate, saveModel } from '../../utils/model';
import { deleteRequest, postRequest, putRequest, search } from '../../utils/request';
/**
 * 缺陷等级
 * @author chova
 */
// 查询表单字段
const searchData = pagination({
  name: '', //  名称
});

const formData = {
  code: '', //  代码
  name: '', //  名称
};

export default {
  namespace: 'qde0010',

  state: {
    list: [],
    selectedRowKeys: [],
    loading: true,
    searchData,
    formData,
  },

  effects: {
    *save(_, { put, select, call }) {
      // 获取 state 里面formData的数据
      const params = yield select(state => state.qde0010.formData);
      const paramsLast = searchAllocate(params, {});
      const response = yield call(saveModel, addQde0010, putQde0010, paramsLast);
      // 重新加载fetch方法
      yield put({
        type: 'fetch',
      });
      return response;
    },

    *fetch(_, { put, call, select }) {
      const params = yield select(state => state.qde0010.searchData); // 获取searchData中的值
      const paramsLast = searchAllocate(params, {});
      // 解析参数使之转化成所需格式
      const response = yield call(getQde0010, paramsLast); // 通过接口加载数据(传递参数)
      // 更新list
      yield put({
        type: 'updateTable',
        payload: response,
      });
      return response;
    },

    *delete({ payload }, { put, call }) {
      const response = yield call(deleteQde0010, payload.id);
      yield put({
        type: 'fetch',
      });
      return response;
    },
  },
  reducers: {
    updateLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },

    updateTable(state, { payload }) {
      return {
        ...state,
        loading: false,
        list: payload, // 给list赋值
      };
    },

    updateFormData(state, { payload }) {
      // 通过传递过来的id从中间变量中获取当前行数据 放到formData中
      return {
        ...state,
        formData: payload,
      };
    },

    /**
     * 更改formData中的值
     */
    changeFormFields(state, { payload }) {
      const data = payload || formData;
      return {
        ...state,
        formData: {
          ...state.formData,
          ...data,
        },
      };
    },

    replaceFormFields(state, { payload }) {
      return {
        ...state,
        formData: payload || formData,
      };
    },

    changeSearchFormFields(state, { payload }) {
      const data = payload || searchData;
      return {
        ...state,
        searchData: {
          ...state.searchData,
          pageNum: 1,
          ...data,
        },
      };
    },

    resetToDefaultStore(state, { payload }) {
      return {
        ...state,
        searchData: payload || searchData,
      };
    },
  },
};
async function getQde0010(params) {
  return search('/api/xd/qm/v1/xd/qde0010/', params);
}
async function addQde0010(params) {
  return postRequest('/api/xd/qm/v1/xd/qde0010/', params);
}
async function putQde0010(params) {
  return putRequest('/api/xd/qm/v1/xd/qde0010/', params);
}
async function deleteQde0010(params) {
  return deleteRequest(`/api/xd/qm/v1/xd/qde0010/${params}`);
}

分析:

1.定义页面数据的操作解析方法
2.定义传递参数加载数据的接口,与后端交互
export const pagination = searchData =>
  Object.assign(
    {
      pageNum: 1,
      pageSize: 20,
      sortField: 'update_date',
      sortOrder: 'descend',
    },
    searchData
  );
export const destructuring = (params, defaultString = false) =>
  mapValues(params, item => {
    if (defaultString) {
      return getFormItemValue(item) || '';
    }
    const result = item && (typeof item === 'object' && !Array.isArray(item)) ? item.value : item;
    return removeSearchFLSpace(result);
  });


export function searchAllocate(payload, option = {}) {
  const params = destructuring(payload);
  try {
    Object.entries(option).forEach(([name, allocated]) => {
      let value = params[name];
      if (value && value.length > 0) {
        value = [
          moment(Date.parse(`${value[0].format('YYYY-MM-DD')} 00:00:00`)),
          moment(Date.parse(`${value[1].format('YYYY-MM-DD')} 23:59:59`)),
        ];
        // TODO: 数组验证 适用性扩充
        allocated.forEach((item, el) => {
          params[item] = value[el];
        });
        params[name] = null;
      }
    });
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error('搜索项配置异常!请检查 Effects 配置', e);
  }
  return doParseMomentType(params);
}
export async function saveModel(addApi, putApi, params) {
  if (!params) {
    return {
      code: 0,
      message: '错误!未填写相应字段',
      data: {},
    };
  }
  const deParams = doParseMomentType(destructuring(params));
  let response;
  if (params.id) {
    response = await putApi(deParams);
  } else {
    response = await addApi({ ...deParams, id: undefined });
  }
  return response;
}
	deleteRequest = (url, params = '') => {
    return this.request(`${url}${params}`, {
      method: 'DELETE',
    });
  };


	postRequest = (url, params = {}, hintMessage) => {
    return this.request(
      url,
      {
        method: 'POST',
        body: params,
      },
      hintMessage
    );
  };


	putRequest = (url, params = {}, hintMessage) => {
    return this.request(
      url,
      {
        method: 'PUT',
        body: params,
      },
      hintMessage
    );
  };

search = (url, formRefsData) => {
    let jsonData;
    if (window.FormData && formRefsData instanceof FormData) {
      jsonData = {};
      for (const [key, value] of formRefsData.entries()) {
        jsonData[key] = value;
      }
    } else {
      jsonData = formRefsData;
    }
    return this.request(`${url}${stringify(jsonData)}`);
  };


export const {
  submit,
  search,
  queryEntity,
  postRequest,
  putRequest,
  deleteRequest,
  multDeleteRequest,
} = request;

src包下:src.routes.Qm.Qde0010包

src.routes.Qm.Qde0010.Qde0010.js
import { Table, Card, Icon, Tooltip, Popconfirm, Divider } from 'antd';
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Once from 'lodash-decorators/once';
import Bind from 'lodash-decorators/bind';
import Debounce from 'lodash-decorators/debounce';
import { formValid } from '../../../utils/FormRules';
import LButton from '../../../components/LButton/LButton';
import Qde0010Search from './Qde0010Search';
import Qde0010Form from './Qde0010Form';
import { dateFormat } from '../../../utils/utils';

/**
 * 缺陷等级
 * @author chova
 */
@connect(state => ({
  qde0010: state.qde0010,
  selectData: state.selectData,
}))
export default class Qde0010 extends PureComponent {
  componentDidMount() {
    this.props.dispatch({
      type: 'qde0010/fetch',
    });
    this.getUserSdSelectData();
  }

  @Once
  getUserSdSelectData = () => {
    this.props.dispatch({
      type: 'selectData/fetch',
      payload: { type: 'userSd' },
    });
  };

  handlePaginationSizeChange = (_, pageSize, pageNum = 1) => {
    this.props.dispatch({
      type: 'qde0010/changeSearchFormFields',
      payload: { pageNum, pageSize },
    });
    this.doPageSearch();
  };

  handleCancel = () => {
    this.props.dispatch({
      type: 'qde0010/replaceFormFields',
    });
  };

  saveData = async () => {
    await formValid(this.modelFormRefsAdd);
    const respone = this.props.dispatch({
      type: 'qde0010/save',
    });
    this.props.dispatch({
      type: 'dialog/close',
      payload: '缺陷等级',
    });
    return respone;
  };

  // 刷新
  handleRefresh = async () => {
    await this.props.dispatch({
      type: 'qde0010/updateLoading',
      payload: true,
    });
    this.doPageSearch();
  };

  handleTableChange = (pagination, filters, sorter) => {
    this.props.dispatch({
      type: 'qde0010/changeSearchFormFields',
      payload: {
        sortField: sorter?.field || 'update_date',
        sortOrder: sorter?.order || 'descend',
        pageNum: pagination?.current || '',
        pageSize: pagination?.pageSize || '',
        total: pagination?.total || '',
        ...filters,
      },
    });
    this.doPageSearch();
  };

  // 分页
  handlePaginationChange = pageNum => {
    this.props.dispatch({
      type: 'qde0010/changeSearchFormFields',
      payload: { pageNum },
    });
    this.doPageSearch();
  };

  handleEdit = record => {
    this.props.dispatch({
      type: 'qde0010/updateFormData',
      payload: record,
    });
  };

  deleteData = record => {
    this.props.dispatch({
      type: 'qde0010/delete',
      payload: record,
    });
  };

  handleNavigation = () => {
    return (
      <div>
        <LButton text="新建" linkDialog="缺陷等级信息" />
        <LButton text="刷新" onClick={() => this.handleRefresh()} />
      </div>
    );
  };

  @Bind()
  @Debounce(200)
  doPageSearch() {
    this.props.dispatch({
      type: 'qde0010/fetch',
    });
  }

  render() {
    const { loading, list } = this.props.qde0010;
    const { userSd } = this.props.selectData;
    const column = [
      {
        title: '等级',
        dataIndex: 'levels',
        width: 200,
        sorter: true,
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 200,
      },
      {
        title: '更改人',
        dataIndex: 'updateBy ',
        render: updateBy => userSd?.[updateBy] || '',
        width: 200,
      },
      {
        title: '更改时间',
        dataIndex: 'updateDate',
        render: updateDate => dateFormat(updateDate, true),
        sorter: true,
        width: 200,
      },
      {
        title: '操作',
        width: 100,
        render: record => (
          <div>
            <Tooltip title="编辑">
              <LButton
                iconOnly
                iconType="edit"
                linkDialog="缺陷等级信息"
                style={{ color: '#6abf47' }}
                onClick={() => this.handleEdit(record)}
              />
            </Tooltip>
            <Divider type="vertical" />
            <Popconfirm
              title="确定删除?"
              onConfirm={() => this.deleteData(record)}
              okText="是"
              cancelText="否"
            >
              <span>
                <Icon type="delete" style={{ color: '#ff3673', fontSize: 20, cursor: 'pointer' }} />
              </span>
            </Popconfirm>
          </div>
        ),
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current: list?.data?.pageNum || [],
      pageSize: list?.data?.pageSize || [],
      total: list?.data?.total || [],
      showTotal: total => `总计 ${total} 条数据`,
      onChange: this.handlePaginationChange,
      onShowSizeChange: this.handlePaginationSizeChange,
    };
    const contentHeight = document.getElementById('searchCard')?.offsetHeight;
    return (
      <div>
        <Qde0010Form />
        <Card id="searchCard" title="查询条件" style={{ marginBottom: 8 }}>
          <Qde0010Search />
        </Card>
        <Card title="缺陷等级列表" loading={loading} extra={this.handleNavigation()}>
          <Table
            bordered
            rowKey="id"
            columns={column}
            size="small"
            dataSource={list?.data?.dataList || []}
            scroll={{
              x: column.reduce((sum, item) => sum + item?.width || 0, 0),
              y: `calc(100vh - 300px - ${contentHeight}px)`,
            }}
            pagination={paginationProps}
            onChange={this.handleTableChange}
          />
        </Card>
      </div>
    );
  }
}

分析:

1.缺陷等级表的列表页面
src.routes.Qm.Qde0010.Qde0010Form.js
import React, { PureComponent } from 'react';
import { Form, Input } from 'antd';
import { connect } from 'dva';
import LFormItem from '../../../components/ModalButton/LFormItem';
import Rules from '../../../utils/FormRules';
import { genMapPropsToFields } from '../../../utils/model';
import LForm from '../../../components/ModalButton/LForm';

/**
 * 缺陷等级
 * @author chova
 */
const mapPropsToFields = genMapPropsToFields('qde0010');

@connect(state => ({
  qde0010: state.qde0010,
}))
@Form.create({
  mapPropsToFields,
  onFieldsChange(props, fields) {
    props.dispatch({
      type: 'qde0010/changeFormFields',
      payload: fields,
    });
  },
})
export default class Qde0010Form extends PureComponent {
  render() {
    const { form } = this.props;
    const { getFieldDecorator: field } = form;
    return (
      <LForm
        labelCol={{ span: 7 }}
        form={form}
        title="缺陷等级信息"
        maskClosable={false}
        onOk="qde0010/save"
        onCancel="qde0010/replaceFormFields"
      >
        <LFormItem label="等级">
          {field('levels', {
            rules: new Rules().required().end(),
          })(<Input placeholder="请输入等级" />)}
        </LFormItem>
        <LFormItem label="名称">
          {field('name', {
            rules: new Rules().required().end(),
          })(<Input placeholder="请输入名称" />)}
        </LFormItem>
      </LForm>
    );
  }
}

分析:

1.新建缺陷等级项点的缺陷等级表界面
export const genMapPropsToFields = (namespace, stateName = 'formData') => {
  return function mapPropsToFieldsCore(props) {
    const formData = props?.[namespace]?.[stateName] || props?.[stateName];
    return mapValues(formData, value =>
      Form.createFormField(isFieldsValue(value) ? value : { value })
    );
  };
};
namespace:reduce命名空间
stateName:store内映射表单值,默认为formData
src.routes.Qm.Qde0010.Qde0010Search.js
import React, { PureComponent } from 'react';
import { Form, Input, Row, Col, Button } from 'antd';
import Bind from 'lodash-decorators/bind';
import Debounce from 'lodash-decorators/debounce';
import { connect } from 'dva';
import { genMapPropsToFields } from '../../../utils/model';

/**
 * 缺陷等级
 * @author chova
 */
const mapPropsToFields = genMapPropsToFields('qde0010', 'searchData');
@connect(state => ({
  qde0010: state.qde0010,
}))
@Form.create({
  mapPropsToFields,
  onFieldsChange(props, fields) {
    props.dispatch({
      type: 'qde0010/changeSearchFormFields',
      payload: fields,
    });
  },
})
export default class Qde0010Search extends PureComponent {
  componentWillUnmount() {
    this.props.dispatch({
      type: 'qde0010/resetToDefaultStore',
    });
  }

  handleSubmit = e => {
    if (e && e.preventDefault) {
      e.preventDefault();
    }
    this.doPageSearch();
  };

  handleReset = () => {
    this.props.dispatch({
      type: 'qde0010/resetToDefaultStore',
    });
    this.doPageSearch();
  };

  @Bind()
  @Debounce(200)
  doPageSearch() {
    this.props.dispatch({
      type: 'qde0010/fetch',
    });
  }

  render() {
    const { form } = this.props;
    const { getFieldDecorator: field } = form;
    const simpleSearch = (
      <Row gutter={32}>
        <Col span={8}>{field('levels')(<Input addonBefore="等级" placeholder="请输入等级" />)}</Col>
        <Col span={8}>{field('name')(<Input addonBefore="名称" placeholder="请输入名称" />)}</Col>
        <Button.Group style={{ float: 'right', marginRight: 16 }}>
          <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>
            查询
          </Button>
          <Button htmlType="reset" onClick={this.handleReset}>
            重置
          </Button>
        </Button.Group>
      </Row>
    );
    return (
      <Form onSubmit={this.handleSubmit}>
        <div>{simpleSearch}</div>
      </Form>
    );
  }
}

分析:

1.列表数据搜索界面

src的common包下:src.common.router.js

 '/qm/qde0010': {
      component: dynamicWrapper(app, [], () => import('../routes/Qm/Qde0010/Qde0010')),
    },

分析:

1.配置路由接口路径

web-ui项目包下:.roadhogrc.mock.js

'GET /apiMock/project/qde0010': req('缺陷等级')(require('./mock/QM/QDE0010').getQde0010),

分析:

1.mock数据声明的模拟接口以及获取的路径

标签:return,qde0010,西电,xd,value,MES,import,qm,NCR
来源: https://blog.51cto.com/u_15185289/2783898