ezhizao_zx 4 月之前
父节点
当前提交
6c365a52b8

+ 12 - 0
src/main/java/cn/ezhizao/framework/config/WebSocketConfig.java

@@ -0,0 +1,12 @@
+package cn.ezhizao.framework.config;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.socket.server.standard.ServerEndpointExporter;
+
+@Configuration
+public class WebSocketConfig {
+    @Bean
+    public ServerEndpointExporter serverEndpointExporter() {
+        return new ServerEndpointExporter();
+    }
+}

+ 9 - 0
src/main/java/cn/ezhizao/framework/domo/SubStringDome.java

@@ -0,0 +1,9 @@
+package cn.ezhizao.framework.domo;
+
+public class SubStringDome {
+    public static void main(String[] args) {
+        String inputCode = "D24729910021";
+        System.out.println(inputCode.substring(0, 8));
+        System.out.println(inputCode.substring(8, 11));
+    }
+}

+ 77 - 0
src/main/java/cn/ezhizao/project/business/controller/BizBeforeCheckoutVerifyController.java

@@ -8,13 +8,20 @@ import cn.ezhizao.framework.web.domain.AjaxResult;
 import cn.ezhizao.framework.web.page.TableDataInfo;
 import cn.ezhizao.project.business.domain.*;
 import cn.ezhizao.project.business.service.*;
+import cn.hutool.core.io.IoUtil;
 import cn.hutool.json.JSONArray;
 import cn.hutool.json.JSONObject;
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.excel.write.metadata.WriteSheet;
+import com.alibaba.excel.write.metadata.fill.FillConfig;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
+import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.util.*;
@@ -60,6 +67,8 @@ public class BizBeforeCheckoutVerifyController extends BaseController {
     private IBizLotTechnologicalProcessService bizLotTechnologicalProcessService;
     @Resource
     private IBizLotTechnologicalProcessDetailService bizLotTechnologicalProcessDetailService;
+    @Value("${file.excelTemplate.url}")
+    private  String templatePath;
 
     /**
      * 查询报工列表
@@ -162,6 +171,74 @@ public class BizBeforeCheckoutVerifyController extends BaseController {
         return AjaxResult.success(bizProcessInspecionList.stream().map(BizProcessInspecion::getId).collect(Collectors.toList()));
     }
 
+    @Log(title = "查询外协结算审核列表", businessType = BusinessType.EXPORT)
+    @PostMapping("/export")
+    public void export(HttpServletResponse response, BizProcessInspecion bizProcessInspecion) throws NoSuchFieldException, IllegalAccessException, IOException {
+        List<BizProcessInspecion> list = bizProcessInspecionService.getVerifyList(bizProcessInspecion);
+        List<BizDaywork> dayworks = bizDayworkService.query().in("id", list.isEmpty() ? Collections.singletonList(0L) : list.stream().map(BizProcessInspecion::getDayworkId).collect(Collectors.toList())).list();
+        List<BizOutsourcedOrderDetail> outsourcedOrderDetails = bizOutsourcedOrderDetailService.query().in("id", list.isEmpty() ? Collections.singletonList(0L) : list.stream().map(BizProcessInspecion::getOutsourceOrderDetailId).collect(Collectors.toList())).list();
+        List<BizReturnReceiptDetail> returnReceiptDetails = bizReturnReceiptDetailService.query().in("id", list.isEmpty() ? Collections.singletonList(0L) : list.stream().map(BizProcessInspecion::getReturnReceiptDetailId).collect(Collectors.toList())).list();
+        List<BizSupplier> suppliers = bizSupplierService.query().in("id", outsourcedOrderDetails.isEmpty() ? Collections.singletonList(0L) : outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getSupplierId).collect(Collectors.toList())).list();
+        list.forEach(l -> {
+            l.setDaywork(dayworks.stream().filter(v -> v.getId().equals(l.getDayworkId())).findFirst().orElse(new BizDaywork()));
+            l.setOutsourcedOrderDetail(outsourcedOrderDetails.stream().filter(v -> v.getId().equals(l.getOutsourceOrderDetailId())).findFirst().orElse(new BizOutsourcedOrderDetail()));
+            l.setReturnReceiptDetail(returnReceiptDetails.stream().filter(v -> v.getId().equals(l.getReturnReceiptDetailId())).findFirst().orElse(new BizReturnReceiptDetail()));
+            BizSupplier supplier = suppliers.stream().filter(e -> l.getOutsourcedOrderDetail() != null && e.getId().equals(l.getOutsourcedOrderDetail().getSupplierId())).findFirst().orElse(new BizSupplier());
+            l.setSupplierName(supplier.getName());
+            l.setMnemonicCode(supplier.getMnemonicCode());
+            Integer materialLoss = l.getOutsourcedOrderDetail().getProductNum() - l.getReturnReceiptDetail().getAuditNum();
+            l.setMaterialLoss(materialLoss);
+        });
+        String template = "processInspectionTemplate";
+        String templateFilePath =  templatePath + template + ".xlsx";
+        List<Map<String, Object>> exportList = new ArrayList<>();
+        list.forEach(l -> {
+            Arrays.stream(l.getProcessNames().split(",")).forEach(v -> {
+                Map<String, Object> value = new HashMap<>();
+                value.put("mnemonicCode", l.getMnemonicCode());
+                value.put("supplierName", l.getSupplierName());
+                value.put("productDescription", l.getProductDescription());
+                value.put("lotCode", l.getLotCode());
+                value.put("productNum", l.getOutsourcedOrderDetail().getProductNum());
+                value.put("auditNum", l.getReturnReceiptDetail().getAuditNum());
+                value.put("materialLoss", l.getMaterialLoss());
+                value.put("processName", v);
+                value.put("outsourceDate", l.getOutsourcedOrderDetail().getFormDate());
+                value.put("returnReceiptDate", l.getReturnReceiptDetail().getFormDate());
+                value.put("auditDate", l.getAuditStatus().equals(1) ? l.getUpdateTime() : null);
+//                value.put("balanceDate", l.getBalanceDate());
+                value.put("outsourcedOrderDetailFormCode", l.getOutsourcedOrderDetail().getFormCode());
+                value.put("returnReceiptDetailFormCode", l.getReturnReceiptDetail().getFormCode());
+                value.put("carrierNum", l.getOutsourcedOrderDetail().getCarrierNum());
+                value.put("auditStatus", l.getAuditStatus().equals(1) ? "已审核" : "未审核");
+                exportList.add(value);
+            });
+        });
+        com.alibaba.excel.ExcelWriter writer = EasyExcel.write(response.getOutputStream())
+                .withTemplate(templateFilePath)
+                .build();
+        WriteSheet firstSheet = EasyExcel.writerSheet(0).build();
+        FillConfig fillConfig = FillConfig.builder()
+                // 开启填充行 不开启是在一行覆盖,开启会创建新的行
+                .forceNewRow(true)
+                .build();
+        // 执行填充操作
+        writer.fill(exportList, fillConfig, firstSheet);
+        writer.finish();
+        response.setContentType("application/vnd.ms-excel;charset=utf-8");
+        //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
+        response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
+        ServletOutputStream out = null;
+        try {
+            out = response.getOutputStream();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        //此处记得关闭输出Servlet流
+        IoUtil.close(out);
+//        bizOutsourcedOrderService.exportTemplateProvinceAreaData(response, bizOutsourcedOrder);
+    }
+
     private void addBalanceCheckout(List<BizProcessInspecion> inspections, String authorization) {
         // HttpUtils.sentPostJson()
         // 获取外协商

+ 6 - 0
src/main/java/cn/ezhizao/project/business/domain/BizProcessInspecion.java

@@ -197,6 +197,12 @@ public class BizProcessInspecion extends BaseEntity
     private BizDaywork daywork;
     @TableField(exist = false)
     private String supplierName;
+    @TableField(exist = false)
+    private String mnemonicCode;
+    @TableField(exist = false)
+    private Integer materialLoss;
+    @TableField(exist = false)
+    private String processName;
 
     @TableField(exist = false)
     private String technicianCode;

+ 45 - 0
src/main/java/cn/ezhizao/project/websocket/ServerEncoder.java

@@ -0,0 +1,45 @@
+package cn.ezhizao.project.websocket;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.itextpdf.text.log.Logger;
+import com.itextpdf.text.log.LoggerFactory;
+
+import javax.websocket.EncodeException;
+import javax.websocket.Encoder;
+import javax.websocket.EndpointConfig;
+import java.util.HashMap;
+
+public class ServerEncoder implements Encoder.Text<HashMap> {
+    private static final Logger log = LoggerFactory.getLogger(ServerEncoder.class);
+
+    /**
+     * 这里的参数 hashMap 要和  Encoder.Text<T>保持一致
+     * @param hashMap
+     * @return
+     * @throws EncodeException
+     */
+    @Override
+    public String encode(HashMap hashMap) throws EncodeException {
+        /*
+         * 这里是重点,只需要返回Object序列化后的json字符串就行
+         * 你也可以使用gosn,fastJson来序列化。
+         * 这里我使用fastjson
+         */
+        try {
+            return JSONObject.toJSONString(hashMap);
+        }catch (Exception e){
+            log.error("",e);
+        }
+        return null;
+    }
+
+    @Override
+    public void init(EndpointConfig endpointConfig) {
+
+    }
+
+    @Override
+    public void destroy() {
+
+    }
+}

+ 150 - 0
src/main/java/cn/ezhizao/project/websocket/WebSocketUser.java

@@ -0,0 +1,150 @@
+package cn.ezhizao.project.websocket;
+
+import cn.ezhizao.project.business.domain.BizProcessInspecion;
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import javax.websocket.*;
+import javax.websocket.server.PathParam;
+import javax.websocket.server.ServerEndpoint;
+import java.io.IOException;
+import java.util.Date;
+import java.util.concurrent.ConcurrentHashMap;
+
+//前端请求的路径
+
+@ServerEndpoint(value = "/wsExport/{userId}", encoders = {ServerEncoder.class})
+@Component
+public class WebSocketUser {
+    private static final Logger log = LoggerFactory.getLogger(WebSocketUser.class);
+    /**
+     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
+     */
+    private static int onlineCount = 0;
+    /**
+     * concurrent包的线程安全,用来存放每个客户端对应的MyWebSocket对象。
+     */
+    private static ConcurrentHashMap<String, WebSocketUser> webSocketMap = new ConcurrentHashMap<>();
+    /**
+     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
+     */
+    private Session session;
+    /**
+     * 接收userId
+     */
+    private String userId = "";
+    private String type = "";
+
+//
+//    private static DataInformationServiceImpl dataInformationService;
+//    @Resource
+//    public void setDataInformationService(DataInformationServiceImpl dataInformationService) {
+//        WebSocketUser.dataInformationService = dataInformationService;
+//    }
+
+    /**
+     * 连接建立成功调用的方法
+     */
+    @OnOpen
+    public void onOpen(Session session, @PathParam("userId") String userId) {
+        this.session = session;
+        this.userId = userId;
+        this.type = type;
+        if (webSocketMap.containsKey(userId)) {
+            webSocketMap.remove(userId);
+            webSocketMap.put(userId, this);
+            //加入set中
+        } else {
+            webSocketMap.put(userId, this);
+            //加入set中
+            addOnlineCount();
+            //在线数加1
+        }
+        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
+    }
+
+    /**
+     * 连接关闭调用的方法
+     */
+    @OnClose
+    public void onClose() {
+        if (webSocketMap.containsKey(userId)) {
+            webSocketMap.remove(userId);
+            //从set中删除
+            subOnlineCount();
+        }
+        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
+    }
+
+    /**
+     * 收到客户端消息后调用的方法
+     *
+     * @param message 客户端发送过来的消息
+     */
+    @OnMessage
+    public void onMessage(String message, Session session) {
+        log.info("用户消息:" + userId + ",报文:" + message);
+        //可以群发消息
+        //消息保存到数据库、redis
+        if (StringUtils.isNotBlank(message)) {
+            try {
+//                //解析发送的报文
+//                JSONObject jsonObject = JSON.parseObject(message);
+                JSONObject j = JSON.parseObject(message);
+                BizProcessInspecion i = j.toJavaObject(BizProcessInspecion.class);
+                // 导出excel
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    /**
+     * @param session
+     * @param error
+     */
+    @OnError
+    public void onError(Session session, Throwable error) {
+        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
+        error.printStackTrace();
+    }
+
+    /**
+     * 实现服务器主动推送
+     */
+    public void sendMessage(String message) throws IOException {
+        log.info("服务器消息推送:" + message);
+        this.session.getBasicRemote().sendText(message);
+    }
+
+    /**
+     * 发送自定义消息
+     */
+    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
+        log.info("发送消息到:" + userId + ",报文:" + message);
+        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
+            webSocketMap.get(userId).sendMessage(message);
+        } else {
+            log.error("用户" + userId + ",不在线!");
+//            webSocketMap.get(userId).sendMessage("用户" + userId + ",不在线!");
+        }
+    }
+
+    public static synchronized int getOnlineCount() {
+        return onlineCount;
+    }
+
+    public static synchronized void addOnlineCount() {
+        WebSocketUser.onlineCount++;
+    }
+
+    public static synchronized void subOnlineCount() {
+        WebSocketUser.onlineCount--;
+    }
+
+} 

+ 26 - 0
src/main/java/cn/ezhizao/project/websocket/domain/BizProcessInspectionExport.java

@@ -0,0 +1,26 @@
+package cn.ezhizao.project.websocket.domain;
+
+import lombok.Data;
+
+import java.util.Date;
+
+@Data
+public class BizProcessInspectionExport {
+    private String supplierName;
+    private String mnemonicCode;
+    private Integer productNum;
+    private Integer auditNum;
+    private String productionDescription;
+    private Integer materialLoss;
+    private String processAlias;
+    private String auditStatus;
+    private Date startTime;
+    private Date endTime;
+    private Date outsourceDate;
+    private Date returnReceiptDate;
+    private Date auditDate;
+    private Date balanceDate;
+    private String outsourcedOrderDetailFormCode;
+    private String returnReceiptDetailFormCode;
+    private Integer carrierNum;
+}

+ 25 - 0
src/main/java/cn/ezhizao/project/websocket/service/TaskService.java

@@ -0,0 +1,25 @@
+package cn.ezhizao.project.websocket.service;
+
+import cn.ezhizao.project.business.domain.BizProcessInspecion;
+import cn.ezhizao.project.websocket.WebSocketUser;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+
+@Service
+public class TaskService {
+    @Resource
+    WebSocketUser webSocketUser;
+    @Async
+    public void processTaskAsync(BizProcessInspecion bizProcessInspecion) {
+        try {
+            // 获取所有整年的检查的数量
+            // 分页
+            // 循环
+            // 存到excel中
+        } catch (Exception e) {
+            // 处理错误
+        }
+    }
+}

+ 17 - 1
src/main/resources/mybatis/business/BizProcessInspecionMapper.xml

@@ -21,6 +21,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         <id column="id" property="id"/>
     </resultMap>
 
+    <resultMap id="ExportResult" type="cn.ezhizao.project.websocket.domain.BizProcessInspectionExport">
+    </resultMap>
+
 
     <select id="getList" parameterType="BizProcessInspecion" resultMap="BizProcessInspecionResult">
         SELECT * FROM biz_process_inspecion
@@ -45,7 +48,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
             <if test="lotCode != null  and lotCode != ''">AND t.lot_code like concat ('%',#{lotCode},'%')</if>
             <if test="userId != null  ">AND t.user_id = #{userId}</if>
             <if test="status != null ">AND t.status = #{status}</if>
-            <if test="startTime != null"> AND DATE(t.start_time) = #{startTime}</if>
+            <if test="startTime != null"> AND DATE(t.start_time) &gt;= #{startTime}</if>
+            <if test="endTime != null"> AND DATE(t.start_time) &lt;= #{endTime}</if>
 <!--            <if test="startTime != null"> AND t.date_format(t.start_time, '%Y-%m-%d') = date_format(#{startTime}, '%Y-%m-%d')</if>-->
             <if test="supplierName != null">AND exists (select supplier_name from biz_outsourced_order_detail o where o.id = t.outsource_order_detail_id and o.supplier_name like concat('%', #{supplierName}, '%'))</if>
             <if test="returnReceiptDetailFormCode != null ">AND rrd.form_code like concat('%', #{returnReceiptDetailFormCode}, '%') </if>
@@ -57,6 +61,18 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         </trim>
         order by rrd.form_code,rrd.lot_code
     </select>
+    <select id="getExportList" parameterType="cn.ezhizao.project.websocket.domain.BizProcessInspectionExport" resultMap="ExportResult">
+
+    </select>
+    <select id="getCountForExport" resultType="java.lang.Long">
+        select bs.code as mnemonic_code, bs.name as supplier_name, bod.product_num, brr.audit_num
+        , (case when bod.product_num < brr.audit_num then 0 else bod.product_num - brr.audit_num end) as material_loss
+        , brr.process_alias
+        , (case when bpi.audit_status = 1 then '已审核' else '未审核' end) as audit_status, bpi.start_time, bpi.end_time, bpi.reject_num, bpi.lot_code, bpi.product_description, bod.form_code, bod.form_date, brr.form_code, brr.form_date, (case when bpi.audit_status = 1 then bpi.update_time else null end) as audit_time, (select boa.update_time from biz_outsource_balance_account boa where boa.status = 1 and boa.process_inspection_id = bpi.id order by update_time desc limit 1) from biz_process_inspecion bpi
+        left join biz_outsourced_order_detail bod on bod.id = bpi.outsource_order_detail_id left join biz_return_receipt_detail brr on brr.id = bpi.return_receipt_detail_id
+        left join biz_supplier bs on bs.id = bod.supplier_id
+        where recheck_date is null and is_outsourced_inspection = 1
+    </select>
     <select id="getInfo" parameterType="BizProcessInspecion" resultMap="BizProcessInspecionResult">
         SELECT distinct t1.*,t4.process_alias,t3.dept_name,t5.user_name as technicianCode,t5.nick_name as technicianName ,
         (SELECT user_name FROM sys_user WHERE t1.user_id=user_id) as userName