新增:erp、erp-spi

This commit is contained in:
小久哥
2022-05-26 14:40:32 +08:00
parent 7b742c1701
commit 94eb1b7141
419 changed files with 72184 additions and 1 deletions
@@ -0,0 +1,152 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.Account;
import com.zsw.erp.datasource.vo.AccountVo4InOutList;
import com.zsw.erp.service.account.AccountService;
import com.zsw.base.R;
import com.zsw.erp.utils.ErpInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/account")
@Api(tags = {"账户管理"})
public class AccountController {
private Logger logger = LoggerFactory.getLogger(AccountController.class);
@Resource
private AccountService accountService;
/**
* 查找结算账户信息-下拉框
* @param request
* @return
*/
@GetMapping(value = "/findBySelect")
@ApiOperation(value = "查找结算账户信息-下拉框")
public String findBySelect(HttpServletRequest request) throws Exception {
String res = null;
try {
List<Account> dataList = accountService.findBySelect();
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (Account account : dataList) {
JSONObject item = new JSONObject();
item.put("Id", account.getId());
//结算账户名称
item.put("AccountName", account.getName());
dataArray.add(item);
}
}
res = dataArray.toJSONString();
} catch(Exception e){
e.printStackTrace();
res = "获取数据失败";
}
return res;
}
/**
* 获取所有结算账户
* @param request
* @return
*/
@GetMapping(value = "/getAccount")
@ApiOperation(value = "获取所有结算账户")
public R getAccount(HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<Account> accountList = accountService.getAccount();
map.put("accountList", accountList);
return R.success(map);
}
/**
* 账户流水信息
* @param currentPage
* @param pageSize
* @param accountId
* @param initialAmount
* @param request
* @return
*/
@GetMapping(value = "/findAccountInOutList")
@ApiOperation(value = "账户流水信息")
public R findAccountInOutList(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("accountId") Long accountId,
@RequestParam("initialAmount") BigDecimal initialAmount,
HttpServletRequest request) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
List<AccountVo4InOutList> dataList = accountService.findAccountInOutList(accountId, (currentPage-1)*pageSize, pageSize);
int total = accountService.findAccountInOutListCount(accountId);
map.put("total", total);
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (AccountVo4InOutList aEx : dataList) {
String timeStr = aEx.getOperTime().toString();
BigDecimal balance = accountService.getAccountSum(accountId, timeStr, "date").add(accountService.getAccountSumByHead(accountId, timeStr, "date"))
.add(accountService.getAccountSumByDetail(accountId, timeStr, "date")).add(accountService.getManyAccountSum(accountId, timeStr, "date")).add(initialAmount);
aEx.setBalance(balance);
aEx.setAccountId(accountId);
dataArray.add(aEx);
}
}
map.put("rows", dataArray);
return R.success(map);
}
/**
* 更新默认账户
* @param object
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/updateIsDefault")
@ApiOperation(value = "更新默认账户")
public String updateIsDefault(@RequestBody JSONObject object,
HttpServletRequest request) throws Exception{
Long accountId = object.getLong("id");
Map<String, Object> objectMap = new HashMap<>();
int res = accountService.updateIsDefault(accountId);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 结算账户的统计
* @param request
* @return
*/
@GetMapping(value = "/getStatistics")
@ApiOperation(value = "结算账户的统计")
public R getStatistics(@RequestParam("name") String name,
@RequestParam("serialNo") String serialNo,
HttpServletRequest request) throws Exception {
Map<String, Object> map = accountService.getStatistics(name, serialNo);
return R.success(map);
}
}
@@ -0,0 +1,110 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.constants.ExceptionConstants;
import com.zsw.erp.datasource.entities.AccountHeadVo4Body;
import com.zsw.erp.datasource.entities.AccountHeadVo4ListEx;
import com.zsw.erp.service.accountHead.AccountHeadService;
import com.zsw.base.R;
import com.zsw.erp.utils.ErpInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/accountHead")
@Api(tags = {"财务管理"})
public class AccountHeadController {
private Logger logger = LoggerFactory.getLogger(AccountHeadController.class);
@Resource
private AccountHeadService accountHeadService;
/**
* 批量设置状态-审核或者反审核
* @param jsonObject
* @param request
* @return
*/
@PostMapping(value = "/batchSetStatus")
@ApiOperation(value = "批量设置状态-审核或者反审核")
public String batchSetStatus(@RequestBody JSONObject jsonObject,
HttpServletRequest request) throws Exception{
Map<String, Object> objectMap = new HashMap<>();
String status = jsonObject.getString("status");
String ids = jsonObject.getString("ids");
int res = accountHeadService.batchSetStatus(status, ids);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 新增财务主表及财务子表信息
* @param body
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/addAccountHeadAndDetail")
@ApiOperation(value = "新增财务主表及财务子表信息")
public Object addAccountHeadAndDetail(@RequestBody AccountHeadVo4Body body, HttpServletRequest request) throws Exception{
JSONObject result = ExceptionConstants.standardSuccess();
String beanJson = body.getInfo();
String rows = body.getRows();
accountHeadService.addAccountHeadAndDetail(beanJson,rows, request);
return result;
}
/**
* 更新财务主表及财务子表信息
* @param body
* @param request
* @return
* @throws Exception
*/
@PutMapping(value = "/updateAccountHeadAndDetail")
@ApiOperation(value = "更新财务主表及财务子表信息")
public Object updateAccountHeadAndDetail(@RequestBody AccountHeadVo4Body body, HttpServletRequest request) throws Exception{
JSONObject result = ExceptionConstants.standardSuccess();
String beanJson = body.getInfo();
String rows = body.getRows();
accountHeadService.updateAccountHeadAndDetail(beanJson,rows,request);
return result;
}
/**
* 根据编号查询单据信息
* @param billNo
* @param request
* @return
*/
@GetMapping(value = "/getDetailByNumber")
@ApiOperation(value = "根据编号查询单据信息")
public R getDetailByNumber(@RequestParam("billNo") String billNo,
HttpServletRequest request)throws Exception {
AccountHeadVo4ListEx ahl = new AccountHeadVo4ListEx();
List<AccountHeadVo4ListEx> list = accountHeadService.getDetailByNumber(billNo);
if(list.size() == 1) {
ahl = list.get(0);
return R.success(ahl);
}else {
return R.fail("错误");
}
}
}
@@ -0,0 +1,65 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.vo.AccountItemVo4List;
import com.zsw.erp.service.accountItem.AccountItemService;
import com.zsw.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(value = "/accountItem")
@Api(tags = {"财务明细"})
public class AccountItemController {
private Logger logger = LoggerFactory.getLogger(AccountItemController.class);
@Resource
private AccountItemService accountItemService;
@GetMapping(value = "/getDetailList")
@ApiOperation(value = "明细列表")
public R getDetailList(@RequestParam("headerId") Long headerId,
HttpServletRequest request)throws Exception {
List<AccountItemVo4List> dataList = new ArrayList<>();
if(headerId != 0) {
dataList = accountItemService.getDetailList(headerId);
}
JSONObject outer = new JSONObject();
outer.put("total", dataList.size());
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (AccountItemVo4List ai : dataList) {
JSONObject item = new JSONObject();
item.put("accountId", ai.getAccountId());
item.put("accountName", ai.getAccountName());
item.put("inOutItemId", ai.getInOutItemId());
item.put("inOutItemName", ai.getInOutItemName());
item.put("billNumber", ai.getBillNumber());
item.put("needDebt", ai.getNeedDebt());
item.put("finishDebt", ai.getFinishDebt());
BigDecimal eachAmount = ai.getEachAmount();
item.put("eachAmount", (eachAmount.compareTo(BigDecimal.ZERO))==-1 ? BigDecimal.ZERO.subtract(eachAmount): eachAmount);
item.put("remark", ai.getRemark());
dataArray.add(item);
}
}
outer.put("rows", dataArray);
return R.success(outer);
}
}
@@ -0,0 +1,89 @@
package com.zsw.erp.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.zsw.base.R;
import com.zsw.erp.datasource.dto.BomDto;
import com.zsw.erp.service.zyh.BomService;
import com.zsw.erp.utils.DozerUtils;
import com.zsw.pos.product.dto.AdminStoreProductDTO;
import com.zsw.pos.product.entity.Product;
import com.zsw.pos.product.entity.ProductSku;
import com.zsw.pos.product.service.ProductService;
import com.zsw.pos.product.service.ProductSkuService;
import com.zsw.pos.product.vo.ProductPageVO;
import com.zsw.pos.store.StoreService;
import com.zsw.pos.store.entity.Store;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@Api(tags = "BOM物料清单")
@RequestMapping("/bom")
@Slf4j
public class BomController {
@Resource
private DozerUtils dozerUtils;
@DubboReference
private ProductService productService;
@DubboReference
private ProductSkuService productSkuService;
@DubboReference
private StoreService storeService;
@Resource
private BomService bomService;
@PostMapping("/insert")
@ApiOperation("新增BOM")
public R<Boolean> insert(@RequestBody BomDto bomDto){
return R.success(bomService.save(bomDto));
}
@PostMapping("/edit")
@ApiOperation("修改BOM")
public R<Boolean> edit(@RequestBody BomDto bomDto){
return R.success(bomService.updateById(bomDto));
}
@GetMapping("/list")
@ApiOperation("列举全部BOM")
public R<List<BomDto>> list(){
List<BomDto> rs = dozerUtils.convertList(bomService.list(), BomDto.class);
return R.success(rs);
}
@PostMapping("/listProduct")
@ApiOperation("获取商品")
public R<ProductPageVO> listProduct(AdminStoreProductDTO dto){
return productService.findAdminStoreProductList(dto);
}
@GetMapping("/listProcutSkuByPid")
@ApiOperation("获取SKU")
public R<List<ProductSku>> listProcutSkuByPid(@RequestParam List<Long> ids){
List<ProductSku> sku = productSkuService.getProductSkuByMaterial(ids);
return R.success(sku);
}
@GetMapping("/listStore")
@ApiOperation("获取全部店铺列表")
public R<List<Store>> listStore(){
List<Store> storeList = storeService.list();
return R.success(storeList);
}
}
@@ -0,0 +1,170 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.Depot;
import com.zsw.erp.datasource.entities.DepotEx;
import com.zsw.erp.datasource.entities.MaterialInitialStock;
import com.zsw.erp.service.depot.DepotService;
import com.zsw.erp.service.material.MaterialService;
import com.zsw.erp.service.userBusiness.UserBusinessService;
import com.zsw.base.R;
import com.zsw.erp.utils.ErpInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/depot")
@Api(tags = {"仓库管理"})
public class DepotController {
private Logger logger = LoggerFactory.getLogger(DepotController.class);
@Resource
private DepotService depotService;
@Resource
private UserBusinessService userBusinessService;
@Resource
private MaterialService materialService;
/**
* 仓库列表
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getAllList")
@ApiOperation(value = "仓库列表")
public R getAllList(HttpServletRequest request) throws Exception{
List<Depot> depotList = depotService.getAllList();
return R.success(depotList);
}
/**
* 用户对应仓库显示
* @param type
* @param keyId
* @param request
* @return
*/
@GetMapping(value = "/findUserDepot")
@ApiOperation(value = "用户对应仓库显示")
public JSONArray findUserDepot(@RequestParam("UBType") String type, @RequestParam("UBKeyId") Long keyId,
HttpServletRequest request) throws Exception{
JSONArray arr = new JSONArray();
try {
//获取权限信息
List<Long> ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, keyId);
List<Depot> dataList = depotService.findUserDepot();
//开始拼接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 (Depot depot : dataList) {
JSONObject item = new JSONObject();
item.put("id", depot.getId());
item.put("key", depot.getId());
item.put("value", depot.getId());
item.put("title", depot.getName());
item.put("attributes", depot.getName());
Boolean flag = ubValue.contains(depot.getId());
if (flag) {
item.put("checked", true);
}
dataArray.add(item);
}
}
outer.put("children", dataArray);
arr.add(outer);
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
/**
* 获取当前用户拥有权限的仓库列表
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/findDepotByCurrentUser")
@ApiOperation(value = "获取当前用户拥有权限的仓库列表")
public R findDepotByCurrentUser(HttpServletRequest request) throws Exception{
JSONArray arr = depotService.findDepotByCurrentUser();
return R.success(arr);
}
/**
* 更新默认仓库
* @param object
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/updateIsDefault")
@ApiOperation(value = "更新默认仓库")
public String updateIsDefault(@RequestBody JSONObject object,
HttpServletRequest request) throws Exception{
Long depotId = object.getLong("id");
Map<String, Object> objectMap = new HashMap<>();
int res = depotService.updateIsDefault(depotId);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 仓库列表-带库存
* @param mId
* @param request
* @return
*/
@GetMapping(value = "/getAllListWithStock")
@ApiOperation(value = "仓库列表-带库存")
public R getAllList(@RequestParam("mId") Long mId,
HttpServletRequest request) {
List<Depot> list = depotService.getAllList();
List<DepotEx> depotList = new ArrayList<DepotEx>();
for(Depot depot: list) {
DepotEx de = new DepotEx();
if(mId!=0) {
BigDecimal initStock = materialService.getInitStock(mId, depot.getId()).getNumber();
BigDecimal currentStock = materialService.getCurrentStock(mId, depot.getId());
de.setInitStock(initStock);
de.setCurrentStock(currentStock);
MaterialInitialStock materialInitialStock = materialService.getSafeStock(mId, depot.getId());
de.setLowSafeStock(materialInitialStock.getLowSafeStock());
de.setHighSafeStock(materialInitialStock.getHighSafeStock());
} else {
de.setInitStock(BigDecimal.ZERO);
de.setCurrentStock(BigDecimal.ZERO);
}
de.setId(depot.getId());
de.setName(depot.getName());
depotList.add(de);
}
return R.success(depotList);
}
}
@@ -0,0 +1,495 @@
package com.zsw.erp.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.base.R;
import com.zsw.erp.constants.BusinessConstants;
import com.zsw.erp.constants.ExceptionConstants;
import com.zsw.erp.datasource.dto.DepotItemDto;
import com.zsw.erp.datasource.entities.*;
import com.zsw.erp.datasource.vo.DepotHeadVo4InDetail;
import com.zsw.erp.datasource.vo.DepotHeadVo4InOutMCount;
import com.zsw.erp.datasource.vo.DepotHeadVo4List;
import com.zsw.erp.datasource.vo.DepotHeadVo4StatementAccount;
import com.zsw.erp.service.account.AccountService;
import com.zsw.erp.service.accountHead.AccountHeadService;
import com.zsw.erp.service.depot.DepotService;
import com.zsw.erp.service.depotHead.DepotHeadService;
import com.zsw.erp.service.depotItem.DepotItemService;
import com.zsw.erp.service.redis.RedisService;
import com.zsw.erp.service.supplier.SupplierService;
import com.zsw.erp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
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;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
import static com.zsw.erp.utils.Tools.getNow3;
@RestController
@RequestMapping(value = "/depotHead")
@Api(tags = {"单据管理"})
public class DepotHeadController {
private Logger logger = LoggerFactory.getLogger(DepotHeadController.class);
@Resource
private DepotHeadService depotHeadService;
@Resource
private AccountHeadService accountHeadService;
@Resource
private AccountService accountService;
@Resource
private SupplierService supplierService;
@Resource
private DepotService depotService;
@Resource
private RedisService redisService;
@Resource
private DepotItemService depotItemService;
/**
* 批量设置状态-审核或者反审核
* @param jsonObject
* @param request
* @return
*/
@PostMapping(value = "/batchSetStatus")
@ApiOperation(value = "批量设置状态-审核或者反审核")
public String batchSetStatus(@RequestBody JSONObject jsonObject,
HttpServletRequest request) throws Exception{
Map<String, Object> objectMap = new HashMap<>();
String status = jsonObject.getString("status");
String ids = jsonObject.getString("ids");
int res = depotHeadService.batchSetStatus(status, ids);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 入库出库明细接口
* @param currentPage
* @param pageSize
* @param oId
* @param number
* @param materialParam
* @param depotId
* @param beginTime
* @param endTime
* @param type
* @param request
* @return
*/
@GetMapping(value = "/findInDetail")
@ApiOperation(value = "入库出库明细接口")
public R findInDetail(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam(value = "organId", required = false) Integer oId,
@RequestParam("number") String number,
@RequestParam("materialParam") String materialParam,
@RequestParam(value = "depotId", required = false) Long depotId,
@RequestParam("beginTime") String beginTime,
@RequestParam("endTime") String endTime,
@RequestParam("type") String type,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<Long> depotList = new ArrayList<>();
if(depotId != null) {
depotList.add(depotId);
} else {
//未选择仓库时默认为当前用户有权限的仓库
JSONArray depotArr = depotService.findDepotByCurrentUser();
for(Object obj: depotArr) {
JSONObject object = JSONObject.parseObject(obj.toString());
depotList.add(object.getLong("id"));
}
}
List<DepotHeadVo4InDetail> resList = new ArrayList<DepotHeadVo4InDetail>();
beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
List<DepotHeadVo4InDetail> list = depotHeadService.findByAll(beginTime, endTime, type, materialParam, depotList, oId, number, (currentPage-1)*pageSize, pageSize);
int total = depotHeadService.findByAllCount(beginTime, endTime, type, materialParam, depotList, oId, number);
map.put("total", total);
//存放数据json数组
if (null != list) {
for (DepotHeadVo4InDetail dhd : list) {
resList.add(dhd);
}
}
map.put("rows", resList);
return R.success(map);
}
/**
* 入库出库统计接口
* @param currentPage
* @param pageSize
* @param oId
* @param materialParam
* @param depotId
* @param beginTime
* @param endTime
* @param type
* @param request
* @return
*/
@GetMapping(value = "/findInOutMaterialCount")
@ApiOperation(value = "入库出库统计接口")
public R findInOutMaterialCount(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam(value = "organId", required = false) Integer oId,
@RequestParam("materialParam") String materialParam,
@RequestParam(value = "depotId", required = false) Long depotId,
@RequestParam("beginTime") String beginTime,
@RequestParam("endTime") String endTime,
@RequestParam("type") String type,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<Long> depotList = new ArrayList<>();
if(depotId != null) {
depotList.add(depotId);
} else {
//未选择仓库时默认为当前用户有权限的仓库
JSONArray depotArr = depotService.findDepotByCurrentUser();
for(Object obj: depotArr) {
JSONObject object = JSONObject.parseObject(obj.toString());
depotList.add(object.getLong("id"));
}
}
List<DepotHeadVo4InOutMCount> resList = new ArrayList<>();
beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
List<DepotHeadVo4InOutMCount> list = depotHeadService.findInOutMaterialCount(beginTime, endTime, type, materialParam, depotList, oId, (currentPage-1)*pageSize, pageSize);
int total = depotHeadService.findInOutMaterialCountTotal(beginTime, endTime, type, materialParam, depotList, oId);
map.put("total", total);
//存放数据json数组
if (null != list) {
for (DepotHeadVo4InOutMCount dhc : list) {
resList.add(dhc);
}
}
map.put("rows", resList);
return R.success(map);
}
/**
* 调拨明细统计
* @param currentPage
* @param pageSize
* @param number
* @param materialParam
* @param depotIdF 调出仓库
* @param depotId 调入仓库
* @param beginTime
* @param endTime
* @param subType
* @param request
* @return
*/
@GetMapping(value = "/findAllocationDetail")
@ApiOperation(value = "调拨明细统计")
public R findallocationDetail(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("number") String number,
@RequestParam("materialParam") String materialParam,
@RequestParam(value = "depotId", required = false) Long depotId,
@RequestParam(value = "depotIdF", required = false) Long depotIdF,
@RequestParam("beginTime") String beginTime,
@RequestParam("endTime") String endTime,
@RequestParam("subType") String subType,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<Long> depotList = new ArrayList<>();
List<Long> depotFList = new ArrayList<>();
if(depotId != null) {
depotList.add(depotId);
} else {
//未选择仓库时默认为当前用户有权限的仓库
JSONArray depotArr = depotService.findDepotByCurrentUser();
for(Object obj: depotArr) {
JSONObject object = JSONObject.parseObject(obj.toString());
depotList.add(object.getLong("id"));
}
}
if(depotIdF != null) {
depotFList.add(depotIdF);
} else {
//未选择仓库时默认为当前用户有权限的仓库
JSONArray depotArr = depotService.findDepotByCurrentUser();
for(Object obj: depotArr) {
JSONObject object = JSONObject.parseObject(obj.toString());
depotFList.add(object.getLong("id"));
}
}
beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
List<DepotHeadVo4InDetail> list = depotHeadService.findAllocationDetail(beginTime, endTime, subType, number, materialParam, depotList, depotFList, (currentPage-1)*pageSize, pageSize);
int total = depotHeadService.findAllocationDetailCount(beginTime, endTime, subType, number, materialParam, depotList, depotFList);
map.put("rows", list);
map.put("total", total);
return R.success(map);
}
/**
* 对账单接口
* @param currentPage
* @param pageSize
* @param beginTime
* @param endTime
* @param organId
* @param supType
* @param request
* @return
*/
@GetMapping(value = "/findStatementAccount")
@ApiOperation(value = "对账单接口")
public R findStatementAccount(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("beginTime") String beginTime,
@RequestParam("endTime") String endTime,
@RequestParam(value = "organId", required = false) Integer organId,
@RequestParam("supType") String supType,
HttpServletRequest request) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
List<DepotHeadVo4StatementAccount> list = depotHeadService.findStatementAccount(beginTime, endTime, organId, supType, (currentPage-1)*pageSize, pageSize);
int total = depotHeadService.findStatementAccountCount(beginTime, endTime, organId, supType);
map.put("rows", list);
map.put("total", total);
if(null!=organId) {
Supplier supplier = supplierService.getSupplier(organId);
BigDecimal beginNeed = BigDecimal.ZERO;
if (("客户").equals(supType)) {
if(supplier.getBeginNeedGet()!=null) {
beginNeed = supplier.getBeginNeedGet();
}
} else if (("供应商").equals(supType)) {
if(supplier.getBeginNeedPay()!=null) {
beginNeed = supplier.getBeginNeedPay();
}
}
BigDecimal firstMoney = depotHeadService.findTotalPay(organId, beginTime, supType)
.subtract(accountHeadService.findTotalPay(organId, beginTime, supType)).add(beginNeed);
BigDecimal lastMoney = depotHeadService.findTotalPay(organId, endTime, supType)
.subtract(accountHeadService.findTotalPay(organId, endTime, supType)).add(beginNeed);
map.put("firstMoney", firstMoney); //期初
map.put("lastMoney", lastMoney); //期末
}
return R.success(map);
}
/**
* 根据编号查询单据信息
* @param number
* @param request
* @return
*/
@GetMapping(value = "/getDetailByNumber")
@ApiOperation(value = "根据编号查询单据信息")
public R getDetailByNumber(@RequestParam("number") String number,
HttpServletRequest request)throws Exception {
DepotHeadVo4List dhl = new DepotHeadVo4List();
List<DepotHeadVo4List> list = depotHeadService.getDetailByNumber(number);
if(list.size() == 1) {
dhl = list.get(0);
}
return R.success(dhl);
}
/**
* 新增单据主表及单据子表信息
* @param body
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/addDepotHeadAndDetail")
@ApiOperation(value = "新增单据主表及单据子表信息")
public Object addDepotHeadAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws Exception{
JSONObject result = ExceptionConstants.standardSuccess();
depotHeadService.addDepotHeadAndDetail(body, request);
return result;
}
/**
* 更新单据主表及单据子表信息
* @param body
* @param request
* @return
* @throws Exception
*/
@PutMapping(value = "/updateDepotHeadAndDetail")
@ApiOperation(value = "更新单据主表及单据子表信息")
public Object updateDepotHeadAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws Exception{
JSONObject result = ExceptionConstants.standardSuccess();
depotHeadService.updateDepotHeadAndDetail(body,request);
return result;
}
/**
* 统计今日采购额、本月采购额、今日销售额、本月销售额、今日零售额、本月零售额
* @param request
* @return
*/
@GetMapping(value = "/getBuyAndSaleStatistics")
@ApiOperation(value = "统计今日采购额、本月采购额、今日销售额、本月销售额、今日零售额、本月零售额")
public R getBuyAndSaleStatistics(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
String today = Tools.getNow() + BusinessConstants.DAY_FIRST_TIME;
String firstDay = Tools.firstDayOfMonth(Tools.getCurrentMonth()) + BusinessConstants.DAY_FIRST_TIME;
BigDecimal todayBuy = depotHeadService.getBuyAndSaleStatistics("入库", "采购",
1, today, getNow3()); //今日采购入库
BigDecimal todayBuyBack = depotHeadService.getBuyAndSaleStatistics("出库", "采购退货",
1, today, getNow3()); //今日采购退货
BigDecimal todaySale = depotHeadService.getBuyAndSaleStatistics("出库", "销售",
1, today, getNow3()); //今日销售出库
BigDecimal todaySaleBack = depotHeadService.getBuyAndSaleStatistics("入库", "销售退货",
1, today, getNow3()); //今日销售退货
BigDecimal todayRetailSale = depotHeadService.getBuyAndSaleRetailStatistics("出库", "零售",
today, getNow3()); //今日零售出库
BigDecimal todayRetailSaleBack = depotHeadService.getBuyAndSaleRetailStatistics("入库", "零售退货",
today, getNow3()); //今日零售退货
BigDecimal monthBuy = depotHeadService.getBuyAndSaleStatistics("入库", "采购",
1, firstDay, getNow3()); //本月采购入库
BigDecimal monthBuyBack = depotHeadService.getBuyAndSaleStatistics("出库", "采购退货",
1, firstDay, getNow3()); //本月采购退货
BigDecimal monthSale = depotHeadService.getBuyAndSaleStatistics("出库", "销售",
1,firstDay, getNow3()); //本月销售出库
BigDecimal monthSaleBack = depotHeadService.getBuyAndSaleStatistics("入库", "销售退货",
1,firstDay, getNow3()); //本月销售退货
BigDecimal monthRetailSale = depotHeadService.getBuyAndSaleRetailStatistics("出库", "零售",
firstDay, getNow3()); //本月零售出库
BigDecimal monthRetailSaleBack = depotHeadService.getBuyAndSaleRetailStatistics("入库", "零售退货",
firstDay, getNow3()); //本月零售退货
map.put("todayBuy", todayBuy.subtract(todayBuyBack));
map.put("todaySale", todaySale.subtract(todaySaleBack));
map.put("todayRetailSale", todayRetailSale.subtract(todayRetailSaleBack));
map.put("monthBuy", monthBuy.subtract(monthBuyBack));
map.put("monthSale", monthSale.subtract(monthSaleBack));
map.put("monthRetailSale", monthRetailSale.subtract(monthRetailSaleBack));
return R.success(map);
}
/**
* 根据当前用户获取操作员数组,用于控制当前用户的数据权限,限制可以看到的单据范围
* 注意:该接口提供给部分插件使用,勿删
* @param request
* @return
*/
@GetMapping(value = "/getCreatorByCurrentUser")
@ApiOperation(value = "根据当前用户获取操作员数组")
public R getCreatorByRoleType(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
String creator = "";
String roleType = redisService.getObjectFromSessionByKey(request,"roleType").toString();
if(StringUtil.isNotEmpty(roleType)) {
creator = depotHeadService.getCreatorByRoleType(roleType);
}
return R.success(creator);
}
/**
* 查询存在欠款的单据
* @param search
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/debtList")
@ApiOperation(value = "查询存在欠款的单据")
public String debtList(@RequestParam(value = Constants.SEARCH, required = false) String search,
HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<>();
String organIdStr = StringUtil.getInfo(search, "organId");
Long organId = Long.parseLong(organIdStr);
String materialParam = StringUtil.getInfo(search, "materialParam");
String number = StringUtil.getInfo(search, "number");
String beginTime = StringUtil.getInfo(search, "beginTime");
String endTime = StringUtil.getInfo(search, "endTime");
String type = StringUtil.getInfo(search, "type");
String subType = StringUtil.getInfo(search, "subType");
String roleType = StringUtil.getInfo(search, "roleType");
String status = StringUtil.getInfo(search, "status");
List<DepotHeadVo4List> list = depotHeadService.debtList(organId, materialParam, number, beginTime, endTime, type, subType, roleType, status);
if (list != null) {
objectMap.put("rows", list);
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
objectMap.put("rows", new ArrayList<>());
return returnJson(objectMap, "查找不到数据", ErpInfo.OK.code);
}
}
@GetMapping("/view")
public ModelAndView depotView(@RequestParam("no") String no) throws Exception {
ModelAndView model = new ModelAndView("depotView.html");
DepotHead head = depotHeadService.getDepotHead(no);
if (head == null || head.getId() == null){
model.addObject("order",null);
return model;
}
DepotHeadVo4Body body = new DepotHeadVo4Body();
body.setInfo(head);
List<DepotItem> list = depotItemService.getListByHeaderId(head.getId());
List<DepotItemDto> listRs = BeanUtil.copyToList(list, DepotItemDto.class);
body.setRows(listRs);
body.setId(head.getId());
String sub = no.substring(0, 4).toUpperCase();
logger.info("sub:{}",sub);
Supplier supplier = supplierService.getSupplier(head.getOrganId());
Account acc = accountService.getAccount(head.getAccountId());
model.addObject("supplier",supplier.getSupplier());
model.addObject("create_time", DateUtil.format(head.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
model.addObject("no",no);
model.addObject("link_no",head.getLinkNumber());
model.addObject("discount",head.getDiscount());
model.addObject("discount_money",head.getDiscountMoney());
model.addObject("discount_last_money",head.getDiscountLastMoney());
model.addObject("other_money",head.getOtherMoney());
model.addObject("account",acc.getName());
model.addObject("total_price",head.getTotalPrice());
model.addObject("debt",head.getDiscountLastMoney().subtract(head.getChangeAmount()));
model.addObject("title",sub);
model.addObject("order",body);
model.addObject("info",body.getInfo());
return model;
}
}
@@ -0,0 +1,640 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zsw.base.R;
import com.zsw.erp.constants.BusinessConstants;
import com.zsw.erp.datasource.mappers.MaterialInitialStockMapper;
import com.zsw.erp.datasource.vo.DepotItemStockWarningCount;
import com.zsw.erp.datasource.vo.DepotItemVoBatchNumberList;
import com.zsw.erp.dto.depot.RecordVo;
import com.zsw.erp.dto.depotItem.BatchStockDto;
import com.zsw.erp.service.depot.DepotService;
import com.zsw.erp.service.materialExtend.MaterialExtendService;
import com.zsw.erp.service.depotItem.DepotItemService;
import com.zsw.erp.service.material.MaterialService;
import com.zsw.erp.service.redis.RedisService;
import com.zsw.erp.service.unit.UnitService;
import com.zsw.erp.datasource.entities.*;
import com.zsw.erp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/depotItem")
@Api(tags = {"单据明细"})
public class DepotItemController {
private Logger logger = LoggerFactory.getLogger(DepotItemController.class);
@Resource
private DepotItemService depotItemService;
@Resource
private MaterialService materialService;
@Resource
private MaterialInitialStockMapper initialStockMapper;
@Resource
private MaterialExtendService materialExtendService;
@Resource
private UnitService unitService;
@Resource
private DepotService depotService;
@Resource
private RedisService redisService;
/**
* 只根据商品id查询单据列表
* @param mId
* @param request
* @return
*/
@GetMapping(value = "/findDetailByTypeAndMaterialId")
@ApiOperation(value = "只根据商品id查询单据列表")
public String findDetailByTypeAndMaterialId(
@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
@RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
@RequestParam("materialId") String mId, HttpServletRequest request)throws Exception {
Map<String, String> parameterMap = ParamUtils.requestToMap(request);
parameterMap.put("mId", mId);
Map<String, Object> objectMap = new HashMap<String, Object>();
if (pageSize != null && pageSize <= 0) {
pageSize = 10;
}
String offset = ParamUtils.getPageOffset(currentPage, pageSize);
if (StringUtil.isNotEmpty(offset)) {
parameterMap.put(Constants.OFFSET, offset);
}
List<DepotItemVo4DetailByTypeAndMId> list = depotItemService.findDetailByTypeAndMaterialIdList(parameterMap);
List<RecordVo> dataArray = Lists.newArrayList();
// 先把期初入库填入
// MaterialInitialStock initStock = initialStockMapper.selectOne(Wrappers.<MaterialInitialStock>lambdaQuery()
// .eq(MaterialInitialStock::getMaterialId, mId));
if (list != null) {
for (DepotItemVo4DetailByTypeAndMId d: list) {
RecordVo vo = new RecordVo();
vo.setNumber(d.getNumber());//编号
vo.setBarCode(d.getBarCode());//条码
vo.setMaterialName(d.getMaterialName());//名称
String type = d.getType();
String subType = d.getSubType();
if(("其它").equals(type)) {
vo.setType(subType);//进出类型
} else {
vo.setType( subType + type);
}
vo.setDepotName(d.getDepotName());//仓库名称
vo.setBasicNumber(d.getBnum());//数量
vo.setOperTime(d.getOtime());//时间
dataArray.add(vo);
}
}
if (list == null) {
objectMap.put("rows", new ArrayList<Object>());
objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
return returnJson(objectMap, "查找不到数据", ErpInfo.OK.code);
}
objectMap.put("rows", dataArray);
objectMap.put("total", depotItemService.findDetailByTypeAndMaterialIdCounts(parameterMap));
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
}
/**
* 根据商品条码和仓库id查询库存数量
* @param depotId
* @param barCode
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/findStockByDepotAndBarCode")
@ApiOperation(value = "根据商品条码和仓库id查询库存数量")
public R findStockByDepotAndBarCode(
@RequestParam(value = "depotId",required = false) Long depotId,
@RequestParam("barCode") String barCode,
HttpServletRequest request) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
BigDecimal stock = BigDecimal.ZERO;
List<MaterialVo4Unit> list = materialService.getMaterialByBarCode(barCode);
if(list!=null && list.size()>0) {
MaterialVo4Unit materialVo4Unit = list.get(0);
if(StringUtil.isNotEmpty(materialVo4Unit.getSku())){
stock = depotItemService.getSkuStockByParam(depotId,materialVo4Unit.getMeId(),null,null);
} else {
stock = depotItemService.getStockByParam(depotId,materialVo4Unit.getId(),null,null).getStock();
if(materialVo4Unit.getUnitId()!=null) {
Unit unit = unitService.getUnit(materialVo4Unit.getUnitId());
String commodityUnit = materialVo4Unit.getCommodityUnit();
stock = unitService.parseStockByUnit(stock, unit, commodityUnit);
}
}
}
map.put("stock", stock);
return R.success(map);
}
/**
* 单据明细列表
* @param headerId
* @param mpList
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getDetailList")
@ApiOperation(value = "单据明细列表")
public R getDetailList(@RequestParam("headerId") Long headerId,
@RequestParam("mpList") String mpList,
HttpServletRequest request)throws Exception {
List<DepotItemVo4WithInfoEx> dataList = new ArrayList<DepotItemVo4WithInfoEx>();
if(headerId != 0) {
dataList = depotItemService.getDetailList(headerId);
}
String[] mpArr = mpList.split(",");
JSONObject outer = new JSONObject();
outer.put("total", dataList.size());
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (DepotItemVo4WithInfoEx diEx : dataList) {
JSONObject item = new JSONObject();
item.put("materialExtendId", diEx.getMaterialExtendId() == null ? "" : diEx.getMaterialExtendId());
item.put("barCode", diEx.getBarCode());
item.put("name", diEx.getMName());
item.put("standard", diEx.getMStandard());
item.put("model", diEx.getMModel());
item.put("color", diEx.getMColor());
item.put("materialOther", getOtherInfo(mpArr, diEx));
BigDecimal stock;
if(StringUtil.isNotEmpty(diEx.getSku())){
stock = depotItemService.getSkuStockByParam(diEx.getDepotId(),diEx.getMaterialExtendId(),null,null);
} else {
stock = depotItemService.getStockByParam(diEx.getDepotId(),diEx.getMaterialId(),null,null).getStock();
Unit unitInfo = materialService.findUnit(diEx.getMaterialId()); //查询计量单位信息
if (StringUtil.isNotEmpty(unitInfo.getName())) {
String materialUnit = diEx.getMaterialUnit();
stock = unitService.parseStockByUnit(stock, unitInfo, materialUnit);
}
}
item.put("stock", stock);
item.put("unit", diEx.getMaterialUnit());
item.put("snList", diEx.getSnList());
item.put("batchNumber", diEx.getBatchNumber());
item.put("expirationDate", Tools.parseDateToStr(diEx.getExpirationDate()));
item.put("sku", diEx.getSku());
item.put("enableSerialNumber", diEx.getEnableSerialNumber());
item.put("enableBatchNumber", diEx.getEnableBatchNumber());
item.put("operNumber", diEx.getOperNumber());
item.put("basicNumber", diEx.getBasicNumber());
item.put("preNumber", diEx.getOperNumber()); //原数量
item.put("finishNumber", depotItemService.getFinishNumber(diEx.getMaterialId(), diEx.getHeaderId())); //已入库|已出库
item.put("unitPrice", diEx.getUnitPrice());
item.put("taxUnitPrice", diEx.getTaxUnitPrice());
item.put("allPrice", diEx.getAllPrice());
item.put("remark", diEx.getRemark());
item.put("depotId", diEx.getDepotId() == null ? "" : diEx.getDepotId());
item.put("depotName", diEx.getDepotId() == null ? "" : diEx.getDepotName());
item.put("anotherDepotId", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotId());
item.put("anotherDepotName", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotName());
item.put("taxRate", diEx.getTaxRate());
item.put("taxMoney", diEx.getTaxMoney());
item.put("taxLastMoney", diEx.getTaxLastMoney());
item.put("mType", diEx.getMaterialType());
item.put("op", 1);
dataArray.add(item);
}
}
outer.put("rows", dataArray);
return R.success(outer);
}
/**
* 获取扩展信息
*
* @return
*/
public String getOtherInfo(String[] mpArr, DepotItemVo4WithInfoEx diEx)throws Exception {
String materialOther = "";
for (int i = 0; i < mpArr.length; i++) {
if (mpArr[i].equals("制造商")) {
materialOther = materialOther + ((diEx.getMMfrs() == null || diEx.getMMfrs().equals("")) ? "" : "(" + diEx.getMMfrs() + ")");
}
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;
}
/**
* 查找所有的明细
* @param currentPage
* @param pageSize
* @param depotIds
* @param monthTime
* @param materialParam
* @param mpList
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/findByAll")
@ApiOperation(value = "查找所有的明细")
public R findByAll(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("depotIds") String depotIds,
@RequestParam("monthTime") String monthTime,
@RequestParam("materialParam") String materialParam,
@RequestParam("mpList") String mpList,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<>();
String timeA = Tools.firstDayOfMonth(monthTime) + BusinessConstants.DAY_FIRST_TIME;
String timeB = Tools.lastDayOfMonth(monthTime) + BusinessConstants.DAY_LAST_TIME;
List<Long> depotList = StringUtil.strToLongList(depotIds);
List<DepotItemVo4WithInfoEx> dataList = depotItemService.findByAll(StringUtil.toNull(materialParam),
timeB,(currentPage-1)*pageSize, pageSize);
String[] mpArr = mpList.split(",");
int total = depotItemService.findByAllCount(StringUtil.toNull(materialParam), timeB);
map.put("total", total);
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
List<Long> idList = new ArrayList<>();
for (DepotItemVo4WithInfoEx m : dataList) {
idList.add(m.getMId());
}
List<MaterialExtend> meList = materialExtendService.getListByMIds(idList);
for (DepotItemVo4WithInfoEx diEx : dataList) {
JSONObject item = new JSONObject();
Long mId = diEx.getMId();
item.put("barCode", diEx.getBarCode());
item.put("materialName", diEx.getMName());
item.put("materialModel", diEx.getMModel());
item.put("materialStandard", diEx.getMStandard());
//扩展信息
String materialOther = getOtherInfo(mpArr, diEx);
item.put("materialOther", materialOther);
item.put("materialColor", diEx.getMColor());
item.put("unitName", diEx.getMaterialUnit());
BigDecimal prevSum = depotItemService.getStockByParamWithDepotList(depotList,mId,null,timeA);
Map<String,BigDecimal> intervalMap = depotItemService.getIntervalMapByParamWithDepotList(depotList,mId,timeA,timeB);
BigDecimal inSum = intervalMap.get("inSum");
BigDecimal outSum = intervalMap.get("outSum");
BigDecimal thisSum = prevSum.add(inSum).subtract(outSum);
item.put("prevSum", prevSum);
item.put("inSum", inSum);
item.put("outSum", outSum);
item.put("thisSum", thisSum);
for(MaterialExtend me:meList) {
if(me.getMaterialId().longValue() == diEx.getMId().longValue()) {
if(me.getPurchaseDecimal()!=null) {
item.put("unitPrice", me.getPurchaseDecimal());
item.put("thisAllPrice", thisSum.multiply(me.getPurchaseDecimal()));
}
}
}
dataArray.add(item);
}
}
map.put("rows", dataArray);
return R.success(map);
}
/**
* 统计总计金额
* @param depotIds
* @param monthTime
* @param materialParam
* @param request
* @return
*/
@GetMapping(value = "/totalCountMoney")
@ApiOperation(value = "统计总计金额")
public R totalCountMoney(@RequestParam("depotIds") String depotIds,
@RequestParam("monthTime") String monthTime,
@RequestParam("materialParam") String materialParam,
HttpServletRequest request) throws Exception{
Map<String, Object> map = new HashMap<>();
String endTime = Tools.lastDayOfMonth(monthTime) + BusinessConstants.DAY_LAST_TIME;
List<Long> depotList = StringUtil.strToLongList(depotIds);
List<DepotItemVo4WithInfoEx> dataList = depotItemService.findByAll(StringUtil.toNull(materialParam),
endTime, null, null);
BigDecimal thisAllPrice = BigDecimal.ZERO;
if (null != dataList) {
for (DepotItemVo4WithInfoEx diEx : dataList) {
Long mId = diEx.getMId();
BigDecimal thisSum = depotItemService.getStockByParamWithDepotList(depotList,mId,null,endTime);
BigDecimal unitPrice = diEx.getPurchaseDecimal();
if(unitPrice == null) {
unitPrice = BigDecimal.ZERO;
}
thisAllPrice = thisAllPrice.add(thisSum.multiply(unitPrice));
}
}
map.put("totalCount", thisAllPrice);
return R.success(map);
}
/**
* 进货统计
* @param currentPage
* @param pageSize
* @param monthTime
* @param materialParam
* @param mpList
* @param request
* @return
*/
@GetMapping(value = "/buyIn")
@ApiOperation(value = "进货统计")
public R buyIn(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("monthTime") String monthTime,
@RequestParam("materialParam") String materialParam,
@RequestParam("mpList") String mpList,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String endTime = Tools.lastDayOfMonth(monthTime) + BusinessConstants.DAY_LAST_TIME;
List<DepotItemVo4WithInfoEx> dataList = depotItemService.findByAll(StringUtil.toNull(materialParam),
endTime, (currentPage-1)*pageSize, pageSize);
String[] mpArr = mpList.split(",");
int total = depotItemService.findByAllCount(StringUtil.toNull(materialParam), endTime);
map.put("total", total);
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (DepotItemVo4WithInfoEx diEx : dataList) {
JSONObject item = new JSONObject();
BigDecimal InSum = depotItemService.buyOrSale("入库", "采购", diEx.getMId(), monthTime, "number");
BigDecimal OutSum = depotItemService.buyOrSale("出库", "采购退货", diEx.getMId(), monthTime, "number");
BigDecimal InSumPrice = depotItemService.buyOrSale("入库", "采购", diEx.getMId(), monthTime, "price");
BigDecimal OutSumPrice = depotItemService.buyOrSale("出库", "采购退货", diEx.getMId(), monthTime, "price");
BigDecimal InOutSumPrice = InSumPrice.subtract(OutSumPrice);
item.put("barCode", diEx.getBarCode());
item.put("materialName", diEx.getMName());
item.put("materialModel", diEx.getMModel());
item.put("materialStandard", diEx.getMStandard());
//扩展信息
String materialOther = getOtherInfo(mpArr, diEx);
item.put("materialOther", materialOther);
item.put("materialColor", diEx.getMColor());
item.put("materialUnit", diEx.getMaterialUnit());
item.put("unitName", diEx.getUnitName());
item.put("inSum", InSum);
item.put("outSum", OutSum);
item.put("inSumPrice", InSumPrice);
item.put("outSumPrice", OutSumPrice);
item.put("inOutSumPrice",InOutSumPrice);//实际采购金额
dataArray.add(item);
}
}
map.put("rows", dataArray);
return R.success(map);
}
/**
* 销售统计
* @param currentPage
* @param pageSize
* @param monthTime
* @param materialParam
* @param mpList
* @param request
* @return
*/
@GetMapping(value = "/saleOut")
@ApiOperation(value = "销售统计")
public R saleOut(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("monthTime") String monthTime,
@RequestParam("materialParam") String materialParam,
@RequestParam("mpList") String mpList,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String endTime = Tools.lastDayOfMonth(monthTime) + BusinessConstants.DAY_LAST_TIME;
List<DepotItemVo4WithInfoEx> dataList = depotItemService.findByAll(StringUtil.toNull(materialParam),
endTime,(currentPage-1)*pageSize, pageSize);
String[] mpArr = mpList.split(",");
int total = depotItemService.findByAllCount(StringUtil.toNull(materialParam), endTime);
map.put("total", total);
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (DepotItemVo4WithInfoEx diEx : dataList) {
JSONObject item = new JSONObject();
BigDecimal OutSumRetail = depotItemService.buyOrSale("出库", "零售", diEx.getMId(), monthTime,"number");
BigDecimal OutSum = depotItemService.buyOrSale("出库", "销售", diEx.getMId(), monthTime,"number");
BigDecimal InSumRetail = depotItemService.buyOrSale("入库", "零售退货", diEx.getMId(), monthTime,"number");
BigDecimal InSum = depotItemService.buyOrSale("入库", "销售退货", diEx.getMId(), monthTime,"number");
BigDecimal OutSumRetailPrice = depotItemService.buyOrSale("出库", "零售", diEx.getMId(), monthTime,"price");
BigDecimal OutSumPrice = depotItemService.buyOrSale("出库", "销售", diEx.getMId(), monthTime,"price");
BigDecimal InSumRetailPrice = depotItemService.buyOrSale("入库", "零售退货", diEx.getMId(), monthTime,"price");
BigDecimal InSumPrice = depotItemService.buyOrSale("入库", "销售退货", diEx.getMId(), monthTime,"price");
BigDecimal OutInSumPrice = (OutSumRetailPrice.add(OutSumPrice)).subtract(InSumRetailPrice.add(InSumPrice));
item.put("barCode", diEx.getBarCode());
item.put("materialName", diEx.getMName());
item.put("materialModel", diEx.getMModel());
item.put("materialStandard", diEx.getMStandard());
//扩展信息
String materialOther = getOtherInfo(mpArr, diEx);
item.put("materialOther", materialOther);
item.put("materialColor", diEx.getMColor());
item.put("materialUnit", diEx.getMaterialUnit());
item.put("unitName", diEx.getUnitName());
item.put("outSum", OutSumRetail.add(OutSum));
item.put("inSum", InSumRetail.add(InSum));
item.put("outSumPrice", OutSumRetailPrice.add(OutSumPrice));
item.put("inSumPrice", InSumRetailPrice.add(InSumPrice));
item.put("outInSumPrice",OutInSumPrice);//实际销售金额
dataArray.add(item);
}
}
map.put("rows", dataArray);
return R.success(map);
}
/**
* 获取单位
* @param materialUnit
* @param uName
* @return
*/
public String getUName(String materialUnit, String uName) {
String unitName = null;
if(StringUtil.isNotEmpty(materialUnit)) {
unitName = materialUnit;
} else if(StringUtil.isNotEmpty(uName)) {
unitName = uName;
}
return unitName;
}
/**
* 库存预警报表
* @param currentPage
* @param pageSize
* @return
*/
@GetMapping(value = "/findStockWarningCount")
@ApiOperation(value = "库存预警报表")
public R findStockWarningCount(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("materialParam") String materialParam,
@RequestParam(value = "depotId", required = false) Long depotId,
@RequestParam("mpList") String mpList)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<Long> depotList = new ArrayList<>();
if(depotId != null) {
depotList.add(depotId);
} else {
//未选择仓库时默认为当前用户有权限的仓库
JSONArray depotArr = depotService.findDepotByCurrentUser();
for(Object obj: depotArr) {
JSONObject object = JSONObject.parseObject(obj.toString());
depotList.add(object.getLong("id"));
}
}
String[] mpArr = mpList.split(",");
List<DepotItemStockWarningCount> list = depotItemService.findStockWarningCount((currentPage-1)*pageSize, pageSize, materialParam, depotList);
//存放数据json数组
if (null != list) {
for (DepotItemStockWarningCount disw : list) {
DepotItemVo4WithInfoEx diEx = new DepotItemVo4WithInfoEx();
diEx.setMMfrs(disw.getMMfrs());
diEx.setMOtherField1(disw.getMOtherField1());
diEx.setMOtherField2(disw.getMOtherField2());
diEx.setMOtherField3(disw.getMOtherField3());
disw.setMaterialOther(getOtherInfo(mpArr, diEx));
disw.setMaterialUnit(getUName(disw.getMaterialUnit(), disw.getUnitName()));
if(disw.getCurrentNumber().compareTo(disw.getLowSafeStock())<0) {
disw.setLowCritical(disw.getLowSafeStock().subtract(disw.getCurrentNumber()));
disw.setHighCritical(BigDecimal.ZERO);
}
if(disw.getCurrentNumber().compareTo(disw.getHighSafeStock())>0) {
disw.setLowCritical(BigDecimal.ZERO);
disw.setHighCritical(disw.getCurrentNumber().subtract(disw.getHighSafeStock()));
}
}
}
int total = depotItemService.findStockWarningCountTotal(materialParam, depotList);
map.put("total", total);
map.put("rows", list);
return R.success(map);
}
/**
* 统计采购、销售、零售的总金额
* @param request
* @param response
* @return
* @throws Exception
*/
@GetMapping(value = "/buyOrSalePrice")
@ApiOperation(value = "统计采购、销售、零售的总金额")
public R buyOrSalePrice(HttpServletRequest request, HttpServletResponse response)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String message = "成功";
List<String> list = Tools.getLastMonths(6);
JSONArray buyPriceList = new JSONArray();
for(String month: list) {
JSONObject obj = new JSONObject();
BigDecimal outPrice = depotItemService.inOrOutPrice("入库", "采购", month);
BigDecimal inPrice = depotItemService.inOrOutPrice("出库", "采购退货", month);
obj.put("x", month);
obj.put("y", outPrice.subtract(inPrice));
buyPriceList.add(obj);
}
map.put("buyPriceList", buyPriceList);
JSONArray salePriceList = new JSONArray();
for(String month: list) {
JSONObject obj = new JSONObject();
BigDecimal outPrice = depotItemService.inOrOutPrice("出库", "销售", month);
BigDecimal inPrice = depotItemService.inOrOutPrice("入库", "销售退货", month);
obj.put("x", month);
obj.put("y", outPrice.subtract(inPrice));
salePriceList.add(obj);
}
map.put("salePriceList", salePriceList);
JSONArray retailPriceList = new JSONArray();
for(String month: list) {
JSONObject obj = new JSONObject();
BigDecimal outPrice = depotItemService.inOrOutRetailPrice("出库", "零售", month);
BigDecimal inPrice = depotItemService.inOrOutRetailPrice("入库", "零售退货", month);
obj.put("x", month);
obj.put("y", outPrice.subtract(inPrice));
retailPriceList.add(obj);
}
map.put("retailPriceList", retailPriceList);
return R.success(map);
}
/**
* 获取批次商品列表信息
* @param request
* @return
*/
@GetMapping(value = "/getBatchNumberList")
@ApiOperation(value = "获取批次商品列表信息")
public R getBatchNumberList(@RequestParam("name") String name,
@RequestParam("depotId") Long depotId,
@RequestParam("barCode") String barCode,
@RequestParam(value = "batchNumber", required = false) String batchNumber,
HttpServletRequest request) throws Exception{
Map<String, Object> map = new HashMap<>();
List<DepotItemVoBatchNumberList> reslist = new ArrayList<>();
List<DepotItemVoBatchNumberList> list = depotItemService.getBatchNumberList(name, depotId, barCode, batchNumber);
for(DepotItemVoBatchNumberList bn: list) {
if(bn.getTotalNum()!=null && bn.getTotalNum().compareTo(BigDecimal.ZERO)>0) {
reslist.add(bn);
}
bn.setExpirationDateStr(Tools.parseDateToStr(bn.getExpirationDate()));
}
map.put("rows", reslist);
map.put("total", reslist.size());
return R.success(map);
}
@GetMapping(value = "/batchStock")
@ApiOperation(value = "批次库存查询")
public R batchStock(BatchStockDto dto) {
Map<String, Object> map = new HashMap<>();
map.put("rows", depotItemService.batchStockPage(dto));
map.put("total", depotItemService.batchStockCount(dto));
return R.success(map);
}
}
@@ -0,0 +1,241 @@
package com.zsw.erp.controller;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.google.common.collect.Lists;
import com.zsw.erp.datasource.entities.BtnDto;
import com.zsw.erp.datasource.entities.Function;
import com.zsw.erp.datasource.entities.UserBusiness;
import com.zsw.erp.service.functions.FunctionService;
import com.zsw.erp.service.userBusiness.UserBusinessService;
import com.zsw.base.R;
import com.zsw.erp.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value = "/function")
@Api(tags = {"功能管理"})
public class FunctionController {
private Logger logger = LoggerFactory.getLogger(FunctionController.class);
@Resource
private FunctionService functionService;
@Resource
private UserBusinessService userBusinessService;
/**
* 根据父编号查询菜单
* @param jsonObject
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/findMenuByPNumber")
@ApiOperation(value = "根据父编号查询菜单")
public JSONArray findMenuByPNumber(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
String pNumber = jsonObject.getStr("pNumber");
Long userId = jsonObject.getLong("userId");
//存放数据json数组
JSONArray dataArray = new JSONArray();
try {
Long roleId = 0L;
List<Long> fc = Lists.newArrayList();
UserBusiness role = userBusinessService.getBasicData(userId, "UserRole");
roleId = role.getValue().get(0).longValue();
//当前用户所拥有的功能列表,格式如:[1][2][5]
// List<UserBusiness> funList = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions");
// if(funList!=null && funList.size()>0){
// fc = funList.get(0).getValue();
// }
// List<Function> dataList = functionService.getRoleFunction(pNumber);
List<Function> dataList;
if (roleId == 1L){
logger.info("当前是系统管理员,给予全部菜单和权限。");
dataList = functionService.getRoleFunction(pNumber);
fc = functionService.getFunction().stream().map(Function::getId).collect(Collectors.toList());
}else{
dataList = functionService.getRoleFunction(pNumber);
UserBusiness fun = userBusinessService.getBasicData(roleId, "RoleFunctions");
fc = fun.getValue().stream().map(Number::longValue).collect(Collectors.toList());
}
if (dataList.size() != 0) {
dataArray = getMenuByFunction(dataList, fc);
//增加首页菜单项
JSONObject homeItem = new JSONObject();
homeItem.set("id", 0);
homeItem.set("text", "首页");
homeItem.set("icon", "home");
homeItem.set("url", "/dashboard/analysis");
homeItem.set("component", "/layouts/TabLayout");
dataArray.add(0,homeItem);
}
} catch (DataAccessException e) {
logger.error(">>>>>>>>>>>>>>>>>>>查找异常", e);
}
return dataArray;
}
public JSONArray getMenuByFunction(List<Function> dataList, List<Long> fc) throws Exception {
dataList = dataList.stream()
.filter(function -> fc.contains(function.getId()))
.collect(Collectors.toList());
JSONArray dataArray = new JSONArray();
for (Function function : dataList) {
JSONObject item = new JSONObject();
List<Function> newList = functionService.getRoleFunction(function.getNumber());
item.set("id", function.getId());
item.set("text", function.getName());
item.set("icon", function.getIcon());
item.set("url", function.getUrl());
item.set("component", function.getComponent());
if (newList.size()>0) {
JSONArray childrenArr = getMenuByFunction(newList, fc);
if(childrenArr.size()>0) {
item.put("children", childrenArr);
dataArray.add(item);
}
} else {
if (fc.contains(function.getId())) {
dataArray.add(item);
}
}
}
return dataArray;
}
/**
* 角色对应功能显示
* @param request
* @return
*/
@GetMapping(value = "/findRoleFunction")
@ApiOperation(value = "角色对应功能显示")
public JSONArray findRoleFunction(@RequestParam("UBType") String type, @RequestParam("UBKeyId") Long keyId,
HttpServletRequest request)throws Exception {
JSONArray arr = new JSONArray();
try {
List<Function> dataListFun = functionService.findRoleFunction("0");
//开始拼接json数据
JSONObject outer = new JSONObject();
outer.set("id", 0);
outer.set("key", 0);
outer.set("value", 0);
outer.set("title", "功能列表");
outer.set("attributes", "功能列表");
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataListFun) {
//根据条件从列表里面移除"系统管理"
List<Function> dataList = new ArrayList<>();
for (Function fun : dataListFun) {
String token = request.getHeader("X-Access-Token");
Long tenantId = Tools.getTenantIdByToken(token);
if (tenantId!=0L) {
if(!("系统管理").equals(fun.getName())) {
dataList.add(fun);
}
} else {
//超管
dataList.add(fun);
}
}
dataArray = getFunctionList(dataList, type, keyId);
outer.set("children", dataArray);
}
arr.add(outer);
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
public JSONArray getFunctionList(List<Function> dataList, String type, Long keyId) throws Exception {
JSONArray dataArray = new JSONArray();
//获取权限信息
List<Long> ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, keyId);
if (null != dataList) {
for (Function function : dataList) {
JSONObject item = new JSONObject();
item.set("id", function.getId());
item.set("key", function.getId());
item.set("value", function.getId());
item.set("title", function.getName());
item.set("attributes", function.getName());
List<Function> funList = functionService.findRoleFunction(function.getNumber());
if(funList.size()>0) {
JSONArray funArr = getFunctionList(funList, type, keyId);
item.set("children", funArr);
} else {
if (ubValue == null){
item.set("checked", false);
}else {
Boolean flag = ubValue.contains(function.getId());
item.set("checked", flag);
}
}
dataArray.add(item);
}
}
return dataArray;
}
/**
* 根据id列表查找功能信息
* @param roleId
* @param request
* @return
*/
@GetMapping(value = "/findRoleFunctionsById")
@ApiOperation(value = "根据id列表查找功能信息")
public R findByIds(@RequestParam("roleId") Long roleId,
HttpServletRequest request)throws Exception {
UserBusiness ub = userBusinessService.getBasicData(roleId, "RoleFunctions");
//按钮
Map<Long,String> btnMap = new HashMap<>();
List<BtnDto> btnStr = ub.getBtnStr();
if(ObjectUtil.isNotEmpty(btnStr)) {
for(BtnDto obj: btnStr) {
if(obj.getFunId()!=null && obj.getBtnStr()!=null) {
btnMap.put(obj.getFunId(), obj.getBtnStr());
}
}
}
//菜单
List<Long> funIds = ub.getValue().stream().map(Number::longValue).collect(Collectors.toList());
List<Function> dataList = functionService.findByIds(funIds);
JSONObject outer = new JSONObject();
outer.set("total", dataList.size());
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (ObjectUtil.isNotEmpty(dataList)) {
for (Function function : dataList) {
JSONObject item = new JSONObject();
item.set("id", function.getId());
item.set("name", function.getName());
item.set("pushBtn", function.getPushBtn());
item.set("btnStr", ObjectUtil.isEmpty(btnMap.get(function.getId()))?"":btnMap.get(function.getId()));
dataArray.add(item);
}
}
outer.set("rows", dataArray);
return R.success(outer);
}
}
@@ -0,0 +1,59 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.InOutItem;
import com.zsw.erp.service.inOutItem.InOutItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping(value = "/inOutItem")
@Api(tags = {"收支项目"})
public class InOutItemController {
private Logger logger = LoggerFactory.getLogger(InOutItemController.class);
@Resource
private InOutItemService inOutItemService;
/**
* 查找收支项目信息-下拉框
* @param request
* @return
*/
@GetMapping(value = "/findBySelect")
@ApiOperation(value = "查找收支项目信息")
public String findBySelect(@RequestParam("type") String type, HttpServletRequest request) throws Exception{
String res = null;
try {
List<InOutItem> dataList = inOutItemService.findBySelect(type);
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (InOutItem inOutItem : dataList) {
JSONObject item = new JSONObject();
item.put("id", inOutItem.getId());
//收支项目名称
item.put("name", inOutItem.getName());
dataArray.add(item);
}
}
res = dataArray.toJSONString();
} catch(Exception e){
e.printStackTrace();
res = "获取数据失败";
}
return res;
}
}
@@ -0,0 +1,14 @@
package com.zsw.erp.controller;
import com.zsw.base.R;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@RequestMapping("/")
public R<String> index(){
return R.success("","欢迎访问回乡进销存系统");
}
}
@@ -0,0 +1,33 @@
package com.zsw.erp.controller;
import com.zsw.base.R;
import com.zsw.erp.service.inventorySeason.InventorySeasonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(value = "期次管理",tags = "期次管理")
@RequestMapping("/inventory")
public class InventorySeasonController {
@Autowired
private InventorySeasonService inventorySeasonService;
@ApiOperation("获取当前期次")
@GetMapping("/now")
public R getNow(){
return R.success(inventorySeasonService.getNow());
}
@ApiOperation("结束当前期次 开始新的期次")
@GetMapping("/endNow")
public R endNow(){
return R.success(inventorySeasonService.endNow());
}
}
@@ -0,0 +1,39 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONObject;
import com.zsw.base.R;
import com.zsw.erp.service.materialAttribute.MaterialAttributeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping(value = "/materialAttribute")
@Api(tags = {"商品属性"})
public class MaterialAttributeController {
private Logger logger = LoggerFactory.getLogger(MaterialAttributeController.class);
@Resource
private MaterialAttributeService materialAttributeService;
/**
* 获取全部商品属性
* @param request
* @return
* @throws Exception
*/
@GetMapping("/getAll")
@ApiOperation(value = "获取全部商品属性")
public R getAll(HttpServletRequest request)throws Exception {
JSONObject obj = materialAttributeService.getAll();
return R.success(obj);
}
}
@@ -0,0 +1,141 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.constants.ExceptionConstants;
import com.zsw.erp.datasource.entities.MaterialCategory;
import com.zsw.erp.datasource.vo.TreeNode;
import com.zsw.erp.exception.BusinessRunTimeException;
import com.zsw.erp.service.materialCategory.MaterialCategoryService;
import com.zsw.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;
@RestController
@RequestMapping(value = "/materialCategory")
@Api(tags = {"商品类别"})
@Validated
public class MaterialCategoryController {
private Logger logger = LoggerFactory.getLogger(MaterialCategoryController.class);
@Resource
private MaterialCategoryService materialCategoryService;
/**
* 获取全部商品类别
* @param parentId
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getAllList")
@ApiOperation(value = "获取全部商品类别")
public R getAllList(@RequestParam("parentId") Long parentId, HttpServletRequest request) throws Exception{
List<MaterialCategory> materialCategoryList = materialCategoryService.getAllList(parentId);
return R.success(materialCategoryList);
}
/**
* 根据id来查询商品名称
* @param id
* @param request
* @return
*/
@GetMapping(value = "/findById")
@ApiOperation(value = "根据id来查询商品名称")
public R findById(@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
List<MaterialCategory> dataList = materialCategoryService.findById(id);
JSONObject outer = new JSONObject();
if (null != dataList) {
for (MaterialCategory mc : dataList) {
outer.put("id", mc.getId());
outer.put("name", mc.getName());
outer.put("parentId", mc.getParentId());
List<MaterialCategory> dataParentList = materialCategoryService.findById(mc.getParentId());
if(dataParentList!=null&&dataParentList.size()>0){
outer.put("parentName", dataParentList.get(0).getName());
}
outer.put("sort", mc.getSort());
outer.put("serialNo", mc.getSerialNo());
outer.put("remark", mc.getRemark());
}
}
return R.success(outer);
}
/**
* create by: cjl
* description:
* 获取商品类别树数据
* create time: 2019/2/19 11:49
* @Param:
* @return com.alibaba.fastjson.JSONArray
*/
@RequestMapping(value = "/getMaterialCategoryTree")
@ApiOperation(value = "获取商品类别树数据")
public JSONArray getMaterialCategoryTree(@RequestParam(value = "id",defaultValue = "0") Long id) throws Exception{
JSONArray arr=new JSONArray();
List<TreeNode> materialCategoryTree = materialCategoryService.getMaterialCategoryTree(id);
if(materialCategoryTree!=null&&materialCategoryTree.size()>0){
for(TreeNode node:materialCategoryTree){
String str=JSON.toJSONString(node);
JSONObject obj=JSON.parseObject(str);
arr.add(obj) ;
}
}
return arr;
}
/**
* create by: cjl
* description:
* 新增商品类别数据
* create time: 2019/2/19 17:17
* @Param: beanJson
* @return java.lang.Object
*/
@RequestMapping(value = "/addMaterialCategory")
@ApiOperation(value = "新增商品类别数据")
public Object addMaterialCategory(@RequestParam("info") String beanJson) throws Exception {
JSONObject result = ExceptionConstants.standardSuccess();
MaterialCategory mc= JSON.parseObject(beanJson, MaterialCategory.class);
int i= materialCategoryService.addMaterialCategory(mc);
if(i<1){
throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_ADD_FAILED_CODE,
ExceptionConstants.MATERIAL_CATEGORY_ADD_FAILED_MSG);
}
return result;
}
/**
* create by: cjl
* description:
* 修改商品类别数据
* create time: 2019/2/20 9:30
* @Param: beanJson
* @return java.lang.Object
*/
@RequestMapping(value = "/editMaterialCategory")
@ApiOperation(value = "修改商品类别数据")
public Object editMaterialCategory(@RequestParam("info") String beanJson) throws Exception {
JSONObject result = ExceptionConstants.standardSuccess();
MaterialCategory mc= JSON.parseObject(beanJson, MaterialCategory.class);
int i= materialCategoryService.editMaterialCategory(mc);
if(i<1){
throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_EDIT_FAILED_CODE,
ExceptionConstants.MATERIAL_CATEGORY_EDIT_FAILED_MSG);
}
return result;
}
}
@@ -0,0 +1,662 @@
package com.zsw.erp.controller;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.base.R;
import com.zsw.erp.service.depot.DepotService;
import com.zsw.erp.service.depotItem.DepotItemService;
import com.zsw.erp.service.material.MaterialService;
import com.zsw.erp.service.redis.RedisService;
import com.zsw.erp.service.unit.UnitService;
import com.zsw.erp.datasource.entities.MaterialVo4Unit;
import com.zsw.erp.datasource.entities.Unit;
import com.zsw.erp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
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.*;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/material")
@Api(tags = {"商品管理"})
public class MaterialController {
private Logger logger = LoggerFactory.getLogger(MaterialController.class);
@Resource
private MaterialService materialService;
@Resource
private DepotItemService depotItemService;
@Resource
private UnitService unitService;
@Resource
private DepotService depotService;
@Resource
private RedisService redisService;
/**
* 检查商品是否存在
*
* @param id
* @param name
* @param model
* @param color
* @param standard
* @param mfrs
* @param otherField1
* @param otherField2
* @param otherField3
* @param unit
* @param unitId
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/checkIsExist")
@ApiOperation(value = "检查商品是否存在")
public String checkIsExist(@RequestParam("id") Long id, @RequestParam("name") String name,
@RequestParam("model") String model, @RequestParam("color") String color,
@RequestParam("standard") String standard, @RequestParam("mfrs") String mfrs,
@RequestParam("otherField1") String otherField1, @RequestParam("otherField2") String otherField2,
@RequestParam("otherField3") String otherField3, @RequestParam("unit") String unit, @RequestParam("unitId") Long unitId,
HttpServletRequest request) throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>();
int exist = materialService.checkIsExist(id, name, StringUtil.toNull(model), StringUtil.toNull(color),
StringUtil.toNull(standard), StringUtil.toNull(mfrs), StringUtil.toNull(otherField1),
StringUtil.toNull(otherField2), StringUtil.toNull(otherField3), StringUtil.toNull(unit), unitId);
if (exist > 0) {
objectMap.put("status", true);
} else {
objectMap.put("status", false);
}
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
}
/**
* 批量设置状态-启用或者禁用
*
* @param jsonObject
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/batchSetStatus")
@ApiOperation(value = "批量设置状态-启用或者禁用")
public String batchSetStatus(@RequestBody JSONObject jsonObject,
HttpServletRequest request) throws Exception {
Boolean status = jsonObject.getBoolean("status");
String ids = jsonObject.getString("ids");
Map<String, Object> objectMap = new HashMap<>();
int res = materialService.batchSetStatus(status, ids);
if (res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 根据id来查询商品名称
*
* @param id
* @param request
* @return
*/
@GetMapping(value = "/findById")
@ApiOperation(value = "根据id来查询商品名称")
public R findById(@RequestParam("id") Long id, HttpServletRequest request) throws Exception {
List<MaterialVo4Unit> list = materialService.findById(id);
return R.success(list);
}
/**
* 根据meId来查询商品名称
*
* @param meId
* @param request
* @return
*/
@GetMapping(value = "/findByIdWithBarCode")
@ApiOperation(value = "根据meId来查询商品名称")
public R findByIdWithBarCode(@RequestParam("meId") Long meId,
@RequestParam("mpList") String mpList,
HttpServletRequest request) throws Exception {
String[] mpArr = mpList.split(",");
MaterialVo4Unit mu = new MaterialVo4Unit();
List<MaterialVo4Unit> list = materialService.findByIdWithBarCode(meId);
if (list != null && list.size() > 0) {
mu = list.get(0);
String expand = ""; //扩展信息
for (int i = 0; i < mpArr.length; i++) {
if (mpArr[i].equals("制造商")) {
expand = expand + ((mu.getMfrs() == null || mu.getMfrs().equals("")) ? "" : "(" + mu.getMfrs() + ")");
}
if (mpArr[i].equals("自定义1")) {
expand = expand + ((mu.getOtherField1() == null || mu.getOtherField1().equals("")) ? "" : "(" + mu.getOtherField1() + ")");
}
if (mpArr[i].equals("自定义2")) {
expand = expand + ((mu.getOtherField2() == null || mu.getOtherField2().equals("")) ? "" : "(" + mu.getOtherField2() + ")");
}
if (mpArr[i].equals("自定义3")) {
expand = expand + ((mu.getOtherField3() == null || mu.getOtherField3().equals("")) ? "" : "(" + mu.getOtherField3() + ")");
}
}
mu.setMaterialOther(expand);
}
return R.success(mu);
}
/**
* 查找商品信息-下拉框
*
* @param mpList
* @param request
* @return
*/
@GetMapping(value = "/findBySelect")
@ApiOperation(value = "查找商品信息")
public JSONObject findBySelect(@RequestParam(value = "categoryId", required = false) Long categoryId,
@RequestParam(value = "q", required = false) String q,
@RequestParam("mpList") String mpList,
@RequestParam(value = "depotId", required = false) Long depotId,
@RequestParam("page") Integer currentPage,
@RequestParam("rows") Integer pageSize,
HttpServletRequest request) throws Exception {
JSONObject object = new JSONObject();
try {
List<MaterialVo4Unit> dataList = materialService.findBySelectWithBarCode(categoryId, q, (currentPage - 1) * pageSize, pageSize);
String[] mpArr = mpList.split(",");
int total = materialService.findBySelectWithBarCodeCount(categoryId, q);
object.put("total", total);
JSONArray dataArray = new JSONArray();
//存放数据json数组
if (null != dataList) {
for (MaterialVo4Unit material : dataList) {
JSONObject item = new JSONObject();
item.put("id", material.getMeId()); //商品扩展表的id
String ratioStr = ""; //比例
Unit unit = new Unit();
if (material.getUnitId() == null) {
ratioStr = "";
} else {
unit = unitService.getUnit(material.getUnitId());
//拼接副单位的比例
String commodityUnit = material.getCommodityUnit();
if (commodityUnit.equals(unit.getBasicUnit())) {
ratioStr = "[基本]";
}
if (commodityUnit.equals(unit.getOtherUnit())) {
ratioStr = "[" + unit.getRatio() + unit.getBasicUnit() + "]";
}
if (commodityUnit.equals(unit.getOtherUnitTwo())) {
ratioStr = "[" + unit.getRatioTwo() + unit.getBasicUnit() + "]";
}
if (commodityUnit.equals(unit.getOtherUnitThree())) {
ratioStr = "[" + unit.getRatioThree() + unit.getBasicUnit() + "]";
}
}
item.put("mBarCode", material.getMBarCode());
item.put("name", material.getName());
item.put("categoryName", material.getCategoryName());
item.put("standard", material.getStandard());
item.put("model", material.getModel());
item.put("color", material.getColor());
item.put("unit", material.getCommodityUnit() + ratioStr);
item.put("sku", material.getSku());
item.put("enableSerialNumber", material.getEnableSerialNumber());
item.put("enableBatchNumber", material.getEnableBatchNumber());
BigDecimal stock;
if (StringUtil.isNotEmpty(material.getSku())) {
stock = depotItemService.getSkuStockByParam(depotId, material.getMeId(), null, null);
} else {
stock = depotItemService.getStockByParam(depotId, material.getId(), null, null).getStock();
if (material.getUnitId() != null) {
String commodityUnit = material.getCommodityUnit();
stock = unitService.parseStockByUnit(stock, unit, commodityUnit);
}
}
item.put("stock", stock);
String expand = ""; //扩展信息
for (int i = 0; i < mpArr.length; i++) {
if (mpArr[i].equals("制造商")) {
expand = expand + ((material.getMfrs() == null || material.getMfrs().equals("")) ? "" : "(" + material.getMfrs() + ")");
}
if (mpArr[i].equals("自定义1")) {
expand = expand + ((material.getOtherField1() == null || material.getOtherField1().equals("")) ? "" : "(" + material.getOtherField1() + ")");
}
if (mpArr[i].equals("自定义2")) {
expand = expand + ((material.getOtherField2() == null || material.getOtherField2().equals("")) ? "" : "(" + material.getOtherField2() + ")");
}
if (mpArr[i].equals("自定义3")) {
expand = expand + ((material.getOtherField3() == null || material.getOtherField3().equals("")) ? "" : "(" + material.getOtherField3() + ")");
}
}
item.put("expand", expand);
dataArray.add(item);
}
}
object.put("rows", dataArray);
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
/**
* 根据商品id查找商品信息
*
* @param meId
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getMaterialByMeId")
@ApiOperation(value = "根据商品id查找商品信息")
public JSONObject getMaterialByMeId(@RequestParam(value = "meId", required = false) Long meId,
@RequestParam("mpList") String mpList,
HttpServletRequest request) throws Exception {
JSONObject item = new JSONObject();
try {
String[] mpArr = mpList.split(",");
List<MaterialVo4Unit> materialList = materialService.getMaterialByMeId(meId);
if (materialList != null && materialList.size() != 1) {
return item;
} else if (materialList.size() == 1) {
MaterialVo4Unit material = materialList.get(0);
item.put("Id", material.getMeId()); //商品扩展表的id
String ratio; //比例
if (material.getUnitId() == null || material.getUnitId().equals("")) {
ratio = "";
} else {
ratio = material.getUnitName();
ratio = ratio.substring(ratio.indexOf("("));
}
//名称/型号/扩展信息/包装
String MaterialName = "";
MaterialName = MaterialName + material.getMBarCode() + "_" + material.getName()
+ ((material.getStandard() == null || material.getStandard().equals("")) ? "" : "(" + material.getStandard() + ")");
String expand = ""; //扩展信息
for (int i = 0; i < mpArr.length; i++) {
if (mpArr[i].equals("颜色")) {
expand = expand + ((material.getColor() == null || material.getColor().equals("")) ? "" : "(" + material.getColor() + ")");
}
if (mpArr[i].equals("制造商")) {
expand = expand + ((material.getMfrs() == null || material.getMfrs().equals("")) ? "" : "(" + material.getMfrs() + ")");
}
if (mpArr[i].equals("自定义1")) {
expand = expand + ((material.getOtherField1() == null || material.getOtherField1().equals("")) ? "" : "(" + material.getOtherField1() + ")");
}
if (mpArr[i].equals("自定义2")) {
expand = expand + ((material.getOtherField2() == null || material.getOtherField2().equals("")) ? "" : "(" + material.getOtherField2() + ")");
}
if (mpArr[i].equals("自定义3")) {
expand = expand + ((material.getOtherField3() == null || material.getOtherField3().equals("")) ? "" : "(" + material.getOtherField3() + ")");
}
}
MaterialName = MaterialName + expand + ((material.getUnit() == null || material.getUnit().equals("")) ? "" : "(" + material.getUnit() + ")") + ratio;
item.put("MaterialName", MaterialName);
item.put("name", material.getName());
item.put("expand", expand);
item.put("model", material.getModel());
item.put("standard", material.getStandard());
item.put("unit", material.getUnit() + ratio);
}
} catch (Exception e) {
e.printStackTrace();
}
return item;
}
/**
* 生成excel表格
*
* @param barCode
* @param name
* @param standard
* @param model
* @param categoryId
* @param request
* @param response
*/
@GetMapping(value = "/exportExcel")
@ApiOperation(value = "生成excel表格")
public void exportExcel(@RequestParam("categoryId") String categoryId,
@RequestParam("barCode") String barCode,
@RequestParam("name") String name,
@RequestParam("standard") String standard,
@RequestParam("model") String model,
@RequestParam("mpList") String mpList,
HttpServletRequest request, HttpServletResponse response) {
try {
List<MaterialVo4Unit> dataList = materialService.findByAll(StringUtil.toNull(barCode), StringUtil.toNull(name),
StringUtil.toNull(standard), StringUtil.toNull(model), StringUtil.toNull(categoryId));
String[] names = {"名称", "类型", "型号", "单位", "零售价", "最低售价", "采购价", "销售价", "备注", "状态"};
String title = "商品信息";
List<String[]> objects = new ArrayList<String[]>();
if (null != dataList) {
for (MaterialVo4Unit m : dataList) {
String[] objs = new String[10];
objs[0] = m.getName();
objs[1] = m.getCategoryName();
objs[2] = m.getModel();
objs[3] = m.getCommodityUnit();
objs[4] = m.getCommodityDecimal() == null ? "" : m.getCommodityDecimal().toString();
objs[5] = m.getLowDecimal() == null ? "" : m.getLowDecimal().toString();
objs[6] = m.getPurchaseDecimal() == null ? "" : m.getPurchaseDecimal().toString();
objs[7] = m.getWholesaleDecimal() == null ? "" : m.getWholesaleDecimal().toString();
objs[8] = m.getRemark();
objs[9] = m.getEnabled() ? "启用" : "禁用";
objects.add(objs);
}
}
File file = ExcelUtils.exportObjectsWithoutTitle(title, names, title, objects);
ExportExecUtil.showExec(file, file.getName(), response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* excel表格导入产品(含初始库存)
*
* @param file
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importExcel")
@ApiOperation(value = "excel表格导入产品")
public R importExcel(MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws Exception {
String message = "成功";
//文件合法性校验
ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
List<List<Object>> list = reader.read();
return materialService.importExcel(list, request);
}
public BigDecimal parseBigDecimalEx(String str) throws Exception {
if (!StringUtil.isEmpty(str)) {
return new BigDecimal(str);
} else {
return null;
}
}
/**
* 获取商品序列号
*
* @param q
* @param currentPage
* @param pageSize
* @param request
* @param response
* @return
* @throws Exception
*/
@GetMapping(value = "/getMaterialEnableSerialNumberList")
@ApiOperation(value = "获取商品序列号")
public JSONObject getMaterialEnableSerialNumberList(
@RequestParam(value = "q", required = false) String q,
@RequestParam("page") Integer currentPage,
@RequestParam("rows") Integer pageSize,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
JSONObject object = new JSONObject();
try {
List<MaterialVo4Unit> list = materialService.getMaterialEnableSerialNumberList(q, (currentPage - 1) * pageSize, pageSize);
Long count = materialService.getMaterialEnableSerialNumberCount(q);
object.put("rows", list);
object.put("total", count);
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
/**
* 获取最大条码
*
* @return
* @throws Exception
*/
@GetMapping(value = "/getMaxBarCode")
@ApiOperation(value = "获取最大条码")
public R getMaxBarCode() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String barCode = materialService.getMaxBarCode();
map.put("barCode", barCode);
return R.success(map);
}
/**
* 商品名称模糊匹配
*
* @return
* @throws Exception
*/
@GetMapping(value = "/getMaterialNameList")
@ApiOperation(value = "商品名称模糊匹配")
public JSONArray getMaterialNameList() throws Exception {
JSONArray arr = new JSONArray();
try {
List<String> list = materialService.getMaterialNameList();
for (String s : list) {
JSONObject item = new JSONObject();
item.put("value", s);
item.put("text", s);
arr.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
/**
* 根据条码查询商品信息
*
* @return
* @throws Exception
*/
@GetMapping(value = "/getMaterialByBarCode")
@ApiOperation(value = "根据条码查询商品信息")
public R getMaterialByBarCode(@RequestParam("barCode") String barCode,
@RequestParam(value = "depotId", required = false) Long depotId,
@RequestParam("mpList") String mpList,
@RequestParam(required = false, value = "prefixNo") String prefixNo,
HttpServletRequest request) throws Exception {
String[] mpArr = mpList.split(",");
List<MaterialVo4Unit> list = materialService.getMaterialByBarCode(barCode);
if (list != null && list.size() > 0) {
for (MaterialVo4Unit mvo : list) {
String expand = ""; //扩展信息
for (int i = 0; i < mpArr.length; i++) {
if (mpArr[i].equals("制造商")) {
expand = expand + ((mvo.getMfrs() == null || mvo.getMfrs().equals("")) ? "" : "(" + mvo.getMfrs() + ")");
}
if (mpArr[i].equals("自定义1")) {
expand = expand + ((mvo.getOtherField1() == null || mvo.getOtherField1().equals("")) ? "" : "(" + mvo.getOtherField1() + ")");
}
if (mpArr[i].equals("自定义2")) {
expand = expand + ((mvo.getOtherField2() == null || mvo.getOtherField2().equals("")) ? "" : "(" + mvo.getOtherField2() + ")");
}
if (mpArr[i].equals("自定义3")) {
expand = expand + ((mvo.getOtherField3() == null || mvo.getOtherField3().equals("")) ? "" : "(" + mvo.getOtherField3() + ")");
}
}
mvo.setMaterialOther(expand);
if ("LSCK".equals(prefixNo) || "LSTH".equals(prefixNo)) {
//零售价
mvo.setBillPrice(mvo.getCommodityDecimal());
} else if ("CGDD".equals(prefixNo) || "CGRK".equals(prefixNo) || "CGTH".equals(prefixNo)
|| "QTRK".equals(prefixNo) || "DBCK".equals(prefixNo) || "ZZD".equals(prefixNo) || "CXD".equals(prefixNo)
|| "PDLR".equals(prefixNo) || "PDFP".equals(prefixNo)) {
//采购价
mvo.setBillPrice(mvo.getPurchaseDecimal());
} else if ("XSDD".equals(prefixNo) || "XSCK".equals(prefixNo) || "XSTH".equals(prefixNo) || "QTCK".equals(prefixNo)) {
//销售价
mvo.setBillPrice(mvo.getWholesaleDecimal());
}
//仓库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);
}
}
}
return R.success(list);
}
/**
* 根据商品信息获取库存,进行赋值
*
* @param mvo
* @throws Exception
*/
private void getStockByMaterialInfo(MaterialVo4Unit mvo) throws Exception {
BigDecimal stock;
if (StringUtil.isNotEmpty(mvo.getSku())) {
stock = depotItemService.getSkuStockByParam(mvo.getDepotId(), mvo.getMeId(), null, null);
} else {
stock = depotItemService.getStockByParam(mvo.getDepotId(), mvo.getId(), null, null).getStock();
if (mvo.getUnitId() != null) {
Unit unit = unitService.getUnit(mvo.getUnitId());
String commodityUnit = mvo.getCommodityUnit();
stock = unitService.parseStockByUnit(stock, unit, commodityUnit);
}
}
mvo.setStock(stock);
}
/**
* 商品库存查询
*
* @param currentPage
* @param pageSize
* @param depotIds
* @param categoryId
* @param materialParam
* @param mpList
* @param column
* @param order
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getListWithStock")
@ApiOperation(value = "商品库存查询")
public R getListWithStock(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam(value = "depotIds", required = false) String depotIds,
@RequestParam(value = "categoryId", required = false) Long categoryId,
@RequestParam("materialParam") String materialParam,
@RequestParam("zeroStock") Integer zeroStock,
@RequestParam("mpList") String mpList,
@RequestParam("column") String column,
@RequestParam("order") String order,
@RequestParam("startTime") String startTime,
HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<>();
try {
List<Long> idList = new ArrayList<>();
List<Long> depotList = new ArrayList<>();
if (categoryId != null) {
idList = materialService.getListByParentId(categoryId);
}
if (StringUtil.isNotEmpty(depotIds)) {
depotList = StringUtil.strToLongList(depotIds);
} else {
//未选择仓库时默认为当前用户有权限的仓库
JSONArray depotArr = depotService.findDepotByCurrentUser();
for (Object obj : depotArr) {
JSONObject object = JSONObject.parseObject(obj.toString());
depotList.add(object.getLong("id"));
}
}
List<MaterialVo4Unit> dataList = materialService.getListWithStock(depotList, idList, StringUtil.toNull(materialParam), zeroStock,
startTime,
StringUtil.safeSqlParse(column), StringUtil.safeSqlParse(order), (currentPage - 1) * pageSize, pageSize);
// int total = materialService.getListWithStockCount(depotList, idList, StringUtil.toNull(materialParam), zeroStock,startTime);
MaterialVo4Unit materialVo4Unit = materialService.getTotalStockAndPrice(depotList, idList, StringUtil.toNull(materialParam),startTime);
if (ObjectUtil.isEmpty(dataList)){
map.put("total", 0);
map.put("currentStock", 0);
map.put("currentStockPrice", 0);
map.put("rows", dataList);
return R.success(map);
}
map.put("total", materialVo4Unit.getStock());
map.put("currentStock", materialVo4Unit.getCurrentStock());
map.put("currentStockPrice", materialVo4Unit.getCurrentStockPrice());
//存放数据json数组
map.put("rows", dataList);
return R.success(map);
} catch (Exception e) {
e.printStackTrace();
return R.fail("获取数据失败");
}
}
/**
* 批量设置商品当前的实时库存(按每个仓库)
*
* @param jsonObject
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/batchSetMaterialCurrentStock")
@ApiOperation(value = "批量设置商品当前的实时库存(按每个仓库)")
public String batchSetMaterialCurrentStock(@RequestBody JSONObject jsonObject,
HttpServletRequest request) throws Exception {
String ids = jsonObject.getString("ids");
Map<String, Object> objectMap = new HashMap<>();
int res = materialService.batchSetMaterialCurrentStock(ids);
if (res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
}
@@ -0,0 +1,109 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.MaterialExtend;
import com.zsw.erp.datasource.vo.MaterialExtendVo4List;
import com.zsw.erp.service.materialExtend.MaterialExtendService;
import com.zsw.base.R;
import com.zsw.erp.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/materialsExtend")
@Api(tags = {"商品价格扩展"})
public class MaterialExtendController {
private Logger logger = LoggerFactory.getLogger(MaterialExtendController.class);
@Resource
private MaterialExtendService materialExtendService;
@GetMapping(value = "/getDetailList")
@ApiOperation(value = "价格信息列表")
public R getDetailList(@RequestParam("materialId") Long materialId,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<MaterialExtendVo4List> dataList = new ArrayList<MaterialExtendVo4List>();
if(materialId!=0) {
dataList = materialExtendService.getDetailList(materialId);
}
JSONObject outer = new JSONObject();
outer.put("total", dataList.size());
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (MaterialExtendVo4List md : dataList) {
JSONObject item = new JSONObject();
item.put("id", md.getId());
item.put("barCode", md.getBarCode());
item.put("commodityUnit", md.getCommodityUnit());
if(StringUtil.isNotEmpty(md.getSku())){
item.put("sku", md.getSku());
}
item.put("purchaseDecimal", md.getPurchaseDecimal());
item.put("commodityDecimal", md.getCommodityDecimal());
item.put("wholesaleDecimal", md.getWholesaleDecimal());
item.put("lowDecimal", md.getLowDecimal());
dataArray.add(item);
}
}
outer.put("rows", dataArray);
return R.success(outer);
}
/**
* 根据条码查询商品信息
* @param barCode
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getInfoByBarCode")
@ApiOperation(value = "根据条码查询商品信息")
public R getInfoByBarCode(@RequestParam("barCode") String barCode,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
MaterialExtend materialExtend = materialExtendService.getInfoByBarCode(barCode);
return R.success(materialExtend);
}
/**
* 校验条码是否存在
* @param id
* @param barCode
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/checkIsBarCodeExist")
@ApiOperation(value = "校验条码是否存在")
public R checkIsBarCodeExist(@RequestParam("id") Long id,
@RequestParam("barCode") String barCode,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<>();
int exist = materialExtendService.checkIsBarCodeExist(id, barCode);
if(exist > 0) {
map.put("status", true);
} else {
map.put("status", false);
}
return R.success(map);
}
}
@@ -0,0 +1,19 @@
package com.zsw.erp.controller;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description
*
* @Author: qiankunpingtai
* @Date: 2019/3/29 15:24
*/
@RestController
@RequestMapping(value = "/materialProperty")
@Api(tags = {"商品扩展字段"})
public class MaterialPropertyController {
}
@@ -0,0 +1,111 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.MsgEx;
import com.zsw.erp.service.msg.MsgService;
import com.zsw.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/msg")
@Api(tags = {"消息管理"})
public class MsgController {
private Logger logger = LoggerFactory.getLogger(MsgController.class);
@Resource
private MsgService msgService;
/**
* 根据状态查询消息
* @param status
* @param request
* @return
* @throws Exception
*/
@GetMapping("/getMsgByStatus")
@ApiOperation(value = "根据状态查询消息")
public R getMsgByStatus(@RequestParam("status") String status,
HttpServletRequest request)throws Exception {
List<MsgEx> list = msgService.getMsgByStatus(status);
return R.success(list);
}
/**
* 批量更新状态
* @param jsonObject
* @param request
* @return
* @throws Exception
*/
@PostMapping("/batchUpdateStatus")
@ApiOperation(value = "批量更新状态")
public R batchUpdateStatus(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
String ids = jsonObject.getString("ids");
String status = jsonObject.getString("status");
msgService.batchUpdateStatus(ids, status);
return R.success();
}
/**
* 根据状态查询数量
* @param status
* @param request
* @return
* @throws Exception
*/
@GetMapping("/getMsgCountByStatus")
@ApiOperation(value = "根据状态查询数量")
public R getMsgCountByStatus(@RequestParam("status") String status,
HttpServletRequest request)throws Exception {
Map<String, Long> map = new HashMap<String, Long>();
Long count = msgService.getMsgCountByStatus(status);
map.put("count", count);
return R.success(map);
}
/**
* 根据类型查询数量
* @param type
* @param request
* @return
* @throws Exception
*/
@GetMapping("/getMsgCountByType")
@ApiOperation(value = "根据类型查询数量")
public R getMsgCountByType(@RequestParam("type") String type,
HttpServletRequest request)throws Exception {
Map<String, Integer> map = new HashMap<>();
Integer count = msgService.getMsgCountByType(type);
map.put("count", count);
return R.success(map);
}
/**
* 全部设置未已读
* @param request
* @return
* @throws Exception
*/
@PostMapping("/readAllMsg")
@ApiOperation(value = "全部设置未已读")
public R readAllMsg(HttpServletRequest request)throws Exception {
msgService.readAllMsg();
return R.success();
}
}
@@ -0,0 +1,130 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.base.R;
import com.zsw.erp.constants.ExceptionConstants;
import com.zsw.erp.datasource.entities.Organization;
import com.zsw.erp.datasource.vo.TreeNode;
import com.zsw.erp.exception.BusinessRunTimeException;
import com.zsw.erp.service.organization.OrganizationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* create by: cjl
* description:
*
* create time: 2019/3/6 10:54
*/
@RestController
@RequestMapping(value = "/organization")
@Api(tags = {"机构管理"})
public class OrganizationController {
private Logger logger = LoggerFactory.getLogger(OrganizationController.class);
@Resource
private OrganizationService organizationService;
/**
* 根据id来查询机构信息
* @param id
* @param request
* @return
*/
@GetMapping(value = "/findById")
@ApiOperation(value = "根据id来查询机构信息")
public R findById(@RequestParam("id") Long id, HttpServletRequest request) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Organization> dataList = organizationService.findById(id);
JSONObject outer = new JSONObject();
if (null != dataList) {
for (Organization org : dataList) {
outer.put("id", org.getId());
outer.put("orgAbr", org.getOrgAbr());
outer.put("parentId", org.getParentId());
List<Organization> dataParentList = organizationService.findByParentId(org.getParentId());
if(dataParentList!=null&&dataParentList.size()>0){
//父级机构名称显示简称
outer.put("orgParentName", dataParentList.get(0).getOrgAbr());
}
outer.put("orgNo", org.getOrgNo());
outer.put("sort", org.getSort());
outer.put("remark", org.getRemark());
}
}
return R.success(outer);
}
/**
* create by: cjl
* description:
* 获取机构树数据
* create time: 2019/2/19 11:49
* @Param:
* @return com.alibaba.fastjson.JSONArray
*/
@RequestMapping(value = "/getOrganizationTree")
@ApiOperation(value = "获取机构树数据")
public JSONArray getOrganizationTree(@RequestParam(value = "id",defaultValue = "0") Long id) throws Exception{
JSONArray arr=new JSONArray();
List<TreeNode> organizationTree= organizationService.getOrganizationTree(id);
if(organizationTree!=null&&organizationTree.size()>0){
for(TreeNode node:organizationTree){
String str=JSON.toJSONString(node);
JSONObject obj=JSON.parseObject(str);
arr.add(obj);
}
}
return arr;
}
/**
* create by: cjl
* description:
* 新增机构信息
* create time: 2019/2/19 17:17
* @Param: beanJson
* @return java.lang.Object
*/
@PostMapping(value = "/addOrganization")
@ApiOperation(value = "新增机构信息")
public Object addOrganization(@RequestParam("info") String beanJson) throws Exception {
JSONObject result = ExceptionConstants.standardSuccess();
Organization org= JSON.parseObject(beanJson, Organization.class);
int i= organizationService.addOrganization(org);
if(i<1){
throw new BusinessRunTimeException(ExceptionConstants.ORGANIZATION_ADD_FAILED_CODE,
ExceptionConstants.ORGANIZATION_ADD_FAILED_MSG);
}
return result;
}
/**
* create by: cjl
* description:
* 修改机构信息
* create time: 2019/2/20 9:30
* @Param: beanJson
* @return java.lang.Object
*/
@PostMapping(value = "/editOrganization")
@ApiOperation(value = "修改机构信息")
public Object editOrganization(@RequestParam("info") String beanJson) throws Exception {
JSONObject result = ExceptionConstants.standardSuccess();
Organization org= JSON.parseObject(beanJson, Organization.class);
int i= organizationService.editOrganization(org);
if(i<1){
throw new BusinessRunTimeException(ExceptionConstants.ORGANIZATION_EDIT_FAILED_CODE,
ExceptionConstants.ORGANIZATION_EDIT_FAILED_MSG);
}
return result;
}
}
@@ -0,0 +1,118 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.Person;
import com.zsw.erp.service.person.PersonService;
import com.zsw.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/person")
@Api(tags = {"经手人管理"})
public class PersonController {
private Logger logger = LoggerFactory.getLogger(PersonController.class);
@Resource
private PersonService personService;
/**
* 全部数据列表
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getAllList")
@ApiOperation(value = "全部数据列表")
public R getAllList(HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<Person> personList = personService.getPerson();
map.put("personList", personList);
return R.success(map);
}
/**
* 根据Id获取经手人信息
* @param personIds
* @param request
* @return
*/
@GetMapping(value = "/getPersonByIds")
@ApiOperation(value = "根据Id获取经手人信息")
public R getPersonByIds(@RequestParam("personIds") String personIds,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
Map<Long,String> personMap = personService.getPersonMap();
String names = personService.getPersonByMapAndIds(personMap, personIds);
map.put("names", names);
return R.success(map);
}
/**
* 根据类型获取经手人信息
* @param type
* @param request
* @return
*/
@GetMapping(value = "/getPersonByType")
@ApiOperation(value = "根据类型获取经手人信息")
public R getPersonByType(@RequestParam("type") String type,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<Person> personList = personService.getPersonByType(type);
map.put("personList", personList);
return R.success(map);
}
/**
* 根据类型获取经手人信息 1-业务员,2-仓管员,3-财务员
* @param typeNum
* @param request
* @return
*/
@GetMapping(value = "/getPersonByNumType")
@ApiOperation(value = "根据类型获取经手人信息1-业务员,2-仓管员,3-财务员")
public JSONArray getPersonByNumType(@RequestParam("type") String typeNum,
HttpServletRequest request)throws Exception {
JSONArray dataArray = new JSONArray();
try {
String type = "";
if (typeNum.equals("1")) {
type = "业务员";
} else if (typeNum.equals("2")) {
type = "仓管员";
} else if (typeNum.equals("3")) {
type = "财务员";
}
List<Person> personList = personService.getPersonByType(type);
if (null != personList) {
for (Person person : personList) {
JSONObject item = new JSONObject();
item.put("value", person.getId().toString());
item.put("text", person.getName());
dataArray.add(item);
}
}
} catch(Exception e){
e.printStackTrace();
}
return dataArray;
}
}
@@ -0,0 +1,116 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.PlatformConfig;
import com.zsw.erp.service.platformConfig.PlatformConfigService;
import com.zsw.erp.service.user.UserService;
import com.zsw.base.R;
import com.zsw.erp.utils.ErpInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/platformConfig")
@Api(tags = {"平台参数"})
public class PlatformConfigController {
private Logger logger = LoggerFactory.getLogger(PlatformConfigController.class);
@Value("${demonstrate.open}")
private boolean demonstrateOpen;
@Resource
private PlatformConfigService platformConfigService;
@Resource
private UserService userService;
private static final String TEST_USER = "jsh";
/**
* 获取平台名称
* @param request
* @return
*/
@GetMapping(value = "/getPlatform/name")
@ApiOperation(value = "获取平台名称")
public String getPlatformName(HttpServletRequest request)throws Exception {
String res;
try {
String platformKey = "platform_name";
PlatformConfig platformConfig = platformConfigService.getPlatformConfigByKey(platformKey);
res = platformConfig.getPlatformValue();
} catch(Exception e){
e.printStackTrace();
res = "ERP系统";
}
return res;
}
/**
* 获取官方网站地址
* @param request
* @return
*/
@GetMapping(value = "/getPlatform/url")
@ApiOperation(value = "获取官方网站地址")
public String getPlatformUrl(HttpServletRequest request)throws Exception {
String res;
try {
String platformKey = "platform_url";
PlatformConfig platformConfig = platformConfigService.getPlatformConfigByKey(platformKey);
res = platformConfig.getPlatformValue();
} catch(Exception e){
e.printStackTrace();
res = "#";
}
return res;
}
/**
* 根据platformKey更新platformValue
* @param object
* @param request
* @return
*/
@PostMapping(value = "/updatePlatformConfigByKey")
@ApiOperation(value = "根据platformKey更新platformValue")
public String updatePlatformConfigByKey(@RequestBody JSONObject object,
HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<>();
String platformKey = object.getString("platformKey");
String platformValue = object.getString("platformValue");
int res = platformConfigService.updatePlatformConfigByKey(platformKey, platformValue);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 根据platformKey查询信息
* @param platformKey
* @param request
* @return
*/
@GetMapping(value = "/getPlatformConfigByKey")
@ApiOperation(value = "根据platformKey查询信息")
public R getPlatformConfigByKey(@RequestParam("platformKey") String platformKey,
HttpServletRequest request)throws Exception {
PlatformConfig platformConfig = platformConfigService.getPlatformConfigByKey(platformKey);
return R.success(platformConfig);
}
}
@@ -0,0 +1,150 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.constants.BusinessConstants;
import com.zsw.erp.service.CommonQueryManager;
import com.zsw.erp.utils.Constants;
import com.zsw.erp.utils.ErpInfo;
import com.zsw.erp.utils.ParamUtils;
import com.zsw.erp.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@Api(tags = {"资源接口"})
public class ResourceController {
@Resource
private CommonQueryManager configResourceManager;
@GetMapping(value = "/{apiName}/info")
@ApiOperation(value = "根据id获取信息")
public String getList(@PathVariable("apiName") String apiName,
@RequestParam("id") Long id,
HttpServletRequest request) throws Exception {
Object obj = configResourceManager.selectOne(apiName, id);
Map<String, Object> objectMap = new HashMap<String, Object>();
if(obj != null) {
objectMap.put("info", obj);
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
@GetMapping(value = "/{apiName}/list")
@ApiOperation(value = "获取信息列表")
public String getList(@PathVariable("apiName") String apiName,
@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
@RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
@RequestParam(value = Constants.SEARCH, required = false) String search,
HttpServletRequest request)throws Exception {
Map<String, String> parameterMap = ParamUtils.requestToMap(request);
parameterMap.put(Constants.SEARCH, search);
Map<String, Object> objectMap = new HashMap<String, Object>();
if (pageSize != null && pageSize <= 0) {
pageSize = 10;
}
String offset = ParamUtils.getPageOffset(currentPage, pageSize);
if (StringUtil.isNotEmpty(offset)) {
parameterMap.put(Constants.OFFSET, offset);
}
List<?> list = configResourceManager.select(apiName, parameterMap);
if (list != null) {
objectMap.put("total", configResourceManager.counts(apiName, parameterMap));
objectMap.put("rows", list);
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
objectMap.put("rows", new ArrayList<Object>());
return returnJson(objectMap, "查找不到数据", ErpInfo.OK.code);
}
}
@PostMapping(value = "/{apiName}/add", produces = {"application/javascript", "application/json"})
@ApiOperation(value = "新增")
public String addResource(@PathVariable("apiName") String apiName,
@RequestBody JSONObject obj, HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>();
int insert = configResourceManager.insert(apiName, obj, request);
if(insert > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else if(insert == -1) {
return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
@PutMapping(value = "/{apiName}/update", produces = {"application/javascript", "application/json"})
@ApiOperation(value = "修改")
public String updateResource(@PathVariable("apiName") String apiName,
@RequestBody JSONObject obj, HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>();
int update = configResourceManager.update(apiName, obj, request);
if(update > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else if(update == -1) {
return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
@DeleteMapping(value = "/{apiName}/delete", produces = {"application/javascript", "application/json"})
@ApiOperation(value = "删除")
public String deleteResource(@PathVariable("apiName") String apiName,
@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>();
int delete = configResourceManager.delete(apiName, id, request);
if(delete > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else if(delete == -1) {
return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
@DeleteMapping(value = "/{apiName}/deleteBatch", produces = {"application/javascript", "application/json"})
@ApiOperation(value = "批量删除")
public String batchDeleteResource(@PathVariable("apiName") String apiName,
@RequestParam("ids") String ids, HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>();
int delete = configResourceManager.deleteBatch(apiName, ids, request);
if(delete > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else if(delete == -1) {
return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
@GetMapping(value = "/{apiName}/checkIsNameExist")
@ApiOperation(value = "检查名称是否存在")
public String checkIsNameExist(@PathVariable("apiName") String apiName,
@RequestParam Long id, @RequestParam(value ="name", required = false) String name,
HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>();
int exist = configResourceManager.checkIsNameExist(apiName, id, name);
if(exist > 0) {
objectMap.put("status", true);
} else {
objectMap.put("status", false);
}
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
}
}
@@ -0,0 +1,71 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.Role;
import com.zsw.erp.service.role.RoleService;
import com.zsw.erp.service.userBusiness.UserBusinessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping(value = "/role")
@Api(tags = {"角色管理"})
public class RoleController {
private Logger logger = LoggerFactory.getLogger(RoleController.class);
@Resource
private RoleService roleService;
@Resource
private UserBusinessService userBusinessService;
/**
* 角色对应应用显示
* @param request
* @return
*/
@GetMapping(value = "/findUserRole")
@ApiOperation(value = "查询用户的角色")
public JSONArray findUserRole(@RequestParam("UBType") String type, @RequestParam("UBKeyId") Long keyId,
HttpServletRequest request)throws Exception {
JSONArray arr = new JSONArray();
try {
//获取权限信息
List<Long> ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, keyId);
List<Role> dataList = roleService.findUserRole();
if (null != dataList) {
for (Role role : dataList) {
JSONObject item = new JSONObject();
item.put("id", role.getId());
item.put("text", role.getName());
Boolean flag = ubValue.contains(role.getId());
if (flag) {
item.put("checked", true);
}
arr.add(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
@GetMapping(value = "/allList")
@ApiOperation(value = "查询全部角色列表")
public List<Role> allList(HttpServletRequest request)throws Exception {
return roleService.allList();
}
}
@@ -0,0 +1,43 @@
package com.zsw.erp.controller;
import com.zsw.erp.service.sequence.SequenceService;
import com.zsw.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping(value = "/sequence")
@Api(tags = {"单据编号"})
public class SequenceController {
private Logger logger = LoggerFactory.getLogger(SequenceController.class);
@Resource
private SequenceService sequenceService;
/**
* 单据编号生成接口
* @param request
* @return
*/
@GetMapping(value = "/buildNumber")
@ApiOperation(value = "单据编号生成接口")
public R buildNumber(HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String number = sequenceService.buildOnlyNumber();
map.put("defaultNumber", number);
return R.success(map);
}
}
@@ -0,0 +1,93 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.datasource.entities.SerialNumber;
import com.zsw.erp.service.serialNumber.SerialNumberService;
import com.zsw.base.R;
import com.zsw.erp.utils.ErpInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
/**
* Description
*
* @Author: cjl
* @Date: 2019/1/22 10:29
*/
@RestController
@RequestMapping(value = "/serialNumber")
@Api(tags = {"序列号管理"})
public class SerialNumberController {
private Logger logger = LoggerFactory.getLogger(SerialNumberController.class);
@Resource
private SerialNumberService serialNumberService;
/**
* create by: cjl
* description:
*批量添加序列号
* create time: 2019/1/29 15:11
* @Param: materialName
* @Param: serialNumberPrefix
* @Param: batAddTotal
* @Param: remark
* @return java.lang.Object
*/
@PostMapping("/batAddSerialNumber")
@ApiOperation(value = "批量添加序列号")
public String batAddSerialNumber(@RequestBody JSONObject jsonObject, HttpServletRequest request)throws Exception{
Map<String, Object> objectMap = new HashMap<>();
String materialCode = jsonObject.getString("materialCode");
String serialNumberPrefix = jsonObject.getString("serialNumberPrefix");
Integer batAddTotal = jsonObject.getInteger("batAddTotal");
String remark = jsonObject.getString("remark");
int insert = serialNumberService.batAddSerialNumber(materialCode,serialNumberPrefix,batAddTotal,remark);
if(insert > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else if(insert == -1) {
return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 获取序列号商品
* @param name
* @param depotId
* @param barCode
* @param currentPage
* @param pageSize
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getEnableSerialNumberList")
@ApiOperation(value = "获取序列号商品")
public R getEnableSerialNumberList(@RequestParam("name") String name,
@RequestParam("depotId") Long depotId,
@RequestParam("barCode") String barCode,
@RequestParam("page") Integer currentPage,
@RequestParam("rows") Integer pageSize,
HttpServletRequest request)throws Exception {
Map<String, Object> map = new HashMap<>();
List<SerialNumber> list = serialNumberService.getEnableSerialNumberList(name, depotId, barCode, (currentPage-1)*pageSize, pageSize);
Long total = serialNumberService.getEnableSerialNumberCount(name, depotId, barCode);
map.put("rows", list);
map.put("total", total);
return R.success(map);
}
}
@@ -0,0 +1,358 @@
package com.zsw.erp.controller;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zsw.erp.datasource.entities.Supplier;
import com.zsw.erp.dto.supplier.SupplierVo;
import com.zsw.erp.service.supplier.SupplierService;
import com.zsw.erp.service.systemConfig.SystemConfigService;
import com.zsw.erp.service.tenant.TenantService;
import com.zsw.erp.service.user.UserService;
import com.zsw.erp.service.userBusiness.UserBusinessService;
import com.zsw.base.R;
import com.zsw.erp.utils.ErpInfo;
import com.zsw.erp.utils.ExportExecUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
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.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/supplier")
@Api(tags = {"商家管理"})
public class SupplierController {
private Logger logger = LoggerFactory.getLogger(SupplierController.class);
@Resource
private SupplierService supplierService;
@Resource
private UserBusinessService userBusinessService;
@Resource
private SystemConfigService systemConfigService;
@Resource
private UserService userService;
@Resource
private TenantService tenantService;
@GetMapping(value = "/checkIsNameAndTypeExist")
@ApiOperation(value = "检查名称和类型是否存在")
public String checkIsNameAndTypeExist(@RequestParam Long id,
@RequestParam(value ="name") String name,
@RequestParam(value ="type") String type,
HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<>();
int exist = supplierService.checkIsNameAndTypeExist(id, name, type);
if(exist > 0) {
objectMap.put("status", true);
} else {
objectMap.put("status", false);
}
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
}
/**
* 查找客户信息-下拉框
* @param request
* @return
*/
@PostMapping(value = "/findBySelect_cus")
@ApiOperation(value = "查找客户信息")
public List<SupplierVo> findBySelectCus(HttpServletRequest request) throws Exception {
List<SupplierVo> list = Lists.newArrayList();
// String type = "UserCustomer";
// Long userId = userService.getUserId(request);
//获取权限信息
// List<Long> ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, userId);
List<Supplier> supplierList = supplierService.findBySelectCus();
if (null != supplierList) {
boolean customerFlag = systemConfigService.getCustomerFlag();
for (Supplier supplier : supplierList) {
// JSONObject item = new JSONObject();
// Boolean flag = ubValue.contains(supplier.getId());
if (!customerFlag ) { //flag
SupplierVo vo = new SupplierVo();
vo.setId(supplier.getId());
vo.setSupplier(supplier.getSupplier());
vo.setTargetType(false);
list.add(vo);
}
}
}
addSupplier(list);
return list;
}
/**
* 查找供应商信息-下拉框
* @param request
* @return
*/
@PostMapping(value = "/findBySelect_sup")
@ApiOperation(value = "查找供应商信息")
public List<SupplierVo> findBySelectSup(HttpServletRequest request) throws Exception{
List<SupplierVo> list = Lists.newArrayList();
List<Supplier> supplierList = supplierService.findBySelectSup();
if (null != supplierList) {
for (Supplier supplier : supplierList) {
SupplierVo vo = new SupplierVo();
vo.setId(supplier.getId());
vo.setSupplier(supplier.getSupplier());
vo.setTargetType(false);
list.add(vo);
}
}
addSupplier(list);
return list;
}
private void addSupplier(List<SupplierVo> list) {
// // 把系统租户倒进来
// List<Tenant> tenants = tenantService.getTenant();
// //过滤自己
// tenants = tenants.stream().filter(t-> !t.getTenantId().equals(LocalUser.getTenantId())).collect(Collectors.toList());
// for (Tenant tenant:tenants){
// SupplierVo vo = new SupplierVo();
// vo.setId(tenant.getId());
// SystemConfig systemConfig = systemConfigService.getSystemConfigByTenentId(tenant.getTenantId());
// vo.setSupplier(ObjectUtil.isEmpty(systemConfig)?"租户:"+tenant.getTenantId():systemConfig.getCompanyName());
// vo.setTargetType(true);
// list.add(vo);
// }
}
/**
* 查找往来单位,含供应商和客户信息-下拉框
* @param request
* @return
*/
@PostMapping(value = "/findBySelect_organ")
@ApiOperation(value = "查找往来单位,含供应商和客户信息")
public JSONArray findBySelectOrgan(HttpServletRequest request) throws Exception{
JSONArray arr = new JSONArray();
try {
JSONArray dataArray = new JSONArray();
//1、获取供应商信息
List<Supplier> supplierList = supplierService.findBySelectSup();
if (null != supplierList) {
for (Supplier supplier : supplierList) {
JSONObject item = new JSONObject();
item.put("id", supplier.getId());
item.put("supplier", supplier.getSupplier() + "[供应商]"); //供应商名称
dataArray.add(item);
}
}
//2、获取客户信息
String type = "UserCustomer";
Long userId = userService.getUserId(request);
List<Long> ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, userId);
List<Supplier> customerList = supplierService.findBySelectCus();
if (null != customerList) {
boolean customerFlag = systemConfigService.getCustomerFlag();
for (Supplier supplier : customerList) {
JSONObject item = new JSONObject();
Boolean flag = ubValue.contains(supplier.getId());
if (!customerFlag || flag) {
item.put("id", supplier.getId());
item.put("supplier", supplier.getSupplier() + "[客户]"); //客户名称
dataArray.add(item);
}
}
}
arr = dataArray;
} catch(Exception e){
e.printStackTrace();
}
return arr;
}
/**
* 查找会员信息-下拉框
* @param request
* @return
*/
@PostMapping(value = "/findBySelect_retail")
@ApiOperation(value = "查找会员信息")
public JSONArray findBySelectRetail(HttpServletRequest request)throws Exception {
JSONArray arr = new JSONArray();
try {
List<Supplier> supplierList = supplierService.findBySelectRetail();
JSONArray dataArray = new JSONArray();
if (null != supplierList) {
for (Supplier supplier : supplierList) {
JSONObject item = new JSONObject();
item.put("id", supplier.getId());
//客户名称
item.put("supplier", supplier.getSupplier());
item.put("advanceIn", supplier.getAdvanceIn()); //预付款金额
dataArray.add(item);
}
}
arr = dataArray;
} catch(Exception e){
e.printStackTrace();
}
return arr;
}
/**
* 批量设置状态-启用或者禁用
* @param jsonObject
* @param request
* @return
*/
@PostMapping(value = "/batchSetStatus")
@ApiOperation(value = "批量设置状态")
public String batchSetStatus(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
Boolean status = jsonObject.getBoolean("status");
String ids = jsonObject.getString("ids");
Map<String, Object> objectMap = new HashMap<>();
int res = supplierService.batchSetStatus(status, ids);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 用户对应客户显示
* @param type
* @param keyId
* @param request
* @return
*/
@GetMapping(value = "/findUserCustomer")
@ApiOperation(value = "用户对应客户显示")
public JSONArray findUserCustomer(@RequestParam("UBType") String type, @RequestParam("UBKeyId") Long keyId,
HttpServletRequest request) throws Exception{
JSONArray arr = new JSONArray();
try {
//获取权限信息
List<Long> ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, keyId);
List<Supplier> dataList = supplierService.findUserCustomer();
//开始拼接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());
if (flag) {
item.put("checked", true);
}
dataArray.add(item);
}
}
outer.put("children", dataArray);
arr.add(outer);
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
/**
* 导入供应商
* @param file
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importVendor")
@ApiOperation(value = "导入供应商")
public R importVendor(MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws Exception{
supplierService.importVendor(file, request);
return R.success();
}
/**
* 导入客户
* @param file
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importCustomer")
@ApiOperation(value = "导入客户")
public R importCustomer(MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws Exception{
supplierService.importCustomer(file, request);
return R.success();
}
/**
* 导入会员
* @param file
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importMember")
@ApiOperation(value = "导入会员")
public R importMember(MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws Exception{
supplierService.importMember(file, request);
return R.success();
}
/**
* 生成excel表格
* @param supplier
* @param type
* @param phonenum
* @param telephone
* @param request
* @param response
* @return
*/
@GetMapping(value = "/exportExcel")
public void exportExcel(@RequestParam(value = "supplier", required = false) String supplier,
@RequestParam("type") String type,
@RequestParam(value = "phonenum", required = false) String phonenum,
@RequestParam(value = "telephone", required = false) String telephone,
HttpServletRequest request, HttpServletResponse response) {
try {
List<Supplier> dataList = supplierService.findByAll(supplier, type, phonenum, telephone);
File file = supplierService.exportExcel(dataList, type);
ExportExecUtil.showExec(file, file.getName(), response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,239 @@
package com.zsw.erp.controller;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zsw.base.R;
import com.zsw.erp.config.QiniuConfigProperty;
import com.zsw.erp.datasource.entities.SystemConfig;
import com.zsw.erp.service.depot.DepotService;
import com.zsw.erp.service.systemConfig.SystemConfigService;
import com.zsw.erp.service.user.UserService;
import com.zsw.erp.service.userBusiness.UserBusinessService;
import com.zsw.erp.utils.StringUtil;
import com.zsw.erp.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
/**
* Description
* @Date: 2021-3-13 0:01
*/
@RestController
@RequestMapping(value = "/systemConfig")
@Api(tags = {"系统参数"})
@EnableConfigurationProperties(QiniuConfigProperty.class)
public class SystemConfigController {
private Logger logger = LoggerFactory.getLogger(SystemConfigController.class);
@Resource
QiniuConfigProperty qiniuConfigProperty;
@Resource
private UserService userService;
@Resource
private DepotService depotService;
@Resource
private UserBusinessService userBusinessService;
@Resource
private SystemConfigService systemConfigService;
@Value(value="${spring.servlet.multipart.max-file-size}")
private Long maxFileSize;
@Value(value="${spring.servlet.multipart.max-request-size}")
private Long maxRequestSize;
/**
* 获取当前租户的配置信息
* @param request
* @return
*/
@GetMapping(value = "/getCurrentInfo")
@ApiOperation(value = "获取当前租户的配置信息")
public R getCurrentInfo(HttpServletRequest request) throws Exception {
List<SystemConfig> list = systemConfigService.getSystemConfig();
if(list.size()>0) {
return R.success(list.get(0));
}else{
return R.fail("错误");
}
}
/**
* 获取文件大小限制
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/fileSizeLimit")
@ApiOperation(value = "获取文件大小限制")
public R fileSizeLimit(HttpServletRequest request) throws Exception {
Long limit = 0L;
if(maxFileSize<maxRequestSize) {
limit = maxFileSize;
} else {
limit = maxRequestSize;
}
return R.success(limit);
}
/**
* 文件上传统一方法
* @param request
* @param response
* @return
*/
@SneakyThrows
@PostMapping(value = "/upload")
@ApiOperation(value = "文件上传统一方法")
public R upload(HttpServletRequest request, HttpServletResponse response) {
String savePath = "";
String bizPath = request.getParameter("biz");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
if(StringUtil.isEmpty(bizPath)){
bizPath = "";
}
String token = request.getHeader("X-Access-Token");
Long tenantId = Tools.getTenantIdByToken(token);
bizPath = bizPath + File.separator + tenantId;
savePath = this.uploadLocal(file,bizPath);
if(StringUtil.isNotEmpty(savePath)){
return R.success(savePath);
}else {
return R.fail("上传失败");
}
}
/**
* 本地文件上传
* @param file 文件
* @param bizPath 自定义路径
* @return
*/
private String uploadLocal(MultipartFile file,String bizPath) throws IOException, NoSuchMethodException,
InvocationTargetException, IllegalAccessException {
Method f = Region.class.getDeclaredMethod(qiniuConfigProperty.getZone());
Region region = (Region) f.invoke(null);
Configuration cfg = new Configuration(region);
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(qiniuConfigProperty.getAccess(), qiniuConfigProperty.getSecret());
String upToken = auth.uploadToken(qiniuConfigProperty.getBucket());
String key = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN) + "/" +
UUID.fastUUID() + "." + FileUtil.getSuffix(file.getOriginalFilename());
Response response = uploadManager.put(file.getBytes(), key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
return qiniuConfigProperty.getPre() + putRet.key;
}
/**
* 预览图片&下载文件
* 请求地址:http://localhost:8080/common/static/{financial/afsdfasdfasdf_1547866868179.txt}
*
* @param request
* @param response
*/
@GetMapping(value = "/static/**")
@ApiOperation(value = "预览图片&下载文件")
public void view(HttpServletRequest request, HttpServletResponse response) {
// ISO-8859-1 ==> UTF-8 进行编码转换
String imgPath = extractPathFromPattern(request);
if(StringUtil.isEmpty(imgPath) || imgPath=="null"){
return;
}
// 其余处理略
InputStream inputStream = null;
OutputStream outputStream = null;
try {
imgPath = imgPath.replace("..", "");
if (imgPath.endsWith(",")) {
imgPath = imgPath.substring(0, imgPath.length() - 1);
}
String fileUrl = File.separator + imgPath;
File file = new File(fileUrl);
if(!file.exists()){
response.setStatus(404);
throw new RuntimeException("文件不存在..");
}
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
inputStream = new BufferedInputStream(new FileInputStream(fileUrl));
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
response.flushBuffer();
} catch (IOException e) {
logger.error("预览文件失败" + e.getMessage());
response.setStatus(404);
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
/**
* 把指定URL后的字符串全部截断当成参数
* 这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
* @param request
* @return
*/
private static String extractPathFromPattern(final HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
}
}
@@ -0,0 +1,57 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.service.tenant.TenantService;
import com.zsw.erp.utils.ErpInfo;
import com.zsw.erp.utils.ResponseCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
import static com.zsw.erp.utils.ResponseJsonUtil.success;
@RestController
@RequestMapping(value = "/tenant")
@Api(tags = {"租户管理"})
public class TenantController {
private Logger logger = LoggerFactory.getLogger(TenantController.class);
@Resource
private TenantService tenantService;
/**
* 批量设置状态-启用或者禁用
* @param jsonObject
* @param request
* @return
*/
@PostMapping(value = "/batchSetStatus")
@ApiOperation(value = "批量设置状态")
public String batchSetStatus(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
Boolean status = jsonObject.getBoolean("status");
String ids = jsonObject.getString("ids");
Map<String, Object> objectMap = new HashMap<>();
int res = tenantService.batchSetStatus(status, ids);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
@GetMapping("/listAllTenant")
@ApiOperation("列举全部租户")
public ResponseCode listAllTenant() throws Exception {
return success(tenantService.getTenant());
}
}
@@ -0,0 +1,35 @@
package com.zsw.erp.controller;
import com.zsw.base.R;
import com.zsw.jwt.model.TenantAuthInfo;
import com.zsw.pos.authority.dto.auth.LoginParamDTO;
import com.zsw.pos.oauth.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
@Validated
public class TestController {
@DubboReference
private LoginService loginService;
@GetMapping("/test/login")
public R test(@RequestParam String username, @RequestParam String password){
LoginParamDTO dto = new LoginParamDTO();
dto.setAccount(username);
dto.setPassword(password);
dto.setGrantType("password");
R<TenantAuthInfo> rs = loginService.grant(dto);
log.debug("login result : {}",rs.getData());
return rs;
}
}
@@ -0,0 +1,19 @@
package com.zsw.erp.controller;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description
*
* @Author: qiankunpingtai
* @Date: 2019/4/1 15:38
*/
@RestController
@RequestMapping(value = "/unit")
@Api(tags = {"单位管理"})
public class UnitController {
}
@@ -0,0 +1,104 @@
package com.zsw.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zsw.erp.datasource.dto.BtnStrDto;
import com.zsw.erp.datasource.entities.UserBusiness;
import com.zsw.erp.service.user.UserService;
import com.zsw.erp.service.userBusiness.UserBusinessService;
import com.zsw.base.R;
import com.zsw.erp.utils.ErpInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/userBusiness")
@Api(tags = {"用户角色模块的关系"})
public class UserBusinessController {
private Logger logger = LoggerFactory.getLogger(UserBusinessController.class);
@Resource
private UserBusinessService userBusinessService;
@Resource
private UserService userService;
/**
* 获取信息
* @param keyId
* @param type
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getBasicData")
@ApiOperation(value = "获取信息")
public R getBasicData(@RequestParam(value = "KeyId") Long keyId,
@RequestParam(value = "Type") String type,
HttpServletRequest request)throws Exception {
UserBusiness list = userBusinessService.getBasicData(keyId, type);
Map<String, List> mapData = new HashMap<String, List>();
mapData.put("userBusinessList", Lists.newArrayList(list));
return R.success(mapData);
}
/**
* 校验存在
* @param type
* @param keyId
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/checkIsValueExist")
@ApiOperation(value = "校验存在")
public String checkIsValueExist(@RequestParam(value ="type", required = false) String type,
@RequestParam(value ="keyId", required = false) String keyId,
HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>();
Long id = userBusinessService.checkIsValueExist(type, keyId);
if(id != null) {
objectMap.put("id", id);
} else {
objectMap.put("id", null);
}
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
}
/**
* 更新角色的按钮权限
* @param jsonObject
* @param request
* @return
*/
@PostMapping(value = "/updateBtnStr")
@ApiOperation(value = "更新角色的按钮权限")
public R updateBtnStr(@RequestBody BtnStrDto dto,
HttpServletRequest request)throws Exception {
String roleId = dto.getRoleId();
// JSONArray btnStrArray = jsonObject.getJSONArray("btnStr");
// List<BtnDto> btnStr = btnStrArray.toJavaList(BtnDto.class);
String keyId = roleId;
String type = "RoleFunctions";
int back = userBusinessService.updateBtnStr(keyId, type, dto.getBtnStr());
if(back > 0) {
return R.success("成功");
}else {
return R.fail("更新失败");
}
}
}
@@ -0,0 +1,483 @@
package com.zsw.erp.controller;
import cn.hutool.core.date.*;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsw.erp.constants.BusinessConstants;
import com.zsw.erp.constants.ExceptionConstants;
import com.zsw.erp.datasource.entities.BtnDto;
import com.zsw.erp.datasource.dto.UserLoginDto;
import com.zsw.erp.datasource.entities.Tenant;
import com.zsw.erp.datasource.entities.User;
import com.zsw.erp.datasource.entities.UserEx;
import com.zsw.erp.datasource.vo.TreeNodeEx;
import com.zsw.erp.exception.BusinessParamCheckingException;
import com.zsw.erp.service.inventorySeason.InventorySeasonService;
import com.zsw.erp.service.log.LogService;
import com.zsw.erp.service.redis.RedisService;
import com.zsw.erp.service.tenant.TenantService;
import com.zsw.erp.service.user.UserService;
import com.zsw.base.R;
import com.zsw.erp.utils.*;
import com.zsw.jwt.model.AuthInfo;
import com.zsw.jwt.model.TenantAuthInfo;
import com.zsw.pos.authority.dto.auth.LoginParamDTO;
import com.zsw.pos.oauth.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
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.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson;
@RestController
@RequestMapping(value = "/user")
@Api(tags = {"用户管理"})
public class UserController {
private Logger logger = LoggerFactory.getLogger(UserController.class);
@Value("${manage.roleId}")
private Integer manageRoleId;
@Value("${demonstrate.open}")
private boolean demonstrateOpen;
@Resource
private UserService userService;
@Resource
private TenantService tenantService;
@Resource
private LogService logService;
@Resource
private RedisService redisService;
@Resource
private InventorySeasonService inventorySeasonService;
@DubboReference
private LoginService loginService;
@Value("${tenant.userNumLimit}")
private Integer systemLimit;
private static final String TEST_USER = "jsh";
private static String SUCCESS = "操作成功";
private static String ERROR = "操作失败";
private static final String HTTP = "http://";
private static final String CODE_OK = "200";
private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";
@PostMapping(value = "/login")
@ApiOperation(value = "登录")
public R login(@RequestBody User userParam,
HttpServletRequest request)throws Exception {
logger.info("============用户登录 login 方法调用开始==============");
String msgTip = "";
User user=null;
String loginName = userParam.getLoginName().trim();
String password = userParam.getPassword().trim();
String posTenantCode = null;
JWTPayload payload = new JWTPayload();
// 登录zsw-admin
LoginParamDTO dto = new LoginParamDTO();
dto.setAccount(loginName);
dto.setPassword(password);
R<TenantAuthInfo> result = loginService.grant(dto);
logger.error("result:{}",result);
if (result.getIsSuccess()){
// 检查系统里是否存在租户和账户 没有准备走注册流程
posTenantCode = result.getData().getTenantCode();
// 在这里带了太多的门店ID
payload.setPayload("loginName",loginName);
payload.setPayload("tenantId",posTenantCode);
}
//获取用户状态
//int userStatus = -1;
redisService.deleteObjectBySession(request,"userId");
UserLoginDto loginDto = userService.validateUser(loginName, password);
switch (loginDto.getUserStatus()) {
case ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST:
msgTip = "user is not exist";
if (posTenantCode != null){
// 用户不存在 但是用户不存在 可能报错。
UserEx ex = new UserEx();
ex.setLoginName(loginName);
ex.setPassword(password);
ex.setTenantId(Long.parseLong(posTenantCode));
LocalDateTime time = LocalDateTimeUtil.offset(LocalDateTime.now(), 10, ChronoUnit.YEARS);
DateTimeFormatter formater = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
String t = time.format(formater);
ex.setExpireTime(t);
user = this.registerUser(ex,request);
payload.setPayload("userId",user.getId());
payload.setPayload("loginName",loginName);
payload.setPayload("tenantId",posTenantCode);
msgTip = "user can login";
}
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";
user = loginDto.getUser();
payload.setPayload("userId",user.getId());
payload.setPayload("loginName",loginName);
payload.setPayload("tenantId",user.getTenantId());
break;
default:
break;
}
// 1个月过期
DateTime exAt = DateUtil.offset(new Date(), DateField.MONTH, 1);
payload.setExpiresAt(exAt);
String token = JWTUtil.createToken(payload.getClaimsJson(), "88888888".getBytes(StandardCharsets.UTF_8));
Map<String, Object> data = new HashMap<String, Object>();
data.put("msgTip", msgTip);
if(user!=null){
redisService.storageObjectBySession(token,"userId",user.getId());
String roleType = userService.getRoleTypeByUserId(user.getId()); //角色类型
if (roleType == null){
logger.error("角色错误!");
}
redisService.storageObjectBySession(token,"roleType",roleType);
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());
List<BtnDto> btnStrArr = userService.getBtnStrArrById(user.getId());
data.put("token", token);
data.put("user", user);
LocalUser.setTenantId(user.getTenantId());
LocalUser.setUserId(user.getId());
data.put("season",inventorySeasonService.getNow());
//用户的按钮权限
if(!"admin".equals(user.getLoginName())){
data.put("userBtn", btnStrArr);
}
data.put("roleType", roleType);
logger.info("===============用户登录 login 方法调用结束===============");
return R.success(data);
}else{
return R.fail("用户名或者密码错误");
}
}
@GetMapping(value = "/getUserSession")
@ApiOperation(value = "获取用户信息")
public R getSessionUser(HttpServletRequest request)throws Exception {
Map<String, Object> data = new HashMap<>();
Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request,"userId").toString());
User user = userService.getUser(userId);
user.setPassword(null);
data.put("user", user);
return R.success(data);
}
@GetMapping(value = "/logout")
@ApiOperation(value = "退出")
public R logout(HttpServletRequest request, HttpServletResponse response)throws Exception {
redisService.deleteObjectBySession(request,"userId");
return R.success();
}
@PostMapping(value = "/resetPwd")
@ApiOperation(value = "重置密码")
public String resetPwd(@RequestBody JSONObject jsonObject,
HttpServletRequest request) throws Exception {
Map<String, Object> objectMap = new HashMap<>();
Long id = jsonObject.getLong("id");
String password = "123456";
String md5Pwd = Tools.md5Encryp(password);
int update = userService.resetPwd(md5Pwd, id);
if(update > 0) {
return returnJson(objectMap, SUCCESS, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
}
}
@PutMapping(value = "/updatePwd")
@ApiOperation(value = "更新密码")
public String updatePwd(@RequestBody JSONObject jsonObject, HttpServletRequest request)throws Exception {
Integer flag = 0;
Map<String, Object> objectMap = new HashMap<String, Object>();
try {
String info = "";
Long userId = jsonObject.getLong("userId");
String oldpwd = jsonObject.getString("oldpassword");
String password = jsonObject.getString("password");
User user = userService.getUser(userId);
//必须和原始密码一致才可以更新密码
if(demonstrateOpen && user.getLoginName().equals(TEST_USER)){
flag = 3; //jsh用户不能修改密码
info = "jsh用户不能修改密码";
} else if (oldpwd.equalsIgnoreCase(user.getPassword())) {
user.setPassword(password);
flag = userService.updateUserByObj(user); //1-成功
info = "修改成功";
} else {
flag = 2; //原始密码输入错误
info = "原始密码输入错误";
}
objectMap.put("status", flag);
if(flag > 0) {
return returnJson(objectMap, info, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
}
} catch (Exception e) {
logger.error(">>>>>>>>>>>>>修改用户ID为 " + jsonObject.getLong("userId") + "密码信息失败", e);
flag = 3;
objectMap.put("status", flag);
return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
}
}
/**
* 获取全部用户数据列表
* @param request
* @return
*/
@GetMapping(value = "/getAllList")
@ApiOperation(value = "获取全部用户数据列表")
public R getAllList(HttpServletRequest request)throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
List<User> dataList = userService.getUser();
if(dataList!=null) {
data.put("userList", dataList);
}
return R.success(data);
}
/**
* 用户列表,用于用户下拉框
* @param request
* @return
* @throws Exception
*/
@GetMapping(value = "/getUserList")
@ApiOperation(value = "用户列表")
public JSONArray getUserList(HttpServletRequest request)throws Exception {
JSONArray dataArray = new JSONArray();
try {
List<User> dataList = userService.getUser();
if (null != dataList) {
for (User user : dataList) {
JSONObject item = new JSONObject();
item.put("id", user.getId());
item.put("userName", user.getUsername());
dataArray.add(item);
}
}
} catch(Exception e){
e.printStackTrace();
}
return dataArray;
}
/**
* create by: cjl
* description:
* 新增用户及机构和用户关系
* create time: 2019/3/8 16:06
* @Param: beanJson
* @return java.lang.Object
*/
@PostMapping("/addUser")
@ApiOperation(value = "新增用户")
@ResponseBody
public Object addUser(@RequestBody JSONObject obj, HttpServletRequest request)throws Exception{
JSONObject result = ExceptionConstants.standardSuccess();
// 系统的人数限制
Object limit = redisService.getObjectFromSessionByKey(request, "userNumLimit");
Long userNumLimit = ObjectUtil.isNotEmpty(limit)
? Long.parseLong(limit.toString())
: systemLimit;
Long count = userService.countUser(null,null);
if(count>= userNumLimit) {
throw new BusinessParamCheckingException(ExceptionConstants.USER_OVER_LIMIT_FAILED_CODE,
ExceptionConstants.USER_OVER_LIMIT_FAILED_MSG);
} else {
UserEx ue= JSONObject.parseObject(obj.toJSONString(), UserEx.class);
userService.addUserAndOrgUserRel(ue, request);
}
return result;
}
/**
* create by: cjl
* description:
* 修改用户及机构和用户关系
* create time: 2019/3/8 16:06
* @Param: beanJson
* @return java.lang.Object
*/
@PutMapping("/updateUser")
@ApiOperation(value = "修改用户")
@ResponseBody
public Object updateUser(@RequestBody JSONObject obj, HttpServletRequest request)throws Exception{
JSONObject result = ExceptionConstants.standardSuccess();
UserEx ue= JSONObject.parseObject(obj.toJSONString(), UserEx.class);
userService.updateUserAndOrgUserRel(ue, request);
return result;
}
/**
* 注册用户
* @param ue
* @return
* @throws Exception
*/
@PostMapping(value = "/registerUser")
@ApiOperation(value = "注册用户")
public UserEx registerUser(@RequestBody UserEx ue,
HttpServletRequest request)throws Exception{
logger.error("用户注册开始...");
JSONObject result = ExceptionConstants.standardSuccess();
ue.setUsername(ue.getLoginName());
userService.checkUserNameAndLoginName(ue); //检查用户名和登录名
ue = userService.registerUser(ue,manageRoleId,request);
return ue;
}
/**
* 获取机构用户树
* @return
* @throws Exception
*/
@RequestMapping("/getOrganizationUserTree")
@ApiOperation(value = "获取机构用户树")
public JSONArray getOrganizationUserTree()throws Exception{
JSONArray arr=new JSONArray();
List<TreeNodeEx> organizationUserTree= userService.getOrganizationUserTree();
if(organizationUserTree!=null&&organizationUserTree.size()>0){
for(TreeNodeEx node:organizationUserTree){
String str=JSON.toJSONString(node);
JSONObject obj=JSON.parseObject(str);
arr.add(obj) ;
}
}
return arr;
}
/**
* 获取当前用户的角色类型
* @param request
* @return
*/
@GetMapping("/getRoleTypeByCurrentUser")
@ApiOperation(value = "获取当前用户的角色类型")
public R getRoleTypeByCurrentUser(HttpServletRequest request) {
Map<String, Object> data = new HashMap<String, Object>();
String roleType = redisService.getObjectFromSessionByKey(request,"roleType").toString();
data.put("roleType", roleType);
return R.success(data);
}
/**
* 获取随机校验码
* @param response
* @param key
* @return
*/
@GetMapping(value = "/randomImage/{key}")
@ApiOperation(value = "获取随机校验码")
public R randomImage(HttpServletResponse response,@PathVariable String key) throws IOException {
Map<String, Object> data = new HashMap<>();
String codeNum = Tools.getCharAndNum(4);
String base64 = RandImageUtil.generate(codeNum);
data.put("codeNum", codeNum);
data.put("base64", base64);
return R.success(data);
}
/**
* 批量设置状态-启用或者禁用
* @param jsonObject
* @param request
* @return
*/
@PostMapping(value = "/batchSetStatus")
@ApiOperation(value = "批量设置状态")
public String batchSetStatus(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
Byte status = jsonObject.getByte("status");
String ids = jsonObject.getString("ids");
Map<String, Object> objectMap = new HashMap<>();
int res = userService.batchSetStatus(status, ids);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
/**
* 获取当前用户的用户数量和租户信息
* @param request
* @return
*/
@GetMapping(value = "/infoWithTenant")
@ApiOperation(value = "获取当前用户的用户数量和租户信息")
public R randomImage(HttpServletRequest request){
Map<String, Object> data = new HashMap<>();
Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request,"userId").toString());
User user = userService.getUser(userId);
//获取当前用户数
Long userCurrentNum = userService.countUser(null, null);
Tenant tenant = tenantService.getTenantByTenantId(user.getTenantId());
data.put("type", tenant.getType()); //租户类型,0免费租户,1付费租户
data.put("expireTime", Tools.parseDateToStr(tenant.getExpireTime()));
data.put("userCurrentNum", userCurrentNum);
data.put("userNumLimit", tenant.getUserNumLimit());
return R.success(data);
}
}