Pārlūkot izejas kodu

Merge branch 'master' into xq

15102826049 1 mēnesi atpakaļ
vecāks
revīzija
1aaf8a5adc
100 mainītis faili ar 4272 papildinājumiem un 7223 dzēšanām
  1. 73 0
      docs/new_sql.sql
  2. 3 0
      jshERP-web/src/api/api.js
  3. 1 1
      jshERP-web/src/components/jeecg/JEditableTable.vue
  4. 4 2
      jshERP-web/src/components/tools/ImportFileModal.vue
  5. 31 2
      jshERP-web/src/views/dashboard/Analysis.vue
  6. 13 6
      jshERP-web/src/views/dashboard/dialog/SysTipModal.vue
  7. 2 2
      jshERP-web/src/views/material/MaterialList.vue
  8. 1 1
      jshERP-web/src/views/material/mixins/MaterialModalMixins.js
  9. 185 139
      jshERP-web/src/views/material/modules/MaterialModal.vue
  10. 33 1
      pom.xml
  11. 1 1
      src/main/java/com/jsh/erp/base/AjaxResult.java
  12. 41 0
      src/main/java/com/jsh/erp/config/JacksonConfig.java
  13. 0 116
      src/main/java/com/jsh/erp/config/TenantConfig.java
  14. 23 0
      src/main/java/com/jsh/erp/constants/ExceptionConstants.java
  15. 1 5
      src/main/java/com/jsh/erp/controller/DepotHeadController.java
  16. 31 22
      src/main/java/com/jsh/erp/controller/DepotItemController.java
  17. 163 17
      src/main/java/com/jsh/erp/controller/MaterialController.java
  18. 8 0
      src/main/java/com/jsh/erp/controller/MaterialExtendController.java
  19. 56 0
      src/main/java/com/jsh/erp/controller/OpenController.java
  20. 43 0
      src/main/java/com/jsh/erp/controller/OssController.java
  21. 44 1
      src/main/java/com/jsh/erp/controller/SupplierController.java
  22. 17 0
      src/main/java/com/jsh/erp/controller/UnitController.java
  23. 18 10
      src/main/java/com/jsh/erp/controller/UserController.java
  24. 191 0
      src/main/java/com/jsh/erp/controller/pda/PdaController.java
  25. 138 0
      src/main/java/com/jsh/erp/controller/stocktaking/StocktakingController.java
  26. 21 0
      src/main/java/com/jsh/erp/datasource/dto/TaskStocktakingDTO.java
  27. 32 0
      src/main/java/com/jsh/erp/datasource/dto/TaskStocktakingItemDTO.java
  28. 72 0
      src/main/java/com/jsh/erp/datasource/entities/DepotHead.java
  29. 50 0
      src/main/java/com/jsh/erp/datasource/entities/DepotItem.java
  30. 10 87
      src/main/java/com/jsh/erp/datasource/entities/DepotItemVo4DetailByTypeAndMId.java
  31. 28 4
      src/main/java/com/jsh/erp/datasource/entities/DepotItemVo4WithInfoEx.java
  32. 5 0
      src/main/java/com/jsh/erp/datasource/entities/Log.java
  33. 43 135
      src/main/java/com/jsh/erp/datasource/entities/Material.java
  34. 10 9
      src/main/java/com/jsh/erp/datasource/entities/MaterialCategory.java
  35. 8 0
      src/main/java/com/jsh/erp/datasource/entities/MaterialCurrentStock.java
  36. 44 97
      src/main/java/com/jsh/erp/datasource/entities/MaterialExtend.java
  37. 18 0
      src/main/java/com/jsh/erp/datasource/entities/MaterialInitialStock.java
  38. 73 8
      src/main/java/com/jsh/erp/datasource/entities/MaterialVo4Unit.java
  39. 4 16
      src/main/java/com/jsh/erp/datasource/entities/MaterialWithInitStock.java
  40. 10 5
      src/main/java/com/jsh/erp/datasource/entities/Supplier.java
  41. 64 0
      src/main/java/com/jsh/erp/datasource/entities/TaskStocktaking.java
  42. 47 0
      src/main/java/com/jsh/erp/datasource/entities/TaskStocktakingItem.java
  43. 5 0
      src/main/java/com/jsh/erp/datasource/entities/User.java
  44. 143 0
      src/main/java/com/jsh/erp/datasource/mappers/BaseMapperX.java
  45. 20 1
      src/main/java/com/jsh/erp/datasource/mappers/DepotHeadMapper.java
  46. 26 1
      src/main/java/com/jsh/erp/datasource/mappers/DepotItemMapper.java
  47. 7 1
      src/main/java/com/jsh/erp/datasource/mappers/DepotItemMapperEx.java
  48. 1 1
      src/main/java/com/jsh/erp/datasource/mappers/LogMapper.java
  49. 5 0
      src/main/java/com/jsh/erp/datasource/mappers/MaterialCategoryMapper.java
  50. 1 1
      src/main/java/com/jsh/erp/datasource/mappers/MaterialCategoryMapperEx.java
  51. 3 1
      src/main/java/com/jsh/erp/datasource/mappers/MaterialCurrentStockMapper.java
  52. 26 1
      src/main/java/com/jsh/erp/datasource/mappers/MaterialExtendMapper.java
  53. 9 2
      src/main/java/com/jsh/erp/datasource/mappers/MaterialExtendMapperEx.java
  54. 2 1
      src/main/java/com/jsh/erp/datasource/mappers/MaterialInitialStockMapper.java
  55. 2 1
      src/main/java/com/jsh/erp/datasource/mappers/MaterialMapper.java
  56. 8 3
      src/main/java/com/jsh/erp/datasource/mappers/MaterialMapperEx.java
  57. 1 1
      src/main/java/com/jsh/erp/datasource/mappers/SupplierMapper.java
  58. 16 0
      src/main/java/com/jsh/erp/datasource/mappers/TaskStocktakingItemMapper.java
  59. 15 0
      src/main/java/com/jsh/erp/datasource/mappers/TaskStocktakingMapper.java
  60. 5 1
      src/main/java/com/jsh/erp/datasource/mappers/UserMapper.java
  61. 43 0
      src/main/java/com/jsh/erp/datasource/pda/dto/PDADepotHeadDTO.java
  62. 23 0
      src/main/java/com/jsh/erp/datasource/pda/dto/PDADepotMaterialDto.java
  63. 15 0
      src/main/java/com/jsh/erp/datasource/pda/dto/PDATaskStocktakingDTO.java
  64. 35 0
      src/main/java/com/jsh/erp/datasource/pda/vo/PDADepotHeadVO.java
  65. 64 0
      src/main/java/com/jsh/erp/datasource/pda/vo/PDADepotItemVO.java
  66. 43 0
      src/main/java/com/jsh/erp/datasource/pda/vo/PDATaskStocktakingItemVO.java
  67. 47 0
      src/main/java/com/jsh/erp/datasource/pda/vo/PDATaskStocktakingVO.java
  68. 87 0
      src/main/java/com/jsh/erp/datasource/tesco/request/ErpXsddReqVO.java
  69. 15 0
      src/main/java/com/jsh/erp/datasource/vo/DepotHeadXsddRequestVO.java
  70. 10 0
      src/main/java/com/jsh/erp/datasource/vo/DepotItemVo4Stock.java
  71. 5 0
      src/main/java/com/jsh/erp/datasource/vo/DepotItemVoBatchNumberList.java
  72. 15 0
      src/main/java/com/jsh/erp/datasource/vo/DepotItemXsddRequestVO.java
  73. 56 0
      src/main/java/com/jsh/erp/datasource/vo/Material4UnitPrice.java
  74. 4 53
      src/main/java/com/jsh/erp/datasource/vo/MaterialVoSearch.java
  75. 25 0
      src/main/java/com/jsh/erp/datasource/vo/MaterialWarnListVo.java
  76. 14 0
      src/main/java/com/jsh/erp/datasource/vo/SpinnerVO.java
  77. 77 0
      src/main/java/com/jsh/erp/datasource/vo/TaskStocktakingItemVO.java
  78. 36 0
      src/main/java/com/jsh/erp/datasource/vo/TaskStocktakingVO.java
  79. 20 0
      src/main/java/com/jsh/erp/datasource/vo/UnitListVo.java
  80. 4 1
      src/main/java/com/jsh/erp/filter/LogCostFilter.java
  81. 128 0
      src/main/java/com/jsh/erp/query/LambdaQueryWrapperX.java
  82. 128 0
      src/main/java/com/jsh/erp/query/QueryWrapperX.java
  83. 37 0
      src/main/java/com/jsh/erp/result/PageParam.java
  84. 66 0
      src/main/java/com/jsh/erp/result/PageResult.java
  85. 56 0
      src/main/java/com/jsh/erp/result/SortingField.java
  86. 118 1634
      src/main/java/com/jsh/erp/service/DepotHeadService.java
  87. 96 1345
      src/main/java/com/jsh/erp/service/DepotItemService.java
  88. 6 0
      src/main/java/com/jsh/erp/service/DepotService.java
  89. 12 152
      src/main/java/com/jsh/erp/service/LogService.java
  90. 2 1
      src/main/java/com/jsh/erp/service/MaterialCategoryService.java
  91. 22 371
      src/main/java/com/jsh/erp/service/MaterialExtendService.java
  92. 127 1400
      src/main/java/com/jsh/erp/service/MaterialService.java
  93. 69 669
      src/main/java/com/jsh/erp/service/SupplierService.java
  94. 624 0
      src/main/java/com/jsh/erp/service/SyncTescoSystemService.java
  95. 18 11
      src/main/java/com/jsh/erp/service/SystemConfigService.java
  96. 7 0
      src/main/java/com/jsh/erp/service/TaskStocktakingItemService.java
  97. 67 0
      src/main/java/com/jsh/erp/service/TaskStocktakingService.java
  98. 25 0
      src/main/java/com/jsh/erp/service/UnitService.java
  99. 8 0
      src/main/java/com/jsh/erp/service/UserBusinessService.java
  100. 63 883
      src/main/java/com/jsh/erp/service/UserService.java

+ 73 - 0
docs/new_sql.sql

@@ -10,3 +10,76 @@ ADD COLUMN invoice_type VARCHAR(1)  DEFAULT '' COMMENT '发票类型:0-普通
 ADD COLUMN contract_upload VARCHAR(1000) DEFAULT '' COMMENT '合同附件存储路径';
 
 
+-- 产品信息表  新增系统sku、无动销提醒周期
+ALTER TABLE jsh_material
+ADD COLUMN system_sku VARCHAR(50) DEFAULT '' COMMENT '系统sku',
+ADD COLUMN moving_pin_reminder_cycle VARCHAR(20) DEFAULT '' COMMENT '无动销提醒周期';
+
+-- 产品信息表  删除制造商、保质期天数、仓位货架
+ALTER TABLE jsh_material
+DROP mfrs,
+DROP expiry_num,
+DROP position;
+
+-- 产品价格扩展信息表  新增生产日期、保质期天数、供应商id、批次号、库存、仓库id、仓位货架
+ALTER TABLE jsh_material_extend
+ADD COLUMN production_date DATE DEFAULT NULL COMMENT '生产日期',
+ADD COLUMN expiry_num INT DEFAULT NULL COMMENT '保质期天数',
+ADD COLUMN supplier_id BIGINT DEFAULT NULL COMMENT '供应商id',
+ADD COLUMN batch_number VARCHAR(255) DEFAULT '' COMMENT '批次号',
+ADD COLUMN inventory DECIMAL(24,6) DEFAULT NULL COMMENT '库存',
+ADD COLUMN depot_id BIGINT DEFAULT NULL COMMENT '仓库id',
+ADD COLUMN position VARCHAR(255) DEFAULT '' COMMENT '仓位货架';
+
+-- 单据主表  新增凭证图片、商品数量、商品总类数量
+ALTER TABLE jsh_depot_head
+ADD COLUMN voucher_picture VARCHAR(255) DEFAULT '' COMMENT '凭证图片',
+ADD COLUMN goods_quantity INT DEFAULT NULL COMMENT '商品数量',
+ADD COLUMN goods_type_count INT DEFAULT NULL COMMENT '商品总类数量';
+
+-- 单据子表  新增实际出入库数量、出入库差异、出入库差异原因、出入库操作用户、出入库时间
+ALTER TABLE jsh_depot_item
+ADD COLUMN actual_quantity_in_storage DECIMAL(24,6) DEFAULT NULL COMMENT '实际出入库数量',
+ADD COLUMN warehousing_variance DECIMAL(24,6) DEFAULT NULL COMMENT '出入库差异',
+ADD COLUMN reason_of_difference VARCHAR(255) DEFAULT '' COMMENT '出入库差异原因',
+ADD COLUMN warehousing_user BIGINT DEFAULT NULL COMMENT '出入库操作用户',
+ADD COLUMN warehousing_time DATE DEFAULT NULL COMMENT '出入库时间';
+
+-- 修改产品类型编码为BIGINT
+ALTER TABLE jsh_material_category MODIFY COLUMN serial_no BIGINT;
+
+CREATE TABLE `task_stocktaking` (
+    `id` bigint NOT NULL COMMENT '主键ID',
+    `task_name` varchar(255) DEFAULT NULL COMMENT '任务名称',
+    `creator` bigint DEFAULT NULL COMMENT '负责人',
+    `create_by` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '创建人',
+    `create_time` datetime DEFAULT NULL COMMENT '创建时间',
+    `task_type` varchar(255) DEFAULT NULL COMMENT '任务类型',
+    `depot_id` bigint DEFAULT NULL COMMENT '仓库ID',
+    `number` varchar(255) DEFAULT NULL COMMENT '任务单号',
+    `material_count` int DEFAULT NULL COMMENT '商品数',
+    `task_status` int DEFAULT NULL COMMENT '任务状态',
+    `position_range` varchar(255) DEFAULT NULL COMMENT '库位范围',
+    `delete_flag` tinyint DEFAULT NULL COMMENT '删除标志(0:否,1是)',
+    PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='盘点任务表';
+
+ALTER TABLE jsh_depot_head
+    ADD COLUMN link_tesco varchar(50) DEFAULT '' COMMENT '集采订单编号',
+    ADD COLUMN receiver_name VARCHAR(255) DEFAULT '' COMMENT '收货人',
+    ADD COLUMN receiver_phone VARCHAR(20) DEFAULT '' COMMENT '收货人电话',
+    ADD COLUMN receiver_address VARCHAR(255) DEFAULT '' COMMENT '收货地址';
+
+CREATE TABLE `task_stocktaking_item` (
+    `id` bigint NOT NULL COMMENT '主键ID',
+    `task_stocktaking_id` bigint DEFAULT NULL COMMENT '任务ID',
+    `material_item_id` bigint DEFAULT NULL COMMENT '商品ID',
+    `creator` bigint DEFAULT NULL COMMENT '操作人',
+    `new_position` varchar(255) DEFAULT NULL COMMENT '新仓位货架',
+    `new_inventory` decimal(24,6) DEFAULT NULL COMMENT '新库存数',
+    `difference_count` int DEFAULT NULL COMMENT '差异数量',
+    `difference_reasion` varchar(255) DEFAULT NULL COMMENT '差异原因',
+    `delete_flag` varchar(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT '0' COMMENT '删除标记,0未删除,1删除',
+    `oper_time` datetime DEFAULT NULL COMMENT '操作时间',
+    PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='盘点任务关联商品表';

+ 3 - 0
jshERP-web/src/api/api.js

@@ -3,6 +3,8 @@ import { getAction, deleteAction, putAction, postAction, httpAction } from '@/ap
 //首页统计
 const getBuyAndSaleStatistics = (params) => getAction('/depotHead/getBuyAndSaleStatistics', params)
 const buyOrSalePrice = (params) => getAction('/depotItem/buyOrSalePrice', params)
+const getMaterialWarn = (params) => getAction('/material/getMaterialWarn', params)
+
 //租户管理
 const checkTenant = (params) => getAction('/tenant/checkIsNameExist', params)
 const addTenant = (params) => postAction('/tenant/add', params)
@@ -121,6 +123,7 @@ const findFinancialDetailByNumber = (params) => getAction('/accountHead/getDetai
 export {
   getBuyAndSaleStatistics,
   buyOrSalePrice,
+  getMaterialWarn,
   checkTenant,
   addTenant,
   editTenant,

+ 1 - 1
jshERP-web/src/components/jeecg/JEditableTable.vue

@@ -1406,7 +1406,7 @@ export default {
         let disabled = false
         this.columns.forEach((column) => {
           let inputId = column.key + value.id
-          let sourceValue = (data[column.key] == null ? '' : data[column.key]).toString()
+          let sourceValue = data[column.key] == null ? '' : data[column.key]
 
           let defaultValue = null
           if (setDefaultValue) {

+ 4 - 2
jshERP-web/src/components/tools/ImportFileModal.vue

@@ -71,6 +71,7 @@ export default {
       disableMixinCreated: true,
       templateUrl: '',
       templateName: '',
+      templateDownloadName: '',
       url: {
         importExcelUrl: '',
       },
@@ -83,15 +84,16 @@ export default {
     },
   },
   methods: {
-    initModal(apiUrl, templateUrl, templateName) {
+    initModal(apiUrl, templateUrl, templateName, templateDownloadName = '供应商模板') {
       this.url.importExcelUrl = apiUrl
       this.templateUrl = templateUrl
       this.templateName = templateName
+      this.templateDownloadName = templateDownloadName
       this.visible = true
     },
     importTemplate() {
       let link = this.$refs.myLink
-      link.setAttribute('download', '供应商模板' + '.xls')
+      link.setAttribute('download', this.templateDownloadName + '.xls')
     },
     close() {
       this.$emit('close')

+ 31 - 2
jshERP-web/src/views/dashboard/Analysis.vue

@@ -8,6 +8,9 @@
 <script>
 import IndexChart from './IndexChart'
 import SysTipModal from './dialog/SysTipModal.vue'
+import { getMaterialWarn } from '@/api/api.js'
+
+let isFirst = true
 export default {
   name: 'Analysis',
   components: {
@@ -15,10 +18,36 @@ export default {
     SysTipModal,
   },
   data() {
-    return {}
+    return {
+      warnData: {}
+    }
+  },
+  created() {
+    if(isFirst){
+      this.getWarnData()
+    }
   },
-  created() {},
   methods: {
+    getWarnData(){
+      isFirst = false
+      const hasArrayData = (val) => {
+        return Array.isArray(val) && val.length > 0
+      }
+      getMaterialWarn().then(res => {
+        const {expirationReminder = [],inventoryReminder = [],noMovingPinReminder = []} = res.data
+        if(hasArrayData(expirationReminder)||hasArrayData(inventoryReminder)||hasArrayData(noMovingPinReminder)){
+          this.$nextTick(() => {
+            this.$refs.sysTipModal.open(
+              {
+                expirationReminder,
+                inventoryReminder,
+                noMovingPinReminder
+              }
+            )
+          })
+        }
+      })
+    },
     openSysTipModal() {
       this.$refs.sysTipModal.open({})
     },

+ 13 - 6
jshERP-web/src/views/dashboard/dialog/SysTipModal.vue

@@ -18,12 +18,14 @@
       <div class="tip-body">
         <div class="tip-content">
           <div class="text-title">无动销提醒</div>
-          <p class="text-val">1.商品名称xxx,在【无动销提醒周期】内,无动销,请及时处理</p>
-          <p class="text-val">1.商品名称xxx,在【无动销提醒周期】内,无动销,请及时处理</p>
+          <p class="text-val" v-for="(item,index) in dataInfo.noMovingPinReminder" :key="index">{{ `${index+1}.${item}` }}</p>
+          <p class="text-val" v-show="dataInfo.noMovingPinReminder.length===0">暂无</p>
           <div class="text-title">过期提醒</div>
-          <p class="text-val">3.商品名称xxx,条码xxx,生产日期xxx,保质期xxx,库存xxx,即将要过期,请及时处理</p>
+          <p class="text-val" v-for="(item,index) in dataInfo.expirationReminder" :key="index">{{ `${index+1}.${item}` }}</p>
+          <p class="text-val" v-show="dataInfo.expirationReminder.length===0">暂无</p>
           <div class="text-title">库存提醒</div>
-          <p class="text-val">4.商品名称xxx,库存告警,请及时处理</p>
+          <p class="text-val" v-for="(item,index) in dataInfo.inventoryReminder" :key="index">{{ `${index+1}.${item}` }}</p>
+          <p class="text-val" v-show="dataInfo.inventoryReminder.length===0">暂无</p>
         </div>
         <div class="btn-wrap">
           <a-button type="primary" @click="handleOk" class="confirm-btn">好的</a-button>
@@ -39,7 +41,11 @@ export default {
     return {
       visible: false,
       confirmLoading: false,
-      dataInfo: {},
+      dataInfo: {
+        expirationReminder: [],
+        inventoryReminder: [],
+        noMovingPinReminder: []
+      },
     }
   },
   methods: {
@@ -103,7 +109,8 @@ export default {
     background-color: rgba(255, 255, 255, 0.8);
   }
   .tip-content {
-    height: 210px;
+    max-height: 300px;
+    overflow: hidden scroll;
   }
   .btn-wrap {
     margin-top: 16px;

+ 2 - 2
jshERP-web/src/views/material/MaterialList.vue

@@ -549,8 +549,8 @@ export default {
     handleImportXls() {
       let importExcelUrl = this.url.importExcelUrl
       let templateUrl = '/doc/goods_template.xls'
-      let templateName = '商品Excel模板[下载]'
-      this.$refs.modalImportForm.initModal(importExcelUrl, templateUrl, templateName)
+      let templateName = '商品信息导入模版[下载]'
+      this.$refs.modalImportForm.initModal(importExcelUrl, templateUrl, templateName, '商品信息导入模版')
       this.$refs.modalImportForm.title = '商品导入'
     },
     searchReset() {

+ 1 - 1
jshERP-web/src/views/material/mixins/MaterialModalMixins.js

@@ -44,7 +44,7 @@ export const MaterialModalMixins = {
           let arr = res.data
           that.depotList = arr.map((item) => {
             return {
-              value: item.id + '',
+              value: item.id,
               text: item.depotName,
               title: item.depotName,
             }

+ 185 - 139
jshERP-web/src/views/material/modules/MaterialModal.vue

@@ -111,14 +111,47 @@
                   </a-row>
                 </a-form-item>
               </a-col>
+           
             </a-row>
             <a-row class="form-row" :gutter="24">
+              <a-col :md="6" :sm="24" v-if="!model.id">
+                <a-form-item
+                  :labelCol="labelCol"
+                  :wrapperCol="wrapperCol"
+                  label="多属性"
+                  data-step="5"
+                  data-title="多属性"
+                  data-intro="多属性是针对的sku商品(比如服装、鞋帽行业),此处开关如果启用就可以在下方进行多sku的配置,配置具体的颜色、尺码之类的组合"
+                >
+                  <a-tooltip title="多属性针对服装、鞋帽等行业,需要先录入单位才能激活此处输入框">
+                    <a-tag class="tag-info" v-if="!manySkuStatus">需要先录入单位才能激活</a-tag>
+                    <a-select
+                      mode="multiple"
+                      v-decorator="['manySku']"
+                      showSearch
+                      optionFilterProp="children"
+                      placeholder="请选择多属性(可多选)"
+                      @change="onManySkuChange"
+                      v-show="manySkuStatus"
+                    >
+                      <a-select-option
+                        v-for="(item, index) in materialAttributeList"
+                        :key="index"
+                        :value="item.value"
+                        :disabled="item.disabled"
+                      >
+                        {{ item.name }}
+                      </a-select-option>
+                    </a-select>
+                  </a-tooltip>
+                </a-form-item>
+              </a-col>
               <a-col :md="6" :sm="24">
                 <a-form-item
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="颜色"
-                  data-step="5"
+                  data-step="6"
                   data-title="颜色"
                   data-intro="请填写商品的颜色,如果是多属性商品可以不填(下面有多属性开关)"
                 >
@@ -130,7 +163,7 @@
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="品牌"
-                  data-step="6"
+                  data-step="7"
                   data-title="品牌"
                   data-intro="请填写商品的品牌,方便区别不同品牌的商品"
                 >
@@ -142,19 +175,22 @@
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="助记码"
-                  data-step="7"
+                  data-step="8"
                   data-title="助记码"
                   data-intro="助记码自动生成,助记码是商品名称的首字母缩写"
                 >
                   <a-input placeholder="" v-decorator.trim="['mnemonic']" :readOnly="true" />
                 </a-form-item>
               </a-col>
+    
+            </a-row>
+            <a-row class="form-row" :gutter="24">
               <a-col :md="6" :sm="24">
                 <a-form-item
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="类别"
-                  data-step="8"
+                  data-step="9"
                   data-title="类别"
                   data-intro="类别需要在【商品类别】页面进行录入,录入之后在此处进行调用"
                 >
@@ -169,14 +205,12 @@
                   </a-tree-select>
                 </a-form-item>
               </a-col>
-            </a-row>
-            <a-row class="form-row" :gutter="24">
               <a-col :md="6" :sm="24">
                 <a-form-item
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="基础重量"
-                  data-step="9"
+                  data-step="10"
                   data-title="基础重量"
                   data-intro="请填写基本单位对应的重量,用于计算按重量分摊费用时单据中各行商品分摊的费用成本"
                 >
@@ -188,7 +222,7 @@
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="序列号"
-                  data-step="10"
+                  data-step="11"
                   data-title="序列号"
                   data-intro="此处是商品的序列号开关,如果选择了有,则在采购入库单据需要录入该商品的序列号,在销售出库单据需要选择该商品的序列号进行出库"
                 >
@@ -205,7 +239,7 @@
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="系统SKU"
-                  data-step="11"
+                  data-step="12"
                   data-title="系统SKU"
                   data-intro="系统SKU"
                 >
@@ -217,16 +251,16 @@
                   :labelCol="labelCol"
                   :wrapperCol="wrapperCol"
                   label="无动销提醒周期"
-                  data-step="12"
+                  data-step="13"
                   data-title="无动销提醒周期"
                   data-intro="无动销提醒周期"
                 >
                   <a-tooltip title="无动销提醒周期">
                     <a-select placeholder="无动销提醒周期" v-decorator="['movingPinReminderCycle']">
-                      <a-select-option value="一周">一周</a-select-option>
-                      <a-select-option value="两周">两周</a-select-option>
-                      <a-select-option value="一个月">一个月</a-select-option>
-                      <a-select-option value="一季度">一季度</a-select-option>
+                      <a-select-option value="7">一周</a-select-option>
+                      <a-select-option value="14">两周</a-select-option>
+                      <a-select-option value="30">一个月</a-select-option>
+                      <a-select-option value="90">一季度</a-select-option>
                     </a-select>
                   </a-tooltip>
                 </a-form-item>
@@ -407,7 +441,7 @@
                     :dropdownMatchSelectWidth="false"
                     showSearch
                     optionFilterProp="children"
-                    :value="typeof value === 'string' ? Number(value) : ''"
+                    :value="value"
                     @change="($event) => handleChange($event)"
                   >
                     <div slot="dropdownRender" slot-scope="menu">
@@ -660,9 +694,10 @@ export default {
             key: 'commodityUnit',
             width: '8%',
             type: FormTypes.input,
+            disabled: true,
             defaultValue: '',
             placeholder: '请输入${title}',
-            validateRules: [{ required: true, message: '${title}不能为空' }],
+            // validateRules: [{ required: true, message: '${title}不能为空' }],
           },
           {
             title: '多属性',
@@ -1086,69 +1121,69 @@ export default {
                 }
               }
             }
-            if (!formData.unit) {
-              //此时为多单位
-              if (formData.meList.length < 2) {
-                this.$message.warning('多单位的商品条码行数至少要有两行,请再新增一行条码信息!')
-                return
-              }
-              if (formData.meList[0].commodityUnit != basicUnit) {
-                this.$message.warning(
-                  '条码之后的单位填写有误,单位【' +
-                    formData.meList[0].commodityUnit +
-                    '】请修改为【' +
-                    basicUnit +
-                    '】!'
-                )
-                return
-              }
-              if (formData.meList[1].commodityUnit != otherUnit) {
-                this.$message.warning(
-                  '条码之后的单位填写有误,单位【' +
-                    formData.meList[1].commodityUnit +
-                    '】请修改为【' +
-                    otherUnit +
-                    '】!'
-                )
-                return
-              }
-            }
+            // if (!formData.unit) {
+            //   // 此时为多单位
+            //   if (formData.meList.length < 2) {
+            //     this.$message.warning('多单位的商品条码行数至少要有两行,请再新增一行条码信息!')
+            //     return
+            //   }
+            //   if (formData.meList[0].commodityUnit != basicUnit) {
+            //     this.$message.warning(
+            //       '条码之后的单位填写有误,单位【' +
+            //         formData.meList[0].commodityUnit +
+            //         '】请修改为【' +
+            //         basicUnit +
+            //         '】!'
+            //     )
+            //     return
+            //   }
+            //   if (formData.meList[1].commodityUnit != otherUnit) {
+            //     this.$message.warning(
+            //       '条码之后的单位填写有误,单位【' +
+            //         formData.meList[1].commodityUnit +
+            //         '】请修改为【' +
+            //         otherUnit +
+            //         '】!'
+            //     )
+            //     return
+            //   }
+            // }
             let skuCount = 0
             for (let i = 0; i < formData.meList.length; i++) {
-              let commodityUnit = formData.meList[i].commodityUnit
-              if (formData.unit) {
-                if (commodityUnit != formData.unit) {
-                  this.$message.warning(
-                    '条码之后的单位填写有误,单位【' + commodityUnit + '】请修改为【' + formData.unit + '】!'
-                  )
-                  return
-                }
-              } else if (formData.unitId) {
-                if (
-                  commodityUnit != basicUnit &&
-                  commodityUnit != otherUnit &&
-                  commodityUnit != otherUnitTwo &&
-                  commodityUnit != otherUnitThree
-                ) {
-                  let warnInfo =
-                    '条码之后的单位填写有误,单位【' +
-                    commodityUnit +
-                    '】请修改为【' +
-                    basicUnit +
-                    '】或【' +
-                    otherUnit +
-                    '】'
-                  if (otherUnitTwo) {
-                    warnInfo += '或【' + otherUnitTwo + '】'
-                  }
-                  if (otherUnitThree) {
-                    warnInfo += '或【' + otherUnitThree + '】'
-                  }
-                  warnInfo += '!'
-                  this.$message.warning(warnInfo)
-                  return
-                }
-              }
+              // let commodityUnit = formData.meList[i].commodityUnit
+              // if (formData.unit) {
+              //   if (commodityUnit != formData.unit) {
+              //     this.$message.warning(
+              //       '条码之后的单位填写有误,单位【' + commodityUnit + '】请修改为【' + formData.unit + '】!'
+              //     )
+              //     return
+              //   }
+              // } else if (formData.unitId) {
+              //   if (
+              //     commodityUnit != basicUnit &&
+              //     commodityUnit != otherUnit &&
+              //     commodityUnit != otherUnitTwo &&
+              //     commodityUnit != otherUnitThree
+              //   ) {
+              //     let warnInfo =
+              //       '条码之后的单位填写有误,单位【' +
+              //       commodityUnit +
+              //       '】请修改为【' +
+              //       basicUnit +
+              //       '】或【' +
+              //       otherUnit +
+              //       '】'
+              //     if (otherUnitTwo) {
+              //       warnInfo += '或【' + otherUnitTwo + '】'
+              //     }
+              //     if (otherUnitThree) {
+              //       warnInfo += '或【' + otherUnitThree + '】'
+              //     }
+              //     warnInfo += '!'
+              //     this.$message.warning(warnInfo)
+              //     return
+              //   }
+              // }
               if (formData.sku) {
                 skuCount++
               }
@@ -1410,7 +1445,17 @@ export default {
     },
     onAdded(event) {
       const { row, target } = event
-      target.setValues([{ rowKey: row.id, values: { barCode: '', commodityUnit: '' } }])
+      let formUnit = ''
+      // 勾选多单位
+      if(this.unitChecked){
+        const obj = this.unitList.find(item => item.id === this.form.getFieldValue('unitId'))
+        if(obj){
+          formUnit = obj.basicUnit
+        }
+      }else{
+        formUnit = this.form.getFieldValue('unit')||''
+      }
+      target.setValues([{ rowKey: row.id, values: { barCode: '', commodityUnit: formUnit, supplierId: undefined, depotId: undefined } }])
     },
     onDeleted(value) {
       this.meDeleteIdList = value
@@ -1418,15 +1463,15 @@ export default {
     //单元值改变一个字符就触发一次
     onValueChange(event) {
       console.log('onValueChange--------table-change', event)
-      const { type, row, column, value, target } = event
-      switch (column.key) {
-        case 'purchaseDecimal':
-        case 'commodityDecimal':
-        case 'wholesaleDecimal':
-        case 'lowDecimal':
-          this.changeDecimalByValue(row)
-          break
-      }
+      // const { type, row, column, value, target } = event
+      // switch (column.key) {
+      //   case 'purchaseDecimal':
+      //   case 'commodityDecimal':
+      //   case 'wholesaleDecimal':
+      //   case 'lowDecimal':
+      //     this.changeDecimalByValue(row)
+      //     break
+      // }
     },
     //修改商品明细中的价格触发计算
     changeDecimalByValue(row) {
@@ -1679,58 +1724,59 @@ export default {
           basicLowDecimal = ''
         for (let i = 0; i < mArr.length; i++) {
           let mInfo = mArr[i]
-          if (i === 0) {
-            mInfo.commodityUnit = basicUnit
-            basicPurchaseDecimal = mInfo.purchaseDecimal
-            basicCommodityDecimal = mInfo.commodityDecimal
-            basicWholesaleDecimal = mInfo.wholesaleDecimal
-            basicLowDecimal = mInfo.lowDecimal
-          } else {
-            //副单位进行换算
-            mInfo.commodityUnit = otherUnit
-            if (basicPurchaseDecimal) {
-              mInfo.purchaseDecimal = (basicPurchaseDecimal * ratio).toFixed(2)
-            }
-            if (basicCommodityDecimal) {
-              mInfo.commodityDecimal = (basicCommodityDecimal * ratio).toFixed(2)
-            }
-            if (basicWholesaleDecimal) {
-              mInfo.wholesaleDecimal = (basicWholesaleDecimal * ratio).toFixed(2)
-            }
-            if (basicLowDecimal) {
-              mInfo.lowDecimal = (basicLowDecimal * ratio).toFixed(2)
-            }
-            if (otherUnitTwo && i === 2) {
-              mInfo.commodityUnit = otherUnitTwo
-              if (basicPurchaseDecimal) {
-                mInfo.purchaseDecimal = (basicPurchaseDecimal * ratioTwo).toFixed(2)
-              }
-              if (basicCommodityDecimal) {
-                mInfo.commodityDecimal = (basicCommodityDecimal * ratioTwo).toFixed(2)
-              }
-              if (basicWholesaleDecimal) {
-                mInfo.wholesaleDecimal = (basicWholesaleDecimal * ratioTwo).toFixed(2)
-              }
-              if (basicLowDecimal) {
-                mInfo.lowDecimal = (basicLowDecimal * ratioTwo).toFixed(2)
-              }
-            }
-            if (otherUnitThree && i === 3) {
-              mInfo.commodityUnit = otherUnitThree
-              if (basicPurchaseDecimal) {
-                mInfo.purchaseDecimal = (basicPurchaseDecimal * ratioThree).toFixed(2)
-              }
-              if (basicCommodityDecimal) {
-                mInfo.commodityDecimal = (basicCommodityDecimal * ratioThree).toFixed(2)
-              }
-              if (basicWholesaleDecimal) {
-                mInfo.wholesaleDecimal = (basicWholesaleDecimal * ratioThree).toFixed(2)
-              }
-              if (basicLowDecimal) {
-                mInfo.lowDecimal = (basicLowDecimal * ratioThree).toFixed(2)
-              }
-            }
-          }
+          mInfo.commodityUnit = basicUnit
+          // if (i === 0) {
+          //   // mInfo.commodityUnit = basicUnit
+          //   basicPurchaseDecimal = mInfo.purchaseDecimal
+          //   basicCommodityDecimal = mInfo.commodityDecimal
+          //   basicWholesaleDecimal = mInfo.wholesaleDecimal
+          //   basicLowDecimal = mInfo.lowDecimal
+          // } else {
+          //   //副单位进行换算
+          //   // mInfo.commodityUnit = otherUnit
+          //   if (basicPurchaseDecimal) {
+          //     mInfo.purchaseDecimal = (basicPurchaseDecimal * ratio).toFixed(2)
+          //   }
+          //   if (basicCommodityDecimal) {
+          //     mInfo.commodityDecimal = (basicCommodityDecimal * ratio).toFixed(2)
+          //   }
+          //   if (basicWholesaleDecimal) {
+          //     mInfo.wholesaleDecimal = (basicWholesaleDecimal * ratio).toFixed(2)
+          //   }
+          //   if (basicLowDecimal) {
+          //     mInfo.lowDecimal = (basicLowDecimal * ratio).toFixed(2)
+          //   }
+          //   if (otherUnitTwo && i === 2) {
+          //     // mInfo.commodityUnit = otherUnitTwo
+          //     if (basicPurchaseDecimal) {
+          //       mInfo.purchaseDecimal = (basicPurchaseDecimal * ratioTwo).toFixed(2)
+          //     }
+          //     if (basicCommodityDecimal) {
+          //       mInfo.commodityDecimal = (basicCommodityDecimal * ratioTwo).toFixed(2)
+          //     }
+          //     if (basicWholesaleDecimal) {
+          //       mInfo.wholesaleDecimal = (basicWholesaleDecimal * ratioTwo).toFixed(2)
+          //     }
+          //     if (basicLowDecimal) {
+          //       mInfo.lowDecimal = (basicLowDecimal * ratioTwo).toFixed(2)
+          //     }
+          //   }
+          //   if (otherUnitThree && i === 3) {
+          //     // mInfo.commodityUnit = otherUnitThree
+          //     if (basicPurchaseDecimal) {
+          //       mInfo.purchaseDecimal = (basicPurchaseDecimal * ratioThree).toFixed(2)
+          //     }
+          //     if (basicCommodityDecimal) {
+          //       mInfo.commodityDecimal = (basicCommodityDecimal * ratioThree).toFixed(2)
+          //     }
+          //     if (basicWholesaleDecimal) {
+          //       mInfo.wholesaleDecimal = (basicWholesaleDecimal * ratioThree).toFixed(2)
+          //     }
+          //     if (basicLowDecimal) {
+          //       mInfo.lowDecimal = (basicLowDecimal * ratioThree).toFixed(2)
+          //     }
+          //   }
+          // }
         }
         this.meTable.dataSource = mArr
       })

+ 33 - 1
pom.xml

@@ -85,7 +85,7 @@
 		<dependency>
 			<groupId>com.baomidou</groupId>
 			<artifactId>mybatis-plus-boot-starter</artifactId>
-			<version>3.0.7.1</version>
+			<version>3.5.2</version>
 		</dependency>
 		<dependency>
 			<groupId>org.springframework.boot</groupId>
@@ -128,6 +128,38 @@
 			<artifactId>pagehelper-spring-boot-starter</artifactId>
 			<version>1.2.13</version>
 		</dependency>
+
+		<!--常用工具类 -->
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-lang3</artifactId>
+			<version>3.12.0</version>
+		</dependency>
+
+		<dependency>
+			<groupId>com.sun.mail</groupId>
+			<artifactId>jakarta.mail</artifactId>
+			<version>1.6.5</version>
+		</dependency>
+
+		<dependency>
+			<groupId>cn.hutool</groupId>
+			<artifactId>hutool-all</artifactId>
+			<version>5.8.25</version>
+		</dependency>
+
+		<!-- 二维码 -->
+		<dependency>
+			<groupId>com.google.zxing</groupId>
+			<artifactId>core</artifactId>
+			<version>3.4.1</version>
+		</dependency>
+		<dependency>
+			<groupId>com.google.zxing</groupId>
+			<artifactId>javase</artifactId>
+			<version>3.4.1</version>
+		</dependency>
+
 	</dependencies>
 
 	<build>

+ 1 - 1
src/main/java/com/jsh/erp/base/AjaxResult.java

@@ -29,7 +29,7 @@ public class AjaxResult extends HashMap<String, Object>
     public enum Type
     {
         /** 成功 */
-        SUCCESS(0),
+        SUCCESS(200),
         /** 警告 */
         WARN(301),
         /** 错误 */

+ 41 - 0
src/main/java/com/jsh/erp/config/JacksonConfig.java

@@ -0,0 +1,41 @@
+package com.jsh.erp.config;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
+import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+
+import java.util.TimeZone;
+
+/**
+ * Jackson配置
+ *
+ * @author ruoyi
+ *
+ */
+@Configuration
+public class JacksonConfig
+{
+    @Bean
+    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter()
+    {
+        final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
+        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
+        final ObjectMapper objectMapper = builder.build();
+        SimpleModule simpleModule = new SimpleModule();
+        // Long 转为 String 防止 js 丢失精度
+        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
+        //simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
+        objectMapper.registerModule(simpleModule);
+        // 忽略 transient 关键词属性
+        objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
+        // 设置时区
+        objectMapper.setTimeZone(TimeZone.getDefault());
+        return new MappingJackson2HttpMessageConverter(objectMapper);
+    }
+}

+ 0 - 116
src/main/java/com/jsh/erp/config/TenantConfig.java

@@ -1,116 +0,0 @@
-package com.jsh.erp.config;
-
-import com.baomidou.mybatisplus.core.parser.ISqlParser;
-import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
-import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
-import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
-import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
-import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
-import com.jsh.erp.utils.Tools;
-import net.sf.jsqlparser.expression.Expression;
-import net.sf.jsqlparser.expression.LongValue;
-import org.apache.ibatis.mapping.MappedStatement;
-import org.apache.ibatis.reflection.MetaObject;
-import org.springframework.context.annotation.Bean;
-import org.springframework.stereotype.Service;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.List;
-
-@Service
-public class TenantConfig {
-
-    @Bean
-    public PaginationInterceptor paginationInterceptor(HttpServletRequest request) {
-        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
-        List<ISqlParser> sqlParserList = new ArrayList<>();
-        TenantSqlParser tenantSqlParser = new TenantSqlParser();
-        tenantSqlParser.setTenantHandler(new TenantHandler() {
-            @Override
-            public Expression getTenantId() {
-                String token = request.getHeader("X-Access-Token");
-                Long tenantId = Tools.getTenantIdByToken(token);
-                if (tenantId!=0L) {
-                    return new LongValue(tenantId);
-                } else {
-                    //超管
-                    return null;
-                }
-            }
-
-            @Override
-            public String getTenantIdColumn() {
-                return "tenant_id";
-            }
-
-            @Override
-            public boolean doTableFilter(String tableName) {
-                //获取开启状态
-                Boolean res = true;
-                String token = request.getHeader("X-Access-Token");
-                Long tenantId = Tools.getTenantIdByToken(token);
-                if (tenantId!=0L) {
-                    // 这里可以判断是否过滤表
-                    if ("jsh_material_property".equals(tableName) || "jsh_sequence".equals(tableName)
-                            || "jsh_function".equals(tableName) || "jsh_platform_config".equals(tableName)
-                            || "jsh_tenant".equals(tableName)) {
-                        res = true;
-                    } else {
-                        res = false;
-                    }
-                }
-                return res;
-            }
-        });
-
-        sqlParserList.add(tenantSqlParser);
-        paginationInterceptor.setSqlParserList(sqlParserList);
-        paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
-            @Override
-            public boolean doFilter(MetaObject metaObject) {
-                MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
-                // 过滤自定义查询此时无租户信息约束出现
-                if ("com.jsh.erp.datasource.mappers.UserMapperEx.getUserByWeixinOpenId".equals(ms.getId())) {
-                    return true;
-                } else if ("com.jsh.erp.datasource.mappers.UserMapperEx.updateUserWithWeixinOpenId".equals(ms.getId())) {
-                    return true;
-                } else if ("com.jsh.erp.datasource.mappers.UserMapperEx.getUserListByUserNameOrLoginName".equals(ms.getId())) {
-                    return true;
-                } else if ("com.jsh.erp.datasource.mappers.UserMapperEx.disableUserByLimit".equals(ms.getId())) {
-                    return true;
-                } else if ("com.jsh.erp.datasource.mappers.RoleMapperEx.getRoleWithoutTenant".equals(ms.getId())) {
-                    return true;
-                } else if ("com.jsh.erp.datasource.mappers.LogMapperEx.insertLogWithUserId".equals(ms.getId())) {
-                    return true;
-                } else if ("com.jsh.erp.datasource.mappers.UserBusinessMapperEx.getBasicDataByKeyIdAndType".equals(ms.getId())) {
-                    return true;
-                }
-                return false;
-            }
-        });
-        return paginationInterceptor;
-    }
-
-    /**
-     * 相当于顶部的:
-     * {@code @MapperScan("com.jsh.erp.datasource.mappers*")}
-     * 这里可以扩展,比如使用配置文件来配置扫描Mapper的路径
-     */
-//    @Bean
-//    public MapperScannerConfigurer mapperScannerConfigurer() {
-//        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
-//        scannerConfigurer.setBasePackage("com.jsh.erp.datasource.mappers");
-//        return scannerConfigurer;
-//    }
-
-    /**
-     * 性能分析拦截器,不建议生产使用
-     */
-//    @Bean
-//    public PerformanceInterceptor performanceInterceptor(){
-//        return new PerformanceInterceptor();
-//    }
-
-
-}

+ 23 - 0
src/main/java/com/jsh/erp/constants/ExceptionConstants.java

@@ -353,6 +353,25 @@ public class ExceptionConstants {
     //EXCEL中有副条码在系统中已存在(除自身商品之外)
     public static final int MATERIAL_EXCEL_IMPORT_MANY_BARCODE_EXIST_CODE = 80000028;
     public static final String MATERIAL_EXCEL_IMPORT_MANY_BARCODE_EXIST_MSG = "抱歉,EXCEL中有副条码在系统中已存在,具体副条码为:%s";
+    //基本单位为空
+    public static final int MATERIAL_Category_Name_EMPTY_CODE = 8000029;
+    public static final String MATERIAL_Category_Name_EMPTY_MSG = "第%s行类别为空";
+
+    //类型不存在错误
+    public static final int MATERIAL_TYPE_NOT_DECIMAL_CODE = 8000030;
+    public static final String MATERIAL_TYPE_NOT_DECIMAL_MSG = "第%s行类别不存在";
+
+    //供应商不存在错误
+    public static final int MATERIAL_SUPPLIER_NOT_DECIMAL_CODE = 8000031;
+    public static final String MATERIAL_SUPPLIER_NOT_DECIMAL_MSG = "第%s行供应商不存在";
+
+    //仓库不存在错误
+    public static final int MATERIAL_DEPOT_NOT_DECIMAL_CODE = 8000031;
+    public static final String MATERIAL_DEPOT_NOT_DECIMAL_MSG = "第%s行仓库不存在";
+
+    //erp_sku 不存在
+    public static final int MATERIAL_ERP_SKU_NOT_DECIMAL_CODE = 8000032;
+    public static final String MATERIAL_ERP_SKU_NOT_DECIMAL_MSG = "商品erp_sku[%s]不存在";
 
     /**
      *  单据信息
@@ -443,6 +462,10 @@ public class ExceptionConstants {
     public static final int DEPOT_ITEM_EXIST_NEW_STATUS_FAILED_CODE = 8500030;
     public static final String DEPOT_ITEM_EXIST_NEW_STATUS_FAILED_MSG = "抱歉,单据:%s最新状态不能进行批量操作";
 
+    public static final int DEPOT_HEAD_NOT_EXIST_CODE = 8500031;
+    public static final String DEPOT_HEAD_NOT_EXIST_MSG = "抱歉,单据不存在";
+
+
     /**
      *  单据明细信息
      * type = 90

+ 1 - 5
src/main/java/com/jsh/erp/controller/DepotHeadController.java

@@ -12,11 +12,7 @@ import com.jsh.erp.datasource.vo.DepotHeadVo4InDetail;
 import com.jsh.erp.datasource.vo.DepotHeadVo4InOutMCount;
 import com.jsh.erp.datasource.vo.DepotHeadVo4List;
 import com.jsh.erp.datasource.vo.DepotHeadVo4StatementAccount;
-import com.jsh.erp.service.DepotService;
-import com.jsh.erp.service.DepotHeadService;
-import com.jsh.erp.service.MaterialService;
-import com.jsh.erp.service.SystemConfigService;
-import com.jsh.erp.service.UserService;
+import com.jsh.erp.service.*;
 import com.jsh.erp.utils.*;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;

+ 31 - 22
src/main/java/com/jsh/erp/controller/DepotItemController.java

@@ -9,14 +9,7 @@ import com.jsh.erp.datasource.vo.DepotItemStockWarningCount;
 import com.jsh.erp.datasource.vo.DepotItemVoBatchNumberList;
 import com.jsh.erp.datasource.vo.InOutPriceVo;
 import com.jsh.erp.exception.BusinessRunTimeException;
-import com.jsh.erp.service.DepotService;
-import com.jsh.erp.service.DepotHeadService;
-import com.jsh.erp.service.DepotItemService;
-import com.jsh.erp.service.MaterialService;
-import com.jsh.erp.service.RoleService;
-import com.jsh.erp.service.SystemConfigService;
-import com.jsh.erp.service.UnitService;
-import com.jsh.erp.service.UserService;
+import com.jsh.erp.service.*;
 import com.jsh.erp.utils.*;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -156,7 +149,7 @@ public class DepotItemController {
         Map<String, Object> map = new HashMap<String, Object>();
         try {
             BigDecimal stock = BigDecimal.ZERO;
-            List<MaterialVo4Unit> list = materialService.getMaterialByBarCode(barCode);
+            List<MaterialVo4Unit> list = materialService.getMaterialByBatchNumber(barCode);
             if(list!=null && list.size()>0) {
                 MaterialVo4Unit materialVo4Unit = list.get(0);
                 if(StringUtil.isNotEmpty(materialVo4Unit.getSku())){
@@ -280,6 +273,19 @@ public class DepotItemController {
                     item.put("anotherDepotName", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotName());
                     item.put("mType", diEx.getMaterialType());
                     item.put("op", 1);
+                    item.put("productionDate",diEx.getProductionDate());
+                    item.put("expiryNum",diEx.getExpiryNum());
+                    item.put("supplierId",diEx.getSupplierId());
+                    item.put("batchNumber",diEx.getBatchNumber());
+                    item.put("inventory",diEx.getInventory());
+                    item.put("supplierName",diEx.getSupplierName());
+                    item.put("unitId",diEx.getUnitId());
+                    item.put("unitList",diEx.getUnitId() == null ? null : unitService.getUnitListByID(diEx.getUnitId()));
+                    item.put("actualQuantityInStorage",diEx.getActualQuantityInStorage());
+                    item.put("warehousingVariance",diEx.getWarehousingVariance());
+                    item.put("reasonOfDifference",diEx.getReasonOfDifference());
+                    item.put("warehousingUser",diEx.getWarehousingUser());
+                    item.put("warehousingTime",diEx.getWarehousingTime());
                     dataArray.add(item);
                     //合计数据汇总
                     totalOperNumber = totalOperNumber.add(diEx.getOperNumber()==null?BigDecimal.ZERO:diEx.getOperNumber());
@@ -951,7 +957,6 @@ public class DepotItemController {
     @ApiOperation(value = "获取批次商品列表信息")
     public BaseResponseInfo getBatchNumberList(@RequestParam("name") String name,
                                                @RequestParam("depotItemId") Long depotItemId,
-                                               @RequestParam("depotId") Long depotId,
                                                @RequestParam("barCode") String barCode,
                                                @RequestParam(value = "batchNumber", required = false) String batchNumber,
                                                HttpServletRequest request) throws Exception{
@@ -965,7 +970,7 @@ public class DepotItemController {
             }
             Boolean forceFlag = systemConfigService.getForceApprovalFlag();
             Boolean inOutManageFlag = systemConfigService.getInOutManageFlag();
-            List<DepotItemVoBatchNumberList> list = depotItemService.getBatchNumberList(number, name, depotId, barCode,
+            List<DepotItemVoBatchNumberList> list = depotItemService.getBatchNumberList(number, name, null, barCode,
                     batchNumber, forceFlag, inOutManageFlag);
             map.put("rows", list);
             map.put("total", list.size());
@@ -994,7 +999,7 @@ public class DepotItemController {
         Map<String, Object> data = new HashMap<>();
         String message = "";
         try {
-            String barCodes = "";
+            String batchNumbers = "";
             //文件合法性校验
             Sheet src = null;
             try {
@@ -1014,22 +1019,23 @@ public class DepotItemController {
             } else {
                 List<Map<String, String>> detailList = new ArrayList<>();
                 for (int i = 2; i < src.getRows(); i++) {
-                    String depotName = "", barCode = "", num = "", unitPrice = "", taxRate = "", remark = "";
+                    String depotName = "", batchNumber = "", num = "", unitPrice = "", taxRate = "", remark = "";
                     if("QGD".equals(prefixNo)) {
-                        barCode = ExcelUtils.getContent(src, i, 0);
+                        batchNumber = ExcelUtils.getContent(src, i, 0);
                         num = ExcelUtils.getContent(src, i, 2);
                         remark = ExcelUtils.getContent(src, i, 3);
                     }
                     if("CGDD".equals(prefixNo) || "XSDD".equals(prefixNo)) {
-                        barCode = ExcelUtils.getContent(src, i, 0);
+                        batchNumber = ExcelUtils.getContent(src, i, 0);
                         num = ExcelUtils.getContent(src, i, 2);
                         unitPrice = ExcelUtils.getContent(src, i, 3);
                         taxRate = ExcelUtils.getContent(src, i, 4);
                         remark = ExcelUtils.getContent(src, i, 5);
                     }
                     if("CGRK".equals(prefixNo) || "XSCK".equals(prefixNo)) {
+                        //采购入库
                         depotName = ExcelUtils.getContent(src, i, 0);
-                        barCode = ExcelUtils.getContent(src, i, 1);
+                        batchNumber = ExcelUtils.getContent(src, i, 1);
                         num = ExcelUtils.getContent(src, i, 3);
                         unitPrice = ExcelUtils.getContent(src, i, 4);
                         taxRate = ExcelUtils.getContent(src, i, 5);
@@ -1037,25 +1043,25 @@ public class DepotItemController {
                     }
                     if("QTRK".equals(prefixNo) || "QTCK".equals(prefixNo)) {
                         depotName = ExcelUtils.getContent(src, i, 0);
-                        barCode = ExcelUtils.getContent(src, i, 1);
+                        batchNumber = ExcelUtils.getContent(src, i, 1);
                         num = ExcelUtils.getContent(src, i, 3);
                         unitPrice = ExcelUtils.getContent(src, i, 4);
                         remark = ExcelUtils.getContent(src, i, 5);
                     }
                     Map<String, String> materialMap = new HashMap<>();
                     materialMap.put("depotName", depotName);
-                    materialMap.put("barCode", barCode);
+                    materialMap.put("batchNumber", batchNumber);
                     materialMap.put("num", num);
                     materialMap.put("unitPrice", unitPrice);
                     materialMap.put("taxRate", taxRate);
                     materialMap.put("remark", remark);
                     detailList.add(materialMap);
-                    barCodes += "'" + barCode + "',";
+                    batchNumbers += "'" + batchNumber + "',";
                 }
-                if (StringUtil.isNotEmpty(barCodes)) {
-                    barCodes = barCodes.substring(0, barCodes.length() - 1);
+                if (StringUtil.isNotEmpty(batchNumbers)) {
+                    batchNumbers = batchNumbers.substring(0, batchNumbers.length() - 1);
                 }
-                JSONObject map = depotItemService.parseMapByExcelData(barCodes, detailList, prefixNo);
+                JSONObject map = depotItemService.parseMapByExcelData(batchNumbers, detailList, prefixNo);
                 if (map != null) {
                     res.code = 200;
                 } else {
@@ -1076,4 +1082,7 @@ public class DepotItemController {
         }
         return res;
     }
+
+
+
 }

+ 163 - 17
src/main/java/com/jsh/erp/controller/MaterialController.java

@@ -8,13 +8,7 @@ import com.jsh.erp.datasource.entities.Material;
 import com.jsh.erp.datasource.entities.MaterialExtend;
 import com.jsh.erp.datasource.entities.MaterialVo4Unit;
 import com.jsh.erp.datasource.entities.Unit;
-import com.jsh.erp.service.DepotService;
-import com.jsh.erp.service.DepotItemService;
-import com.jsh.erp.service.MaterialService;
-import com.jsh.erp.service.RoleService;
-import com.jsh.erp.service.SystemConfigService;
-import com.jsh.erp.service.UnitService;
-import com.jsh.erp.service.UserService;
+import com.jsh.erp.service.*;
 import com.jsh.erp.utils.*;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -317,9 +311,9 @@ public class MaterialController extends BaseController {
             }
             List<MaterialVo4Unit> dataList = materialService.findBySelectWithBarCode(categoryId, q, StringUtil.toNull(standardOrModel),
                     StringUtil.toNull(color), StringUtil.toNull(brand), StringUtil.toNull(mfrs), enableSerialNumber, enableBatchNumber,
-                    (currentPage-1)*pageSize, pageSize);
+                    (currentPage-1)*pageSize, pageSize,depotId);
             int total = materialService.findBySelectWithBarCodeCount(categoryId, q, StringUtil.toNull(standardOrModel),
-                    StringUtil.toNull(color), StringUtil.toNull(brand), StringUtil.toNull(mfrs), enableSerialNumber, enableBatchNumber);
+                    StringUtil.toNull(color), StringUtil.toNull(brand), StringUtil.toNull(mfrs), enableSerialNumber, enableBatchNumber,depotId);
             object.put("total", total);
             JSONArray dataArray = new JSONArray();
             //存放数据json数组
@@ -327,6 +321,7 @@ public class MaterialController extends BaseController {
                 for (MaterialVo4Unit material : dataList) {
                     JSONObject item = new JSONObject();
                     item.put("id", material.getMeId()); //商品扩展表的id
+                    item.put("mid", material.getId()); //商品扩展表的id
                     String ratioStr = ""; //比例
                     Unit unit = new Unit();
                     if (material.getUnitId() == null) {
@@ -348,7 +343,7 @@ public class MaterialController extends BaseController {
                             ratioStr = "[" + unit.getRatioThree().stripTrailingZeros().toPlainString() + unit.getBasicUnit() + "]";
                         }
                     }
-                    item.put("mBarCode", material.getmBarCode());
+                    item.put("barCode", material.getBarCode());
                     item.put("name", material.getName());
                     item.put("mnemonic", material.getMnemonic());
                     item.put("categoryName", material.getCategoryName());
@@ -356,11 +351,20 @@ public class MaterialController extends BaseController {
                     item.put("model", material.getModel());
                     item.put("color", material.getColor());
                     item.put("brand", material.getBrand());
-                    item.put("mfrs", material.getMfrs());
+                    //item.put("mfrs", material.getMfrs());
                     item.put("unit", material.getCommodityUnit() + ratioStr);
                     item.put("sku", material.getSku());
                     item.put("enableSerialNumber", material.getEnableSerialNumber());
                     item.put("enableBatchNumber", material.getEnableBatchNumber());
+                    item.put("productionDate",material.getProductionDate());
+                    item.put("expiryNum",material.getExpiryNum());
+                    item.put("batchNumber",material.getBatchNumber());
+                    item.put("position",material.getPosition());
+                    item.put("supplierId",material.getSupplierId());
+                    item.put("supplierName",material.getSupplierName());
+                    item.put("depotId",material.getDepotId());
+                    item.put("depotName",material.getDepotName());
+                    item.put("unitId",material.getUnitId());
                     BigDecimal stock;
                     if(StringUtil.isNotEmpty(material.getSku())){
                         stock = depotItemService.getSkuStockByParam(depotId,material.getMeId(),null,null);
@@ -490,7 +494,7 @@ public class MaterialController extends BaseController {
                             HttpServletRequest request, HttpServletResponse response) throws Exception{
         BaseResponseInfo res = new BaseResponseInfo();
         try {
-            res = materialService.importExcel(file, request);
+            res = materialService.importExcelTwo(file, request);
         } catch (Exception e) {
             logger.error(e.getMessage(), e);
         }
@@ -575,11 +579,11 @@ public class MaterialController extends BaseController {
     @GetMapping(value = "/getMaterialByBarCode")
     @ApiOperation(value = "根据条码查询商品信息")
     public BaseResponseInfo getMaterialByBarCode(@RequestParam("barCode") String barCode,
-                                          @RequestParam(value = "organId", required = false) Long organId,
-                                          @RequestParam(value = "depotId", required = false) Long depotId,
-                                          @RequestParam("mpList") String mpList,
-                                          @RequestParam(required = false, value = "prefixNo") String prefixNo,
-                                          HttpServletRequest request) throws Exception {
+                                                 @RequestParam(value = "organId", required = false) Long organId,
+                                                 @RequestParam(value = "depotId", required = false) Long depotId,
+                                                 @RequestParam("mpList") String mpList,
+                                                 @RequestParam(required = false, value = "prefixNo") String prefixNo,
+                                                 HttpServletRequest request) throws Exception {
         BaseResponseInfo res = new BaseResponseInfo();
         try {
             Long userId = userService.getUserId(request);
@@ -820,4 +824,146 @@ public class MaterialController extends BaseController {
         }
         return res;
     }
+
+    /**
+     * 根据批次号查询商品信息
+     * @return
+     * @throws Exception
+     */
+    @GetMapping(value = "/getMaterialByBatchNumber")
+    @ApiOperation(value = "根据批次号查询商品信息")
+    public BaseResponseInfo getMaterialByBatchNumber(@RequestParam("batchNumber") String batchNumber,
+                                                     @RequestParam(value = "organId", required = false) Long organId,
+                                                     @RequestParam(value = "depotId", required = false) Long depotId,
+                                                     @RequestParam("mpList") String mpList,
+                                                     @RequestParam(required = false, value = "prefixNo") String prefixNo,
+                                                     HttpServletRequest request) throws Exception {
+        BaseResponseInfo res = new BaseResponseInfo();
+        try {
+            Long userId = userService.getUserId(request);
+            String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
+            String[] mpArr = mpList.split(",");
+            //支持序列号查询,先根据序列号查询条码,如果查不到就直接查条码
+//            MaterialExtend materialExtend = materialService.getMaterialExtendBySerialNumber(barCode);
+//            if(materialExtend!=null && StringUtil.isNotEmpty(materialExtend.getBarCode())) {
+//                barCode = materialExtend.getBarCode();
+//            }
+            List<MaterialVo4Unit> list = materialService.getMaterialByBatchNumber(batchNumber);
+            if(list!=null && list.size()>0) {
+                for(MaterialVo4Unit mvo: list) {
+                    mvo.setMaterialOther(materialService.getMaterialOtherByParam(mpArr, mvo));
+                    if ("LSCK".equals(prefixNo) || "LSTH".equals(prefixNo)) {
+                        //零售价
+                        mvo.setBillPrice(mvo.getCommodityDecimal());
+                    } else if ("CGDD".equals(prefixNo) || "CGRK".equals(prefixNo) || "CGTH".equals(prefixNo)) {
+                        //采购价
+                        mvo.setBillPrice(mvo.getPurchaseDecimal());
+                    } else if("QTRK".equals(prefixNo) || "DBCK".equals(prefixNo) || "ZZD".equals(prefixNo) || "CXD".equals(prefixNo)
+                            || "PDLR".equals(prefixNo) || "PDFP".equals(prefixNo)) {
+                        //采购价-给录入界面按权限屏蔽
+                        mvo.setBillPrice(roleService.parseBillPriceByLimit(mvo.getPurchaseDecimal(), "buy", priceLimit, request));
+                    } if ("XSDD".equals(prefixNo) || "XSCK".equals(prefixNo) || "XSTH".equals(prefixNo) || "QTCK".equals(prefixNo)) {
+                        //销售价
+                        if(organId == null) {
+                            mvo.setBillPrice(mvo.getWholesaleDecimal());
+                        } else {
+                            //查询最后一单的销售价,实现不同的客户不同的销售价
+                            BigDecimal lastUnitPrice = depotItemService.getLastUnitPriceByParam(organId, mvo.getMeId(), prefixNo);
+                            mvo.setBillPrice(lastUnitPrice!=null? lastUnitPrice : mvo.getWholesaleDecimal());
+                        }
+                        //销售价-给录入界面按权限屏蔽价格
+                        if("QTCK".equals(prefixNo)) {
+                            mvo.setBillPrice(roleService.parseBillPriceByLimit(mvo.getWholesaleDecimal(), "sale", priceLimit, request));
+                        }
+                    }
+                    //仓库id
+//                    if (depotId == null) {
+//                        JSONArray depotArr = depotService.findDepotByCurrentUser();
+//                        for (Object obj : depotArr) {
+//                            JSONObject depotObj = JSONObject.parseObject(obj.toString());
+//                            if (depotObj.get("isDefault") != null) {
+//                                Boolean isDefault = depotObj.getBoolean("isDefault");
+//                                if (isDefault) {
+//                                    Long id = depotObj.getLong("id");
+//                                    if (!"CGDD".equals(prefixNo) && !"XSDD".equals(prefixNo)) {
+//                                        //除订单之外的单据才有仓库
+//                                        mvo.setDepotId(id);
+//                                    }
+//                                    getStockByMaterialInfo(mvo);
+//                                }
+//                            }
+//                        }
+//                    } else {
+//                        mvo.setDepotId(depotId);
+//                        getStockByMaterialInfo(mvo);
+//                    }
+                }
+            }
+            res.code = 200;
+            res.data = list;
+        } catch(Exception e){
+            logger.error(e.getMessage(), e);
+            res.code = 500;
+            res.data = "获取数据失败";
+        }
+        return res;
+    }
+
+    @GetMapping(value = "/getMaterialById")
+    @ApiOperation(value = "根据商品id查询商品及子表信息")
+    public BaseResponseInfo getMaterialById(@RequestParam("mid") Long materialId,
+                                          HttpServletRequest request)throws Exception {
+        BaseResponseInfo res = new BaseResponseInfo();
+        res.code = 200;
+        res.data = materialService.getMaterialById(materialId);
+        return res;
+    }
+
+    @GetMapping(value = "/getMaterialWarn")
+    @ApiOperation(value = "获取商品提醒")
+    public BaseResponseInfo getMaterialWarn()throws Exception {
+        BaseResponseInfo res = new BaseResponseInfo();
+        res.code = 200;
+        res.data = materialService.getMaterialWarn();
+        return res;
+    }
+
+    /**
+     * 商品信息全选获取批次号
+     */
+    @GetMapping(value = "/findBatchNumbersBySelect")
+    @ApiOperation(value = "商品选择全选获取商品批次号")
+    public BaseResponseInfo findBatchNumberSBySelect(@RequestParam(value = "categoryId", required = false) Long categoryId,
+                                           @RequestParam(value = "q", required = false) String q,
+                                           @RequestParam(value = "standardOrModel", required = false) String standardOrModel,
+                                           @RequestParam(value = "mpList", required = false) String mpList,
+                                           @RequestParam(value = "depotId", required = false) Long depotId,
+                                           @RequestParam(value = "color", required = false) String color,
+                                           @RequestParam(value = "brand", required = false) String brand,
+                                           @RequestParam(value = "mfrs", required = false) String mfrs,
+                                           @RequestParam(value = "enableSerialNumber", required = false) String enableSerialNumber,
+                                           @RequestParam(value = "enableBatchNumber", required = false) String enableBatchNumber,
+                                           HttpServletRequest request){
+        BaseResponseInfo res = new BaseResponseInfo();
+        try {
+            List<MaterialVo4Unit> dataList = materialService.findBySelectWithBarCode(categoryId, q, StringUtil.toNull(standardOrModel),
+                    StringUtil.toNull(color), StringUtil.toNull(brand), StringUtil.toNull(mfrs), enableSerialNumber, enableBatchNumber,
+                    null, null,depotId);
+            StringBuffer str = new StringBuffer();
+            //存放数据json数组
+            if (null != dataList) {
+                for (MaterialVo4Unit material : dataList) {
+                    str.append("," + material.getBatchNumber());
+                }
+            }
+            res.code = 200;
+            res.data = str.deleteCharAt(0);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+            res.code = 500;
+        }
+        return res;
+    }
+
+
 }

+ 8 - 0
src/main/java/com/jsh/erp/controller/MaterialExtendController.java

@@ -108,6 +108,14 @@ public class MaterialExtendController {
                     item.put("commodityDecimal", md.getCommodityDecimal());
                     item.put("wholesaleDecimal", md.getWholesaleDecimal());
                     item.put("lowDecimal", md.getLowDecimal());
+                    item.put("productionDate",md.getProductionDate());
+                    item.put("expiryNum",md.getExpiryNum());
+                    item.put("supplierId",md.getSupplierId());
+                    item.put("barCode",md.getBarCode());
+                    item.put("batchNumber",md.getBatchNumber());
+                    item.put("inventory",md.getInventory());
+                    item.put("depotId",md.getDepotId());
+                    item.put("position",md.getPosition());
                     dataArray.add(item);
                 }
             }

+ 56 - 0
src/main/java/com/jsh/erp/controller/OpenController.java

@@ -0,0 +1,56 @@
+package com.jsh.erp.controller;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.jsh.erp.datasource.entities.MaterialVo4Unit;
+import com.jsh.erp.service.MaterialService;
+import com.jsh.erp.service.SyncTescoSystemService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @Description 外部接口
+ * @Author MS.BLUE
+ * @Date 2025-04-12
+ */
+@RestController
+@RequestMapping(value = "/open-api")
+@Api(tags = {"外部接口"})
+public class OpenController {
+
+    private Logger logger = LoggerFactory.getLogger(OpenController.class);
+
+    @Resource
+    private SyncTescoSystemService syncTescoSystemService;
+
+    /**
+     * 获取商品系统sku,返回结果为json格式
+     * @param param 商品条码 ,[{"barCode":"1"},{"barCode":"2"}]
+     * @return 返回结果,JSON格式,{"code":0,"data":[{"barCode":"1","systemSku":"20230412100000000001"}]}
+     */
+    @ApiOperation(value = "获取商品系统sku,返回信息集采系统")
+    @PostMapping(value = "/sync-system-sku")
+    public String syncSystemSku(@RequestBody String param) {
+        return syncTescoSystemService.syncSystemSku(param);
+    }
+
+
+    @ApiOperation(value = "同步集采订单-》销售订单")
+    @PostMapping(value = "/sync-order")
+    public String syncOrder(@RequestBody String param){
+        return syncTescoSystemService.syncOrder(param);
+    }
+
+
+
+}

+ 43 - 0
src/main/java/com/jsh/erp/controller/OssController.java

@@ -0,0 +1,43 @@
+package com.jsh.erp.controller;
+
+import com.jsh.erp.base.AjaxResult;
+import com.jsh.erp.utils.OssUtils;
+import io.swagger.annotations.Api;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.util.List;
+
+@RestController
+@Api(tags = "OSS对象存储Controller")
+@RequestMapping("/oss")
+public class OssController {
+    @Autowired
+    OssUtils ossUtils;
+
+    @PostMapping("upload")
+    public AjaxResult uploadFile(MultipartFile file) {
+        //返回上传oss的url
+        String url = ossUtils.uploadOneFile(file);
+        AjaxResult ajax = AjaxResult.success();
+        ajax.put("fileName", file.getOriginalFilename());
+        ajax.put("url", url);
+        return ajax;
+    }
+
+    @PostMapping("uploadArrayFile")
+    public List<String> uploadArrayFile(MultipartFile[] files) {
+        //返回上传oss的url
+        return ossUtils.uploadArrayFile(files);
+    }
+
+    @PostMapping("deleteFile")
+    public boolean deleteFile(@RequestBody String fileUrl) {
+        //返回是否删除成功
+        return ossUtils.deleteFile(fileUrl);
+    }
+}

+ 44 - 1
src/main/java/com/jsh/erp/controller/SupplierController.java

@@ -297,7 +297,7 @@ public class SupplierController extends BaseController {
 
     /**
      * 用户对应客户显示
-     * @param type
+     * @param type UserCustomer-客户;UserSupplier-供应商
      * @param keyId
      * @param request
      * @return
@@ -343,6 +343,49 @@ public class SupplierController extends BaseController {
         return arr;
     }
 
+
+    @GetMapping(value = "/findUserSupplier")
+    @ApiOperation(value = "用户对应供应商显示")
+    public JSONArray findUserSupplier(@RequestParam(value = "UBType",defaultValue = "UserSupplier") String type,
+                                      @RequestParam(value = "UBKeyId") String keyId,
+                                   HttpServletRequest request) throws Exception{
+        JSONArray arr = new JSONArray();
+        try {
+            //获取权限信息
+            String ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, keyId);
+            List<Supplier> dataList = supplierService.findBySelectSup();
+            //开始拼接json数据
+            JSONObject outer = new JSONObject();
+            outer.put("id", 0);
+            outer.put("key", 0);
+            outer.put("value", 0);
+            outer.put("title", "供应商列表");
+            outer.put("attributes", "供应商列表");
+            //存放数据json数组
+            JSONArray dataArray = new JSONArray();
+            if (null != dataList) {
+                for (Supplier supplier : dataList) {
+                    JSONObject item = new JSONObject();
+                    item.put("id", supplier.getId());
+                    item.put("key", supplier.getId());
+                    item.put("value", supplier.getId());
+                    item.put("title", supplier.getSupplier());
+                    item.put("attributes", supplier.getSupplier());
+                    Boolean flag = ubValue.contains("[" + supplier.getId().toString() + "]");
+                    if (flag) {
+                        item.put("checked", true);
+                    }
+                    dataArray.add(item);
+                }
+            }
+            outer.put("children", dataArray);
+            arr.add(outer);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        }
+        return arr;
+    }
+
     /**
      * 根据客户或供应商查询期初、期初已收等信息
      * @param organId

+ 17 - 0
src/main/java/com/jsh/erp/controller/UnitController.java

@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.jsh.erp.base.BaseController;
 import com.jsh.erp.base.TableDataInfo;
 import com.jsh.erp.datasource.entities.Unit;
+import com.jsh.erp.datasource.vo.UnitListVo;
 import com.jsh.erp.service.UnitService;
 import com.jsh.erp.utils.*;
 import io.swagger.annotations.Api;
@@ -14,6 +15,8 @@ import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
+import java.math.BigDecimal;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -147,4 +150,18 @@ public class UnitController extends BaseController {
             return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
         }
     }
+
+    /**
+     * 根据单位id获取单位集合
+     */
+    @GetMapping(value = "/getUnitListByID")
+    @ApiOperation(value = "根据单位id获取单位集合")
+    public BaseResponseInfo getUnitListByID(Long id) throws Exception {
+        BaseResponseInfo res = new BaseResponseInfo();
+        res.code = 200;
+        res.data = unitService.getUnitListByID(id);
+        return res;
+    }
+
+
 }

+ 18 - 10
src/main/java/com/jsh/erp/controller/UserController.java

@@ -149,6 +149,24 @@ public class UserController extends BaseController {
         return res;
     }
 
+    @PostMapping(value = "/pdaLogin")
+    @ApiOperation(value = "PDA登录")
+    public BaseResponseInfo pdaLogin(@RequestBody UserEx userParam, HttpServletRequest request) throws Exception {
+        BaseResponseInfo res = new BaseResponseInfo();
+        try {
+            Map<String, Object> data = userService.login(userParam.getLoginName().trim(), userParam.getPassword().trim(), request);
+            res.code = 200;
+            res.data = data;
+        } catch (BusinessRunTimeException e) {
+            throw new BusinessRunTimeException(e.getCode(), e.getMessage());
+        } catch(Exception e){
+            logger.error(e.getMessage(), e);
+            res.code = 500;
+            res.data = "用户登录失败";
+        }
+        return res;
+    }
+
     @PostMapping(value = "/weixinLogin")
     @ApiOperation(value = "微信登录")
     public BaseResponseInfo weixinLogin(@RequestBody JSONObject jsonObject,
@@ -518,17 +536,7 @@ public class UserController extends BaseController {
             User user = userService.getUser(userId);
             //获取当前用户数
             int userCurrentNum = userService.getUser(request).size();
-            Tenant tenant = tenantService.getTenantByTenantId(user.getTenantId());
-            if(tenant.getExpireTime()!=null && tenant.getExpireTime().getTime()<System.currentTimeMillis()){
-                //租户已经过期,移除token
-                redisService.deleteObjectBySession(request,"userId");
-                redisService.deleteObjectBySession(request,"clientIp");
-            }
-            data.put("type", tenant.getType()); //租户类型,0免费租户,1付费租户
-            data.put("expireTime", Tools.parseDateToStr(tenant.getExpireTime()));
             data.put("userCurrentNum", userCurrentNum);
-            data.put("userNumLimit", tenant.getUserNumLimit());
-            data.put("tenantId", tenant.getTenantId());
             res.code = 200;
             res.data = data;
         } catch (Exception e) {

+ 191 - 0
src/main/java/com/jsh/erp/controller/pda/PdaController.java

@@ -0,0 +1,191 @@
+package com.jsh.erp.controller.pda;
+
+import cn.hutool.core.util.ObjectUtil;
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
+import com.jsh.erp.base.AjaxResult;
+import com.jsh.erp.base.BaseController;
+import com.jsh.erp.base.TableDataInfo;
+import com.jsh.erp.datasource.entities.DepotHead;
+import com.jsh.erp.datasource.entities.Supplier;
+import com.jsh.erp.datasource.entities.TaskStocktakingItem;
+import com.jsh.erp.datasource.entities.User;
+import com.jsh.erp.datasource.pda.dto.PDADepotHeadDTO;
+import com.jsh.erp.datasource.pda.dto.PDATaskStocktakingDTO;
+import com.jsh.erp.datasource.pda.vo.PDADepotHeadVO;
+import com.jsh.erp.datasource.pda.vo.PDADepotItemVO;
+import com.jsh.erp.datasource.pda.vo.PDATaskStocktakingItemVO;
+import com.jsh.erp.datasource.pda.vo.PDATaskStocktakingVO;
+import com.jsh.erp.datasource.vo.TaskStocktakingVO;
+import com.jsh.erp.query.LambdaQueryWrapperX;
+import com.jsh.erp.service.*;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiModelProperty;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+@RestController
+@RequestMapping(value = "/pda")
+@Api(tags = {"PDA接口"})
+public class PdaController extends BaseController {
+
+    @Resource
+    private DepotHeadService depotHeadService;
+
+    @Resource
+    private DepotItemService depotItemService;
+
+    @Resource
+    private SupplierService supplierService;
+
+    @Resource
+    private TaskStocktakingService taskStocktakingService;
+
+    @Resource
+    private TaskStocktakingItemService taskStocktakingItemService;
+
+    @Resource
+    private UserService userService;
+
+    /**
+     * 采购入库
+     * @return
+     */
+    @PostMapping ("/purchaseInventory")
+    @ApiOperation(value = "采购入库")
+    public TableDataInfo purchaseInventory(@RequestBody PDADepotHeadDTO pdaDepotHeadDTO) {
+        pdaDepotHeadDTO.setSubType("采购订单");
+        startPage();
+        List<PDADepotHeadVO> pdaDepotHeadVOList = depotHeadService.pdaList(pdaDepotHeadDTO);
+        return getDataTable(pdaDepotHeadVOList);
+    }
+
+    @PostMapping("/saleOrder")
+    @ApiOperation(value = "检货任务")
+    public TableDataInfo saleOrder(@RequestBody PDADepotHeadDTO pdaDepotHeadDTO) {
+        pdaDepotHeadDTO.setSubType("销售订单");
+        startPage();
+        List<PDADepotHeadVO> pdaDepotHeadVOList = depotHeadService.pdaList(pdaDepotHeadDTO);
+        return getDataTable(pdaDepotHeadVOList);
+    }
+
+    @ApiModelProperty(value = "订单详情")
+    @GetMapping("/orderInfo/{id}")
+    public AjaxResult orderInfo(@PathVariable("id") Long id){
+        DepotHead depotHead = depotHeadService.getOne(new LambdaQueryWrapperX<DepotHead>().eq(DepotHead::getId, id));
+        depotHead.setSupplierName(supplierService.getOne(new LambdaQueryWrapperX<Supplier>().eq(Supplier::getId, depotHead.getOrganId())).getSupplier());
+        return AjaxResult.success(depotHead);
+    }
+
+    @GetMapping("/orderDetail/{id}")
+    @ApiOperation("订单明细")
+    public TableDataInfo orderDetail(@PathVariable("id") Long id) {
+        startPage();
+        List<PDADepotItemVO> list = depotItemService.pdaList(id);
+        return getDataTable(list);
+    }
+
+    @ApiOperation("订单开始处理")
+    @GetMapping("/orderStartHandle/{id}")
+    public AjaxResult orderStartHandle(@PathVariable("id") Long id) {
+        depotHeadService.update(new UpdateWrapper<DepotHead>().set("status", "4").eq("id", id));
+        return AjaxResult.success();
+    }
+
+    @ApiOperation("商品详情")
+    @GetMapping("/materialDetail/{id}")
+    public AjaxResult materialDetail(@PathVariable("id") Long id) {
+        return AjaxResult.success(depotItemService.pdaDetail(id));
+    }
+
+    @ApiOperation("商品库存详情")
+    @GetMapping("/materialDepotDetail/{type}/{materialId}")
+    public TableDataInfo materialDepotDetail(@PathVariable("type") String type, @PathVariable("materialId") Long materialId) {
+        startPage();
+        if ("out".equals(type)) {
+            type = "入库";
+        } else {
+            type = "出库";
+        }
+        List<PDADepotItemVO> list = depotItemService.materialDepotDetail(type , materialId);
+        return getDataTable(list);
+    }
+
+    @ApiOperation("盘点任务列表")
+    @PostMapping("/taskStocktakingList")
+    public TableDataInfo taskStocktakingList(@RequestBody PDATaskStocktakingDTO pdaTaskStocktakingDTO) {
+        startPage();
+        List<PDATaskStocktakingVO> list = taskStocktakingService.pdaList(pdaTaskStocktakingDTO.getNumber(), pdaTaskStocktakingDTO.getStatus());
+        return getDataTable(list);
+    }
+
+    @ApiOperation(value = "盘点任务详情-商品列表")
+    @GetMapping("/taskStocktakingItemList/{taskId}")
+    public TableDataInfo taskStocktakingItemList(@PathVariable("taskId") Long taskId){
+        startPage();
+        List<PDATaskStocktakingItemVO> list = taskStocktakingService.pdaItemList(taskId);
+        return getDataTable(list);
+    }
+
+    @ApiOperation("盘点任务详情")
+    @GetMapping("/taskStocktakingDetail/{taskId}")
+    public AjaxResult taskStocktakingDetail(@PathVariable("taskId") Long taskId) throws Exception{
+        TaskStocktakingVO taskStocktakingVO = taskStocktakingService.pdaDetail(taskId);
+        return AjaxResult.success(taskStocktakingVO);
+    }
+
+    @ApiOperation("盘点")
+    @PostMapping("/stocktaking")
+    public AjaxResult stocktaking(@RequestBody TaskStocktakingItem taskStocktakingItem) throws Exception{
+        User currentUser = userService.getCurrentUser();
+        UpdateWrapper<TaskStocktakingItem> updateWrapper = new UpdateWrapper<>();
+        updateWrapper.eq("id", taskStocktakingItem.getId())
+                .set("creator", currentUser.getId())
+                .set("oper_time", new Date());
+        if (ObjectUtil.isNotEmpty(taskStocktakingItem.getNewInventory())) {
+            updateWrapper.set("new_inventory", taskStocktakingItem.getNewInventory());
+        }
+        if (ObjectUtil.isNotEmpty(taskStocktakingItem.getNewPosition())) {
+            updateWrapper.set("new_position", taskStocktakingItem.getNewPosition());
+        }
+        if (ObjectUtil.isNotEmpty(taskStocktakingItem.getDifferenceCount())) {
+            updateWrapper.set("difference_count", taskStocktakingItem.getDifferenceCount());
+        }
+        if (ObjectUtil.isNotEmpty(taskStocktakingItem.getDifferenceReason())){
+            updateWrapper.set("difference_reason", taskStocktakingItem.getDifferenceReason());
+        }
+        taskStocktakingItemService.update(updateWrapper);
+        return AjaxResult.success();
+    }
+
+    @ApiOperation("订单-用于返回字段说明")
+    @GetMapping("test")
+    public AjaxResult test(PDADepotItemVO pdaDepotItemVO) {
+        return AjaxResult.success();
+    }
+
+    @ApiOperation("盘点-用于字段返回说明")
+    @GetMapping("taskTest")
+    public AjaxResult taskTest(PDATaskStocktakingVO pdaTaskStocktakingVO){
+        return AjaxResult.success();
+    }
+
+    /**
+     * PDA订单提交
+     */
+    @PostMapping ("/orderSubmit")
+    @ApiOperation(value = "订单提交")
+    public AjaxResult orderSubmit(@RequestBody PDADepotHeadDTO pdaDepotHeadDTO) {
+        try {
+            depotHeadService.pdaOrderSubmit(pdaDepotHeadDTO);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return AjaxResult.error();
+        }
+        return AjaxResult.success();
+    }
+
+}

+ 138 - 0
src/main/java/com/jsh/erp/controller/stocktaking/StocktakingController.java

@@ -0,0 +1,138 @@
+package com.jsh.erp.controller.stocktaking;
+
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
+import com.jsh.erp.base.AjaxResult;
+import com.jsh.erp.base.BaseController;
+import com.jsh.erp.base.TableDataInfo;
+import com.jsh.erp.datasource.dto.TaskStocktakingDTO;
+import com.jsh.erp.datasource.dto.TaskStocktakingItemDTO;
+import com.jsh.erp.datasource.entities.TaskStocktaking;
+import com.jsh.erp.datasource.entities.TaskStocktakingItem;
+import com.jsh.erp.datasource.entities.User;
+import com.jsh.erp.datasource.vo.SpinnerVO;
+import com.jsh.erp.datasource.vo.TaskStocktakingVO;
+import com.jsh.erp.service.TaskStocktakingItemService;
+import com.jsh.erp.service.TaskStocktakingService;
+import com.jsh.erp.service.UserService;
+import com.jsh.erp.utils.DateUtils;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiModelProperty;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.List;
+
+@RestController
+@RequestMapping(value = "/stocktaking")
+@Api(tags = {"盘点接口"})
+public class StocktakingController extends BaseController {
+
+    @Resource
+    private TaskStocktakingService taskStocktakingService;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private TaskStocktakingItemService taskStocktakingItemService;
+
+    @ApiOperation("盘点任务列表")
+    @PostMapping("/list")
+    public TableDataInfo list(){
+        startPage();
+        List<TaskStocktakingVO> list = taskStocktakingService.listBy();
+        return getDataTable(list);
+    }
+
+    @ApiOperation("新增盘点任务")
+    @PostMapping("/add")
+    public AjaxResult add(@RequestBody TaskStocktakingDTO taskStocktakingDTO) {
+        boolean b = taskStocktakingService.add(taskStocktakingDTO);
+        if (!b){
+            return AjaxResult.error("创建失败,请联系系统管理员");
+        }
+        return AjaxResult.success();
+    }
+
+    @ApiOperation("负责人下拉列表")
+    @GetMapping("/creatorSpinnerList")
+    public AjaxResult creatorSpinnerList() {
+        List<SpinnerVO> spinnerVOList = userService.creatorSpinnerList();
+        return AjaxResult.success(spinnerVOList);
+    }
+
+    /**
+     * 查询任务详情
+     * @param id
+     * @return
+     */
+    @ApiOperation("任务详情")
+    @GetMapping("/detail/{id}")
+    public AjaxResult detail(@PathVariable("id") Long id) throws Exception{
+        return AjaxResult.success(taskStocktakingService.detail(id));
+    }
+
+    /**
+     * 任务详情-商品列表
+     * @param taskStocktakingId 任务ID
+     * @return
+     */
+    @ApiOperation("任务详情-商品列表")
+    @GetMapping("/detailByItemList/{taskStocktakingId}")
+    public AjaxResult detailByItemList(@PathVariable("taskStocktakingId") Long taskStocktakingId) {
+        return AjaxResult.success(taskStocktakingService.listByTaskStocktakingId(taskStocktakingId));
+    }
+
+    @ApiOperation("任务详情-修改")
+    @PostMapping("/detailUpdate")
+    public AjaxResult detailUpdate(@RequestBody TaskStocktakingDTO taskStocktakingDTO) {
+        boolean b = taskStocktakingService.detailUpdate(taskStocktakingDTO);
+        if (!b){
+            return AjaxResult.error("修改失败,请联系系统管理员");
+        }
+        return AjaxResult.success();
+    }
+
+    /**
+     * 任务详情-商品列表-编辑
+     * @return
+     */
+    @ApiModelProperty("任务详情-商品-编辑")
+    @PostMapping("/itemUpdate")
+    public AjaxResult itemUpdate(@RequestBody TaskStocktakingItemDTO taskStocktakingItemDTO) throws Exception {
+        User currentUser = userService.getCurrentUser();
+        taskStocktakingItemService.update(new UpdateWrapper<TaskStocktakingItem>()
+                .set("new_inventory", taskStocktakingItemDTO.getNewInventory())
+                .set("new_position", taskStocktakingItemDTO.getNewPosition())
+                .set("difference_count", taskStocktakingItemDTO.getDifferenceCount())
+                .set("difference_reason", taskStocktakingItemDTO.getDifferenceReason())
+                .set("creator", currentUser.getId())
+                .set("oper_time", DateUtils.getTime())
+                .eq("id", taskStocktakingItemDTO.getId()));
+        return AjaxResult.success();
+    }
+
+    /**
+     * 任务详情-商品-删除
+     * @param id 商品ID
+     * @return
+     */
+    @ApiModelProperty("任务详情-商品-删除")
+    @GetMapping("/itemDelete/{id}")
+    public AjaxResult itemDelete(@PathVariable("id") Long id) {
+        taskStocktakingItemService.update(new UpdateWrapper<TaskStocktakingItem>().set("delete_flag", true).eq("id", id));
+        return AjaxResult.success();
+    }
+
+    @ApiOperation("取消任务")
+    @GetMapping("/taskCancel/{ids}")
+    public AjaxResult taskCancel(@PathVariable("ids") Long[] ids) {
+        Arrays.asList(ids).forEach(id -> {
+            taskStocktakingService.update(new UpdateWrapper<TaskStocktaking>().eq("id", id).set("task_status", "4"));
+        });
+        return AjaxResult.success();
+    }
+
+}

+ 21 - 0
src/main/java/com/jsh/erp/datasource/dto/TaskStocktakingDTO.java

@@ -0,0 +1,21 @@
+package com.jsh.erp.datasource.dto;
+
+import com.jsh.erp.datasource.entities.TaskStocktaking;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 盘点任务
+ */
+@Data
+@Accessors(chain = true)
+public class TaskStocktakingDTO extends TaskStocktaking {
+
+    @ApiModelProperty("商品扩展ID集合")
+    private List<String> materialExtendIdList;
+
+}

+ 32 - 0
src/main/java/com/jsh/erp/datasource/dto/TaskStocktakingItemDTO.java

@@ -0,0 +1,32 @@
+package com.jsh.erp.datasource.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.math.BigDecimal;
+import java.util.Date;
+
+/**
+ * 盘点任务明细
+ */
+@Data
+@Accessors(chain = true)
+public class TaskStocktakingItemDTO {
+
+    @ApiModelProperty("主键ID")
+    private Long id;
+
+    @ApiModelProperty("新仓位货架")
+    private String newPosition;
+
+    @ApiModelProperty("新库存数")
+    private BigDecimal newInventory;
+
+    @ApiModelProperty("差异数量")
+    private Integer differenceCount;
+
+    @ApiModelProperty("差异原因")
+    private String differenceReason;
+
+}

+ 72 - 0
src/main/java/com/jsh/erp/datasource/entities/DepotHead.java

@@ -1,73 +1,145 @@
 package com.jsh.erp.datasource.entities;
 
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
 import java.math.BigDecimal;
 import java.util.Date;
 
+/**
+ * 单据主表实体类
+ */
+@Data
+@TableName("jsh_depot_head")
 public class DepotHead {
+
+    @ApiModelProperty("主键id")
     private Long id;
 
+    @ApiModelProperty("类型(出库/入库)")
     private String type;
 
+    @ApiModelProperty("出入库分类")
     private String subType;
 
+    @ApiModelProperty("初始票据号")
     private String defaultNumber;
 
+    @ApiModelProperty("票据号")
     private String number;
 
+    @ApiModelProperty("创建时间")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     private Date createTime;
 
+    @ApiModelProperty("出入库时间")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     private Date operTime;
 
+    @ApiModelProperty("供应商id")
     private Long organId;
 
+    @ApiModelProperty("操作员")
     private Long creator;
 
+    @ApiModelProperty("账户id")
     private Long accountId;
 
+    @ApiModelProperty("变动金额(收款/付款)")
     private BigDecimal changeAmount;
 
+    @ApiModelProperty("找零金额")
     private BigDecimal backAmount;
 
+    @ApiModelProperty("合计金额")
     private BigDecimal totalPrice;
 
+    @ApiModelProperty("付款类型(现金、记账等)")
     private String payType;
 
+    @ApiModelProperty("单据类型")
     private String billType;
 
+    @ApiModelProperty("备注")
     private String remark;
 
+    @ApiModelProperty("附件名称")
     private String fileName;
 
+    @ApiModelProperty("销售员(可以多个)")
     private String salesMan;
 
+    @ApiModelProperty("多账户ID列表")
     private String accountIdList;
 
+    @ApiModelProperty("多账户金额列表")
     private String accountMoneyList;
 
+    @ApiModelProperty("优惠率")
     private BigDecimal discount;
 
+    @ApiModelProperty("优惠金额")
     private BigDecimal discountMoney;
 
+    @ApiModelProperty("优惠后金额")
     private BigDecimal discountLastMoney;
 
+    @ApiModelProperty("销售或采购费用合计")
     private BigDecimal otherMoney;
 
+    @ApiModelProperty("订金")
     private BigDecimal deposit;
 
+    @ApiModelProperty("状态,0未审核、1已审核、2完成采购|销售、3部分采购|销售、9审核中")
     private String status;
 
+    @ApiModelProperty("采购状态,0未采购、2完成采购、3部分采购")
     private String purchaseStatus;
 
+    @ApiModelProperty("单据来源,0-pc,1-手机")
     private String source;
 
+    @ApiModelProperty("关联订单号")
     private String linkNumber;
 
+    @ApiModelProperty("关联请购单")
     private String linkApply;
 
+    @ApiModelProperty("租户id")
     private Long tenantId;
 
+    @ApiModelProperty("删除标记,0未删除,1删除")
     private String deleteFlag;
 
+    @ApiModelProperty("凭证图片")
+    private String voucherPicture;
+
+    @ApiModelProperty("商品数量")
+    private int goodsQuantity;
+
+    @ApiModelProperty("商品总类数量")
+    private int goodsTypeCount;
+
+    @TableField(exist = false)
+    @ApiModelProperty("供应商名称")
+    private String supplierName;
+
+    @ApiModelProperty("集采订单编号")
+    private String linkTesco;
+
+    @ApiModelProperty("收货人信息")
+    private String receiverName;
+
+    @ApiModelProperty("收货人电话")
+    private String receiverPhone;
+
+    @ApiModelProperty("收货人地址")
+    private String receiverAddress;
+
+
     public Long getId() {
         return id;
     }

+ 50 - 0
src/main/java/com/jsh/erp/datasource/entities/DepotItem.java

@@ -1,59 +1,109 @@
 package com.jsh.erp.datasource.entities;
 
+import com.baomidou.mybatisplus.annotation.TableName;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
 import java.math.BigDecimal;
 import java.util.Date;
 
+/**
+ * 单据子表实体类
+ */
+@Data
+@TableName("jsh_depot_item")
 public class DepotItem {
+
+    @ApiModelProperty("主键id")
     private Long id;
 
+    @ApiModelProperty("表头Id")
     private Long headerId;
 
+    @ApiModelProperty("商品Id")
     private Long materialId;
 
+    @ApiModelProperty("商品扩展id")
     private Long materialExtendId;
 
+    @ApiModelProperty("商品单位")
     private String materialUnit;
 
+    @ApiModelProperty("多属性")
     private String sku;
 
+    @ApiModelProperty("数量")
     private BigDecimal operNumber;
 
+    @ApiModelProperty("基础数量,如kg、瓶")
     private BigDecimal basicNumber;
 
+    @ApiModelProperty("单价")
     private BigDecimal unitPrice;
 
+    @ApiModelProperty("采购单价")
     private BigDecimal purchaseUnitPrice;
 
+    @ApiModelProperty("含税单价")
     private BigDecimal taxUnitPrice;
 
+    @ApiModelProperty("金额")
     private BigDecimal allPrice;
 
+    @ApiModelProperty("备注")
     private String remark;
 
+    @ApiModelProperty("仓库ID")
     private Long depotId;
 
+    @ApiModelProperty("调拨时,对方仓库Id")
     private Long anotherDepotId;
 
+    @ApiModelProperty("税率")
     private BigDecimal taxRate;
 
+    @ApiModelProperty("税额")
     private BigDecimal taxMoney;
 
+    @ApiModelProperty("价税合计")
     private BigDecimal taxLastMoney;
 
+    @ApiModelProperty("商品类型")
     private String materialType;
 
+    @ApiModelProperty("序列号列表")
     private String snList;
 
+    @ApiModelProperty("批号")
     private String batchNumber;
 
+    @ApiModelProperty("有效日期")
     private Date expirationDate;
 
+    @ApiModelProperty("关联明细id")
     private Long linkId;
 
+    @ApiModelProperty("租户id")
     private Long tenantId;
 
+    @ApiModelProperty("删除标记,0未删除,1删除")
     private String deleteFlag;
 
+    @ApiModelProperty("实际出入库数量")
+    private BigDecimal actualQuantityInStorage;
+
+    @ApiModelProperty("出入库差异")
+    private BigDecimal warehousingVariance;
+
+    @ApiModelProperty("出入库差异原因")
+    private String reasonOfDifference;
+
+    @ApiModelProperty("出入库用户")
+    private Long warehousingUser;
+
+    @ApiModelProperty("出入库时间")
+    private Date warehousingTime;
+
     public Long getId() {
         return id;
     }

+ 10 - 87
src/main/java/com/jsh/erp/datasource/entities/DepotItemVo4DetailByTypeAndMId.java

@@ -1,18 +1,27 @@
 package com.jsh.erp.datasource.entities;
 
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
 import java.math.BigDecimal;
 import java.util.Date;
 
+@Data
 public class DepotItemVo4DetailByTypeAndMId {
 
+    @ApiModelProperty("序列号")
     private String number;
 
+    @ApiModelProperty("商品条码")
     private String barCode;
 
+    @ApiModelProperty("商品名称")
     private String materialName;
 
+    @ApiModelProperty("出入库类型")
     private String type;
 
+    @ApiModelProperty("单据类型")
     private String subType;
 
     private BigDecimal bnum;
@@ -21,97 +30,11 @@ public class DepotItemVo4DetailByTypeAndMId {
 
     private BigDecimal allPrice;
 
+    @ApiModelProperty("商品单位")
     private String materialUnit;
 
     private String depotName;
 
     private Date otime;
 
-    public String getNumber() {
-        return number;
-    }
-
-    public void setNumber(String number) {
-        this.number = number;
-    }
-
-    public String getBarCode() {
-        return barCode;
-    }
-
-    public void setBarCode(String barCode) {
-        this.barCode = barCode;
-    }
-
-    public String getMaterialName() {
-        return materialName;
-    }
-
-    public void setMaterialName(String materialName) {
-        this.materialName = materialName;
-    }
-
-    public String getType() {
-        return type;
-    }
-
-    public void setType(String type) {
-        this.type = type;
-    }
-
-    public String getSubType() {
-        return subType;
-    }
-
-    public void setSubType(String subType) {
-        this.subType = subType;
-    }
-
-    public BigDecimal getBnum() {
-        return bnum;
-    }
-
-    public void setBnum(BigDecimal bnum) {
-        this.bnum = bnum;
-    }
-
-    public BigDecimal getUnitPrice() {
-        return unitPrice;
-    }
-
-    public void setUnitPrice(BigDecimal unitPrice) {
-        this.unitPrice = unitPrice;
-    }
-
-    public BigDecimal getAllPrice() {
-        return allPrice;
-    }
-
-    public void setAllPrice(BigDecimal allPrice) {
-        this.allPrice = allPrice;
-    }
-
-    public String getMaterialUnit() {
-        return materialUnit;
-    }
-
-    public void setMaterialUnit(String materialUnit) {
-        this.materialUnit = materialUnit;
-    }
-
-    public String getDepotName() {
-        return depotName;
-    }
-
-    public void setDepotName(String depotName) {
-        this.depotName = depotName;
-    }
-
-    public Date getOtime() {
-        return otime;
-    }
-
-    public void setOtime(Date otime) {
-        this.otime = otime;
-    }
 }

+ 28 - 4
src/main/java/com/jsh/erp/datasource/entities/DepotItemVo4WithInfoEx.java

@@ -1,7 +1,11 @@
 package com.jsh.erp.datasource.entities;
 
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
 import java.math.BigDecimal;
 
+@Data
 public class DepotItemVo4WithInfoEx extends DepotItem{
 
     private Long MId;
@@ -48,16 +52,36 @@ public class DepotItemVo4WithInfoEx extends DepotItem{
 
     private BigDecimal currentUnitPrice;
 
-    private String barCode;
-
     private BigDecimal weight;
 
-    private String position;
-
     private String imgName;
 
     private String brand;
 
+    @ApiModelProperty("生产日期")
+    private String productionDate;
+
+    @ApiModelProperty("保质期天数")
+    private Integer expiryNum;
+
+    @ApiModelProperty("供应商id")
+    private Long supplierId;
+
+    @ApiModelProperty("商品条码")
+    private String barCode;
+
+    @ApiModelProperty("批次号")
+    private String batchNumber;
+
+    @ApiModelProperty("库存")
+    private BigDecimal inventory;
+
+    @ApiModelProperty("仓位货架")
+    private String position;
+
+    @ApiModelProperty("供应商名称")
+    private String supplierName;
+
     public Long getMId() {
         return MId;
     }

+ 5 - 0
src/main/java/com/jsh/erp/datasource/entities/Log.java

@@ -1,7 +1,12 @@
 package com.jsh.erp.datasource.entities;
 
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
 import java.util.Date;
 
+@Data
+@TableName("jsh_log")
 public class Log {
     private Long id;
 

+ 43 - 135
src/main/java/com/jsh/erp/datasource/entities/Material.java

@@ -1,245 +1,153 @@
 package com.jsh.erp.datasource.entities;
 
-import java.math.BigDecimal;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableName;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
 
+import java.math.BigDecimal;
+import java.util.List;
+
+/**
+ * 产品表实体类(商品信息)
+ */
+@Data
+@Accessors(chain = true)
+@TableName("jsh_material")
 public class Material {
+
+    @ApiModelProperty("主键id")
     private Long id;
 
+    @ApiModelProperty("产品类型id")
     private Long categoryId;
 
+    @ApiModelProperty("产品名称")
     private String name;
 
-    private String mfrs;
-
+    @ApiModelProperty("型号")
     private String model;
 
+    @ApiModelProperty("规格")
     private String standard;
 
+    @ApiModelProperty("品牌")
     private String brand;
 
+    @ApiModelProperty("助记码")
     private String mnemonic;
 
+    @ApiModelProperty("颜色")
     private String color;
 
+    @ApiModelProperty("单位-单个")
     private String unit;
 
+    @ApiModelProperty("备注")
     private String remark;
 
+    @ApiModelProperty("图片名称")
     private String imgName;
 
+    @ApiModelProperty("计量单位Id")
     private Long unitId;
 
-    private Integer expiryNum;
-
+    @ApiModelProperty("基础重量(kg)")
     private BigDecimal weight;
 
+    @ApiModelProperty("启用 0-禁用  1-启用")
     private Boolean enabled;
 
+    @ApiModelProperty("自定义1")
     private String otherField1;
 
+    @ApiModelProperty("自定义2")
     private String otherField2;
 
+    @ApiModelProperty("自定义3")
     private String otherField3;
 
+    @ApiModelProperty("是否开启序列号,0否,1是")
     private String enableSerialNumber;
 
+    @ApiModelProperty("是否开启批号,0否,1是")
     private String enableBatchNumber;
 
-    private String position;
-
+    @ApiModelProperty("租户id")
     private Long tenantId;
 
+    @ApiModelProperty("删除标记,0未删除,1删除")
     private String deleteFlag;
 
-    public Long getId() {
-        return id;
-    }
-
-    public void setId(Long id) {
-        this.id = id;
-    }
+    @ApiModelProperty("系统sku")
+    private String systemSku;
 
-    public Long getCategoryId() {
-        return categoryId;
-    }
+    @ApiModelProperty("无动销提醒周期")
+    private String movingPinReminderCycle;
 
-    public void setCategoryId(Long categoryId) {
-        this.categoryId = categoryId;
-    }
+    @TableField(exist = false)
+    private List<MaterialExtend> list;
 
-    public String getName() {
-        return name;
-    }
 
     public void setName(String name) {
         this.name = name == null ? null : name.trim();
     }
 
-    public String getMfrs() {
-        return mfrs;
-    }
-
-    public void setMfrs(String mfrs) {
-        this.mfrs = mfrs == null ? null : mfrs.trim();
-    }
-
-    public String getModel() {
-        return model;
-    }
-
     public void setModel(String model) {
         this.model = model == null ? null : model.trim();
     }
 
-    public String getStandard() {
-        return standard;
-    }
-
     public void setStandard(String standard) {
         this.standard = standard == null ? null : standard.trim();
     }
 
-    public String getBrand() {
-        return brand;
-    }
-
     public void setBrand(String brand) {
         this.brand = brand == null ? null : brand.trim();
     }
 
-    public String getMnemonic() {
-        return mnemonic;
-    }
-
     public void setMnemonic(String mnemonic) {
         this.mnemonic = mnemonic == null ? null : mnemonic.trim();
     }
 
-    public String getColor() {
-        return color;
-    }
-
     public void setColor(String color) {
         this.color = color == null ? null : color.trim();
     }
 
-    public String getUnit() {
-        return unit;
-    }
-
     public void setUnit(String unit) {
         this.unit = unit == null ? null : unit.trim();
     }
 
-    public String getRemark() {
-        return remark;
-    }
-
     public void setRemark(String remark) {
         this.remark = remark == null ? null : remark.trim();
     }
 
-    public String getImgName() {
-        return imgName;
-    }
-
     public void setImgName(String imgName) {
         this.imgName = imgName == null ? null : imgName.trim();
     }
 
-    public Long getUnitId() {
-        return unitId;
-    }
-
-    public void setUnitId(Long unitId) {
-        this.unitId = unitId;
-    }
-
-    public Integer getExpiryNum() {
-        return expiryNum;
-    }
-
-    public void setExpiryNum(Integer expiryNum) {
-        this.expiryNum = expiryNum;
-    }
-
-    public BigDecimal getWeight() {
-        return weight;
-    }
-
-    public void setWeight(BigDecimal weight) {
-        this.weight = weight;
-    }
-
-    public Boolean getEnabled() {
-        return enabled;
-    }
-
-    public void setEnabled(Boolean enabled) {
-        this.enabled = enabled;
-    }
-
-    public String getOtherField1() {
-        return otherField1;
-    }
-
     public void setOtherField1(String otherField1) {
         this.otherField1 = otherField1 == null ? null : otherField1.trim();
     }
 
-    public String getOtherField2() {
-        return otherField2;
-    }
-
     public void setOtherField2(String otherField2) {
         this.otherField2 = otherField2 == null ? null : otherField2.trim();
     }
 
-    public String getOtherField3() {
-        return otherField3;
-    }
-
     public void setOtherField3(String otherField3) {
         this.otherField3 = otherField3 == null ? null : otherField3.trim();
     }
 
-    public String getEnableSerialNumber() {
-        return enableSerialNumber;
-    }
-
     public void setEnableSerialNumber(String enableSerialNumber) {
         this.enableSerialNumber = enableSerialNumber == null ? null : enableSerialNumber.trim();
     }
 
-    public String getEnableBatchNumber() {
-        return enableBatchNumber;
-    }
-
     public void setEnableBatchNumber(String enableBatchNumber) {
         this.enableBatchNumber = enableBatchNumber == null ? null : enableBatchNumber.trim();
     }
 
-    public String getPosition() {
-        return position;
-    }
-
-    public void setPosition(String position) {
-        this.position = position == null ? null : position.trim();
-    }
-
-    public Long getTenantId() {
-        return tenantId;
-    }
-
-    public void setTenantId(Long tenantId) {
-        this.tenantId = tenantId;
-    }
-
-    public String getDeleteFlag() {
-        return deleteFlag;
-    }
-
     public void setDeleteFlag(String deleteFlag) {
         this.deleteFlag = deleteFlag == null ? null : deleteFlag.trim();
     }
+
 }

+ 10 - 9
src/main/java/com/jsh/erp/datasource/entities/MaterialCategory.java

@@ -1,8 +1,17 @@
 package com.jsh.erp.datasource.entities;
 
+import lombok.Data;
+import lombok.experimental.Accessors;
+
 import java.util.Date;
 
+/**
+ * 产品类型表实体类
+ */
+@Data
+@Accessors(chain = true)
 public class MaterialCategory {
+
     private Long id;
 
     private String name;
@@ -13,7 +22,7 @@ public class MaterialCategory {
 
     private String sort;
 
-    private String serialNo;
+    private Long serialNo;
 
     private String remark;
 
@@ -65,14 +74,6 @@ public class MaterialCategory {
         this.sort = sort == null ? null : sort.trim();
     }
 
-    public String getSerialNo() {
-        return serialNo;
-    }
-
-    public void setSerialNo(String serialNo) {
-        this.serialNo = serialNo == null ? null : serialNo.trim();
-    }
-
     public String getRemark() {
         return remark;
     }

+ 8 - 0
src/main/java/com/jsh/erp/datasource/entities/MaterialCurrentStock.java

@@ -1,7 +1,15 @@
 package com.jsh.erp.datasource.entities;
 
+import lombok.Data;
+import lombok.experimental.Accessors;
+
 import java.math.BigDecimal;
 
+/**
+ * 产品当前库存表实体类
+ */
+@Data
+@Accessors(chain = true)
 public class MaterialCurrentStock {
     private Long id;
 

+ 44 - 97
src/main/java/com/jsh/erp/datasource/entities/MaterialExtend.java

@@ -1,165 +1,112 @@
 package com.jsh.erp.datasource.entities;
 
+import com.baomidou.mybatisplus.annotation.TableName;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
 import java.math.BigDecimal;
 import java.util.Date;
 
+/**
+ * 产品价格扩展表实体类
+ */
+@Data
+@TableName("jsh_material_extend")
 public class MaterialExtend {
+
+    @ApiModelProperty("主键id")
     private Long id;
 
+    @ApiModelProperty("商品id")
     private Long materialId;
 
-    private String barCode;
-
+    @ApiModelProperty("商品单位")
     private String commodityUnit;
 
+    @ApiModelProperty("商品属性")
     private String sku;
 
+    @ApiModelProperty("采购价格")
     private BigDecimal purchaseDecimal;
 
+    @ApiModelProperty("零售价格")
     private BigDecimal commodityDecimal;
 
+    @ApiModelProperty("销售价格")
     private BigDecimal wholesaleDecimal;
 
+    @ApiModelProperty("最低售价")
     private BigDecimal lowDecimal;
 
+    @ApiModelProperty("是否为默认单位,1是,0否")
     private String defaultFlag;
 
+    @ApiModelProperty("创建日期")
     private Date createTime;
 
+    @ApiModelProperty("创建人编码")
     private String createSerial;
 
+    @ApiModelProperty("更新人编码")
     private String updateSerial;
 
+    @ApiModelProperty("更新时间戳")
     private Long updateTime;
 
+    @ApiModelProperty("租户id")
     private Long tenantId;
 
+    @ApiModelProperty("删除标记,0未删除,1删除")
     private String deleteFlag;
 
-    public Long getId() {
-        return id;
-    }
+    @ApiModelProperty("生产日期")
+    private Date productionDate;
 
-    public void setId(Long id) {
-        this.id = id;
-    }
+    @ApiModelProperty("保质期天数")
+    private Integer expiryNum;
 
-    public Long getMaterialId() {
-        return materialId;
-    }
+    @ApiModelProperty("供应商id")
+    private Long supplierId;
 
-    public void setMaterialId(Long materialId) {
-        this.materialId = materialId;
-    }
+    @ApiModelProperty("商品条码")
+    private String barCode;
 
-    public String getBarCode() {
-        return barCode;
-    }
+    @ApiModelProperty("批次号")
+    private String batchNumber;
+
+    @ApiModelProperty("库存")
+    private BigDecimal inventory;
+
+    @ApiModelProperty("仓库id")
+    private Long depotId;
+
+    @ApiModelProperty("仓位货架")
+    private String position;
 
     public void setBarCode(String barCode) {
         this.barCode = barCode == null ? null : barCode.trim();
     }
 
-    public String getCommodityUnit() {
-        return commodityUnit;
-    }
-
     public void setCommodityUnit(String commodityUnit) {
         this.commodityUnit = commodityUnit == null ? null : commodityUnit.trim();
     }
 
-    public String getSku() {
-        return sku;
-    }
-
     public void setSku(String sku) {
         this.sku = sku == null ? null : sku.trim();
     }
 
-    public BigDecimal getPurchaseDecimal() {
-        return purchaseDecimal;
-    }
-
-    public void setPurchaseDecimal(BigDecimal purchaseDecimal) {
-        this.purchaseDecimal = purchaseDecimal;
-    }
-
-    public BigDecimal getCommodityDecimal() {
-        return commodityDecimal;
-    }
-
-    public void setCommodityDecimal(BigDecimal commodityDecimal) {
-        this.commodityDecimal = commodityDecimal;
-    }
-
-    public BigDecimal getWholesaleDecimal() {
-        return wholesaleDecimal;
-    }
-
-    public void setWholesaleDecimal(BigDecimal wholesaleDecimal) {
-        this.wholesaleDecimal = wholesaleDecimal;
-    }
-
-    public BigDecimal getLowDecimal() {
-        return lowDecimal;
-    }
-
-    public void setLowDecimal(BigDecimal lowDecimal) {
-        this.lowDecimal = lowDecimal;
-    }
-
-    public String getDefaultFlag() {
-        return defaultFlag;
-    }
-
     public void setDefaultFlag(String defaultFlag) {
         this.defaultFlag = defaultFlag == null ? null : defaultFlag.trim();
     }
 
-    public Date getCreateTime() {
-        return createTime;
-    }
-
-    public void setCreateTime(Date createTime) {
-        this.createTime = createTime;
-    }
-
-    public String getCreateSerial() {
-        return createSerial;
-    }
-
     public void setCreateSerial(String createSerial) {
         this.createSerial = createSerial == null ? null : createSerial.trim();
     }
 
-    public String getUpdateSerial() {
-        return updateSerial;
-    }
-
     public void setUpdateSerial(String updateSerial) {
         this.updateSerial = updateSerial == null ? null : updateSerial.trim();
     }
 
-    public Long getUpdateTime() {
-        return updateTime;
-    }
-
-    public void setUpdateTime(Long updateTime) {
-        this.updateTime = updateTime;
-    }
-
-    public Long getTenantId() {
-        return tenantId;
-    }
-
-    public void setTenantId(Long tenantId) {
-        this.tenantId = tenantId;
-    }
-
-    public String getDeleteFlag() {
-        return deleteFlag;
-    }
-
     public void setDeleteFlag(String deleteFlag) {
         this.deleteFlag = deleteFlag == null ? null : deleteFlag.trim();
     }

+ 18 - 0
src/main/java/com/jsh/erp/datasource/entities/MaterialInitialStock.java

@@ -1,22 +1,40 @@
 package com.jsh.erp.datasource.entities;
 
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
 import java.math.BigDecimal;
 
+/**
+ * 产品初始库存表实体类
+ */
+@Data
+@Accessors(chain = true)
 public class MaterialInitialStock {
+
+    @ApiModelProperty("主键id")
     private Long id;
 
+    @ApiModelProperty("产品id")
     private Long materialId;
 
+    @ApiModelProperty("仓库id")
     private Long depotId;
 
+    @ApiModelProperty("初始库存数量")
     private BigDecimal number;
 
+    @ApiModelProperty("最低库存数量")
     private BigDecimal lowSafeStock;
 
+    @ApiModelProperty("最高库存数量")
     private BigDecimal highSafeStock;
 
+    @ApiModelProperty("租户id")
     private Long tenantId;
 
+    @ApiModelProperty("删除标记,0未删除,1删除")
     private String deleteFlag;
 
     public Long getId() {

+ 73 - 8
src/main/java/com/jsh/erp/datasource/entities/MaterialVo4Unit.java

@@ -1,9 +1,20 @@
 package com.jsh.erp.datasource.entities;
 
+import com.jsh.erp.datasource.vo.UnitListVo;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
 import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
 
+@Data
+@Accessors(chain = true)
 public class MaterialVo4Unit extends Material{
 
+
     private String unitName;
 
     private BigDecimal ratio;
@@ -44,7 +55,7 @@ public class MaterialVo4Unit extends Material{
 
     private String sku;
 
-    private Long depotId;
+//    private Long depotId;
 
     /**
      * 换算为大单位的库存
@@ -60,6 +71,54 @@ public class MaterialVo4Unit extends Material{
 
     private String imgLarge;
 
+    @ApiModelProperty("生产日期")
+    private String productionDate;
+
+    @ApiModelProperty("保质期天数")
+    private Integer expiryNum;
+
+    @ApiModelProperty("供应商id")
+    private Long supplierId;
+
+    @ApiModelProperty("商品条码")
+    private String barCode;
+
+    @ApiModelProperty("批次号")
+    private String batchNumber;
+
+    @ApiModelProperty("库存")
+    private BigDecimal inventory;
+
+    @ApiModelProperty("仓库id")
+    private Long depotId;
+
+    @ApiModelProperty("仓位货架")
+    private String position;
+
+    @ApiModelProperty("供应商名称")
+    private String supplierName;
+
+    @ApiModelProperty("仓库名称")
+    private String depotName;
+
+    @ApiModelProperty("实际出入库数量")
+    private BigDecimal actualQuantityInStorage;
+
+    @ApiModelProperty("出入库差异")
+    private BigDecimal warehousingVariance;
+
+    @ApiModelProperty("出入库差异原因")
+    private String reasonOfDifference;
+
+    @ApiModelProperty("出入库用户")
+    private Long warehousingUser;
+
+    @ApiModelProperty("出入库时间")
+    private Date warehousingTime;
+
+    @ApiModelProperty("多单位集合")
+    private List<UnitListVo> unitList;
+
     public String getUnitName() {
         return unitName;
     }
@@ -220,13 +279,13 @@ public class MaterialVo4Unit extends Material{
         this.sku = sku;
     }
 
-    public Long getDepotId() {
-        return depotId;
-    }
-
-    public void setDepotId(Long depotId) {
-        this.depotId = depotId;
-    }
+//    public Long getDepotId() {
+//        return depotId;
+//    }
+//
+//    public void setDepotId(Long depotId) {
+//        this.depotId = depotId;
+//    }
 
     public String getBigUnitStock() {
         return bigUnitStock;
@@ -259,4 +318,10 @@ public class MaterialVo4Unit extends Material{
     public void setBigUnitInitialStock(String bigUnitInitialStock) {
         this.bigUnitInitialStock = bigUnitInitialStock;
     }
+
+    public void setProductionDate(Date productionDate) {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        String date = productionDate == null ? null : sdf.format(productionDate);
+        this.productionDate = productionDate == null ? null : date;
+    }
 }

+ 4 - 16
src/main/java/com/jsh/erp/datasource/entities/MaterialWithInitStock.java

@@ -1,29 +1,17 @@
 package com.jsh.erp.datasource.entities;
 
 import com.alibaba.fastjson.JSONObject;
+import lombok.Data;
+import lombok.experimental.Accessors;
 
 import java.math.BigDecimal;
 import java.util.Map;
 
+@Data
+@Accessors(chain = true)
 public class MaterialWithInitStock extends Material {
 
     private Map<Long, BigDecimal> stockMap;
 
     private JSONObject materialExObj;
-
-    public Map<Long, BigDecimal> getStockMap() {
-        return stockMap;
-    }
-
-    public void setStockMap(Map<Long, BigDecimal> stockMap) {
-        this.stockMap = stockMap;
-    }
-
-    public JSONObject getMaterialExObj() {
-        return materialExObj;
-    }
-
-    public void setMaterialExObj(JSONObject materialExObj) {
-        this.materialExObj = materialExObj;
-    }
 }

+ 10 - 5
src/main/java/com/jsh/erp/datasource/entities/Supplier.java

@@ -1,11 +1,16 @@
 package com.jsh.erp.datasource.entities;
 
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
 import java.math.BigDecimal;
 
 /**
  * 供应商/客户信息表实体类
  *
  */
+@Data
+@TableName("jsh_supplier")
 public class Supplier {
 
     /** 主键 */
@@ -96,7 +101,7 @@ public class Supplier {
     private String procurementContact;
 
     /** 到货天数(单位:天) */
-    private Integer deliverydays;
+    private Integer deliveryDays;
 
     /** 发票类型:0-普通发票, 1-增值税专用发票 */
     private String invoiceType;
@@ -337,12 +342,12 @@ public class Supplier {
         this.procurementContact = procurementContact == null ? null : procurementContact.trim();;
     }
 
-    public Integer getDeliverydays() {
-        return deliverydays;
+    public Integer getDeliveryDays() {
+        return deliveryDays;
     }
 
-    public void setDeliverydays(Integer deliverydays) {
-        this.deliverydays = deliverydays;
+    public void setDeliveryDays(Integer deliveryDays) {
+        this.deliveryDays = deliveryDays;
     }
 
     public String getInvoiceType() {

+ 64 - 0
src/main/java/com/jsh/erp/datasource/entities/TaskStocktaking.java

@@ -0,0 +1,64 @@
+package com.jsh.erp.datasource.entities;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.util.Date;
+
+/**
+ * 盘点任务
+ */
+@Data
+@Accessors(chain = true)
+public class TaskStocktaking {
+
+    @ApiModelProperty("主键ID")
+    private Long id;
+
+    @ApiModelProperty("任务名称")
+    private String taskName;
+
+    @ApiModelProperty("负责人ID")
+    private Long creator;
+
+    @ApiModelProperty("创建人ID")
+    private Long createBy;
+
+    @ApiModelProperty("创建时间")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date createTime;
+
+    @ApiModelProperty("任务类型 1.全盘,2.抽盘")
+    private int taskType;
+
+    @ApiModelProperty("仓库ID")
+    private Long depotId;
+
+    @ApiModelProperty("任务单号")
+    private String number;
+
+    @ApiModelProperty("种类数")
+    private Integer categoryCount;
+
+    @ApiModelProperty("商品数")
+    private int materialCount;
+
+    @ApiModelProperty("任务状态 1.未开始,2.进行中,3.已完成,4.已取消")
+    private Integer taskStatus;
+
+    @ApiModelProperty("盘点范围")
+    private String positionRange;
+
+    @ApiModelProperty("删除标记,0.未删除,1.已删除")
+    private boolean deleteFlag;
+
+    @ApiModelProperty("盘点人")
+    private Long operBy;
+
+    @ApiModelProperty("盘点时间")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date operTime;
+
+}

+ 47 - 0
src/main/java/com/jsh/erp/datasource/entities/TaskStocktakingItem.java

@@ -0,0 +1,47 @@
+package com.jsh.erp.datasource.entities;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.math.BigDecimal;
+import java.util.Date;
+
+/**
+ * 盘点任务明细
+ */
+@Data
+@Accessors(chain = true)
+public class TaskStocktakingItem {
+
+    @ApiModelProperty("主键ID")
+    private Long id;
+
+    @ApiModelProperty("任务ID")
+    private Long taskStocktakingId;
+
+    @ApiModelProperty("商品ID")
+    private Long materialItemId;
+
+    @ApiModelProperty("操作人ID")
+    private Long creator;
+
+    @ApiModelProperty("操作时间")
+    private Date operTime;
+
+    @ApiModelProperty("新仓位货架")
+    private String newPosition;
+
+    @ApiModelProperty("新库存数")
+    private BigDecimal newInventory;
+
+    @ApiModelProperty("差异数量")
+    private Integer differenceCount;
+
+    @ApiModelProperty("差异原因")
+    private String differenceReason;
+
+    @ApiModelProperty("删除标记,0.未删除,1.已删除")
+    private boolean deleteFlag;
+
+}

+ 5 - 0
src/main/java/com/jsh/erp/datasource/entities/User.java

@@ -1,5 +1,10 @@
 package com.jsh.erp.datasource.entities;
 
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+@Data
+@TableName(value = "jsh_user")
 public class User {
     private Long id;
 

+ 143 - 0
src/main/java/com/jsh/erp/datasource/mappers/BaseMapperX.java

@@ -0,0 +1,143 @@
+package com.jsh.erp.datasource.mappers;
+
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
+import com.github.pagehelper.PageHelper;
+import com.jsh.erp.query.LambdaQueryWrapperX;
+import com.jsh.erp.result.PageParam;
+import com.jsh.erp.result.PageResult;
+import com.jsh.erp.util.MyBatisUtils;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Supplier;
+
+/**
+ * 在 MyBatis Plus 的 BaseMapper 的基础上拓展,提供更多的能力
+ */
+public interface BaseMapperX<T> extends BaseMapper<T> {
+
+    default PageResult<T> selectPage(PageParam pageParam, @Param("ew") Wrapper<T> queryWrapper) {
+        // MyBatis Plus 查询
+        IPage<T> mpPage = MyBatisUtils.buildPage(pageParam);
+        selectPage(mpPage, queryWrapper);
+        // 转换返回
+        return new PageResult<T>(mpPage.getRecords(), mpPage.getTotal(),(int)mpPage.getSize(),(int)mpPage.getCurrent());
+    }
+
+    default T selectOne(String field, Object value) {
+        return selectOne(new QueryWrapper<T>().eq(field, value));
+    }
+
+    /**
+     *  获取查询mapper
+     * @return
+     */
+    default LambdaQueryWrapperX<T> getWeekend() {
+        return new LambdaQueryWrapperX<>();
+    }
+
+    /**
+     *  自定义分页
+     * @param supplier
+     * @param pageQuery
+     * @param <T>
+     * @return
+     */
+    default <T> PageResult<T> pageSelect(Supplier<List<T>> supplier, PageParam pageQuery) {
+        if (Objects.equals(pageQuery.getPageNo(), 0)) {
+            List<T> list = supplier.get();
+            return PageResult.of(list, pageQuery);
+        } else {
+            com.github.pagehelper.Page<T> page = PageHelper.startPage(pageQuery.getPageNo(), pageQuery.getPageSize());
+            List<T> list = supplier.get();
+            PageResult<T> resultVO = PageResult.of(list, pageQuery);
+            resultVO.setTotal(page.getTotal());
+            resultVO.setPageNumber(page.getPageNum());
+            resultVO.setPageSize(page.getPageSize());
+            return resultVO;
+        }
+    }
+
+    default T selectOne(SFunction<T, ?> field, Object value) {
+        return selectOne(new LambdaQueryWrapper<T>().eq(field, value));
+    }
+
+    default T selectOne(String field1, Object value1, String field2, Object value2) {
+        return selectOne(new QueryWrapper<T>().eq(field1, value1).eq(field2, value2));
+    }
+
+    default T selectOne(SFunction<T, ?> field1, Object value1, SFunction<T, ?> field2, Object value2) {
+        return selectOne(new LambdaQueryWrapper<T>().eq(field1, value1).eq(field2, value2));
+    }
+
+    default Long selectCount() {
+        return selectCount(new QueryWrapper<T>());
+    }
+
+    default Long selectCount(String field, Object value) {
+        return selectCount(new QueryWrapper<T>().eq(field, value));
+    }
+
+    default Long selectCount(SFunction<T, ?> field, Object value) {
+        return selectCount(new LambdaQueryWrapper<T>().eq(field, value));
+    }
+
+    default Long selectCount(SFunction<T, ?> field1, Object value1, SFunction<T, ?> field2, Object value2) {
+        return selectCount(new LambdaQueryWrapper<T>().eq(field1, value1).eq(field2, value2));
+    }
+
+    default List<T> selectList() {
+        return selectList(new QueryWrapper<>());
+    }
+
+    default List<T> selectList(String field, Object value) {
+        return selectList(new QueryWrapper<T>().eq(field, value));
+    }
+
+    default List<T> selectList(SFunction<T, ?> field, Object value, SFunction<T, ?> field1, Object value1) {
+        return selectList(new LambdaQueryWrapper<T>().eq(field, value).eq(field1, value1));
+    }
+
+    default List<T> selectList(SFunction<T, ?> field, Object value) {
+        return selectList(new LambdaQueryWrapper<T>().eq(field, value));
+    }
+
+    default List<T> selectList(String field, Collection<?> values) {
+        return selectList(new QueryWrapper<T>().in(field, values));
+    }
+
+    default List<T> selectList(SFunction<T, ?> field, Collection<?> values) {
+        return selectList(new LambdaQueryWrapper<T>().in(field, values));
+    }
+    
+    default int deleteByProperty(SFunction<T, ?> field, Object value) {
+        if(value == null){
+            return -1;
+        }
+        return delete(new LambdaQueryWrapperX<T>().eq(field,value));
+    }
+
+    /**
+     * 逐条插入,适合少量数据插入,或者对性能要求不高的场景
+     *
+     * 如果大量,请使用 {@link com.baomidou.mybatisplus.extension.service.impl.ServiceImpl#saveBatch(Collection)} 方法
+     * 使用示例,可见 RoleMenuBatchInsertMapper、UserRoleBatchInsertMapper 类
+     *
+     * @param entities 实体们
+     */
+    default void insertBatch(Collection<T> entities) {
+        entities.forEach(this::insert);
+    }
+
+    default void updateBatch(T update) {
+        update(update, new QueryWrapper<>());
+    }
+
+}

+ 20 - 1
src/main/java/com/jsh/erp/datasource/mappers/DepotHeadMapper.java

@@ -3,9 +3,20 @@ package com.jsh.erp.datasource.mappers;
 import com.jsh.erp.datasource.entities.DepotHead;
 import com.jsh.erp.datasource.entities.DepotHeadExample;
 import java.util.List;
+
+import com.jsh.erp.datasource.pda.dto.PDADepotHeadDTO;
+import com.jsh.erp.datasource.pda.vo.PDADepotHeadVO;
 import org.apache.ibatis.annotations.Param;
 
-public interface DepotHeadMapper {
+public interface DepotHeadMapper extends BaseMapperX<DepotHead> {
+
+    /**
+     * PDA查询订单
+     * @param pdaDepotHeadDTO 筛选条件
+     * @return
+     */
+    List<PDADepotHeadVO> pdaList(PDADepotHeadDTO pdaDepotHeadDTO);
+
     long countByExample(DepotHeadExample example);
 
     int deleteByExample(DepotHeadExample example);
@@ -27,4 +38,12 @@ public interface DepotHeadMapper {
     int updateByPrimaryKeySelective(DepotHead record);
 
     int updateByPrimaryKey(DepotHead record);
+
+    /**
+     * 根据商品id获取最后一条销售订单
+     * @param id 商品id
+     * @return
+     */
+    DepotHead getDepotLastByMaterialId(long id);
+
 }

+ 26 - 1
src/main/java/com/jsh/erp/datasource/mappers/DepotItemMapper.java

@@ -1,11 +1,36 @@
 package com.jsh.erp.datasource.mappers;
 
+import com.jsh.erp.datasource.entities.DepotHead;
 import com.jsh.erp.datasource.entities.DepotItem;
 import com.jsh.erp.datasource.entities.DepotItemExample;
 import java.util.List;
+
+import com.jsh.erp.datasource.pda.vo.PDADepotItemVO;
 import org.apache.ibatis.annotations.Param;
 
-public interface DepotItemMapper {
+public interface DepotItemMapper  extends BaseMapperX<DepotItem>{
+
+    /**
+     * 根据单据ID获取单据详情
+     * @param id 订单ID
+     * @return
+     */
+    List<PDADepotItemVO> pdaList(@Param("id") Long id);
+
+    /**
+     * 根据商品订单ID获取单据详情
+     * @param id 商品订单ID
+     * @return
+     */
+    PDADepotItemVO pdaDetail(@Param("id") Long id);
+
+    /**
+     * pda根据商品订单ID查询商品详情
+     * @param materialId 商品ID
+     * @return
+     */
+    List<PDADepotItemVO> materialDepotDetail(@Param("type")String type , @Param("materialId") Long materialId);
+
     long countByExample(DepotItemExample example);
 
     int deleteByExample(DepotItemExample example);

+ 7 - 1
src/main/java/com/jsh/erp/datasource/mappers/DepotItemMapperEx.java

@@ -249,7 +249,7 @@ public interface DepotItemMapperEx {
             @Param("batchNumber") String batchNumber);
 
     List<MaterialVo4Unit> getBillItemByParam(
-            @Param("barCodes") String barCodes);
+            @Param("batchNumbers") String batchNumbers);
 
     BigDecimal getCurrentStockByParam(
             @Param("depotId") Long depotId,
@@ -260,4 +260,10 @@ public interface DepotItemMapperEx {
             @Param("meId") Long meId,
             @Param("type") String type,
             @Param("subType") String subType);
+
+    /**
+     * 根据系统sku获取库存不为零的单据商品,按生产日期顺序排序取第一条
+     * @param systemSku 系统sku
+     */
+    MaterialVo4Unit getDepotMaterialBySystemSku(@Param("systemSku") String systemSku);
 }

+ 1 - 1
src/main/java/com/jsh/erp/datasource/mappers/LogMapper.java

@@ -5,7 +5,7 @@ import com.jsh.erp.datasource.entities.LogExample;
 import java.util.List;
 import org.apache.ibatis.annotations.Param;
 
-public interface LogMapper {
+public interface LogMapper extends BaseMapperX<Log> {
     long countByExample(LogExample example);
 
     int deleteByExample(LogExample example);

+ 5 - 0
src/main/java/com/jsh/erp/datasource/mappers/MaterialCategoryMapper.java

@@ -27,4 +27,9 @@ public interface MaterialCategoryMapper {
     int updateByPrimaryKeySelective(MaterialCategory record);
 
     int updateByPrimaryKey(MaterialCategory record);
+
+    /**
+     * 查询最大类型编码
+     */
+    Long selectMaxId();
 }

+ 1 - 1
src/main/java/com/jsh/erp/datasource/mappers/MaterialCategoryMapperEx.java

@@ -28,7 +28,7 @@ public interface MaterialCategoryMapperEx {
 
     int editMaterialCategory(MaterialCategory mc);
 
-    List<MaterialCategory> getMaterialCategoryBySerialNo(@Param("serialNo") String serialNo, @Param("id") Long id);
+    List<MaterialCategory> getMaterialCategoryBySerialNo(@Param("serialNo") Long serialNo, @Param("id") Long id);
 
     List<MaterialCategory> getMaterialCategoryListByCategoryIds(@Param("parentIds") String[] categoryIds);
 

+ 3 - 1
src/main/java/com/jsh/erp/datasource/mappers/MaterialCurrentStockMapper.java

@@ -3,9 +3,11 @@ package com.jsh.erp.datasource.mappers;
 import com.jsh.erp.datasource.entities.MaterialCurrentStock;
 import com.jsh.erp.datasource.entities.MaterialCurrentStockExample;
 import java.util.List;
+
+import com.jsh.erp.datasource.entities.MaterialInitialStock;
 import org.apache.ibatis.annotations.Param;
 
-public interface MaterialCurrentStockMapper {
+public interface MaterialCurrentStockMapper extends BaseMapperX<MaterialCurrentStock> {
     long countByExample(MaterialCurrentStockExample example);
 
     int deleteByExample(MaterialCurrentStockExample example);

+ 26 - 1
src/main/java/com/jsh/erp/datasource/mappers/MaterialExtendMapper.java

@@ -2,10 +2,12 @@ package com.jsh.erp.datasource.mappers;
 
 import com.jsh.erp.datasource.entities.MaterialExtend;
 import com.jsh.erp.datasource.entities.MaterialExtendExample;
+
+import java.math.BigDecimal;
 import java.util.List;
 import org.apache.ibatis.annotations.Param;
 
-public interface MaterialExtendMapper {
+public interface MaterialExtendMapper extends BaseMapperX<MaterialExtend>{
     long countByExample(MaterialExtendExample example);
 
     int deleteByExample(MaterialExtendExample example);
@@ -27,4 +29,27 @@ public interface MaterialExtendMapper {
     int updateByPrimaryKeySelective(MaterialExtend record);
 
     int updateByPrimaryKey(MaterialExtend record);
+
+    /**
+     * 根据商品id查询拓展行数据集合
+     * @param id id数组
+     */
+    List<MaterialExtend> selectByMId(@Param("id") Long id);
+
+    /**
+     * 根据批次号查询拓展行数据
+     * @param batchNumber
+     * @return
+     */
+    MaterialExtend selectByBatchNumber(@Param("batchNumber") String batchNumber);
+
+    /**
+     * 根据仓库id和商品id查询商品库存
+     * @param depotList 仓库id
+     * @param mid   商品id
+     * @return
+     */
+    BigDecimal getInventorySumByDepotAndMid(@Param("depotList") List<Long> depotList,
+                                            @Param("mid") long mid);
+
 }

+ 9 - 2
src/main/java/com/jsh/erp/datasource/mappers/MaterialExtendMapperEx.java

@@ -9,6 +9,10 @@ import java.util.List;
 
 public interface MaterialExtendMapperEx {
 
+    /**
+     * 批量删除拓展表
+     * @param ids 拓展表id数组
+     */
     int batchDeleteMaterialExtendByIds(@Param("ids") String ids[]);
 
     List<MaterialExtendVo4List> getDetailList(
@@ -19,12 +23,15 @@ public interface MaterialExtendMapperEx {
             @Param("lastTime") Long lastTime,
             @Param("syncNum") Long syncNum);
 
+    /**
+     * 根据商品id数组查询拓展表数据
+     * @param ids 商品id数组
+     */
     List<MaterialExtend> getListByMId(@Param("ids") Long ids[]);
 
     int batchDeleteMaterialExtendByMIds(@Param("ids") String ids[]);
 
     int specialUpdatePrice(MaterialExtend record);
 
-    List<MaterialExtend> getBasicInfoByMid(
-            @Param("materialId") Long materialId);
+    List<MaterialExtend> getBasicInfoByMid(@Param("materialId") Long materialId);
 }

+ 2 - 1
src/main/java/com/jsh/erp/datasource/mappers/MaterialInitialStockMapper.java

@@ -1,11 +1,12 @@
 package com.jsh.erp.datasource.mappers;
 
+import com.jsh.erp.datasource.entities.Material;
 import com.jsh.erp.datasource.entities.MaterialInitialStock;
 import com.jsh.erp.datasource.entities.MaterialInitialStockExample;
 import java.util.List;
 import org.apache.ibatis.annotations.Param;
 
-public interface MaterialInitialStockMapper {
+public interface MaterialInitialStockMapper extends BaseMapperX<MaterialInitialStock> {
     long countByExample(MaterialInitialStockExample example);
 
     int deleteByExample(MaterialInitialStockExample example);

+ 2 - 1
src/main/java/com/jsh/erp/datasource/mappers/MaterialMapper.java

@@ -1,11 +1,12 @@
 package com.jsh.erp.datasource.mappers;
 
+import com.jsh.erp.datasource.entities.DepotItem;
 import com.jsh.erp.datasource.entities.Material;
 import com.jsh.erp.datasource.entities.MaterialExample;
 import java.util.List;
 import org.apache.ibatis.annotations.Param;
 
-public interface MaterialMapper {
+public interface MaterialMapper extends BaseMapperX<Material>{
     long countByExample(MaterialExample example);
 
     int deleteByExample(MaterialExample example);

+ 8 - 3
src/main/java/com/jsh/erp/datasource/mappers/MaterialMapperEx.java

@@ -4,7 +4,6 @@ import com.jsh.erp.datasource.entities.*;
 import com.jsh.erp.datasource.vo.MaterialVoSearch;
 import org.apache.ibatis.annotations.Param;
 
-import java.math.BigDecimal;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
@@ -54,7 +53,8 @@ public interface MaterialMapperEx {
                                                   @Param("enableSerialNumber") String enableSerialNumber,
                                                   @Param("enableBatchNumber") String enableBatchNumber,
                                                   @Param("offset") Integer offset,
-                                                  @Param("rows") Integer rows);
+                                                  @Param("rows") Integer rows,
+                                                  @Param("depotId") Long depotId);
 
     int findBySelectWithBarCodeCount(@Param("idList") List<Long> idList,
                                      @Param("q") String q,
@@ -63,7 +63,8 @@ public interface MaterialMapperEx {
                                      @Param("brand") String brand,
                                      @Param("mfrs") String mfrs,
                                      @Param("enableSerialNumber") String enableSerialNumber,
-                                     @Param("enableBatchNumber") String enableBatchNumber);
+                                     @Param("enableBatchNumber") String enableBatchNumber,
+                                     @Param("depotId") Long depotId);
 
     List<MaterialVo4Unit> exportExcel(
             @Param("materialParam") String materialParam,
@@ -157,4 +158,8 @@ public interface MaterialMapperEx {
 
     MaterialExtend getMaterialExtendBySerialNumber(
             @Param("serialNumber") String serialNumber);
+
+    List<MaterialVo4Unit> getMaterialByBatchNumber(@Param("batchNumberArray") String [] batchNumberArray);
+
+    List<MaterialVo4Unit> getMaterialBySystemSku(@Param("systemSkuArray") String [] systemSkuArray);
 }

+ 1 - 1
src/main/java/com/jsh/erp/datasource/mappers/SupplierMapper.java

@@ -5,7 +5,7 @@ import com.jsh.erp.datasource.entities.SupplierExample;
 import java.util.List;
 import org.apache.ibatis.annotations.Param;
 
-public interface SupplierMapper {
+public interface SupplierMapper extends BaseMapperX<Supplier> {
     long countByExample(SupplierExample example);
 
     int deleteByExample(SupplierExample example);

+ 16 - 0
src/main/java/com/jsh/erp/datasource/mappers/TaskStocktakingItemMapper.java

@@ -0,0 +1,16 @@
+package com.jsh.erp.datasource.mappers;
+
+import com.jsh.erp.datasource.entities.TaskStocktakingItem;
+import com.jsh.erp.datasource.pda.vo.PDATaskStocktakingItemVO;
+import com.jsh.erp.datasource.vo.TaskStocktakingItemVO;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+
+public interface TaskStocktakingItemMapper extends BaseMapperX<TaskStocktakingItem> {
+
+    List<TaskStocktakingItemVO> listByTaskStocktakingId(@Param("taskStocktakingId") Long taskStocktakingId);
+
+    List<PDATaskStocktakingItemVO> pdaList(@Param("taskId") Long taskId);
+
+}

+ 15 - 0
src/main/java/com/jsh/erp/datasource/mappers/TaskStocktakingMapper.java

@@ -0,0 +1,15 @@
+package com.jsh.erp.datasource.mappers;
+
+import com.jsh.erp.datasource.entities.TaskStocktaking;
+import com.jsh.erp.datasource.pda.vo.PDATaskStocktakingVO;
+import com.jsh.erp.datasource.vo.TaskStocktakingVO;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+
+public interface TaskStocktakingMapper extends BaseMapperX<TaskStocktaking> {
+
+    List<TaskStocktakingVO> listBy();
+
+    List<PDATaskStocktakingVO> pdaList(@Param("number") String number , @Param("taskStatus") Integer taskStatus);
+}

+ 5 - 1
src/main/java/com/jsh/erp/datasource/mappers/UserMapper.java

@@ -3,9 +3,11 @@ package com.jsh.erp.datasource.mappers;
 import com.jsh.erp.datasource.entities.User;
 import com.jsh.erp.datasource.entities.UserExample;
 import java.util.List;
+
+import com.jsh.erp.datasource.vo.SpinnerVO;
 import org.apache.ibatis.annotations.Param;
 
-public interface UserMapper {
+public interface UserMapper extends BaseMapperX<User> {
     long countByExample(UserExample example);
 
     int deleteByExample(UserExample example);
@@ -27,4 +29,6 @@ public interface UserMapper {
     int updateByPrimaryKeySelective(User record);
 
     int updateByPrimaryKey(User record);
+
+    List<SpinnerVO> creatorSpinnerList();
 }

+ 43 - 0
src/main/java/com/jsh/erp/datasource/pda/dto/PDADepotHeadDTO.java

@@ -0,0 +1,43 @@
+package com.jsh.erp.datasource.pda.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.util.List;
+
+@Data
+public class PDADepotHeadDTO {
+
+    @ApiModelProperty("单据ID")
+    private Long id;
+
+    @ApiModelProperty("开始时间")
+    private String beginTime;
+
+    @ApiModelProperty("结束时间")
+    private String endTime;
+
+    @ApiModelProperty("单据编号")
+    private String number;
+
+    @ApiModelProperty("状态 0.未审核,1.已审核,2.已完成,3.部分完成,4.进行中,9.审核中")
+    private String status;
+
+    @ApiModelProperty("单据类型")
+    private String subType;
+
+    @ApiModelProperty("操作类型")
+    private String type;
+
+    @ApiModelProperty("凭证图片")
+    private String voucherPicture;
+
+    @ApiModelProperty("备注")
+    private String remark;
+
+    @ApiModelProperty("订单商品数据")
+    private List<PDADepotMaterialDto> materials;
+
+
+
+}

+ 23 - 0
src/main/java/com/jsh/erp/datasource/pda/dto/PDADepotMaterialDto.java

@@ -0,0 +1,23 @@
+package com.jsh.erp.datasource.pda.dto;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.math.BigDecimal;
+import java.util.Date;
+
+@Data
+public class PDADepotMaterialDto {
+
+    @ApiModelProperty("批次号")
+    private String batchNumber;
+
+    @ApiModelProperty("商品数量")
+    private BigDecimal materialNumber;
+
+    @ApiModelProperty("生产日期")
+    @JsonFormat(pattern = "yyyy-MM-dd")
+    private Date productionDate;
+
+}

+ 15 - 0
src/main/java/com/jsh/erp/datasource/pda/dto/PDATaskStocktakingDTO.java

@@ -0,0 +1,15 @@
+package com.jsh.erp.datasource.pda.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+@Data
+public class PDATaskStocktakingDTO {
+
+    @ApiModelProperty("任务状态 1.未开始,2.进行中,3.已完成,4.已取消")
+    private Integer status;
+
+    @ApiModelProperty("任务单号")
+    private String number;
+
+}

+ 35 - 0
src/main/java/com/jsh/erp/datasource/pda/vo/PDADepotHeadVO.java

@@ -0,0 +1,35 @@
+package com.jsh.erp.datasource.pda.vo;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import org.springframework.format.annotation.DateTimeFormat;
+
+import java.util.Date;
+
+@Data
+public class PDADepotHeadVO {
+
+    @ApiModelProperty("主键ID")
+    private Long id;
+
+    @ApiModelProperty("单据编号")
+    private String number;
+
+    @ApiModelProperty("供应商名称")
+    private String supplierName;
+
+    @ApiModelProperty("订单创建时间")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+    private Date createTime;
+
+    @ApiModelProperty("商品总数量")
+    private int goodsQuantity;
+
+    @ApiModelProperty("商品总类")
+    private String goodsTypeCount;
+
+    @ApiModelProperty("订单状态")
+    private String status;
+
+}

+ 64 - 0
src/main/java/com/jsh/erp/datasource/pda/vo/PDADepotItemVO.java

@@ -0,0 +1,64 @@
+package com.jsh.erp.datasource.pda.vo;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.math.BigDecimal;
+import java.util.Date;
+
+@Data
+@Accessors
+public class PDADepotItemVO{
+
+    @ApiModelProperty("商品订单ID")
+    private Long id;
+
+    @ApiModelProperty("商品ID")
+    private Long materialId;
+
+    @ApiModelProperty("商品名称")
+    private String materialName;
+
+    @ApiModelProperty("商品规格")
+    private String materialStandard;
+
+    @ApiModelProperty("批次号")
+    private String batchNumber;
+
+    @ApiModelProperty("生产日期")
+    @JsonFormat(pattern = "yyyy-MM-dd")
+    private Date productionDate;
+
+    @ApiModelProperty("商品库位")
+    private String position;
+
+    @ApiModelProperty("商品库存")
+    private String inventory;
+
+    @ApiModelProperty("商品条码")
+    private String barCode;
+
+    @ApiModelProperty("订单数量")
+    private BigDecimal operNumber;
+
+    @ApiModelProperty("库存单位")
+    private String commodityUnit;
+
+    @ApiModelProperty("商品单位")
+    private String materialUnit;
+
+    @ApiModelProperty("创建时间")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+    private Date createTime;
+
+    @ApiModelProperty("商品系统SKU")
+    private String systemId;
+
+    @ApiModelProperty("仓库名称")
+    private String depotName;
+
+    @ApiModelProperty("实际出入库数量")
+    private String actualQuantityInStorage;
+}

+ 43 - 0
src/main/java/com/jsh/erp/datasource/pda/vo/PDATaskStocktakingItemVO.java

@@ -0,0 +1,43 @@
+package com.jsh.erp.datasource.pda.vo;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.util.Date;
+
+/**
+ * 盘点任务明细
+ */
+@Data
+@Accessors(chain = true)
+public class PDATaskStocktakingItemVO {
+
+    @ApiModelProperty("主键ID")
+    private Long id;
+
+    @ApiModelProperty("库位")
+    private String position;
+
+    @ApiModelProperty("商品总类")
+    private String categoryName;
+
+    @ApiModelProperty("商品名称")
+    private String materialName;
+
+    @ApiModelProperty("商品规格")
+    private String standard;
+
+    @ApiModelProperty("盘点人名称")
+    private String createName;
+
+    @ApiModelProperty("盘点时间")
+    private Date operTime;
+
+    @ApiModelProperty("库存数")
+    private Integer inventory;
+
+    @ApiModelProperty("盘点库存数")
+    private Integer newInventory;
+
+}

+ 47 - 0
src/main/java/com/jsh/erp/datasource/pda/vo/PDATaskStocktakingVO.java

@@ -0,0 +1,47 @@
+package com.jsh.erp.datasource.pda.vo;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.util.Date;
+
+@Data
+public class PDATaskStocktakingVO {
+
+    @ApiModelProperty("任务ID")
+    private Long id;
+
+    @ApiModelProperty("任务名称")
+    private String taskName;
+
+    @ApiModelProperty("任务单号")
+    private String number;
+
+    @ApiModelProperty("仓库名称")
+    private String depotName;
+
+    @ApiModelProperty("创建人名称")
+    private String createByName;
+
+    @ApiModelProperty("负责人名称")
+    private String creatorName;
+
+    @ApiModelProperty("种类数")
+    private Integer categoryCount;
+
+    @ApiModelProperty("商品数")
+    private Integer materialCount;
+
+    @ApiModelProperty("盘点人名称")
+    private String operName;
+
+    @ApiModelProperty("创建时间")
+    private Date createTime;
+
+    @ApiModelProperty("盘点时间")
+    private Date operTime;
+
+    @ApiModelProperty("任务状态 1.未开始,2.进行中,3.已完成,4.已取消")
+    private Integer taskStatus;
+
+}

+ 87 - 0
src/main/java/com/jsh/erp/datasource/tesco/request/ErpXsddReqVO.java

@@ -0,0 +1,87 @@
+package com.jsh.erp.datasource.tesco.request;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+/**
+ * @Description TODO
+ * @Author MS.BLUE
+ * @Date 2025-04-14
+ */
+@Data
+public class ErpXsddReqVO {
+
+    /**
+     * 订单编号
+     */
+    private String orderSn;
+
+    /**
+     * 订单总额
+     */
+    private BigDecimal totalPrice ;
+
+    /**
+     * 客户信息
+     */
+    private Customer customer;
+
+    /**
+     * 订单商品列表
+     */
+    private List<OrderItem> items;
+
+    @Data
+    public static class Customer {
+        /**
+         * 客户名称
+         */
+        private String name;
+
+        /**
+         * 客户账号
+         */
+        private String account;
+
+        /**
+         * 收货人姓名
+         */
+        private String receiverName;
+
+        /**
+         * 收货人电话
+         */
+        private String receiverPhone;
+
+        /**
+         * 收货人地址
+         */
+        private String receiverAddress;
+    }
+
+    @Data
+    public static class OrderItem {
+        /**
+         * ERP SKU编号
+         */
+        private String erpSku;
+
+        /**
+         * 商品单价
+         */
+        private BigDecimal unitPrice;
+
+        /**
+         * 商品下单数量
+         */
+        private Integer quantity;
+
+        /**
+         * 商品实付价格
+         */
+        private BigDecimal price;
+    }
+}

+ 15 - 0
src/main/java/com/jsh/erp/datasource/vo/DepotHeadXsddRequestVO.java

@@ -0,0 +1,15 @@
+package com.jsh.erp.datasource.vo;
+
+import com.jsh.erp.datasource.entities.DepotHead;
+import lombok.Data;
+
+/**
+ * @Description 销售订单主表
+ * @Author MS.BLUE
+ * @Date 2025-04-12
+ */
+@Data
+public class DepotHeadXsddRequestVO extends DepotHead {
+
+
+}

+ 10 - 0
src/main/java/com/jsh/erp/datasource/vo/DepotItemVo4Stock.java

@@ -1,12 +1,22 @@
 package com.jsh.erp.datasource.vo;
 
 
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
 import java.math.BigDecimal;
 
+/**
+ * 单据子表库存数量
+ */
+@Data
 public class DepotItemVo4Stock {
 
+    @ApiModelProperty("入库数量")
     private BigDecimal inTotal;
+    @ApiModelProperty("出库数量")
     private BigDecimal outTotal;
+
     private BigDecimal transfInTotal;
     private BigDecimal transfOutTotal;
     private BigDecimal assemInTotal;

+ 5 - 0
src/main/java/com/jsh/erp/datasource/vo/DepotItemVoBatchNumberList.java

@@ -1,9 +1,12 @@
 package com.jsh.erp.datasource.vo;
 
 
+import lombok.Data;
+
 import java.math.BigDecimal;
 import java.util.Date;
 
+@Data
 public class DepotItemVoBatchNumberList {
 
     private String id;
@@ -18,6 +21,8 @@ public class DepotItemVoBatchNumberList {
     private String expirationDateStr;
     private BigDecimal totalNum;
 
+
+
     public String getId() {
         return id;
     }

+ 15 - 0
src/main/java/com/jsh/erp/datasource/vo/DepotItemXsddRequestVO.java

@@ -0,0 +1,15 @@
+package com.jsh.erp.datasource.vo;
+
+import com.jsh.erp.datasource.entities.DepotItem;
+import lombok.Data;
+
+/**
+ * @Description 销售订单子表
+ * @Author MS.BLUE
+ * @Date 2025-04-12
+ */
+@Data
+public class DepotItemXsddRequestVO extends DepotItem {
+
+
+}

+ 56 - 0
src/main/java/com/jsh/erp/datasource/vo/Material4UnitPrice.java

@@ -0,0 +1,56 @@
+package com.jsh.erp.datasource.vo;
+
+import com.jsh.erp.datasource.entities.Unit;
+import lombok.Data;
+
+import java.math.BigDecimal;
+
+/**
+ * @Description TODO
+ * @Author MS.BLUE
+ * @Date 2025-04-15
+ */
+@Data
+public class Material4UnitPrice extends Unit {
+
+    /**
+     *基础单位 销售价格
+     */
+    private BigDecimal basicUnitPrice;
+
+    /**
+     *其他单位 销售价格
+     */
+    private BigDecimal otherUnitPrice;
+
+    /**
+     *其他单位2 销售价格
+     */
+    private BigDecimal otherUnitTwoPrice;
+
+    /**
+     *其他单位3 销售价格
+     */
+    private BigDecimal otherUnitThreePrice;
+
+    /**
+     *基础单位 基础数量
+     */
+    private BigDecimal basicUnitNumber;
+
+    /**
+     *其他单位 基础数量
+     */
+    private BigDecimal otherUnitNumber;
+
+    /**
+     *其他单位2 基础数量
+     */
+    private BigDecimal otherUnitTwoNumber;
+
+    /**
+     *其他单位3 基础数量
+     */
+    private BigDecimal otherUnitThreeNumber;
+
+}

+ 4 - 53
src/main/java/com/jsh/erp/datasource/vo/MaterialVoSearch.java

@@ -1,5 +1,8 @@
 package com.jsh.erp.datasource.vo;
 
+import lombok.Data;
+
+@Data
 public class MaterialVoSearch {
 
     private String barCode;
@@ -16,59 +19,7 @@ public class MaterialVoSearch {
 
     private String unit;
 
-    public String getBarCode() {
-        return barCode;
-    }
-
-    public void setBarCode(String barCode) {
-        this.barCode = barCode;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getMnemonic() {
-        return mnemonic;
-    }
-
-    public void setMnemonic(String mnemonic) {
-        this.mnemonic = mnemonic;
-    }
-
-    public String getStandard() {
-        return standard;
-    }
-
-    public void setStandard(String standard) {
-        this.standard = standard;
-    }
-
-    public String getModel() {
-        return model;
-    }
-
-    public void setModel(String model) {
-        this.model = model;
-    }
-
-    public String getColor() {
-        return color;
-    }
-
-    public void setColor(String color) {
-        this.color = color;
-    }
+    private String batchNumber;
 
-    public String getUnit() {
-        return unit;
-    }
 
-    public void setUnit(String unit) {
-        this.unit = unit;
-    }
 }

+ 25 - 0
src/main/java/com/jsh/erp/datasource/vo/MaterialWarnListVo.java

@@ -0,0 +1,25 @@
+package com.jsh.erp.datasource.vo;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.util.List;
+
+/**
+ * 商品库存提醒
+ */
+@Data
+@Accessors(chain = true)
+public class MaterialWarnListVo {
+
+    @ApiModelProperty("无动销提醒")
+    private List<String> NoMovingPinReminder;
+
+    @ApiModelProperty("过期提醒")
+    private List<String> expirationReminder;
+
+    @ApiModelProperty("库存提醒")
+    private List<String> inventoryReminder;
+
+}

+ 14 - 0
src/main/java/com/jsh/erp/datasource/vo/SpinnerVO.java

@@ -0,0 +1,14 @@
+package com.jsh.erp.datasource.vo;
+
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+@Data
+@Accessors(chain = true)
+public class SpinnerVO {
+
+    private String label;
+
+    private String value;
+
+}

+ 77 - 0
src/main/java/com/jsh/erp/datasource/vo/TaskStocktakingItemVO.java

@@ -0,0 +1,77 @@
+package com.jsh.erp.datasource.vo;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.math.BigDecimal;
+import java.util.Date;
+
+/**
+ * 盘点任务明细
+ */
+@Data
+@Accessors(chain = true)
+public class TaskStocktakingItemVO {
+
+    @ApiModelProperty("主键ID")
+    private Long id;
+
+    @ApiModelProperty("任务ID")
+    private Long taskStocktakingId;
+
+    @ApiModelProperty("商品名称")
+    private String materialName;
+
+    @ApiModelProperty("系统编码")
+    private String systemSku;
+
+    @ApiModelProperty("商品单位")
+    private String commodityUnit;
+
+    @ApiModelProperty("生产日期")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date productionDate;
+
+    @ApiModelProperty("供应商名称")
+    private String supplierName;
+
+    @ApiModelProperty("商品编码")
+    private String barCode;
+
+    @ApiModelProperty("库存数量")
+    private String inventory;
+
+    @ApiModelProperty("仓库名称")
+    private String depotName;
+
+    @ApiModelProperty("商品种类名称")
+    private String categoryName;
+
+    @ApiModelProperty("商品ID")
+    private Long materialItemId;
+
+    @ApiModelProperty("操作人ID")
+    private Long creator;
+
+    @ApiModelProperty("操作时间")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date operTime;
+
+    @ApiModelProperty("新仓位货架")
+    private String newPosition;
+
+    @ApiModelProperty("新库存数")
+    private BigDecimal newInventory;
+
+    @ApiModelProperty("差异数量")
+    private Integer differenceCount;
+
+    @ApiModelProperty("差异原因")
+    private String differenceReason;
+
+    @ApiModelProperty("删除标记,0.未删除,1.已删除")
+    private boolean deleteFlag;
+
+}

+ 36 - 0
src/main/java/com/jsh/erp/datasource/vo/TaskStocktakingVO.java

@@ -0,0 +1,36 @@
+package com.jsh.erp.datasource.vo;
+
+import com.jsh.erp.datasource.entities.TaskStocktaking;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+/**
+ * 盘点任务
+ */
+@Data
+@Accessors(chain = true)
+public class TaskStocktakingVO extends TaskStocktaking {
+
+    @ApiModelProperty(value = "负责人名称")
+    private String creatorName;
+
+    @ApiModelProperty("创建人名称")
+    private String createByName;
+
+    @ApiModelProperty("仓库名称")
+    private String depotName;
+
+    @ApiModelProperty("完成操作次数")
+    private Long finishCount;
+
+    @ApiModelProperty("商品总数量")
+    private Long itemCount;
+
+    @ApiModelProperty("差异率")
+    private double differenceRate;
+
+    @ApiModelProperty("准确率")
+    private double accuracyRate;
+
+}

+ 20 - 0
src/main/java/com/jsh/erp/datasource/vo/UnitListVo.java

@@ -0,0 +1,20 @@
+package com.jsh.erp.datasource.vo;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.math.BigDecimal;
+
+@Data
+@Accessors(chain = true)
+public class UnitListVo {
+
+    @ApiModelProperty("单位名")
+    private String name;
+
+    @ApiModelProperty("单位比例")
+    private BigDecimal ratio;
+
+
+}

+ 4 - 1
src/main/java/com/jsh/erp/filter/LogCostFilter.java

@@ -14,6 +14,7 @@ import java.io.IOException;
 @WebFilter(filterName = "LogCostFilter", urlPatterns = {"/*"},
         initParams = {@WebInitParam(name = "filterPath",
                       value = "/user/login#" +
+                              "user/pdaLogin#" +
                               "/user/weixinLogin#" +
                               "/user/weixinBind#" +
                               "/user/registerUser#" +
@@ -54,7 +55,9 @@ public class LogCostFilter implements Filter {
             return;
         }
         if (requestUrl != null && (requestUrl.contains("/doc.html") ||
-            requestUrl.contains("/user/login") || requestUrl.contains("/user/register"))) {
+            requestUrl.contains("/user/pdaLogin") ||
+            requestUrl.contains("/user/login") || requestUrl.contains("/user/register") || requestUrl.contains("/user/randomImage")
+            ||requestUrl.contains("/open-api"))) {
             chain.doFilter(request, response);
             return;
         }

+ 128 - 0
src/main/java/com/jsh/erp/query/LambdaQueryWrapperX.java

@@ -0,0 +1,128 @@
+package com.jsh.erp.query;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
+import org.springframework.util.StringUtils;
+
+import java.util.Collection;
+
+/**
+ * 拓展 MyBatis Plus QueryWrapper 类,主要增加如下功能:
+ *
+ * 1. 拼接条件的方法,增加 xxxIfPresent 方法,用于判断值不存在的时候,不要拼接到条件中。
+ *
+ * @param <T> 数据类型
+ */
+public class LambdaQueryWrapperX<T> extends LambdaQueryWrapper<T> {
+
+    public LambdaQueryWrapperX<T> likeIfPresent(SFunction<T, ?> column, String val) {
+        if (StringUtils.hasText(val)) {
+            return (LambdaQueryWrapperX<T>) super.like(column, val);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> inIfPresent(SFunction<T, ?> column, Collection<?> values) {
+        if (!CollectionUtils.isEmpty(values)) {
+            return (LambdaQueryWrapperX<T>) super.in(column, values);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> inIfPresent(SFunction<T, ?> column, Object... values) {
+        if (!ArrayUtils.isEmpty(values)) {
+            return (LambdaQueryWrapperX<T>) super.in(column, values);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> eqIfPresent(SFunction<T, ?> column, Object val) {
+        if (val != null && !val.equals("")) {
+            return (LambdaQueryWrapperX<T>) super.eq(column, val);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> neIfPresent(SFunction<T, ?> column, Object val) {
+        if (val != null) {
+            return (LambdaQueryWrapperX<T>) super.ne(column, val);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> gtIfPresent(SFunction<T, ?> column, Object val) {
+        if (val != null) {
+            return (LambdaQueryWrapperX<T>) super.gt(column, val);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> geIfPresent(SFunction<T, ?> column, Object val) {
+        if (val != null) {
+            return (LambdaQueryWrapperX<T>) super.ge(column, val);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> ltIfPresent(SFunction<T, ?> column, Object val) {
+        if (val != null) {
+            return (LambdaQueryWrapperX<T>) super.lt(column, val);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> leIfPresent(SFunction<T, ?> column, Object val) {
+        if (val != null) {
+            return (LambdaQueryWrapperX<T>) super.le(column, val);
+        }
+        return this;
+    }
+
+    public LambdaQueryWrapperX<T> betweenIfPresent(SFunction<T, ?> column, Object val1, Object val2) {
+        if (val1 != null && !val1.equals("") && val2 != null && !val2.equals("")) {
+            return (LambdaQueryWrapperX<T>) super.between(column, val1, val2);
+        }
+        if (val1 != null && !val1.equals("")) {
+            return (LambdaQueryWrapperX<T>) ge(column, val1);
+        }
+        if (val2 != null && !val2.equals("")) {
+            return (LambdaQueryWrapperX<T>) le(column, val2);
+        }
+        return this;
+    }
+
+    // ========== 重写父类方法,方便链式调用 ==========
+
+    @Override
+    public LambdaQueryWrapperX<T> eq(boolean condition, SFunction<T, ?> column, Object val) {
+        super.eq(condition, column, val);
+        return this;
+    }
+
+    @Override
+    public LambdaQueryWrapperX<T> eq(SFunction<T, ?> column, Object val) {
+        super.eq(column, val);
+        return this;
+    }
+
+    @Override
+    public LambdaQueryWrapperX<T> orderByDesc(SFunction<T, ?> column) {
+        super.orderByDesc(true, column);
+        return this;
+    }
+
+    @Override
+    public LambdaQueryWrapperX<T> last(String lastSql) {
+        super.last(lastSql);
+        return this;
+    }
+
+    @Override
+    public LambdaQueryWrapperX<T> in(SFunction<T, ?> column, Collection<?> coll) {
+        super.in(column, coll);
+        return this;
+    }
+
+}

+ 128 - 0
src/main/java/com/jsh/erp/query/QueryWrapperX.java

@@ -0,0 +1,128 @@
+package com.jsh.erp.query;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import org.springframework.util.StringUtils;
+
+import java.util.Collection;
+
+/**
+ * 2022-09-29  龙涌
+ * 拓展 MyBatis Plus QueryWrapper 类,主要增加如下功能:
+ *
+ * 1. 拼接条件的方法,增加 xxxIfPresent 方法,用于判断值不存在的时候,不要拼接到条件中。
+ *
+ * @param <T> 数据类型
+ */
+public class QueryWrapperX<T> extends QueryWrapper<T> {
+
+    public QueryWrapperX<T> likeIfPresent(String column, String val) {
+        if (StringUtils.hasText(val)) {
+            return (QueryWrapperX<T>) super.like(column, val);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> inIfPresent(String column, Collection<?> values) {
+        if (!CollectionUtils.isEmpty(values)) {
+            return (QueryWrapperX<T>) super.in(column, values);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> inIfPresent(String column, Object... values) {
+        if (!ArrayUtils.isEmpty(values)) {
+            return (QueryWrapperX<T>) super.in(column, values);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> eqIfPresent(String column, Object val) {
+        if (val != null) {
+            return (QueryWrapperX<T>) super.eq(column, val);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> neIfPresent(String column, Object val) {
+        if (val != null) {
+            return (QueryWrapperX<T>) super.ne(column, val);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> gtIfPresent(String column, Object val) {
+        if (val != null) {
+            return (QueryWrapperX<T>) super.gt(column, val);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> geIfPresent(String column, Object val) {
+        if (val != null) {
+            return (QueryWrapperX<T>) super.ge(column, val);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> ltIfPresent(String column, Object val) {
+        if (val != null) {
+            return (QueryWrapperX<T>) super.lt(column, val);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> leIfPresent(String column, Object val) {
+        if (val != null) {
+            return (QueryWrapperX<T>) super.le(column, val);
+        }
+        return this;
+    }
+
+    public QueryWrapperX<T> betweenIfPresent(String column, Object val1, Object val2) {
+        if (val1 != null && val2 != null) {
+            return (QueryWrapperX<T>) super.between(column, val1, val2);
+        }
+        if (val1 != null) {
+            return (QueryWrapperX<T>) ge(column, val1);
+        }
+        if (val2 != null) {
+            return (QueryWrapperX<T>) le(column, val2);
+        }
+        return this;
+    }
+
+    // ========== 重写父类方法,方便链式调用 ==========
+
+    @Override
+    public QueryWrapperX<T> eq(boolean condition, String column, Object val) {
+        super.eq(condition, column, val);
+        return this;
+    }
+
+    @Override
+    public QueryWrapperX<T> eq(String column, Object val) {
+        super.eq(column, val);
+        return this;
+    }
+
+    @Override
+    public QueryWrapperX<T> orderByDesc(String column) {
+        super.orderByDesc(true, column);
+        return this;
+    }
+
+    @Override
+    public QueryWrapperX<T> last(String lastSql) {
+        super.last(lastSql);
+        return this;
+    }
+
+    @Override
+    public QueryWrapperX<T> in(String column, Collection<?> coll) {
+        super.in(column, coll);
+        return this;
+    }
+
+}

+ 37 - 0
src/main/java/com/jsh/erp/result/PageParam.java

@@ -0,0 +1,37 @@
+package com.jsh.erp.result;
+
+import cn.hutool.core.util.ObjectUtil;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import javax.validation.constraints.Max;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotNull;
+import java.io.Serializable;
+
+@ApiModel("分页参数")
+@Data
+public class PageParam implements Serializable {
+
+    private static final Integer PAGE_NO = 1;
+    private static final Integer PAGE_SIZE = 10;
+
+    @ApiModelProperty(value = "页码,从 1 开始", required = true,example = "1")
+    @NotNull(message = "页码不能为空")
+    @Min(value = 1, message = "页码最小值为 1")
+    private Integer pageNo = PAGE_NO;
+    
+    private Integer pageNumber;
+
+    public Integer getPageNo() {
+        return ObjectUtil.defaultIfNull(pageNumber,pageNo);
+    }
+
+    @ApiModelProperty(value = "每页条数,最大值为 100", required = true, example = "10")
+    @NotNull(message = "每页条数不能为空")
+    @Min(value = 1, message = "每页条数最小值为 1")
+    @Max(value = 100, message = "每页条数最大值为 100")
+    private Integer pageSize = PAGE_SIZE;
+
+}

+ 66 - 0
src/main/java/com/jsh/erp/result/PageResult.java

@@ -0,0 +1,66 @@
+package com.jsh.erp.result;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+@ApiModel("分页结果")
+@Data
+public final class PageResult<T> implements Serializable {
+
+    @ApiModelProperty(value = "数据", required = true)
+    private List<T> list;
+    
+    @ApiModelProperty(value = "总量", required = true)
+    private Long total;
+    
+    private Integer pageSize;
+    
+    private Integer pageNumber;
+
+    public PageResult() {
+    }
+
+    public PageResult(List<T> list, Long total) {
+        this.list = list;
+        this.total = total;
+    }
+    public PageResult(List<T> list, Long total, Integer pageSize, Integer pageNumber) {
+        this.list = list;
+        this.total = total;
+        this.pageSize = pageSize;
+        this.pageNumber = pageNumber;
+    }
+    
+    public PageResult(List<T> list, PageResult oldResult) {
+        this.list = list;
+        this.total = oldResult.getTotal();
+        this.pageSize = oldResult.getPageSize();
+        this.pageNumber = oldResult.getPageNumber();
+    }
+
+    public PageResult(Long total) {
+        this.list = new ArrayList<>();
+        this.total = total;
+    }
+
+    public static <T> PageResult<T> empty() {
+        return new PageResult<>(0L);
+    }
+
+    public static <T> PageResult<T> empty(Long total) {
+        return new PageResult<>(total);
+    }
+
+    public static <T> PageResult<T> of(List<T> list, PageParam page) {
+        return new PageResult<>(list, (long) list.size(), page.getPageSize(), page.getPageNo());
+    }
+    
+    public static <T> PageResult<T> of(List<T> list, PageResult oldResult) {
+        return new PageResult<>(list, oldResult);
+    }
+}

+ 56 - 0
src/main/java/com/jsh/erp/result/SortingField.java

@@ -0,0 +1,56 @@
+package com.jsh.erp.result;
+
+import java.io.Serializable;
+
+/**
+ * 排序字段 DTO
+ *
+ * 类名加了 ing 的原因是,避免和 ES SortField 重名。
+ */
+public class SortingField implements Serializable {
+
+    /**
+     * 顺序 - 升序
+     */
+    public static final String ORDER_ASC = "asc";
+    /**
+     * 顺序 - 降序
+     */
+    public static final String ORDER_DESC = "desc";
+
+    /**
+     * 字段
+     */
+    private String field;
+    /**
+     * 顺序
+     */
+    private String order;
+
+    // 空构造方法,解决反序列化
+    public SortingField() {
+    }
+
+    public SortingField(String field, String order) {
+        this.field = field;
+        this.order = order;
+    }
+
+    public String getField() {
+        return field;
+    }
+
+    public SortingField setField(String field) {
+        this.field = field;
+        return this;
+    }
+
+    public String getOrder() {
+        return order;
+    }
+
+    public SortingField setOrder(String order) {
+        this.order = order;
+        return this;
+    }
+}

+ 118 - 1634
src/main/java/com/jsh/erp/service/DepotHeadService.java

@@ -1,1715 +1,199 @@
 package com.jsh.erp.service;
 
-import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.jsh.erp.constants.BusinessConstants;
-import com.jsh.erp.constants.ExceptionConstants;
-import com.jsh.erp.datasource.entities.*;
-import com.jsh.erp.datasource.mappers.DepotHeadMapper;
-import com.jsh.erp.datasource.mappers.DepotHeadMapperEx;
-import com.jsh.erp.datasource.mappers.DepotItemMapperEx;
-import com.jsh.erp.datasource.vo.*;
-import com.jsh.erp.exception.BusinessRunTimeException;
-import com.jsh.erp.exception.JshException;
-import com.jsh.erp.utils.ExcelUtils;
-import com.jsh.erp.utils.PageUtils;
-import com.jsh.erp.utils.StringUtil;
-import com.jsh.erp.utils.Tools;
-import jxl.Workbook;
-import jxl.write.WritableWorkbook;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.jsh.erp.datasource.entities.DepotHead;
+import com.jsh.erp.datasource.pda.dto.PDADepotHeadDTO;
+import com.jsh.erp.datasource.pda.vo.PDADepotHeadVO;
+import com.jsh.erp.datasource.vo.DepotHeadVo4InDetail;
+import com.jsh.erp.datasource.vo.DepotHeadVo4InOutMCount;
+import com.jsh.erp.datasource.vo.DepotHeadVo4List;
+import com.jsh.erp.datasource.vo.DepotHeadVo4StatementAccount;
+import com.jsh.erp.datasource.vo.DepotHeadXsddRequestVO;
+import com.jsh.erp.datasource.vo.DepotItemXsddRequestVO;
 import org.springframework.transaction.annotation.Transactional;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.File;
 import java.math.BigDecimal;
-import java.sql.Timestamp;
-import java.util.*;
-import java.util.stream.Collectors;
+import java.util.List;
+import java.util.Map;
 
-import static com.jsh.erp.utils.Tools.getCenternTime;
-import static com.jsh.erp.utils.Tools.getNow3;
+public interface DepotHeadService extends IService<DepotHead> {
 
-@Service
-public class DepotHeadService {
-    private Logger logger = LoggerFactory.getLogger(DepotHeadService.class);
-
-    @Resource
-    private DepotHeadMapper depotHeadMapper;
-    @Resource
-    private DepotHeadMapperEx depotHeadMapperEx;
-    @Resource
-    private UserService userService;
-    @Resource
-    private RoleService roleService;
-    @Resource
-    private DepotService depotService;
-    @Resource
-    DepotItemService depotItemService;
-    @Resource
-    private SupplierService supplierService;
-    @Resource
-    private UserBusinessService userBusinessService;
-    @Resource
-    private SystemConfigService systemConfigService;
-    @Resource
-    private SerialNumberService serialNumberService;
-    @Resource
-    private OrgaUserRelService orgaUserRelService;
-    @Resource
-    private PersonService personService;
-    @Resource
-    private AccountService accountService;
-    @Resource
-    private AccountHeadService accountHeadService;
-    @Resource
-    private AccountItemService accountItemService;
-    @Resource
-    private SequenceService sequenceService;
-    @Resource
-    DepotItemMapperEx depotItemMapperEx;
-    @Resource
-    private LogService logService;
+    /**
+     * PDA查询订单
+     * @param pdaDepotHeadDTO 筛选条件
+     * @return
+     */
+    List<PDADepotHeadVO> pdaList(PDADepotHeadDTO pdaDepotHeadDTO);
 
-    public DepotHead getDepotHead(long id)throws Exception {
-        DepotHead result=null;
-        try{
-            result=depotHeadMapper.selectByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    DepotHead getDepotHead(long id)throws Exception;
 
-    public List<DepotHead> getDepotHead()throws Exception {
-        DepotHeadExample example = new DepotHeadExample();
-        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<DepotHead> list=null;
-        try{
-            list=depotHeadMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHead> getDepotHead()throws Exception;
 
-    public List<DepotHeadVo4List> select(String type, String subType, String hasDebt, String status, String purchaseStatus, String number, String linkApply, String linkNumber,
-           String beginTime, String endTime, String materialParam, Long organId, Long creator, Long depotId, Long accountId, String remark) throws Exception {
-        List<DepotHeadVo4List> list = new ArrayList<>();
-        try{
-            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
-            Long userId = userService.getUserId(request);
-            String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
-            String billCategory = getBillCategory(subType);
-            String [] depotArray = getDepotArray(subType);
-            String [] creatorArray = getCreatorArray();
-            String [] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
-            String [] purchaseStatusArray = StringUtil.isNotEmpty(purchaseStatus) ? purchaseStatus.split(",") : null;
-            String [] organArray = getOrganArray(subType, purchaseStatus);
-            //以销定购,查看全部数据
-            creatorArray = StringUtil.isNotEmpty(purchaseStatus) ? null: creatorArray;
-            Map<Long,String> personMap = personService.getPersonMap();
-            Map<Long,String> accountMap = accountService.getAccountMap();
-            beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
-            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
-            PageUtils.startPage();
-            list = depotHeadMapperEx.selectByConditionDepotHead(type, subType, creatorArray, hasDebt,
-                    statusArray, purchaseStatusArray, number, linkApply, linkNumber, beginTime, endTime,
-                    materialParam, organId, organArray, creator, depotId, depotArray, accountId, remark);
-            if (null != list) {
-                List<Long> idList = new ArrayList<>();
-                List<String> numberList = new ArrayList<>();
-                for (DepotHeadVo4List dh : list) {
-                    idList.add(dh.getId());
-                    numberList.add(dh.getNumber());
-                }
-                //通过批量查询去构造map
-                Map<String,BigDecimal> finishDepositMap = getFinishDepositMapByNumberList(numberList);
-                Map<Long,Integer> financialBillNoMap = getFinancialBillNoMapByBillIdList(idList);
-                Map<String,Integer> billSizeMap = getBillSizeMapByLinkNumberList(numberList);
-                Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
-                Map<Long,BigDecimal> materialCountListMap = getMaterialCountListMapByHeaderIdList(idList);
-                for (DepotHeadVo4List dh : list) {
-                    if(accountMap!=null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
-                        String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
-                        dh.setAccountName(accountStr);
-                    }
-                    if(dh.getAccountIdList() != null) {
-                        String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
-                        dh.setAccountIdList(accountidlistStr);
-                    }
-                    if(dh.getAccountMoneyList() != null) {
-                        String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
-                        dh.setAccountMoneyList(accountmoneylistStr);
-                    }
-                    if(dh.getChangeAmount() != null) {
-                        dh.setChangeAmount(roleService.parseBillPriceByLimit(dh.getChangeAmount().abs(), billCategory, priceLimit, request));
-                    } else {
-                        dh.setChangeAmount(BigDecimal.ZERO);
-                    }
-                    if(dh.getTotalPrice() != null) {
-                        BigDecimal lastTotalPrice = BusinessConstants.SUB_TYPE_CHECK_ENTER.equals(dh.getSubType())||
-                                BusinessConstants.SUB_TYPE_REPLAY.equals(dh.getSubType())?dh.getTotalPrice():dh.getTotalPrice().abs();
-                        dh.setTotalPrice(roleService.parseBillPriceByLimit(lastTotalPrice, billCategory, priceLimit, request));
-                    }
-                    BigDecimal discountLastMoney = dh.getDiscountLastMoney()!=null?dh.getDiscountLastMoney():BigDecimal.ZERO;
-                    dh.setDiscountLastMoney(roleService.parseBillPriceByLimit(discountLastMoney, billCategory, priceLimit, request));
-                    BigDecimal backAmount = dh.getBackAmount()!=null?dh.getBackAmount():BigDecimal.ZERO;
-                    dh.setBackAmount(roleService.parseBillPriceByLimit(backAmount, billCategory, priceLimit, request));
-                    if(dh.getDeposit() == null) {
-                        dh.setDeposit(BigDecimal.ZERO);
-                    } else {
-                        dh.setDeposit(roleService.parseBillPriceByLimit(dh.getDeposit(), billCategory, priceLimit, request));
-                    }
-                    //已经完成的欠款
-                    if(finishDepositMap!=null) {
-                        BigDecimal finishDeposit = finishDepositMap.get(dh.getNumber()) != null ? finishDepositMap.get(dh.getNumber()) : BigDecimal.ZERO;
-                        dh.setFinishDeposit(roleService.parseBillPriceByLimit(finishDeposit, billCategory, priceLimit, request));
-                    }
-                    //欠款计算
-                    BigDecimal otherMoney = dh.getOtherMoney()!=null?dh.getOtherMoney():BigDecimal.ZERO;
-                    BigDecimal deposit = dh.getDeposit()!=null?dh.getDeposit():BigDecimal.ZERO;
-                    BigDecimal changeAmount = dh.getChangeAmount()!=null?dh.getChangeAmount():BigDecimal.ZERO;
-                    BigDecimal debt = discountLastMoney.add(otherMoney).subtract((deposit.add(changeAmount)));
-                    dh.setDebt(roleService.parseBillPriceByLimit(debt, billCategory, priceLimit, request));
-                    //是否有付款单或收款单
-                    if(financialBillNoMap!=null) {
-                        Integer financialBillNoSize = financialBillNoMap.get(dh.getId());
-                        dh.setHasFinancialFlag(financialBillNoSize!=null && financialBillNoSize>0);
-                    }
-                    //是否有退款单
-                    if(billSizeMap!=null) {
-                        Integer billListSize = billSizeMap.get(dh.getNumber());
-                        dh.setHasBackFlag(billListSize!=null && billListSize>0);
-                    }
-                    if(StringUtil.isNotEmpty(dh.getSalesMan())) {
-                        dh.setSalesManStr(personService.getPersonByMapAndIds(personMap,dh.getSalesMan()));
-                    }
-                    if(dh.getOperTime() != null) {
-                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
-                    }
-                    //商品信息简述
-                    if(materialsListMap!=null) {
-                        dh.setMaterialsList(materialsListMap.get(dh.getId()));
-                    }
-                    //商品总数量
-                    if(materialCountListMap!=null) {
-                        dh.setMaterialCount(materialCountListMap.get(dh.getId()));
-                    }
-                    //以销定购的情况(不能显示销售单据的金额和客户名称)
-                    if(StringUtil.isNotEmpty(purchaseStatus)) {
-                        dh.setOrganName("****");
-                        dh.setTotalPrice(null);
-                        dh.setDiscountLastMoney(null);
-                    }
-                }
-            }
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHeadVo4List> select(String type, String subType, String hasDebt, String status, String purchaseStatus, String number, String linkApply, String linkNumber,
+                                  String beginTime, String endTime, String materialParam, Long organId, Long creator, Long depotId, Long accountId, String remark) throws Exception;
 
-    /**
-     * 根据单据类型获取仓库数组
-     * @param subType
-     * @return
-     * @throws Exception
-     */
-    public String[] getDepotArray(String subType) throws Exception {
-        String [] depotArray = null;
-        if(!BusinessConstants.SUB_TYPE_PURCHASE_APPLY.equals(subType)
-                && !BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(subType)
-                && !BusinessConstants.SUB_TYPE_SALES_ORDER.equals(subType)) {
-            String depotIds = depotService.findDepotStrByCurrentUser();
-            depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
-        }
-        return depotArray;
-    }
+    String[] getDepotArray(String subType) throws Exception;
 
-    /**
-     * 根据角色类型获取操作员数组
-     * @return
-     * @throws Exception
-     */
-    public String[] getCreatorArray() throws Exception {
-        String creator = getCreatorByCurrentUser();
-        String [] creatorArray=null;
-        if(StringUtil.isNotEmpty(creator)){
-            creatorArray = creator.split(",");
-        }
-        return creatorArray;
-    }
+    String[] getCreatorArray() throws Exception;
 
-    /**
-     * 根据角色类型获取操作员数组
-     * @param organizationId
-     * @return
-     * @throws Exception
-     */
-    public String[] getCreatorArrayByOrg(Long organizationId) throws Exception {
-        List<Long> userIdList = orgaUserRelService.getUserIdListByOrgId(organizationId);
-        if(userIdList.size()>0) {
-            List<String> userIdStrList = userIdList.stream().map(Object::toString).collect(Collectors.toList());
-            return StringUtil.listToStringArray(userIdStrList);
-        } else {
-            return "-1".split(",");
-        }
-    }
+    String[] getCreatorArrayByOrg(Long organizationId) throws Exception;
 
-    /**
-     * 获取机构数组
-     * @return
-     */
-    public String[] getOrganArray(String subType, String purchaseStatus) throws Exception {
-        String [] organArray = null;
-        String type = "UserCustomer";
-        Long userId = userService.getCurrentUser().getId();
-        //获取权限信息
-        String ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, userId.toString());
-        List<Supplier> supplierList = supplierService.findBySelectCus();
-        if(BusinessConstants.SUB_TYPE_SALES_ORDER.equals(subType) || BusinessConstants.SUB_TYPE_SALES.equals(subType)
-                ||BusinessConstants.SUB_TYPE_SALES_RETURN.equals(subType) ) {
-            //采购订单里面选择销售订单的时候不要过滤
-            if(StringUtil.isEmpty(purchaseStatus)) {
-                if (null != supplierList && supplierList.size() > 0) {
-                    boolean customerFlag = systemConfigService.getCustomerFlag();
-                    List<String> organList = new ArrayList<>();
-                    for (Supplier supplier : supplierList) {
-                        boolean flag = ubValue.contains("[" + supplier.getId().toString() + "]");
-                        if (!customerFlag || flag) {
-                            organList.add(supplier.getId().toString());
-                        }
-                    }
-                    if(organList.size() > 0) {
-                        organArray = StringUtil.listToStringArray(organList);
-                    }
-                }
-            }
-        }
-        return organArray;
-    }
+    String[] getOrganArray(String subType, String purchaseStatus) throws Exception;
 
-    /**
-     * 根据角色类型获取操作员
-     * @return
-     * @throws Exception
-     */
-    public String getCreatorByCurrentUser() throws Exception {
-        String creator = "";
-        User user = userService.getCurrentUser();
-        String roleType = userService.getRoleTypeByUserId(user.getId()).getType(); //角色类型
-        if(BusinessConstants.ROLE_TYPE_PRIVATE.equals(roleType)) {
-            creator = user.getId().toString();
-        } else if(BusinessConstants.ROLE_TYPE_THIS_ORG.equals(roleType)) {
-            creator = orgaUserRelService.getUserIdListByUserId(user.getId());
-        }
-        return creator;
-    }
+    String getCreatorByCurrentUser() throws Exception;
 
-    public Map<String, BigDecimal> getFinishDepositMapByNumberList(List<String> numberList) {
-        Map<String,BigDecimal> finishDepositMap = new HashMap<>();
-        if(numberList.size()>0) {
-            List<FinishDepositVo> list = depotHeadMapperEx.getFinishDepositByNumberList(numberList);
-            if(list!=null && list.size()>0) {
-                for (FinishDepositVo finishDepositVo : list) {
-                    if(finishDepositVo!=null) {
-                        finishDepositMap.put(finishDepositVo.getNumber(), finishDepositVo.getFinishDeposit());
-                    }
-                }
-            }
-        }
-        return finishDepositMap;
-    }
+    Map<String, BigDecimal> getFinishDepositMapByNumberList(List<String> numberList);
 
-    public Map<String, Integer> getBillSizeMapByLinkNumberList(List<String> numberList) throws Exception {
-        Map<String, Integer> billListMap = new HashMap<>();
-        if(numberList.size()>0) {
-            List<DepotHead> list = getBillListByLinkNumberList(numberList);
-            if(list!=null && list.size()>0) {
-                for (DepotHead depotHead : list) {
-                    if(depotHead!=null) {
-                        billListMap.put(depotHead.getLinkNumber(), list.size());
-                    }
-                }
-            }
-        }
-        return billListMap;
-    }
+    Map<String, Integer> getBillSizeMapByLinkNumberList(List<String> numberList) throws Exception;
 
-    public Map<Long,Integer> getFinancialBillNoMapByBillIdList(List<Long> idList) {
-        Map<Long, Integer> billListMap = new HashMap<>();
-        if(idList.size()>0) {
-            List<AccountItem> list = accountHeadService.getFinancialBillNoByBillIdList(idList);
-            if(list!=null && list.size()>0) {
-                for (AccountItem accountItem : list) {
-                    if(accountItem!=null) {
-                        billListMap.put(accountItem.getBillId(), list.size());
-                    }
-                }
-            }
-        }
-        return billListMap;
-    }
+    Map<Long,Integer> getFinancialBillNoMapByBillIdList(List<Long> idList);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertDepotHead(JSONObject obj, HttpServletRequest request)throws Exception {
-        DepotHead depotHead = JSONObject.parseObject(obj.toJSONString(), DepotHead.class);
-        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
-        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
-        int result=0;
-        try{
-            result=depotHeadMapper.insert(depotHead);
-            logService.insertLog("单据", BusinessConstants.LOG_OPERATION_TYPE_ADD, request);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int insertDepotHead(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateDepotHead(JSONObject obj, HttpServletRequest request) throws Exception{
-        DepotHead depotHead = JSONObject.parseObject(obj.toJSONString(), DepotHead.class);
-        DepotHead dh=null;
-        try{
-            dh = depotHeadMapper.selectByPrimaryKey(depotHead.getId());
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        depotHead.setStatus(dh.getStatus());
-        depotHead.setCreateTime(dh.getCreateTime());
-        int result=0;
-        try{
-            result = depotHeadMapper.updateByPrimaryKey(depotHead);
-            logService.insertLog("单据",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(depotHead.getId()).toString(), request);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int updateDepotHead(JSONObject obj, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int deleteDepotHead(Long id, HttpServletRequest request)throws Exception {
-        return batchDeleteBillByIds(id.toString());
-    }
+    int deleteDepotHead(Long id, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteDepotHead(String ids, HttpServletRequest request)throws Exception {
-        return batchDeleteBillByIds(ids);
-    }
+    int batchDeleteDepotHead(String ids, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteBillByIds(String ids)throws Exception {
-        StringBuffer sb = new StringBuffer();
-        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
-        List<DepotHead> dhList = getDepotHeadListByIds(ids);
-        for(DepotHead depotHead: dhList){
-            //只有未审核的单据才能被删除
-            if(!"0".equals(depotHead.getStatus())) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_DELETE_FAILED_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_DELETE_FAILED_MSG));
-            }
-        }
-        for(DepotHead depotHead: dhList){
-            sb.append("[").append(depotHead.getNumber()).append("]");
-            User userInfo = userService.getCurrentUser();
-            //删除入库单据,先校验序列号是否出库,如果未出库则同时删除序列号,如果已出库则不能删除单据
-            if (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType())) {
-                List<DepotItem> depotItemList = depotItemMapperEx.findDepotItemListBydepotheadId(depotHead.getId(), BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED);
-                if (depotItemList != null && depotItemList.size() > 0) {
-                    //单据明细里面存在序列号商品
-                    int serialNumberSellCount = depotHeadMapperEx.getSerialNumberBySell(depotHead.getNumber());
-                    if (serialNumberSellCount > 0) {
-                        //已出库则不能删除单据
-                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_SERIAL_IS_SELL_CODE,
-                                String.format(ExceptionConstants.DEPOT_HEAD_SERIAL_IS_SELL_MSG, depotHead.getNumber()));
-                    } else {
-                        //删除序列号
-                        SerialNumberExample example = new SerialNumberExample();
-                        example.createCriteria().andInBillNoEqualTo(depotHead.getNumber());
-                        serialNumberService.deleteByExample(example);
-                    }
-                }
-            }
-            //删除出库数据回收序列号
-            if (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
-                    && !BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
-                //查询单据子表列表
-                List<DepotItem> depotItemList = depotItemMapperEx.findDepotItemListBydepotheadId(depotHead.getId(), BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED);
-                /**回收序列号*/
-                if (depotItemList != null && depotItemList.size() > 0) {
-                    for (DepotItem depotItem : depotItemList) {
-                        //BasicNumber=OperNumber*ratio
-                        serialNumberService.cancelSerialNumber(depotItem.getMaterialId(), depotHead.getNumber(), (depotItem.getBasicNumber() == null ? 0 : depotItem.getBasicNumber()).intValue(), userInfo);
-                    }
-                }
-            }
-            List<DepotItem> list = depotItemService.getListByHeaderId(depotHead.getId());
-            //删除单据子表数据
-            depotItemMapperEx.batchDeleteDepotItemByDepotHeadIds(new Long[]{depotHead.getId()});
-            //删除单据主表信息
-            batchDeleteDepotHeadByIds(depotHead.getId().toString());
-            //将关联的单据置为审核状态-针对采购入库、销售出库、盘点复盘、其它入库、其它出库
-            if(StringUtil.isNotEmpty(depotHead.getLinkNumber())){
-                if((BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
-                        BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType()))
-                        || (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) &&
-                        BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType()))
-                        || (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
-                        BusinessConstants.SUB_TYPE_REPLAY.equals(depotHead.getSubType()))
-                        || (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
-                        BusinessConstants.SUB_TYPE_OTHER.equals(depotHead.getSubType()))
-                        || (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) &&
-                        BusinessConstants.SUB_TYPE_OTHER.equals(depotHead.getSubType()))) {
-                    String status = BusinessConstants.BILLS_STATUS_AUDIT;
-                    //查询除当前单据之外的关联单据列表
-                    List<DepotHead> exceptCurrentList = getListByLinkNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber(), depotHead.getType());
-                    if(exceptCurrentList!=null && exceptCurrentList.size()>0) {
-                        status = BusinessConstants.BILLS_STATUS_SKIPING;
-                    }
-                    DepotHead dh = new DepotHead();
-                    dh.setStatus(status);
-                    DepotHeadExample example = new DepotHeadExample();
-                    example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
-                    depotHeadMapper.updateByExampleSelective(dh, example);
-                }
-            }
-            //将关联的单据置为审核状态-针对请购单转采购订单的情况
-            if(StringUtil.isNotEmpty(depotHead.getLinkApply())){
-                if(BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
-                        BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
-                    String status = BusinessConstants.BILLS_STATUS_AUDIT;
-                    //查询除当前单据之外的关联单据列表
-                    List<DepotHead> exceptCurrentList = getListByLinkApplyExceptCurrent(depotHead.getLinkApply(), depotHead.getNumber(), depotHead.getType());
-                    if(exceptCurrentList!=null && exceptCurrentList.size()>0) {
-                        status = BusinessConstants.BILLS_STATUS_SKIPING;
-                    }
-                    DepotHead dh = new DepotHead();
-                    dh.setStatus(status);
-                    DepotHeadExample example = new DepotHeadExample();
-                    example.createCriteria().andNumberEqualTo(depotHead.getLinkApply());
-                    depotHeadMapper.updateByExampleSelective(dh, example);
-                }
-            }
-            //将关联的销售订单单据置为未采购状态-针对销售订单转采购订单的情况
-            if(StringUtil.isNotEmpty(depotHead.getLinkNumber())){
-                if(BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
-                        BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
-                    DepotHead dh = new DepotHead();
-                    //获取分批操作后单据的商品和商品数量(汇总)
-                    List<DepotItemVo4MaterialAndSum> batchList = depotItemMapperEx.getBatchBillDetailMaterialSum(depotHead.getLinkNumber(), "normal", depotHead.getType());
-                    if(batchList.size()>0) {
-                        dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_SKIPING);
-                    } else {
-                        dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_UN_AUDIT);
-                    }
-                    DepotHeadExample example = new DepotHeadExample();
-                    example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
-                    depotHeadMapper.updateByExampleSelective(dh, example);
-                }
-            }
-            //对于零售出库单据,更新会员的预收款信息
-            if (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
-                    && BusinessConstants.SUB_TYPE_RETAIL.equals(depotHead.getSubType())){
-                if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())) {
-                    if (depotHead.getOrganId() != null) {
-                        //更新会员预付款
-                        supplierService.updateAdvanceIn(depotHead.getOrganId());
-                    }
-                }
-            }
-            for (DepotItem depotItem : list) {
-                //更新当前库存
-                depotItemService.updateCurrentStock(depotItem);
-                //更新当前成本价
-                depotItemService.updateCurrentUnitPrice(depotItem);
-            }
-        }
-        //路径列表
-        List<String> pathList = new ArrayList<>();
-        for(DepotHead depotHead: dhList){
-            if(StringUtil.isNotEmpty(depotHead.getFileName())) {
-                pathList.add(depotHead.getFileName());
-            }
-        }
-        //逻辑删除文件
-        systemConfigService.deleteFileByPathList(pathList);
-        logService.insertLog("单据", sb.toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        return 1;
-    }
+    int batchDeleteBillByIds(String ids)throws Exception;
 
-    /**
-     * 删除单据主表信息
-     * @param ids
-     * @return
-     * @throws Exception
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteDepotHeadByIds(String ids)throws Exception {
-        User userInfo=userService.getCurrentUser();
-        String [] idArray=ids.split(",");
-        int result=0;
-        try{
-            result = depotHeadMapperEx.batchDeleteDepotHeadByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int batchDeleteDepotHeadByIds(String ids)throws Exception;
 
-    public List<DepotHead> getDepotHeadListByIds(String ids)throws Exception {
-        List<Long> idList = StringUtil.strToLongList(ids);
-        List<DepotHead> list = new ArrayList<>();
-        try{
-            DepotHeadExample example = new DepotHeadExample();
-            example.createCriteria().andIdIn(idList);
-            list = depotHeadMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHead> getDepotHeadListByIds(String ids)throws Exception;
 
-    /**
-     * 校验单据编号是否存在
-     * @param id
-     * @param number
-     * @return
-     * @throws Exception
-     */
-    public int checkIsBillNumberExist(Long id, String number)throws Exception {
-        DepotHeadExample example = new DepotHeadExample();
-        example.createCriteria().andIdNotEqualTo(id).andNumberEqualTo(number).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<DepotHead> list = null;
-        try{
-            list = depotHeadMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list==null?0:list.size();
-    }
+    int checkIsBillNumberExist(Long id, String number)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchSetStatus(String status, String depotHeadIDs)throws Exception {
-        int result = 0;
-        List<Long> dhIds = new ArrayList<>();
-        List<Long> ids = StringUtil.strToLongList(depotHeadIDs);
-        for(Long id: ids) {
-            DepotHead depotHead = getDepotHead(id);
-            if("0".equals(status)){
-                //进行反审核操作
-                if("1".equals(depotHead.getStatus()) && "0".equals(depotHead.getPurchaseStatus())) {
-                    dhIds.add(id);
-                } else if("2".equals(depotHead.getPurchaseStatus())) {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_TWO_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_TWO_MSG));
-                } else if("3".equals(depotHead.getPurchaseStatus())) {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_THREE_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_THREE_MSG));
-                } else {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG));
-                }
-            } else if("1".equals(status)){
-                //进行审核操作
-                if("0".equals(depotHead.getStatus())) {
-                    dhIds.add(id);
-                } else {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_TO_AUDIT_FAILED_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_TO_AUDIT_FAILED_MSG));
-                }
-            }
-        }
-        if(dhIds.size()>0) {
-            DepotHead depotHead = new DepotHead();
-            depotHead.setStatus(status);
-            DepotHeadExample example = new DepotHeadExample();
-            example.createCriteria().andIdIn(dhIds);
-            result = depotHeadMapper.updateByExampleSelective(depotHead, example);
-            //更新当前库存
-            if(systemConfigService.getForceApprovalFlag()) {
-                for(Long dhId: dhIds) {
-                    List<DepotItem> list = depotItemService.getListByHeaderId(dhId);
-                    for (DepotItem depotItem : list) {
-                        depotItemService.updateCurrentStock(depotItem);
-                    }
-                }
-            }
-        }
-        return result;
-    }
+    int batchSetStatus(String status, String depotHeadIDs)throws Exception;
 
-    public Map<Long,String> findMaterialsListMapByHeaderIdList(List<Long> idList)throws Exception {
-        Map<Long,String> materialsListMap = new HashMap<>();
-        if(idList.size()>0) {
-            List<MaterialsListVo> list = depotHeadMapperEx.findMaterialsListMapByHeaderIdList(idList);
-            for (MaterialsListVo materialsListVo : list) {
-                String materialsList = materialsListVo.getMaterialsList();
-                if(StringUtil.isNotEmpty(materialsList)) {
-                    materialsList = materialsList.replace(",",",");
-                }
-                materialsListMap.put(materialsListVo.getHeaderId(), materialsList);
-            }
-        }
-        return materialsListMap;
-    }
+    Map<Long,String> findMaterialsListMapByHeaderIdList(List<Long> idList)throws Exception;
 
-    public Map<Long,BigDecimal> getMaterialCountListMapByHeaderIdList(List<Long> idList)throws Exception {
-        Map<Long,BigDecimal> materialCountListMap = new HashMap<>();
-        if(idList.size()>0) {
-            List<MaterialCountVo> list = depotHeadMapperEx.getMaterialCountListByHeaderIdList(idList);
-            for(MaterialCountVo materialCountVo : list){
-                materialCountListMap.put(materialCountVo.getHeaderId(), materialCountVo.getMaterialCount());
-            }
-        }
-        return materialCountListMap;
-    }
+    Map<Long,BigDecimal> getMaterialCountListMapByHeaderIdList(List<Long> idList)throws Exception;
 
-    public List<DepotHeadVo4InDetail> findInOutDetail(String beginTime, String endTime, String type, String[] creatorArray,
-                                                      String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag,
-                                                      String materialParam, List<Long> depotList, Integer oId, String number,
-                                                      Long creator, String remark, String column, String order, Integer offset, Integer rows) throws Exception{
-        List<DepotHeadVo4InDetail> list = null;
-        try{
-            list =depotHeadMapperEx.findInOutDetail(beginTime, endTime, type, creatorArray, organArray, categoryList, forceFlag, inOutManageFlag,
-                    materialParam, depotList, oId, number, creator, remark, column, order, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHeadVo4InDetail> findInOutDetail(String beginTime, String endTime, String type, String[] creatorArray,
+                                               String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag,
+                                               String materialParam, List<Long> depotList, Integer oId, String number,
+                                               Long creator, String remark, String column, String order, Integer offset, Integer rows) throws Exception;
 
-    public int findInOutDetailCount(String beginTime, String endTime, String type, String[] creatorArray,
-                                    String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag, String materialParam, List<Long> depotList, Integer oId, String number,
-                                    Long creator, String remark) throws Exception{
-        int result = 0;
-        try{
-            result =depotHeadMapperEx.findInOutDetailCount(beginTime, endTime, type, creatorArray, organArray, categoryList, forceFlag, inOutManageFlag,
-                    materialParam, depotList, oId, number, creator, remark);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int findInOutDetailCount(String beginTime, String endTime, String type, String[] creatorArray,
+                             String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag, String materialParam, List<Long> depotList, Integer oId, String number,
+                             Long creator, String remark) throws Exception;
 
-    public DepotHeadVo4InDetail findInOutDetailStatistic(String beginTime, String endTime, String type, String [] creatorArray,
-                                                      String [] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag,
-                                                      String materialParam, List<Long> depotList, Integer oId, String number,
-                                                      Long creator, String remark) throws Exception{
-        DepotHeadVo4InDetail item = new DepotHeadVo4InDetail();
-        try{
-            List<DepotHeadVo4InDetail> list =depotHeadMapperEx.findInOutDetailStatistic(beginTime, endTime, type, creatorArray, organArray, categoryList, forceFlag, inOutManageFlag,
-                    materialParam, depotList, oId, number, creator, remark);
-            if(list.size()>0) {
-                item.setOperNumber(list.get(0).getOperNumber());
-                item.setAllPrice(list.get(0).getAllPrice());
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return item;
-    }
+    DepotHeadVo4InDetail findInOutDetailStatistic(String beginTime, String endTime, String type, String[] creatorArray,
+                                                  String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag,
+                                                  String materialParam, List<Long> depotList, Integer oId, String number,
+                                                  Long creator, String remark) throws Exception;
 
-    public List<DepotHeadVo4InOutMCount> findInOutMaterialCount(String beginTime, String endTime, String type, List<Long> categoryList,
-                                                                Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
-                                                                List<Long> depotList, Long organizationId, Integer oId, String column, String order,
-                                                                Integer offset, Integer rows)throws Exception {
-        List<DepotHeadVo4InOutMCount> list = null;
-        try{
-            String [] creatorArray = getCreatorArray();
-            if(creatorArray == null && organizationId != null) {
-                creatorArray = getCreatorArrayByOrg(organizationId);
-            }
-            String subType = "出库".equals(type)? "销售" : "";
-            String [] organArray = getOrganArray(subType, "");
-            list =depotHeadMapperEx.findInOutMaterialCount(beginTime, endTime, type, categoryList, forceFlag, inOutManageFlag, materialParam, depotList, oId,
-                    creatorArray, organArray, column, order, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHeadVo4InOutMCount> findInOutMaterialCount(String beginTime, String endTime, String type, List<Long> categoryList,
+                                                         Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
+                                                         List<Long> depotList, Long organizationId, Integer oId, String column, String order,
+                                                         Integer offset, Integer rows)throws Exception;
 
-    public int findInOutMaterialCountTotal(String beginTime, String endTime, String type, List<Long> categoryList,
-                                           Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
-                                           List<Long> depotList, Long organizationId, Integer oId)throws Exception {
-        int result = 0;
-        try{
-            String [] creatorArray = getCreatorArray();
-            if(creatorArray == null && organizationId != null) {
-                creatorArray = getCreatorArrayByOrg(organizationId);
-            }
-            String subType = "出库".equals(type)? "销售" : "";
-            String [] organArray = getOrganArray(subType, "");
-            result =depotHeadMapperEx.findInOutMaterialCountTotal(beginTime, endTime, type, categoryList, forceFlag, inOutManageFlag, materialParam, depotList, oId,
-                    creatorArray, organArray);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int findInOutMaterialCountTotal(String beginTime, String endTime, String type, List<Long> categoryList,
+                                    Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
+                                    List<Long> depotList, Long organizationId, Integer oId)throws Exception;
 
-    public DepotHeadVo4InOutMCount findInOutMaterialCountStatistic(String beginTime, String endTime, String type, List<Long> categoryList,
-                                                                Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
-                                                                List<Long> depotList, Long organizationId, Integer oId) throws Exception {
-        DepotHeadVo4InOutMCount item = new DepotHeadVo4InOutMCount();
-        try{
-            String [] creatorArray = getCreatorArray();
-            if(creatorArray == null && organizationId != null) {
-                creatorArray = getCreatorArrayByOrg(organizationId);
-            }
-            String subType = "出库".equals(type)? "销售" : "";
-            String [] organArray = getOrganArray(subType, "");
-            List<DepotHeadVo4InOutMCount> list = depotHeadMapperEx.findInOutMaterialCountStatistic(beginTime, endTime, type, categoryList,
-                    forceFlag, inOutManageFlag, materialParam, depotList, oId, creatorArray, organArray);
-            if(list.size()>0) {
-                item.setNumSum(list.get(0).getNumSum());
-                item.setPriceSum(list.get(0).getPriceSum());
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return item;
-    }
+    DepotHeadVo4InOutMCount findInOutMaterialCountStatistic(String beginTime, String endTime, String type, List<Long> categoryList,
+                                                            Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
+                                                            List<Long> depotList, Long organizationId, Integer oId) throws Exception;
 
-    public List<DepotHeadVo4InDetail> findAllocationDetail(String beginTime, String endTime, String subType, String number,
-                            String [] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
-                            String remark, String column, String order, Integer offset, Integer rows) throws Exception{
-        List<DepotHeadVo4InDetail> list = null;
-        try{
-            list =depotHeadMapperEx.findAllocationDetail(beginTime, endTime, subType, number, creatorArray, categoryList, forceFlag,
-                    materialParam, depotList, depotFList, remark, column, order, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHeadVo4InDetail> findAllocationDetail(String beginTime, String endTime, String subType, String number,
+                                                    String[] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
+                                                    String remark, String column, String order, Integer offset, Integer rows) throws Exception;
 
-    public int findAllocationDetailCount(String beginTime, String endTime, String subType, String number,
-                            String [] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList,  List<Long> depotFList,
-                            String remark) throws Exception{
-        int result = 0;
-        try{
-            result =depotHeadMapperEx.findAllocationDetailCount(beginTime, endTime, subType, number, creatorArray, categoryList, forceFlag,
-                    materialParam, depotList, depotFList, remark);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int findAllocationDetailCount(String beginTime, String endTime, String subType, String number,
+                                  String[] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
+                                  String remark) throws Exception;
 
-    public DepotHeadVo4InDetail findAllocationStatistic(String beginTime, String endTime, String subType, String number,
-                                                        String [] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
-                                                        String remark) throws Exception{
-        DepotHeadVo4InDetail item = new DepotHeadVo4InDetail();
-        try{
-            List<DepotHeadVo4InDetail> list =depotHeadMapperEx.findAllocationStatistic(beginTime, endTime, subType, number, creatorArray, categoryList, forceFlag,
-                    materialParam, depotList, depotFList, remark);
-            if(list.size()>0) {
-                item.setOperNumber(list.get(0).getOperNumber());
-                item.setAllPrice(list.get(0).getAllPrice());
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return item;
-    }
+    DepotHeadVo4InDetail findAllocationStatistic(String beginTime, String endTime, String subType, String number,
+                                                 String[] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
+                                                 String remark) throws Exception;
 
-    public List<DepotHeadVo4StatementAccount> getStatementAccount(String beginTime, String endTime, Integer organId, String [] organArray,
-                                                                  Integer hasDebt, String supplierType, String type, String subType, String typeBack,
-                                                                  String subTypeBack, String billType, Integer offset, Integer rows) {
-        List<DepotHeadVo4StatementAccount> list = null;
-        try{
-            list = depotHeadMapperEx.getStatementAccount(beginTime, endTime, organId, organArray, hasDebt, supplierType, type, subType,typeBack, subTypeBack, billType, offset, rows);
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHeadVo4StatementAccount> getStatementAccount(String beginTime, String endTime, Integer organId, String[] organArray,
+                                                           Integer hasDebt, String supplierType, String type, String subType, String typeBack,
+                                                           String subTypeBack, String billType, Integer offset, Integer rows);
 
-    public int getStatementAccountCount(String beginTime, String endTime, Integer organId, String [] organArray,
-                                        Integer hasDebt, String supplierType, String type, String subType, String typeBack, String subTypeBack, String billType) {
-        int result = 0;
-        try{
-            result = depotHeadMapperEx.getStatementAccountCount(beginTime, endTime, organId, organArray, hasDebt, supplierType, type, subType,typeBack, subTypeBack, billType);
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int getStatementAccountCount(String beginTime, String endTime, Integer organId, String[] organArray,
+                                 Integer hasDebt, String supplierType, String type, String subType, String typeBack, String subTypeBack, String billType);
 
-    public List<DepotHeadVo4StatementAccount> getStatementAccountTotalPay(String beginTime, String endTime, Integer organId, String [] organArray,
-                                                                          Integer hasDebt, String supplierType, String type, String subType,
-                                                                          String typeBack, String subTypeBack, String billType) {
-        List<DepotHeadVo4StatementAccount> list = null;
-        try{
-            list = depotHeadMapperEx.getStatementAccountTotalPay(beginTime, endTime, organId, organArray, hasDebt, supplierType, type, subType,typeBack, subTypeBack, billType);
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotHeadVo4StatementAccount> getStatementAccountTotalPay(String beginTime, String endTime, Integer organId, String[] organArray,
+                                                                   Integer hasDebt, String supplierType, String type, String subType,
+                                                                   String typeBack, String subTypeBack, String billType);
 
-    public List<DepotHeadVo4List> getDetailByNumber(String number, HttpServletRequest request)throws Exception {
-        List<DepotHeadVo4List> resList = new ArrayList<>();
-        try{
-            Long userId = userService.getUserId(request);
-            String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
-            Map<Long,String> personMap = personService.getPersonMap();
-            Map<Long,String> accountMap = accountService.getAccountMap();
-            List<DepotHeadVo4List> list = depotHeadMapperEx.getDetailByNumber(number);
-            if (null != list) {
-                List<Long> idList = new ArrayList<>();
-                List<String> numberList = new ArrayList<>();
-                for (DepotHeadVo4List dh : list) {
-                    idList.add(dh.getId());
-                    numberList.add(dh.getNumber());
-                }
-                //通过批量查询去构造map
-                Map<Long,Integer> financialBillNoMap = getFinancialBillNoMapByBillIdList(idList);
-                Map<String,Integer> billSizeMap = getBillSizeMapByLinkNumberList(numberList);
-                Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
-                DepotHeadVo4List dh = list.get(0);
-                String billCategory = getBillCategory(dh.getSubType());
-                if(accountMap!=null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
-                    String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
-                    dh.setAccountName(accountStr);
-                }
-                if(dh.getAccountIdList() != null) {
-                    String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
-                    dh.setAccountIdList(accountidlistStr);
-                }
-                if(dh.getAccountMoneyList() != null) {
-                    String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
-                    dh.setAccountMoneyList(accountmoneylistStr);
-                }
-                if(dh.getChangeAmount() != null) {
-                    dh.setChangeAmount(roleService.parseBillPriceByLimit(dh.getChangeAmount().abs(), billCategory, priceLimit, request));
-                } else {
-                    dh.setChangeAmount(BigDecimal.ZERO);
-                }
-                if(dh.getTotalPrice() != null) {
-                    dh.setTotalPrice(roleService.parseBillPriceByLimit(dh.getTotalPrice().abs(), billCategory, priceLimit, request));
-                }
-                BigDecimal discountLastMoney = dh.getDiscountLastMoney()!=null?dh.getDiscountLastMoney():BigDecimal.ZERO;
-                dh.setDiscountLastMoney(roleService.parseBillPriceByLimit(discountLastMoney, billCategory, priceLimit, request));
-                BigDecimal backAmount = dh.getBackAmount()!=null?dh.getBackAmount():BigDecimal.ZERO;
-                dh.setBackAmount(roleService.parseBillPriceByLimit(backAmount, billCategory, priceLimit, request));
-                if(dh.getDeposit() == null) {
-                    dh.setDeposit(BigDecimal.ZERO);
-                } else {
-                    dh.setDeposit(roleService.parseBillPriceByLimit(dh.getDeposit(), billCategory, priceLimit, request));
-                }
-                //欠款计算
-                BigDecimal otherMoney = dh.getOtherMoney()!=null?dh.getOtherMoney():BigDecimal.ZERO;
-                BigDecimal deposit = dh.getDeposit()!=null?dh.getDeposit():BigDecimal.ZERO;
-                BigDecimal changeAmount = dh.getChangeAmount()!=null?dh.getChangeAmount():BigDecimal.ZERO;
-                BigDecimal debt = discountLastMoney.add(otherMoney).subtract((deposit.add(changeAmount)));
-                dh.setDebt(roleService.parseBillPriceByLimit(debt, billCategory, priceLimit, request));
-                //是否有付款单或收款单
-                if(financialBillNoMap!=null) {
-                    Integer financialBillNoSize = financialBillNoMap.get(dh.getId());
-                    dh.setHasFinancialFlag(financialBillNoSize!=null && financialBillNoSize>0);
-                }
-                //是否有退款单
-                if(billSizeMap!=null) {
-                    Integer billListSize = billSizeMap.get(dh.getNumber());
-                    dh.setHasBackFlag(billListSize!=null && billListSize>0);
-                }
-                if(StringUtil.isNotEmpty(dh.getSalesMan())) {
-                    dh.setSalesManStr(personService.getPersonByMapAndIds(personMap,dh.getSalesMan()));
-                }
-                if(dh.getOperTime() != null) {
-                    dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
-                }
-                //商品信息简述
-                if(materialsListMap!=null) {
-                    dh.setMaterialsList(materialsListMap.get(dh.getId()));
-                }
-                dh.setCreatorName(userService.getUser(dh.getCreator()).getUsername());
-                resList.add(dh);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return resList;
-    }
+    List<DepotHeadVo4List> getDetailByNumber(String number, HttpServletRequest request)throws Exception;
 
-    /**
-     * 查询除当前单据之外的关联单据列表
-     * @param linkNumber
-     * @param number
-     * @return
-     * @throws Exception
-     */
-    public List<DepotHead> getListByLinkNumberExceptCurrent(String linkNumber, String number, String type)throws Exception {
-        DepotHeadExample example = new DepotHeadExample();
-        example.createCriteria().andLinkNumberEqualTo(linkNumber).andNumberNotEqualTo(number).andTypeEqualTo(type)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        return depotHeadMapper.selectByExample(example);
-    }
+    List<DepotHead> getListByLinkNumberExceptCurrent(String linkNumber, String number, String type)throws Exception;
 
-    /**
-     * 查询除当前单据之外的关联单据列表
-     * @param linkApply
-     * @param number
-     * @return
-     * @throws Exception
-     */
-    public List<DepotHead> getListByLinkApplyExceptCurrent(String linkApply, String number, String type)throws Exception {
-        DepotHeadExample example = new DepotHeadExample();
-        example.createCriteria().andLinkApplyEqualTo(linkApply).andNumberNotEqualTo(number).andTypeEqualTo(type)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        return depotHeadMapper.selectByExample(example);
-    }
+    List<DepotHead> getListByLinkApplyExceptCurrent(String linkApply, String number, String type)throws Exception;
 
-    /**
-     * 根据原单号查询关联的单据列表(批量)
-     * @param linkNumberList
-     * @return
-     * @throws Exception
-     */
-    public List<DepotHead> getBillListByLinkNumberList(List<String> linkNumberList)throws Exception {
-        if(linkNumberList!=null && linkNumberList.size()>0) {
-            DepotHeadExample example = new DepotHeadExample();
-            example.createCriteria().andLinkNumberIn(linkNumberList).andSubTypeLike("退货").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            return depotHeadMapper.selectByExample(example);
-        } else {
-            return new ArrayList<>();
-        }
-    }
+    List<DepotHead> getBillListByLinkNumberList(List<String> linkNumberList)throws Exception;
 
-    /**
-     * 根据原单号查询关联的单据列表
-     * @param linkNumber
-     * @return
-     * @throws Exception
-     */
-    public List<DepotHead> getBillListByLinkNumber(String linkNumber)throws Exception {
-        DepotHeadExample example = new DepotHeadExample();
-        example.createCriteria().andLinkNumberEqualTo(linkNumber).andSubTypeLike("退货").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        return depotHeadMapper.selectByExample(example);
-    }
+    List<DepotHead> getBillListByLinkNumber(String linkNumber)throws Exception;
 
     /**
      * 新增单据主表及单据子表信息
-     * @param beanJson
-     * @param rows
-     * @param request
-     * @throws Exception
+     * @param beanJson 主表信息
+     * @param rows  子表信息
      */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void addDepotHeadAndDetail(String beanJson, String rows,
-                                      HttpServletRequest request) throws Exception {
-        /**处理单据主表数据*/
-        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
-        //校验单号是否重复
-        if(checkIsBillNumberExist(0L, depotHead.getNumber())>0) {
-            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_CODE,
-                    String.format(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_MSG));
-        }
-        //校验是否同时录入关联请购单号和关联订单号
-        if(StringUtil.isNotEmpty(depotHead.getLinkNumber()) && StringUtil.isNotEmpty(depotHead.getLinkApply())) {
-            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_CODE,
-                    String.format(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_MSG));
-        }
-        String subType = depotHead.getSubType();
-        //结算账户校验
-        if("采购".equals(subType) || "采购退货".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)) {
-            if (StringUtil.isEmpty(depotHead.getAccountIdList()) && depotHead.getAccountId() == null) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG));
-            }
-        }
-        //判断用户是否已经登录过,登录过不再处理
-        User userInfo=userService.getCurrentUser();
-        depotHead.setCreator(userInfo==null?null:userInfo.getId());
-        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
-        if(StringUtil.isEmpty(depotHead.getStatus())) {
-            depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
-        }
-        depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
-        depotHead.setPayType(depotHead.getPayType()==null?"现付":depotHead.getPayType());
-        if(StringUtil.isNotEmpty(depotHead.getAccountIdList())){
-            depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
-        }
-        if(StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
-            //校验多账户的结算金额
-            String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
-            BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
-            BigDecimal manyAccountSum = sum.abs();
-            if(manyAccountSum.compareTo(depotHead.getChangeAmount().abs())!=0) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG));
-            }
-            depotHead.setAccountMoneyList(accountMoneyList);
-        }
-        //校验累计扣除订金是否超出订单中的金额
-        if(depotHead.getDeposit()!=null && StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
-            BigDecimal finishDeposit = depotHeadMapperEx.getFinishDepositByNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber());
-            //订单中的订金金额
-            BigDecimal changeAmount = getDepotHead(depotHead.getLinkNumber()).getChangeAmount();
-            if(changeAmount!=null) {
-                BigDecimal preDeposit = changeAmount.abs();
-                if(depotHead.getDeposit().add(finishDeposit).compareTo(preDeposit)>0) {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG));
-                }
-            }
-        }
-        //校验附件的数量
-        if(StringUtil.isNotEmpty(depotHead.getFileName())) {
-            String[] fileArr = depotHead.getFileName().split(",");
-            if(fileArr.length>4) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_MSG, 4));
-            }
-        }
-        depotHeadMapper.insertSelective(depotHead);
-        /**入库和出库处理预付款信息*/
-        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
-            if(depotHead.getOrganId()!=null) {
-                BigDecimal currentAdvanceIn = supplierService.getSupplier(depotHead.getOrganId()).getAdvanceIn();
-                if(currentAdvanceIn.compareTo(depotHead.getTotalPrice())>=0) {
-                    //更新会员的预付款
-                    supplierService.updateAdvanceIn(depotHead.getOrganId());
-                } else {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG));
-                }
-            }
-        }
-        //根据单据编号查询单据id
-        DepotHeadExample dhExample = new DepotHeadExample();
-        dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
-        if(list!=null) {
-            Long headId = list.get(0).getId();
-            /**入库和出库处理单据子表信息*/
-            depotItemService.saveDetials(rows,headId, "add",request);
-        }
-        logService.insertLog("单据",
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(depotHead.getNumber()).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-    }
+    void addDepotHeadAndDetail(String beanJson, String rows,
+                               HttpServletRequest request) throws Exception;
 
-    /**
-     * 更新单据主表及单据子表信息
-     * @param beanJson
-     * @param rows
-     * @param request
-     * @throws Exception
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void updateDepotHeadAndDetail(String beanJson, String rows,HttpServletRequest request)throws Exception {
-        /**更新单据主表信息*/
-        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
-        //校验单号是否重复
-        if(checkIsBillNumberExist(depotHead.getId(), depotHead.getNumber())>0) {
-            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_CODE,
-                    String.format(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_MSG));
-        }
-        //校验是否同时录入关联请购单号和关联订单号
-        if(StringUtil.isNotEmpty(depotHead.getLinkNumber()) && StringUtil.isNotEmpty(depotHead.getLinkApply())) {
-            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_CODE,
-                    String.format(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_MSG));
-        }
-        //校验单据状态,如果不是未审核则提示
-        if(!"0".equals(getDepotHead(depotHead.getId()).getStatus())) {
-            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_CANNOT_EDIT_CODE,
-                    String.format(ExceptionConstants.DEPOT_HEAD_BILL_CANNOT_EDIT_MSG));
-        }
-        //获取之前的会员id
-        Long preOrganId = getDepotHead(depotHead.getId()).getOrganId();
-        String subType = depotHead.getSubType();
-        //结算账户校验
-        if("采购".equals(subType) || "采购退货".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)) {
-            if (StringUtil.isEmpty(depotHead.getAccountIdList()) && depotHead.getAccountId() == null) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG));
-            }
-        }
-        if(StringUtil.isNotEmpty(depotHead.getAccountIdList())){
-            depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
-        }
-        if(StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
-            //校验多账户的结算金额
-            String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
-            BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
-            BigDecimal manyAccountSum = sum.abs();
-            if(manyAccountSum.compareTo(depotHead.getChangeAmount().abs())!=0) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG));
-            }
-            depotHead.setAccountMoneyList(accountMoneyList);
-        }
-        //校验累计扣除订金是否超出订单中的金额
-        if(depotHead.getDeposit()!=null && StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
-            BigDecimal finishDeposit = depotHeadMapperEx.getFinishDepositByNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber());
-            //订单中的订金金额
-            BigDecimal changeAmount = getDepotHead(depotHead.getLinkNumber()).getChangeAmount();
-            if(changeAmount!=null) {
-                BigDecimal preDeposit = changeAmount.abs();
-                if(depotHead.getDeposit().add(finishDeposit).compareTo(preDeposit)>0) {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG));
-                }
-            }
-        }
-        //校验附件的数量
-        if(StringUtil.isNotEmpty(depotHead.getFileName())) {
-            String[] fileArr = depotHead.getFileName().split(",");
-            if(fileArr.length>4) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_MSG, 4));
-            }
-        }
-        depotHeadMapper.updateByPrimaryKeySelective(depotHead);
-        //如果存在多账户结算需要将原账户的id置空
-        if(StringUtil.isNotEmpty(depotHead.getAccountIdList())) {
-            depotHeadMapperEx.setAccountIdToNull(depotHead.getId());
-        }
-        /**入库和出库处理预付款信息*/
-        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
-            if(depotHead.getOrganId()!=null){
-                BigDecimal currentAdvanceIn = supplierService.getSupplier(depotHead.getOrganId()).getAdvanceIn();
-                if(currentAdvanceIn.compareTo(depotHead.getTotalPrice())>=0) {
-                    //更新会员的预付款
-                    supplierService.updateAdvanceIn(depotHead.getOrganId());
-                    if(null != preOrganId && !preOrganId.equals(depotHead.getOrganId())) {
-                        //更新之前会员的预付款
-                        supplierService.updateAdvanceIn(preOrganId);
-                    }
-                } else {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG));
-                }
-            }
-        }
-        /**入库和出库处理单据子表信息*/
-        depotItemService.saveDetials(rows,depotHead.getId(), "update",request);
-        logService.insertLog("单据",
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(depotHead.getNumber()).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-    }
-
-    public Map<String, Object> getBuyAndSaleStatistics(String today, String monthFirstDay, String yesterdayBegin, String yesterdayEnd,
-                                                       String yearBegin, String yearEnd, HttpServletRequest request) throws Exception {
-        Long userId = userService.getUserId(request);
-        String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
-        Boolean forceFlag = systemConfigService.getForceApprovalFlag();
-        String[] creatorArray = getCreatorArray();
-        List<InOutPriceVo> inOutPriceVoList = depotHeadMapperEx.getBuyAndSaleStatisticsList(yearBegin, yearEnd, creatorArray, forceFlag);
-
-        String[] periods = {"today", "month", "yesterday", "year"};
-        String[] types = {"Buy", "BuyBack", "Sale", "SaleBack", "RetailSale", "RetailSaleBack"};
-
-        Map<String, BigDecimal> statistics = new HashMap<>();
+    void updateDepotHeadAndDetail(String beanJson, String rows, HttpServletRequest request)throws Exception;
 
-        // 初始化 statistics Map
-        for (String period : periods) {
-            for (String type : types) {
-                statistics.put(period + type, BigDecimal.ZERO);
-            }
-        }
+    Map<String, Object> getBuyAndSaleStatistics(String today, String monthFirstDay, String yesterdayBegin, String yesterdayEnd,
+                                                String yearBegin, String yearEnd, HttpServletRequest request) throws Exception;
 
-        Date todayDate = Tools.strToDate(today);
-        Date monthFirstDate = Tools.strToDate(monthFirstDay);
-        Date yesterdayStartDate = Tools.strToDate(yesterdayBegin);
-        Date yesterdayEndDate = Tools.strToDate(yesterdayEnd);
-        Date yearStartDate = Tools.strToDate(yearBegin);
-        Date yearEndDate = Tools.strToDate(yearEnd);
+    DepotHead getDepotHead(String number)throws Exception;
 
-        for (InOutPriceVo item : inOutPriceVoList) {
-            Date operTime = item.getOperTime();
-            BigDecimal discountLastMoney = item.getDiscountLastMoney();
-            BigDecimal totalPriceAbs = item.getTotalPrice().abs();
+    List<DepotHeadVo4List> debtList(Long organId, String materialParam, String number, String beginTime, String endTime,
+                                    String status, Integer offset, Integer rows);
 
-            if (isWithinRange(operTime, todayDate, Tools.strToDate(getNow3()))) {
-                updateStatistics(statistics, item, "today", discountLastMoney, totalPriceAbs);
-            }
+    int debtListCount(Long organId, String materialParam, String number, String beginTime, String endTime,
+                      String status);
 
-            if (isWithinRange(operTime, monthFirstDate, Tools.strToDate(getNow3()))) {
-                updateStatistics(statistics, item, "month", discountLastMoney, totalPriceAbs);
-            }
+    void debtExport(Long organId, String materialParam, String number, String type, String subType,
+                    String beginTime, String endTime, String status, String mpList,
+                    HttpServletRequest request, HttpServletResponse response);
 
-            if (isWithinRange(operTime, yesterdayStartDate, yesterdayEndDate)) {
-                updateStatistics(statistics, item, "yesterday", discountLastMoney, totalPriceAbs);
-            }
+    List<DepotHeadVo4List> parseDebtBillList(List<DepotHeadVo4List> list) throws Exception;
 
-            if (isWithinRange(operTime, yearStartDate, yearEndDate)) {
-                updateStatistics(statistics, item, "year", discountLastMoney, totalPriceAbs);
-            }
-        }
+    String getBillCategory(String subType);
 
-        Map<String, Object> result = new HashMap<>();
-        for (String period : periods) {
-            result.put(period + "Buy", roleService.parseHomePriceByLimit(statistics.get(period + "Buy").subtract(statistics.get(period + "BuyBack")), "buy", priceLimit, "***", request));
-            result.put(period + "Sale", roleService.parseHomePriceByLimit(statistics.get(period + "Sale").subtract(statistics.get(period + "SaleBack")), "sale", priceLimit, "***", request));
-            result.put(period + "RetailSale", roleService.parseHomePriceByLimit(statistics.get(period + "RetailSale").subtract(statistics.get(period + "RetailSaleBack")), "retail", priceLimit, "***", request));
-        }
+    List<DepotHeadVo4List> waitBillList(String number, String materialParam, String type, String subType,
+                                        String beginTime, String endTime, String status, int offset, int rows);
 
-        return result;
-    }
+    Long waitBillCount(String number, String materialParam, String type, String subType,
+                       String beginTime, String endTime, String status);
 
-    private boolean isWithinRange(Date operTime, Date startDate, Date endDate) {
-        return operTime.compareTo(startDate) >= 0 && operTime.compareTo(endDate) <= 0;
-    }
-
-    private void updateStatistics(Map<String, BigDecimal> statistics, InOutPriceVo item, String period, BigDecimal discountLastMoney, BigDecimal totalPriceAbs) {
-        switch (item.getType()) {
-            case "入库":
-                switch (item.getSubType()) {
-                    case "采购":
-                        statistics.put(period + "Buy", statistics.get(period + "Buy").add(discountLastMoney));
-                        break;
-                    case "销售退货":
-                        statistics.put(period + "SaleBack", statistics.get(period + "SaleBack").add(discountLastMoney));
-                        break;
-                    case "零售退货":
-                        statistics.put(period + "RetailSaleBack", statistics.get(period + "RetailSaleBack").add(totalPriceAbs));
-                        break;
-                }
-                break;
-            case "出库":
-                switch (item.getSubType()) {
-                    case "采购退货":
-                        statistics.put(period + "BuyBack", statistics.get(period + "BuyBack").add(discountLastMoney));
-                        break;
-                    case "销售":
-                        statistics.put(period + "Sale", statistics.get(period + "Sale").add(discountLastMoney));
-                        break;
-                    case "零售":
-                        statistics.put(period + "RetailSale", statistics.get(period + "RetailSale").add(totalPriceAbs));
-                        break;
-                }
-                break;
-        }
-    }
-
-
-    public DepotHead getDepotHead(String number)throws Exception {
-        DepotHead depotHead = new DepotHead();
-        try{
-            DepotHeadExample example = new DepotHeadExample();
-            example.createCriteria().andNumberEqualTo(number).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            List<DepotHead> list = depotHeadMapper.selectByExample(example);
-            if(null!=list && list.size()>0) {
-                depotHead = list.get(0);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return depotHead;
-    }
-
-    public List<DepotHeadVo4List> debtList(Long organId, String materialParam, String number, String beginTime, String endTime,
-                                           String status, Integer offset, Integer rows) {
-        List<DepotHeadVo4List> resList = new ArrayList<>();
-        try{
-            String depotIds = depotService.findDepotStrByCurrentUser();
-            String [] depotArray=depotIds.split(",");
-            String [] creatorArray = getCreatorArray();
-            beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
-            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
-            List<DepotHeadVo4List> list=depotHeadMapperEx.debtList(organId, creatorArray, status, number,
-                    beginTime, endTime, materialParam, depotArray, offset, rows);
-            if (null != list) {
-                resList = parseDebtBillList(list);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return resList;
-    }
-
-    public int debtListCount(Long organId, String materialParam, String number, String beginTime, String endTime,
-                             String status) {
-        int total = 0;
-        try {
-            String depotIds = depotService.findDepotStrByCurrentUser();
-            String[] depotArray = depotIds.split(",");
-            String[] creatorArray = getCreatorArray();
-            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
-            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
-            total = depotHeadMapperEx.debtListCount(organId, creatorArray, status, number,
-                    beginTime, endTime, materialParam, depotArray);
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return total;
-    }
-
-    public void debtExport(Long organId, String materialParam, String number, String type, String subType,
-                           String beginTime, String endTime, String status, String mpList,
-                           HttpServletRequest request, HttpServletResponse response) {
-        try {
-            Long userId = userService.getUserId(request);
-            String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
-            String billCategory = getBillCategory(subType);
-            String depotIds = depotService.findDepotStrByCurrentUser();
-            String[] depotArray = depotIds.split(",");
-            String[] creatorArray = getCreatorArray();
-            status = StringUtil.isNotEmpty(status) ? status : null;
-            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
-            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
-            List<DepotHeadVo4List> dhList = new ArrayList<>();
-            List<DepotHeadVo4List> list = depotHeadMapperEx.debtList(organId, creatorArray, status, number,
-                    beginTime, endTime, materialParam, depotArray, null, null);
-            if (null != list) {
-                dhList = parseDebtBillList(list);
-            }
-            //生成Excel文件
-            String fileName = "单据信息";
-            File file = new File("/opt/"+ fileName);
-            WritableWorkbook wtwb = Workbook.createWorkbook(file);
-            String oneTip = "";
-            String sheetOneStr = "";
-            if("采购".equals(subType)) {
-                oneTip = "供应商对账列表";
-                sheetOneStr = "供应商,单据编号,关联单据,商品信息,单据日期,操作员,单据金额,本单欠款,已付欠款,待付欠款,备注";
-            } else if("出库".equals(type) && "销售".equals(subType)) {
-                oneTip = "客户对账列表";
-                sheetOneStr = "客户,单据编号,关联单据,商品信息,单据日期,操作员,单据金额,本单欠款,已收欠款,待收欠款,备注";
-            }
-            if(StringUtil.isNotEmpty(beginTime) && StringUtil.isNotEmpty(endTime)) {
-                oneTip = oneTip + "(" + beginTime + "至" + endTime + ")";
-            }
-            List<String> sheetOneList = StringUtil.strToStringList(sheetOneStr);
-            String[] sheetOneArr = StringUtil.listToStringArray(sheetOneList);
-            List<Long> idList = new ArrayList<>();
-            List<String[]> billList = new ArrayList<>();
-            Map<Long, BillListCacheVo> billListCacheVoMap = new HashMap<>();
-            for (DepotHeadVo4List dh : dhList) {
-                idList.add(dh.getId());
-                BillListCacheVo billListCacheVo = new BillListCacheVo();
-                billListCacheVo.setNumber(dh.getNumber());
-                billListCacheVo.setOrganName(dh.getOrganName());
-                billListCacheVo.setOperTimeStr(getCenternTime(dh.getOperTime()));
-                billListCacheVoMap.put(dh.getId(), billListCacheVo);
-                String[] objs = new String[sheetOneArr.length];
-                objs[0] = dh.getOrganName();
-                objs[1] = dh.getNumber();
-                objs[2] = dh.getLinkNumber();
-                objs[3] = dh.getMaterialsList();
-                objs[4] = dh.getOperTimeStr();
-                objs[5] = dh.getUserName();
-                BigDecimal discountLastMoney = dh.getDiscountLastMoney() == null ? BigDecimal.ZERO : dh.getDiscountLastMoney();
-                BigDecimal otherMoney = dh.getOtherMoney() == null ? BigDecimal.ZERO : dh.getOtherMoney();
-                BigDecimal deposit = dh.getDeposit() == null ? BigDecimal.ZERO : dh.getDeposit();
-                objs[6] = parseDecimalToStr(discountLastMoney.add(otherMoney).subtract(deposit), 2);
-                objs[7] = parseDecimalToStr(dh.getNeedDebt(), 2);
-                objs[8] = parseDecimalToStr(dh.getFinishDebt(), 2);
-                objs[9] = parseDecimalToStr(dh.getDebt(), 2);
-                objs[10] = dh.getRemark();
-                billList.add(objs);
-            }
-            ExcelUtils.exportObjectsManySheet(wtwb, oneTip, sheetOneArr, "单据列表", 0, billList);
-            //导出明细数据
-            if(idList.size()>0) {
-                List<DepotItemVo4WithInfoEx> dataList = depotItemMapperEx.getBillDetailListByIds(idList);
-                String[] mpArr = mpList.split(",");
-                String twoTip = "";
-                String sheetTwoStr = "";
-                if ("采购".equals(subType)) {
-                    twoTip = "供应商单据明细";
-                    sheetTwoStr = "供应商,单据编号,单据日期,仓库名称,条码,名称,规格,型号,颜色,品牌,制造商,扩展信息,单位,序列号,批号,有效期,多属性,数量,单价,金额,税率(%),税额,价税合计,重量,备注";
-                } else if ("销售".equals(subType)) {
-                    twoTip = "客户单据明细";
-                    sheetTwoStr = "客户,单据编号,单据日期,仓库名称,条码,名称,规格,型号,颜色,品牌,制造商,扩展信息,单位,序列号,批号,有效期,多属性,数量,单价,金额,税率(%),税额,价税合计,重量,备注";
-                }
-                if (StringUtil.isNotEmpty(beginTime) && StringUtil.isNotEmpty(endTime)) {
-                    twoTip = twoTip + "(" + beginTime + "至" + endTime + ")";
-                }
-                List<String> sheetTwoList = StringUtil.strToStringList(sheetTwoStr);
-                String[] sheetTwoArr = StringUtil.listToStringArray(sheetTwoList);
-                List<String[]> billDetail = new ArrayList<>();
-                for (DepotItemVo4WithInfoEx diEx : dataList) {
-                    String[] objs = new String[sheetTwoArr.length];
-                    BillListCacheVo billListCacheVo = billListCacheVoMap.get(diEx.getHeaderId());
-                    objs[0] = billListCacheVo != null ? billListCacheVo.getOrganName() : "";
-                    objs[1] = billListCacheVo != null ? billListCacheVo.getNumber() : "";
-                    objs[2] = billListCacheVo != null ? billListCacheVo.getOperTimeStr() : "";
-                    objs[3] = diEx.getDepotId() == null ? "" : diEx.getDepotName();
-                    objs[4] = diEx.getBarCode();
-                    objs[5] = diEx.getMName();
-                    objs[6] = diEx.getMStandard();
-                    objs[7] = diEx.getMModel();
-                    objs[8] = diEx.getMColor();
-                    objs[9] = diEx.getBrand();
-                    objs[10] = diEx.getMMfrs();
-                    objs[11] = depotItemService.getOtherInfo(mpArr, diEx);
-                    objs[12] = diEx.getMaterialUnit();
-                    objs[13] = diEx.getSnList();
-                    objs[14] = diEx.getBatchNumber();
-                    objs[15] = Tools.parseDateToStr(diEx.getExpirationDate());
-                    objs[16] = diEx.getSku();
-                    objs[17] = parseDecimalToStr(diEx.getOperNumber(), 2);
-                    objs[18] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getUnitPrice(), billCategory, priceLimit, request), 2);
-                    objs[19] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getAllPrice(), billCategory, priceLimit, request), 2);
-                    objs[20] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getTaxRate(), billCategory, priceLimit, request), 2);
-                    objs[21] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getTaxMoney(), billCategory, priceLimit, request), 2);
-                    objs[22] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getTaxLastMoney(), billCategory, priceLimit, request), 2);
-                    BigDecimal allWeight = diEx.getBasicNumber() == null || diEx.getWeight() == null ? BigDecimal.ZERO : diEx.getBasicNumber().multiply(diEx.getWeight());
-                    objs[23] = parseDecimalToStr(allWeight, 2);
-                    objs[24] = diEx.getRemark();
-                    billDetail.add(objs);
-                }
-                ExcelUtils.exportObjectsManySheet(wtwb, twoTip, sheetTwoArr, "单据明细", 1, billDetail);
-            }
-            wtwb.write();
-            wtwb.close();
-            ExcelUtils.downloadExcel(file, file.getName(), response);
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-    }
+    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
+    void batchAddDepotHeadAndDetail(String ids, HttpServletRequest request) throws Exception;
 
-    public List<DepotHeadVo4List> parseDebtBillList(List<DepotHeadVo4List> list) throws Exception {
-        List<Long> idList = new ArrayList<>();
-        List<DepotHeadVo4List> dhList = new ArrayList<>();
-        for (DepotHeadVo4List dh : list) {
-            idList.add(dh.getId());
-        }
-        //通过批量查询去构造map
-        Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
-        for (DepotHeadVo4List dh : list) {
-            if(dh.getChangeAmount() != null) {
-                dh.setChangeAmount(dh.getChangeAmount().abs());
-            }
-            if(dh.getTotalPrice() != null) {
-                dh.setTotalPrice(dh.getTotalPrice().abs());
-            }
-            if(dh.getDeposit() == null) {
-                dh.setDeposit(BigDecimal.ZERO);
-            }
-            if(dh.getOperTime() != null) {
-                dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
-            }
-            BigDecimal discountLastMoney = dh.getDiscountLastMoney()!=null?dh.getDiscountLastMoney():BigDecimal.ZERO;
-            BigDecimal otherMoney = dh.getOtherMoney()!=null?dh.getOtherMoney():BigDecimal.ZERO;
-            BigDecimal deposit = dh.getDeposit()!=null?dh.getDeposit():BigDecimal.ZERO;
-            BigDecimal changeAmount = dh.getChangeAmount()!=null?dh.getChangeAmount().abs():BigDecimal.ZERO;
-            //本单欠款(如果退货则为负数)
-            dh.setNeedDebt(discountLastMoney.add(otherMoney).subtract(deposit.add(changeAmount)));
-            if(BusinessConstants.SUB_TYPE_PURCHASE_RETURN.equals(dh.getSubType()) || BusinessConstants.SUB_TYPE_SALES_RETURN.equals(dh.getSubType())) {
-                dh.setNeedDebt(BigDecimal.ZERO.subtract(dh.getNeedDebt()));
-            }
-            BigDecimal needDebt = dh.getNeedDebt()!=null?dh.getNeedDebt():BigDecimal.ZERO;
-            BigDecimal finishDebt = accountItemService.getEachAmountByBillId(dh.getId());
-            finishDebt = finishDebt!=null?finishDebt:BigDecimal.ZERO;
-            //已收欠款
-            dh.setFinishDebt(finishDebt);
-            //待收欠款
-            dh.setDebt(needDebt.subtract(finishDebt));
-            //商品信息简述
-            if(materialsListMap!=null) {
-                dh.setMaterialsList(materialsListMap.get(dh.getId()));
-            }
-            dhList.add(dh);
-        }
-        return dhList;
-    }
 
-    public String getBillCategory(String subType) {
-        if(subType.equals("零售") || subType.equals("零售退货")) {
-            return "retail";
-        } else if(subType.equals("销售订单") || subType.equals("销售") || subType.equals("销售退货")) {
-            return "sale";
-        } else {
-            return "buy";
-        }
-    }
+    String syncOrderToXsdd(DepotHeadXsddRequestVO depotHead, List<DepotItemXsddRequestVO> depotItemList) throws Exception;
 
     /**
-     * 格式化金额样式
-     * @param decimal
-     * @param num
+     * 根据商品id查询最后一条商品订单
+     * @param mid 商品ID
      * @return
      */
-    private String parseDecimalToStr(BigDecimal decimal, Integer num) {
-        return decimal == null ? "" : decimal.setScale(num, BigDecimal.ROUND_HALF_UP).toString();
-    }
+    DepotHead getDepotLastByMaterialId(long mid);
 
-    private String parseStatusToStr(String status, String type) {
-        if(StringUtil.isNotEmpty(status)) {
-            if("purchase".equals(type)) {
-                switch (status) {
-                    case "2":
-                        return "完成采购";
-                    case "3":
-                        return "部分采购";
-                }
-            } else if("sale".equals(type)) {
-                switch (status) {
-                    case "2":
-                        return "完成销售";
-                    case "3":
-                        return "部分销售";
-                }
-            }
-            switch (status) {
-                case "0":
-                    return "未审核";
-                case "1":
-                    return "已审核";
-                case "9":
-                    return "审核中";
-            }
-        }
-        return "";
-    }
-
-    public List<DepotHeadVo4List> waitBillList(String number, String materialParam, String type, String subType,
-                                               String beginTime, String endTime, String status, int offset, int rows) {
-        List<DepotHeadVo4List> resList = new ArrayList<>();
-        try{
-            String [] depotArray = getDepotArray("其它");
-            //给仓管可以看全部的单据(此时可以通过分配仓库去控制权限)
-            String [] creatorArray = null;
-            String [] subTypeArray = StringUtil.isNotEmpty(subType) ? subType.split(",") : null;
-            String [] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
-            Map<Long,String> accountMap = accountService.getAccountMap();
-            beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
-            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
-            List<DepotHeadVo4List> list = depotHeadMapperEx.waitBillList(type, subTypeArray, creatorArray, statusArray, number, beginTime, endTime,
-                    materialParam, depotArray, offset, rows);
-            if (null != list) {
-                List<Long> idList = new ArrayList<>();
-                for (DepotHeadVo4List dh : list) {
-                    idList.add(dh.getId());
-                }
-                //通过批量查询去构造map
-                Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
-                Map<Long,BigDecimal> materialCountListMap = getMaterialCountListMapByHeaderIdList(idList);
-                for (DepotHeadVo4List dh : list) {
-                    if(accountMap!=null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
-                        String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
-                        dh.setAccountName(accountStr);
-                    }
-                    if(dh.getOperTime() != null) {
-                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
-                    }
-                    //商品信息简述
-                    if(materialsListMap!=null) {
-                        dh.setMaterialsList(materialsListMap.get(dh.getId()));
-                    }
-                    //商品总数量
-                    if(materialCountListMap!=null) {
-                        dh.setMaterialCount(materialCountListMap.get(dh.getId()));
-                    }
-                    resList.add(dh);
-                }
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return resList;
-    }
-
-    public Long waitBillCount(String number, String materialParam, String type, String subType,
-                             String beginTime, String endTime, String status) {
-        Long result=null;
-        try{
-            String [] depotArray = getDepotArray("其它");
-            //给仓管可以看全部的单据(此时可以通过分配仓库去控制权限)
-            String [] creatorArray = null;
-            String [] subTypeArray = StringUtil.isNotEmpty(subType) ? subType.split(",") : null;
-            String [] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
-            beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
-            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
-            result=depotHeadMapperEx.waitBillCount(type, subTypeArray, creatorArray, statusArray, number, beginTime, endTime,
-                    materialParam, depotArray);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-
-    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void batchAddDepotHeadAndDetail(String ids, HttpServletRequest request) throws Exception {
-        List<DepotHead> dhList = getDepotHeadListByIds(ids);
-        StringBuilder sb = new StringBuilder();
-        User userInfo=userService.getCurrentUser();
-        for(DepotHead depotHead : dhList) {
-            String prefixNo = BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType())?"QTRK":"QTCK";
-            //关联单据单号
-            String oldNumber = depotHead.getNumber();
-            //校验单据最新状态不能进行批量操作
-            if("0".equals(depotHead.getStatus()) || "2".equals(depotHead.getStatus()) || "9".equals(depotHead.getStatus())) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_NEW_STATUS_FAILED_CODE,
-                        String.format(ExceptionConstants.DEPOT_ITEM_EXIST_NEW_STATUS_FAILED_MSG, oldNumber, depotHead.getType()));
-            }
-            //校验是否是部分入库或者部分出库
-            if("3".equals(depotHead.getStatus())) {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_PARTIALLY_STATUS_FAILED_CODE,
-                        String.format(ExceptionConstants.DEPOT_ITEM_EXIST_PARTIALLY_STATUS_FAILED_MSG, oldNumber, depotHead.getType()));
-            }
-            depotHead.setLinkNumber(oldNumber);
-            //给单号重新赋值
-            String number = prefixNo + sequenceService.buildOnlyNumber();
-            depotHead.setNumber(number);
-            depotHead.setDefaultNumber(number);
-            depotHead.setOperTime(new Date());
-            depotHead.setSubType(BusinessConstants.SUB_TYPE_OTHER);
-            depotHead.setChangeAmount(BigDecimal.ZERO);
-            depotHead.setTotalPrice(BigDecimal.ZERO);
-            depotHead.setDiscountLastMoney(BigDecimal.ZERO);
-            depotHead.setCreator(userInfo==null?null:userInfo.getId());
-            depotHead.setOrganId(null);
-            depotHead.setAccountId(null);
-            depotHead.setAccountIdList(null);
-            depotHead.setAccountMoneyList(null);
-            depotHead.setFileName(null);
-            depotHead.setSalesMan(null);
-            depotHead.setStatus("0");
-            depotHead.setTenantId(null);
-            //查询明细
-            List<DepotItemVo4WithInfoEx> itemList = depotItemService.getDetailList(depotHead.getId());
-            depotHead.setId(null);
-            JSONArray rowArr = new JSONArray();
-            for(DepotItemVo4WithInfoEx item: itemList) {
-                if("1".equals(item.getEnableSerialNumber())) {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_SERIAL_NUMBER_FAILED_CODE,
-                            String.format(ExceptionConstants.DEPOT_ITEM_EXIST_SERIAL_NUMBER_FAILED_MSG, oldNumber));
-                }
-                if("1".equals(item.getEnableBatchNumber())) {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_BATCH_NUMBER_FAILED_CODE,
-                            String.format(ExceptionConstants.DEPOT_ITEM_EXIST_BATCH_NUMBER_FAILED_MSG, oldNumber));
-                }
-                item.setUnitPrice(BigDecimal.ZERO);
-                item.setAllPrice(BigDecimal.ZERO);
-                item.setLinkId(item.getId());
-                item.setTenantId(null);
-                String itemStr = JSONObject.toJSONString(item);
-                JSONObject itemObj = JSONObject.parseObject(itemStr);
-                itemObj.put("unit", itemObj.getString("materialUnit"));
-                rowArr.add(itemObj.toJSONString());
-            }
-            String rows = rowArr.toJSONString();
-            //新增其它入库单或其它出库单
-            sb.append("[").append(depotHead.getNumber()).append("]");
-            depotHeadMapper.insertSelective(depotHead);
-            //根据单据编号查询单据id
-            DepotHeadExample dhExample = new DepotHeadExample();
-            dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
-            if(list!=null) {
-                Long headId = list.get(0).getId();
-                /**入库和出库处理单据子表信息*/
-                depotItemService.saveDetials(rows, headId, "add", request);
-            }
-        }
-        logService.insertLog("单据",
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_BATCH_ADD).append(sb).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-    }
+    /**
+     * pda订单提交
+     * @param pdaDepotHeadDTO
+     * @return
+     */
+    boolean pdaOrderSubmit(PDADepotHeadDTO pdaDepotHeadDTO) throws Exception;
 }

+ 96 - 1345
src/main/java/com/jsh/erp/service/DepotItemService.java

@@ -2,1432 +2,183 @@ package com.jsh.erp.service;
 
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.jsh.erp.constants.BusinessConstants;
-import com.jsh.erp.constants.ExceptionConstants;
+import com.baomidou.mybatisplus.extension.service.IService;
 import com.jsh.erp.datasource.entities.*;
-import com.jsh.erp.datasource.mappers.*;
+import com.jsh.erp.datasource.pda.vo.PDADepotItemVO;
+import com.jsh.erp.datasource.vo.DepotHeadXsddRequestVO;
 import com.jsh.erp.datasource.vo.DepotItemStockWarningCount;
-import com.jsh.erp.datasource.vo.DepotItemVo4Stock;
 import com.jsh.erp.datasource.vo.DepotItemVoBatchNumberList;
+import com.jsh.erp.datasource.vo.DepotItemXsddRequestVO;
 import com.jsh.erp.datasource.vo.InOutPriceVo;
-import com.jsh.erp.exception.BusinessRunTimeException;
-import com.jsh.erp.exception.JshException;
-import com.jsh.erp.utils.StringUtil;
-import com.jsh.erp.utils.Tools;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import java.math.BigDecimal;
-import java.util.*;
+import java.util.List;
+import java.util.Map;
 
-@Service
-public class DepotItemService {
-    private Logger logger = LoggerFactory.getLogger(DepotItemService.class);
+public interface DepotItemService extends IService<DepotItem> {
 
-    private final static String TYPE = "入库";
-    private final static String SUM_TYPE = "number";
-    private final static String IN = "in";
-    private final static String OUT = "out";
+    /**
+     * pda根据订单信息查询商品列表
+     * @return
+     */
+    List<PDADepotItemVO> pdaList(Long id);
+
+    /**
+     * pda根据商品订单ID查询商品详情
+     * @param id 商品订单ID
+     * @return
+     */
+    PDADepotItemVO pdaDetail(Long id);
 
-    @Resource
-    private DepotItemMapper depotItemMapper;
-    @Resource
-    private DepotItemMapperEx depotItemMapperEx;
-    @Resource
-    private MaterialService materialService;
-    @Resource
-    private MaterialExtendService materialExtendService;
-    @Resource
-    private SerialNumberMapperEx serialNumberMapperEx;
-    @Resource
-    private DepotHeadService depotHeadService;
-    @Resource
-    private DepotHeadMapper depotHeadMapper;
-    @Resource
-    private SerialNumberService serialNumberService;
-    @Resource
-    private UserService userService;
-    @Resource
-    private SystemConfigService systemConfigService;
-    @Resource
-    private DepotService depotService;
-    @Resource
-    private UnitService unitService;
-    @Resource
-    private MaterialCurrentStockMapper materialCurrentStockMapper;
-    @Resource
-    private MaterialCurrentStockMapperEx materialCurrentStockMapperEx;
-    @Resource
-    private LogService logService;
+    /**
+     * 商品库存详情列表
+     * @param materialId 商品ID
+     * @return
+     */
+    List<PDADepotItemVO> materialDepotDetail(String type, Long materialId);
 
-    public DepotItem getDepotItem(long id)throws Exception {
-        DepotItem result=null;
-        try{
-            result=depotItemMapper.selectByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    DepotItem getDepotItem(long id)throws Exception;
 
-    public List<DepotItem> getDepotItem()throws Exception {
-        DepotItemExample example = new DepotItemExample();
-        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<DepotItem> list=null;
-        try{
-            list=depotItemMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItem> getDepotItem()throws Exception;
 
-    public List<DepotItem> select(String name, Integer type, String remark, int offset, int rows)throws Exception {
-        List<DepotItem> list=null;
-        try{
-            list=depotItemMapperEx.selectByConditionDepotItem(name, type, remark, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItem> select(String name, Integer type, String remark, int offset, int rows)throws Exception;
 
-    public Long countDepotItem(String name, Integer type, String remark) throws Exception{
-        Long result =null;
-        try{
-            result=depotItemMapperEx.countsByDepotItem(name, type, remark);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    Long countDepotItem(String name, Integer type, String remark) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertDepotItem(JSONObject obj, HttpServletRequest request)throws Exception {
-        DepotItem depotItem = JSONObject.parseObject(obj.toJSONString(), DepotItem.class);
-        int result =0;
-        try{
-            result=depotItemMapper.insertSelective(depotItem);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int insertDepotItem(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateDepotItem(JSONObject obj, HttpServletRequest request)throws Exception {
-        DepotItem depotItem = JSONObject.parseObject(obj.toJSONString(), DepotItem.class);
-        int result =0;
-        try{
-            result=depotItemMapper.updateByPrimaryKeySelective(depotItem);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int updateDepotItem(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int deleteDepotItem(Long id, HttpServletRequest request)throws Exception {
-        int result =0;
-        try{
-            result=depotItemMapper.deleteByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int deleteDepotItem(Long id, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteDepotItem(String ids, HttpServletRequest request)throws Exception {
-        List<Long> idList = StringUtil.strToLongList(ids);
-        DepotItemExample example = new DepotItemExample();
-        example.createCriteria().andIdIn(idList);
-        int result =0;
-        try{
-            result=depotItemMapper.deleteByExample(example);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int batchDeleteDepotItem(String ids, HttpServletRequest request)throws Exception;
 
-    public int checkIsNameExist(Long id, String name)throws Exception {
-        DepotItemExample example = new DepotItemExample();
-        example.createCriteria().andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<DepotItem> list =null;
-        try{
-            list=depotItemMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list==null?0:list.size();
-    }
+    int checkIsNameExist(Long id, String name)throws Exception;
 
-    public List<DepotItemVo4DetailByTypeAndMId> findDetailByDepotIdsAndMaterialIdList(String depotIds, Boolean forceFlag, Boolean inOutManageFlag, String sku, String batchNumber,
-                                                                                      String number, String beginTime, String endTime, Long mId, Integer offset, Integer rows)throws Exception {
-        Long depotId = null;
-        if(StringUtil.isNotEmpty(depotIds)) {
-            depotId = Long.parseLong(depotIds);
-        }
-        List<Long> depotList = depotService.parseDepotList(depotId);
-        Long[] depotIdArray = StringUtil.listToLongArray(depotList);
-        List<DepotItemVo4DetailByTypeAndMId> list =null;
-        try{
-            list = depotItemMapperEx.findDetailByDepotIdsAndMaterialIdList(depotIdArray, forceFlag, inOutManageFlag, sku, batchNumber, number, beginTime, endTime, mId, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItemVo4DetailByTypeAndMId> findDetailByDepotIdsAndMaterialIdList(String depotIds, Boolean forceFlag, Boolean inOutManageFlag, String sku, String batchNumber,
+                                                                               String number, String beginTime, String endTime, Long mId, Integer offset, Integer rows)throws Exception;
 
-    public Long findDetailByDepotIdsAndMaterialIdCount(String depotIds, Boolean forceFlag, Boolean inOutManageFlag, String sku, String batchNumber,
-                                                       String number, String beginTime, String endTime, Long mId)throws Exception {
-        Long depotId = null;
-        if(StringUtil.isNotEmpty(depotIds)) {
-            depotId = Long.parseLong(depotIds);
-        }
-        List<Long> depotList = depotService.parseDepotList(depotId);
-        Long[] depotIdArray = StringUtil.listToLongArray(depotList);
-        Long result =null;
-        try{
-            result = depotItemMapperEx.findDetailByDepotIdsAndMaterialIdCount(depotIdArray, forceFlag, inOutManageFlag, sku, batchNumber, number, beginTime, endTime, mId);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    Long findDetailByDepotIdsAndMaterialIdCount(String depotIds, Boolean forceFlag, Boolean inOutManageFlag, String sku, String batchNumber,
+                                                String number, String beginTime, String endTime, Long mId)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertDepotItemWithObj(DepotItem depotItem)throws Exception {
-        int result =0;
-        try{
-            result = depotItemMapper.insertSelective(depotItem);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int insertDepotItemWithObj(DepotItem depotItem)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateDepotItemWithObj(DepotItem depotItem)throws Exception {
-        int result =0;
-        try{
-            result = depotItemMapper.updateByPrimaryKeySelective(depotItem);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int updateDepotItemWithObj(DepotItem depotItem)throws Exception;
 
-    public List<DepotItem> getListByHeaderId(Long headerId)throws Exception {
-        List<DepotItem> list =null;
-        try{
-            DepotItemExample example = new DepotItemExample();
-            example.createCriteria().andHeaderIdEqualTo(headerId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            list = depotItemMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItem> getListByHeaderId(Long headerId)throws Exception;
 
-    /**
-     * 查询当前单据中指定商品的明细信息
-     * @param headerId
-     * @param meId
-     * @return
-     * @throws Exception
-     */
-    public DepotItem getItemByHeaderIdAndMaterial(Long headerId, Long meId)throws Exception {
-        DepotItem depotItem = new DepotItem();
-        try{
-            DepotItemExample example = new DepotItemExample();
-            example.createCriteria().andHeaderIdEqualTo(headerId).andMaterialExtendIdEqualTo(meId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            List<DepotItem> list = depotItemMapper.selectByExample(example);
-            if(list!=null && list.size()>0) {
-                depotItem = list.get(0);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return depotItem;
-    }
+    DepotItem getItemByHeaderIdAndMaterial(Long headerId, Long meId)throws Exception;
 
-    /**
-     * 查询被关联订单中指定商品的明细信息
-     * @param linkStr
-     * @param meId
-     * @return
-     * @throws Exception
-     */
-    public DepotItem getPreItemByHeaderIdAndMaterial(String linkStr, Long meId, Long linkId)throws Exception {
-        DepotItem depotItem = new DepotItem();
-        try{
-            DepotHead depotHead = depotHeadService.getDepotHead(linkStr);
-            if(null!=depotHead && null!=depotHead.getId()) {
-                DepotItemExample example = new DepotItemExample();
-                example.createCriteria().andHeaderIdEqualTo(depotHead.getId()).andMaterialExtendIdEqualTo(meId).andIdEqualTo(linkId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-                List<DepotItem> list = depotItemMapper.selectByExample(example);
-                if(list!=null && list.size()>0) {
-                    depotItem = list.get(0);
-                }
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return depotItem;
-    }
+    DepotItem getPreItemByHeaderIdAndMaterial(String linkStr, Long meId, Long linkId)throws Exception;
 
-    public List<DepotItemVo4WithInfoEx> getDetailList(Long headerId)throws Exception {
-        List<DepotItemVo4WithInfoEx> list =null;
-        try{
-            list = depotItemMapperEx.getDetailList(headerId);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItemVo4WithInfoEx> getDetailList(Long headerId)throws Exception;
 
-    public List<DepotItemVo4WithInfoEx> getInOutStock(String materialParam, List<Long> categoryIdList, String endTime, Integer offset, Integer rows)throws Exception {
-        List<DepotItemVo4WithInfoEx> list =null;
-        try{
-            list = depotItemMapperEx.getInOutStock(materialParam, categoryIdList, endTime, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItemVo4WithInfoEx> getInOutStock(String materialParam, List<Long> categoryIdList, String endTime, Integer offset, Integer rows)throws Exception;
 
-    public int getInOutStockCount(String materialParam, List<Long> categoryIdList, String endTime)throws Exception {
-        int result=0;
-        try{
-            result = depotItemMapperEx.getInOutStockCount(materialParam, categoryIdList, endTime);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int getInOutStockCount(String materialParam, List<Long> categoryIdList, String endTime)throws Exception;
 
-    public List<DepotItemVo4WithInfoEx> getListWithBuyOrSale(String materialParam, String billType,
-                                                             String beginTime, String endTime, String[] creatorArray, Long organId, String[] organArray, List<Long> categoryList, List<Long> depotList, Boolean forceFlag, Integer offset, Integer rows)throws Exception {
-        List<DepotItemVo4WithInfoEx> list =null;
-        try{
-            list = depotItemMapperEx.getListWithBuyOrSale(materialParam, billType, beginTime, endTime, creatorArray, organId, organArray, categoryList, depotList, forceFlag, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItemVo4WithInfoEx> getListWithBuyOrSale(String materialParam, String billType,
+                                                      String beginTime, String endTime, String[] creatorArray, Long organId, String[] organArray, List<Long> categoryList, List<Long> depotList, Boolean forceFlag, Integer offset, Integer rows)throws Exception;
 
-    public int getListWithBuyOrSaleCount(String materialParam, String billType,
-                                         String beginTime, String endTime, String[] creatorArray, Long organId, String[] organArray, List<Long> categoryList, List<Long> depotList, Boolean forceFlag)throws Exception {
-        int result=0;
-        try{
-            result = depotItemMapperEx.getListWithBuyOrSaleCount(materialParam, billType, beginTime, endTime, creatorArray, organId, organArray, categoryList, depotList, forceFlag);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int getListWithBuyOrSaleCount(String materialParam, String billType,
+                                  String beginTime, String endTime, String[] creatorArray, Long organId, String[] organArray, List<Long> categoryList, List<Long> depotList, Boolean forceFlag)throws Exception;
 
-    public BigDecimal buyOrSale(String type, String subType, Long MId, String beginTime, String endTime,
-                                String[] creatorArray, Long organId, String [] organArray, List<Long> depotList, Boolean forceFlag, String sumType) throws Exception{
-        BigDecimal result= BigDecimal.ZERO;
-        try{
-            if (SUM_TYPE.equals(sumType)) {
-                result= depotItemMapperEx.buyOrSaleNumber(type, subType, MId, beginTime, endTime, creatorArray, organId, organArray, depotList, forceFlag, sumType);
-            } else {
-                result= depotItemMapperEx.buyOrSalePrice(type, subType, MId, beginTime, endTime, creatorArray, organId, organArray, depotList, forceFlag, sumType);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    BigDecimal buyOrSale(String type, String subType, Long MId, String beginTime, String endTime,
+                         String[] creatorArray, Long organId, String[] organArray, List<Long> depotList, Boolean forceFlag, String sumType) throws Exception;
 
-    public BigDecimal buyOrSalePriceTotal(String type, String subType, String materialParam, String beginTime, String endTime,
-                                String[] creatorArray, Long organId, String [] organArray, List<Long> categoryList, List<Long> depotList, Boolean forceFlag) throws Exception{
-        BigDecimal result= BigDecimal.ZERO;
-        try{
-            result= depotItemMapperEx.buyOrSalePriceTotal(type, subType, materialParam, beginTime, endTime, creatorArray, organId, organArray, categoryList, depotList, forceFlag);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
+    BigDecimal buyOrSalePriceTotal(String type, String subType, String materialParam, String beginTime, String endTime,
+                                   String[] creatorArray, Long organId, String[] organArray, List<Long> categoryList, List<Long> depotList, Boolean forceFlag) throws Exception;
 
-    }
+    List<InOutPriceVo> inOrOutPriceList(String beginTime, String endTime) throws Exception;
 
     /**
-     * 统计采购、销售、零售的总金额列表
-     * @param beginTime
-     * @param endTime
-     * @return
-     * @throws Exception
+     * 保存单据子表信息
+     * @param rows 子表信息
+     * @param headerId  主表id
+     * @param actionType    操作类型
      */
-    public List<InOutPriceVo> inOrOutPriceList(String beginTime, String endTime) throws Exception{
-        List<InOutPriceVo> result = new ArrayList<>();
-        try{
-            String [] creatorArray = depotHeadService.getCreatorArray();
-            Boolean forceFlag = systemConfigService.getForceApprovalFlag();
-            result = depotItemMapperEx.inOrOutPriceList(beginTime, endTime, creatorArray, forceFlag);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
+    void saveDetials(String rows, Long headerId, String actionType, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void saveDetials(String rows, Long headerId, String actionType, HttpServletRequest request) throws Exception{
-        //查询单据主表信息
-        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(headerId);
-        //删除序列号和回收序列号
-        deleteOrCancelSerialNumber(actionType, depotHead, headerId);
-        //删除单据的明细
-        deleteDepotItemHeadId(headerId);
-        JSONArray rowArr = JSONArray.parseArray(rows);
-        if (null != rowArr && rowArr.size()>0) {
-            //针对组装单、拆卸单校验是否存在组合件和普通子件
-            checkAssembleWithMaterialType(rowArr, depotHead.getSubType());
-            for (int i = 0; i < rowArr.size(); i++) {
-                DepotItem depotItem = new DepotItem();
-                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
-                depotItem.setHeaderId(headerId);
-                String barCode = rowObj.getString("barCode");
-                MaterialExtend materialExtend = materialExtendService.getInfoByBarCode(barCode);
-                if(materialExtend == null) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_BARCODE_IS_NOT_EXIST_CODE,
-                            String.format(ExceptionConstants.MATERIAL_BARCODE_IS_NOT_EXIST_MSG, barCode));
-                }
-                depotItem.setMaterialId(materialExtend.getMaterialId());
-                depotItem.setMaterialExtendId(materialExtend.getId());
-                depotItem.setMaterialUnit(rowObj.getString("unit"));
-                Material material= materialService.getMaterial(depotItem.getMaterialId());
-                if (BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber()) ||
-                        BusinessConstants.ENABLE_BATCH_NUMBER_ENABLED.equals(material.getEnableBatchNumber())) {
-                    //组装拆卸单不能选择批号或序列号商品
-                    if(BusinessConstants.SUB_TYPE_ASSEMBLE.equals(depotHead.getSubType()) ||
-                            BusinessConstants.SUB_TYPE_DISASSEMBLE.equals(depotHead.getSubType())) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_ASSEMBLE_SELECT_ERROR_CODE,
-                                String.format(ExceptionConstants.MATERIAL_ASSEMBLE_SELECT_ERROR_MSG, barCode));
-                    }
-                    //调拨单不能选择批号或序列号商品(该场景走出库和入库单)
-                    if(BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_TRANSFER_SELECT_ERROR_CODE,
-                                String.format(ExceptionConstants.MATERIAL_TRANSFER_SELECT_ERROR_MSG, barCode));
-                    }
-                    //盘点业务不能选择批号或序列号商品(该场景走出库和入库单)
-                    if(BusinessConstants.SUB_TYPE_CHECK_ENTER.equals(depotHead.getSubType())
-                       ||BusinessConstants.SUB_TYPE_REPLAY.equals(depotHead.getSubType())) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_CHECK_ERROR_CODE,
-                                String.format(ExceptionConstants.MATERIAL_STOCK_CHECK_ERROR_MSG, barCode));
-                    }
-                }
-                if (StringUtil.isExist(rowObj.get("snList"))) {
-                    depotItem.setSnList(rowObj.getString("snList"));
-                    if(StringUtil.isExist(rowObj.get("depotId"))) {
-                        String [] snArray = depotItem.getSnList().split(",");
-                        int operNum = rowObj.getInteger("operNumber");
-                        if(snArray.length == operNum) {
-                            Long depotId = rowObj.getLong("depotId");
-                            BigDecimal inPrice = BigDecimal.ZERO;
-                            if (StringUtil.isExist(rowObj.get("unitPrice"))) {
-                                inPrice = rowObj.getBigDecimal("unitPrice");
-                            }
-                            serialNumberService.addSerialNumberByBill(depotHead.getType(), depotHead.getSubType(),
-                                    depotHead.getNumber(), materialExtend.getMaterialId(), depotId, inPrice, depotItem.getSnList());
-                        } else {
-                            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_SN_NUMBERE_FAILED_CODE,
-                                    String.format(ExceptionConstants.DEPOT_HEAD_SN_NUMBERE_FAILED_MSG, barCode));
-                        }
-                    }
-                } else {
-                    //入库或出库
-                    if (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) ||
-                            BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())) {
-                        //序列号不能为空
-                        if (BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())) {
-                            //如果开启出入库管理,并且类型等于采购、采购退货、销售、销售退货,则跳过
-                            if(systemConfigService.getInOutManageFlag() &&
-                                    (BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_PURCHASE_RETURN.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_SALES_RETURN.equals(depotHead.getSubType()))) {
-                                //跳过
-                            } else {
-                                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_SERIAL_NUMBERE_EMPTY_CODE,
-                                        String.format(ExceptionConstants.MATERIAL_SERIAL_NUMBERE_EMPTY_MSG, barCode));
-                            }
-                        }
-                    }
-                }
-                if (StringUtil.isExist(rowObj.get("batchNumber"))) {
-                    depotItem.setBatchNumber(rowObj.getString("batchNumber"));
-                } else {
-                    //入库或出库
-                    if(BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) ||
-                            BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())) {
-                        //批号不能为空
-                        if (BusinessConstants.ENABLE_BATCH_NUMBER_ENABLED.equals(material.getEnableBatchNumber())) {
-                            //如果开启出入库管理,并且类型等于采购、采购退货、销售、销售退货,则跳过
-                            if(systemConfigService.getInOutManageFlag() &&
-                                    (BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_PURCHASE_RETURN.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_SALES_RETURN.equals(depotHead.getSubType()))) {
-                                //跳过
-                            } else {
-                                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BATCH_NUMBERE_EMPTY_CODE,
-                                        String.format(ExceptionConstants.DEPOT_HEAD_BATCH_NUMBERE_EMPTY_MSG, barCode));
-                            }
-                        }
-                    }
-                }
-                if (StringUtil.isExist(rowObj.get("expirationDate"))) {
-                    depotItem.setExpirationDate(rowObj.getDate("expirationDate"));
-                }
-                if (StringUtil.isExist(rowObj.get("sku"))) {
-                    depotItem.setSku(rowObj.getString("sku"));
-                }
-                if (StringUtil.isExist(rowObj.get("linkId"))) {
-                    depotItem.setLinkId(rowObj.getLong("linkId"));
-                }
-                //以下进行单位换算
-                Unit unitInfo = materialService.findUnit(materialExtend.getMaterialId()); //查询多单位信息
-                if (StringUtil.isExist(rowObj.get("operNumber"))) {
-                    depotItem.setOperNumber(rowObj.getBigDecimal("operNumber"));
-                    String unit = rowObj.get("unit").toString();
-                    BigDecimal oNumber = rowObj.getBigDecimal("operNumber");
-                    if (StringUtil.isNotEmpty(unitInfo.getName())) {
-                        String basicUnit = unitInfo.getBasicUnit(); //基本单位
-                        if (unit.equals(basicUnit)) { //如果等于基本单位
-                            depotItem.setBasicNumber(oNumber); //数量一致
-                        } else if (unit.equals(unitInfo.getOtherUnit())) { //如果等于副单位
-                            depotItem.setBasicNumber(oNumber.multiply(unitInfo.getRatio())); //数量乘以比例
-                        } else if (unit.equals(unitInfo.getOtherUnitTwo())) { //如果等于副单位2
-                            depotItem.setBasicNumber(oNumber.multiply(unitInfo.getRatioTwo())); //数量乘以比例
-                        } else if (unit.equals(unitInfo.getOtherUnitThree())) { //如果等于副单位3
-                            depotItem.setBasicNumber(oNumber.multiply(unitInfo.getRatioThree())); //数量乘以比例
-                        } else {
-                            depotItem.setBasicNumber(oNumber); //数量一致
-                        }
-                    } else {
-                        depotItem.setBasicNumber(oNumber); //其他情况
-                    }
-                }
-                //如果数量+已完成数量>原订单数量,给出预警(判断前提是存在关联订单|关联请购单)
-                String linkStr = StringUtil.isNotEmpty(depotHead.getLinkNumber())? depotHead.getLinkNumber(): depotHead.getLinkApply();
-                if (StringUtil.isNotEmpty(linkStr) && StringUtil.isExist(rowObj.get("preNumber")) && StringUtil.isExist(rowObj.get("finishNumber"))) {
-                    if("add".equals(actionType)) {
-                        //在新增模式进行状态赋值
-                        BigDecimal preNumber = rowObj.getBigDecimal("preNumber");
-                        BigDecimal finishNumber = rowObj.getBigDecimal("finishNumber");
-                        if(depotItem.getOperNumber().add(finishNumber).compareTo(preNumber)>0) {
-                            if(!systemConfigService.getOverLinkBillFlag()) {
-                                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_CODE,
-                                        String.format(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG, barCode));
-                            }
-                        }
-                    } else if("update".equals(actionType)) {
-                        //当前单据的类型
-                        String currentSubType = depotHead.getSubType();
-                        //在更新模式进行状态赋值
-                        String unit = rowObj.get("unit").toString();
-                        Long preHeaderId = depotHeadService.getDepotHead(linkStr).getId();
-                        if(null!=preHeaderId) {
-                            //前一个单据的数量
-                            BigDecimal preNumber = getPreItemByHeaderIdAndMaterial(linkStr, depotItem.getMaterialExtendId(), depotItem.getLinkId()).getOperNumber();
-                            //除去此单据之外的已入库|已出库
-                            BigDecimal realFinishNumber = getRealFinishNumber(currentSubType, depotItem.getMaterialExtendId(), depotItem.getLinkId(), preHeaderId, headerId, unitInfo, unit);
-                            if(preNumber!=null) {
-                                if (depotItem.getOperNumber().add(realFinishNumber).compareTo(preNumber) > 0) {
-                                    if (!systemConfigService.getOverLinkBillFlag()) {
-                                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_CODE,
-                                                String.format(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG, barCode));
-                                    }
-                                }
-                            } else {
-                                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_PRE_BILL_IS_CHANGE_CODE,
-                                        ExceptionConstants.DEPOT_ITEM_PRE_BILL_IS_CHANGE_MSG);
-                            }
-                        }
-                    }
-                }
-                if (StringUtil.isExist(rowObj.get("unitPrice"))) {
-                    BigDecimal unitPrice = rowObj.getBigDecimal("unitPrice");
-                    depotItem.setUnitPrice(unitPrice);
-                    if(materialExtend.getLowDecimal()!=null) {
-                        //零售或销售单价低于最低售价,进行提示
-                        if("零售".equals(depotHead.getSubType()) || "销售".equals(depotHead.getSubType())) {
-                            if (unitPrice.compareTo(materialExtend.getLowDecimal()) < 0) {
-                                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UNIT_PRICE_LOW_CODE,
-                                        String.format(ExceptionConstants.DEPOT_HEAD_UNIT_PRICE_LOW_MSG, barCode));
-                            }
-                        }
-                    }
-                }
-                //如果是销售出库、销售退货、零售出库、零售退货则给采购单价字段赋值(如果是批次商品,则要根据批号去找之前的入库价)
-                if(BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType()) ||
-                    BusinessConstants.SUB_TYPE_SALES_RETURN.equals(depotHead.getSubType()) ||
-                    BusinessConstants.SUB_TYPE_RETAIL.equals(depotHead.getSubType()) ||
-                    BusinessConstants.SUB_TYPE_RETAIL_RETURN.equals(depotHead.getSubType())) {
-                    boolean moveAvgPriceFlag = systemConfigService.getMoveAvgPriceFlag();
-                    BigDecimal currentUnitPrice = materialCurrentStockMapperEx.getCurrentUnitPriceByMId(materialExtend.getMaterialId());
-                    currentUnitPrice = unitService.parseUnitPriceByUnit(currentUnitPrice, unitInfo, depotItem.getMaterialUnit());
-                    BigDecimal unitPrice = moveAvgPriceFlag? currentUnitPrice: materialExtend.getPurchaseDecimal();
-                    depotItem.setPurchaseUnitPrice(unitPrice);
-                    if(StringUtil.isNotEmpty(depotItem.getBatchNumber())) {
-                        depotItem.setPurchaseUnitPrice(getDepotItemByBatchNumber(depotItem.getMaterialExtendId(),depotItem.getBatchNumber()).getUnitPrice());
-                    }
-                }
-                if (StringUtil.isExist(rowObj.get("taxUnitPrice"))) {
-                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("taxUnitPrice"));
-                }
-                if (StringUtil.isExist(rowObj.get("allPrice"))) {
-                    depotItem.setAllPrice(rowObj.getBigDecimal("allPrice"));
-                }
-                if (StringUtil.isExist(rowObj.get("depotId"))) {
-                    depotItem.setDepotId(rowObj.getLong("depotId"));
-                } else {
-                    if(!BusinessConstants.SUB_TYPE_PURCHASE_APPLY.equals(depotHead.getSubType())
-                            && !BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())
-                            && !BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
-                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_CODE,
-                                String.format(ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_MSG));
-                    }
-                }
-                if(BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
-                    if (StringUtil.isExist(rowObj.get("anotherDepotId"))) {
-                        if(rowObj.getLong("anotherDepotId").equals(rowObj.getLong("depotId"))) {
-                            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ANOTHER_DEPOT_EQUAL_FAILED_CODE,
-                                    String.format(ExceptionConstants.DEPOT_HEAD_ANOTHER_DEPOT_EQUAL_FAILED_MSG));
-                        } else {
-                            depotItem.setAnotherDepotId(rowObj.getLong("anotherDepotId"));
-                        }
-                    } else {
-                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ANOTHER_DEPOT_FAILED_CODE,
-                                String.format(ExceptionConstants.DEPOT_HEAD_ANOTHER_DEPOT_FAILED_MSG));
-                    }
-                }
-                if (StringUtil.isExist(rowObj.get("taxRate"))) {
-                    depotItem.setTaxRate(rowObj.getBigDecimal("taxRate"));
-                }
-                if (StringUtil.isExist(rowObj.get("taxMoney"))) {
-                    depotItem.setTaxMoney(rowObj.getBigDecimal("taxMoney"));
-                }
-                if (StringUtil.isExist(rowObj.get("taxLastMoney"))) {
-                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("taxLastMoney"));
-                }
-                if (StringUtil.isExist(rowObj.get("mType"))) {
-                    depotItem.setMaterialType(rowObj.getString("mType"));
-                }
-                if (StringUtil.isExist(rowObj.get("remark"))) {
-                    depotItem.setRemark(rowObj.getString("remark"));
-                }
-                //出库时判断库存是否充足
-                if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())){
-                    String stockMsg = material.getName() + "-" + barCode;
-                    BigDecimal stock = getCurrentStockByParam(depotItem.getDepotId(),depotItem.getMaterialId());
-                    if(StringUtil.isNotEmpty(depotItem.getSku())) {
-                        //对于sku商品要换个方式计算库存
-                        stock = getSkuStockByParam(depotItem.getDepotId(),depotItem.getMaterialExtendId(),null,null);
-                    }
-                    if(StringUtil.isNotEmpty(depotItem.getBatchNumber())) {
-                        //对于批次商品要换个方式计算库存
-                        stock = getOneBatchNumberStock(depotItem.getDepotId(), barCode, depotItem.getBatchNumber());
-                        stockMsg += "-批号" + depotItem.getBatchNumber();
-                    }
-                    BigDecimal thisRealNumber = depotItem.getBasicNumber()==null?BigDecimal.ZERO:depotItem.getBasicNumber();
-                    if(StringUtil.isNotEmpty(depotItem.getBatchNumber())) {
-                        //对于批次商品,直接使用当前填写的数量
-                        thisRealNumber = depotItem.getOperNumber()==null?BigDecimal.ZERO:depotItem.getOperNumber();
-                    }
-                    if(!systemConfigService.getMinusStockFlag() && stock.compareTo(thisRealNumber)<0){
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
-                                String.format(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG, stockMsg));
-                    }
-                    //出库时处理序列号
-                    if(!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
-                        //判断商品是否开启序列号,开启的售出序列号,未开启的跳过
-                        if(BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED.equals(material.getEnableSerialNumber())) {
-                            //如果开启出入库管理,并且类型等于采购、采购退货、销售、销售退货,则跳过
-                            if(systemConfigService.getInOutManageFlag() &&
-                                    (BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_PURCHASE_RETURN.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())
-                                            ||BusinessConstants.SUB_TYPE_SALES_RETURN.equals(depotHead.getSubType()))) {
-                                //跳过
-                            } else {
-                                //售出序列号,获得当前操作人
-                                User userInfo = userService.getCurrentUser();
-                                serialNumberService.checkAndUpdateSerialNumber(depotItem, depotHead.getNumber(), userInfo, StringUtil.toNull(depotItem.getSnList()));
-                            }
-                        }
-                    }
-                }
-                this.insertDepotItemWithObj(depotItem);
-                //更新当前库存
-                updateCurrentStock(depotItem);
-                //更新当前成本价
-                updateCurrentUnitPrice(depotItem);
-                //更新商品的价格
-                updateMaterialExtendPrice(materialExtend.getId(), depotHead.getSubType(), depotHead.getBillType(), rowObj);
-            }
-            //如果关联单据号非空则更新订单的状态,单据类型:采购入库单、销售出库单、盘点复盘单、其它入库单、其它出库单
-            if(BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())
-                    || BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())
-                    || BusinessConstants.SUB_TYPE_REPLAY.equals(depotHead.getSubType())
-                    || BusinessConstants.SUB_TYPE_OTHER.equals(depotHead.getSubType())) {
-                if(StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
-                    //单据状态:是否全部完成 2-全部完成 3-部分完成(针对订单的分批出入库)
-                    String billStatus = getBillStatusByParam(depotHead, depotHead.getLinkNumber(), "normal");
-                    changeBillStatus(depotHead.getLinkNumber(), billStatus);
-                }
-            }
-            //当前单据类型为采购订单的逻辑
-            if(BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
-                //如果关联单据号非空则更新订单的状态,此处针对销售订单转采购订单的场景
-                if(StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
-                    String billStatus = getBillStatusByParam(depotHead, depotHead.getLinkNumber(), "normal");
-                    changeBillPurchaseStatus(depotHead.getLinkNumber(), billStatus);
-                }
-                //如果关联单据号非空则更新订单的状态,此处针对请购单转采购订单的场景
-                if(StringUtil.isNotEmpty(depotHead.getLinkApply())) {
-                    String billStatus = getBillStatusByParam(depotHead, depotHead.getLinkApply(), "apply");
-                    changeBillStatus(depotHead.getLinkApply(), billStatus);
-                }
-            }
-        } else {
-            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ROW_FAILED_CODE,
-                    String.format(ExceptionConstants.DEPOT_HEAD_ROW_FAILED_MSG));
-        }
-    }
-    /**
-     * 判断单据的状态
-     * 通过数组对比:原单据的商品和商品数量(汇总) 与 分批操作后单据的商品和商品数量(汇总)
-     * @param depotHead
-     * @param linkStr
-     * @return
-     */
+    void saveOrderItem(DepotHeadXsddRequestVO order, List<DepotItemXsddRequestVO> itemList) throws Exception;
+
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public String getBillStatusByParam(DepotHead depotHead, String linkStr, String linkType) {
-        String res = BusinessConstants.BILLS_STATUS_SKIPED;
-        //获取原单据的商品和商品数量(汇总)
-        List<DepotItemVo4MaterialAndSum> linkList = depotItemMapperEx.getLinkBillDetailMaterialSum(linkStr);
-        //获取分批操作后单据的商品和商品数量(汇总)
-        List<DepotItemVo4MaterialAndSum> batchList = depotItemMapperEx.getBatchBillDetailMaterialSum(linkStr, linkType, depotHead.getType());
-        //将分批操作后的单据的商品和商品数据构造成Map
-        Map<Long, BigDecimal> materialSumMap = new HashMap<>();
-        for(DepotItemVo4MaterialAndSum materialAndSum : batchList) {
-            materialSumMap.put(materialAndSum.getMaterialExtendId(), materialAndSum.getOperNumber());
-        }
-        for(DepotItemVo4MaterialAndSum materialAndSum : linkList) {
-            //过滤掉原单里面有数量为0的商品
-            if(materialAndSum.getOperNumber().compareTo(BigDecimal.ZERO) != 0) {
-                BigDecimal materialSum = materialSumMap.get(materialAndSum.getMaterialExtendId());
-                if (materialSum != null) {
-                    if (materialSum.compareTo(materialAndSum.getOperNumber()) < 0) {
-                        res = BusinessConstants.BILLS_STATUS_SKIPING;
-                    }
-                } else {
-                    res = BusinessConstants.BILLS_STATUS_SKIPING;
-                }
-            }
-        }
-        return res;
-    }
+    String getBillStatusByParam(DepotHead depotHead, String linkStr, String linkType);
 
-    /**
-     * 更新单据状态
-     * @param linkStr
-     * @param billStatus
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void changeBillStatus(String linkStr, String billStatus) {
-        DepotHead depotHeadOrders = new DepotHead();
-        depotHeadOrders.setStatus(billStatus);
-        DepotHeadExample example = new DepotHeadExample();
-        List<String> linkNoList = StringUtil.strToStringList(linkStr);
-        example.createCriteria().andNumberIn(linkNoList);
-        try{
-            depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
-        }catch(Exception e){
-            logger.error("异常码[{}],异常提示[{}],异常[{}]",
-                    ExceptionConstants.DATA_WRITE_FAIL_CODE,ExceptionConstants.DATA_WRITE_FAIL_MSG,e);
-            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
-                    ExceptionConstants.DATA_WRITE_FAIL_MSG);
-        }
-    }
+    void changeBillStatus(String linkStr, String billStatus);
 
-    /**
-     * 更新单据状态,此处针对销售订单转采购订单的场景
-     * @param linkStr
-     * @param billStatus
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void changeBillPurchaseStatus(String linkStr, String billStatus) {
-        DepotHead depotHeadOrders = new DepotHead();
-        depotHeadOrders.setPurchaseStatus(billStatus);
-        DepotHeadExample example = new DepotHeadExample();
-        List<String> linkNoList = StringUtil.strToStringList(linkStr);
-        example.createCriteria().andNumberIn(linkNoList);
-        try{
-            depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
-        }catch(Exception e){
-            logger.error("异常码[{}],异常提示[{}],异常[{}]",
-                    ExceptionConstants.DATA_WRITE_FAIL_CODE,ExceptionConstants.DATA_WRITE_FAIL_MSG,e);
-            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
-                    ExceptionConstants.DATA_WRITE_FAIL_MSG);
-        }
-    }
+    void changeBillPurchaseStatus(String linkStr, String billStatus);
 
-    /**
-     * 根据批号查询单据明细信息
-     * @param materialExtendId
-     * @param batchNumber
-     * @return
-     */
-    public DepotItem getDepotItemByBatchNumber(Long materialExtendId, String batchNumber) {
-        List<DepotItem> depotItemList = depotItemMapperEx.getDepotItemByBatchNumber(materialExtendId, batchNumber);
-        if(null != depotItemList && depotItemList.size() > 0){
-            return depotItemList.get(0);
-        } else {
-            return new DepotItem();
-        }
-    }
+    DepotItem getDepotItemByBatchNumber(Long materialExtendId, String batchNumber);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void deleteDepotItemHeadId(Long headerId)throws Exception {
-        try{
-            //1、查询删除前的单据明细
-            List<DepotItem> depotItemList = getListByHeaderId(headerId);
-            //2、删除单据明细
-            DepotItemExample example = new DepotItemExample();
-            example.createCriteria().andHeaderIdEqualTo(headerId);
-            depotItemMapper.deleteByExample(example);
-            //3、计算删除之后单据明细中商品的库存
-            for(DepotItem depotItem : depotItemList){
-                updateCurrentStock(depotItem);
-            }
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-    }
+    void deleteDepotItemHeadId(Long headerId)throws Exception;
 
-    /**
-     * 删除序列号和回收序列号
-     * @param actionType
-     * @throws Exception
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void deleteOrCancelSerialNumber(String actionType, DepotHead depotHead, Long headerId) throws Exception {
-        if(actionType.equals("update")) {
-            User userInfo = userService.getCurrentUser();
-            if(BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType())){
-                //入库逻辑
-                String number = depotHead.getNumber();
-                SerialNumberExample example = new SerialNumberExample();
-                example.createCriteria().andInBillNoEqualTo(number);
-                serialNumberService.deleteByExample(example);
-            } else if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())){
-                //出库逻辑
-                DepotItemExample example = new DepotItemExample();
-                example.createCriteria().andHeaderIdEqualTo(headerId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-                List<DepotItem> depotItemList = depotItemMapper.selectByExample(example);
-                if(null != depotItemList && depotItemList.size() > 0){
-                    for (DepotItem depotItem : depotItemList){
-                        if(StringUtil.isNotEmpty(depotItem.getSnList())){
-                            serialNumberService.cancelSerialNumber(depotItem.getMaterialId(), depotHead.getNumber(), (depotItem.getBasicNumber() == null ? 0 : depotItem.getBasicNumber()).intValue(), userInfo);
-                        }
-                    }
-                }
-            }
-        }
-    }
+    void deleteOrCancelSerialNumber(String actionType, DepotHead depotHead, Long headerId) throws Exception;
 
-    /**
-     * 针对组装单、拆卸单校验是否存在组合件和普通子件
-     * @param rowArr
-     * @param subType
-     */
-    public void checkAssembleWithMaterialType(JSONArray rowArr, String subType) {
-        if(BusinessConstants.SUB_TYPE_ASSEMBLE.equals(subType) ||
-                BusinessConstants.SUB_TYPE_DISASSEMBLE.equals(subType)) {
-            if(rowArr.size() > 1) {
-                JSONObject firstRowObj = JSONObject.parseObject(rowArr.getString(0));
-                JSONObject secondRowObj = JSONObject.parseObject(rowArr.getString(1));
-                String firstMaterialType = firstRowObj.getString("mType");
-                String secondMaterialType = secondRowObj.getString("mType");
-                if(!"组合件".equals(firstMaterialType) || !"普通子件".equals(secondMaterialType)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_CHECK_ASSEMBLE_EMPTY_CODE,
-                            String.format(ExceptionConstants.DEPOT_HEAD_CHECK_ASSEMBLE_EMPTY_MSG));
-                }
-            } else {
-                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_CHECK_ASSEMBLE_EMPTY_CODE,
-                        String.format(ExceptionConstants.DEPOT_HEAD_CHECK_ASSEMBLE_EMPTY_MSG));
-            }
-        }
-    }
+    void checkAssembleWithMaterialType(JSONArray rowArr, String subType);
 
-    /**
-     * 更新商品的价格
-     * @param meId
-     * @param subType
-     * @param rowObj
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void updateMaterialExtendPrice(Long meId, String subType, String billType, JSONObject rowObj) throws Exception {
-        if(systemConfigService.getUpdateUnitPriceFlag()) {
-            if (StringUtil.isExist(rowObj.get("unitPrice"))) {
-                BigDecimal unitPrice = rowObj.getBigDecimal("unitPrice");
-                MaterialExtend materialExtend = new MaterialExtend();
-                materialExtend.setId(meId);
-                if(BusinessConstants.SUB_TYPE_PURCHASE.equals(subType)) {
-                    materialExtend.setPurchaseDecimal(unitPrice);
-                }
-                if(BusinessConstants.SUB_TYPE_SALES.equals(subType)) {
-                    materialExtend.setWholesaleDecimal(unitPrice);
-                }
-                if(BusinessConstants.SUB_TYPE_RETAIL.equals(subType)) {
-                    materialExtend.setCommodityDecimal(unitPrice);
-                }
-                //其它入库-生产入库的情况更新采购单价
-                if(BusinessConstants.SUB_TYPE_OTHER.equals(subType)) {
-                    if(BusinessConstants.BILL_TYPE_PRODUCE_IN.equals(billType)) {
-                        materialExtend.setPurchaseDecimal(unitPrice);
-                    }
-                }
-                materialExtendService.updateMaterialExtend(materialExtend);
-            }
-        }
-    }
+    void updateMaterialExtendPrice(Long meId, String subType, String billType, JSONObject rowObj) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public List<DepotItemStockWarningCount> findStockWarningCount(Integer offset, Integer rows, String materialParam, List<Long> depotList, List<Long> categoryList) {
-        List<DepotItemStockWarningCount> list = null;
-        try{
-            list =depotItemMapperEx.findStockWarningCount(offset, rows, materialParam, depotList, categoryList);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<DepotItemStockWarningCount> findStockWarningCount(Integer offset, Integer rows, String materialParam, List<Long> depotList, List<Long> categoryList);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int findStockWarningCountTotal(String materialParam, List<Long> depotList, List<Long> categoryList) {
-        int result = 0;
-        try{
-            result =depotItemMapperEx.findStockWarningCountTotal(materialParam, depotList, categoryList);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+    int findStockWarningCountTotal(String materialParam, List<Long> depotList, List<Long> categoryList);
 
-    /**
-     * 库存统计-sku
-     * @param depotId
-     * @param meId
-     * @param beginTime
-     * @param endTime
-     * @return
-     */
-    public BigDecimal getSkuStockByParam(Long depotId, Long meId, String beginTime, String endTime) throws Exception {
-        Boolean forceFlag = systemConfigService.getForceApprovalFlag();
-        Boolean inOutManageFlag = systemConfigService.getInOutManageFlag();
-        List<Long> depotList = depotService.parseDepotList(depotId);
-        //盘点复盘后数量的变动
-        BigDecimal stockCheckSum = depotItemMapperEx.getSkuStockCheckSumByDepotList(depotList, meId, forceFlag, beginTime, endTime);
-        DepotItemVo4Stock stockObj = depotItemMapperEx.getSkuStockByParamWithDepotList(depotList, meId, forceFlag, inOutManageFlag, beginTime, endTime);
-        BigDecimal stockSum = BigDecimal.ZERO;
-        if(stockObj!=null) {
-            BigDecimal inTotal = stockObj.getInTotal();
-            BigDecimal transfInTotal = stockObj.getTransfInTotal();
-            BigDecimal assemInTotal = stockObj.getAssemInTotal();
-            BigDecimal disAssemInTotal = stockObj.getDisAssemInTotal();
-            BigDecimal outTotal = stockObj.getOutTotal();
-            BigDecimal transfOutTotal = stockObj.getTransfOutTotal();
-            BigDecimal assemOutTotal = stockObj.getAssemOutTotal();
-            BigDecimal disAssemOutTotal = stockObj.getDisAssemOutTotal();
-            stockSum = inTotal.add(transfInTotal).add(assemInTotal).add(disAssemInTotal)
-                    .subtract(outTotal).subtract(transfOutTotal).subtract(assemOutTotal).subtract(disAssemOutTotal);
-        }
-        return stockCheckSum.add(stockSum);
-    }
+    BigDecimal getSkuStockByParam(Long depotId, Long meId, String beginTime, String endTime) throws Exception;
 
-    /**
-     * 库存统计-单仓库
-     * @param depotId
-     * @param mId
-     * @param beginTime
-     * @param endTime
-     * @return
-     */
-    public BigDecimal getStockByParam(Long depotId, Long mId, String beginTime, String endTime) throws Exception {
-        List<Long> depotList = depotService.parseDepotList(depotId);
-        return getStockByParamWithDepotList(depotList, mId, beginTime, endTime);
-    }
+    BigDecimal getStockByParam(Long depotId, Long mId, String beginTime, String endTime) throws Exception;
 
-    /**
-     * 库存统计-多仓库
-     * @param depotList
-     * @param mId
-     * @param beginTime
-     * @param endTime
-     * @return
-     */
-    public BigDecimal getStockByParamWithDepotList(List<Long> depotList, Long mId, String beginTime, String endTime) throws Exception {
-        Boolean forceFlag = systemConfigService.getForceApprovalFlag();
-        Boolean inOutManageFlag = systemConfigService.getInOutManageFlag();
-        //初始库存
-        BigDecimal initStock = materialService.getInitStockByMidAndDepotList(depotList, mId);
-        //盘点复盘后数量的变动
-        BigDecimal stockCheckSum = depotItemMapperEx.getStockCheckSumByDepotList(depotList, mId, forceFlag, beginTime, endTime);
-        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParamWithDepotList(depotList, mId, forceFlag, inOutManageFlag, beginTime, endTime);
-        BigDecimal stockSum = BigDecimal.ZERO;
-        if(stockObj!=null) {
-            BigDecimal inTotal = stockObj.getInTotal();
-            BigDecimal transfInTotal = stockObj.getTransfInTotal();
-            BigDecimal assemInTotal = stockObj.getAssemInTotal();
-            BigDecimal disAssemInTotal = stockObj.getDisAssemInTotal();
-            BigDecimal outTotal = stockObj.getOutTotal();
-            BigDecimal transfOutTotal = stockObj.getTransfOutTotal();
-            BigDecimal assemOutTotal = stockObj.getAssemOutTotal();
-            BigDecimal disAssemOutTotal = stockObj.getDisAssemOutTotal();
-            stockSum = inTotal.add(transfInTotal).add(assemInTotal).add(disAssemInTotal)
-                    .subtract(outTotal).subtract(transfOutTotal).subtract(assemOutTotal).subtract(disAssemOutTotal);
-        }
-        return initStock.add(stockCheckSum).add(stockSum);
-    }
+    BigDecimal getStockByParamWithDepotList(List<Long> depotList, Long mId, String beginTime, String endTime) throws Exception;
 
-    /**
-     * 统计时间段内的入库和出库数量-多仓库
-     * @param depotList
-     * @param mId
-     * @param beginTime
-     * @param endTime
-     * @return
-     */
-    public Map<String, BigDecimal> getIntervalMapByParamWithDepotList(List<Long> depotList, Long mId, String beginTime, String endTime) throws Exception {
-        Boolean forceFlag = systemConfigService.getForceApprovalFlag();
-        Boolean inOutManageFlag = systemConfigService.getInOutManageFlag();
-        Map<String,BigDecimal> intervalMap = new HashMap<>();
-        BigDecimal inSum = BigDecimal.ZERO;
-        BigDecimal outSum = BigDecimal.ZERO;
-        //盘点复盘后数量的变动
-        BigDecimal stockCheckSum = depotItemMapperEx.getStockCheckSumByDepotList(depotList, mId, forceFlag, beginTime, endTime);
-        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParamWithDepotList(depotList, mId, forceFlag, inOutManageFlag, beginTime, endTime);
-        if(stockObj!=null) {
-            BigDecimal inTotal = stockObj.getInTotal();
-            BigDecimal transfInTotal = stockObj.getTransfInTotal();
-            BigDecimal assemInTotal = stockObj.getAssemInTotal();
-            BigDecimal disAssemInTotal = stockObj.getDisAssemInTotal();
-            inSum = inTotal.add(transfInTotal).add(assemInTotal).add(disAssemInTotal);
-            BigDecimal outTotal = stockObj.getOutTotal();
-            BigDecimal transfOutTotal = stockObj.getTransfOutTotal();
-            BigDecimal assemOutTotal = stockObj.getAssemOutTotal();
-            BigDecimal disAssemOutTotal = stockObj.getDisAssemOutTotal();
-            outSum = outTotal.add(transfOutTotal).add(assemOutTotal).add(disAssemOutTotal);
-        }
-        if(stockCheckSum.compareTo(BigDecimal.ZERO)>0) {
-            inSum = inSum.add(stockCheckSum);
-        } else {
-            //盘点复盘数量为负数代表出库
-            outSum = outSum.subtract(stockCheckSum);
-        }
-        intervalMap.put("inSum", inSum);
-        intervalMap.put("outSum", outSum);
-        return intervalMap;
-    }
+    Map<String, BigDecimal> getIntervalMapByParamWithDepotList(List<Long> depotList, Long mId, String beginTime, String endTime) throws Exception;
 
-    /**
-     * 根据单据明细来批量更新当前库存
-     * @param depotItem
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void updateCurrentStock(DepotItem depotItem) throws Exception {
-        updateCurrentStockFun(depotItem.getMaterialId(), depotItem.getDepotId());
-        if(depotItem.getAnotherDepotId()!=null){
-            updateCurrentStockFun(depotItem.getMaterialId(), depotItem.getAnotherDepotId());
-        }
-    }
+    void updateCurrentStock(DepotItem depotItem) throws Exception;
 
-    /**
-     * 根据单据明细来批量更新当前成本价
-     * @param depotItem
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void updateCurrentUnitPrice(DepotItem depotItem) throws Exception {
-        Boolean forceFlag = systemConfigService.getForceApprovalFlag();
-        Boolean inOutManageFlag = systemConfigService.getInOutManageFlag();
-        //查询多单位信息
-        Unit unitInfo = materialService.findUnit(depotItem.getMaterialId());
-        List<DepotItemVo4DetailByTypeAndMId> itemList = findDetailByDepotIdsAndMaterialIdList(null, forceFlag, inOutManageFlag, depotItem.getSku(),
-                depotItem.getBatchNumber(), null, null, null, depotItem.getMaterialId(), null, null);
-        Collections.reverse(itemList); //倒序之后变成按时间从前往后排序
-        BigDecimal currentNumber = BigDecimal.ZERO;
-        BigDecimal currentUnitPrice = BigDecimal.ZERO;
-        BigDecimal currentAllPrice = BigDecimal.ZERO;
-        for(DepotItemVo4DetailByTypeAndMId item: itemList) {
-            BigDecimal basicNumber = item.getBnum()!=null?item.getBnum():BigDecimal.ZERO;
-            //数量*单价  另外计算新的成本价
-            BigDecimal allPrice = unitService.parseAllPriceByUnit(item.getAllPrice()!=null?item.getAllPrice():BigDecimal.ZERO, unitInfo, item.getMaterialUnit());
-            if(basicNumber.compareTo(BigDecimal.ZERO)!=0 && allPrice.compareTo(BigDecimal.ZERO)!=0) {
-                //入库
-                if (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(item.getType())) {
-                    //零售退货、销售退货
-                    if (BusinessConstants.SUB_TYPE_RETAIL_RETURN.equals(item.getSubType()) || BusinessConstants.SUB_TYPE_SALES_RETURN.equals(item.getSubType())) {
-                        //数量*当前的成本单价
-                        currentNumber = currentNumber.add(basicNumber);
-                        currentAllPrice = currentAllPrice.add(basicNumber.multiply(currentUnitPrice));
-                    } else {
-                        currentAllPrice = currentAllPrice.add(allPrice);
-                        currentNumber = currentNumber.add(basicNumber);
-                        //只有当前库存总金额和当前库存数量都大于0才计算移动平均价
-                        if (currentAllPrice.compareTo(BigDecimal.ZERO) > 0 && currentNumber.compareTo(BigDecimal.ZERO) > 0) {
-                            currentUnitPrice = currentAllPrice.divide(currentNumber, 2, BigDecimal.ROUND_HALF_UP);
-                        } else {
-                            currentUnitPrice = item.getUnitPrice();
-                        }
-                    }
-                }
-                //出库
-                if (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(item.getType())) {
-                    //采购退货
-                    if (BusinessConstants.SUB_TYPE_PURCHASE_RETURN.equals(item.getSubType())) {
-                        currentAllPrice = currentAllPrice.add(allPrice);
-                        currentNumber = currentNumber.add(basicNumber);
-                        //只有当前库存总金额和当前库存数量都大于0才计算移动平均价
-                        if (currentAllPrice.compareTo(BigDecimal.ZERO) > 0 && currentNumber.compareTo(BigDecimal.ZERO) > 0) {
-                            currentUnitPrice = currentAllPrice.divide(currentNumber, 2, BigDecimal.ROUND_HALF_UP);
-                        } else {
-                            currentUnitPrice = item.getUnitPrice();
-                        }
-                    } else {
-                        currentNumber = currentNumber.add(basicNumber);
-                        //数量*当前的成本单价
-                        currentAllPrice = currentAllPrice.add(basicNumber.multiply(currentUnitPrice));
-                    }
-                }
-                //防止单价金额溢出
-                if(currentUnitPrice.compareTo(BigDecimal.valueOf(100000000))>0 || currentUnitPrice.compareTo(BigDecimal.valueOf(-100000000))<0) {
-                    currentUnitPrice = BigDecimal.ZERO;
-                }
-            }
-        }
-        //更新实时库存中的当前单价
-        materialCurrentStockMapperEx.updateUnitPriceByMId(currentUnitPrice, depotItem.getMaterialId());
-    }
+    void updateCurrentUnitPrice(DepotItem depotItem) throws Exception;
 
-    /**
-     * 根据商品和仓库来更新当前库存
-     * @param mId
-     * @param dId
-     */
-    public void updateCurrentStockFun(Long mId, Long dId) throws Exception {
-        if(mId!=null && dId!=null) {
-            MaterialCurrentStockExample example = new MaterialCurrentStockExample();
-            example.createCriteria().andMaterialIdEqualTo(mId).andDepotIdEqualTo(dId)
-                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            List<MaterialCurrentStock> list = materialCurrentStockMapper.selectByExample(example);
-            MaterialCurrentStock materialCurrentStock = new MaterialCurrentStock();
-            materialCurrentStock.setMaterialId(mId);
-            materialCurrentStock.setDepotId(dId);
-            materialCurrentStock.setCurrentNumber(getStockByParam(dId,mId,null,null));
-            if(list!=null && list.size()>0) {
-                Long mcsId = list.get(0).getId();
-                materialCurrentStock.setId(mcsId);
-                materialCurrentStockMapper.updateByPrimaryKeySelective(materialCurrentStock);
-            } else {
-                materialCurrentStockMapper.insertSelective(materialCurrentStock);
-            }
-        }
-    }
+    void updateCurrentStockFun(Long mId, Long dId) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public BigDecimal getFinishNumber(Long meId, Long id, Long headerId, Unit unitInfo, String materialUnit, String linkType) {
-        Long linkId = id;
-        String goToType = "";
-        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(headerId);
-        String linkStr = depotHead.getNumber(); //订单号
-        if("purchase".equals(linkType)) {
-            //针对以销定购的情况
-            if(BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
-                goToType = BusinessConstants.SUB_TYPE_PURCHASE_ORDER;
-            }
-        } else if("other".equals(linkType)) {
-            //采购入库、采购退货、销售出库、销售退货都转其它入库
-            if(BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())
-                    || BusinessConstants.SUB_TYPE_PURCHASE_RETURN.equals(depotHead.getSubType())
-                    || BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())
-                    || BusinessConstants.SUB_TYPE_SALES_RETURN.equals(depotHead.getSubType())) {
-                goToType = BusinessConstants.SUB_TYPE_OTHER;
-            }
-        } else if("basic".equals(linkType)) {
-            //采购订单转采购入库
-            if(BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
-                goToType = BusinessConstants.SUB_TYPE_PURCHASE;
-            }
-            //销售订单转销售出库
-            if(BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
-                goToType = BusinessConstants.SUB_TYPE_SALES;
-            }
-            //采购入库转采购退货
-            if(BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())) {
-                goToType = BusinessConstants.SUB_TYPE_PURCHASE_RETURN;
-            }
-            //销售出库转销售退货
-            if(BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())) {
-                goToType = BusinessConstants.SUB_TYPE_SALES_RETURN;
-            }
-        }
-        String noType = "normal";
-        if(BusinessConstants.SUB_TYPE_PURCHASE_APPLY.equals(depotHead.getSubType())) {
-            noType = "apply";
-        }
-        BigDecimal count = depotItemMapperEx.getFinishNumber(meId, linkId, linkStr, noType, goToType);
-        //根据多单位情况进行数量的转换
-        if(materialUnit.equals(unitInfo.getOtherUnit()) && unitInfo.getRatio()!=null && unitInfo.getRatio().compareTo(BigDecimal.ZERO)!=0) {
-            count = count.divide(unitInfo.getRatio(),2,BigDecimal.ROUND_HALF_UP);
-        }
-        if(materialUnit.equals(unitInfo.getOtherUnitTwo()) && unitInfo.getRatioTwo()!=null && unitInfo.getRatioTwo().compareTo(BigDecimal.ZERO)!=0) {
-            count = count.divide(unitInfo.getRatioTwo(),2,BigDecimal.ROUND_HALF_UP);
-        }
-        if(materialUnit.equals(unitInfo.getOtherUnitThree()) && unitInfo.getRatioThree()!=null && unitInfo.getRatioThree().compareTo(BigDecimal.ZERO)!=0) {
-            count = count.divide(unitInfo.getRatioThree(),2,BigDecimal.ROUND_HALF_UP);
-        }
-        return count;
-    }
+    BigDecimal getFinishNumber(Long meId, Long id, Long headerId, Unit unitInfo, String materialUnit, String linkType);
 
-    /**
-     * 除去此单据之外的已入库|已出库|已转采购
-     * @param currentSubType
-     * @param meId
-     * @param linkId
-     * @param preHeaderId
-     * @param currentHeaderId
-     * @param unitInfo
-     * @param materialUnit
-     * @return
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public BigDecimal getRealFinishNumber(String currentSubType, Long meId, Long linkId, Long preHeaderId, Long currentHeaderId, Unit unitInfo, String materialUnit) {
-        String goToType = currentSubType;
-        DepotHead depotHead =depotHeadMapper.selectByPrimaryKey(preHeaderId);
-        String linkStr = depotHead.getNumber(); //订单号
-        String linkType = "normal";
-        if(BusinessConstants.SUB_TYPE_PURCHASE_APPLY.equals(depotHead.getSubType())) {
-            linkType = "apply";
-        }
-        BigDecimal count = depotItemMapperEx.getRealFinishNumber(meId, linkId, linkStr, linkType, currentHeaderId, goToType);
-        //根据多单位情况进行数量的转换
-        if(materialUnit.equals(unitInfo.getOtherUnit()) && unitInfo.getRatio()!=null && unitInfo.getRatio().compareTo(BigDecimal.ZERO)!=0) {
-            count = count.divide(unitInfo.getRatio(),2,BigDecimal.ROUND_HALF_UP);
-        }
-        if(materialUnit.equals(unitInfo.getOtherUnitTwo()) && unitInfo.getRatioTwo()!=null && unitInfo.getRatioTwo().compareTo(BigDecimal.ZERO)!=0) {
-            count = count.divide(unitInfo.getRatioTwo(),2,BigDecimal.ROUND_HALF_UP);
-        }
-        if(materialUnit.equals(unitInfo.getOtherUnitThree()) && unitInfo.getRatioThree()!=null && unitInfo.getRatioThree().compareTo(BigDecimal.ZERO)!=0) {
-            count = count.divide(unitInfo.getRatioThree(),2,BigDecimal.ROUND_HALF_UP);
-        }
-        return count;
-    }
+    BigDecimal getRealFinishNumber(String currentSubType, Long meId, Long linkId, Long preHeaderId, Long currentHeaderId, Unit unitInfo, String materialUnit);
 
-    public List<DepotItemVoBatchNumberList> getBatchNumberList(String number, String name, Long depotId, String barCode,
-                                                               String batchNumber, Boolean forceFlag, Boolean inOutManageFlag) throws Exception {
-        List<DepotItemVoBatchNumberList> reslist = new ArrayList<>();
-        List<DepotItemVoBatchNumberList> list =  depotItemMapperEx.getBatchNumberList(StringUtil.toNull(number), name,
-                depotId, barCode, batchNumber, forceFlag, inOutManageFlag);
-        for(DepotItemVoBatchNumberList bn: list) {
-            if(bn.getTotalNum()!=null && bn.getTotalNum().compareTo(BigDecimal.ZERO)>0) {
-                bn.setExpirationDateStr(Tools.parseDateToStr(bn.getExpirationDate()));
-                if(bn.getUnitId()!=null) {
-                    Unit unit = unitService.getUnit(bn.getUnitId());
-                    String commodityUnit = bn.getCommodityUnit();
-                    bn.setTotalNum(unitService.parseStockByUnit(bn.getTotalNum(), unit, commodityUnit));
-                }
-                reslist.add(bn);
-            }
-        }
-        return reslist;
-    }
+    List<DepotItemVoBatchNumberList> getBatchNumberList(String number, String name, Long depotId, String barCode,
+                                                        String batchNumber, Boolean forceFlag, Boolean inOutManageFlag) throws Exception;
 
-    /**
-     * 查询某个批号的商品库存
-     * @param depotId
-     * @param barCode
-     * @param batchNumber
-     * @return
-     * @throws Exception
-     */
-    public BigDecimal getOneBatchNumberStock(Long depotId, String barCode, String batchNumber) throws Exception {
-        BigDecimal totalNum = BigDecimal.ZERO;
-        Boolean forceFlag = systemConfigService.getForceApprovalFlag();
-        Boolean inOutManageFlag = systemConfigService.getInOutManageFlag();
-        List<DepotItemVoBatchNumberList> list =  depotItemMapperEx.getBatchNumberList(null, null,
-                depotId, barCode, batchNumber, forceFlag, inOutManageFlag);
-        if(list!=null && list.size()>0) {
-            DepotItemVoBatchNumberList bn = list.get(0);
-            totalNum = bn.getTotalNum();
-            if(bn.getTotalNum()!=null && bn.getTotalNum().compareTo(BigDecimal.ZERO)>0) {
-                if(bn.getUnitId()!=null) {
-                    Unit unit = unitService.getUnit(bn.getUnitId());
-                    String commodityUnit = bn.getCommodityUnit();
-                    totalNum = unitService.parseStockByUnit(bn.getTotalNum(), unit, commodityUnit);
-                }
-            }
-        }
-        return totalNum;
-    }
+    BigDecimal getOneBatchNumberStock(Long depotId, String barCode, String batchNumber) throws Exception;
 
-    public Long getCountByMaterialAndDepot(Long mId, Long depotId) {
-        return depotItemMapperEx.getCountByMaterialAndDepot(mId, depotId);
-    }
+    Long getCountByMaterialAndDepot(Long mId, Long depotId);
 
-    public JSONObject parseMapByExcelData(String barCodes, List<Map<String, String>> detailList, String prefixNo) throws Exception {
-        JSONObject map = new JSONObject();
-        JSONArray arr = new JSONArray();
-        List<MaterialVo4Unit> list = depotItemMapperEx.getBillItemByParam(barCodes);
-        Map<String, MaterialVo4Unit> materialMap = new HashMap<>();
-        Map<String, Long> depotMap = new HashMap<>();
-        for (MaterialVo4Unit material: list) {
-            materialMap.put(material.getmBarCode(), material);
-        }
-        JSONArray depotArr = depotService.findDepotByCurrentUser();
-        for (Object depotObj: depotArr) {
-            if(depotObj!=null) {
-                JSONObject depotObject = JSONObject.parseObject(depotObj.toString());
-                depotMap.put(depotObject.getString("depotName"), depotObject.getLong("id"));
-            }
-        }
-        for (Map<String, String> detailMap: detailList) {
-            JSONObject item = new JSONObject();
-            String barCode = detailMap.get("barCode");
-            if(StringUtil.isNotEmpty(barCode)) {
-                MaterialVo4Unit m = materialMap.get(barCode);
-                if(m!=null) {
-                    //判断仓库是否存在
-                    String depotName = detailMap.get("depotName");
-                    if(StringUtil.isNotEmpty(depotName)) {
-                        if(depotMap.get(depotName)!=null) {
-                            item.put("depotName", depotName);
-                            item.put("depotId", depotMap.get(depotName));
-                        } else {
-                            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_DEPOTNAME_IS_NOT_EXIST_CODE,
-                                    String.format(ExceptionConstants.DEPOT_ITEM_DEPOTNAME_IS_NOT_EXIST_MSG, depotName));
-                        }
-                    }
-                    item.put("barCode", barCode);
-                    item.put("name", m.getName());
-                    item.put("standard", m.getStandard());
-                    if(StringUtil.isNotEmpty(m.getModel())) {
-                        item.put("model", m.getModel());
-                    }
-                    if(StringUtil.isNotEmpty(m.getColor())) {
-                        item.put("color", m.getColor());
-                    }
-                    if(StringUtil.isNotEmpty(m.getSku())) {
-                        item.put("sku", m.getSku());
-                    }
-                    BigDecimal stock = BigDecimal.ZERO;
-                    if(StringUtil.isNotEmpty(m.getSku())){
-                        stock = getSkuStockByParam(null, m.getMeId(),null,null);
-                    } else {
-                        stock = getCurrentStockByParam(null, m.getId());
-                    }
-                    item.put("stock", stock);
-                    item.put("unit", m.getCommodityUnit());
-                    BigDecimal operNumber = BigDecimal.ZERO;
-                    BigDecimal unitPrice = BigDecimal.ZERO;
-                    BigDecimal taxRate = BigDecimal.ZERO;
-                    if(StringUtil.isNotEmpty(detailMap.get("num"))) {
-                        operNumber = new BigDecimal(detailMap.get("num"));
-                    }
-                    if(StringUtil.isNotEmpty(detailMap.get("unitPrice"))) {
-                        unitPrice = new BigDecimal(detailMap.get("unitPrice"));
-                    } else {
-                        if("CGDD".equals(prefixNo)) {
-                            unitPrice = m.getPurchaseDecimal();
-                        } else if("XSDD".equals(prefixNo)) {
-                            unitPrice = m.getWholesaleDecimal();
-                        }
-                    }
-                    if(StringUtil.isNotEmpty(detailMap.get("taxRate"))) {
-                        taxRate = new BigDecimal(detailMap.get("taxRate"));
-                    }
-                    String remark = detailMap.get("remark");
-                    item.put("operNumber", operNumber);
-                    item.put("unitPrice", unitPrice);
-                    BigDecimal allPrice = BigDecimal.ZERO;
-                    if(unitPrice!=null && unitPrice.compareTo(BigDecimal.ZERO)!=0) {
-                        allPrice = unitPrice.multiply(operNumber);
-                    }
-                    BigDecimal taxMoney = BigDecimal.ZERO;
-                    if(taxRate.compareTo(BigDecimal.ZERO) != 0) {
-                        taxMoney = taxRate.multiply(allPrice).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
-                    }
-                    BigDecimal taxLastMoney = allPrice.add(taxMoney);
-                    item.put("allPrice", allPrice);
-                    item.put("taxRate", taxRate);
-                    item.put("taxMoney", taxMoney);
-                    item.put("taxLastMoney", taxLastMoney);
-                    item.put("remark", remark);
-                    arr.add(item);
-                } else {
-                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_BARCODE_IS_NOT_EXIST_CODE,
-                            String.format(ExceptionConstants.DEPOT_ITEM_BARCODE_IS_NOT_EXIST_MSG, barCode));
-                }
-            }
-        }
-        map.put("rows", arr);
-        return map;
-    }
+    /**
+     * 解析excel表格数据
+     * @param batchNumbers 批次号
+     * @param detailList    数据明细
+     * @param prefixNo  单据类型
+     */
+    JSONObject parseMapByExcelData(String batchNumbers, List<Map<String, String>> detailList, String prefixNo) throws Exception;
 
-    public BigDecimal getLastUnitPriceByParam(Long organId, Long meId, String prefixNo) {
-        String type = "";
-        String subType = "";
-        if("XSDD".equals(prefixNo)) {
-            type = "其它";
-            subType = "销售订单";
-        } else if("XSCK".equals(prefixNo)) {
-            type = "出库";
-            subType = "销售";
-        } else if("XSTH".equals(prefixNo)) {
-            type = "入库";
-            subType = "销售退货";
-        } else if("QTCK".equals(prefixNo)) {
-            type = "出库";
-            subType = "其它";
-        }
-        return depotItemMapperEx.getLastUnitPriceByParam(organId, meId, type, subType);
-    }
+    BigDecimal getLastUnitPriceByParam(Long organId, Long meId, String prefixNo);
 
-    public BigDecimal getCurrentStockByParam(Long depotId, Long mId) {
-        BigDecimal stock = depotItemMapperEx.getCurrentStockByParam(depotId, mId);
-        return stock!=null? stock: BigDecimal.ZERO;
-    }
+    BigDecimal getCurrentStockByParam(Long depotId, Long mId);
 
-    /**
-     * 获取扩展信息
-     *
-     * @return
-     */
-    public String getOtherInfo(String[] mpArr, DepotItemVo4WithInfoEx diEx)throws Exception {
-        String materialOther = "";
-        for (int i = 0; i < mpArr.length; i++) {
-            if (mpArr[i].equals("自定义1")) {
-                materialOther = materialOther + ((diEx.getMOtherField1() == null || diEx.getMOtherField1().equals("")) ? "" : "(" + diEx.getMOtherField1() + ")");
-            }
-            if (mpArr[i].equals("自定义2")) {
-                materialOther = materialOther + ((diEx.getMOtherField2() == null || diEx.getMOtherField2().equals("")) ? "" : "(" + diEx.getMOtherField2() + ")");
-            }
-            if (mpArr[i].equals("自定义3")) {
-                materialOther = materialOther + ((diEx.getMOtherField3() == null || diEx.getMOtherField3().equals("")) ? "" : "(" + diEx.getMOtherField3() + ")");
-            }
-        }
-        return materialOther;
-    }
+    String getOtherInfo(String[] mpArr, DepotItemVo4WithInfoEx diEx)throws Exception;
 }

+ 6 - 0
src/main/java/com/jsh/erp/service/DepotService.java

@@ -268,6 +268,12 @@ public class DepotService {
         return id;
     }
 
+
+    /**
+     * 解析仓库列表
+     * @param depotId 仓库id
+     * @return 仓库id为空,返回当前用户有权限的仓库,不为空返回仓库id的集合
+     */
     public List<Long> parseDepotList(Long depotId) throws Exception {
         List<Long> depotList = new ArrayList<>();
         if(depotId !=null) {

+ 12 - 152
src/main/java/com/jsh/erp/service/LogService.java

@@ -1,176 +1,36 @@
 package com.jsh.erp.service;
 
 import com.alibaba.fastjson.JSONObject;
-import com.jsh.erp.constants.BusinessConstants;
+import com.baomidou.mybatisplus.extension.service.IService;
 import com.jsh.erp.datasource.entities.Log;
-import com.jsh.erp.datasource.entities.LogExample;
-import com.jsh.erp.datasource.mappers.LogMapper;
-import com.jsh.erp.datasource.mappers.LogMapperEx;
 import com.jsh.erp.datasource.vo.LogVo4List;
-import com.jsh.erp.exception.JshException;
-import com.jsh.erp.utils.PageUtils;
-import com.jsh.erp.utils.StringUtil;
-import com.jsh.erp.utils.Tools;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
-import java.util.Date;
 import java.util.List;
 
-import static com.jsh.erp.utils.Tools.getLocalIp;
+public interface LogService extends IService<Log> {
 
-@Service
-public class LogService {
-    private Logger logger = LoggerFactory.getLogger(LogService.class);
-    @Resource
-    private LogMapper logMapper;
+    Log getLog(long id)throws Exception;
 
-    @Resource
-    private LogMapperEx logMapperEx;
+    List<Log> getLog()throws Exception;
 
-    @Resource
-    private UserService userService;
-
-    @Resource
-    private RedisService redisService;
-
-    public Log getLog(long id)throws Exception {
-        Log result=null;
-        try{
-            result=logMapper.selectByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-
-    public List<Log> getLog()throws Exception {
-        LogExample example = new LogExample();
-        List<Log> list=null;
-        try{
-            list=logMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<LogVo4List> select(String operation, String userInfo, String clientIp, String tenantLoginName, String tenantType,
-                                   String beginTime, String endTime, String content)throws Exception {
-        List<LogVo4List> list=null;
-        try{
-            beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
-            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
-            PageUtils.startPage();
-            list=logMapperEx.selectByConditionLog(operation, userInfo, clientIp, tenantLoginName, tenantType, beginTime, endTime,
-                    content);
-            if (null != list) {
-                for (LogVo4List log : list) {
-                    log.setCreateTimeStr(Tools.getCenternTime(log.getCreateTime()));
-                }
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<LogVo4List> select(String operation, String userInfo, String clientIp, String tenantLoginName, String tenantType,
+                            String beginTime, String endTime, String content)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertLog(JSONObject obj, HttpServletRequest request) throws Exception{
-        Log log = JSONObject.parseObject(obj.toJSONString(), Log.class);
-        int result=0;
-        try{
-            result=logMapper.insertSelective(log);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int insertLog(JSONObject obj, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateLog(JSONObject obj, HttpServletRequest request)throws Exception {
-        Log log = JSONObject.parseObject(obj.toJSONString(), Log.class);
-        int result=0;
-        try{
-            result=logMapper.updateByPrimaryKeySelective(log);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int updateLog(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int deleteLog(Long id, HttpServletRequest request)throws Exception {
-        int result=0;
-        try{
-            result=logMapper.deleteByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int deleteLog(Long id, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteLog(String ids, HttpServletRequest request)throws Exception {
-        List<Long> idList = StringUtil.strToLongList(ids);
-        LogExample example = new LogExample();
-        example.createCriteria().andIdIn(idList);
-        int result=0;
-        try{
-            result=logMapper.deleteByExample(example);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int batchDeleteLog(String ids, HttpServletRequest request)throws Exception;
 
-    public void insertLog(String moduleName, String content, HttpServletRequest request)throws Exception{
-        try{
-            Long userId = userService.getUserId(request);
-            if(userId!=null) {
-                String clientIp = getLocalIp(request);
-                String createTime = Tools.getNow3();
-                Long count = logMapperEx.getCountByIpAndDate(userId, moduleName, clientIp, createTime);
-                if(count > 0) {
-                    //如果某个用户某个IP在同1秒内连续操作两遍,此时需要删除该redis记录,使其退出,防止恶意攻击
-                    redisService.deleteObjectByUserAndIp(userId, clientIp);
-                } else {
-                    Log log = new Log();
-                    log.setUserId(userId);
-                    log.setOperation(moduleName);
-                    log.setClientIp(getLocalIp(request));
-                    log.setCreateTime(new Date());
-                    Byte status = 0;
-                    log.setStatus(status);
-                    log.setContent(content);
-                    logMapper.insertSelective(log);
-                }
-            }
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-    }
+    void insertLog(String moduleName, String content, HttpServletRequest request)throws Exception;
 
-    public void insertLogWithUserId(Long userId, Long tenantId, String moduleName, String content, HttpServletRequest request)throws Exception{
-        try{
-            if(userId!=null) {
-                Log log = new Log();
-                log.setUserId(userId);
-                log.setOperation(moduleName);
-                log.setClientIp(getLocalIp(request));
-                log.setCreateTime(new Date());
-                Byte status = 0;
-                log.setStatus(status);
-                log.setContent(content);
-                log.setTenantId(tenantId);
-                logMapperEx.insertLogWithUserId(log);
-            }
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-    }
+    void insertLogWithUserId(Long userId, Long tenantId, String moduleName, String content, HttpServletRequest request)throws Exception;
 }

+ 2 - 1
src/main/java/com/jsh/erp/service/MaterialCategoryService.java

@@ -122,6 +122,7 @@ public class MaterialCategoryService {
         MaterialCategory materialCategory = JSONObject.parseObject(obj.toJSONString(), MaterialCategory.class);
         materialCategory.setCreateTime(new Date());
         materialCategory.setUpdateTime(new Date());
+        materialCategory.setSerialNo(materialCategoryMapper.selectMaxId()+10001);
         int result=0;
         try{
             result=materialCategoryMapper.insertSelective(materialCategory);
@@ -249,7 +250,7 @@ public class MaterialCategoryService {
         if(mc==null){
             return;
         }
-        if(StringUtil.isEmpty(mc.getSerialNo())){
+        if( mc.getSerialNo() < 0){
             return;
         }
         //根据商品类别编号查询商品类别

+ 22 - 371
src/main/java/com/jsh/erp/service/MaterialExtendService.java

@@ -1,406 +1,57 @@
 package com.jsh.erp.service;
 
-import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.baomidou.mybatisplus.core.toolkit.StringUtils;
-import com.jsh.erp.constants.BusinessConstants;
-import com.jsh.erp.constants.ExceptionConstants;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.jsh.erp.datasource.entities.Log;
 import com.jsh.erp.datasource.entities.MaterialExtend;
-import com.jsh.erp.datasource.entities.MaterialExtendExample;
-import com.jsh.erp.datasource.entities.User;
-import com.jsh.erp.datasource.mappers.MaterialExtendMapper;
-import com.jsh.erp.datasource.mappers.MaterialExtendMapperEx;
 import com.jsh.erp.datasource.vo.MaterialExtendVo4List;
-import com.jsh.erp.exception.BusinessRunTimeException;
-import com.jsh.erp.exception.JshException;
-import com.jsh.erp.utils.StringUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.Date;
 import java.util.List;
 
+public interface MaterialExtendService extends IService<MaterialExtend> {
+    MaterialExtend getMaterialExtend(long id)throws Exception;
 
-@Service
-public class MaterialExtendService {
-    private Logger logger = LoggerFactory.getLogger(MaterialExtendService.class);
+    List<MaterialExtendVo4List> getDetailList(Long materialId);
 
-    @Resource
-    private MaterialExtendMapper materialExtendMapper;
-    @Resource
-    private MaterialExtendMapperEx materialExtendMapperEx;
-    @Resource
-    private UserService userService;
-    @Resource
-    private RedisService redisService;
-    
-    public MaterialExtend getMaterialExtend(long id)throws Exception {
-        MaterialExtend result=null;
-        try{
-            result=materialExtendMapper.selectByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-    public List<MaterialExtendVo4List> getDetailList(Long materialId) {
-        List<MaterialExtendVo4List> list=null;
-        try{
-            list = materialExtendMapperEx.getDetailList(materialId);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<MaterialExtend> getListByMIds(List<Long> idList) {
-        List<MaterialExtend> meList = null;
-        try{
-            Long [] idArray= StringUtil.listToLongArray(idList);
-            if(idArray!=null && idArray.length>0) {
-                meList = materialExtendMapperEx.getListByMId(idArray);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return meList;
-    }
+    List<MaterialExtend> getListByMIds(List<Long> idList);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public String saveDetials(JSONObject obj, String sortList, Long materialId, String type) throws Exception {
-        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
-        JSONArray meArr = obj.getJSONArray("meList");
-        JSONArray insertedJson = new JSONArray();
-        JSONArray updatedJson = new JSONArray();
-        JSONArray deletedJson = obj.getJSONArray("meDeleteIdList");
-        JSONArray sortJson = JSONArray.parseArray(sortList);
-        if (null != meArr) {
-            if("insert".equals(type)){
-                for (int i = 0; i < meArr.size(); i++) {
-                    JSONObject tempJson = meArr.getJSONObject(i);
-                    insertedJson.add(tempJson);
-                }
-            } else if("update".equals(type)){
-                for (int i = 0; i < meArr.size(); i++) {
-                    JSONObject tempJson = meArr.getJSONObject(i);
-                    String tempId = tempJson.getString("id");
-                    if(tempId.length()>19){
-                        insertedJson.add(tempJson);
-                    } else {
-                        updatedJson.add(tempJson);
-                    }
-                }
-            }
-        }
-        if (null != deletedJson) {
-            StringBuffer bf=new StringBuffer();
-            for (int i = 0; i < deletedJson.size(); i++) {
-                bf.append(deletedJson.getString(i));
-                if(i<(deletedJson.size()-1)){
-                    bf.append(",");
-                }
-            }
-            this.batchDeleteMaterialExtendByIds(bf.toString(), request);
-        }
-        if (null != insertedJson) {
-            for (int i = 0; i < insertedJson.size(); i++) {
-                MaterialExtend materialExtend = new MaterialExtend();
-                JSONObject tempInsertedJson = JSONObject.parseObject(insertedJson.getString(i));
-                materialExtend.setMaterialId(materialId);
-                if (StringUtils.isNotEmpty(tempInsertedJson.getString("barCode"))) {
-                    int exist = checkIsBarCodeExist(0L, tempInsertedJson.getString("barCode"));
-                    if(exist>0) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_BARCODE_EXISTS_CODE,
-                                String.format(ExceptionConstants.MATERIAL_BARCODE_EXISTS_MSG,tempInsertedJson.getString("barCode")));
-                    } else {
-                        materialExtend.setBarCode(tempInsertedJson.getString("barCode"));
-                    }
-                }
-                if (StringUtils.isNotEmpty(tempInsertedJson.getString("commodityUnit"))) {
-                    materialExtend.setCommodityUnit(tempInsertedJson.getString("commodityUnit"));
-                }
-                if (tempInsertedJson.get("sku")!=null) {
-                    materialExtend.setSku(tempInsertedJson.getString("sku"));
-                }
-                if (StringUtils.isNotEmpty(tempInsertedJson.getString("purchaseDecimal"))) {
-                    materialExtend.setPurchaseDecimal(tempInsertedJson.getBigDecimal("purchaseDecimal"));
-                }
-                if (StringUtils.isNotEmpty(tempInsertedJson.getString("commodityDecimal"))) {
-                    materialExtend.setCommodityDecimal(tempInsertedJson.getBigDecimal("commodityDecimal"));
-                }
-                if (StringUtils.isNotEmpty(tempInsertedJson.getString("wholesaleDecimal"))) {
-                    materialExtend.setWholesaleDecimal(tempInsertedJson.getBigDecimal("wholesaleDecimal"));
-                }
-                if (StringUtils.isNotEmpty(tempInsertedJson.getString("lowDecimal"))) {
-                    materialExtend.setLowDecimal(tempInsertedJson.getBigDecimal("lowDecimal"));
-                }
-                this.insertMaterialExtend(materialExtend);
-            }
-        }
-        if (null != updatedJson) {
-            for (int i = 0; i < updatedJson.size(); i++) {
-                JSONObject tempUpdatedJson = JSONObject.parseObject(updatedJson.getString(i));
-                MaterialExtend materialExtend = new MaterialExtend();
-                materialExtend.setId(tempUpdatedJson.getLong("id"));
-                if (StringUtils.isNotEmpty(tempUpdatedJson.getString("barCode"))) {
-                    int exist = checkIsBarCodeExist(tempUpdatedJson.getLong("id"), tempUpdatedJson.getString("barCode"));
-                    if(exist>0) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_BARCODE_EXISTS_CODE,
-                                String.format(ExceptionConstants.MATERIAL_BARCODE_EXISTS_MSG,tempUpdatedJson.getString("barCode")));
-                    } else {
-                        materialExtend.setBarCode(tempUpdatedJson.getString("barCode"));
-                    }
-                }
-                if (StringUtils.isNotEmpty(tempUpdatedJson.getString("commodityUnit"))) {
-                    materialExtend.setCommodityUnit(tempUpdatedJson.getString("commodityUnit"));
-                }
-                if (tempUpdatedJson.get("sku")!=null) {
-                    materialExtend.setSku(tempUpdatedJson.getString("sku"));
-                }
-                if (StringUtils.isNotEmpty(tempUpdatedJson.getString("purchaseDecimal"))) {
-                    materialExtend.setPurchaseDecimal(tempUpdatedJson.getBigDecimal("purchaseDecimal"));
-                }
-                if (StringUtils.isNotEmpty(tempUpdatedJson.getString("commodityDecimal"))) {
-                    materialExtend.setCommodityDecimal(tempUpdatedJson.getBigDecimal("commodityDecimal"));
-                }
-                if (StringUtils.isNotEmpty(tempUpdatedJson.getString("wholesaleDecimal"))) {
-                    materialExtend.setWholesaleDecimal(tempUpdatedJson.getBigDecimal("wholesaleDecimal"));
-                }
-                if (StringUtils.isNotEmpty(tempUpdatedJson.getString("lowDecimal"))) {
-                    materialExtend.setLowDecimal(tempUpdatedJson.getBigDecimal("lowDecimal"));
-                }
-                this.updateMaterialExtend(materialExtend);
-                //如果金额为空,此处单独置空
-                materialExtendMapperEx.specialUpdatePrice(materialExtend);
-            }
-        }
-        //处理条码的排序,基本单位排第一个
-        if (null != sortJson && sortJson.size()>0) {
-            //此处为更新的逻辑
-            for (int i = 0; i < sortJson.size(); i++) {
-                JSONObject tempSortJson = JSONObject.parseObject(sortJson.getString(i));
-                MaterialExtend materialExtend = new MaterialExtend();
-                if(StringUtil.isExist(tempSortJson.get("id"))) {
-                    materialExtend.setId(tempSortJson.getLong("id"));
-                }
-                if(StringUtil.isExist(tempSortJson.get("defaultFlag"))) {
-                    materialExtend.setDefaultFlag(tempSortJson.getString("defaultFlag"));
-                }
-                this.updateMaterialExtend(materialExtend);
-            }
-        } else {
-            //新增的时候将第一条记录设置为默认基本单位
-            MaterialExtendExample example = new MaterialExtendExample();
-            example.createCriteria().andMaterialIdEqualTo(materialId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            List<MaterialExtend> meList = materialExtendMapper.selectByExample(example);
-            if(meList!=null) {
-                for(int i=0; i<meList.size(); i++) {
-                    MaterialExtend materialExtend = new MaterialExtend();
-                    materialExtend.setId(meList.get(i).getId());
-                    if(i==0) {
-                        materialExtend.setDefaultFlag("1"); //默认
-                    } else {
-                        materialExtend.setDefaultFlag("0"); //非默认
-                    }
-                    this.updateMaterialExtend(materialExtend);
-                }
-            }
-        }
-        return null;
-    }
+    String saveDetials(JSONObject obj, String sortList, Long materialId, String type) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertMaterialExtend(MaterialExtend materialExtend)throws Exception {
-        User user = userService.getCurrentUser();
-        materialExtend.setDeleteFlag(BusinessConstants.DELETE_FLAG_EXISTS);
-        materialExtend.setCreateTime(new Date());
-        materialExtend.setUpdateTime(new Date().getTime());
-        materialExtend.setCreateSerial(user.getLoginName());
-        materialExtend.setUpdateSerial(user.getLoginName());
-        int result =0;
-        try{
-            result= materialExtendMapper.insertSelective(materialExtend);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int insertMaterialExtend(MaterialExtend materialExtend)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateMaterialExtend(MaterialExtend materialExtend) throws Exception{
-        User user = userService.getCurrentUser();
-        materialExtend.setUpdateTime(System.currentTimeMillis());
-        materialExtend.setUpdateSerial(user.getLoginName());
-        int res =0;
-        try{
-            res= materialExtendMapper.updateByPrimaryKeySelective(materialExtend);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return res;
-    }
+    int updateMaterialExtend(MaterialExtend materialExtend) throws Exception;
 
-    public int checkIsBarCodeExist(Long id, String barCode)throws Exception {
-        MaterialExtendExample example = new MaterialExtendExample();
-        MaterialExtendExample.Criteria criteria = example.createCriteria();
-        criteria.andBarCodeEqualTo(barCode);
-        if (id > 0) {
-            criteria.andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        } else {
-            criteria.andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        }
-        List<MaterialExtend> list =null;
-        try{
-            list = materialExtendMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list==null?0:list.size();
-    }
+    int checkIsBarCodeExist(Long id, String barCode)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int deleteMaterialExtend(Long id, HttpServletRequest request)throws Exception {
-        int result =0;
-        MaterialExtend materialExtend = new MaterialExtend();
-        materialExtend.setId(id);
-        materialExtend.setDeleteFlag(BusinessConstants.DELETE_FLAG_DELETED);
-        Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request,"userId").toString());
-        User user = userService.getUser(userId);
-        materialExtend.setUpdateTime(new Date().getTime());
-        materialExtend.setUpdateSerial(user.getLoginName());
-        try{
-            result= materialExtendMapper.updateByPrimaryKeySelective(materialExtend);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int deleteMaterialExtend(Long id, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteMaterialExtendByIds(String ids, HttpServletRequest request) throws Exception{
-        String [] idArray=ids.split(",");
-        int result = 0;
-        try{
-            result = materialExtendMapperEx.batchDeleteMaterialExtendByIds(idArray);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int batchDeleteMaterialExtendByIds(String ids, HttpServletRequest request) throws Exception;
 
-    public int insertMaterialExtend(JSONObject obj, HttpServletRequest request) throws Exception{
-        MaterialExtend materialExtend = JSONObject.parseObject(obj.toJSONString(), MaterialExtend.class);
-        int result=0;
-        try{
-            result = materialExtendMapper.insertSelective(materialExtend);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int insertMaterialExtend(JSONObject obj, HttpServletRequest request) throws Exception;
 
-    public int updateMaterialExtend(JSONObject obj, HttpServletRequest request)throws Exception {
-        MaterialExtend materialExtend = JSONObject.parseObject(obj.toJSONString(), MaterialExtend.class);
-        int result=0;
-        try{
-            result = materialExtendMapper.updateByPrimaryKeySelective(materialExtend);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int updateMaterialExtend(JSONObject obj, HttpServletRequest request)throws Exception;
 
-    public List<MaterialExtend> getMaterialExtendByTenantAndTime(Long tenantId, Long lastTime, Long syncNum)throws Exception {
-        List<MaterialExtend> list=new ArrayList<MaterialExtend>();
-        try{
-            //先获取最大的时间戳,再查两个时间戳之间的数据,这样同步能够防止丢失数据(应为时间戳有重复)
-            Long maxTime = materialExtendMapperEx.getMaxTimeByTenantAndTime(tenantId, lastTime, syncNum);
-            if(tenantId!=null && lastTime!=null && maxTime!=null) {
-                MaterialExtendExample example = new MaterialExtendExample();
-                example.createCriteria().andTenantIdEqualTo(tenantId)
-                        .andUpdateTimeGreaterThan(lastTime)
-                        .andUpdateTimeLessThanOrEqualTo(maxTime);
-                list=materialExtendMapper.selectByExample(example);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    List<MaterialExtend> getMaterialExtendByTenantAndTime(Long tenantId, Long lastTime, Long syncNum)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public Long selectIdByMaterialIdAndDefaultFlag(Long materialId, String defaultFlag) {
-        Long id = 0L;
-        MaterialExtendExample example = new MaterialExtendExample();
-        example.createCriteria().andMaterialIdEqualTo(materialId).andDefaultFlagEqualTo(defaultFlag)
-                                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<MaterialExtend> list = materialExtendMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            id = list.get(0).getId();
-        }
-        return id;
-    }
+    Long selectIdByMaterialIdAndDefaultFlag(Long materialId, String defaultFlag);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public Long selectIdByMaterialIdAndBarCode(Long materialId, String barCode) {
-        Long id = 0L;
-        MaterialExtendExample example = new MaterialExtendExample();
-        example.createCriteria().andMaterialIdEqualTo(materialId).andBarCodeEqualTo(barCode)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<MaterialExtend> list = materialExtendMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            id = list.get(0).getId();
-        }
-        return id;
-    }
+    Long selectIdByMaterialIdAndBarCode(Long materialId, String barCode);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public List<MaterialExtend> getListByMaterialIdAndDefaultFlagAndBarCode(Long materialId, String defaultFlag, String barCode) {
-        MaterialExtendExample example = new MaterialExtendExample();
-        example.createCriteria().andMaterialIdEqualTo(materialId).andDefaultFlagEqualTo(defaultFlag).andBarCodeNotEqualTo(barCode)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        return materialExtendMapper.selectByExample(example);
-    }
+    List<MaterialExtend> getListByMaterialIdAndDefaultFlagAndBarCode(Long materialId, String defaultFlag, String barCode);
+
+    MaterialExtend getInfoByBarCode(String barCode)throws Exception;
 
-    public MaterialExtend getInfoByBarCode(String barCode)throws Exception {
-        MaterialExtendExample example = new MaterialExtendExample();
-        example.createCriteria().andBarCodeEqualTo(barCode)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<MaterialExtend> list = materialExtendMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            return list.get(0);
-        } else {
-            return null;
-        }
-    }
+    int getCountByManyBarCodeWithoutUs(String manyBarCode, String barCode);
 
-    /**
-     * 商品的副条码和数据库里面的商品条码存在重复(除自身商品之外)
-     * @param manyBarCode
-     * @param barCode
-     * @return
-     */
-    public int getCountByManyBarCodeWithoutUs(String manyBarCode, String barCode) {
-        MaterialExtendExample example = new MaterialExtendExample();
-        example.createCriteria().andBarCodeEqualTo(manyBarCode).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<MaterialExtend> list = materialExtendMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            for(MaterialExtend me: list) {
-                List<MaterialExtend> basicMeList = materialExtendMapperEx.getBasicInfoByMid(me.getMaterialId());
-                for(MaterialExtend basicMe: basicMeList) {
-                    if(basicMe!=null && !barCode.equals(basicMe.getBarCode())) {
-                        return 1;
-                    }
-                }
-            }
-        }
-        return 0;
-    }
+    MaterialExtend getInfoByBatchNumber(String batchNumber)throws Exception;
 }

+ 127 - 1400
src/main/java/com/jsh/erp/service/MaterialService.java

@@ -1,1453 +1,180 @@
 package com.jsh.erp.service;
 
-import com.alibaba.fastjson.JSON;
+
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.jsh.erp.constants.BusinessConstants;
-import com.jsh.erp.constants.ExceptionConstants;
+import com.baomidou.mybatisplus.extension.service.IService;
 import com.jsh.erp.datasource.entities.*;
-import com.jsh.erp.datasource.mappers.*;
-import com.jsh.erp.datasource.vo.MaterialVoSearch;
-import com.jsh.erp.exception.BusinessRunTimeException;
-import com.jsh.erp.exception.JshException;
-import com.jsh.erp.utils.*;
-import jxl.Sheet;
-import jxl.Workbook;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Service;
+import com.jsh.erp.datasource.vo.MaterialWarnListVo;
+import com.jsh.erp.utils.BaseResponseInfo;
 import org.springframework.transaction.annotation.Transactional;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
 import org.springframework.web.multipart.MultipartFile;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.File;
 import java.math.BigDecimal;
-import java.util.*;
-
-@Service
-public class MaterialService {
-    private Logger logger = LoggerFactory.getLogger(MaterialService.class);
-
-    @Resource
-    private MaterialMapper materialMapper;
-    @Resource
-    private MaterialExtendMapper materialExtendMapper;
-    @Resource
-    private MaterialMapperEx materialMapperEx;
-    @Resource
-    private MaterialCategoryMapperEx materialCategoryMapperEx;
-    @Resource
-    private MaterialExtendMapperEx materialExtendMapperEx;
-    @Resource
-    private LogService logService;
-    @Resource
-    private UserService userService;
-    @Resource
-    private DepotItemMapperEx depotItemMapperEx;
-    @Resource
-    private DepotItemService depotItemService;
-    @Resource
-    private MaterialCategoryService materialCategoryService;
-    @Resource
-    private UnitService unitService;
-    @Resource
-    private MaterialInitialStockMapper materialInitialStockMapper;
-    @Resource
-    private MaterialInitialStockMapperEx materialInitialStockMapperEx;
-    @Resource
-    private MaterialCurrentStockMapper materialCurrentStockMapper;
-    @Resource
-    private MaterialCurrentStockMapperEx materialCurrentStockMapperEx;
-    @Resource
-    private DepotService depotService;
-    @Resource
-    private MaterialExtendService materialExtendService;
-    @Resource
-    private SystemConfigService systemConfigService;
-
-    @Value(value="${file.uploadType}")
-    private Long fileUploadType;
-
-    public Material getMaterial(long id)throws Exception {
-        Material result=null;
-        try{
-            result=materialMapper.selectByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-
-    public List<Material> getMaterialListByIds(String ids)throws Exception {
-        List<Long> idList = StringUtil.strToLongList(ids);
-        List<Material> list = new ArrayList<>();
-        try{
-            MaterialExample example = new MaterialExample();
-            example.createCriteria().andIdIn(idList);
-            list = materialMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Material> getMaterial() throws Exception{
-        MaterialExample example = new MaterialExample();
-        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<Material> list=null;
-        try{
-            list=materialMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<MaterialVo4Unit> select(String materialParam, String standard, String model, String color, String brand, String mfrs,
-                                        String materialOther, String weight, String expiryNum, String enableSerialNumber,
-                                        String enableBatchNumber, String position, String enabled, String remark, String categoryId,
-                                        String mpList)
-            throws Exception{
-        String[] mpArr = new String[]{};
-        if(StringUtil.isNotEmpty(mpList)){
-            mpArr= mpList.split(",");
-        }
-        List<MaterialVo4Unit> list = new ArrayList<>();
-        try{
-            List<Long> idList = new ArrayList<>();
-            if(StringUtil.isNotEmpty(categoryId)){
-                idList = getListByParentId(Long.parseLong(categoryId));
-            }
-            PageUtils.startPage();
-            list= materialMapperEx.selectByConditionMaterial(materialParam, standard, model, color, brand, mfrs, materialOther, weight, expiryNum,
-                    enableSerialNumber, enableBatchNumber, position, enabled, remark, idList, mpList);
-            if (null != list && list.size()>0) {
-                Map<Long,BigDecimal> initialStockMap = getInitialStockMapByMaterialList(list);
-                Map<Long,BigDecimal> currentStockMap = getCurrentStockMapByMaterialList(list);
-                for (MaterialVo4Unit m : list) {
-                    if(fileUploadType == 2) {
-                        m.setImgSmall("small");
-                        m.setImgLarge("large");
-                    }
-                    m.setMaterialOther(getMaterialOtherByParam(mpArr, m));
-                    m.setInitialStock(initialStockMap.get(m.getId())!=null? initialStockMap.get(m.getId()): BigDecimal.ZERO);
-                    m.setBigUnitInitialStock(getBigUnitStock(m.getInitialStock(), m.getUnitId()));
-                    m.setStock(currentStockMap.get(m.getId())!=null? currentStockMap.get(m.getId()): BigDecimal.ZERO);
-                    m.setBigUnitStock(getBigUnitStock(m.getStock(), m.getUnitId()));
-                }
-            }
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+import java.util.List;
+import java.util.Map;
 
-    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertMaterial(JSONObject obj, HttpServletRequest request)throws Exception {
-        Material m = JSONObject.parseObject(obj.toJSONString(), Material.class);
-        m.setEnabled(true);
-        try{
-            materialMapperEx.insertSelectiveEx(m);
-            Long mId = m.getId();
-            materialExtendService.saveDetials(obj, obj.getString("sortList"), mId, "insert");
-            if(obj.get("stock")!=null) {
-                JSONArray stockArr = obj.getJSONArray("stock");
-                for (int i = 0; i < stockArr.size(); i++) {
-                    JSONObject jsonObj = stockArr.getJSONObject(i);
-                    if(jsonObj.get("id")!=null && jsonObj.get("initStock")!=null) {
-                        String number = jsonObj.getString("initStock");
-                        BigDecimal lowSafeStock = null;
-                        BigDecimal highSafeStock = null;
-                        if(jsonObj.get("lowSafeStock")!=null) {
-                            lowSafeStock = jsonObj.getBigDecimal("lowSafeStock");
-                        }
-                        if(jsonObj.get("highSafeStock")!=null) {
-                            highSafeStock = jsonObj.getBigDecimal("highSafeStock");
-                        }
-                        Long depotId = jsonObj.getLong("id");
-                        if(StringUtil.isNotEmpty(number) && Double.parseDouble(number)>0 || lowSafeStock!=null || highSafeStock!=null) {
-                            insertInitialStockByMaterialAndDepot(depotId, mId, parseBigDecimalEx(number), lowSafeStock, highSafeStock);
-                            insertCurrentStockByMaterialAndDepot(depotId, mId, parseBigDecimalEx(number));
-                        }
-                    }
-                }
-            }
-            logService.insertLog("商品",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(m.getName()).toString(), request);
-            return 1;
-        }
-        catch (BusinessRunTimeException ex) {
-            throw new BusinessRunTimeException(ex.getCode(), ex.getMessage());
-        }
-        catch(Exception e){
-            JshException.writeFail(logger, e);
-            return 0;
-        }
-    }
+public interface MaterialService extends IService<Material> {
+    Material getMaterial(long id)throws Exception;
+
+    List<Material> getMaterialListByIds(String ids)throws Exception;
 
+    List<Material> getMaterial() throws Exception;
+
+    List<MaterialVo4Unit> select(String materialParam, String standard, String model, String color, String brand, String mfrs,
+                                 String materialOther, String weight, String expiryNum, String enableSerialNumber,
+                                 String enableBatchNumber, String position, String enabled, String remark, String categoryId,
+                                 String mpList)
+            throws Exception;
+
+    /**
+     * 新增商品
+     * @param obj
+     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateMaterial(JSONObject obj, HttpServletRequest request) throws Exception{
-        Material material = JSONObject.parseObject(obj.toJSONString(), Material.class);
-        try{
-            materialMapper.updateByPrimaryKeySelective(material);
-            if(material.getUnitId() == null) {
-                materialMapperEx.setUnitIdToNull(material.getId());
-            }
-            if(material.getExpiryNum() == null) {
-                materialMapperEx.setExpiryNumToNull(material.getId());
-            }
-            materialExtendService.saveDetials(obj, obj.getString("sortList"),material.getId(), "update");
-            if(obj.get("stock")!=null) {
-                JSONArray stockArr = obj.getJSONArray("stock");
-                for (int i = 0; i < stockArr.size(); i++) {
-                    JSONObject jsonObj = stockArr.getJSONObject(i);
-                    if (jsonObj.get("id") != null && jsonObj.get("initStock") != null) {
-                        String number = jsonObj.getString("initStock");
-                        BigDecimal lowSafeStock = null;
-                        BigDecimal highSafeStock = null;
-                        if(jsonObj.get("lowSafeStock")!=null) {
-                            lowSafeStock = jsonObj.getBigDecimal("lowSafeStock");
-                        }
-                        if(jsonObj.get("highSafeStock")!=null) {
-                            highSafeStock = jsonObj.getBigDecimal("highSafeStock");
-                        }
-                        Long depotId = jsonObj.getLong("id");
-                        //初始库存-先清除再插入
-                        MaterialInitialStockExample example = new MaterialInitialStockExample();
-                        example.createCriteria().andMaterialIdEqualTo(material.getId()).andDepotIdEqualTo(depotId);
-                        materialInitialStockMapper.deleteByExample(example);
-                        if (StringUtil.isNotEmpty(number) || lowSafeStock!=null || highSafeStock!=null) {
-                            insertInitialStockByMaterialAndDepot(depotId, material.getId(), parseBigDecimalEx(number), lowSafeStock, highSafeStock);
-                        }
-                        //更新当前库存
-                        depotItemService.updateCurrentStockFun(material.getId(), depotId);
-                    }
-                }
-            }
-            logService.insertLog("商品",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(material.getName()).toString(), request);
-            return 1;
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-            return 0;
-        }
-    }
+    int insertMaterial(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int deleteMaterial(Long id, HttpServletRequest request)throws Exception {
-        return batchDeleteMaterialByIds(id.toString());
-    }
+    int updateMaterial(JSONObject obj, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteMaterial(String ids, HttpServletRequest request)throws Exception {
-        return batchDeleteMaterialByIds(ids);
-    }
+    int deleteMaterial(Long id, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteMaterialByIds(String ids) throws Exception{
-        String [] idArray=ids.split(",");
-        //校验单据子表	jsh_depot_item
-        List<DepotItem> depotItemList =null;
-        try{
-            depotItemList=  depotItemMapperEx.getDepotItemListListByMaterialIds(idArray);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        if(depotItemList!=null&&depotItemList.size()>0){
-            logger.error("异常码[{}],异常提示[{}],参数,MaterialIds[{}]",
-                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
-            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
-                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
-        }
-        //记录日志
-        StringBuffer sb = new StringBuffer();
-        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
-        //路径列表
-        List<String> pathList = new ArrayList<>();
-        List<Material> list = getMaterialListByIds(ids);
-        for(Material material: list){
-            sb.append("[").append(material.getName()).append("]");
-            if(StringUtil.isNotEmpty(material.getImgName())) {
-                pathList.add(material.getImgName());
-            }
-        }
-        logService.insertLog("商品", sb.toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        User userInfo=userService.getCurrentUser();
-        //校验通过执行删除操作
-        try{
-            //逻辑删除商品
-            materialMapperEx.batchDeleteMaterialByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
-            //逻辑删除商品价格扩展
-            materialExtendMapperEx.batchDeleteMaterialExtendByMIds(idArray);
-            //逻辑删除文件
-            systemConfigService.deleteFileByPathList(pathList);
-            return 1;
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-            return 0;
-        }
-    }
-
-    public int checkIsNameExist(Long id, String name)throws Exception {
-        MaterialExample example = new MaterialExample();
-        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<Material> list =null;
-        try{
-            list=  materialMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list==null?0:list.size();
-    }
-
-    public int checkIsExist(Long id, String name, String model, String color, String standard, String mfrs,
-                            String otherField1, String otherField2, String otherField3, String unit, Long unitId)throws Exception {
-        return materialMapperEx.checkIsExist(id, name, model, color, standard, mfrs, otherField1,
-                otherField2, otherField3, unit, unitId);
-    }
+    int batchDeleteMaterial(String ids, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchSetStatus(Boolean status, String ids)throws Exception {
-        logService.insertLog("商品",
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(ids).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        List<Long> materialIds = StringUtil.strToLongList(ids);
-        Material material = new Material();
-        material.setEnabled(status);
-        MaterialExample example = new MaterialExample();
-        example.createCriteria().andIdIn(materialIds);
-        int result =0;
-        try{
-            result=  materialMapper.updateByExampleSelective(material, example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-
-    public Unit findUnit(Long mId)throws Exception{
-        Unit unit = new Unit();
-        try{
-            List<Unit> list = materialMapperEx.findUnitList(mId);
-            if(list!=null && list.size()>0) {
-                unit = list.get(0);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return unit;
-    }
-
-    public List<MaterialVo4Unit> findById(Long id)throws Exception{
-        List<MaterialVo4Unit> list =null;
-        try{
-            list=  materialMapperEx.findById(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<MaterialVo4Unit> findByIdWithBarCode(Long meId)throws Exception{
-        List<MaterialVo4Unit> list =null;
-        try{
-            list=  materialMapperEx.findByIdWithBarCode(meId);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Long> getListByParentId(Long parentId) {
-        List<Long> idList = new ArrayList<Long>();
-        List<MaterialCategory> list = materialCategoryMapperEx.getListByParentId(parentId);
-        idList.add(parentId);
-        if(list!=null && list.size()>0) {
-            getIdListByParentId(idList, parentId);
-        }
-        return idList;
-    }
-
-    public List<Long> getIdListByParentId(List<Long> idList, Long parentId){
-        List<MaterialCategory> list = materialCategoryMapperEx.getListByParentId(parentId);
-        if(list!=null && list.size()>0) {
-            for(MaterialCategory mc : list){
-                idList.add(mc.getId());
-                getIdListByParentId(idList, mc.getId());
-            }
-        }
-        return idList;
-    }
-
-    public JSONArray getMaterialByParam(String materialParam) {
-        JSONArray arr = new JSONArray();
-        List<MaterialVoSearch> list = materialMapperEx.getMaterialByParam(materialParam);
-        for(MaterialVoSearch item: list) {
-            JSONObject obj = new JSONObject();
-            StringBuilder sb = new StringBuilder();
-            sb.append(item.getBarCode());
-            sb.append("_").append(item.getName());
-            if(StringUtil.isNotEmpty(item.getMnemonic())) {
-                sb.append("(").append(item.getMnemonic()).append(")");
-            }
-            if(StringUtil.isNotEmpty(item.getStandard())) {
-                sb.append("(").append(item.getStandard()).append(")");
-            }
-            if(StringUtil.isNotEmpty(item.getModel())) {
-                sb.append("(").append(item.getModel()).append(")");
-            }
-            if(StringUtil.isNotEmpty(item.getColor())) {
-                sb.append("(").append(item.getColor()).append(")");
-            }
-            if(StringUtil.isNotEmpty(item.getUnit())) {
-                sb.append("(").append(item.getUnit()).append(")");
-            }
-            obj.put("barCode", item.getBarCode());
-            obj.put("materialStr", sb.toString());
-            arr.add(obj);
-        }
-        return arr;
-    }
-
-    public List<MaterialVo4Unit> findBySelectWithBarCode(Long categoryId, String q, String standardOrModel, String color,
-                                                         String brand, String mfrs, String enableSerialNumber, String enableBatchNumber,
-                                                         Integer offset, Integer rows) throws Exception{
-        List<MaterialVo4Unit> list =null;
-        try{
-            List<Long> idList = new ArrayList<>();
-            if(categoryId!=null){
-                Long parentId = categoryId;
-                idList = getListByParentId(parentId);
-            }
-            if(StringUtil.isNotEmpty(q)) {
-                q = q.replace("'", "");
-                q = q.trim();
-            }
-            list=  materialMapperEx.findBySelectWithBarCode(idList, q, standardOrModel, color, brand, mfrs,
-                    enableSerialNumber, enableBatchNumber, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public int findBySelectWithBarCodeCount(Long categoryId, String q, String standardOrModel, String color,
-                                            String brand, String mfrs, String enableSerialNumber, String enableBatchNumber) throws Exception{
-        int result=0;
-        try{
-            List<Long> idList = new ArrayList<>();
-            if(categoryId!=null){
-                Long parentId = categoryId;
-                idList = getListByParentId(parentId);
-            }
-            if(StringUtil.isNotEmpty(q)) {
-                q = q.replace("'", "");
-            }
-            result = materialMapperEx.findBySelectWithBarCodeCount(idList, q, standardOrModel, color, brand, mfrs,
-                    enableSerialNumber, enableBatchNumber);
-        }catch(Exception e){
-            logger.error("异常码[{}],异常提示[{}],异常[{}]",
-                    ExceptionConstants.DATA_READ_FAIL_CODE,ExceptionConstants.DATA_READ_FAIL_MSG,e);
-            throw new BusinessRunTimeException(ExceptionConstants.DATA_READ_FAIL_CODE,
-                    ExceptionConstants.DATA_READ_FAIL_MSG);
-        }
-        return result;
-    }
-
-    public void exportExcel(String categoryId, String materialParam, String color, String materialOther, String weight,
-                                             String expiryNum, String enabled, String enableSerialNumber, String enableBatchNumber,
-                                             String remark, HttpServletResponse response)throws Exception {
-        List<Long> idList = new ArrayList<>();
-        if(StringUtil.isNotEmpty(categoryId)){
-            idList = getListByParentId(Long.parseLong(categoryId));
-        }
-        //查询商品主条码相关列表
-        List<MaterialVo4Unit> dataList = materialMapperEx.exportExcel(materialParam, color, materialOther, weight, expiryNum, enabled, enableSerialNumber,
-                enableBatchNumber, remark, idList);
-        //查询商品副条码相关列表
-        Map<Long, MaterialExtend> otherMaterialMap = new HashMap<>();
-        List<MaterialExtend> otherDataList = materialMapperEx.getOtherMaterialList();
-        for(MaterialExtend me: otherDataList) {
-            //遇到多个副条码的情况,只加第一个
-            otherMaterialMap.putIfAbsent(me.getMaterialId(), me);
-        }
-        String nameStr = "名称*,规格,型号,颜色,品牌,类别,基础重量(kg),保质期(天),基本单位*,副单位,基本条码*,副条码,比例,多属性," +
-                "采购价,零售价,销售价,最低售价,状态*,序列号,批号,仓位货架,制造商,自定义1,自定义2,自定义3,备注";
-        List<String> nameList = StringUtil.strToStringList(nameStr);
-        //仓库列表
-        List<Depot> depotList = depotService.getAllList();
-        if (nameList != null) {
-            for(Depot depot: depotList) {
-                nameList.add(depot.getName());
-            }
-        }
-        //期初库存缓存
-        List<MaterialInitialStock> misList = materialInitialStockMapperEx.getListExceptZero();
-        Map<String, BigDecimal> misMap = new HashMap<>();
-        if (misList != null) {
-            for (MaterialInitialStock mis : misList) {
-                misMap.put(mis.getMaterialId() + "_" + mis.getDepotId(), mis.getNumber());
-            }
-        }
-        String[] names = StringUtil.listToStringArray(nameList);
-        String title = "商品信息";
-        List<String[]> objects = new ArrayList<>();
-        if (null != dataList) {
-            for (MaterialVo4Unit m : dataList) {
-                String[] objs = new String[names.length];
-                objs[0] = m.getName();
-                objs[1] = m.getStandard();
-                objs[2] = m.getModel();
-                objs[3] = m.getColor();
-                objs[4] = m.getBrand();
-                objs[5] = m.getCategoryName();
-                objs[6] = m.getWeight() == null ? "" : m.getWeight().setScale(3, BigDecimal.ROUND_HALF_UP).toString();
-                objs[7] = m.getExpiryNum() == null ? "" : m.getExpiryNum().toString();
-                objs[8] = m.getCommodityUnit();
-                objs[9] = otherMaterialMap.get(m.getId()) == null ? "" : otherMaterialMap.get(m.getId()).getCommodityUnit();
-                objs[10] = m.getmBarCode();
-                objs[11] = otherMaterialMap.get(m.getId()) == null ? "" : otherMaterialMap.get(m.getId()).getBarCode();
-                objs[12] = m.getRatio() == null ? "" : m.getRatio().toString();
-                objs[13] = m.getSku();
-                objs[14] = m.getPurchaseDecimal() == null ? "" : m.getPurchaseDecimal().setScale(3, BigDecimal.ROUND_HALF_UP).toString();
-                objs[15] = m.getCommodityDecimal() == null ? "" : m.getCommodityDecimal().setScale(3, BigDecimal.ROUND_HALF_UP).toString();
-                objs[16] = m.getWholesaleDecimal() == null ? "" : m.getWholesaleDecimal().setScale(3, BigDecimal.ROUND_HALF_UP).toString();
-                objs[17] = m.getLowDecimal() == null ? "" : m.getLowDecimal().setScale(3, BigDecimal.ROUND_HALF_UP).toString();
-                objs[18] = m.getEnabled() ? "1" : "0";
-                objs[19] = m.getEnableSerialNumber();
-                objs[20] = m.getEnableBatchNumber();
-                objs[21] = m.getPosition();
-                objs[22] = m.getMfrs();
-                objs[23] = m.getOtherField1();
-                objs[24] = m.getOtherField2();
-                objs[25] = m.getOtherField3();
-                objs[26] = m.getRemark();
-                //仓库期初库存
-                int i = 27;
-                for(Depot depot: depotList) {
-                    BigDecimal number = misMap.get(m.getId() + "_" + depot.getId());
-                    objs[i] = number == null ? "0" : number.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
-                    i++;
-                }
-                objects.add(objs);
-            }
-        }
-        File file = ExcelUtils.exportObjectsOneSheet(title, "*导入时本行内容请勿删除,切记!", names, title, objects);
-        ExcelUtils.downloadExcel(file, file.getName(), response);
-    }
+    int batchDeleteMaterialByIds(String ids) throws Exception;
+
+    int checkIsNameExist(Long id, String name)throws Exception;
+
+    int checkIsExist(Long id, String name, String model, String color, String standard, String mfrs,
+                     String otherField1, String otherField2, String otherField3, String unit, Long unitId)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public BaseResponseInfo importExcel(MultipartFile file, HttpServletRequest request) throws Exception {
-        BaseResponseInfo info = new BaseResponseInfo();
-        try {
-            Long beginTime = System.currentTimeMillis();
-            //文件扩展名只能为xls
-            String fileName = file.getOriginalFilename();
-            if(StringUtil.isNotEmpty(fileName)) {
-                String fileExt = fileName.substring(fileName.indexOf(".")+1);
-                if(!"xls".equals(fileExt)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXTENSION_ERROR_CODE,
-                            ExceptionConstants.MATERIAL_EXTENSION_ERROR_MSG);
-                }
-            }
-            Workbook workbook = Workbook.getWorkbook(file.getInputStream());
-            Sheet src = workbook.getSheet(0);
-            //获取真实的行数,剔除掉空白行
-            int rightRows = ExcelUtils.getRightRows(src);
-            List<Depot> depotList= depotService.getDepot();
-            int depotCount = depotList.size();
-            Map<String, Long> depotMap = parseDepotToMap(depotList);
-            User user = userService.getCurrentUser();
-            List<MaterialWithInitStock> mList = new ArrayList<>();
-            //单次导入超出1000条
-            if(rightRows > 1002) {
-                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_IMPORT_OVER_LIMIT_CODE,
-                        String.format(ExceptionConstants.MATERIAL_IMPORT_OVER_LIMIT_MSG));
-            }
-            for (int i = 2; i < rightRows; i++) {
-                String name = ExcelUtils.getContent(src, i, 0); //名称
-                String standard = ExcelUtils.getContent(src, i, 1); //规格
-                String model = ExcelUtils.getContent(src, i, 2); //型号
-                String color = ExcelUtils.getContent(src, i, 3); //颜色
-                String brand = ExcelUtils.getContent(src, i, 4); //品牌
-                String categoryName = ExcelUtils.getContent(src, i, 5); //类别
-                String weight = ExcelUtils.getContent(src, i, 6); //基础重量(kg)
-                String expiryNum = ExcelUtils.getContent(src, i, 7); //保质期(天)
-                String unit = ExcelUtils.getContent(src, i, 8); //基本单位
-                //名称为空
-                if(StringUtil.isEmpty(name)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NAME_EMPTY_CODE,
-                            String.format(ExceptionConstants.MATERIAL_NAME_EMPTY_MSG, i+1));
-                }
-                //名称长度超出
-                if(name.length()>100) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NAME_OVER_CODE,
-                            String.format(ExceptionConstants.MATERIAL_NAME_OVER_MSG, i+1));
-                }
-                //规格长度超出
-                if(StringUtil.isNotEmpty(standard) && standard.length()>100) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STANDARD_OVER_CODE,
-                            String.format(ExceptionConstants.MATERIAL_STANDARD_OVER_MSG, i+1));
-                }
-                //型号长度超出
-                if(StringUtil.isNotEmpty(model) && model.length()>100) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_MODEL_OVER_CODE,
-                            String.format(ExceptionConstants.MATERIAL_MODEL_OVER_MSG, i+1));
-                }
-                //基本单位为空
-                if(StringUtil.isEmpty(unit)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_UNIT_EMPTY_CODE,
-                            String.format(ExceptionConstants.MATERIAL_UNIT_EMPTY_MSG, i+1));
-                }
-                MaterialWithInitStock m = new MaterialWithInitStock();
-                m.setName(name);
-                m.setStandard(standard);
-                m.setModel(model);
-                m.setColor(color);
-                m.setBrand(brand);
-                //通过名称生成助记码
-                m.setMnemonic(PinYinUtil.getFirstLettersLo(name));
-                Long categoryId = materialCategoryService.getCategoryIdByName(categoryName);
-                if(null!=categoryId){
-                    m.setCategoryId(categoryId);
-                }
-                if(StringUtil.isNotEmpty(weight)) {
-                    //校验基础重量是否是数字(含小数)
-                    if(!StringUtil.isPositiveBigDecimal(weight)) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_WEIGHT_NOT_DECIMAL_CODE,
-                                String.format(ExceptionConstants.MATERIAL_WEIGHT_NOT_DECIMAL_MSG, i+1));
-                    }
-                    m.setWeight(new BigDecimal(weight));
-                }
-                if(StringUtil.isNotEmpty(expiryNum)) {
-                    //校验保质期是否是正整数
-                    if(!StringUtil.isPositiveLong(expiryNum)) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXPIRY_NUM_NOT_INTEGER_CODE,
-                                String.format(ExceptionConstants.MATERIAL_EXPIRY_NUM_NOT_INTEGER_MSG, i+1));
-                    }
-                    m.setExpiryNum(Integer.parseInt(expiryNum));
-                }
-                String manyUnit = ExcelUtils.getContent(src, i, 9); //副单位
-                String barCode = ExcelUtils.getContent(src, i, 10); //基础条码
-                String manyBarCode = ExcelUtils.getContent(src, i, 11); //副条码
-                String ratio = ExcelUtils.getContent(src, i, 12); //比例
-                String sku = ExcelUtils.getContent(src, i, 13); //多属性
-                String purchaseDecimal = ExcelUtils.getContent(src, i, 14); //采购价
-                String commodityDecimal = ExcelUtils.getContent(src, i, 15); //零售价
-                String wholesaleDecimal = ExcelUtils.getContent(src, i, 16); //销售价
-                String lowDecimal = ExcelUtils.getContent(src, i, 17); //最低售价
-                String enabled = ExcelUtils.getContent(src, i, 18); //状态
-                String enableSerialNumber = ExcelUtils.getContent(src, i, 19); //序列号
-                String enableBatchNumber = ExcelUtils.getContent(src, i, 20); //批号
-                String position = ExcelUtils.getContent(src, i, 21); //仓位货架
-                String mfrs = ExcelUtils.getContent(src, i, 22); //制造商
-                String otherField1 = ExcelUtils.getContent(src, i, 23); //自定义1
-                String otherField2 = ExcelUtils.getContent(src, i, 24); //自定义2
-                String otherField3 = ExcelUtils.getContent(src, i, 25); //自定义3
-                String remark = ExcelUtils.getContent(src, i, 26); //备注
-                m.setPosition(StringUtil.isNotEmpty(position)?position:null);
-                m.setMfrs(StringUtil.isNotEmpty(mfrs)?mfrs:null);
-                m.setOtherField1(StringUtil.isNotEmpty(otherField1)?otherField1:null);
-                m.setOtherField2(StringUtil.isNotEmpty(otherField2)?otherField2:null);
-                m.setOtherField3(StringUtil.isNotEmpty(otherField3)?otherField3:null);
-                m.setRemark(remark);
-                //状态格式错误
-                if(!"1".equals(enabled) && !"0".equals(enabled)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_ENABLED_ERROR_CODE,
-                            String.format(ExceptionConstants.MATERIAL_ENABLED_ERROR_MSG, i+1));
-                }
-                //基本条码为空
-                if(StringUtil.isEmpty(barCode)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_BARCODE_EMPTY_CODE,
-                            String.format(ExceptionConstants.MATERIAL_BARCODE_EMPTY_MSG, i+1));
-                }
-                //校验基本条码长度为4到40位
-                if(!StringUtil.checkBarCodeLength(barCode)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_BARCODE_LENGTH_ERROR_CODE,
-                            String.format(ExceptionConstants.MATERIAL_BARCODE_LENGTH_ERROR_MSG, barCode));
-                }
-                //校验副条码长度为4到40位
-                if(StringUtil.isNotEmpty(manyBarCode) && !StringUtil.checkBarCodeLength(manyBarCode)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_BARCODE_LENGTH_ERROR_CODE,
-                            String.format(ExceptionConstants.MATERIAL_BARCODE_LENGTH_ERROR_MSG, manyBarCode));
-                }
-                //批量校验excel中有无重复商品,是指名称、规格、型号、颜色、单位、多属性
-                batchCheckExistMaterialListByParam(mList, name, standard, model, color, unit, sku);
-                //批量校验excel中有无重复条码(1-文档自身校验,2-和数据库里面的商品校验)
-                batchCheckExistBarCodeByParam(mList, barCode, manyBarCode);
-                JSONObject materialExObj = new JSONObject();
-                JSONObject basicObj = new JSONObject();
-                basicObj.put("barCode", barCode);
-                basicObj.put("commodityUnit", unit);
-                basicObj.put("sku", sku);
-                basicObj.put("purchaseDecimal", purchaseDecimal);
-                basicObj.put("commodityDecimal", commodityDecimal);
-                basicObj.put("wholesaleDecimal", wholesaleDecimal);
-                basicObj.put("lowDecimal", lowDecimal);
-                materialExObj.put("basic", basicObj);
-                if(StringUtil.isNotEmpty(manyUnit) && StringUtil.isNotEmpty(ratio)){ //多单位
-                    //校验比例是否是数字(含小数)
-                    if(!StringUtil.isPositiveBigDecimal(ratio.trim())) {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_RATIO_NOT_INTEGER_CODE,
-                                String.format(ExceptionConstants.MATERIAL_RATIO_NOT_INTEGER_MSG, i+1));
-                    }
-                    Long unitId = unitService.getUnitIdByParam(unit, manyUnit, new BigDecimal(ratio.trim()));
-                    if(unitId != null) {
-                        m.setUnitId(unitId);
-                        m.setUnit("");
-                    } else {
-                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_UNIT_MATE_CODE,
-                                String.format(ExceptionConstants.MATERIAL_UNIT_MATE_MSG, manyBarCode));
-                    }
-                    JSONObject otherObj = new JSONObject();
-                    otherObj.put("barCode", manyBarCode);
-                    otherObj.put("commodityUnit", manyUnit);
-                    otherObj.put("purchaseDecimal", parsePrice(purchaseDecimal,ratio));
-                    otherObj.put("commodityDecimal", parsePrice(commodityDecimal,ratio));
-                    otherObj.put("wholesaleDecimal", parsePrice(wholesaleDecimal,ratio));
-                    otherObj.put("lowDecimal", parsePrice(lowDecimal,ratio));
-                    materialExObj.put("other", otherObj);
-                } else {
-                    m.setUnit(unit);
-                    m.setUnitId(null);
-                }
-                m.setMaterialExObj(materialExObj);
-                m.setEnabled("1".equals(enabled));
-                if(StringUtil.isNotEmpty(enableSerialNumber) && "1".equals(enableSerialNumber)) {
-                    m.setEnableSerialNumber("1");
-                } else {
-                    m.setEnableSerialNumber("0");
-                }
-                if(StringUtil.isNotEmpty(enableBatchNumber) && "1".equals(enableBatchNumber)) {
-                    m.setEnableBatchNumber("1");
-                } else {
-                    m.setEnableBatchNumber("0");
-                }
-                if("1".equals(enableSerialNumber) && "1".equals(enableBatchNumber)) {
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_ENABLE_MUST_ONE_CODE,
-                            String.format(ExceptionConstants.MATERIAL_ENABLE_MUST_ONE_MSG, barCode));
-                }
-                m.setStockMap(getStockMapCache(src, depotCount, depotMap, i));
-                mList.add(m);
-            }
-            List<Long> deleteInitialStockMaterialIdList = new ArrayList<>();
-            List<Long> deleteCurrentStockMaterialIdList = new ArrayList<>();
-            List<MaterialInitialStock> insertInitialStockMaterialList = new ArrayList<>();
-            List<MaterialCurrentStock> insertCurrentStockMaterialList = new ArrayList<>();
-            //防止初始库存和当前库存出现重复
-            Map<String, String> materialDepotInitialMap = new HashMap<>();
-            Map<String, String> materialDepotCurrentMap = new HashMap<>();
-            for(MaterialWithInitStock m: mList) {
-                Long mId = 0L;
-                //判断该商品是否存在,如果不存在就新增,如果存在就更新
-                String basicBarCode = getBasicBarCode(m);
-                List<Material> materials = getMaterialListByParam(m.getName(),m.getStandard(),m.getModel(),m.getColor(),m.getUnit(),m.getUnitId(), basicBarCode);
-                if(materials.size() == 0) {
-                    materialMapperEx.insertSelectiveEx(m);
-                    mId = m.getId();
-                } else {
-                    mId = materials.get(0).getId();
-                    String materialJson = JSON.toJSONString(m);
-                    Material material = JSONObject.parseObject(materialJson, Material.class);
-                    material.setId(mId);
-                    materialMapper.updateByPrimaryKeySelective(material);
-                    //更新多单位
-                    if(material.getUnitId() == null) {
-                        materialMapperEx.setUnitIdToNull(material.getId());
-                    }
-                    //如果之前有保质期,则更新保质期
-                    if(materials.get(0).getExpiryNum()!=null && material.getExpiryNum() == null) {
-                        materialMapperEx.setExpiryNumToNull(material.getId());
-                    }
-                }
-                //给商品新增或更新条码与价格相关信息
-                JSONObject materialExObj = m.getMaterialExObj();
-                insertOrUpdateMaterialExtend(materialExObj, "basic", "1", mId, user);
-                insertOrUpdateMaterialExtend(materialExObj, "other", "0", mId, user);
-                //给商品更新库存
-                Map<Long, BigDecimal> stockMap = m.getStockMap();
-                for(Depot depot: depotList){
-                    Long depotId = depot.getId();
-                    String materialDepotKey = mId + "_" + depotId;
-                    //获取初始库存
-                    BigDecimal initStock = getInitStock(mId, depotId);
-                    //excel里面的当前库存
-                    BigDecimal stock = stockMap.get(depot.getId());
-                    //新增或更新初始库存
-                    if(stock!=null && stock.compareTo(BigDecimal.ZERO)!=0) {
-                        String basicStr = materialExObj.getString("basic");
-                        MaterialExtend materialExtend = JSONObject.parseObject(basicStr, MaterialExtend.class);
-                        if(StringUtil.isNotEmpty(materialExtend.getSku())) {
-                            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_SKU_BEGIN_STOCK_FAILED_CODE,
-                                    String.format(ExceptionConstants.MATERIAL_SKU_BEGIN_STOCK_FAILED_MSG, materialExtend.getBarCode()));
-                        }
-                        buildChangeInitialStock(deleteInitialStockMaterialIdList, insertInitialStockMaterialList, materialDepotInitialMap, mId, depotId, materialDepotKey, stock);
-                    } else {
-                        if(initStock.compareTo(BigDecimal.ZERO)!=0) {
-                            buildChangeInitialStock(deleteInitialStockMaterialIdList, insertInitialStockMaterialList, materialDepotInitialMap, mId, depotId, materialDepotKey, stock);
-                        }
-                    }
-                    //新增或更新当前库存
-                    Long billCount = depotItemService.getCountByMaterialAndDepot(mId, depotId);
-                    if(billCount == 0) {
-                        if(stock!=null && stock.compareTo(BigDecimal.ZERO)!=0) {
-                            buildChangeCurrentStock(deleteCurrentStockMaterialIdList, insertCurrentStockMaterialList, materialDepotCurrentMap, mId, depotId, materialDepotKey, stock);
-                        } else {
-                            if(initStock.compareTo(BigDecimal.ZERO)!=0) {
-                                buildChangeCurrentStock(deleteCurrentStockMaterialIdList, insertCurrentStockMaterialList, materialDepotCurrentMap, mId, depotId, materialDepotKey, stock);
-                            }
-                        }
-                    } else {
-                        BigDecimal currentNumber = getCurrentStockByMaterialIdAndDepotId(mId, depotId);
-                        //当前库存的更新:减去初始库存,再加上导入的新初始库存
-                        if(currentNumber!=null && initStock!=null && stock!=null) {
-                            currentNumber = currentNumber.subtract(initStock).add(stock);
-                        }
-                        buildChangeCurrentStock(deleteCurrentStockMaterialIdList, insertCurrentStockMaterialList, materialDepotCurrentMap, mId, depotId, materialDepotKey, currentNumber);
-                    }
-                }
-            }
-            //批量更新库存,先删除后新增
-            if(insertInitialStockMaterialList.size()>0) {
-                batchDeleteInitialStockByMaterialList(deleteInitialStockMaterialIdList);
-                materialInitialStockMapperEx.batchInsert(insertInitialStockMaterialList);
-            }
-            if(insertCurrentStockMaterialList.size()>0) {
-                batchDeleteCurrentStockByMaterialList(deleteCurrentStockMaterialIdList);
-                materialCurrentStockMapperEx.batchInsert(insertCurrentStockMaterialList);
-            }
-            logService.insertLog("商品",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_IMPORT).append(mList.size()).append(BusinessConstants.LOG_DATA_UNIT).toString(),
-                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-            Long endTime = System.currentTimeMillis();
-            logger.info("导入耗时:{}", endTime-beginTime);
-            info.code = 200;
-            info.data = "导入成功";
-        } catch (BusinessRunTimeException e) {
-            info.code = e.getCode();
-            info.data = e.getData().get("message");
-        } catch (Exception e) {
-            logger.error(e.getMessage(), e);
-            info.code = 500;
-            info.data = "导入失败";
-        }
-        return info;
-    }
+    int batchSetStatus(Boolean status, String ids)throws Exception;
 
-    /**
-     * 构造初始库存的变化
-     */
-    private void buildChangeInitialStock(List<Long> deleteInitialStockMaterialIdList, List<MaterialInitialStock> insertInitialStockMaterialList,
-                                         Map<String, String> materialDepotInitialMap, Long mId, Long depotId, String materialDepotKey, BigDecimal stock) {
-        if(materialDepotInitialMap.get(materialDepotKey)==null) {
-            MaterialInitialStock materialInitialStock = new MaterialInitialStock();
-            materialInitialStock.setMaterialId(mId);
-            materialInitialStock.setDepotId(depotId);
-            materialInitialStock.setNumber(stock);
-            insertInitialStockMaterialList.add(materialInitialStock);
-            deleteInitialStockMaterialIdList.add(mId);
-            materialDepotInitialMap.put(materialDepotKey, materialDepotKey);
-        }
-    }
+    Unit findUnit(Long mId)throws Exception;
 
-    /**
-     * 构造当前库存的变化
-     */
-    private void buildChangeCurrentStock(List<Long> deleteCurrentStockMaterialIdList, List<MaterialCurrentStock> insertCurrentStockMaterialList,
-                                         Map<String, String> materialDepotCurrentMap, Long mId, Long depotId, String materialDepotKey, BigDecimal stock) {
-        if(materialDepotCurrentMap.get(materialDepotKey)==null) {
-            MaterialCurrentStock materialCurrentStock = new MaterialCurrentStock();
-            materialCurrentStock.setMaterialId(mId);
-            materialCurrentStock.setDepotId(depotId);
-            materialCurrentStock.setCurrentNumber(stock);
-            insertCurrentStockMaterialList.add(materialCurrentStock);
-            deleteCurrentStockMaterialIdList.add(mId);
-            materialDepotCurrentMap.put(materialDepotKey, materialDepotKey);
-        }
-    }
-
-    private Map<String, Long> parseDepotToMap(List<Depot> depotList) {
-        Map<String, Long> map = new HashMap<>();
-        for(Depot depot: depotList) {
-            map.put(depot.getName(), depot.getId());
-        }
-        return map;
-    }
+    List<MaterialVo4Unit> findById(Long id)throws Exception;
 
-    /**
-     * 缓存各个仓库的库存信息
-     * @param src
-     * @param depotCount
-     * @param depotMap
-     * @param i
-     * @return
-     * @throws Exception
-     */
-    private Map<Long, BigDecimal> getStockMapCache(Sheet src, int depotCount, Map<String, Long> depotMap, int i) throws Exception {
-        Map<Long, BigDecimal> stockMap = new HashMap<>();
-        for(int j = 1; j<= depotCount; j++) {
-            int col = 26 + j;
-            if(col < src.getColumns()){
-                String depotName = ExcelUtils.getContent(src, 1, col); //获取仓库名称
-                if(StringUtil.isNotEmpty(depotName)) {
-                    Long depotId = depotMap.get(depotName);
-                    if(depotId!=null && depotId!=0L){
-                        String stockStr = ExcelUtils.getContent(src, i, col);
-                        if(StringUtil.isNotEmpty(stockStr)) {
-                            stockMap.put(depotId, parseBigDecimalEx(stockStr));
-                        }
-                    }
-                }
-            }
-        }
-        return stockMap;
-    }
+    List<MaterialVo4Unit> findByIdWithBarCode(Long meId)throws Exception;
 
-    /**
-     * 批量校验excel中有无重复商品,是指名称、规格、型号、颜色、单位
-     * @param mList
-     */
-    public void batchCheckExistMaterialListByParam(List<MaterialWithInitStock> mList, String name, String standard,
-                                                   String model, String color, String unit, String sku) {
-        for(MaterialWithInitStock material: mList){
-            String materialSku = "";
-            JSONObject materialExObj = material.getMaterialExObj();
-            if(materialExObj!=null && materialExObj.get("basic")!=null) {
-                JSONObject basicObj = materialExObj.getJSONObject("basic");
-                if(basicObj!=null && materialExObj.get("sku")!=null) {
-                    materialSku = basicObj.getString("sku");
-                }
-            }
-            if(name.equals(material.getName()) &&
-                    standard.equals(material.getStandard()) &&
-                    model.equals(material.getModel()) &&
-                    color.equals(material.getColor()) &&
-                    unit.equals(material.getUnit()) &&
-                    sku.equals(materialSku)) {
-                String info = name + "-" + standard + "-" + model + "-" + color + "-" + unit + "-" + sku;
-                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXCEL_IMPORT_EXIST_CODE,
-                        String.format(ExceptionConstants.MATERIAL_EXCEL_IMPORT_EXIST_MSG, info));
-            }
-        }
-    }
+    List<Long> getListByParentId(Long parentId);
 
-    /**
-     * 批量校验excel中有无重复条码(1-文档自身校验,2-和数据库里面的商品校验)
-     * @param mList
-     */
-    public void batchCheckExistBarCodeByParam(List<MaterialWithInitStock> mList,
-                                              String barCode, String manyBarCode) throws Exception {
-        if(StringUtil.isNotEmpty(manyBarCode)) {
-            if(barCode.equals(manyBarCode)) {
-                //同一个商品的主副条码重复了,进行提醒
-                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXCEL_IMPORT_BARCODE_EXIST_CODE,
-                        String.format(ExceptionConstants.MATERIAL_EXCEL_IMPORT_BARCODE_EXIST_MSG, manyBarCode));
-            }
-            //EXCEL中有副条码在系统中已存在(除自身商品之外)
-            int count = materialExtendService.getCountByManyBarCodeWithoutUs(manyBarCode, barCode);
-            if (count>0) {
-                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXCEL_IMPORT_MANY_BARCODE_EXIST_CODE,
-                        String.format(ExceptionConstants.MATERIAL_EXCEL_IMPORT_MANY_BARCODE_EXIST_MSG, manyBarCode));
-            }
-        }
-        for(MaterialWithInitStock material: mList){
-            JSONObject materialExObj = material.getMaterialExObj();
-            String basicBarCode = "";
-            String otherBarCode = "";
-            if(materialExObj.get("basic")!=null) {
-                JSONObject basicObj = materialExObj.getJSONObject("basic");
-                basicBarCode = basicObj.getString("barCode");
-            }
-            if(materialExObj.get("other")!=null) {
-                JSONObject otherObj = materialExObj.getJSONObject("other");
-                otherBarCode = otherObj.getString("barCode");
-            }
-            if(barCode.equals(basicBarCode) || barCode.equals(otherBarCode)){
-                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXCEL_IMPORT_BARCODE_EXIST_CODE,
-                        String.format(ExceptionConstants.MATERIAL_EXCEL_IMPORT_BARCODE_EXIST_MSG, barCode));
-            }
-            if(StringUtil.isNotEmpty(manyBarCode)) {
-                if(manyBarCode.equals(basicBarCode) || manyBarCode.equals(otherBarCode)){
-                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXCEL_IMPORT_BARCODE_EXIST_CODE,
-                            String.format(ExceptionConstants.MATERIAL_EXCEL_IMPORT_BARCODE_EXIST_MSG, manyBarCode));
-                }
-            }
-        }
-    }
+    List<Long> getIdListByParentId(List<Long> idList, Long parentId);
+
+    JSONArray getMaterialByParam(String materialParam);
+
+    List<MaterialVo4Unit> findBySelectWithBarCode(Long categoryId, String q, String standardOrModel, String color,
+                                                  String brand, String mfrs, String enableSerialNumber, String enableBatchNumber,
+                                                  Integer offset, Integer rows, Long depotId) throws Exception;
+
+    int findBySelectWithBarCodeCount(Long categoryId, String q, String standardOrModel, String color,
+                                     String brand, String mfrs, String enableSerialNumber, String enableBatchNumber, Long depotId) throws Exception;
+
+    void exportExcel(String categoryId, String materialParam, String color, String materialOther, String weight,
+                     String expiryNum, String enabled, String enableSerialNumber, String enableBatchNumber,
+                     String remark, HttpServletResponse response)throws Exception;
 
-    /**
-     * 给商品新增或更新条码与价格相关信息
-     * @param materialExObj
-     * @param type
-     * @param defaultFlag
-     * @param mId
-     * @param user
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void insertOrUpdateMaterialExtend(JSONObject materialExObj, String type, String defaultFlag, Long mId, User user) throws Exception {
-        if(StringUtil.isExist(materialExObj.get(type))){
-            String basicStr = materialExObj.getString(type);
-            MaterialExtend materialExtend = JSONObject.parseObject(basicStr, MaterialExtend.class);
-            materialExtend.setMaterialId(mId);
-            materialExtend.setDefaultFlag(defaultFlag);
-            materialExtend.setCreateTime(new Date());
-            materialExtend.setUpdateTime(System.currentTimeMillis());
-            materialExtend.setCreateSerial(user.getLoginName());
-            materialExtend.setUpdateSerial(user.getLoginName());
-            Long meId = 0L;
-            if(StringUtil.isNotEmpty(materialExtend.getSku())){
-                //含sku的商品,特殊逻辑
-                meId = materialExtendService.selectIdByMaterialIdAndBarCode(mId, materialExtend.getBarCode());
-                List<MaterialExtend> meList = materialExtendService.getListByMaterialIdAndDefaultFlagAndBarCode(mId, "1", materialExtend.getBarCode());
-                if(meList.size() == 0) {
-                    materialExtend.setDefaultFlag("1");
-                } else {
-                    materialExtend.setDefaultFlag("0");
-                }
-            } else {
-                meId = materialExtendService.selectIdByMaterialIdAndDefaultFlag(mId, defaultFlag);
-            }
-            if(meId==0L){
-                materialExtendMapper.insertSelective(materialExtend);
-            } else {
-                materialExtend.setId(meId);
-                materialExtendMapper.updateByPrimaryKeySelective(materialExtend);
-                //如果金额为空,此处单独置空
-                materialExtendMapperEx.specialUpdatePrice(materialExtend);
-            }
-        }
-    }
-
-    public String getBasicBarCode(MaterialWithInitStock m) {
-        String barCode = "";
-        JSONObject materialExObj = m.getMaterialExObj();
-        if(StringUtil.isExist(materialExObj.get("basic"))) {
-            String basicStr = materialExObj.getString("basic");
-            MaterialExtend basicMaterialExtend = JSONObject.parseObject(basicStr, MaterialExtend.class);
-            barCode = basicMaterialExtend.getBarCode();
-        }
-        return barCode;
-    }
+    BaseResponseInfo importExcel(MultipartFile file, HttpServletRequest request) throws Exception;
 
-    /**
-     * 根据条件返回产品列表
-     * @param name
-     * @param standard
-     * @param model
-     * @param color
-     * @param unit
-     * @param unitId
-     * @return
-     */
-    private List<Material> getMaterialListByParam(String name, String standard, String model, String color, String unit, Long unitId, String basicBarCode) throws Exception {
-        List<Material> list = new ArrayList<>();
-        MaterialExample example = new MaterialExample();
-        MaterialExample.Criteria criteria = example.createCriteria();
-        criteria.andNameEqualTo(name);
-        if (StringUtil.isNotEmpty(model)) {
-            criteria.andModelEqualTo(model);
-        }
-        if (StringUtil.isNotEmpty(color)) {
-            criteria.andColorEqualTo(color);
-        }
-        if (StringUtil.isNotEmpty(standard)) {
-            criteria.andStandardEqualTo(standard);
-        }
-        if (StringUtil.isNotEmpty(unit)) {
-            criteria.andUnitEqualTo(unit);
-        }
-        if (unitId !=null) {
-            criteria.andUnitIdEqualTo(unitId);
-        }
-        criteria.andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        list = materialMapper.selectByExample(example);
-        if(list.size()==0) {
-            //如果通过组合条件没有查到该商品,则通过条码再查一次
-            MaterialExtend materialExtend = materialExtendService.getInfoByBarCode(basicBarCode);
-            if(materialExtend != null && materialExtend.getMaterialId()!=null) {
-                Material material = new Material();
-                material.setId(materialExtend.getMaterialId());
-                list.add(material);
-            }
-        }
-        return list;
-    }
+    void batchCheckExistMaterialListByParam(List<MaterialWithInitStock> mList, String name, String standard,
+                                            String model, String color, String unit, String sku);
+
+    void batchCheckExistBarCodeByParam(List<MaterialWithInitStock> mList,
+                                       String barCode, String manyBarCode) throws Exception;
 
-    /**
-     * 写入初始库存
-     * @param depotId
-     * @param mId
-     * @param stock
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void insertInitialStockByMaterialAndDepot(Long depotId, Long mId, BigDecimal stock, BigDecimal lowSafeStock, BigDecimal highSafeStock){
-        MaterialInitialStock materialInitialStock = new MaterialInitialStock();
-        materialInitialStock.setDepotId(depotId);
-        materialInitialStock.setMaterialId(mId);
-        stock = stock == null? BigDecimal.ZERO: stock;
-        materialInitialStock.setNumber(stock);
-        if(lowSafeStock!=null) {
-            materialInitialStock.setLowSafeStock(lowSafeStock);
-        }
-        if(highSafeStock!=null) {
-            materialInitialStock.setHighSafeStock(highSafeStock);
-        }
-        materialInitialStockMapper.insertSelective(materialInitialStock); //存入初始库存
-    }
+    void insertOrUpdateMaterialExtend(JSONObject materialExObj, String type, String defaultFlag, Long mId, User user) throws Exception;
+
+    String getBasicBarCode(MaterialWithInitStock m);
+
+    List<Material> getMaterialListByParam(String name, String standard, String model, String color, String unit, Long unitId, String basicBarCode) throws Exception;
 
-    /**
-     * 写入当前库存
-     * @param depotId
-     * @param mId
-     * @param stock
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void insertCurrentStockByMaterialAndDepot(Long depotId, Long mId, BigDecimal stock){
-        MaterialCurrentStock materialCurrentStock = new MaterialCurrentStock();
-        materialCurrentStock.setDepotId(depotId);
-        materialCurrentStock.setMaterialId(mId);
-        materialCurrentStock.setCurrentNumber(stock);
-        materialCurrentStockMapper.insertSelective(materialCurrentStock); //存入初始库存
-    }
+    void insertInitialStockByMaterialAndDepot(Long depotId, Long mId, BigDecimal stock, BigDecimal lowSafeStock, BigDecimal highSafeStock);
 
-    /**
-     * 批量删除初始库存
-     * @param mIdList
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void batchDeleteInitialStockByMaterialList(List<Long> mIdList){
-        MaterialInitialStockExample example = new MaterialInitialStockExample();
-        example.createCriteria().andMaterialIdIn(mIdList);
-        materialInitialStockMapper.deleteByExample(example);
-    }
+    void insertCurrentStockByMaterialAndDepot(Long depotId, Long mId, BigDecimal stock);
 
-    /**
-     * 批量删除当前库存
-     * @param mIdList
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void batchDeleteCurrentStockByMaterialList(List<Long> mIdList){
-        MaterialCurrentStockExample example = new MaterialCurrentStockExample();
-        example.createCriteria().andMaterialIdIn(mIdList);
-        materialCurrentStockMapper.deleteByExample(example);
-    }
-
-    public List<MaterialVo4Unit> getMaterialEnableSerialNumberList(String q, Integer offset, Integer rows)throws Exception {
-        List<MaterialVo4Unit> list =null;
-        try{
-            list=  materialMapperEx.getMaterialEnableSerialNumberList(q, offset, rows);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public Long getMaterialEnableSerialNumberCount(String q)throws Exception {
-        Long count =null;
-        try{
-            count=  materialMapperEx.getMaterialEnableSerialNumberCount(q);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return count;
-    }
-
-    public BigDecimal parseBigDecimalEx(String str) throws Exception{
-        if(!StringUtil.isEmpty(str)) {
-            return  new BigDecimal(str);
-        } else {
-            return null;
-        }
-    }
-
-    public BigDecimal parsePrice(String price, String ratio) throws Exception{
-        if(StringUtil.isEmpty(price) || StringUtil.isEmpty(ratio)) {
-            return BigDecimal.ZERO;
-        } else {
-            BigDecimal pr=new BigDecimal(price);
-            BigDecimal r=new BigDecimal(ratio);
-            return pr.multiply(r);
-        }
-    }
+    void batchDeleteInitialStockByMaterialList(List<Long> mIdList);
 
-    /**
-     * 根据商品获取初始库存-多仓库
-     * @param depotList
-     * @param materialId
-     * @return
-     */
-    public BigDecimal getInitStockByMidAndDepotList(List<Long> depotList, Long materialId) {
-        BigDecimal stock = BigDecimal.ZERO;
-        MaterialInitialStockExample example = new MaterialInitialStockExample();
-        if(depotList!=null && depotList.size()>0) {
-            example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdIn(depotList)
-                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        } else {
-            example.createCriteria().andMaterialIdEqualTo(materialId)
-                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        }
-        List<MaterialInitialStock> list = materialInitialStockMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            for(MaterialInitialStock ms: list) {
-                if(ms!=null) {
-                    stock = stock.add(ms.getNumber());
-                }
-            }
-        }
-        return stock;
-    }
+    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
+    void batchDeleteCurrentStockByMaterialList(List<Long> mIdList);
 
-    /**
-     * 根据商品和仓库获取初始库存
-     * @param materialId
-     * @param depotId
-     * @return
-     */
-    public BigDecimal getInitStock(Long materialId, Long depotId) {
-        BigDecimal stock = BigDecimal.ZERO;
-        MaterialInitialStockExample example = new MaterialInitialStockExample();
-        example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdEqualTo(depotId)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<MaterialInitialStock> list = materialInitialStockMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            stock = list.get(0).getNumber();
-        }
-        return stock;
-    }
+    List<MaterialVo4Unit> getMaterialEnableSerialNumberList(String q, Integer offset, Integer rows)throws Exception;
 
-    /**
-     * 根据商品和仓库获取当前库存
-     * @param materialId
-     * @param depotId
-     * @return
-     */
-    public BigDecimal getCurrentStockByMaterialIdAndDepotId(Long materialId, Long depotId) {
-        BigDecimal stock = BigDecimal.ZERO;
-        MaterialCurrentStockExample example = new MaterialCurrentStockExample();
-        example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdEqualTo(depotId)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<MaterialCurrentStock> list = materialCurrentStockMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            stock = list.get(0).getCurrentNumber();
-        } else {
-            stock = getInitStock(materialId,depotId);
-        }
-        return stock;
-    }
+    Long getMaterialEnableSerialNumberCount(String q)throws Exception;
 
-    /**
-     * 根据商品列表获取初始库存Map
-     * @param list
-     * @return
-     */
-    public Map<Long,BigDecimal> getInitialStockMapByMaterialList(List<MaterialVo4Unit> list) {
-        Map<Long,BigDecimal> map = new HashMap<>();
-        List<Long> materialIdList = new ArrayList<>();
-        for(MaterialVo4Unit materialVo4Unit: list) {
-            materialIdList.add(materialVo4Unit.getId());
-        }
-        List<MaterialInitialStock> mcsList = materialInitialStockMapperEx.getInitialStockMapByIdList(materialIdList);
-        for(MaterialInitialStock materialInitialStock: mcsList) {
-            map.put(materialInitialStock.getMaterialId(), materialInitialStock.getNumber());
-        }
-        return map;
-    }
+    BigDecimal parseBigDecimalEx(String str) throws Exception;
 
-    /**
-     * 根据商品列表获取当前库存Map
-     * @param list
-     * @return
-     */
-    public Map<Long,BigDecimal> getCurrentStockMapByMaterialList(List<MaterialVo4Unit> list) {
-        Map<Long,BigDecimal> map = new HashMap<>();
-        List<Long> materialIdList = new ArrayList<>();
-        for(MaterialVo4Unit materialVo4Unit: list) {
-            materialIdList.add(materialVo4Unit.getId());
-        }
-        List<MaterialCurrentStock> mcsList = materialCurrentStockMapperEx.getCurrentStockMapByIdList(materialIdList);
-        for(MaterialCurrentStock materialCurrentStock: mcsList) {
-            map.put(materialCurrentStock.getMaterialId(), materialCurrentStock.getCurrentNumber());
-        }
-        return map;
-    }
+    BigDecimal parsePrice(String price, String ratio) throws Exception;
 
-    /**
-     * 根据商品和仓库获取安全库存信息
-     * @param materialId
-     * @param depotId
-     * @return
-     */
-    public MaterialInitialStock getSafeStock(Long materialId, Long depotId) {
-        MaterialInitialStock materialInitialStock = new MaterialInitialStock();
-        MaterialInitialStockExample example = new MaterialInitialStockExample();
-        example.createCriteria().andMaterialIdEqualTo(materialId).andDepotIdEqualTo(depotId)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<MaterialInitialStock> list = materialInitialStockMapper.selectByExample(example);
-        if(list!=null && list.size()>0) {
-            materialInitialStock = list.get(0);
-        }
-        return materialInitialStock;
-    }
-
-    public List<MaterialVo4Unit> getMaterialByMeId(Long meId) {
-        List<MaterialVo4Unit> result = new ArrayList<MaterialVo4Unit>();
-        try{
-            if(meId!=null) {
-                result= materialMapperEx.getMaterialByMeId(meId);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-
-    public String getMaxBarCode() {
-        List<String> barCodeOldList = materialMapperEx.getBarCodeList();
-        // 使用 Stream API 处理条码列表
-        OptionalLong maxBarcode = barCodeOldList.stream()
-                .filter(StringUtil::isNumeric)   // 过滤掉非数字条码
-                .mapToLong(Long::parseLong)      // 将字符串转换为 Long 类型
-                .max();                          // 获取最大值
-        // 如果存在最大值,返回它;否则返回 1000L
-        Long maxBarCodeOld = maxBarcode.orElse(1000L);
-        return maxBarCodeOld + "";
-    }
-
-    public List<String> getMaterialNameList() {
-        return materialMapperEx.getMaterialNameList();
-    }
-
-    public List<MaterialVo4Unit> getMaterialByBarCode(String barCode) {
-        String [] barCodeArray=barCode.split(",");
-        return materialMapperEx.getMaterialByBarCode(barCodeArray);
-    }
-
-    public List<MaterialVo4Unit> getMaterialByBarCodeAndWithOutMId(String barCode, Long mId) {
-        String [] barCodeArray=barCode.split(",");
-        return materialMapperEx.getMaterialByBarCodeAndWithOutMId(barCodeArray, mId);
-    }
-
-    public List<MaterialInitialStockWithMaterial> getInitialStockWithMaterial(List<Long> depotList) {
-        return materialMapperEx.getInitialStockWithMaterial(depotList);
-    }
-
-    public List<MaterialVo4Unit> getListWithStock(List<Long> depotList, List<Long> idList, String position, String materialParam,
-                                                  Boolean moveAvgPriceFlag, Integer zeroStock, String column, String order,
-                                                  Integer offset, Integer rows) throws Exception {
-        Map<Long, BigDecimal> initialStockMap = new HashMap<>();
-        List<MaterialInitialStockWithMaterial> initialStockList = getInitialStockWithMaterial(depotList);
-        for (MaterialInitialStockWithMaterial mism: initialStockList) {
-            initialStockMap.put(mism.getMaterialId(), mism.getNumber());
-        }
-        List<MaterialVo4Unit> dataList = materialMapperEx.getListWithStock(depotList, idList, position, materialParam, zeroStock, column, order, offset, rows);
-        for(MaterialVo4Unit item: dataList) {
-            if(moveAvgPriceFlag) {
-                item.setPurchaseDecimal(item.getCurrentUnitPrice());
-                item.setCurrentStockPrice(item.getCurrentStockMovePrice());
-            }
-            item.setUnitName(null!=item.getUnitId()?item.getUnitName() + "[多单位]":item.getUnitName());
-            item.setInitialStock(null!=initialStockMap.get(item.getId())?initialStockMap.get(item.getId()):BigDecimal.ZERO);
-            item.setBigUnitStock(getBigUnitStock(item.getCurrentStock(), item.getUnitId()));
-            if(fileUploadType == 2) {
-                item.setImgSmall("small");
-                item.setImgLarge("large");
-            }
-        }
-        return dataList;
-    }
-
-    public int getListWithStockCount(List<Long> depotList, List<Long> idList, String position, String materialParam, Integer zeroStock) {
-        return materialMapperEx.getListWithStockCount(depotList, idList, position, materialParam, zeroStock);
-    }
-
-    public MaterialVo4Unit getTotalStockAndPrice(List<Long> depotList, List<Long> idList, String position, String materialParam) {
-        return materialMapperEx.getTotalStockAndPrice(depotList, idList, position, materialParam);
-    }
+    BigDecimal getInitStockByMidAndDepotList(List<Long> depotList, Long materialId);
 
-    /**
-     * 将小单位的库存换算为大单位的库存
-     * @param stock
-     * @param unitId
-     * @return
-     * @throws Exception
-     */
-    public String getBigUnitStock(BigDecimal stock, Long unitId) throws Exception {
-        String bigUnitStock = "";
-        if(null!= unitId) {
-            Unit unit = unitService.getUnit(unitId);
-            if(unit.getRatio()!=null && unit.getRatio().compareTo(BigDecimal.ZERO)!=0 && stock!=null) {
-                bigUnitStock = stock.divide(unit.getRatio(),2,BigDecimal.ROUND_HALF_UP) + unit.getOtherUnit();
-            }
-        }
-        return bigUnitStock;
-    }
+    BigDecimal getInitStock(Long materialId, Long depotId);
 
-    /**
-     * 构造扩展信息
-     * @param mpArr
-     * @param m
-     * @return
-     */
-    public String getMaterialOtherByParam(String[] mpArr, MaterialVo4Unit m) {
-        String materialOther = "";
-        for (int i = 0; i < mpArr.length; i++) {
-            if (mpArr[i].equals("自定义1")) {
-                materialOther = materialOther + ((m.getOtherField1() == null || m.getOtherField1().equals("")) ? "" : "(" + m.getOtherField1() + ")");
-            }
-            if (mpArr[i].equals("自定义2")) {
-                materialOther = materialOther + ((m.getOtherField2() == null || m.getOtherField2().equals("")) ? "" : "(" + m.getOtherField2() + ")");
-            }
-            if (mpArr[i].equals("自定义3")) {
-                materialOther = materialOther + ((m.getOtherField3() == null || m.getOtherField3().equals("")) ? "" : "(" + m.getOtherField3() + ")");
-            }
-        }
-        return materialOther;
-    }
+    BigDecimal getCurrentStockByMaterialIdAndDepotId(Long materialId, Long depotId);
+
+    Map<Long,BigDecimal> getInitialStockMapByMaterialList(List<MaterialVo4Unit> list);
+
+    Map<Long,BigDecimal> getCurrentStockMapByMaterialList(List<MaterialVo4Unit> list);
+
+    MaterialInitialStock getSafeStock(Long materialId, Long depotId);
+
+    List<MaterialVo4Unit> getMaterialByMeId(Long meId);
+
+    String getMaxBarCode();
+
+    List<String> getMaterialNameList();
+
+    List<MaterialVo4Unit> getMaterialByBarCode(String barCode);
+
+    List<MaterialVo4Unit> getMaterialByBarCode(List<String> barCodeList);
+
+    List<MaterialVo4Unit> getMaterialByBarCodeAndWithOutMId(String barCode, Long mId);
+
+    List<MaterialInitialStockWithMaterial> getInitialStockWithMaterial(List<Long> depotList);
+
+    List<MaterialVo4Unit> getListWithStock(List<Long> depotList, List<Long> idList, String position, String materialParam,
+                                           Boolean moveAvgPriceFlag, Integer zeroStock, String column, String order,
+                                           Integer offset, Integer rows) throws Exception;
+
+    int getListWithStockCount(List<Long> depotList, List<Long> idList, String position, String materialParam, Integer zeroStock);
+
+    MaterialVo4Unit getTotalStockAndPrice(List<Long> depotList, List<Long> idList, String position, String materialParam);
+
+    String getBigUnitStock(BigDecimal stock, Long unitId) throws Exception;
+
+    String getMaterialOtherByParam(String[] mpArr, MaterialVo4Unit m);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchSetMaterialCurrentStock(String ids) throws Exception {
-        int res = 0;
-        List<Long> idList = StringUtil.strToLongList(ids);
-        List<Depot> depotList = depotService.getAllList();
-        for(Long mId: idList) {
-            for(Depot depot: depotList) {
-                depotItemService.updateCurrentStockFun(mId, depot.getId());
-                res = 1;
-            }
-        }
-        return res;
-    }
+    int batchSetMaterialCurrentStock(String ids) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchSetMaterialCurrentUnitPrice(String ids) throws Exception {
-        int res = 0;
-        List<Long> idList = StringUtil.strToLongList(ids);
-        for(Long mId: idList) {
-            DepotItem depotItem = new DepotItem();
-            depotItem.setMaterialId(mId);
-            depotItemService.updateCurrentUnitPrice(depotItem);
-            res = 1;
-        }
-        return res;
-    }
-
-    public int batchUpdate(JSONObject jsonObject) {
-        String ids = jsonObject.getString("ids");
-        String materialStr = jsonObject.getString("material");
-        List<Long> idList = StringUtil.strToLongList(ids);
-        Material material = JSONObject.parseObject(materialStr, Material.class);
-        MaterialExample example = new MaterialExample();
-        example.createCriteria().andIdIn(idList).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        return materialMapper.updateByExampleSelective(material, example);
-    }
-
-    public MaterialExtend getMaterialExtendBySerialNumber(String serialNumber) {
-        return materialMapperEx.getMaterialExtendBySerialNumber(serialNumber);
-    }
+    int batchSetMaterialCurrentUnitPrice(String ids) throws Exception;
+
+    int batchUpdate(JSONObject jsonObject);
+
+    MaterialExtend getMaterialExtendBySerialNumber(String serialNumber);
+
+    List<MaterialVo4Unit> getMaterialByBatchNumber(String batchNumber);
+
+    Material getMaterialById(Long id);
+
+    List<MaterialVo4Unit> getMaterialBySystemSku(List<String> systemSkuList);
+
+    /**
+     * 获取商品提醒
+     * @return
+     */
+    MaterialWarnListVo getMaterialWarn();
+
+    //导入表格
+    BaseResponseInfo importExcelTwo(MultipartFile file, HttpServletRequest request) throws Exception;
 }

+ 69 - 669
src/main/java/com/jsh/erp/service/SupplierService.java

@@ -1,705 +1,105 @@
 package com.jsh.erp.service;
 
 import com.alibaba.fastjson.JSONObject;
-import com.jsh.erp.constants.BusinessConstants;
-import com.jsh.erp.constants.ExceptionConstants;
-import com.jsh.erp.datasource.entities.*;
-import com.jsh.erp.datasource.mappers.*;
-import com.jsh.erp.datasource.vo.DepotHeadVo4StatementAccount;
-import com.jsh.erp.exception.BusinessRunTimeException;
-import com.jsh.erp.exception.JshException;
-import com.jsh.erp.utils.*;
-import jxl.Sheet;
-import jxl.Workbook;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.jsh.erp.datasource.entities.Supplier;
+import com.jsh.erp.utils.BaseResponseInfo;
 import org.springframework.transaction.annotation.Transactional;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
 import org.springframework.web.multipart.MultipartFile;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import java.io.File;
 import java.math.BigDecimal;
-import java.util.*;
-
-
-@Service
-public class SupplierService {
-    private Logger logger = LoggerFactory.getLogger(SupplierService.class);
-
-    @Resource
-    private SupplierMapper supplierMapper;
-
-    @Resource
-    private SupplierMapperEx supplierMapperEx;
-    @Resource
-    private LogService logService;
-    @Resource
-    private UserService userService;
-    @Resource
-    private AccountHeadMapperEx accountHeadMapperEx;
-    @Resource
-    private DepotHeadMapperEx depotHeadMapperEx;
-    @Resource
-    private AccountItemMapperEx accountItemMapperEx;
-    @Resource
-    private DepotHeadService depotHeadService;
-    @Resource
-    private UserBusinessService userBusinessService;
-    @Resource
-    private UserBusinessMapper userBusinessMapper;
-
-    public Supplier getSupplier(long id)throws Exception {
-        Supplier result=null;
-        try{
-            result=supplierMapper.selectByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-
-    public List<Supplier> getSupplierListByIds(String ids)throws Exception {
-        List<Long> idList = StringUtil.strToLongList(ids);
-        List<Supplier> list = new ArrayList<>();
-        try{
-            SupplierExample example = new SupplierExample();
-            example.createCriteria().andIdIn(idList);
-            list = supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Supplier> getSupplier()throws Exception {
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<Supplier> list=null;
-        try{
-            list=supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Supplier> select(String supplier, String type, String phonenum, String telephone) throws Exception{
-        List<Supplier> list = new ArrayList<>();
-        try{
-            String [] creatorArray = depotHeadService.getCreatorArray();
-            PageUtils.startPage();
-            list = supplierMapperEx.selectByConditionSupplier(supplier, type, phonenum, telephone, creatorArray);
-            for(Supplier s : list) {
-                Integer supplierId = s.getId().intValue();
-                String beginTime = Tools.getYearBegin();
-                String endTime = Tools.getCenternTime(new Date());
-                BigDecimal sum = BigDecimal.ZERO;
-                String supplierType = type;
-                String inOutType = "";
-                String subType = "";
-                String typeBack = "";
-                String subTypeBack = "";
-                String billType = "";
-                if (("供应商").equals(supplierType)) {
-                    inOutType = "入库";
-                    subType = "采购";
-                    typeBack = "出库";
-                    subTypeBack = "采购退货";
-                    billType = "付款";
-                } else if (("客户").equals(supplierType)) {
-                    inOutType = "出库";
-                    subType = "销售";
-                    typeBack = "入库";
-                    subTypeBack = "销售退货";
-                    billType = "收款";
-                }
-                List<DepotHeadVo4StatementAccount> saList = depotHeadService.getStatementAccount(beginTime, endTime, supplierId, null,
-                        1, supplierType, inOutType, subType, typeBack, subTypeBack, billType, null, null);
-                if(saList.size()>0) {
-                    DepotHeadVo4StatementAccount item = saList.get(0);
-                    //期初 = 起始期初金额+上期欠款金额-上期退货的欠款金额-上期收付款
-                    BigDecimal preNeed = item.getBeginNeed().add(item.getPreDebtMoney()).subtract(item.getPreReturnDebtMoney()).subtract(item.getPreBackMoney());
-                    item.setPreNeed(preNeed);
-                    //实际欠款 = 本期欠款-本期退货的欠款金额
-                    BigDecimal realDebtMoney = item.getDebtMoney().subtract(item.getReturnDebtMoney());
-                    item.setDebtMoney(realDebtMoney);
-                    //期末 = 期初+实际欠款-本期收款
-                    BigDecimal allNeedGet = preNeed.add(realDebtMoney).subtract(item.getBackMoney());
-                    sum = sum.add(allNeedGet);
-                }
-                if(("客户").equals(s.getType())) {
-                    s.setAllNeedGet(sum);
-                } else if(("供应商").equals(s.getType())) {
-                    s.setAllNeedPay(sum);
-                }
-            }
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+import java.util.List;
+import java.util.Map;
+
+public interface SupplierService extends IService<Supplier> {
+    Supplier getSupplier(long id)throws Exception;
+
+    List<Supplier> getSupplierListByIds(String ids)throws Exception;
+
+    List<Supplier> getSupplier()throws Exception;
+
+    List<Supplier> select(String supplier, String type, String phonenum, String telephone) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertSupplier(JSONObject obj, HttpServletRequest request)throws Exception {
-        Supplier supplier = JSONObject.parseObject(obj.toJSONString(), Supplier.class);
-        int result=0;
-        try{
-            supplier.setEnabled(true);
-            User userInfo=userService.getCurrentUser();
-            supplier.setCreator(userInfo==null?null:userInfo.getId());
-            result=supplierMapper.insertSelective(supplier);
-            //新增客户时给当前用户自动授权
-            setUserCustomerPermission(request, supplier);
-            logService.insertLog("商家",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(supplier.getSupplier()).toString(),request);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int insertSupplier(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateSupplier(JSONObject obj, HttpServletRequest request)throws Exception {
-        Supplier supplier = JSONObject.parseObject(obj.toJSONString(), Supplier.class);
-        if(supplier.getBeginNeedPay() == null) {
-            supplier.setBeginNeedPay(BigDecimal.ZERO);
-        }
-        if(supplier.getBeginNeedGet() == null) {
-            supplier.setBeginNeedGet(BigDecimal.ZERO);
-        }
-        int result=0;
-        try{
-            result=supplierMapper.updateByPrimaryKeySelective(supplier);
-            logService.insertLog("商家",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(supplier.getSupplier()).toString(), request);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int updateSupplier(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int deleteSupplier(Long id, HttpServletRequest request)throws Exception {
-        return batchDeleteSupplierByIds(id.toString());
-    }
+    int deleteSupplier(Long id, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteSupplier(String ids, HttpServletRequest request) throws Exception{
-        return batchDeleteSupplierByIds(ids);
-    }
+    int batchDeleteSupplier(String ids, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteSupplierByIds(String ids)throws Exception {
-        int result=0;
-        String [] idArray=ids.split(",");
-        //校验财务主表	jsh_accounthead
-        List<AccountHead> accountHeadList=null;
-        try{
-            accountHeadList = accountHeadMapperEx.getAccountHeadListByOrganIds(idArray);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        if(accountHeadList!=null&&accountHeadList.size()>0){
-            logger.error("异常码[{}],异常提示[{}],参数,OrganIds[{}]",
-                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
-            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
-                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
-        }
-        //校验单据主表	jsh_depot_head
-        List<DepotHead> depotHeadList=null;
-        try{
-            depotHeadList = depotHeadMapperEx.getDepotHeadListByOrganIds(idArray);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        if(depotHeadList!=null&&depotHeadList.size()>0){
-            logger.error("异常码[{}],异常提示[{}],参数,OrganIds[{}]",
-                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
-            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
-                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
-        }
-        //记录日志
-        StringBuffer sb = new StringBuffer();
-        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
-        List<Supplier> list = getSupplierListByIds(ids);
-        for(Supplier supplier: list){
-            sb.append("[").append(supplier.getSupplier()).append("]");
-        }
-        logService.insertLog("商家", sb.toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        User userInfo=userService.getCurrentUser();
-        //校验通过执行删除操作
-        try{
-            result = supplierMapperEx.batchDeleteSupplierByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
-
-    public int checkIsNameExist(Long id, String name)throws Exception {
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andIdNotEqualTo(id).andSupplierEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<Supplier> list=null;
-        try{
-            list= supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list==null?0:list.size();
-    }
-
-    public int checkIsNameAndTypeExist(Long id, String name, String type)throws Exception {
-        name = name == null? "": name;
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andIdNotEqualTo(id).andSupplierEqualTo(name).andTypeEqualTo(type)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<Supplier> list=null;
-        try{
-            list= supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list==null?0:list.size();
-    }
+    int batchDeleteSupplierByIds(String ids)throws Exception;
+
+    int checkIsNameExist(Long id, String name)throws Exception;
+
+    int checkIsNameAndTypeExist(Long id, String name, String type)throws Exception;
+
+    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
+    void updateAdvanceIn(Long supplierId);
+
+    List<Supplier> findBySelectCus()throws Exception;
+
+    List<Supplier> findBySelectSup()throws Exception;
+
+    List<Supplier> findBySelectRetail()throws Exception;
+
+    List<Supplier> findById(Long supplierId)throws Exception;
 
-    /**
-     * 更新会员的预付款
-     * @param supplierId
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void updateAdvanceIn(Long supplierId) {
-        try{
-            //查询会员在收预付款单据的总金额
-            BigDecimal financialAllPrice = accountHeadMapperEx.getFinancialAllPriceByOrganId(supplierId);
-            //查询会员在零售出库单据的总金额
-            BigDecimal billAllPrice = depotHeadMapperEx.getBillAllPriceByOrganId(supplierId);
-            Supplier supplier = new Supplier();
-            supplier.setId(supplierId);
-            supplier.setAdvanceIn(financialAllPrice.subtract(billAllPrice));
-            supplierMapper.updateByPrimaryKeySelective(supplier);
-        } catch (Exception e){
-            JshException.writeFail(logger, e);
-        }
-    }
-
-    public List<Supplier> findBySelectCus()throws Exception {
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andTypeLike("客户").andEnabledEqualTo(true).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        example.setOrderByClause("sort asc, id desc");
-        List<Supplier> list=null;
-        try{
-            list = supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Supplier> findBySelectSup()throws Exception {
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andTypeLike("供应商").andEnabledEqualTo(true)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        example.setOrderByClause("sort asc, id desc");
-        List<Supplier> list=null;
-        try{
-            list = supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Supplier> findBySelectRetail()throws Exception {
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andTypeLike("会员").andEnabledEqualTo(true)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        example.setOrderByClause("sort asc, id desc");
-        List<Supplier> list=null;
-        try{
-            list = supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Supplier> findById(Long supplierId)throws Exception {
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andIdEqualTo(supplierId)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        example.setOrderByClause("sort asc, id desc");
-        List<Supplier> list=null;
-        try{
-            list = supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    int batchSetStatus(Boolean status, String ids)throws Exception;
+
+    List<Supplier> findUserCustomer()throws Exception;
+
+    List<Supplier> findByAll(String supplier, String type, String phonenum, String telephone) throws Exception;
+
+    Map<String, Object> getBeginNeedByOrganId(Long organId) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchSetStatus(Boolean status, String ids)throws Exception {
-        logService.insertLog("商家",
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ENABLED).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        List<Long> supplierIds = StringUtil.strToLongList(ids);
-        Supplier supplier = new Supplier();
-        supplier.setEnabled(status);
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andIdIn(supplierIds);
-        int result=0;
-        try{
-            result = supplierMapper.updateByExampleSelective(supplier, example);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
-
-    public List<Supplier> findUserCustomer()throws Exception{
-        SupplierExample example = new SupplierExample();
-        example.createCriteria().andTypeEqualTo("客户")
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        example.setOrderByClause("sort asc, id desc");
-        List<Supplier> list=null;
-        try{
-            list = supplierMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<Supplier> findByAll(String supplier, String type, String phonenum, String telephone) throws Exception{
-        List<Supplier> list=null;
-        try{
-            list = supplierMapperEx.findByAll(supplier, type, phonenum, telephone);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public Map<String, Object> getBeginNeedByOrganId(Long organId) throws Exception {
-        Supplier supplier = getSupplier(organId);
-        Map<String, Object> map = new HashMap<>();
-        BigDecimal needDebt = BigDecimal.ZERO;
-        if("供应商".equals(supplier.getType())) {
-            needDebt = supplier.getBeginNeedPay();
-        } else if("客户".equals(supplier.getType())) {
-            needDebt = supplier.getBeginNeedGet();
-        }
-        BigDecimal finishDebt = accountItemMapperEx.getFinishDebtByOrganId(organId).abs();
-        BigDecimal eachAmount = BigDecimal.ZERO;
-        if(needDebt != null) {
-            eachAmount = needDebt.subtract(finishDebt);
-        }
-        //应收欠款
-        map.put("needDebt", needDebt);
-        //已收欠款
-        map.put("finishDebt", finishDebt);
-        //本次收款
-        map.put("eachAmount", eachAmount);
-        return map;
-    }
+    void importVendor(MultipartFile file, HttpServletRequest request) throws Exception;
+
+    Integer parseIntegerFromExcel(String content);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void importVendor(MultipartFile file, HttpServletRequest request) throws Exception{
-        String type = "供应商";
-        User userInfo = userService.getCurrentUser();
-        Workbook workbook = Workbook.getWorkbook(file.getInputStream());
-        Sheet src = workbook.getSheet(0);
-        //'名称', '联系人', '手机号码', '联系电话', '电子邮箱', '纳税人识别号', '开具发票情况','税率(%)', '开户行', '账号', '地址', '供应商分级', '结算方式',	'账单周期', '采购对接人', '到货天数', '备注', '排序', '状态'
-        List<Supplier> sList = new ArrayList<>();
-        for (int i = 2; i < src.getRows(); i++) {
-            String supplierName = ExcelUtils.getContent(src, i, 0);
-            String enabled = ExcelUtils.getContent(src, i, 18);
-            if(StringUtil.isNotEmpty(supplierName) && StringUtil.isNotEmpty(enabled)) {
-                Supplier s = new Supplier();
-                s.setType(type);
-                s.setSupplier(supplierName);
-                s.setContacts(ExcelUtils.getContent(src, i, 1));
-                s.setTelephone(ExcelUtils.getContent(src, i, 2));
-                s.setPhoneNum(ExcelUtils.getContent(src, i, 3));
-                s.setEmail(ExcelUtils.getContent(src, i, 4));
-                s.setTaxNum(ExcelUtils.getContent(src, i, 5));
-                s.setInvoiceType(ExcelUtils.getContent(src, i, 6));
-                s.setTaxRate(parseBigDecimalEx(ExcelUtils.getContent(src, i, 7)));
-                s.setBankName(ExcelUtils.getContent(src, i, 8));
-                s.setAccountNumber(ExcelUtils.getContent(src, i, 9));
-                s.setAddress(ExcelUtils.getContent(src, i, 10));
-                s.setSupplierLevel(ExcelUtils.getContent(src, i, 11));
-                s.setSettlementMethod(ExcelUtils.getContent(src, i, 12));
-                s.setBillingCycleDays(Integer.valueOf(ExcelUtils.getContent(src, i, 13)));
-                s.setProcurementContact(ExcelUtils.getContent(src, i, 14));
-                s.setDeliverydays(Integer.valueOf(ExcelUtils.getContent(src, i, 15)));
-                s.setDescription(ExcelUtils.getContent(src, i, 16));
-                s.setSort(ExcelUtils.getContent(src, i, 17));
-                s.setCreator(userInfo==null?null:userInfo.getId());
-                s.setEnabled("1".equals(enabled));
-                sList.add(s);
-            }
-        }
-        importExcel(sList, type, request);
-    }
+    void importCustomer(MultipartFile file, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void importCustomer(MultipartFile file, HttpServletRequest request) throws Exception{
-        String type = "客户";
-        User userInfo = userService.getCurrentUser();
-        Workbook workbook = Workbook.getWorkbook(file.getInputStream());
-        Sheet src = workbook.getSheet(0);
-        //'名称', '联系人', '手机号码', '联系电话', '电子邮箱', '传真', '期初应收', '纳税人识别号', '税率(%)', '开户行', '账号', '地址', '备注', '排序', '状态'
-        List<Supplier> sList = new ArrayList<>();
-        for (int i = 2; i < src.getRows(); i++) {
-            String supplierName = ExcelUtils.getContent(src, i, 0);
-            String enabled = ExcelUtils.getContent(src, i, 14);
-            if(StringUtil.isNotEmpty(supplierName) && StringUtil.isNotEmpty(enabled)) {
-                Supplier s = new Supplier();
-                s.setType(type);
-                s.setSupplier(supplierName);
-                s.setContacts(ExcelUtils.getContent(src, i, 1));
-                s.setTelephone(ExcelUtils.getContent(src, i, 2));
-                s.setPhoneNum(ExcelUtils.getContent(src, i, 3));
-                s.setEmail(ExcelUtils.getContent(src, i, 4));
-                s.setFax(ExcelUtils.getContent(src, i, 5));
-                s.setBeginNeedGet(parseBigDecimalEx(ExcelUtils.getContent(src, i, 6)));
-                s.setTaxNum(ExcelUtils.getContent(src, i, 7));
-                s.setTaxRate(parseBigDecimalEx(ExcelUtils.getContent(src, i, 8)));
-                s.setBankName(ExcelUtils.getContent(src, i, 9));
-                s.setAccountNumber(ExcelUtils.getContent(src, i, 10));
-                s.setAddress(ExcelUtils.getContent(src, i, 11));
-                s.setDescription(ExcelUtils.getContent(src, i, 12));
-                s.setSort(ExcelUtils.getContent(src, i, 13));
-                s.setCreator(userInfo==null?null:userInfo.getId());
-                s.setEnabled("1".equals(enabled));
-                sList.add(s);
-            }
-        }
-        importExcel(sList, type, request);
-    }
+    void importMember(MultipartFile file, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void importMember(MultipartFile file, HttpServletRequest request) throws Exception{
-        String type = "会员";
-        User userInfo = userService.getCurrentUser();
-        Workbook workbook = Workbook.getWorkbook(file.getInputStream());
-        Sheet src = workbook.getSheet(0);
-        //'名称', '联系人', '手机号码', '联系电话', '电子邮箱', '备注', '排序', '状态'
-        List<Supplier> sList = new ArrayList<>();
-        for (int i = 2; i < src.getRows(); i++) {
-            String supplierName = ExcelUtils.getContent(src, i, 0);
-            String enabled = ExcelUtils.getContent(src, i, 7);
-            if(StringUtil.isNotEmpty(supplierName) && StringUtil.isNotEmpty(enabled)) {
-                Supplier s = new Supplier();
-                s.setType(type);
-                s.setSupplier(supplierName);
-                s.setContacts(ExcelUtils.getContent(src, i, 1));
-                s.setTelephone(ExcelUtils.getContent(src, i, 2));
-                s.setPhoneNum(ExcelUtils.getContent(src, i, 3));
-                s.setEmail(ExcelUtils.getContent(src, i, 4));
-                s.setDescription(ExcelUtils.getContent(src, i, 5));
-                s.setSort(ExcelUtils.getContent(src, i, 6));
-                s.setCreator(userInfo==null?null:userInfo.getId());
-                s.setEnabled("1".equals(enabled));
-                sList.add(s);
-            }
-        }
-        importExcel(sList, type, request);
-    }
+    BaseResponseInfo importExcel(List<Supplier> mList, String type, HttpServletRequest request) throws Exception;
+
+    BigDecimal parseBigDecimalEx(String str)throws Exception;
+
+    File exportExcel(List<Supplier> dataList, String type) throws Exception;
+
+    File exportExcelVendorOrCustomer(List<Supplier> dataList, String type) throws Exception;
+
+    String mapInvoiceType(String invoiceType);
+
+    String mapSettlementMethod(String settlementMethod);
+
+    void setUserCustomerPermission(HttpServletRequest request, Supplier supplier) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public BaseResponseInfo importExcel(List<Supplier> mList, String type, HttpServletRequest request) throws Exception {
-        logService.insertLog(type,
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_IMPORT).append(mList.size()).append(BusinessConstants.LOG_DATA_UNIT).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        BaseResponseInfo info = new BaseResponseInfo();
-        Map<String, Object> data = new HashMap<>();
-        try {
-            for(Supplier supplier: mList) {
-                SupplierExample example = new SupplierExample();
-                example.createCriteria().andSupplierEqualTo(supplier.getSupplier()).andTypeEqualTo(type).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-                List<Supplier> list= supplierMapper.selectByExample(example);
-                if(list.size() <= 0) {
-                    supplierMapper.insertSelective(supplier);
-                    //新增客户时给当前用户自动授权
-                    setUserCustomerPermission(request, supplier);
-                } else {
-                    Long id = list.get(0).getId();
-                    supplier.setId(id);
-                    supplierMapper.updateByPrimaryKeySelective(supplier);
-                }
-            }
-            info.code = 200;
-            data.put("message", "成功");
-        } catch (Exception e) {
-            logger.error(e.getMessage(), e);
-            info.code = 500;
-            data.put("message", e.getMessage());
-        }
-        info.data = data;
-        return info;
-    }
-
-    public BigDecimal parseBigDecimalEx(String str)throws Exception{
-        if(!StringUtil.isEmpty(str)) {
-            return new BigDecimal(str);
-        } else {
-            return null;
-        }
-    }
-
-    public File exportExcel(List<Supplier> dataList, String type) throws Exception {
-        if("供应商".equals(type)) {
-            return exportExcelVendorOrCustomer(dataList, type);
-        } else if("客户".equals(type)) {
-            return exportExcelVendorOrCustomer(dataList, type);
-        } else {
-            //会员
-            String[] names = {"会员卡号*", "联系人", "手机号码", "联系电话", "电子邮箱", "备注", "排序", "状态*"};
-            String title = "信息内容";
-            List<String[]> objects = new ArrayList<String[]>();
-            if (null != dataList) {
-                for (Supplier s : dataList) {
-                    String[] objs = new String[names.length];
-                    objs[0] = s.getSupplier();
-                    objs[1] = s.getContacts();
-                    objs[2] = s.getTelephone();
-                    objs[3] = s.getPhoneNum();
-                    objs[4] = s.getEmail();
-                    objs[5] = s.getDescription();
-                    objs[6] = s.getSort();
-                    objs[7] = s.getEnabled() ? "1" : "0";
-                    objects.add(objs);
-                }
-            }
-            return ExcelUtils.exportObjectsOneSheet(title, "*导入时本行内容请勿删除,切记!", names, title, objects);
-        }
-    }
-
-    private File exportExcelVendorOrCustomer(List<Supplier> dataList, String type) throws Exception {
-        /*String beginNeedStr = "";
-        if("供应商".equals(type)) {
-            beginNeedStr = "期初应付";
-        } else if("客户".equals(type)) {
-            beginNeedStr = "期初应收";
-        }*/
-        String[] names = {"名称*", "联系人", "手机号码", "联系电话", "电子邮箱",
-                "纳税人识别号", "发票类型","税率(%)", "开户行", "账号", "地址","供应商分级",
-                "结算方式", "账单周期", "采购对接人", "到货天数", "备注", "排序", "状态*"};
-        String title = "信息内容";
-        List<String[]> objects = new ArrayList<String[]>();
-        if (null != dataList) {
-            for (Supplier s : dataList) {
-                String[] objs = new String[names.length];
-                objs[0] = s.getSupplier();
-                objs[1] = s.getContacts();
-                objs[2] = s.getTelephone();
-                objs[3] = s.getPhoneNum();
-                objs[4] = s.getEmail();
-                /*if(("客户").equals(s.getType())) {
-                    objs[6] = s.getBeginNeedGet() == null? "" : s.getBeginNeedGet().setScale(2,BigDecimal.ROUND_HALF_UP).toString();
-                } else if(("供应商").equals(s.getType())) {
-                    objs[6] = s.getBeginNeedPay() == null? "" : s.getBeginNeedPay().setScale(2,BigDecimal.ROUND_HALF_UP).toString();
-                }*/
-                objs[5] = s.getTaxNum();
-                // 发票类型
-                objs[6] = mapInvoiceType(s.getInvoiceType());
-                // 税率
-                objs[7] = s.getTaxRate() == null? "" : s.getTaxRate().setScale(2,BigDecimal.ROUND_HALF_UP).toString();
-
-                // 银行信息
-                objs[8] = s.getBankName();
-                objs[9] = s.getAccountNumber();
-                objs[10] = s.getAddress();
-
-                // 供应商分级
-                objs[11] = s.getSupplierLevel();
-
-                // 结算方式
-                objs[12] = mapSettlementMethod(s.getSettlementMethod());
-                // 账单周期
-                objs[13] = s.getBillingCycleDays() == null? "" : s.getBillingCycleDays().toString();
-                // 采购对接人
-                objs[14] = s.getProcurementContact();
-                // 到货天数
-                objs[15] = s.getDeliverydays() == null? "" : s.getDeliverydays().toString();
-                objs[16] = s.getDescription();
-                objs[17] = s.getSort();
-                objs[18] = s.getEnabled() ? "1" : "0";
-                objects.add(objs);
-            }
-        }
-        return ExcelUtils.exportObjectsOneSheet(title, "*导入时本行内容请勿删除,切记!", names, title, objects);
-    }
-
-    private String mapInvoiceType(String invoiceType) {
-        if ("0".equals(invoiceType)) {
-            return "普通发票";
-        } else if ("1".equals(invoiceType)) {
-            return "增值税专用发票";
-        }
-        return "";
-    }
-
-    private String mapSettlementMethod(String settlementMethod) {
-        if ("0".equals(settlementMethod)) {
-            return "周结";
-        } else if ("1".equals(settlementMethod)) {
-            return "现结/按单";
-        } else if ("2".equals(settlementMethod)) {
-            return "预付款";
-        } else if ("3".equals(settlementMethod)) {
-            return "月结";
-        }
-        return "";
-    }
+    int batchSetAdvanceIn(String ids) throws Exception;
 
     /**
-     * 新增客户时给当前用户自动授权
-     * @param request
-     * @param supplier
-     * @throws Exception
+     * 根据类型 和 电话号码查询供应商/客户信息
+     * @param type
+     * @param telephone
+     * @return
      */
-    private void setUserCustomerPermission(HttpServletRequest request, Supplier supplier) throws Exception {
-        if("客户".equals(supplier.getType())) {
-            Long userId = userService.getUserId(request);
-            Supplier sInfo = supplierMapperEx.getSupplierByNameAndType(supplier.getSupplier(), supplier.getType());
-            String ubKey = "[" + sInfo.getId() + "]";
-            List<UserBusiness> ubList = userBusinessService.getBasicData(userId.toString(), "UserCustomer");
-            if(ubList ==null || ubList.size() == 0) {
-                JSONObject ubObj = new JSONObject();
-                ubObj.put("type", "UserCustomer");
-                ubObj.put("keyId", userId);
-                ubObj.put("value", ubKey);
-                UserBusiness userBusiness = JSONObject.parseObject(ubObj.toJSONString(), UserBusiness.class);
-                userBusinessMapper.insertSelective(userBusiness);
-            } else {
-                UserBusiness ubInfo = ubList.get(0);
-                JSONObject ubObj = new JSONObject();
-                ubObj.put("id", ubInfo.getId());
-                ubObj.put("type", ubInfo.getType());
-                ubObj.put("keyId", ubInfo.getKeyId());
-                ubObj.put("value", ubInfo.getValue() + ubKey);
-                UserBusiness userBusiness = JSONObject.parseObject(ubObj.toJSONString(), UserBusiness.class);
-                userBusinessMapper.updateByPrimaryKeySelective(userBusiness);
-            }
-        }
-    }
+    Supplier getSupplierByPhone(String type,String telephone );
 
-    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchSetAdvanceIn(String ids) throws Exception {
-        int res = 0;
-        List<Long> idList = StringUtil.strToLongList(ids);
-        for(Long sId: idList) {
-            updateAdvanceIn(sId);
-            res = 1;
-        }
-        return res;
-    }
+    Supplier getCustomerByPhone(String telephone );
+
+    // 创建新客户
+    Supplier createCustomer(Supplier supplier);
 }

+ 624 - 0
src/main/java/com/jsh/erp/service/SyncTescoSystemService.java

@@ -0,0 +1,624 @@
+package com.jsh.erp.service;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+import com.jsh.erp.constants.ExceptionConstants;
+import com.jsh.erp.datasource.entities.DepotHeadVo4Body;
+import com.jsh.erp.datasource.entities.MaterialVo4Unit;
+import com.jsh.erp.datasource.entities.Supplier;
+import com.jsh.erp.datasource.entities.Unit;
+import com.jsh.erp.datasource.tesco.request.ErpXsddReqVO;
+import com.jsh.erp.datasource.vo.DepotHeadXsddRequestVO;
+import com.jsh.erp.datasource.vo.DepotItemXsddRequestVO;
+import com.jsh.erp.datasource.vo.Material4UnitPrice;
+import com.jsh.erp.exception.BusinessRunTimeException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.BeanUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.CollectionUtils;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * @Description TODO
+ * @Author MS.BLUE
+ * @Date 2025-04-12
+ */
+@Service
+public class SyncTescoSystemService {
+
+    private Logger logger = LoggerFactory.getLogger(SyncTescoSystemService.class);
+
+    @Resource
+    private MaterialService materialService;
+
+    @Resource
+    private DepotHeadService depotHeadService;
+
+    @Resource
+    private SequenceService sequenceService;
+
+    @Resource
+    private SupplierService supplierService;
+
+    public String syncSystemSku(String param) {
+        logger.info("获取商品系统sku,返回信息集采系统 param:{}", param);
+        JSONObject result = new JSONObject();
+        JSONArray dataArray = new JSONArray();
+
+        try {
+            // 参数校验
+            if (param == null || param.isEmpty()) {
+                result.put("code", 1);
+                result.put("msg", "参数不能为空");
+                return result.toJSONString();
+            }
+
+            // 解析传入的JSON参数
+            JSONArray barCodeArray = JSON.parseArray(param);
+            if (barCodeArray == null || barCodeArray.isEmpty()) {
+                result.put("code", 1);
+                result.put("msg", "参数格式错误");
+                return result.toJSONString();
+            }
+
+            // 提取 barCode 到字符串数组
+            List<String> barCodeList = new ArrayList<>();
+            for (int i = 0; i < barCodeArray.size(); i++) {
+                JSONObject barCodeObj = barCodeArray.getJSONObject(i);
+                String barCode = barCodeObj.getString("barCode");
+                barCodeList.add(barCode);
+            }
+
+            // 查询商品信息
+            List<MaterialVo4Unit> materialList = materialService.getMaterialByBarCode(barCodeList);
+            if (materialList != null && !materialList.isEmpty()) {
+                result.put("code", 0);
+                for (MaterialVo4Unit material : materialList) {
+                    JSONObject item = new JSONObject();
+                    item.put("barCode", material.getmBarCode());
+                    item.put("systemSku", material.getSystemSku());
+                    dataArray.add(item);
+                }
+            } else {
+                result.put("code", 1);
+                result.put("msg", "未找到对应商品信息");
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            result.put("code", 1);
+            result.put("msg", "系统异常,请稍后重试");
+        }
+
+        // 将数据数组放入返回结果
+        result.put("data", dataArray);
+        logger.info("  result:{}", result);
+        return result.toJSONString();
+    }
+
+    /**
+     *
+     集采下单成功->封装同步erp销售订单请求体
+
+     {
+     orderSn:"订单编号",
+     customer:{//客户信息
+     name:"客户名称",
+     contact:"客户联系方式",
+     address:"客户地址"
+     },
+     item:[{//订单商品信息
+     erp_sku:"erp_sku编号",
+     unitPrice:"商品单价",
+     quantity:"商品下单数量",
+     price:"商品实付价格"
+     }]
+     }
+
+     * @param param
+     * @return
+     */
+    public String syncOrder(String param) {
+        logger.info("同步集采订单-》销售订单 param:{}", param);
+        JSONObject result = new JSONObject();
+        try {
+            // 解析传入的JSON参数为 ErpXsddReqVO
+            ErpXsddReqVO erpXsddReqVO = JSON.parseObject(param, ErpXsddReqVO.class);
+            if (erpXsddReqVO == null) {
+                result.put("code", 1);
+                result.put("msg", "参数不能为空");
+                return result.toJSONString();
+            }
+
+            // 校验订单编号
+            if (erpXsddReqVO.getOrderSn() == null || erpXsddReqVO.getOrderSn().isEmpty()) {
+                result.put("code", 1);
+                result.put("msg", "订单编号不能为空");
+                return result.toJSONString();
+            }
+
+            // 校验客户信息
+            if (erpXsddReqVO.getCustomer() == null) {
+                result.put("code", 1);
+                result.put("msg", "客户信息不能为空");
+                return result.toJSONString();
+            }
+
+            // 校验订单商品信息
+            if (erpXsddReqVO.getItems() == null || erpXsddReqVO.getItems().isEmpty()) {
+                result.put("code", 1);
+                result.put("msg", "订单商品信息不能为空");
+                return result.toJSONString();
+            }
+
+            // 构建订单和商品信息
+            buildOrderAndItem(erpXsddReqVO);
+
+            // 返回成功结果
+            result.put("code", 0);
+            result.put("msg", "订单同步成功");
+        } catch (Exception e) {
+            logger.error("同步订单发生异常", e);
+            result.put("code", 1);
+            result.put("msg", "系统异常,请稍后重试");
+        }
+        return result.toJSONString();
+    }
+
+    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
+    private void buildOrderAndItem(ErpXsddReqVO erpXsddReqVO) throws Exception {
+        // 1. 初始化订单基本信息
+        DepotHeadXsddRequestVO order = initSalesOrder(erpXsddReqVO);
+
+        // 2. 处理订单商品项
+        List<DepotItemXsddRequestVO> itemList = processOrderItems(erpXsddReqVO, order);
+
+        // 3. 提交订单
+        depotHeadService.syncOrderToXsdd(order, itemList);
+    }
+
+    private DepotHeadXsddRequestVO initSalesOrder(ErpXsddReqVO erpXsddReqVO) throws Exception {
+        DepotHeadXsddRequestVO order = new DepotHeadXsddRequestVO();
+        order.setType("其它");
+        order.setSubType("销售订单");
+        order.setLinkTesco(erpXsddReqVO.getOrderSn());
+
+        ErpXsddReqVO.Customer customer = erpXsddReqVO.getCustomer();
+        // 根据手机号查询客户
+        Supplier supplier = supplierService.getCustomerByPhone(customer.getAccount());
+        if (supplier == null) {
+            // 如果客户不存在,创建新客户
+            supplier = new Supplier();
+            supplier.setSupplier(customer.getName());
+            supplier.setTelephone(customer.getAccount());
+            supplier.setContacts(customer.getReceiverName());
+            supplier.setPhoneNum(customer.getReceiverPhone());
+            supplier.setAddress(customer.getReceiverAddress());
+            supplier = supplierService.createCustomer(supplier);
+        }
+
+        // 绑定客户 ID
+        order.setOrganId(supplier.getId());
+        order.setReceiverName(customer.getReceiverName());
+        order.setReceiverPhone(customer.getReceiverPhone());
+        order.setReceiverAddress(customer.getReceiverAddress());
+        order.setRemark("集采同步订单");
+        String number = sequenceService.buildOnlyNumber();
+        String defaultNumber = "XSDD" + number;
+        order.setDefaultNumber(defaultNumber);
+        order.setNumber(defaultNumber);
+        order.setCreateTime(new Date());
+        order.setOperTime(new Date());
+        order.setCreator(1L); // 创建人ID
+        order.setAccountId(1L); // 账户ID
+        order.setChangeAmount(BigDecimal.ZERO);
+        order.setBackAmount(BigDecimal.ZERO);
+        order.setTotalPrice(erpXsddReqVO.getTotalPrice());
+        order.setPayType("现付");
+        order.setDiscount(BigDecimal.ZERO);
+        order.setDiscountMoney(BigDecimal.ZERO);
+        order.setDiscountLastMoney(erpXsddReqVO.getTotalPrice());
+        order.setStatus("0");
+        order.setPurchaseStatus("0");
+        order.setSource("2"); // 来源集采商城
+        order.setTenantId(null);
+        order.setDeleteFlag("0");
+        return order;
+    }
+
+    /**
+     * 处理订单商品项
+     */
+    private List<DepotItemXsddRequestVO> processOrderItems(ErpXsddReqVO erpXsddReqVO, DepotHeadXsddRequestVO order) throws Exception {
+
+        List<DepotItemXsddRequestVO> itemList = new ArrayList<>();
+        List<ErpXsddReqVO.OrderItem> reqVOItems = erpXsddReqVO.getItems();
+
+        // 1. 获取所有商品信息
+        List<String> systemSkuList = reqVOItems.stream().map(ErpXsddReqVO.OrderItem::getErpSku).collect(Collectors.toList());
+        List<MaterialVo4Unit> materialList = materialService.getMaterialBySystemSku(systemSkuList);
+        Map<String, List<MaterialVo4Unit>> skuToMaterialMap = materialList.stream().collect(Collectors.groupingBy(MaterialVo4Unit::getSystemSku));
+
+        // 2. 处理每个订单项
+        for (ErpXsddReqVO.OrderItem reqVOItem : reqVOItems) {
+            try {
+                processSingleOrderItem(reqVOItem, order, itemList, skuToMaterialMap);
+            } catch (Exception e) {
+                logger.error("处理订单项失败 erp_sku: {}: {}", reqVOItem.getErpSku(), e.getMessage());
+                throw e;
+            }
+        }
+
+        return itemList;
+    }
+
+
+    /**
+     * 处理单个订单项
+     */
+    private void processSingleOrderItem(ErpXsddReqVO.OrderItem reqVOItem, DepotHeadXsddRequestVO order, List<DepotItemXsddRequestVO> itemList, Map<String, List<MaterialVo4Unit>> skuToMaterialMap) throws Exception {
+
+        // 1. 参数校验
+        validateOrderItem(reqVOItem);
+
+        // 2. 获取商品信息
+        List<MaterialVo4Unit> materials = skuToMaterialMap.get(reqVOItem.getErpSku());
+        if (CollectionUtils.isEmpty(materials)) {
+            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_ERP_SKU_NOT_DECIMAL_CODE, String.format(ExceptionConstants.MATERIAL_ERP_SKU_NOT_DECIMAL_MSG, reqVOItem.getErpSku()));
+        }
+
+        // 3. 获取单位信息
+        MaterialVo4Unit primaryMaterial = materials.get(0);
+        Material4UnitPrice material4UnitPrice = getMaterial4UnitPrice(primaryMaterial);
+
+        // 4. 匹配销售单位
+        UnitMatchResult matchResult = matchUnitAndCalculateBaseQuantity(reqVOItem.getUnitPrice(), BigDecimal.valueOf(reqVOItem.getQuantity()), material4UnitPrice);
+
+        // 5. 根据单位类型分配库存
+        if (matchResult.isLargeUnit()) {
+            allocateLargeUnitStock(reqVOItem, order, itemList, materials, matchResult, material4UnitPrice);
+        } else {
+            allocateBasicUnitStock(reqVOItem, order, itemList, materials, matchResult);
+        }
+    }
+
+    /**
+     * 分配大单位库存(不拆分配)
+     */
+    private void allocateLargeUnitStock(ErpXsddReqVO.OrderItem reqVOItem, DepotHeadXsddRequestVO order, List<DepotItemXsddRequestVO> itemList, List<MaterialVo4Unit> materials,
+        UnitMatchResult matchResult, Material4UnitPrice material4UnitPrice) throws Exception {
+
+        String orderUnit = matchResult.getMatchedUnit();
+        BigDecimal unitRatio = getUnitRatio(orderUnit, material4UnitPrice);
+        BigDecimal remainingOrderQty = matchResult.getOrderUnitQuantity();
+
+        // 分配库存
+        for (MaterialVo4Unit m : materials) {
+            if (remainingOrderQty.compareTo(BigDecimal.ZERO) <= 0)
+                break;
+
+            BigDecimal inventory = m.getInventory();
+            if (inventory.compareTo(unitRatio) < 0)
+                continue;
+
+            // 计算可分配数量(向下取整)
+            BigDecimal allocatableUnits = inventory.divideToIntegralValue(unitRatio).min(remainingOrderQty);
+
+            if (allocatableUnits.compareTo(BigDecimal.ZERO) > 0) {
+                BigDecimal allocBaseQty = allocatableUnits.multiply(unitRatio);
+
+                // 创建订单项
+                DepotItemXsddRequestVO item = createOrderItem(order, m, orderUnit, allocatableUnits, allocBaseQty, reqVOItem.getUnitPrice());
+                itemList.add(item);
+
+                // 更新库存
+                m.setInventory(inventory.subtract(allocBaseQty));
+
+                // 更新剩余需求
+                remainingOrderQty = remainingOrderQty.subtract(allocatableUnits);
+
+                logger.info("分配库存:批次[{}] 分配 {} {} (剩余需求: {})", m.getBatchNumber(), allocatableUnits.toPlainString(), orderUnit, remainingOrderQty.toPlainString());
+            }
+        }
+
+        // 检查是否完全分配
+        if (remainingOrderQty.compareTo(BigDecimal.ZERO) > 0) {
+            throw new RuntimeException(buildStockShortageMessage(reqVOItem.getErpSku(), matchResult.getOrderUnitQuantity(), remainingOrderQty, orderUnit, materials, true, // 是大单位
+                material4UnitPrice));
+        }
+    }
+
+    /**
+     * 分配基本单位库存
+     */
+    private void allocateBasicUnitStock(ErpXsddReqVO.OrderItem reqVOItem, DepotHeadXsddRequestVO order, List<DepotItemXsddRequestVO> itemList, List<MaterialVo4Unit> materials, UnitMatchResult matchResult) throws Exception {
+
+        // 获取基本参数
+        BigDecimal remainingQty = matchResult.getBaseQuantity(); // 剩余需求数量(基本单位)
+        String basicUnit = matchResult.getMatchedUnit(); // 基本单位名称
+        String erpSku = reqVOItem.getErpSku();
+        BigDecimal unitPrice = reqVOItem.getUnitPrice();
+
+        // 记录原始需求用于错误提示
+        BigDecimal originalQty = remainingQty;
+
+        // 遍历库存批次进行分配
+        for (MaterialVo4Unit m : materials) {
+            if (remainingQty.compareTo(BigDecimal.ZERO) <= 0) {
+                break; // 需求已满足
+            }
+
+            BigDecimal inventory = m.getInventory();
+            if (inventory.compareTo(BigDecimal.ZERO) <= 0) {
+                continue; // 跳过无库存批次
+            }
+
+            // 计算当前批次可分配数量
+            BigDecimal allocateQty = inventory.min(remainingQty);
+
+            // 创建订单明细项
+            DepotItemXsddRequestVO item = createOrderItem(order, m, basicUnit, allocateQty, allocateQty, unitPrice);
+            itemList.add(item);
+
+            // 更新库存
+            m.setInventory(inventory.subtract(allocateQty));
+
+            // 更新剩余需求
+            remainingQty = remainingQty.subtract(allocateQty);
+
+            logger.info("分配基本单位库存:批次[{}]  分配 {} {} (剩余需求: {})", m.getBatchNumber(), allocateQty.toPlainString(), basicUnit, remainingQty.toPlainString());
+        }
+
+        // 检查是否完全分配
+        if (remainingQty.compareTo(BigDecimal.ZERO) > 0) {
+            // 在allocateBasicUnitStock方法中调用
+            throw new RuntimeException(buildStockShortageMessage(erpSku, originalQty, remainingQty, basicUnit, materials, false, null));
+        }
+    }
+
+
+    /**
+     * 构建库存不足提示信息(通用方法,支持基本单位和大单位)
+     *
+     * @param erpSku 商品SKU
+     * @param totalQty 总需求数量
+     * @param remainingQty 剩余未分配数量
+     * @param orderUnit 订单单位
+     * @param materials 库存列表
+     * @param isLargeUnit 是否为大单位
+     * @param material4UnitPrice 单位价格信息(大单位时需要)
+     * @return 完整的库存不足提示信息
+     */
+    private String buildStockShortageMessage(String erpSku, BigDecimal totalQty, BigDecimal remainingQty, String orderUnit, List<MaterialVo4Unit> materials, boolean isLargeUnit, Material4UnitPrice material4UnitPrice) {
+
+        StringBuilder sb = new StringBuilder();
+        sb.append("商品[").append(erpSku).append("]库存不足!\n");
+        sb.append("需求: ").append(totalQty.toPlainString()).append(" ").append(orderUnit).append("\n");
+        sb.append("未分配: ").append(remainingQty.toPlainString()).append(" ").append(orderUnit).append("\n");
+        sb.append("当前库存:\n");
+
+        // 获取基本单位名称
+        String basicUnit = isLargeUnit ? material4UnitPrice.getBasicUnit() : orderUnit;
+
+        materials.forEach(m -> {
+            // 计算当前批次的显示库存量
+            String stockDisplay;
+            if (isLargeUnit) {
+                BigDecimal unitRatio = getUnitRatio(orderUnit, material4UnitPrice);
+                BigDecimal stockInOrderUnit = m.getInventory().divideToIntegralValue(unitRatio);
+                stockDisplay = String.format("%s %s (%s %s)", stockInOrderUnit.toPlainString(), orderUnit, m.getInventory().toPlainString(), basicUnit);
+            } else {
+                stockDisplay = m.getInventory().toPlainString() + " " + basicUnit;
+            }
+
+            sb.append(String.format("批次[%s] 生产日期[%s] - 库存: %s\n", m.getBatchNumber(), m.getProductionDate(), stockDisplay));
+        });
+
+        // 添加建议提示
+        if (isLargeUnit) {
+            sb.append("\n提示:").append(orderUnit).append("与").append(basicUnit).append("的换算比例为: 1").append(orderUnit).append("=").append(getUnitRatio(orderUnit, material4UnitPrice).toPlainString()).append(basicUnit);
+        }
+
+        return sb.toString();
+    }
+
+
+    /**
+     * 订单项参数校验
+     */
+    private void validateOrderItem(ErpXsddReqVO.OrderItem item) throws Exception {
+        if (item.getQuantity() == null || item.getQuantity() <= 0) {
+            throw new RuntimeException("商品数量必须大于0");
+        }
+        if (item.getUnitPrice() == null || item.getUnitPrice().compareTo(BigDecimal.ZERO) <= 0) {
+            throw new RuntimeException("商品单价必须大于0");
+        }
+        if (StringUtils.isBlank(item.getErpSku())) {
+            throw new RuntimeException("商品SKU不能为空");
+        }
+    }
+
+
+
+    
+
+    /**
+     * 创建订单明细项
+     */
+    private DepotItemXsddRequestVO createOrderItem(DepotHeadXsddRequestVO order, MaterialVo4Unit material, String unit, BigDecimal operNumber, BigDecimal basicNumber, BigDecimal unitPrice) {
+        DepotItemXsddRequestVO item = new DepotItemXsddRequestVO();
+        item.setHeaderId(order.getId());
+        item.setMaterialId(material.getId());
+        item.setMaterialExtendId(material.getMeId());
+        item.setMaterialUnit(unit);
+        item.setSku(material.getSku());
+        item.setDepotId(material.getDepotId());
+        item.setOperNumber(operNumber);
+        item.setBasicNumber(basicNumber);
+        item.setUnitPrice(unitPrice);
+        item.setTaxRate(BigDecimal.ONE);
+        item.setTaxMoney(BigDecimal.ZERO);
+        item.setBatchNumber("");
+        item.setTaxLastMoney(unitPrice.multiply(operNumber));
+        item.setAllPrice(unitPrice.multiply(operNumber));
+        return item;
+    }
+
+
+    private Material4UnitPrice getMaterial4UnitPrice(MaterialVo4Unit material) throws Exception {
+        Material4UnitPrice material4UnitPrice = new Material4UnitPrice();
+        Unit unitInfo = new Unit(); // 查询多单位信息
+        unitInfo.setBasicUnit(material.getCommodityUnit());
+        if(material.getUnitId() != null){
+            unitInfo = materialService.findUnit(material.getId());
+        }
+
+        BeanUtils.copyProperties(unitInfo, material4UnitPrice);
+
+        // 设置基础单位价格、基础数量
+        material4UnitPrice.setBasicUnitPrice(material.getWholesaleDecimal());
+        material4UnitPrice.setBasicUnitNumber(BigDecimal.ONE);
+
+        // 设置其他单位价格、其他数量
+        if (StringUtils.isNotEmpty(material4UnitPrice.getOtherUnit())) {
+            material4UnitPrice.setOtherUnitPrice(material.getWholesaleDecimal().multiply(material4UnitPrice.getRatio()));
+            material4UnitPrice.setOtherUnitNumber(material4UnitPrice.getRatio());
+        }
+
+        // 设置其他单位2价格、其他数量2
+        if (StringUtils.isNotEmpty(material4UnitPrice.getOtherUnitTwo())) {
+            material4UnitPrice.setOtherUnitTwoPrice(material.getWholesaleDecimal().multiply(material4UnitPrice.getRatioTwo()));
+            material4UnitPrice.setOtherUnitTwoNumber(material4UnitPrice.getRatioTwo());
+        }
+
+        // 设置其他单位3价格、其他数量3
+        if (StringUtils.isNotEmpty(material4UnitPrice.getOtherUnitThree())) {
+            material4UnitPrice.setOtherUnitThreePrice(material.getWholesaleDecimal().multiply(material4UnitPrice.getRatioThree()));
+            material4UnitPrice.setOtherUnitThreeNumber(material4UnitPrice.getRatioThree());
+        }
+        return material4UnitPrice;
+    }
+
+
+
+    /**
+     * 根据单价匹配单位并计算基本单位数量<br>
+     * 如果订单商品单价和商品最小单位单价相等,则使用最小单位, remainingQuantity = quantity<br>
+     * 如果订单商品单价和商品其他单位单价相等,则使用其他单位, remainingQuantity = quantity * material4UnitPrice.getRatio()<br>
+     * 如果订单商品单价和商品其他单位2单价相等,则使用其他单位2, remainingQuantity = quantity * material4UnitPrice.getRatioTwo()<br>
+     * 如果订单商品单价和商品其他单位3单价相等,则使用其他单位3, remainingQuantity = quantity * material4UnitPrice.getRatioThree()<br>
+     */
+    private UnitMatchResult matchUnitAndCalculateBaseQuantity(BigDecimal orderUnitPrice, BigDecimal orderQuantity, Material4UnitPrice material4UnitPrice) {
+        // 允许的价格误差范围
+        final BigDecimal PRICE_TOLERANCE = new BigDecimal("0.001");
+
+        // 1. 检查是否匹配基本单位价格
+        if (material4UnitPrice.getBasicUnitPrice() != null && orderUnitPrice.subtract(material4UnitPrice.getBasicUnitPrice()).abs().compareTo(PRICE_TOLERANCE) <= 0) {
+            return new UnitMatchResult(material4UnitPrice.getBasicUnit(), orderQuantity, orderQuantity, false);
+        }
+
+        // 2. 检查是否匹配副单位价格
+        if (material4UnitPrice.getOtherUnitPrice() != null && orderUnitPrice.subtract(material4UnitPrice.getOtherUnitPrice()).abs().compareTo(PRICE_TOLERANCE) <= 0) {
+            BigDecimal baseQuantity = orderQuantity.multiply(material4UnitPrice.getRatio());
+            return new UnitMatchResult(material4UnitPrice.getOtherUnit(), orderQuantity, baseQuantity, true);
+        }
+
+        // 3. 检查是否匹配副单位2价格
+        if (material4UnitPrice.getOtherUnitTwoPrice() != null && orderUnitPrice.subtract(material4UnitPrice.getOtherUnitTwoPrice()).abs().compareTo(PRICE_TOLERANCE) <= 0) {
+            BigDecimal baseQuantity = orderQuantity.multiply(material4UnitPrice.getRatioTwo());
+            return new UnitMatchResult(material4UnitPrice.getOtherUnitTwo(), orderQuantity, baseQuantity, true);
+        }
+
+        // 4. 检查是否匹配副单位3价格
+        if (material4UnitPrice.getOtherUnitThreePrice() != null && orderUnitPrice.subtract(material4UnitPrice.getOtherUnitThreePrice()).abs().compareTo(PRICE_TOLERANCE) <= 0) {
+            BigDecimal baseQuantity = orderQuantity.multiply(material4UnitPrice.getRatioThree());
+            return new UnitMatchResult(material4UnitPrice.getOtherUnitThree(), orderQuantity, baseQuantity, true);
+        }
+
+        // 5. 默认返回基本单位(如果无法匹配)
+        return new UnitMatchResult(material4UnitPrice.getBasicUnit(), orderQuantity, orderQuantity, false);
+    }
+
+
+
+    /**
+     * 将基本单位数量转换为订单单位数量
+     */
+    private BigDecimal convertToOrderUnitQuantity(BigDecimal baseQuantity, String orderUnit, Material4UnitPrice material4UnitPrice) {
+        if (orderUnit.equals(material4UnitPrice.getBasicUnit())) {
+            return baseQuantity;
+        } else if (orderUnit.equals(material4UnitPrice.getOtherUnit())) {
+            return baseQuantity.divide(material4UnitPrice.getRatio());
+        } else if (orderUnit.equals(material4UnitPrice.getOtherUnitTwo())) {
+            return baseQuantity.divide(material4UnitPrice.getRatioTwo());
+        } else if (orderUnit.equals(material4UnitPrice.getOtherUnitThree())) {
+            return baseQuantity.divide(material4UnitPrice.getRatioThree());
+        }
+        return baseQuantity;
+    }
+
+    /**
+     * 获取单位的换算比例
+     */
+    private BigDecimal getUnitRatio(String unit, Material4UnitPrice material4UnitPrice) {
+        if (unit.equals(material4UnitPrice.getBasicUnit())) {
+            return BigDecimal.ONE;
+        } else if (unit.equals(material4UnitPrice.getOtherUnit())) {
+            return material4UnitPrice.getRatio();
+        } else if (unit.equals(material4UnitPrice.getOtherUnitTwo())) {
+            return material4UnitPrice.getRatioTwo();
+        } else if (unit.equals(material4UnitPrice.getOtherUnitThree())) {
+            return material4UnitPrice.getRatioThree();
+        }
+        return BigDecimal.ONE;
+    }
+
+    /**
+     * 单位匹配结果类
+     */
+    private static class UnitMatchResult {
+        private String matchedUnit;          // 匹配到的单位
+        private BigDecimal orderUnitQuantity; // 订单单位数量
+        private BigDecimal baseQuantity;     // 基本单位数量
+        private boolean isLargeUnit;         // 是否是大单位
+
+        public UnitMatchResult(String matchedUnit, BigDecimal orderUnitQuantity,
+                               BigDecimal baseQuantity, boolean isLargeUnit) {
+            this.matchedUnit = matchedUnit;
+            this.orderUnitQuantity = orderUnitQuantity;
+            this.baseQuantity = baseQuantity;
+            this.isLargeUnit = isLargeUnit;
+        }
+
+        // getter方法
+        public String getMatchedUnit() {
+            return matchedUnit;
+        }
+
+        public BigDecimal getBaseQuantity() {
+            return baseQuantity;
+        }
+
+        public boolean isLargeUnit() {
+            return isLargeUnit;
+        }
+
+        public BigDecimal getOrderUnitQuantity() {
+            return orderUnitQuantity;
+        }
+
+    }
+
+
+}

+ 18 - 11
src/main/java/com/jsh/erp/service/SystemConfigService.java

@@ -62,6 +62,21 @@ public class SystemConfigService {
     @Value(value="${file.path}")
     private String filePath;
 
+    @Value(value="${aliyun.oss.endPoint}")
+    private String endpoint;
+
+    @Value(value="${aliyun.accessKeyId}")
+    private String accessKeyId;
+
+    @Value(value="${aliyun.secretAccessKey}")
+    private String accessKeySecret;
+
+    @Value(value="${aliyun.oss.bucketName}")
+    private String bucketName;
+
+    @Value(value="${aliyun.oss.linkUrl}")
+    private String aliOssLinkUrl;
+
     private static String DELETED = "deleted";
 
     public SystemConfig getSystemConfig(long id)throws Exception {
@@ -248,10 +263,6 @@ public class SystemConfigService {
         String token = request.getHeader("X-Access-Token");
         Long tenantId = Tools.getTenantIdByToken(token);
         bizPath = bizPath + "/" + tenantId;
-        String endpoint = platformConfigService.getPlatformConfigByKey("aliOss_endpoint").getPlatformValue();
-        String accessKeyId = platformConfigService.getPlatformConfigByKey("aliOss_accessKeyId").getPlatformValue();
-        String accessKeySecret = platformConfigService.getPlatformConfigByKey("aliOss_accessKeySecret").getPlatformValue();
-        String bucketName = platformConfigService.getPlatformConfigByKey("aliOss_bucketName").getPlatformValue();
         // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
         String fileName = "";
         String orgName = mf.getOriginalFilename();// 获取文件名
@@ -310,7 +321,7 @@ public class SystemConfigService {
                 ossClient.putObject(putSmallObjectRequest);
             }
             // 返回路径
-            return bizPath + "/" + fileName;
+            return getFileUrlAliOss(bizPath + "/" + fileName);
         } catch (OSSException oe) {
             logger.error("Caught an OSSException, which means your request made it to OSS, "
                     + "but was rejected with an error response for some reason.");
@@ -336,7 +347,7 @@ public class SystemConfigService {
     }
 
     public String getFileUrlAliOss(String imgPath) throws Exception {
-        String linkUrl = platformConfigService.getPlatformConfigByKey("aliOss_linkUrl").getPlatformValue();
+        String linkUrl = aliOssLinkUrl;
         return linkUrl + filePath + "/" + imgPath;
     }
 
@@ -381,10 +392,6 @@ public class SystemConfigService {
             }
         } else if(fileUploadType == 2) {
             //oss
-            String endpoint = platformConfigService.getPlatformConfigByKey("aliOss_endpoint").getPlatformValue();
-            String accessKeyId = platformConfigService.getPlatformConfigByKey("aliOss_accessKeyId").getPlatformValue();
-            String accessKeySecret = platformConfigService.getPlatformConfigByKey("aliOss_accessKeySecret").getPlatformValue();
-            String bucketName = platformConfigService.getPlatformConfigByKey("aliOss_bucketName").getPlatformValue();
             for(String pathStr: pathList) {
                 if(StringUtil.isNotEmpty(pathStr)) {
                     String[] pathArr = pathStr.split(",");
@@ -647,4 +654,4 @@ public class SystemConfigService {
         File file = ExcelUtils.exportObjectsOneSheet(title, tip, names, title, objects);
         ExcelUtils.downloadExcel(file, file.getName(), response);
     }
-}
+}

+ 7 - 0
src/main/java/com/jsh/erp/service/TaskStocktakingItemService.java

@@ -0,0 +1,7 @@
+package com.jsh.erp.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.jsh.erp.datasource.entities.TaskStocktakingItem;
+
+public interface TaskStocktakingItemService extends IService<TaskStocktakingItem> {
+}

+ 67 - 0
src/main/java/com/jsh/erp/service/TaskStocktakingService.java

@@ -0,0 +1,67 @@
+package com.jsh.erp.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.jsh.erp.datasource.dto.TaskStocktakingDTO;
+import com.jsh.erp.datasource.entities.TaskStocktaking;
+import com.jsh.erp.datasource.pda.vo.PDATaskStocktakingItemVO;
+import com.jsh.erp.datasource.pda.vo.PDATaskStocktakingVO;
+import com.jsh.erp.datasource.vo.TaskStocktakingItemVO;
+import com.jsh.erp.datasource.vo.TaskStocktakingVO;
+
+import java.util.List;
+
+public interface TaskStocktakingService extends IService<TaskStocktaking> {
+
+    /**
+     *
+     * @return
+     */
+    List<TaskStocktakingVO> listBy();
+
+    /**
+     * 新增任务
+     * @param taskStocktakingDTO
+     * @return
+     */
+    boolean add(TaskStocktakingDTO taskStocktakingDTO);
+
+    /**
+     * 任务-详情
+     * @param id 任务ID
+     */
+    TaskStocktakingVO detail(Long id) throws Exception;
+
+    /**
+     * 任务详情-修改
+     * @param taskStocktakingDTO
+     * @return
+     */
+    boolean detailUpdate(TaskStocktakingDTO taskStocktakingDTO);
+
+    /**
+     * 任务详情-商品明细
+     * @param taskStocktakingId 盘点任务ID
+     * @return
+     */
+    List<TaskStocktakingItemVO> listByTaskStocktakingId(Long taskStocktakingId);
+
+    /**
+     * PDA-盘点任务列表
+     * @param number 盘点单号或者任务名称
+     * @param taskStatus 盘点任务状态
+     * @return
+     */
+    List<PDATaskStocktakingVO> pdaList(String number , Integer taskStatus);
+
+    /**
+     * PAD-盘点任务详情
+     * @param id 盘点任务ID
+     * @return
+     * @throws Exception
+     */
+    TaskStocktakingVO pdaDetail(Long id) throws Exception;
+
+    List<PDATaskStocktakingItemVO> pdaItemList(Long taskId);
+
+
+}

+ 25 - 0
src/main/java/com/jsh/erp/service/UnitService.java

@@ -10,6 +10,7 @@ import com.jsh.erp.datasource.entities.User;
 import com.jsh.erp.datasource.mappers.MaterialMapperEx;
 import com.jsh.erp.datasource.mappers.UnitMapper;
 import com.jsh.erp.datasource.mappers.UnitMapperEx;
+import com.jsh.erp.datasource.vo.UnitListVo;
 import com.jsh.erp.exception.BusinessRunTimeException;
 import com.jsh.erp.exception.JshException;
 import com.jsh.erp.utils.PageUtils;
@@ -297,4 +298,28 @@ public class UnitService {
         }
         return result;
     }
+
+    /**
+     * 根据单位id获取单位值集合
+     * @param id 单位id
+     */
+    public List getUnitListByID(Long id){
+        Unit unit = unitMapper.selectByPrimaryKey(id);
+        List<UnitListVo> list = new ArrayList();
+        UnitListVo unitListVo = new UnitListVo().setName(unit.getBasicUnit()).setRatio(new BigDecimal("1"));
+        list.add(unitListVo);
+        if (unit.getOtherUnit() != null){
+            UnitListVo vo = new UnitListVo().setName(unit.getOtherUnit()).setRatio(unit.getRatio());
+            list.add(vo);
+        }
+        if (unit.getOtherUnitTwo() != null){
+            UnitListVo vo = new UnitListVo().setName(unit.getOtherUnitTwo()).setRatio(unit.getRatioTwo());
+            list.add(vo);
+        }
+        if (unit.getOtherUnitThree() != null){
+            UnitListVo vo = new UnitListVo().setName(unit.getOtherUnitThree()).setRatio(unit.getRatioThree());
+            list.add(vo);
+        }
+        return list;
+    }
 }

+ 8 - 0
src/main/java/com/jsh/erp/service/UserBusinessService.java

@@ -138,6 +138,14 @@ public class UserBusinessService {
         return ubValue;
     }
 
+    public String[] getUBValuByTypeAndKeyIdToArray(String type, String keyId) throws Exception {
+        String ubValue = getUBValueByTypeAndKeyId(type, keyId);
+        if (ubValue == null || ubValue.length() <= 2) { // "[x]"最小长度3
+            return new String[0];
+        }
+        return ubValue.substring(1, ubValue.length()-1).split("\\]\\[");
+    }
+
     public Long checkIsValueExist(String type, String keyId)throws Exception {
         UserBusinessExample example = new UserBusinessExample();
         example.createCriteria().andTypeEqualTo(type).andKeyIdEqualTo(keyId)

+ 63 - 883
src/main/java/com/jsh/erp/service/UserService.java

@@ -1,925 +1,105 @@
 package com.jsh.erp.service;
 
-import com.jsh.erp.datasource.entities.*;
-import com.jsh.erp.datasource.mappers.TenantMapper;
-import com.jsh.erp.exception.BusinessParamCheckingException;
-import com.jsh.erp.utils.*;
-import org.springframework.util.StringUtils;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.jsh.erp.constants.BusinessConstants;
-import com.jsh.erp.constants.ExceptionConstants;
-import com.jsh.erp.datasource.mappers.UserMapper;
-import com.jsh.erp.datasource.mappers.UserMapperEx;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.jsh.erp.datasource.entities.Role;
+import com.jsh.erp.datasource.entities.User;
+import com.jsh.erp.datasource.entities.UserEx;
+import com.jsh.erp.datasource.vo.SpinnerVO;
 import com.jsh.erp.datasource.vo.TreeNodeEx;
-import com.jsh.erp.exception.BusinessRunTimeException;
-import com.jsh.erp.exception.JshException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
-import java.security.NoSuchAlgorithmException;
-import java.util.*;
-
-@Service
-public class UserService {
-    private Logger logger = LoggerFactory.getLogger(UserService.class);
-
-    @Resource
-    private UserMapper userMapper;
-    @Resource
-    private TenantMapper tenantMapper;
-    @Resource
-    private UserMapperEx userMapperEx;
-    @Resource
-    private OrgaUserRelService orgaUserRelService;
-    @Resource
-    private LogService logService;
-    @Resource
-    private UserService userService;
-    @Resource
-    private TenantService tenantService;
-    @Resource
-    private UserBusinessService userBusinessService;
-    @Resource
-    private RoleService roleService;
-    @Resource
-    private FunctionService functionService;
-    @Resource
-    private PlatformConfigService platformConfigService;
-    @Resource
-    private RedisService redisService;
-
-    @Value("${tenant.userNumLimit}")
-    private Integer userNumLimit;
-
-    @Value("${tenant.tryDayLimit}")
-    private Integer tryDayLimit;
-
-    public User getUser(long id)throws Exception {
-        User result=null;
-        try{
-            result=userMapper.selectByPrimaryKey(id);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
-
-    public List<User> getUserListByIds(String ids)throws Exception {
-        List<Long> idList = StringUtil.strToLongList(ids);
-        List<User> list = new ArrayList<>();
-        try{
-            UserExample example = new UserExample();
-            example.createCriteria().andIdIn(idList);
-            list = userMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<User> getUser(HttpServletRequest request) throws Exception {
-        List<User> list=null;
-        try{
-            //先校验是否登录,然后才能查询用户数据
-            Long userId = this.getUserId(request);
-            if(userId!=null) {
-                UserExample example = new UserExample();
-                example.createCriteria().andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-                list = userMapper.selectByExample(example);
-            }
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<UserEx> select(String userName, String loginName)throws Exception {
-        List<UserEx> list=null;
-        try {
-            //先校验是否登录,然后才能查询用户数据
-            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
-            Long userId = this.getUserId(request);
-            if(userId!=null) {
-                PageUtils.startPage();
-                list = userMapperEx.selectByConditionUser(userName, loginName);
-                for (UserEx ue : list) {
-                    String userType = "";
-                    if (ue.getId().equals(ue.getTenantId())) {
-                        userType = "租户";
-                    } else if (ue.getTenantId() == null) {
-                        userType = "超管";
-                    } else {
-                        userType = "普通";
-                    }
-                    ue.setUserType(userType);
-                    //是否经理
-                    String leaderFlagStr = "";
-                    if ("1".equals(ue.getLeaderFlag())) {
-                        leaderFlagStr = "是";
-                    } else {
-                        leaderFlagStr = "否";
-                    }
-                    ue.setLeaderFlagStr(leaderFlagStr);
-                }
-            }
-        } catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public Long countUser(String userName, String loginName)throws Exception {
-        Long result=null;
-        try{
-            result=userMapperEx.countsByUser(userName, loginName);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return result;
-    }
+import java.util.List;
+import java.util.Map;
+
+public interface UserService extends IService<User> {
+    User getUser(long id)throws Exception;
+
+    /**
+     * 生成用户下拉框
+     * @return
+     */
+    List<SpinnerVO> creatorSpinnerList();
+    List<User> getUserListByIds(String ids)throws Exception;
+
+    List<User> getUser(HttpServletRequest request) throws Exception;
+
+    List<UserEx> select(String userName, String loginName)throws Exception;
+
+    Long countUser(String userName, String loginName)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int insertUser(JSONObject obj, HttpServletRequest request)throws Exception {
-        User user = JSONObject.parseObject(obj.toJSONString(), User.class);
-        String password = "123456";
-        //因密码用MD5加密,需要对密码进行转化
-        try {
-            password = Tools.md5Encryp(password);
-            user.setPassword(password);
-        } catch (NoSuchAlgorithmException e) {
-            logger.error(">>>>>>>>>>>>>>转化MD5字符串错误 :" + e.getMessage());
-        }
-        int result=0;
-        try{
-            result=userMapper.insertSelective(user);
-            logService.insertLog("用户",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(user.getLoginName()).toString(), request);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int insertUser(JSONObject obj, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateUser(JSONObject obj, HttpServletRequest request) throws Exception{
-        User user = JSONObject.parseObject(obj.toJSONString(), User.class);
-        int result=0;
-        try{
-            result=userMapper.updateByPrimaryKeySelective(user);
-            logService.insertLog("用户",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(user.getLoginName()).toString(), request);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int updateUser(JSONObject obj, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int updateUserByObj(User user) throws Exception{
-        logService.insertLog("用户",
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(user.getId()).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        int result=0;
-        try{
-            result=userMapper.updateByPrimaryKeySelective(user);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        return result;
-    }
+    int updateUserByObj(User user) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int resetPwd(String md5Pwd, Long id) throws Exception{
-        int result=0;
-        logService.insertLog("用户",
-                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(id).toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        User u = getUser(id);
-        String loginName = u.getLoginName();
-        if("admin".equals(loginName)){
-            logger.info("禁止重置超管密码");
-        } else {
-            User user = new User();
-            user.setId(id);
-            user.setPassword(md5Pwd);
-            try{
-                result=userMapper.updateByPrimaryKeySelective(user);
-            }catch(Exception e){
-                JshException.writeFail(logger, e);
-            }
-        }
-        return result;
-    }
+    int resetPwd(String md5Pwd, Long id) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int deleteUser(Long id, HttpServletRequest request)throws Exception {
-        return batDeleteUser(id.toString());
-    }
+    int deleteUser(Long id, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchDeleteUser(String ids, HttpServletRequest request)throws Exception {
-        return batDeleteUser(ids);
-    }
+    int batchDeleteUser(String ids, HttpServletRequest request)throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batDeleteUser(String ids) throws Exception{
-        int result=0;
-        StringBuffer sb = new StringBuffer();
-        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
-        List<User> list = getUserListByIds(ids);
-        for(User user: list){
-            if(user.getId().equals(user.getTenantId())) {
-                logger.error("异常码[{}],异常提示[{}],参数,ids:[{}]",
-                        ExceptionConstants.USER_LIMIT_TENANT_DELETE_CODE,ExceptionConstants.USER_LIMIT_TENANT_DELETE_MSG,ids);
-                throw new BusinessRunTimeException(ExceptionConstants.USER_LIMIT_TENANT_DELETE_CODE,
-                        ExceptionConstants.USER_LIMIT_TENANT_DELETE_MSG);
-            }
-            sb.append("[").append(user.getLoginName()).append("]");
-        }
-        logService.insertLog("用户", sb.toString(),
-                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        String[] idsArray =ids.split(",");
-        try{
-            result=userMapperEx.batDeleteOrUpdateUser(idsArray);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        if(result<1){
-            logger.error("异常码[{}],异常提示[{}],参数,ids:[{}]",
-                    ExceptionConstants.USER_DELETE_FAILED_CODE,ExceptionConstants.USER_DELETE_FAILED_MSG,ids);
-            throw new BusinessRunTimeException(ExceptionConstants.USER_DELETE_FAILED_CODE,
-                    ExceptionConstants.USER_DELETE_FAILED_MSG);
-        }
-        return result;
-    }
+    int batDeleteUser(String ids) throws Exception;
 
-    /**
-     * 校验验证码
-     * @param code 验证码
-     * @param uuid 唯一标识
-     * @return 结果
-     */
-    public void validateCaptcha(String code, String uuid) {
-        if(StringUtil.isNotEmpty(code) && StringUtil.isNotEmpty(uuid)) {
-            code = code.trim();
-            uuid = uuid.trim();
-            String verifyKey = BusinessConstants.CAPTCHA_CODE_KEY + uuid;
-            String captcha = redisService.getCacheObject(verifyKey);
-            redisService.deleteObject(verifyKey);
-            if (captcha == null) {
-                logger.error("异常码[{}],异常提示[{}]", ExceptionConstants.USER_JCAPTCHA_EXPIRE_CODE, ExceptionConstants.USER_JCAPTCHA_EXPIRE_MSG);
-                throw new BusinessRunTimeException(ExceptionConstants.USER_JCAPTCHA_EXPIRE_CODE, ExceptionConstants.USER_JCAPTCHA_EXPIRE_MSG);
-            }
-            if (!code.equalsIgnoreCase(captcha)) {
-                logger.error("异常码[{}],异常提示[{}]", ExceptionConstants.USER_JCAPTCHA_ERROR_CODE, ExceptionConstants.USER_JCAPTCHA_ERROR_MSG);
-                throw new BusinessRunTimeException(ExceptionConstants.USER_JCAPTCHA_ERROR_CODE, ExceptionConstants.USER_JCAPTCHA_ERROR_MSG);
-            }
-        } else {
-            logger.error("异常码[{}],异常提示[{}]", ExceptionConstants.USER_JCAPTCHA_EMPTY_CODE, ExceptionConstants.USER_JCAPTCHA_EMPTY_MSG);
-            throw new BusinessRunTimeException(ExceptionConstants.USER_JCAPTCHA_EMPTY_CODE, ExceptionConstants.USER_JCAPTCHA_EMPTY_MSG);
-        }
-    }
+    void validateCaptcha(String code, String uuid);
 
-    /**
-     * 用户登录
-     * @param loginName
-     * @param password
-     * @param request
-     * @return
-     * @throws Exception
-     */
-    public Map<String, Object> login(String loginName, String password, HttpServletRequest request) throws Exception {
-        Map<String, Object> data = new HashMap<>();
-        String msgTip = "";
-        User user = null;
-        //判断用户是否已经登录过,登录过不再处理
-        Object userId = redisService.getObjectFromSessionByKey(request,"userId");
-        if (userId != null) {
-            logger.info("====用户已经登录过, login 方法调用结束====");
-            msgTip = "user already login";
-        }
-        //获取用户状态
-        int userStatus = -1;
-        try {
-            redisService.deleteObjectBySession(request,"userId");
-            userStatus = validateUser(loginName, password);
-        } catch (Exception e) {
-            logger.error(">>>>>>>>>>>>>用户  " + loginName + " 登录 login 方法 访问服务层异常====", e);
-            msgTip = "access service exception";
-        }
-        String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
-        switch (userStatus) {
-            case ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST:
-                msgTip = "user is not exist";
-                break;
-            case ExceptionCodeConstants.UserExceptionCode.USER_PASSWORD_ERROR:
-                msgTip = "user password error";
-                break;
-            case ExceptionCodeConstants.UserExceptionCode.BLACK_USER:
-                msgTip = "user is black";
-                break;
-            case ExceptionCodeConstants.UserExceptionCode.USER_ACCESS_EXCEPTION:
-                msgTip = "access service error";
-                break;
-            case ExceptionCodeConstants.UserExceptionCode.BLACK_TENANT:
-                msgTip = "tenant is black";
-                break;
-            case ExceptionCodeConstants.UserExceptionCode.EXPIRE_TENANT:
-                msgTip = "tenant is expire";
-                break;
-            case ExceptionCodeConstants.UserExceptionCode.USER_CONDITION_FIT:
-                msgTip = "user can login";
-                //验证通过 ,可以登录,放入session,记录登录日志
-                user = getUserByLoginName(loginName);
-                if(user.getTenantId()!=null) {
-                    token = token + "_" + user.getTenantId();
-                }
-                redisService.storageObjectBySession(token,"userId",user.getId());
-                break;
-            default:
-                break;
-        }
-        data.put("msgTip", msgTip);
-        if(user!=null){
-            //校验下密码是不是过于简单
-            boolean pwdSimple = false;
-            if(user.getPassword().equals(Tools.md5Encryp(BusinessConstants.USER_DEFAULT_PASSWORD))) {
-                pwdSimple = true;
-            }
-            user.setPassword(null);
-            redisService.storageObjectBySession(token,"clientIp", Tools.getLocalIp(request));
-            logService.insertLogWithUserId(user.getId(), user.getTenantId(), "用户",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_LOGIN).append(user.getLoginName()).toString(),
-                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-            data.put("token", token);
-            data.put("user", user);
-            data.put("pwdSimple", pwdSimple);
-        }
-        return data;
-    }
-
-    public int validateUser(String loginName, String password) throws Exception {
-        /**默认是可以登录的*/
-        List<User> list = null;
-        try {
-            UserExample example = new UserExample();
-            example.createCriteria().andLoginNameEqualTo(loginName).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            list = userMapper.selectByExample(example);
-            if (null != list && list.size() == 0) {
-                return ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST;
-            } else if(list.size() ==1) {
-                if(list.get(0).getStatus()!=0) {
-                    return ExceptionCodeConstants.UserExceptionCode.BLACK_USER;
-                }
-                Long tenantId = list.get(0).getTenantId();
-                Tenant tenant = tenantService.getTenantByTenantId(tenantId);
-                if(tenant!=null) {
-                    if(tenant.getEnabled()!=null && !tenant.getEnabled()) {
-                        return ExceptionCodeConstants.UserExceptionCode.BLACK_TENANT;
-                    }
-                    if(tenant.getExpireTime()!=null && tenant.getExpireTime().getTime()<System.currentTimeMillis()){
-                        return ExceptionCodeConstants.UserExceptionCode.EXPIRE_TENANT;
-                    }
-                }
-            }
-        } catch (Exception e) {
-            logger.error(">>>>>>>>访问验证用户姓名是否存在后台信息异常", e);
-            return ExceptionCodeConstants.UserExceptionCode.USER_ACCESS_EXCEPTION;
-        }
-        try {
-            UserExample example = new UserExample();
-            example.createCriteria().andLoginNameEqualTo(loginName).andPasswordEqualTo(password)
-                    .andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-            list = userMapper.selectByExample(example);
-            if (null != list && list.size() == 0) {
-                return ExceptionCodeConstants.UserExceptionCode.USER_PASSWORD_ERROR;
-            }
-        } catch (Exception e) {
-            logger.error(">>>>>>>>>>访问验证用户密码后台信息异常", e);
-            return ExceptionCodeConstants.UserExceptionCode.USER_ACCESS_EXCEPTION;
-        }
-        return ExceptionCodeConstants.UserExceptionCode.USER_CONDITION_FIT;
-    }
-
-    public User getUserByLoginName(String loginName)throws Exception {
-        UserExample example = new UserExample();
-        example.createCriteria().andLoginNameEqualTo(loginName).andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<User> list=null;
-        try{
-            list= userMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        User user =null;
-        if(list!=null&&list.size()>0){
-            user = list.get(0);
-        }
-        return user;
-    }
-
-    public int checkIsNameExist(Long id, String name)throws Exception {
-        UserExample example = new UserExample();
-        List<Byte> userStatus = new ArrayList<>();
-        userStatus.add(BusinessConstants.USER_STATUS_NORMAL);
-        example.createCriteria().andIdNotEqualTo(id).andLoginNameEqualTo(name).andStatusIn(userStatus)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<User> list=null;
-        try{
-            list= userMapper.selectByExample(example);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list==null?0:list.size();
-    }
-    /**
-     * create by: cjl
-     * description:
-     *  获取当前用户信息
-     * create time: 2019/1/24 10:01
-     * @Param:
-     * @return com.jsh.erp.datasource.entities.User
-     */
-    public User getCurrentUser()throws Exception{
-        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
-        Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request,"userId").toString());
-        return getUser(userId);
-    }
+    Map<String, Object> login(String loginName, String password, HttpServletRequest request) throws Exception;
 
-    /**
-     * 根据用户名查询id
-     * @param loginName
-     * @return
-     */
-    public Long getIdByLoginName(String loginName) {
-        Long userId = 0L;
-        UserExample example = new UserExample();
-        example.createCriteria().andLoginNameEqualTo(loginName).andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL)
-                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
-        List<User> list = userMapper.selectByExample(example);
-        if(list!=null) {
-            userId = list.get(0).getId();
-        }
-        return userId;
-    }
+    int validateUser(String loginName, String password) throws Exception;
+
+    User getUserByLoginName(String loginName)throws Exception;
+
+    int checkIsNameExist(Long id, String name)throws Exception;
+
+    User getCurrentUser()throws Exception;
+
+    Long getIdByLoginName(String loginName);
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void addUserAndOrgUserRel(UserEx ue, HttpServletRequest request) throws Exception{
-        if(BusinessConstants.DEFAULT_MANAGER.equals(ue.getLoginName())) {
-            throw new BusinessRunTimeException(ExceptionConstants.USER_NAME_LIMIT_USE_CODE,
-                    ExceptionConstants.USER_NAME_LIMIT_USE_MSG);
-        } else {
-            logService.insertLog("用户",
-                    BusinessConstants.LOG_OPERATION_TYPE_ADD,
-                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-            //检查用户名和登录名
-            checkLoginName(ue);
-            //新增用户信息
-            ue= this.addUser(ue);
-            if(ue==null){
-                logger.error("异常码[{}],异常提示[{}],参数,[{}]",
-                        ExceptionConstants.USER_ADD_FAILED_CODE,ExceptionConstants.USER_ADD_FAILED_MSG);
-                throw new BusinessRunTimeException(ExceptionConstants.USER_ADD_FAILED_CODE,
-                        ExceptionConstants.USER_ADD_FAILED_MSG);
-            }
-            //用户id,根据用户名查询id
-            Long userId = getIdByLoginName(ue.getLoginName());
-            if(ue.getRoleId()!=null){
-                JSONObject ubObj = new JSONObject();
-                ubObj.put("type", "UserRole");
-                ubObj.put("keyid", userId);
-                ubObj.put("value", "[" + ue.getRoleId() + "]");
-                userBusinessService.insertUserBusiness(ubObj, request);
-            }
-            if(ue.getOrgaId()==null){
-                //如果没有选择机构,就不建机构和用户的关联关系
-                return;
-            }
-            if(ue.getOrgaId()!=null && "1".equals(ue.getLeaderFlag())){
-                //检查当前机构是否存在经理
-                List<User> checkList = userMapperEx.getListByOrgaId(ue.getId(), ue.getOrgaId());
-                if(checkList.size()>0) {
-                    throw new BusinessRunTimeException(ExceptionConstants.USER_LEADER_IS_EXIST_CODE,
-                            ExceptionConstants.USER_LEADER_IS_EXIST_MSG);
-                }
-            }
-            //新增用户和机构关联关系
-            OrgaUserRel oul=new OrgaUserRel();
-            //机构id
-            oul.setOrgaId(ue.getOrgaId());
-            oul.setUserId(userId);
-            //用户在机构中的排序
-            oul.setUserBlngOrgaDsplSeq(ue.getUserBlngOrgaDsplSeq());
-            oul=orgaUserRelService.addOrgaUserRel(oul);
-            if(oul==null){
-                logger.error("异常码[{}],异常提示[{}],参数,[{}]",
-                        ExceptionConstants.ORGA_USER_REL_ADD_FAILED_CODE,ExceptionConstants.ORGA_USER_REL_ADD_FAILED_MSG);
-                throw new BusinessRunTimeException(ExceptionConstants.ORGA_USER_REL_ADD_FAILED_CODE,
-                        ExceptionConstants.ORGA_USER_REL_ADD_FAILED_MSG);
-            }
-        }
-    }
+    void addUserAndOrgUserRel(UserEx ue, HttpServletRequest request) throws Exception;
+
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public UserEx addUser(UserEx ue) throws Exception{
-        /**
-         * 新增用户默认设置
-         * 1、密码默认123456
-         * 2是否系统自带默认为非系统自带
-         * 3是否管理者默认为员工
-         * 4默认用户状态为正常
-         * */
-        ue.setPassword(Tools.md5Encryp(BusinessConstants.USER_DEFAULT_PASSWORD));
-        ue.setIsystem(BusinessConstants.USER_NOT_SYSTEM);
-        if(ue.getIsmanager()==null){
-            ue.setIsmanager(BusinessConstants.USER_NOT_MANAGER);
-        }
-        ue.setStatus(BusinessConstants.USER_STATUS_NORMAL);
-        int result=0;
-        try{
-            result= userMapper.insertSelective(ue);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        if(result>0){
-            return ue;
-        }
-        return null;
-    }
+    UserEx addUser(UserEx ue) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void registerUser(UserEx ue, Integer manageRoleId, HttpServletRequest request) throws Exception{
-        /**
-         * 多次创建事务,事物之间无法协同,应该在入口处创建一个事务以做协调
-         */
-        if(BusinessConstants.DEFAULT_MANAGER.equals(ue.getLoginName())) {
-            throw new BusinessRunTimeException(ExceptionConstants.USER_NAME_LIMIT_USE_CODE,
-                    ExceptionConstants.USER_NAME_LIMIT_USE_MSG);
-        } else {
-            ue.setPassword(ue.getPassword());
-            ue.setIsystem(BusinessConstants.USER_NOT_SYSTEM);
-            if (ue.getIsmanager() == null) {
-                ue.setIsmanager(BusinessConstants.USER_NOT_MANAGER);
-            }
-            ue.setStatus(BusinessConstants.USER_STATUS_NORMAL);
-            try{
-                userMapper.insertSelective(ue);
-                Long userId = getIdByLoginName(ue.getLoginName());
-                ue.setId(userId);
-            }catch(Exception e){
-                JshException.writeFail(logger, e);
-            }
-            //更新租户id
-            User user = new User();
-            user.setId(ue.getId());
-            user.setTenantId(ue.getId());
-            userService.updateUserTenant(user);
-            //新增用户与角色的关系
-            JSONObject ubObj = new JSONObject();
-            ubObj.put("type", "UserRole");
-            ubObj.put("keyid", ue.getId());
-            JSONArray ubArr = new JSONArray();
-            ubArr.add(manageRoleId);
-            ubObj.put("value", ubArr.toString());
-            ubObj.put("tenantId", ue.getId());
-            userBusinessService.insertUserBusiness(ubObj, null);
-            //创建租户信息
-            JSONObject tenantObj = new JSONObject();
-            tenantObj.put("tenantId", ue.getId());
-            tenantObj.put("loginName",ue.getLoginName());
-            tenantObj.put("userNumLimit", ue.getUserNumLimit());
-            tenantObj.put("expireTime", ue.getExpireTime());
-            tenantObj.put("remark", ue.getRemark());
-            Tenant tenant = JSONObject.parseObject(tenantObj.toJSONString(), Tenant.class);
-            tenant.setCreateTime(new Date());
-            if(tenant.getUserNumLimit()==null) {
-                tenant.setUserNumLimit(userNumLimit); //默认用户限制数量
-            }
-            if(tenant.getExpireTime()==null) {
-                tenant.setExpireTime(Tools.addDays(new Date(), tryDayLimit)); //租户允许试用的天数
-            }
-            tenantMapper.insertSelective(tenant);
-            logger.info("===============创建租户信息完成===============");
-        }
-    }
+    void registerUser(UserEx ue, Integer manageRoleId, HttpServletRequest request) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void updateUserTenant(User user) throws Exception{
-        UserExample example = new UserExample();
-        example.createCriteria().andIdEqualTo(user.getId());
-        try{
-            userMapper.updateByPrimaryKeySelective(user);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-    }
+    void updateUserTenant(User user) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public void updateUserAndOrgUserRel(UserEx ue, HttpServletRequest request) throws Exception{
-        if(BusinessConstants.DEFAULT_MANAGER.equals(ue.getLoginName())) {
-            throw new BusinessRunTimeException(ExceptionConstants.USER_NAME_LIMIT_USE_CODE,
-                    ExceptionConstants.USER_NAME_LIMIT_USE_MSG);
-        } else {
-            logService.insertLog("用户",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(ue.getId()).toString(),
-                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-            //检查用户名和登录名
-            checkLoginName(ue);
-            //更新用户信息
-            ue = this.updateUser(ue);
-            if (ue == null) {
-                logger.error("异常码[{}],异常提示[{}],参数,[{}]",
-                        ExceptionConstants.USER_EDIT_FAILED_CODE, ExceptionConstants.USER_EDIT_FAILED_MSG);
-                throw new BusinessRunTimeException(ExceptionConstants.USER_EDIT_FAILED_CODE,
-                        ExceptionConstants.USER_EDIT_FAILED_MSG);
-            }
-            if(ue.getRoleId()!=null){
-                JSONObject ubObj = new JSONObject();
-                ubObj.put("type", "UserRole");
-                ubObj.put("keyid", ue.getId());
-                ubObj.put("value", "[" + ue.getRoleId() + "]");
-                Long ubId = userBusinessService.checkIsValueExist("UserRole", ue.getId().toString());
-                if(ubId!=null) {
-                    ubObj.put("id", ubId);
-                    userBusinessService.updateUserBusiness(ubObj, request);
-                } else {
-                    userBusinessService.insertUserBusiness(ubObj, request);
-                }
-            }
-            if (ue.getOrgaId() == null) {
-                //如果没有选择机构,就不建机构和用户的关联关系
-                return;
-            }
-            if(ue.getOrgaId()!=null && "1".equals(ue.getLeaderFlag())){
-                //检查当前机构是否存在经理
-                List<User> checkList = userMapperEx.getListByOrgaId(ue.getId(), ue.getOrgaId());
-                if(checkList.size()>0) {
-                    throw new BusinessRunTimeException(ExceptionConstants.USER_LEADER_IS_EXIST_CODE,
-                            ExceptionConstants.USER_LEADER_IS_EXIST_MSG);
-                }
-            }
-            //更新用户和机构关联关系
-            OrgaUserRel oul = new OrgaUserRel();
-            //机构和用户关联关系id
-            oul.setId(ue.getOrgaUserRelId());
-            //机构id
-            oul.setOrgaId(ue.getOrgaId());
-            //用户id
-            oul.setUserId(ue.getId());
-            //用户在机构中的排序
-            oul.setUserBlngOrgaDsplSeq(ue.getUserBlngOrgaDsplSeq());
-            if (oul.getId() != null) {
-                //已存在机构和用户的关联关系,更新
-                oul = orgaUserRelService.updateOrgaUserRel(oul);
-            } else {
-                //不存在机构和用户的关联关系,新建
-                oul = orgaUserRelService.addOrgaUserRel(oul);
-            }
-            if (oul == null) {
-                logger.error("异常码[{}],异常提示[{}],参数,[{}]",
-                        ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_CODE, ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_MSG);
-                throw new BusinessRunTimeException(ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_CODE,
-                        ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_MSG);
-            }
-        }
-    }
+    void updateUserAndOrgUserRel(UserEx ue, HttpServletRequest request) throws Exception;
+
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public UserEx updateUser(UserEx ue)throws Exception{
-        int result =0;
-        try{
-            result=userMapper.updateByPrimaryKeySelective(ue);
-        }catch(Exception e){
-            JshException.writeFail(logger, e);
-        }
-        if(result>0){
-            return ue;
-        }
-        return null;
-    }
-    /**
-     *  检查登录名不能重复
-     * create time: 2019/3/12 11:36
-     * @Param: userEx
-     * @return void
-     */
-    public void checkLoginName(UserEx userEx)throws Exception{
-        List<User> list=null;
-        if(userEx==null){
-            return;
-        }
-        Long userId=userEx.getId();
-        //检查登录名
-        if(!StringUtils.isEmpty(userEx.getLoginName())){
-            String loginName=userEx.getLoginName();
-            list=this.getUserListByloginName(loginName);
-            if(list!=null&&list.size()>0){
-                if(list.size()>1){
-                    //超过一条数据存在,该登录名已存在
-                    logger.error("异常码[{}],异常提示[{}],参数,loginName:[{}]",
-                            ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG,loginName);
-                    throw new BusinessRunTimeException(ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,
-                            ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG);
-                }
-                //一条数据,新增时抛出异常,修改时和当前的id不同时抛出异常
-                if(list.size()==1){
-                    if(userId==null||(userId!=null&&!userId.equals(list.get(0).getId()))){
-                        logger.error("异常码[{}],异常提示[{}],参数,loginName:[{}]",
-                                ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG,loginName);
-                        throw new BusinessRunTimeException(ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,
-                                ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG);
-                    }
-                }
-            }
-        }
-    }
-    /**
-     * 通过登录名获取用户列表
-     * */
-    public List<User> getUserListByloginName(String loginName){
-        List<User> list =null;
-        try{
-            list=userMapperEx.getUserListByUserNameOrLoginName(null,loginName);
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
-
-    public List<TreeNodeEx> getOrganizationUserTree()throws Exception {
-        List<TreeNodeEx> list =null;
-        try{
-            list=userMapperEx.getNodeTree();
-        }catch(Exception e){
-            JshException.readFail(logger, e);
-        }
-        return list;
-    }
+    UserEx updateUser(UserEx ue)throws Exception;
+
+    void checkLoginName(UserEx userEx)throws Exception;
+
+    List<User> getUserListByloginName(String loginName);
+
+    List<TreeNodeEx> getOrganizationUserTree()throws Exception;
 
-    /**
-     * 根据用户id查询角色信息
-     * @param userId
-     * @return
-     */
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public Role getRoleTypeByUserId(long userId) throws Exception {
-        Role role = new Role();
-        List<UserBusiness> list = userBusinessService.getBasicData(String.valueOf(userId), "UserRole");
-        UserBusiness ub = null;
-        if(list.size() > 0) {
-            ub = list.get(0);
-            String values = ub.getValue();
-            String roleId = null;
-            if(values!=null) {
-                values = values.replaceAll("\\[\\]",",").replace("[","").replace("]","");
-            }
-            String [] valueArray=values.split(",");
-            if(valueArray.length>0) {
-                roleId = valueArray[0];
-            }
-            role = roleService.getRoleWithoutTenant(Long.parseLong(roleId));
-        }
-        return role;
-    }
+    Role getRoleTypeByUserId(long userId) throws Exception;
 
-    /**
-     * 获取用户id
-     * @param request
-     * @return
-     */
-    public Long getUserId(HttpServletRequest request) throws Exception{
-        Object userIdObj = redisService.getObjectFromSessionByKey(request,"userId");
-        Long userId = null;
-        if(userIdObj != null) {
-            userId = Long.parseLong(userIdObj.toString());
-        }
-        return userId;
-    }
+    Long getUserId(HttpServletRequest request) throws Exception;
 
-    /**
-     * 用户的按钮权限
-     * @param userId
-     * @return
-     * @throws Exception
-     */
-    public JSONArray getBtnStrArrById(Long userId) throws Exception {
-        JSONArray btnStrArr = new JSONArray();
-        List<UserBusiness> userRoleList = userBusinessService.getBasicData(userId.toString(), "UserRole");
-        if(userRoleList!=null && userRoleList.size()>0) {
-            String roleValue = userRoleList.get(0).getValue();
-            if(StringUtil.isNotEmpty(roleValue) && roleValue.indexOf("[")>-1 && roleValue.indexOf("]")>-1){
-                roleValue = roleValue.replace("[", "").replace("]", ""); //角色id-单个
-                List<UserBusiness> roleFunctionsList = userBusinessService.getBasicData(roleValue, "RoleFunctions");
-                if(roleFunctionsList!=null && roleFunctionsList.size()>0) {
-                    String btnStr = roleFunctionsList.get(0).getBtnStr();
-                    if(StringUtil.isNotEmpty(btnStr)){
-                        btnStrArr = JSONArray.parseArray(btnStr);
-                    }
-                }
-            }
-        }
-        //将数组中的funId转为url
-        JSONArray btnStrWithUrlArr = new JSONArray();
-        if(btnStrArr.size()>0) {
-            List<Function> functionList = functionService.getFunction();
-            Map<Long, String> functionMap = new HashMap<>();
-            for (Function function: functionList) {
-                functionMap.put(function.getId(), function.getUrl());
-            }
-            for (Object obj : btnStrArr) {
-                JSONObject btnStrObj = JSONObject.parseObject(obj.toString());
-                Long funId = btnStrObj.getLong("funId");
-                JSONObject btnStrWithUrlObj = new JSONObject();
-                btnStrWithUrlObj.put("url", functionMap.get(funId));
-                btnStrWithUrlObj.put("btnStr", btnStrObj.getString("btnStr"));
-                btnStrWithUrlArr.add(btnStrWithUrlObj);
-            }
-        }
-        return btnStrWithUrlArr;
-    }
+    JSONArray getBtnStrArrById(Long userId) throws Exception;
 
     @Transactional(value = "transactionManager", rollbackFor = Exception.class)
-    public int batchSetStatus(Byte status, String ids, HttpServletRequest request)throws Exception {
-        int result=0;
-        List<User> list = getUserListByIds(ids);
-        //选中的用户的数量
-        int selectUserSize = list.size();
-        //查询启用状态的用户的数量
-        int enableUserSize = getUser(request).size();
-        User userInfo = userService.getCurrentUser();
-        Tenant tenant = tenantService.getTenantByTenantId(userInfo.getTenantId());
-        if(tenant!=null) {
-            if (selectUserSize + enableUserSize > tenant.getUserNumLimit() && status == 0) {
-                throw new BusinessParamCheckingException(ExceptionConstants.USER_ENABLE_OVER_LIMIT_FAILED_CODE,
-                        ExceptionConstants.USER_ENABLE_OVER_LIMIT_FAILED_MSG);
-            }
-        }
-        StringBuilder userStr = new StringBuilder();
-        List<Long> idList = new ArrayList<>();
-        for(User user: list) {
-            if(user.getId().equals(user.getTenantId())) {
-                //租户不能进行禁用
-            } else {
-                idList.add(user.getId());
-                userStr.append(user.getLoginName()).append(" ");
-            }
-        }
-        String statusStr ="";
-        if(status == 0) {
-            statusStr ="批量启用";
-        } else if(status == 2) {
-            statusStr ="批量禁用";
-        }
-        if(idList.size()>0) {
-            User user = new User();
-            user.setStatus(status);
-            UserExample example = new UserExample();
-            example.createCriteria().andIdIn(idList);
-            result = userMapper.updateByExampleSelective(user, example);
-            logService.insertLog("用户",
-                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(userStr).append("-").append(statusStr).toString(),
-                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
-        } else {
-            result = 1;
-        }
-        return result;
-    }
-
-    public User getUserByWeixinCode(String weixinCode) throws Exception {
-        String weixinUrl = platformConfigService.getPlatformConfigByKey("weixinUrl").getPlatformValue();
-        String weixinAppid = platformConfigService.getPlatformConfigByKey("weixinAppid").getPlatformValue();
-        String weixinSecret = platformConfigService.getPlatformConfigByKey("weixinSecret").getPlatformValue();
-        String url = weixinUrl + "?appid=" + weixinAppid + "&secret=" + weixinSecret + "&js_code=" + weixinCode
-                + "&grant_type=authorization_code";
-        JSONObject jsonObject = HttpClient.httpGet(url);
-        if(jsonObject!=null) {
-            String weixinOpenId = jsonObject.getString("openid");
-            if(StringUtil.isNotEmpty(weixinOpenId)) {
-                return userMapperEx.getUserByWeixinOpenId(weixinOpenId);
-            }
-        }
-        return null;
-    }
-
-    public int weixinBind(String loginName, String password, String weixinCode) throws Exception {
-        String weixinUrl = platformConfigService.getPlatformConfigByKey("weixinUrl").getPlatformValue();
-        String weixinAppid = platformConfigService.getPlatformConfigByKey("weixinAppid").getPlatformValue();
-        String weixinSecret = platformConfigService.getPlatformConfigByKey("weixinSecret").getPlatformValue();
-        String url = weixinUrl + "?appid=" + weixinAppid + "&secret=" + weixinSecret + "&js_code=" + weixinCode
-                + "&grant_type=authorization_code";
-        JSONObject jsonObject = HttpClient.httpGet(url);
-        if(jsonObject!=null) {
-            String weixinOpenId = jsonObject.getString("openid");
-            if(StringUtil.isNotEmpty(weixinOpenId)) {
-                return userMapperEx.updateUserWithWeixinOpenId(loginName, password, weixinOpenId);
-            }
-        }
-        return 0;
-    }
+    int batchSetStatus(Byte status, String ids, HttpServletRequest request)throws Exception;
+
+    User getUserByWeixinCode(String weixinCode) throws Exception;
+
+    int weixinBind(String loginName, String password, String weixinCode) throws Exception;
 }

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels