DepotHeadServiceImpl.java 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  1. package com.jsh.erp.service.impl;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  5. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  6. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  7. import com.fasterxml.jackson.core.JsonProcessingException;
  8. import com.fasterxml.jackson.databind.ObjectMapper;
  9. import com.jsh.erp.constants.BusinessConstants;
  10. import com.jsh.erp.constants.ExceptionConstants;
  11. import com.jsh.erp.datasource.entities.*;
  12. import com.jsh.erp.datasource.mappers.DepotHeadMapper;
  13. import com.jsh.erp.datasource.mappers.DepotHeadMapperEx;
  14. import com.jsh.erp.datasource.mappers.DepotItemMapperEx;
  15. import com.jsh.erp.datasource.mappers.MaterialCurrentStockMapper;
  16. import com.jsh.erp.datasource.mappers.MaterialCurrentStockMapperEx;
  17. import com.jsh.erp.datasource.pda.dto.PDADepotHeadDTO;
  18. import com.jsh.erp.datasource.pda.dto.PDADepotMaterialDto;
  19. import com.jsh.erp.datasource.pda.vo.PDADepotHeadVO;
  20. import com.jsh.erp.datasource.vo.*;
  21. import com.jsh.erp.exception.BusinessRunTimeException;
  22. import com.jsh.erp.exception.JshException;
  23. import com.jsh.erp.query.LambdaQueryWrapperX;
  24. import com.jsh.erp.query.QueryWrapperX;
  25. import com.jsh.erp.service.*;
  26. import com.jsh.erp.util.QRCodeGenerator;
  27. import com.jsh.erp.utils.ExcelUtils;
  28. import com.jsh.erp.utils.HttpClient;
  29. import com.jsh.erp.utils.PageUtils;
  30. import com.jsh.erp.utils.StringUtil;
  31. import com.jsh.erp.utils.Tools;
  32. import jxl.Workbook;
  33. import jxl.write.WritableWorkbook;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import org.springframework.stereotype.Service;
  37. import org.springframework.transaction.annotation.Transactional;
  38. import org.springframework.web.context.request.RequestContextHolder;
  39. import org.springframework.web.context.request.ServletRequestAttributes;
  40. import javax.annotation.Resource;
  41. import javax.servlet.http.HttpServletRequest;
  42. import javax.servlet.http.HttpServletResponse;
  43. import java.io.File;
  44. import java.math.BigDecimal;
  45. import java.sql.Timestamp;
  46. import java.util.*;
  47. import java.util.stream.Collectors;
  48. import static com.jsh.erp.utils.Tools.getCenternTime;
  49. import static com.jsh.erp.utils.Tools.getNow3;
  50. @Service
  51. public class DepotHeadServiceImpl extends ServiceImpl<DepotHeadMapper, DepotHead> implements DepotHeadService {
  52. private Logger logger = LoggerFactory.getLogger(DepotHeadServiceImpl.class);
  53. @Resource
  54. private DepotHeadMapper depotHeadMapper;
  55. @Resource
  56. private DepotHeadMapperEx depotHeadMapperEx;
  57. @Resource
  58. private UserService userService;
  59. @Resource
  60. private RoleService roleService;
  61. @Resource
  62. private DepotService depotService;
  63. @Resource
  64. DepotItemService depotItemService;
  65. @Resource
  66. private SupplierService supplierService;
  67. @Resource
  68. private UserBusinessService userBusinessService;
  69. @Resource
  70. private SystemConfigService systemConfigService;
  71. @Resource
  72. private SerialNumberService serialNumberService;
  73. @Resource
  74. private OrgaUserRelService orgaUserRelService;
  75. @Resource
  76. private PersonService personService;
  77. @Resource
  78. private AccountService accountService;
  79. @Resource
  80. private AccountHeadService accountHeadService;
  81. @Resource
  82. private AccountItemService accountItemService;
  83. @Resource
  84. private SequenceService sequenceService;
  85. @Resource
  86. DepotItemMapperEx depotItemMapperEx;
  87. @Resource
  88. private LogService logService;
  89. @Resource
  90. private QRCodeGenerator qrCodeGenerator;
  91. @Resource
  92. private MaterialService materialService;
  93. @Resource
  94. private MaterialExtendService materialExtendService;
  95. @Resource
  96. private SyncTescoSystemService syncTescoSystemService;
  97. /**
  98. * PDA查询订单
  99. * @param pdaDepotHeadDTO 筛选条件
  100. * @return
  101. */
  102. @Override
  103. public List<PDADepotHeadVO> pdaList(PDADepotHeadDTO pdaDepotHeadDTO) {
  104. return depotHeadMapper.pdaList(pdaDepotHeadDTO);
  105. }
  106. @Override
  107. public PDADepotHeadVO pdaDetail(Long id) {
  108. return depotHeadMapper.pdaDetail(id);
  109. }
  110. @Override
  111. public DepotHead getDepotHead(long id)throws Exception {
  112. DepotHead result=null;
  113. try{
  114. result=depotHeadMapper.selectByPrimaryKey(id);
  115. }catch(Exception e){
  116. JshException.readFail(logger, e);
  117. }
  118. return result;
  119. }
  120. @Override
  121. public List<DepotHead> getDepotHead()throws Exception {
  122. DepotHeadExample example = new DepotHeadExample();
  123. example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  124. List<DepotHead> list=null;
  125. try{
  126. list=depotHeadMapper.selectByExample(example);
  127. }catch(Exception e){
  128. JshException.readFail(logger, e);
  129. }
  130. return list;
  131. }
  132. @Override
  133. public List<DepotHeadVo4List> select(String type, String subType, String hasDebt, String status, String purchaseStatus, String number, String linkApply, String linkNumber,
  134. String beginTime, String endTime, String materialParam, Long organId, Long creator, Long depotId, Long accountId, String remark) throws Exception {
  135. List<DepotHeadVo4List> list = new ArrayList<>();
  136. try{
  137. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  138. Long userId = userService.getUserId(request);
  139. Role role = userService.getRoleTypeByUserId(userId);
  140. String priceLimit = role.getPriceLimit();
  141. String billCategory = getBillCategory(subType);
  142. String [] depotArray = getDepotArray(subType);
  143. String [] creatorArray = getCreatorArray();
  144. String [] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
  145. String [] purchaseStatusArray = StringUtil.isNotEmpty(purchaseStatus) ? purchaseStatus.split(",") : null;
  146. String [] organArray = getOrganArray(subType, purchaseStatus);
  147. if ("采购订单".equals(subType) && "供应商".equals(role.getName())) {
  148. organArray = getOrganArrayByCurrentUser(userId);
  149. }
  150. //以销定购,查看全部数据
  151. creatorArray = StringUtil.isNotEmpty(purchaseStatus) ? null: creatorArray;
  152. Map<Long,String> personMap = personService.getPersonMap();
  153. Map<Long,String> accountMap = accountService.getAccountMap();
  154. beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
  155. endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
  156. PageUtils.startPage();
  157. list = depotHeadMapperEx.selectByConditionDepotHead(type, subType, creatorArray, hasDebt,
  158. statusArray, purchaseStatusArray, number, linkApply, linkNumber, beginTime, endTime,
  159. materialParam, organId, organArray, creator, depotId, depotArray, accountId, remark);
  160. if (null != list) {
  161. List<Long> idList = new ArrayList<>();
  162. List<String> numberList = new ArrayList<>();
  163. for (DepotHeadVo4List dh : list) {
  164. idList.add(dh.getId());
  165. numberList.add(dh.getNumber());
  166. }
  167. //通过批量查询去构造map
  168. Map<String,BigDecimal> finishDepositMap = getFinishDepositMapByNumberList(numberList);
  169. Map<Long,Integer> financialBillNoMap = getFinancialBillNoMapByBillIdList(idList);
  170. Map<String,Integer> billSizeMap = getBillSizeMapByLinkNumberList(numberList);
  171. Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
  172. Map<Long,BigDecimal> materialCountListMap = getMaterialCountListMapByHeaderIdList(idList);
  173. for (DepotHeadVo4List dh : list) {
  174. if(accountMap!=null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
  175. String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
  176. dh.setAccountName(accountStr);
  177. }
  178. if(dh.getAccountIdList() != null) {
  179. String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
  180. dh.setAccountIdList(accountidlistStr);
  181. }
  182. if(dh.getAccountMoneyList() != null) {
  183. String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
  184. dh.setAccountMoneyList(accountmoneylistStr);
  185. }
  186. if(dh.getChangeAmount() != null) {
  187. dh.setChangeAmount(roleService.parseBillPriceByLimit(dh.getChangeAmount().abs(), billCategory, priceLimit, request));
  188. } else {
  189. dh.setChangeAmount(BigDecimal.ZERO);
  190. }
  191. if(dh.getTotalPrice() != null) {
  192. BigDecimal lastTotalPrice = BusinessConstants.SUB_TYPE_CHECK_ENTER.equals(dh.getSubType())||
  193. BusinessConstants.SUB_TYPE_REPLAY.equals(dh.getSubType())?dh.getTotalPrice():dh.getTotalPrice().abs();
  194. dh.setTotalPrice(roleService.parseBillPriceByLimit(lastTotalPrice, billCategory, priceLimit, request));
  195. }
  196. BigDecimal discountLastMoney = dh.getDiscountLastMoney()!=null?dh.getDiscountLastMoney():BigDecimal.ZERO;
  197. dh.setDiscountLastMoney(roleService.parseBillPriceByLimit(discountLastMoney, billCategory, priceLimit, request));
  198. BigDecimal backAmount = dh.getBackAmount()!=null?dh.getBackAmount():BigDecimal.ZERO;
  199. dh.setBackAmount(roleService.parseBillPriceByLimit(backAmount, billCategory, priceLimit, request));
  200. if(dh.getDeposit() == null) {
  201. dh.setDeposit(BigDecimal.ZERO);
  202. } else {
  203. dh.setDeposit(roleService.parseBillPriceByLimit(dh.getDeposit(), billCategory, priceLimit, request));
  204. }
  205. //已经完成的欠款
  206. if(finishDepositMap!=null) {
  207. BigDecimal finishDeposit = finishDepositMap.get(dh.getNumber()) != null ? finishDepositMap.get(dh.getNumber()) : BigDecimal.ZERO;
  208. dh.setFinishDeposit(roleService.parseBillPriceByLimit(finishDeposit, billCategory, priceLimit, request));
  209. }
  210. //欠款计算
  211. BigDecimal otherMoney = dh.getOtherMoney()!=null?dh.getOtherMoney():BigDecimal.ZERO;
  212. BigDecimal deposit = dh.getDeposit()!=null?dh.getDeposit():BigDecimal.ZERO;
  213. BigDecimal changeAmount = dh.getChangeAmount()!=null?dh.getChangeAmount():BigDecimal.ZERO;
  214. BigDecimal debt = discountLastMoney.add(otherMoney).subtract((deposit.add(changeAmount)));
  215. dh.setDebt(roleService.parseBillPriceByLimit(debt, billCategory, priceLimit, request));
  216. //是否有付款单或收款单
  217. if(financialBillNoMap!=null) {
  218. Integer financialBillNoSize = financialBillNoMap.get(dh.getId());
  219. dh.setHasFinancialFlag(financialBillNoSize!=null && financialBillNoSize>0);
  220. }
  221. //是否有退款单
  222. if(billSizeMap!=null) {
  223. Integer billListSize = billSizeMap.get(dh.getNumber());
  224. dh.setHasBackFlag(billListSize!=null && billListSize>0);
  225. }
  226. if(StringUtil.isNotEmpty(dh.getSalesMan())) {
  227. dh.setSalesManStr(personService.getPersonByMapAndIds(personMap,dh.getSalesMan()));
  228. }
  229. if(dh.getOperTime() != null) {
  230. dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
  231. }
  232. //商品信息简述
  233. if(materialsListMap!=null) {
  234. dh.setMaterialsList(materialsListMap.get(dh.getId()));
  235. }
  236. //商品总数量
  237. if(materialCountListMap!=null) {
  238. dh.setMaterialCount(materialCountListMap.get(dh.getId()));
  239. }
  240. //以销定购的情况(不能显示销售单据的金额和客户名称)
  241. if(StringUtil.isNotEmpty(purchaseStatus)) {
  242. dh.setOrganName("****");
  243. dh.setTotalPrice(null);
  244. dh.setDiscountLastMoney(null);
  245. }
  246. }
  247. }
  248. } catch(Exception e){
  249. JshException.readFail(logger, e);
  250. }
  251. return list;
  252. }
  253. /**
  254. * 根据单据类型获取仓库数组
  255. * @param subType
  256. * @return
  257. * @throws Exception
  258. */
  259. @Override
  260. public String[] getDepotArray(String subType) throws Exception {
  261. String [] depotArray = null;
  262. if(!BusinessConstants.SUB_TYPE_PURCHASE_APPLY.equals(subType)
  263. && !BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(subType)
  264. && !BusinessConstants.SUB_TYPE_SALES_ORDER.equals(subType)) {
  265. String depotIds = depotService.findDepotStrByCurrentUser();
  266. depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
  267. }
  268. return depotArray;
  269. }
  270. /**
  271. * 根据角色类型获取操作员数组
  272. * @return
  273. * @throws Exception
  274. */
  275. @Override
  276. public String[] getCreatorArray() throws Exception {
  277. String creator = getCreatorByCurrentUser();
  278. String [] creatorArray=null;
  279. if(StringUtil.isNotEmpty(creator)){
  280. creatorArray = creator.split(",");
  281. }
  282. return creatorArray;
  283. }
  284. /**
  285. * 根据角色类型获取操作员数组
  286. * @param organizationId
  287. * @return
  288. * @throws Exception
  289. */
  290. @Override
  291. public String[] getCreatorArrayByOrg(Long organizationId) throws Exception {
  292. List<Long> userIdList = orgaUserRelService.getUserIdListByOrgId(organizationId);
  293. if(userIdList.size()>0) {
  294. List<String> userIdStrList = userIdList.stream().map(Object::toString).collect(Collectors.toList());
  295. return StringUtil.listToStringArray(userIdStrList);
  296. } else {
  297. return "-1".split(",");
  298. }
  299. }
  300. /**
  301. * 获取机构数组
  302. * @return
  303. */
  304. @Override
  305. public String[] getOrganArray(String subType, String purchaseStatus) throws Exception {
  306. String [] organArray = null;
  307. String type = "UserCustomer";
  308. Long userId = userService.getCurrentUser().getId();
  309. //获取权限信息
  310. String ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, userId.toString());
  311. List<Supplier> supplierList = supplierService.findBySelectCus();
  312. if(BusinessConstants.SUB_TYPE_SALES_ORDER.equals(subType) || BusinessConstants.SUB_TYPE_SALES.equals(subType)
  313. ||BusinessConstants.SUB_TYPE_SALES_RETURN.equals(subType) ) {
  314. //采购订单里面选择销售订单的时候不要过滤
  315. if(StringUtil.isEmpty(purchaseStatus)) {
  316. if (null != supplierList && supplierList.size() > 0) {
  317. boolean customerFlag = systemConfigService.getCustomerFlag();
  318. List<String> organList = new ArrayList<>();
  319. for (Supplier supplier : supplierList) {
  320. boolean flag = ubValue.contains("[" + supplier.getId().toString() + "]");
  321. if (!customerFlag || flag) {
  322. organList.add(supplier.getId().toString());
  323. }
  324. }
  325. if(organList.size() > 0) {
  326. organArray = StringUtil.listToStringArray(organList);
  327. }
  328. }
  329. }
  330. }
  331. return organArray;
  332. }
  333. public String [] getOrganArrayByCurrentUser(Long userId) throws Exception {
  334. String[] organArray = userBusinessService.getUBValuByTypeAndKeyIdToArray("UserSupplier", userId.toString());
  335. return organArray;
  336. }
  337. /**
  338. * 根据角色类型获取操作员
  339. * @return
  340. * @throws Exception
  341. */
  342. @Override
  343. public String getCreatorByCurrentUser() throws Exception {
  344. String creator = "";
  345. User user = userService.getCurrentUser();
  346. String roleType = userService.getRoleTypeByUserId(user.getId()).getType(); //角色类型
  347. if(BusinessConstants.ROLE_TYPE_PRIVATE.equals(roleType)) {
  348. creator = user.getId().toString();
  349. } else if(BusinessConstants.ROLE_TYPE_THIS_ORG.equals(roleType)) {
  350. creator = orgaUserRelService.getUserIdListByUserId(user.getId());
  351. }
  352. return creator;
  353. }
  354. @Override
  355. public Map<String, BigDecimal> getFinishDepositMapByNumberList(List<String> numberList) {
  356. Map<String,BigDecimal> finishDepositMap = new HashMap<>();
  357. if(numberList.size()>0) {
  358. List<FinishDepositVo> list = depotHeadMapperEx.getFinishDepositByNumberList(numberList);
  359. if(list!=null && list.size()>0) {
  360. for (FinishDepositVo finishDepositVo : list) {
  361. if(finishDepositVo!=null) {
  362. finishDepositMap.put(finishDepositVo.getNumber(), finishDepositVo.getFinishDeposit());
  363. }
  364. }
  365. }
  366. }
  367. return finishDepositMap;
  368. }
  369. @Override
  370. public Map<String, Integer> getBillSizeMapByLinkNumberList(List<String> numberList) throws Exception {
  371. Map<String, Integer> billListMap = new HashMap<>();
  372. if(numberList.size()>0) {
  373. List<DepotHead> list = getBillListByLinkNumberList(numberList);
  374. if(list!=null && list.size()>0) {
  375. for (DepotHead depotHead : list) {
  376. if(depotHead!=null) {
  377. billListMap.put(depotHead.getLinkNumber(), list.size());
  378. }
  379. }
  380. }
  381. }
  382. return billListMap;
  383. }
  384. @Override
  385. public Map<Long,Integer> getFinancialBillNoMapByBillIdList(List<Long> idList) {
  386. Map<Long, Integer> billListMap = new HashMap<>();
  387. if(idList.size()>0) {
  388. List<AccountItem> list = accountHeadService.getFinancialBillNoByBillIdList(idList);
  389. if(list!=null && list.size()>0) {
  390. for (AccountItem accountItem : list) {
  391. if(accountItem!=null) {
  392. billListMap.put(accountItem.getBillId(), list.size());
  393. }
  394. }
  395. }
  396. }
  397. return billListMap;
  398. }
  399. @Override
  400. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  401. public int insertDepotHead(JSONObject obj, HttpServletRequest request)throws Exception {
  402. DepotHead depotHead = JSONObject.parseObject(obj.toJSONString(), DepotHead.class);
  403. depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
  404. depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
  405. User user = userService.getCurrentUser();
  406. depotHead.setTenantId(user.getId());
  407. int result=0;
  408. try{
  409. result=depotHeadMapper.insert(depotHead);
  410. logService.insertLog("单据", BusinessConstants.LOG_OPERATION_TYPE_ADD, request);
  411. }catch(Exception e){
  412. JshException.writeFail(logger, e);
  413. }
  414. return result;
  415. }
  416. @Override
  417. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  418. public int updateDepotHead(JSONObject obj, HttpServletRequest request) throws Exception{
  419. DepotHead depotHead = JSONObject.parseObject(obj.toJSONString(), DepotHead.class);
  420. DepotHead dh=null;
  421. try{
  422. dh = depotHeadMapper.selectByPrimaryKey(depotHead.getId());
  423. }catch(Exception e){
  424. JshException.readFail(logger, e);
  425. }
  426. depotHead.setStatus(dh.getStatus());
  427. depotHead.setCreateTime(dh.getCreateTime());
  428. int result=0;
  429. try{
  430. result = depotHeadMapper.updateByPrimaryKey(depotHead);
  431. logService.insertLog("单据",
  432. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(depotHead.getId()).toString(), request);
  433. }catch(Exception e){
  434. JshException.writeFail(logger, e);
  435. }
  436. return result;
  437. }
  438. @Override
  439. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  440. public int deleteDepotHead(Long id, HttpServletRequest request)throws Exception {
  441. return batchDeleteBillByIds(id.toString());
  442. }
  443. @Override
  444. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  445. public int batchDeleteDepotHead(String ids, HttpServletRequest request)throws Exception {
  446. return batchDeleteBillByIds(ids);
  447. }
  448. @Override
  449. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  450. public int batchDeleteBillByIds(String ids)throws Exception {
  451. StringBuffer sb = new StringBuffer();
  452. sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
  453. List<DepotHead> dhList = getDepotHeadListByIds(ids);
  454. for(DepotHead depotHead: dhList){
  455. //只有未审核的单据才能被删除
  456. if(!"0".equals(depotHead.getStatus())) {
  457. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_DELETE_FAILED_CODE,
  458. String.format(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_DELETE_FAILED_MSG));
  459. }
  460. }
  461. for(DepotHead depotHead: dhList){
  462. sb.append("[").append(depotHead.getNumber()).append("]");
  463. User userInfo = userService.getCurrentUser();
  464. //删除入库单据,先校验序列号是否出库,如果未出库则同时删除序列号,如果已出库则不能删除单据
  465. if (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType())) {
  466. List<DepotItem> depotItemList = depotItemMapperEx.findDepotItemListBydepotheadId(depotHead.getId(), BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED);
  467. if (depotItemList != null && depotItemList.size() > 0) {
  468. //单据明细里面存在序列号商品
  469. int serialNumberSellCount = depotHeadMapperEx.getSerialNumberBySell(depotHead.getNumber());
  470. if (serialNumberSellCount > 0) {
  471. //已出库则不能删除单据
  472. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_SERIAL_IS_SELL_CODE,
  473. String.format(ExceptionConstants.DEPOT_HEAD_SERIAL_IS_SELL_MSG, depotHead.getNumber()));
  474. } else {
  475. //删除序列号
  476. SerialNumberExample example = new SerialNumberExample();
  477. example.createCriteria().andInBillNoEqualTo(depotHead.getNumber());
  478. serialNumberService.deleteByExample(example);
  479. }
  480. }
  481. }
  482. //删除出库数据回收序列号
  483. if (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
  484. && !BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())) {
  485. //查询单据子表列表
  486. List<DepotItem> depotItemList = depotItemMapperEx.findDepotItemListBydepotheadId(depotHead.getId(), BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED);
  487. /**回收序列号*/
  488. if (depotItemList != null && depotItemList.size() > 0) {
  489. for (DepotItem depotItem : depotItemList) {
  490. //BasicNumber=OperNumber*ratio
  491. serialNumberService.cancelSerialNumber(depotItem.getMaterialId(), depotHead.getNumber(), (depotItem.getBasicNumber() == null ? 0 : depotItem.getBasicNumber()).intValue(), userInfo);
  492. }
  493. }
  494. }
  495. List<DepotItem> list = depotItemService.getListByHeaderId(depotHead.getId());
  496. //删除单据子表数据
  497. depotItemMapperEx.batchDeleteDepotItemByDepotHeadIds(new Long[]{depotHead.getId()});
  498. //删除单据主表信息
  499. batchDeleteDepotHeadByIds(depotHead.getId().toString());
  500. //将关联的单据置为审核状态-针对采购入库、销售出库、盘点复盘、其它入库、其它出库
  501. if(StringUtil.isNotEmpty(depotHead.getLinkNumber())){
  502. if((BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
  503. BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType()))
  504. || (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) &&
  505. BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType()))
  506. || (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
  507. BusinessConstants.SUB_TYPE_REPLAY.equals(depotHead.getSubType()))
  508. || (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
  509. BusinessConstants.SUB_TYPE_OTHER.equals(depotHead.getSubType()))
  510. || (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) &&
  511. BusinessConstants.SUB_TYPE_OTHER.equals(depotHead.getSubType()))) {
  512. String status = BusinessConstants.BILLS_STATUS_AUDIT;
  513. //查询除当前单据之外的关联单据列表
  514. List<DepotHead> exceptCurrentList = getListByLinkNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber(), depotHead.getType());
  515. if(exceptCurrentList!=null && exceptCurrentList.size()>0) {
  516. status = BusinessConstants.BILLS_STATUS_SKIPING;
  517. }
  518. DepotHead dh = new DepotHead();
  519. dh.setStatus(status);
  520. DepotHeadExample example = new DepotHeadExample();
  521. example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
  522. depotHeadMapper.updateByExampleSelective(dh, example);
  523. }
  524. }
  525. //将关联的单据置为审核状态-针对请购单转采购订单的情况
  526. if(StringUtil.isNotEmpty(depotHead.getLinkApply())){
  527. if(BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
  528. BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
  529. String status = BusinessConstants.BILLS_STATUS_AUDIT;
  530. //查询除当前单据之外的关联单据列表
  531. List<DepotHead> exceptCurrentList = getListByLinkApplyExceptCurrent(depotHead.getLinkApply(), depotHead.getNumber(), depotHead.getType());
  532. if(exceptCurrentList!=null && exceptCurrentList.size()>0) {
  533. status = BusinessConstants.BILLS_STATUS_SKIPING;
  534. }
  535. DepotHead dh = new DepotHead();
  536. dh.setStatus(status);
  537. DepotHeadExample example = new DepotHeadExample();
  538. example.createCriteria().andNumberEqualTo(depotHead.getLinkApply());
  539. depotHeadMapper.updateByExampleSelective(dh, example);
  540. }
  541. }
  542. //将关联的销售订单单据置为未采购状态-针对销售订单转采购订单的情况
  543. if(StringUtil.isNotEmpty(depotHead.getLinkNumber())){
  544. if(BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
  545. BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
  546. DepotHead dh = new DepotHead();
  547. //获取分批操作后单据的商品和商品数量(汇总)
  548. List<DepotItemVo4MaterialAndSum> batchList = depotItemMapperEx.getBatchBillDetailMaterialSum(depotHead.getLinkNumber(), "normal", depotHead.getType());
  549. if(batchList.size()>0) {
  550. dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_SKIPING);
  551. } else {
  552. dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_UN_AUDIT);
  553. }
  554. DepotHeadExample example = new DepotHeadExample();
  555. example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
  556. depotHeadMapper.updateByExampleSelective(dh, example);
  557. }
  558. }
  559. //对于零售出库单据,更新会员的预收款信息
  560. if (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
  561. && BusinessConstants.SUB_TYPE_RETAIL.equals(depotHead.getSubType())){
  562. if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())) {
  563. if (depotHead.getOrganId() != null) {
  564. //更新会员预付款
  565. supplierService.updateAdvanceIn(depotHead.getOrganId());
  566. }
  567. }
  568. }
  569. for (DepotItem depotItem : list) {
  570. //更新当前库存
  571. depotItemService.updateCurrentStock(depotItem);
  572. //更新当前成本价
  573. depotItemService.updateCurrentUnitPrice(depotItem);
  574. }
  575. }
  576. //路径列表
  577. List<String> pathList = new ArrayList<>();
  578. for(DepotHead depotHead: dhList){
  579. if(StringUtil.isNotEmpty(depotHead.getFileName())) {
  580. pathList.add(depotHead.getFileName());
  581. }
  582. }
  583. //逻辑删除文件
  584. systemConfigService.deleteFileByPathList(pathList);
  585. logService.insertLog("单据", sb.toString(),
  586. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  587. return 1;
  588. }
  589. /**
  590. * 删除单据主表信息
  591. * @param ids
  592. * @return
  593. * @throws Exception
  594. */
  595. @Override
  596. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  597. public int batchDeleteDepotHeadByIds(String ids)throws Exception {
  598. User userInfo=userService.getCurrentUser();
  599. String [] idArray=ids.split(",");
  600. int result=0;
  601. try{
  602. result = depotHeadMapperEx.batchDeleteDepotHeadByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
  603. }catch(Exception e){
  604. JshException.writeFail(logger, e);
  605. }
  606. return result;
  607. }
  608. @Override
  609. public List<DepotHead> getDepotHeadListByIds(String ids)throws Exception {
  610. List<Long> idList = StringUtil.strToLongList(ids);
  611. List<DepotHead> list = new ArrayList<>();
  612. try{
  613. DepotHeadExample example = new DepotHeadExample();
  614. example.createCriteria().andIdIn(idList);
  615. list = depotHeadMapper.selectByExample(example);
  616. }catch(Exception e){
  617. JshException.readFail(logger, e);
  618. }
  619. return list;
  620. }
  621. /**
  622. * 校验单据编号是否存在
  623. * @param id
  624. * @param number
  625. * @return
  626. * @throws Exception
  627. */
  628. @Override
  629. public int checkIsBillNumberExist(Long id, String number)throws Exception {
  630. DepotHeadExample example = new DepotHeadExample();
  631. example.createCriteria().andIdNotEqualTo(id).andNumberEqualTo(number).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  632. List<DepotHead> list = null;
  633. try{
  634. list = depotHeadMapper.selectByExample(example);
  635. }catch(Exception e){
  636. JshException.readFail(logger, e);
  637. }
  638. return list==null?0:list.size();
  639. }
  640. @Override
  641. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  642. public int batchSetStatus(String status, String depotHeadIDs)throws Exception {
  643. int result = 0;
  644. List<Long> dhIds = new ArrayList<>();
  645. List<Long> ids = StringUtil.strToLongList(depotHeadIDs);
  646. for(Long id: ids) {
  647. DepotHead depotHead = getDepotHead(id);
  648. if("0".equals(status)){
  649. //进行反审核操作
  650. if("1".equals(depotHead.getStatus()) && "0".equals(depotHead.getPurchaseStatus())) {
  651. dhIds.add(id);
  652. } else if("2".equals(depotHead.getPurchaseStatus())) {
  653. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_TWO_CODE,
  654. String.format(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_TWO_MSG));
  655. } else if("3".equals(depotHead.getPurchaseStatus())) {
  656. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_THREE_CODE,
  657. String.format(ExceptionConstants.DEPOT_HEAD_PURCHASE_STATUS_THREE_MSG));
  658. } else {
  659. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_CODE,
  660. String.format(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG));
  661. }
  662. } else if("1".equals(status)){
  663. //进行审核操作
  664. if("0".equals(depotHead.getStatus())) {
  665. dhIds.add(id);
  666. } else {
  667. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_TO_AUDIT_FAILED_CODE,
  668. String.format(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_TO_AUDIT_FAILED_MSG));
  669. }
  670. }
  671. }
  672. if(dhIds.size()>0) {
  673. DepotHead depotHead = new DepotHead();
  674. depotHead.setStatus(status);
  675. DepotHeadExample example = new DepotHeadExample();
  676. example.createCriteria().andIdIn(dhIds);
  677. result = depotHeadMapper.updateByExampleSelective(depotHead, example);
  678. //更新当前库存
  679. if(systemConfigService.getForceApprovalFlag()) {
  680. for(Long dhId: dhIds) {
  681. List<DepotItem> list = depotItemService.getListByHeaderId(dhId);
  682. for (DepotItem depotItem : list) {
  683. depotItemService.updateCurrentStock(depotItem);
  684. }
  685. }
  686. }
  687. }
  688. return result;
  689. }
  690. @Override
  691. public Map<Long,String> findMaterialsListMapByHeaderIdList(List<Long> idList)throws Exception {
  692. Map<Long,String> materialsListMap = new HashMap<>();
  693. if(idList.size()>0) {
  694. List<MaterialsListVo> list = depotHeadMapperEx.findMaterialsListMapByHeaderIdList(idList);
  695. for (MaterialsListVo materialsListVo : list) {
  696. String materialsList = materialsListVo.getMaterialsList();
  697. if(StringUtil.isNotEmpty(materialsList)) {
  698. materialsList = materialsList.replace(",",",");
  699. }
  700. materialsListMap.put(materialsListVo.getHeaderId(), materialsList);
  701. }
  702. }
  703. return materialsListMap;
  704. }
  705. @Override
  706. public Map<Long,BigDecimal> getMaterialCountListMapByHeaderIdList(List<Long> idList)throws Exception {
  707. Map<Long,BigDecimal> materialCountListMap = new HashMap<>();
  708. if(idList.size()>0) {
  709. List<MaterialCountVo> list = depotHeadMapperEx.getMaterialCountListByHeaderIdList(idList);
  710. for(MaterialCountVo materialCountVo : list){
  711. materialCountListMap.put(materialCountVo.getHeaderId(), materialCountVo.getMaterialCount());
  712. }
  713. }
  714. return materialCountListMap;
  715. }
  716. @Override
  717. public List<DepotHeadVo4InDetail> findInOutDetail(String beginTime, String endTime, String type, String[] creatorArray,
  718. String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag,
  719. String materialParam, List<Long> depotList, Integer oId, String number,
  720. Long creator, String remark, String column, String order, Integer offset, Integer rows) throws Exception{
  721. List<DepotHeadVo4InDetail> list = null;
  722. try{
  723. list =depotHeadMapperEx.findInOutDetail(beginTime, endTime, type, creatorArray, organArray, categoryList, forceFlag, inOutManageFlag,
  724. materialParam, depotList, oId, number, creator, remark, column, order, offset, rows);
  725. }catch(Exception e){
  726. JshException.readFail(logger, e);
  727. }
  728. return list;
  729. }
  730. @Override
  731. public int findInOutDetailCount(String beginTime, String endTime, String type, String[] creatorArray,
  732. String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag, String materialParam, List<Long> depotList, Integer oId, String number,
  733. Long creator, String remark) throws Exception{
  734. int result = 0;
  735. try{
  736. result =depotHeadMapperEx.findInOutDetailCount(beginTime, endTime, type, creatorArray, organArray, categoryList, forceFlag, inOutManageFlag,
  737. materialParam, depotList, oId, number, creator, remark);
  738. }catch(Exception e){
  739. JshException.readFail(logger, e);
  740. }
  741. return result;
  742. }
  743. @Override
  744. public DepotHeadVo4InDetail findInOutDetailStatistic(String beginTime, String endTime, String type, String[] creatorArray,
  745. String[] organArray, List<Long> categoryList, Boolean forceFlag, Boolean inOutManageFlag,
  746. String materialParam, List<Long> depotList, Integer oId, String number,
  747. Long creator, String remark) throws Exception{
  748. DepotHeadVo4InDetail item = new DepotHeadVo4InDetail();
  749. try{
  750. List<DepotHeadVo4InDetail> list =depotHeadMapperEx.findInOutDetailStatistic(beginTime, endTime, type, creatorArray, organArray, categoryList, forceFlag, inOutManageFlag,
  751. materialParam, depotList, oId, number, creator, remark);
  752. if(list.size()>0) {
  753. item.setOperNumber(list.get(0).getOperNumber());
  754. item.setAllPrice(list.get(0).getAllPrice());
  755. }
  756. }catch(Exception e){
  757. JshException.readFail(logger, e);
  758. }
  759. return item;
  760. }
  761. @Override
  762. public List<DepotHeadVo4InOutMCount> findInOutMaterialCount(String beginTime, String endTime, String type, List<Long> categoryList,
  763. Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
  764. List<Long> depotList, Long organizationId, Integer oId, String column, String order,
  765. Integer offset, Integer rows)throws Exception {
  766. List<DepotHeadVo4InOutMCount> list = null;
  767. try{
  768. String [] creatorArray = getCreatorArray();
  769. if(creatorArray == null && organizationId != null) {
  770. creatorArray = getCreatorArrayByOrg(organizationId);
  771. }
  772. String subType = "出库".equals(type)? "销售" : "";
  773. String [] organArray = getOrganArray(subType, "");
  774. list =depotHeadMapperEx.findInOutMaterialCount(beginTime, endTime, type, categoryList, forceFlag, inOutManageFlag, materialParam, depotList, oId,
  775. creatorArray, organArray, column, order, offset, rows);
  776. }catch(Exception e){
  777. JshException.readFail(logger, e);
  778. }
  779. return list;
  780. }
  781. @Override
  782. public int findInOutMaterialCountTotal(String beginTime, String endTime, String type, List<Long> categoryList,
  783. Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
  784. List<Long> depotList, Long organizationId, Integer oId)throws Exception {
  785. int result = 0;
  786. try{
  787. String [] creatorArray = getCreatorArray();
  788. if(creatorArray == null && organizationId != null) {
  789. creatorArray = getCreatorArrayByOrg(organizationId);
  790. }
  791. String subType = "出库".equals(type)? "销售" : "";
  792. String [] organArray = getOrganArray(subType, "");
  793. result =depotHeadMapperEx.findInOutMaterialCountTotal(beginTime, endTime, type, categoryList, forceFlag, inOutManageFlag, materialParam, depotList, oId,
  794. creatorArray, organArray);
  795. }catch(Exception e){
  796. JshException.readFail(logger, e);
  797. }
  798. return result;
  799. }
  800. @Override
  801. public DepotHeadVo4InOutMCount findInOutMaterialCountStatistic(String beginTime, String endTime, String type, List<Long> categoryList,
  802. Boolean forceFlag, Boolean inOutManageFlag, String materialParam,
  803. List<Long> depotList, Long organizationId, Integer oId) throws Exception {
  804. DepotHeadVo4InOutMCount item = new DepotHeadVo4InOutMCount();
  805. try{
  806. String [] creatorArray = getCreatorArray();
  807. if(creatorArray == null && organizationId != null) {
  808. creatorArray = getCreatorArrayByOrg(organizationId);
  809. }
  810. String subType = "出库".equals(type)? "销售" : "";
  811. String [] organArray = getOrganArray(subType, "");
  812. List<DepotHeadVo4InOutMCount> list = depotHeadMapperEx.findInOutMaterialCountStatistic(beginTime, endTime, type, categoryList,
  813. forceFlag, inOutManageFlag, materialParam, depotList, oId, creatorArray, organArray);
  814. if(list.size()>0) {
  815. item.setNumSum(list.get(0).getNumSum());
  816. item.setPriceSum(list.get(0).getPriceSum());
  817. }
  818. }catch(Exception e){
  819. JshException.readFail(logger, e);
  820. }
  821. return item;
  822. }
  823. @Override
  824. public List<DepotHeadVo4InDetail> findAllocationDetail(String beginTime, String endTime, String subType, String number,
  825. String[] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
  826. String remark, String column, String order, Integer offset, Integer rows) throws Exception{
  827. List<DepotHeadVo4InDetail> list = null;
  828. try{
  829. list =depotHeadMapperEx.findAllocationDetail(beginTime, endTime, subType, number, creatorArray, categoryList, forceFlag,
  830. materialParam, depotList, depotFList, remark, column, order, offset, rows);
  831. }catch(Exception e){
  832. JshException.readFail(logger, e);
  833. }
  834. return list;
  835. }
  836. @Override
  837. public int findAllocationDetailCount(String beginTime, String endTime, String subType, String number,
  838. String[] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
  839. String remark) throws Exception{
  840. int result = 0;
  841. try{
  842. result =depotHeadMapperEx.findAllocationDetailCount(beginTime, endTime, subType, number, creatorArray, categoryList, forceFlag,
  843. materialParam, depotList, depotFList, remark);
  844. }catch(Exception e){
  845. JshException.readFail(logger, e);
  846. }
  847. return result;
  848. }
  849. @Override
  850. public DepotHeadVo4InDetail findAllocationStatistic(String beginTime, String endTime, String subType, String number,
  851. String[] creatorArray, List<Long> categoryList, Boolean forceFlag, String materialParam, List<Long> depotList, List<Long> depotFList,
  852. String remark) throws Exception{
  853. DepotHeadVo4InDetail item = new DepotHeadVo4InDetail();
  854. try{
  855. List<DepotHeadVo4InDetail> list =depotHeadMapperEx.findAllocationStatistic(beginTime, endTime, subType, number, creatorArray, categoryList, forceFlag,
  856. materialParam, depotList, depotFList, remark);
  857. if(list.size()>0) {
  858. item.setOperNumber(list.get(0).getOperNumber());
  859. item.setAllPrice(list.get(0).getAllPrice());
  860. }
  861. }catch(Exception e){
  862. JshException.readFail(logger, e);
  863. }
  864. return item;
  865. }
  866. @Override
  867. public List<DepotHeadVo4StatementAccount> getStatementAccount(String beginTime, String endTime, Integer organId, String[] organArray,
  868. Integer hasDebt, String supplierType, String type, String subType, String typeBack,
  869. String subTypeBack, String billType, Integer offset, Integer rows) {
  870. List<DepotHeadVo4StatementAccount> list = null;
  871. try{
  872. list = depotHeadMapperEx.getStatementAccount(beginTime, endTime, organId, organArray, hasDebt, supplierType, type, subType,typeBack, subTypeBack, billType, offset, rows);
  873. } catch(Exception e){
  874. JshException.readFail(logger, e);
  875. }
  876. return list;
  877. }
  878. @Override
  879. public int getStatementAccountCount(String beginTime, String endTime, Integer organId, String[] organArray,
  880. Integer hasDebt, String supplierType, String type, String subType, String typeBack, String subTypeBack, String billType) {
  881. int result = 0;
  882. try{
  883. result = depotHeadMapperEx.getStatementAccountCount(beginTime, endTime, organId, organArray, hasDebt, supplierType, type, subType,typeBack, subTypeBack, billType);
  884. } catch(Exception e){
  885. JshException.readFail(logger, e);
  886. }
  887. return result;
  888. }
  889. @Override
  890. public List<DepotHeadVo4StatementAccount> getStatementAccountTotalPay(String beginTime, String endTime, Integer organId, String[] organArray,
  891. Integer hasDebt, String supplierType, String type, String subType,
  892. String typeBack, String subTypeBack, String billType) {
  893. List<DepotHeadVo4StatementAccount> list = null;
  894. try{
  895. list = depotHeadMapperEx.getStatementAccountTotalPay(beginTime, endTime, organId, organArray, hasDebt, supplierType, type, subType,typeBack, subTypeBack, billType);
  896. } catch(Exception e){
  897. JshException.readFail(logger, e);
  898. }
  899. return list;
  900. }
  901. @Override
  902. public List<DepotHeadVo4List> getDetailByNumber(String number, HttpServletRequest request)throws Exception {
  903. List<DepotHeadVo4List> resList = new ArrayList<>();
  904. try{
  905. Long userId = userService.getUserId(request);
  906. String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
  907. Map<Long,String> personMap = personService.getPersonMap();
  908. Map<Long,String> accountMap = accountService.getAccountMap();
  909. List<DepotHeadVo4List> list = depotHeadMapperEx.getDetailByNumber(number);
  910. if (null != list) {
  911. List<Long> idList = new ArrayList<>();
  912. List<String> numberList = new ArrayList<>();
  913. for (DepotHeadVo4List dh : list) {
  914. idList.add(dh.getId());
  915. numberList.add(dh.getNumber());
  916. }
  917. //通过批量查询去构造map
  918. Map<Long,Integer> financialBillNoMap = getFinancialBillNoMapByBillIdList(idList);
  919. Map<String,Integer> billSizeMap = getBillSizeMapByLinkNumberList(numberList);
  920. Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
  921. DepotHeadVo4List dh = list.get(0);
  922. String billCategory = getBillCategory(dh.getSubType());
  923. if(accountMap!=null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
  924. String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
  925. dh.setAccountName(accountStr);
  926. }
  927. if(dh.getAccountIdList() != null) {
  928. String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
  929. dh.setAccountIdList(accountidlistStr);
  930. }
  931. if(dh.getAccountMoneyList() != null) {
  932. String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
  933. dh.setAccountMoneyList(accountmoneylistStr);
  934. }
  935. if(dh.getChangeAmount() != null) {
  936. dh.setChangeAmount(roleService.parseBillPriceByLimit(dh.getChangeAmount().abs(), billCategory, priceLimit, request));
  937. } else {
  938. dh.setChangeAmount(BigDecimal.ZERO);
  939. }
  940. if(dh.getTotalPrice() != null) {
  941. dh.setTotalPrice(roleService.parseBillPriceByLimit(dh.getTotalPrice().abs(), billCategory, priceLimit, request));
  942. }
  943. BigDecimal discountLastMoney = dh.getDiscountLastMoney()!=null?dh.getDiscountLastMoney():BigDecimal.ZERO;
  944. dh.setDiscountLastMoney(roleService.parseBillPriceByLimit(discountLastMoney, billCategory, priceLimit, request));
  945. BigDecimal backAmount = dh.getBackAmount()!=null?dh.getBackAmount():BigDecimal.ZERO;
  946. dh.setBackAmount(roleService.parseBillPriceByLimit(backAmount, billCategory, priceLimit, request));
  947. if(dh.getDeposit() == null) {
  948. dh.setDeposit(BigDecimal.ZERO);
  949. } else {
  950. dh.setDeposit(roleService.parseBillPriceByLimit(dh.getDeposit(), billCategory, priceLimit, request));
  951. }
  952. //欠款计算
  953. BigDecimal otherMoney = dh.getOtherMoney()!=null?dh.getOtherMoney():BigDecimal.ZERO;
  954. BigDecimal deposit = dh.getDeposit()!=null?dh.getDeposit():BigDecimal.ZERO;
  955. BigDecimal changeAmount = dh.getChangeAmount()!=null?dh.getChangeAmount():BigDecimal.ZERO;
  956. BigDecimal debt = discountLastMoney.add(otherMoney).subtract((deposit.add(changeAmount)));
  957. dh.setDebt(roleService.parseBillPriceByLimit(debt, billCategory, priceLimit, request));
  958. //是否有付款单或收款单
  959. if(financialBillNoMap!=null) {
  960. Integer financialBillNoSize = financialBillNoMap.get(dh.getId());
  961. dh.setHasFinancialFlag(financialBillNoSize!=null && financialBillNoSize>0);
  962. }
  963. //是否有退款单
  964. if(billSizeMap!=null) {
  965. Integer billListSize = billSizeMap.get(dh.getNumber());
  966. dh.setHasBackFlag(billListSize!=null && billListSize>0);
  967. }
  968. if(StringUtil.isNotEmpty(dh.getSalesMan())) {
  969. dh.setSalesManStr(personService.getPersonByMapAndIds(personMap,dh.getSalesMan()));
  970. }
  971. if(dh.getOperTime() != null) {
  972. dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
  973. }
  974. //商品信息简述
  975. if(materialsListMap!=null) {
  976. dh.setMaterialsList(materialsListMap.get(dh.getId()));
  977. }
  978. User creatorUser = userService.getUser(dh.getCreator());
  979. if(creatorUser != null){
  980. dh.setCreatorName(creatorUser.getUsername());
  981. }
  982. resList.add(dh);
  983. }
  984. }catch(Exception e){
  985. JshException.readFail(logger, e);
  986. }
  987. return resList;
  988. }
  989. /**
  990. * 查询除当前单据之外的关联单据列表
  991. * @param linkNumber
  992. * @param number
  993. * @return
  994. * @throws Exception
  995. */
  996. @Override
  997. public List<DepotHead> getListByLinkNumberExceptCurrent(String linkNumber, String number, String type)throws Exception {
  998. DepotHeadExample example = new DepotHeadExample();
  999. example.createCriteria().andLinkNumberEqualTo(linkNumber).andNumberNotEqualTo(number).andTypeEqualTo(type)
  1000. .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1001. return depotHeadMapper.selectByExample(example);
  1002. }
  1003. /**
  1004. * 查询除当前单据之外的关联单据列表
  1005. * @param linkApply
  1006. * @param number
  1007. * @return
  1008. * @throws Exception
  1009. */
  1010. @Override
  1011. public List<DepotHead> getListByLinkApplyExceptCurrent(String linkApply, String number, String type)throws Exception {
  1012. DepotHeadExample example = new DepotHeadExample();
  1013. example.createCriteria().andLinkApplyEqualTo(linkApply).andNumberNotEqualTo(number).andTypeEqualTo(type)
  1014. .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1015. return depotHeadMapper.selectByExample(example);
  1016. }
  1017. /**
  1018. * 根据原单号查询关联的单据列表(批量)
  1019. * @param linkNumberList
  1020. * @return
  1021. * @throws Exception
  1022. */
  1023. @Override
  1024. public List<DepotHead> getBillListByLinkNumberList(List<String> linkNumberList)throws Exception {
  1025. if(linkNumberList!=null && linkNumberList.size()>0) {
  1026. DepotHeadExample example = new DepotHeadExample();
  1027. example.createCriteria().andLinkNumberIn(linkNumberList).andSubTypeLike("退货").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1028. return depotHeadMapper.selectByExample(example);
  1029. } else {
  1030. return new ArrayList<>();
  1031. }
  1032. }
  1033. /**
  1034. * 根据原单号查询关联的单据列表
  1035. * @param linkNumber
  1036. * @return
  1037. * @throws Exception
  1038. */
  1039. @Override
  1040. public List<DepotHead> getBillListByLinkNumber(String linkNumber)throws Exception {
  1041. DepotHeadExample example = new DepotHeadExample();
  1042. example.createCriteria().andLinkNumberEqualTo(linkNumber).andSubTypeLike("退货").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1043. return depotHeadMapper.selectByExample(example);
  1044. }
  1045. /**
  1046. * 新增单据主表及单据子表信息
  1047. * @param beanJson
  1048. * @param rows
  1049. * @param request
  1050. * @throws Exception
  1051. */
  1052. @Override
  1053. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  1054. public void addDepotHeadAndDetail(String beanJson, String rows,
  1055. HttpServletRequest request) throws Exception {
  1056. /**处理单据主表数据*/
  1057. DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
  1058. //校验单号是否重复
  1059. if(checkIsBillNumberExist(0L, depotHead.getNumber())>0) {
  1060. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_CODE,
  1061. String.format(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_MSG));
  1062. }
  1063. //校验是否同时录入关联请购单号和关联订单号
  1064. if(StringUtil.isNotEmpty(depotHead.getLinkNumber()) && StringUtil.isNotEmpty(depotHead.getLinkApply())) {
  1065. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_CODE,
  1066. String.format(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_MSG));
  1067. }
  1068. String subType = depotHead.getSubType();
  1069. //结算账户校验
  1070. if("采购".equals(subType) || "采购退货".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)) {
  1071. if (StringUtil.isEmpty(depotHead.getAccountIdList()) && depotHead.getAccountId() == null) {
  1072. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_CODE,
  1073. String.format(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG));
  1074. }
  1075. }
  1076. //判断用户是否已经登录过,登录过不再处理
  1077. User userInfo=userService.getCurrentUser();
  1078. depotHead.setCreator(userInfo==null?null:userInfo.getId());
  1079. depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
  1080. if(StringUtil.isEmpty(depotHead.getStatus())) {
  1081. depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
  1082. }
  1083. depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
  1084. depotHead.setPayType(depotHead.getPayType()==null?"现付":depotHead.getPayType());
  1085. if(StringUtil.isNotEmpty(depotHead.getAccountIdList())){
  1086. depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
  1087. }
  1088. if(StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
  1089. //校验多账户的结算金额
  1090. String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
  1091. BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
  1092. BigDecimal manyAccountSum = sum.abs();
  1093. if(manyAccountSum.compareTo(depotHead.getChangeAmount().abs())!=0) {
  1094. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
  1095. String.format(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG));
  1096. }
  1097. depotHead.setAccountMoneyList(accountMoneyList);
  1098. }
  1099. //校验累计扣除订金是否超出订单中的金额
  1100. if(depotHead.getDeposit()!=null && StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
  1101. BigDecimal finishDeposit = depotHeadMapperEx.getFinishDepositByNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber());
  1102. //订单中的订金金额
  1103. BigDecimal changeAmount = getDepotHead(depotHead.getLinkNumber()).getChangeAmount();
  1104. if(changeAmount!=null) {
  1105. BigDecimal preDeposit = changeAmount.abs();
  1106. if(depotHead.getDeposit().add(finishDeposit).compareTo(preDeposit)>0) {
  1107. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_CODE,
  1108. String.format(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG));
  1109. }
  1110. }
  1111. }
  1112. //校验附件的数量
  1113. if(StringUtil.isNotEmpty(depotHead.getFileName())) {
  1114. String[] fileArr = depotHead.getFileName().split(",");
  1115. if(fileArr.length>4) {
  1116. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_CODE,
  1117. String.format(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_MSG, 4));
  1118. }
  1119. }
  1120. JSONArray rowArr = JSONArray.parseArray(rows);
  1121. //商品数量
  1122. int operNumber = 0;
  1123. for (int i = 0; i < rowArr.size(); i++) {
  1124. JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
  1125. operNumber = operNumber + rowObj.getInteger("operNumber");
  1126. }
  1127. depotHead.setGoodsQuantity(operNumber);
  1128. //商品总类
  1129. depotHead.setGoodsTypeCount(rowArr.size());
  1130. //添加主表
  1131. depotHeadMapper.insertSelective(depotHead);
  1132. /**入库和出库处理预付款信息*/
  1133. if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
  1134. if(depotHead.getOrganId()!=null) {
  1135. BigDecimal currentAdvanceIn = supplierService.getSupplier(depotHead.getOrganId()).getAdvanceIn();
  1136. if(currentAdvanceIn.compareTo(depotHead.getTotalPrice())>=0) {
  1137. //更新会员的预付款
  1138. supplierService.updateAdvanceIn(depotHead.getOrganId());
  1139. } else {
  1140. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_CODE,
  1141. String.format(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG));
  1142. }
  1143. }
  1144. }
  1145. //根据单据编号查询单据id
  1146. DepotHeadExample dhExample = new DepotHeadExample();
  1147. dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1148. List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
  1149. if(list!=null) {
  1150. Long headId = list.get(0).getId();
  1151. /**入库和出库处理单据子表信息*/
  1152. depotItemService.saveDetials(rows,headId, "add",request);
  1153. }
  1154. logService.insertLog("单据",
  1155. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(depotHead.getNumber()).toString(),
  1156. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  1157. }
  1158. /**
  1159. * 更新单据主表及单据子表信息
  1160. * @param beanJson
  1161. * @param rows
  1162. * @param request
  1163. * @throws Exception
  1164. */
  1165. @Override
  1166. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  1167. public void updateDepotHeadAndDetail(String beanJson, String rows, HttpServletRequest request)throws Exception {
  1168. /**更新单据主表信息*/
  1169. DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
  1170. //校验单号是否重复
  1171. if(checkIsBillNumberExist(depotHead.getId(), depotHead.getNumber())>0) {
  1172. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_CODE,
  1173. String.format(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_MSG));
  1174. }
  1175. //校验是否同时录入关联请购单号和关联订单号
  1176. if(StringUtil.isNotEmpty(depotHead.getLinkNumber()) && StringUtil.isNotEmpty(depotHead.getLinkApply())) {
  1177. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_CODE,
  1178. String.format(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_MSG));
  1179. }
  1180. //校验单据状态,如果不是未审核则提示
  1181. if(!"0".equals(getDepotHead(depotHead.getId()).getStatus())) {
  1182. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_CANNOT_EDIT_CODE,
  1183. String.format(ExceptionConstants.DEPOT_HEAD_BILL_CANNOT_EDIT_MSG));
  1184. }
  1185. //获取之前的会员id
  1186. Long preOrganId = getDepotHead(depotHead.getId()).getOrganId();
  1187. String subType = depotHead.getSubType();
  1188. //结算账户校验
  1189. if("采购".equals(subType) || "采购退货".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)) {
  1190. if (StringUtil.isEmpty(depotHead.getAccountIdList()) && depotHead.getAccountId() == null) {
  1191. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_CODE,
  1192. String.format(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG));
  1193. }
  1194. }
  1195. if(StringUtil.isNotEmpty(depotHead.getAccountIdList())){
  1196. depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
  1197. }
  1198. if(StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
  1199. //校验多账户的结算金额
  1200. String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
  1201. BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
  1202. BigDecimal manyAccountSum = sum.abs();
  1203. if(manyAccountSum.compareTo(depotHead.getChangeAmount().abs())!=0) {
  1204. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
  1205. String.format(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG));
  1206. }
  1207. depotHead.setAccountMoneyList(accountMoneyList);
  1208. }
  1209. //校验累计扣除订金是否超出订单中的金额
  1210. if(depotHead.getDeposit()!=null && StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
  1211. BigDecimal finishDeposit = depotHeadMapperEx.getFinishDepositByNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber());
  1212. //订单中的订金金额
  1213. BigDecimal changeAmount = getDepotHead(depotHead.getLinkNumber()).getChangeAmount();
  1214. if(changeAmount!=null) {
  1215. BigDecimal preDeposit = changeAmount.abs();
  1216. if(depotHead.getDeposit().add(finishDeposit).compareTo(preDeposit)>0) {
  1217. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_CODE,
  1218. String.format(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG));
  1219. }
  1220. }
  1221. }
  1222. //校验附件的数量
  1223. if(StringUtil.isNotEmpty(depotHead.getFileName())) {
  1224. String[] fileArr = depotHead.getFileName().split(",");
  1225. if(fileArr.length>4) {
  1226. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_CODE,
  1227. String.format(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_MSG, 4));
  1228. }
  1229. }
  1230. JSONArray rowArr = JSONArray.parseArray(rows);
  1231. //商品数量
  1232. int operNumber = 0;
  1233. for (int i = 0; i < rowArr.size(); i++) {
  1234. JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
  1235. operNumber = operNumber + rowObj.getInteger("operNumber");
  1236. }
  1237. depotHead.setGoodsQuantity(operNumber);
  1238. //商品总类
  1239. depotHead.setGoodsTypeCount(rowArr.size());
  1240. //修改时间
  1241. depotHead.setOperTime(new Date());
  1242. //修改操作人
  1243. depotHead.setOperId(userService.getCurrentUser().getId());
  1244. //修改单据主表
  1245. depotHeadMapper.updateByPrimaryKeySelective(depotHead);
  1246. //如果存在多账户结算需要将原账户的id置空
  1247. if(StringUtil.isNotEmpty(depotHead.getAccountIdList())) {
  1248. depotHeadMapperEx.setAccountIdToNull(depotHead.getId());
  1249. }
  1250. /**入库和出库处理预付款信息*/
  1251. if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
  1252. if(depotHead.getOrganId()!=null){
  1253. BigDecimal currentAdvanceIn = supplierService.getSupplier(depotHead.getOrganId()).getAdvanceIn();
  1254. if(currentAdvanceIn.compareTo(depotHead.getTotalPrice())>=0) {
  1255. //更新会员的预付款
  1256. supplierService.updateAdvanceIn(depotHead.getOrganId());
  1257. if(null != preOrganId && !preOrganId.equals(depotHead.getOrganId())) {
  1258. //更新之前会员的预付款
  1259. supplierService.updateAdvanceIn(preOrganId);
  1260. }
  1261. } else {
  1262. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_CODE,
  1263. String.format(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG));
  1264. }
  1265. }
  1266. }
  1267. /**入库和出库处理单据子表信息*/
  1268. depotItemService.saveDetials(rows,depotHead.getId(), "update",request);
  1269. logService.insertLog("单据",
  1270. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(depotHead.getNumber()).toString(),
  1271. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  1272. }
  1273. @Override
  1274. public Map<String, Object> getBuyAndSaleStatistics(String today, String monthFirstDay, String yesterdayBegin, String yesterdayEnd,
  1275. String yearBegin, String yearEnd, HttpServletRequest request) throws Exception {
  1276. Long userId = userService.getUserId(request);
  1277. String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
  1278. Boolean forceFlag = systemConfigService.getForceApprovalFlag();
  1279. String[] creatorArray = getCreatorArray();
  1280. List<InOutPriceVo> inOutPriceVoList = depotHeadMapperEx.getBuyAndSaleStatisticsList(yearBegin, yearEnd, creatorArray, forceFlag);
  1281. String[] periods = {"today", "month", "yesterday", "year"};
  1282. String[] types = {"Buy", "BuyBack", "Sale", "SaleBack", "RetailSale", "RetailSaleBack"};
  1283. Map<String, BigDecimal> statistics = new HashMap<>();
  1284. // 初始化 statistics Map
  1285. for (String period : periods) {
  1286. for (String type : types) {
  1287. statistics.put(period + type, BigDecimal.ZERO);
  1288. }
  1289. }
  1290. Date todayDate = Tools.strToDate(today);
  1291. Date monthFirstDate = Tools.strToDate(monthFirstDay);
  1292. Date yesterdayStartDate = Tools.strToDate(yesterdayBegin);
  1293. Date yesterdayEndDate = Tools.strToDate(yesterdayEnd);
  1294. Date yearStartDate = Tools.strToDate(yearBegin);
  1295. Date yearEndDate = Tools.strToDate(yearEnd);
  1296. for (InOutPriceVo item : inOutPriceVoList) {
  1297. Date operTime = item.getOperTime();
  1298. BigDecimal discountLastMoney = item.getDiscountLastMoney();
  1299. BigDecimal totalPriceAbs = item.getTotalPrice().abs();
  1300. if (isWithinRange(operTime, todayDate, Tools.strToDate(getNow3()))) {
  1301. updateStatistics(statistics, item, "today", discountLastMoney, totalPriceAbs);
  1302. }
  1303. if (isWithinRange(operTime, monthFirstDate, Tools.strToDate(getNow3()))) {
  1304. updateStatistics(statistics, item, "month", discountLastMoney, totalPriceAbs);
  1305. }
  1306. if (isWithinRange(operTime, yesterdayStartDate, yesterdayEndDate)) {
  1307. updateStatistics(statistics, item, "yesterday", discountLastMoney, totalPriceAbs);
  1308. }
  1309. if (isWithinRange(operTime, yearStartDate, yearEndDate)) {
  1310. updateStatistics(statistics, item, "year", discountLastMoney, totalPriceAbs);
  1311. }
  1312. }
  1313. Map<String, Object> result = new HashMap<>();
  1314. for (String period : periods) {
  1315. result.put(period + "Buy", roleService.parseHomePriceByLimit(statistics.get(period + "Buy").subtract(statistics.get(period + "BuyBack")), "buy", priceLimit, "***", request));
  1316. result.put(period + "Sale", roleService.parseHomePriceByLimit(statistics.get(period + "Sale").subtract(statistics.get(period + "SaleBack")), "sale", priceLimit, "***", request));
  1317. result.put(period + "RetailSale", roleService.parseHomePriceByLimit(statistics.get(period + "RetailSale").subtract(statistics.get(period + "RetailSaleBack")), "retail", priceLimit, "***", request));
  1318. }
  1319. return result;
  1320. }
  1321. private boolean isWithinRange(Date operTime, Date startDate, Date endDate) {
  1322. return operTime.compareTo(startDate) >= 0 && operTime.compareTo(endDate) <= 0;
  1323. }
  1324. private void updateStatistics(Map<String, BigDecimal> statistics, InOutPriceVo item, String period, BigDecimal discountLastMoney, BigDecimal totalPriceAbs) {
  1325. switch (item.getType()) {
  1326. case "入库":
  1327. switch (item.getSubType()) {
  1328. case "采购":
  1329. statistics.put(period + "Buy", statistics.get(period + "Buy").add(discountLastMoney));
  1330. break;
  1331. case "销售退货":
  1332. statistics.put(period + "SaleBack", statistics.get(period + "SaleBack").add(discountLastMoney));
  1333. break;
  1334. case "零售退货":
  1335. statistics.put(period + "RetailSaleBack", statistics.get(period + "RetailSaleBack").add(totalPriceAbs));
  1336. break;
  1337. }
  1338. break;
  1339. case "出库":
  1340. switch (item.getSubType()) {
  1341. case "采购退货":
  1342. statistics.put(period + "BuyBack", statistics.get(period + "BuyBack").add(discountLastMoney));
  1343. break;
  1344. case "销售":
  1345. statistics.put(period + "Sale", statistics.get(period + "Sale").add(discountLastMoney));
  1346. break;
  1347. case "零售":
  1348. statistics.put(period + "RetailSale", statistics.get(period + "RetailSale").add(totalPriceAbs));
  1349. break;
  1350. }
  1351. break;
  1352. }
  1353. }
  1354. @Override
  1355. public DepotHead getDepotHead(String number)throws Exception {
  1356. DepotHead depotHead = new DepotHead();
  1357. try{
  1358. DepotHeadExample example = new DepotHeadExample();
  1359. example.createCriteria().andNumberEqualTo(number).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1360. List<DepotHead> list = depotHeadMapper.selectByExample(example);
  1361. if(null!=list && list.size()>0) {
  1362. depotHead = list.get(0);
  1363. }
  1364. }catch(Exception e){
  1365. JshException.readFail(logger, e);
  1366. }
  1367. return depotHead;
  1368. }
  1369. @Override
  1370. public List<DepotHeadVo4List> debtList(Long organId, String materialParam, String number, String beginTime, String endTime,
  1371. String status, Integer offset, Integer rows) {
  1372. List<DepotHeadVo4List> resList = new ArrayList<>();
  1373. try{
  1374. String depotIds = depotService.findDepotStrByCurrentUser();
  1375. String [] depotArray=depotIds.split(",");
  1376. String [] creatorArray = getCreatorArray();
  1377. beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
  1378. endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
  1379. List<DepotHeadVo4List> list=depotHeadMapperEx.debtList(organId, creatorArray, status, number,
  1380. beginTime, endTime, materialParam, depotArray, offset, rows);
  1381. if (null != list) {
  1382. resList = parseDebtBillList(list);
  1383. }
  1384. }catch(Exception e){
  1385. JshException.readFail(logger, e);
  1386. }
  1387. return resList;
  1388. }
  1389. @Override
  1390. public int debtListCount(Long organId, String materialParam, String number, String beginTime, String endTime,
  1391. String status) {
  1392. int total = 0;
  1393. try {
  1394. String depotIds = depotService.findDepotStrByCurrentUser();
  1395. String[] depotArray = depotIds.split(",");
  1396. String[] creatorArray = getCreatorArray();
  1397. beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
  1398. endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
  1399. total = depotHeadMapperEx.debtListCount(organId, creatorArray, status, number,
  1400. beginTime, endTime, materialParam, depotArray);
  1401. } catch(Exception e){
  1402. JshException.readFail(logger, e);
  1403. }
  1404. return total;
  1405. }
  1406. @Override
  1407. public void debtExport(Long organId, String materialParam, String number, String type, String subType,
  1408. String beginTime, String endTime, String status, String mpList,
  1409. HttpServletRequest request, HttpServletResponse response) {
  1410. try {
  1411. Long userId = userService.getUserId(request);
  1412. String priceLimit = userService.getRoleTypeByUserId(userId).getPriceLimit();
  1413. String billCategory = getBillCategory(subType);
  1414. String depotIds = depotService.findDepotStrByCurrentUser();
  1415. String[] depotArray = depotIds.split(",");
  1416. String[] creatorArray = getCreatorArray();
  1417. status = StringUtil.isNotEmpty(status) ? status : null;
  1418. beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
  1419. endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
  1420. List<DepotHeadVo4List> dhList = new ArrayList<>();
  1421. List<DepotHeadVo4List> list = depotHeadMapperEx.debtList(organId, creatorArray, status, number,
  1422. beginTime, endTime, materialParam, depotArray, null, null);
  1423. if (null != list) {
  1424. dhList = parseDebtBillList(list);
  1425. }
  1426. //生成Excel文件
  1427. String fileName = "单据信息";
  1428. File file = new File("/opt/"+ fileName);
  1429. WritableWorkbook wtwb = Workbook.createWorkbook(file);
  1430. String oneTip = "";
  1431. String sheetOneStr = "";
  1432. if("采购".equals(subType)) {
  1433. oneTip = "供应商对账列表";
  1434. sheetOneStr = "供应商,单据编号,关联单据,商品信息,单据日期,操作员,单据金额,本单欠款,已付欠款,待付欠款,备注";
  1435. } else if("出库".equals(type) && "销售".equals(subType)) {
  1436. oneTip = "客户对账列表";
  1437. sheetOneStr = "客户,单据编号,关联单据,商品信息,单据日期,操作员,单据金额,本单欠款,已收欠款,待收欠款,备注";
  1438. }
  1439. if(StringUtil.isNotEmpty(beginTime) && StringUtil.isNotEmpty(endTime)) {
  1440. oneTip = oneTip + "(" + beginTime + "至" + endTime + ")";
  1441. }
  1442. List<String> sheetOneList = StringUtil.strToStringList(sheetOneStr);
  1443. String[] sheetOneArr = StringUtil.listToStringArray(sheetOneList);
  1444. List<Long> idList = new ArrayList<>();
  1445. List<String[]> billList = new ArrayList<>();
  1446. Map<Long, BillListCacheVo> billListCacheVoMap = new HashMap<>();
  1447. for (DepotHeadVo4List dh : dhList) {
  1448. idList.add(dh.getId());
  1449. BillListCacheVo billListCacheVo = new BillListCacheVo();
  1450. billListCacheVo.setNumber(dh.getNumber());
  1451. billListCacheVo.setOrganName(dh.getOrganName());
  1452. billListCacheVo.setOperTimeStr(getCenternTime(dh.getOperTime()));
  1453. billListCacheVoMap.put(dh.getId(), billListCacheVo);
  1454. String[] objs = new String[sheetOneArr.length];
  1455. objs[0] = dh.getOrganName();
  1456. objs[1] = dh.getNumber();
  1457. objs[2] = dh.getLinkNumber();
  1458. objs[3] = dh.getMaterialsList();
  1459. objs[4] = dh.getOperTimeStr();
  1460. objs[5] = dh.getUserName();
  1461. BigDecimal discountLastMoney = dh.getDiscountLastMoney() == null ? BigDecimal.ZERO : dh.getDiscountLastMoney();
  1462. BigDecimal otherMoney = dh.getOtherMoney() == null ? BigDecimal.ZERO : dh.getOtherMoney();
  1463. BigDecimal deposit = dh.getDeposit() == null ? BigDecimal.ZERO : dh.getDeposit();
  1464. objs[6] = parseDecimalToStr(discountLastMoney.add(otherMoney).subtract(deposit), 2);
  1465. objs[7] = parseDecimalToStr(dh.getNeedDebt(), 2);
  1466. objs[8] = parseDecimalToStr(dh.getFinishDebt(), 2);
  1467. objs[9] = parseDecimalToStr(dh.getDebt(), 2);
  1468. objs[10] = dh.getRemark();
  1469. billList.add(objs);
  1470. }
  1471. ExcelUtils.exportObjectsManySheet(wtwb, oneTip, sheetOneArr, "单据列表", 0, billList);
  1472. //导出明细数据
  1473. if(idList.size()>0) {
  1474. List<DepotItemVo4WithInfoEx> dataList = depotItemMapperEx.getBillDetailListByIds(idList);
  1475. String[] mpArr = mpList.split(",");
  1476. String twoTip = "";
  1477. String sheetTwoStr = "";
  1478. if ("采购".equals(subType)) {
  1479. twoTip = "供应商单据明细";
  1480. sheetTwoStr = "供应商,单据编号,单据日期,仓库名称,条码,名称,规格,型号,颜色,品牌,制造商,扩展信息,单位,序列号,批号,有效期,多属性,数量,单价,金额,税率(%),税额,价税合计,重量,备注";
  1481. } else if ("销售".equals(subType)) {
  1482. twoTip = "客户单据明细";
  1483. sheetTwoStr = "客户,单据编号,单据日期,仓库名称,条码,名称,规格,型号,颜色,品牌,制造商,扩展信息,单位,序列号,批号,有效期,多属性,数量,单价,金额,税率(%),税额,价税合计,重量,备注";
  1484. }
  1485. if (StringUtil.isNotEmpty(beginTime) && StringUtil.isNotEmpty(endTime)) {
  1486. twoTip = twoTip + "(" + beginTime + "至" + endTime + ")";
  1487. }
  1488. List<String> sheetTwoList = StringUtil.strToStringList(sheetTwoStr);
  1489. String[] sheetTwoArr = StringUtil.listToStringArray(sheetTwoList);
  1490. List<String[]> billDetail = new ArrayList<>();
  1491. for (DepotItemVo4WithInfoEx diEx : dataList) {
  1492. String[] objs = new String[sheetTwoArr.length];
  1493. BillListCacheVo billListCacheVo = billListCacheVoMap.get(diEx.getHeaderId());
  1494. objs[0] = billListCacheVo != null ? billListCacheVo.getOrganName() : "";
  1495. objs[1] = billListCacheVo != null ? billListCacheVo.getNumber() : "";
  1496. objs[2] = billListCacheVo != null ? billListCacheVo.getOperTimeStr() : "";
  1497. objs[3] = diEx.getDepotId() == null ? "" : diEx.getDepotName();
  1498. objs[4] = diEx.getBarCode();
  1499. objs[5] = diEx.getMName();
  1500. objs[6] = diEx.getMStandard();
  1501. objs[7] = diEx.getMModel();
  1502. objs[8] = diEx.getMColor();
  1503. objs[9] = diEx.getBrand();
  1504. objs[10] = diEx.getMMfrs();
  1505. objs[11] = depotItemService.getOtherInfo(mpArr, diEx);
  1506. objs[12] = diEx.getMaterialUnit();
  1507. objs[13] = diEx.getSnList();
  1508. objs[14] = diEx.getBatchNumber();
  1509. objs[15] = Tools.parseDateToStr(diEx.getExpirationDate());
  1510. objs[16] = diEx.getSku();
  1511. objs[17] = parseDecimalToStr(diEx.getOperNumber(), 2);
  1512. objs[18] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getUnitPrice(), billCategory, priceLimit, request), 2);
  1513. objs[19] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getAllPrice(), billCategory, priceLimit, request), 2);
  1514. objs[20] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getTaxRate(), billCategory, priceLimit, request), 2);
  1515. objs[21] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getTaxMoney(), billCategory, priceLimit, request), 2);
  1516. objs[22] = parseDecimalToStr(roleService.parseBillPriceByLimit(diEx.getTaxLastMoney(), billCategory, priceLimit, request), 2);
  1517. BigDecimal allWeight = diEx.getBasicNumber() == null || diEx.getWeight() == null ? BigDecimal.ZERO : diEx.getBasicNumber().multiply(diEx.getWeight());
  1518. objs[23] = parseDecimalToStr(allWeight, 2);
  1519. objs[24] = diEx.getRemark();
  1520. billDetail.add(objs);
  1521. }
  1522. ExcelUtils.exportObjectsManySheet(wtwb, twoTip, sheetTwoArr, "单据明细", 1, billDetail);
  1523. }
  1524. wtwb.write();
  1525. wtwb.close();
  1526. ExcelUtils.downloadExcel(file, file.getName(), response);
  1527. } catch(Exception e){
  1528. JshException.readFail(logger, e);
  1529. }
  1530. }
  1531. @Override
  1532. public List<DepotHeadVo4List> parseDebtBillList(List<DepotHeadVo4List> list) throws Exception {
  1533. List<Long> idList = new ArrayList<>();
  1534. List<DepotHeadVo4List> dhList = new ArrayList<>();
  1535. for (DepotHeadVo4List dh : list) {
  1536. idList.add(dh.getId());
  1537. }
  1538. //通过批量查询去构造map
  1539. Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
  1540. for (DepotHeadVo4List dh : list) {
  1541. if(dh.getChangeAmount() != null) {
  1542. dh.setChangeAmount(dh.getChangeAmount().abs());
  1543. }
  1544. if(dh.getTotalPrice() != null) {
  1545. dh.setTotalPrice(dh.getTotalPrice().abs());
  1546. }
  1547. if(dh.getDeposit() == null) {
  1548. dh.setDeposit(BigDecimal.ZERO);
  1549. }
  1550. if(dh.getOperTime() != null) {
  1551. dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
  1552. }
  1553. BigDecimal discountLastMoney = dh.getDiscountLastMoney()!=null?dh.getDiscountLastMoney():BigDecimal.ZERO;
  1554. BigDecimal otherMoney = dh.getOtherMoney()!=null?dh.getOtherMoney():BigDecimal.ZERO;
  1555. BigDecimal deposit = dh.getDeposit()!=null?dh.getDeposit():BigDecimal.ZERO;
  1556. BigDecimal changeAmount = dh.getChangeAmount()!=null?dh.getChangeAmount().abs():BigDecimal.ZERO;
  1557. //本单欠款(如果退货则为负数)
  1558. dh.setNeedDebt(discountLastMoney.add(otherMoney).subtract(deposit.add(changeAmount)));
  1559. if(BusinessConstants.SUB_TYPE_PURCHASE_RETURN.equals(dh.getSubType()) || BusinessConstants.SUB_TYPE_SALES_RETURN.equals(dh.getSubType())) {
  1560. dh.setNeedDebt(BigDecimal.ZERO.subtract(dh.getNeedDebt()));
  1561. }
  1562. BigDecimal needDebt = dh.getNeedDebt()!=null?dh.getNeedDebt():BigDecimal.ZERO;
  1563. BigDecimal finishDebt = accountItemService.getEachAmountByBillId(dh.getId());
  1564. finishDebt = finishDebt!=null?finishDebt:BigDecimal.ZERO;
  1565. //已收欠款
  1566. dh.setFinishDebt(finishDebt);
  1567. //待收欠款
  1568. dh.setDebt(needDebt.subtract(finishDebt));
  1569. //商品信息简述
  1570. if(materialsListMap!=null) {
  1571. dh.setMaterialsList(materialsListMap.get(dh.getId()));
  1572. }
  1573. dhList.add(dh);
  1574. }
  1575. return dhList;
  1576. }
  1577. @Override
  1578. public String getBillCategory(String subType) {
  1579. if(subType.equals("零售") || subType.equals("零售退货")) {
  1580. return "retail";
  1581. } else if(subType.equals("销售订单") || subType.equals("销售") || subType.equals("销售退货")) {
  1582. return "sale";
  1583. } else {
  1584. return "buy";
  1585. }
  1586. }
  1587. /**
  1588. * 格式化金额样式
  1589. * @param decimal
  1590. * @param num
  1591. * @return
  1592. */
  1593. private String parseDecimalToStr(BigDecimal decimal, Integer num) {
  1594. return decimal == null ? "" : decimal.setScale(num, BigDecimal.ROUND_HALF_UP).toString();
  1595. }
  1596. private String parseStatusToStr(String status, String type) {
  1597. if(StringUtil.isNotEmpty(status)) {
  1598. if("purchase".equals(type)) {
  1599. switch (status) {
  1600. case "2":
  1601. return "完成采购";
  1602. case "3":
  1603. return "部分采购";
  1604. }
  1605. } else if("sale".equals(type)) {
  1606. switch (status) {
  1607. case "2":
  1608. return "完成销售";
  1609. case "3":
  1610. return "部分销售";
  1611. }
  1612. }
  1613. switch (status) {
  1614. case "0":
  1615. return "未审核";
  1616. case "1":
  1617. return "已审核";
  1618. case "9":
  1619. return "审核中";
  1620. }
  1621. }
  1622. return "";
  1623. }
  1624. @Override
  1625. public List<DepotHeadVo4List> waitBillList(String number, String materialParam, String type, String subType,
  1626. String beginTime, String endTime, String status, int offset, int rows) {
  1627. List<DepotHeadVo4List> resList = new ArrayList<>();
  1628. try{
  1629. String [] depotArray = getDepotArray("其它");
  1630. //给仓管可以看全部的单据(此时可以通过分配仓库去控制权限)
  1631. String [] creatorArray = null;
  1632. String [] subTypeArray = StringUtil.isNotEmpty(subType) ? subType.split(",") : null;
  1633. String [] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
  1634. Map<Long,String> accountMap = accountService.getAccountMap();
  1635. beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
  1636. endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
  1637. List<DepotHeadVo4List> list = depotHeadMapperEx.waitBillList(type, subTypeArray, creatorArray, statusArray, number, beginTime, endTime,
  1638. materialParam, depotArray, offset, rows);
  1639. if (null != list) {
  1640. List<Long> idList = new ArrayList<>();
  1641. for (DepotHeadVo4List dh : list) {
  1642. idList.add(dh.getId());
  1643. }
  1644. //通过批量查询去构造map
  1645. Map<Long,String> materialsListMap = findMaterialsListMapByHeaderIdList(idList);
  1646. Map<Long,BigDecimal> materialCountListMap = getMaterialCountListMapByHeaderIdList(idList);
  1647. for (DepotHeadVo4List dh : list) {
  1648. if(accountMap!=null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
  1649. String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
  1650. dh.setAccountName(accountStr);
  1651. }
  1652. if(dh.getOperTime() != null) {
  1653. dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
  1654. }
  1655. //商品信息简述
  1656. if(materialsListMap!=null) {
  1657. dh.setMaterialsList(materialsListMap.get(dh.getId()));
  1658. }
  1659. //商品总数量
  1660. if(materialCountListMap!=null) {
  1661. dh.setMaterialCount(materialCountListMap.get(dh.getId()));
  1662. }
  1663. resList.add(dh);
  1664. }
  1665. }
  1666. }catch(Exception e){
  1667. JshException.readFail(logger, e);
  1668. }
  1669. return resList;
  1670. }
  1671. @Override
  1672. public Long waitBillCount(String number, String materialParam, String type, String subType,
  1673. String beginTime, String endTime, String status) {
  1674. Long result=null;
  1675. try{
  1676. String [] depotArray = getDepotArray("其它");
  1677. //给仓管可以看全部的单据(此时可以通过分配仓库去控制权限)
  1678. String [] creatorArray = null;
  1679. String [] subTypeArray = StringUtil.isNotEmpty(subType) ? subType.split(",") : null;
  1680. String [] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
  1681. beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);
  1682. endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
  1683. result=depotHeadMapperEx.waitBillCount(type, subTypeArray, creatorArray, statusArray, number, beginTime, endTime,
  1684. materialParam, depotArray);
  1685. }catch(Exception e){
  1686. JshException.readFail(logger, e);
  1687. }
  1688. return result;
  1689. }
  1690. @Override
  1691. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  1692. public void batchAddDepotHeadAndDetail(String ids, HttpServletRequest request) throws Exception {
  1693. List<DepotHead> dhList = getDepotHeadListByIds(ids);
  1694. StringBuilder sb = new StringBuilder();
  1695. User userInfo=userService.getCurrentUser();
  1696. for(DepotHead depotHead : dhList) {
  1697. String prefixNo = BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType())?"QTRK":"QTCK";
  1698. //关联单据单号
  1699. String oldNumber = depotHead.getNumber();
  1700. //校验单据最新状态不能进行批量操作
  1701. if("0".equals(depotHead.getStatus()) || "2".equals(depotHead.getStatus()) || "9".equals(depotHead.getStatus())) {
  1702. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_NEW_STATUS_FAILED_CODE,
  1703. String.format(ExceptionConstants.DEPOT_ITEM_EXIST_NEW_STATUS_FAILED_MSG, oldNumber, depotHead.getType()));
  1704. }
  1705. //校验是否是部分入库或者部分出库
  1706. if("3".equals(depotHead.getStatus())) {
  1707. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_PARTIALLY_STATUS_FAILED_CODE,
  1708. String.format(ExceptionConstants.DEPOT_ITEM_EXIST_PARTIALLY_STATUS_FAILED_MSG, oldNumber, depotHead.getType()));
  1709. }
  1710. depotHead.setLinkNumber(oldNumber);
  1711. //给单号重新赋值
  1712. String number = prefixNo + sequenceService.buildOnlyNumber();
  1713. depotHead.setNumber(number);
  1714. depotHead.setDefaultNumber(number);
  1715. depotHead.setOperTime(new Date());
  1716. depotHead.setSubType(BusinessConstants.SUB_TYPE_OTHER);
  1717. depotHead.setChangeAmount(BigDecimal.ZERO);
  1718. depotHead.setTotalPrice(BigDecimal.ZERO);
  1719. depotHead.setDiscountLastMoney(BigDecimal.ZERO);
  1720. depotHead.setCreator(userInfo==null?null:userInfo.getId());
  1721. depotHead.setOrganId(null);
  1722. depotHead.setAccountId(null);
  1723. depotHead.setAccountIdList(null);
  1724. depotHead.setAccountMoneyList(null);
  1725. depotHead.setFileName(null);
  1726. depotHead.setSalesMan(null);
  1727. depotHead.setStatus("0");
  1728. depotHead.setTenantId(null);
  1729. //查询明细
  1730. List<DepotItemVo4WithInfoEx> itemList = depotItemService.getDetailList(depotHead.getId());
  1731. depotHead.setId(null);
  1732. JSONArray rowArr = new JSONArray();
  1733. for(DepotItemVo4WithInfoEx item: itemList) {
  1734. if("1".equals(item.getEnableSerialNumber())) {
  1735. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_SERIAL_NUMBER_FAILED_CODE,
  1736. String.format(ExceptionConstants.DEPOT_ITEM_EXIST_SERIAL_NUMBER_FAILED_MSG, oldNumber));
  1737. }
  1738. if("1".equals(item.getEnableBatchNumber())) {
  1739. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_BATCH_NUMBER_FAILED_CODE,
  1740. String.format(ExceptionConstants.DEPOT_ITEM_EXIST_BATCH_NUMBER_FAILED_MSG, oldNumber));
  1741. }
  1742. item.setUnitPrice(BigDecimal.ZERO);
  1743. item.setAllPrice(BigDecimal.ZERO);
  1744. item.setLinkId(item.getId());
  1745. item.setTenantId(null);
  1746. String itemStr = JSONObject.toJSONString(item);
  1747. JSONObject itemObj = JSONObject.parseObject(itemStr);
  1748. itemObj.put("unit", itemObj.getString("materialUnit"));
  1749. rowArr.add(itemObj.toJSONString());
  1750. }
  1751. String rows = rowArr.toJSONString();
  1752. //新增其它入库单或其它出库单
  1753. sb.append("[").append(depotHead.getNumber()).append("]");
  1754. depotHeadMapper.insertSelective(depotHead);
  1755. //根据单据编号查询单据id
  1756. DepotHeadExample dhExample = new DepotHeadExample();
  1757. dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1758. List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
  1759. if(list!=null) {
  1760. Long headId = list.get(0).getId();
  1761. /**入库和出库处理单据子表信息*/
  1762. depotItemService.saveDetials(rows, headId, "add", request);
  1763. }
  1764. }
  1765. logService.insertLog("单据",
  1766. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_BATCH_ADD).append(sb).toString(),
  1767. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  1768. }
  1769. @Override
  1770. public String syncOrderToXsdd(DepotHeadXsddRequestVO depotHead, List<DepotItemXsddRequestVO> depotItemList) throws Exception {
  1771. // 校验单号是否重复
  1772. if (checkIsBillNumberExist(0L, depotHead.getNumber()) > 0) {
  1773. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_CODE, String.format(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_MSG));
  1774. }
  1775. // 添加主表
  1776. depotHeadMapper.insertSelective(depotHead);
  1777. // 根据单据编号查询单据id
  1778. DepotHeadExample dhExample = new DepotHeadExample();
  1779. dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  1780. List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
  1781. if (list != null) {
  1782. Long headId = list.get(0).getId();
  1783. /** 销售订单 单据子表信息 */
  1784. depotItemService.saveOrderItem(depotHead, depotItemList);
  1785. List<Long> mIdList = depotItemList.stream().map(DepotItemXsddRequestVO::getMaterialId).collect(Collectors.toList());
  1786. //同步集采库存
  1787. syncTescoSystemService.sycnTescoStock(mIdList);
  1788. }
  1789. logService.insertLog("销售订单", new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(depotHead.getNumber()).toString(), ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest());
  1790. return "";
  1791. }
  1792. /**
  1793. * 根据商品id获取最后一条销售订单
  1794. * @param mid 商品id
  1795. * @return 商品信息
  1796. */
  1797. @Override
  1798. public DepotHead getDepotLastByMaterialId(long mid) {
  1799. return depotHeadMapper.getDepotLastByMaterialId(mid);
  1800. }
  1801. /**
  1802. * pda订单提交
  1803. *
  1804. * @param pdaDepotHeadDTO
  1805. * @return
  1806. */
  1807. @Override
  1808. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  1809. public boolean pdaOrderSubmit(PDADepotHeadDTO pdaDepotHeadDTO) throws Exception {
  1810. //根据单据号获取单据信息
  1811. DepotHead depotHead = depotHeadMapper.selectOne(new LambdaQueryWrapperX<DepotHead>().eq(DepotHead::getId, pdaDepotHeadDTO.getId()));
  1812. //根据单据id获取单据子表信息
  1813. List<DepotItem> depotItems = depotItemService.getListByHeaderId(depotHead.getId());
  1814. //设置单据主表信息
  1815. depotHead.setId(null);
  1816. //设置关联订单
  1817. depotHead.setLinkNumber(depotHead.getNumber());
  1818. String number = sequenceService.buildOnlyNumber();
  1819. //设置单号
  1820. if ("采购订单".equals(depotHead.getSubType())){
  1821. depotHead.setSubType("采购");
  1822. depotHead.setType("入库");
  1823. depotHead.setDefaultNumber("CGRK" + number) ;
  1824. depotHead.setNumber("CGRK" + number);
  1825. }else if ("销售订单".equals(depotHead.getSubType())){
  1826. depotHead.setSubType("销售");
  1827. depotHead.setType("出库");
  1828. depotHead.setDefaultNumber("XSCK" + number) ;
  1829. depotHead.setNumber("XSCK" + number);
  1830. }
  1831. //校验单号是否重复
  1832. if(checkIsBillNumberExist(0L, depotHead.getNumber())>0) {
  1833. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_CODE,
  1834. String.format(ExceptionConstants.DEPOT_HEAD_BILL_NUMBER_EXIST_MSG));
  1835. }
  1836. //校验是否同时录入关联请购单号和关联订单号
  1837. if(StringUtil.isNotEmpty(depotHead.getLinkNumber()) && StringUtil.isNotEmpty(depotHead.getLinkApply())) {
  1838. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_CODE,
  1839. String.format(ExceptionConstants.DEPOT_ITEM_EXIST_REPEAT_NO_FAILED_MSG));
  1840. }
  1841. String subType = depotHead.getSubType();
  1842. //结算账户校验
  1843. if("采购".equals(subType) || "采购退货".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)) {
  1844. if (StringUtil.isEmpty(depotHead.getAccountIdList()) && depotHead.getAccountId() == null) {
  1845. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_CODE,
  1846. String.format(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG));
  1847. }
  1848. }
  1849. //判断用户是否已经登录过,登录过不再处理
  1850. User userInfo = userService.getCurrentUser();
  1851. depotHead.setCreator(userInfo==null?null:userInfo.getId());
  1852. depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
  1853. depotHead.setOperId(userInfo==null?null:userInfo.getId());
  1854. depotHead.setOperTime(new Timestamp(System.currentTimeMillis()));
  1855. if(StringUtil.isEmpty(depotHead.getStatus())) {
  1856. depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
  1857. }
  1858. depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
  1859. depotHead.setPayType(depotHead.getPayType()==null?"现付":depotHead.getPayType());
  1860. if(StringUtil.isNotEmpty(depotHead.getAccountIdList())){
  1861. depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
  1862. }
  1863. if(StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
  1864. //校验多账户的结算金额
  1865. String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
  1866. BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
  1867. BigDecimal manyAccountSum = sum.abs();
  1868. if(manyAccountSum.compareTo(depotHead.getChangeAmount().abs())!=0) {
  1869. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
  1870. String.format(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG));
  1871. }
  1872. depotHead.setAccountMoneyList(accountMoneyList);
  1873. }
  1874. //校验附件的数量
  1875. if(StringUtil.isNotEmpty(depotHead.getFileName())) {
  1876. String[] fileArr = depotHead.getFileName().split(",");
  1877. if(fileArr.length>4) {
  1878. throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_CODE,
  1879. String.format(ExceptionConstants.DEPOT_HEAD_FILE_NUM_LIMIT_MSG, 4));
  1880. }
  1881. }
  1882. //商品数量
  1883. int operNumber = 0;
  1884. List<PDADepotMaterialDto> list = pdaDepotHeadDTO.getMaterials();
  1885. Map<String,PDADepotMaterialDto> materialMap = new HashMap<>();
  1886. for (int i = 0; i < list.size(); i++) {
  1887. operNumber = operNumber + list.get(i).getMaterialNumber().intValue();
  1888. materialMap.put(list.get(i).getBatchNumber(),list.get(i));
  1889. }
  1890. depotHead.setGoodsQuantity(operNumber);
  1891. //商品总类
  1892. depotHead.setGoodsTypeCount(list.size());
  1893. //设置凭证图片、备注
  1894. depotHead.setVoucherPicture(pdaDepotHeadDTO.getVoucherPicture());
  1895. depotHead.setRemark(pdaDepotHeadDTO.getRemark());
  1896. User user = userService.getCurrentUser();
  1897. depotHead.setTenantId(user.getId());
  1898. depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
  1899. depotHead.setStatus("2");
  1900. //添加主表
  1901. depotHeadMapper.insertSelective(depotHead);
  1902. //根据单据编号查询单据id
  1903. long id = depotHeadMapper.selectOne(new QueryWrapperX<DepotHead>().eq("number",depotHead.getNumber())).getId();
  1904. //设置单据子表信息
  1905. for (DepotItem depotItem : depotItems) {
  1906. //获取子表单商品
  1907. MaterialExtend materialExtend = materialExtendService.getMaterialExtend(depotItem.getMaterialExtendId());
  1908. //获取子表单批次号
  1909. String batchNumber = materialExtend.getBatchNumber();
  1910. //修改原先采购订单实际入库数量
  1911. depotItemService.update(new UpdateWrapper<DepotItem>().set("actual_quantity_in_storage", materialMap.get(batchNumber).getMaterialNumber()).eq("id", depotItem.getId()));
  1912. //设置单据主表id
  1913. depotItem.setHeaderId(id);
  1914. depotItem.setId(null);
  1915. //设置实际入库数量
  1916. depotItem.setActualQuantityInStorage(materialMap.get(batchNumber).getMaterialNumber());
  1917. //以下进行单位换算
  1918. Unit unitInfo = materialService.findUnit(depotItem.getMaterialId()); //查询多单位信息
  1919. if (StringUtil.isExist(depotItem.getActualQuantityInStorage())) {
  1920. //获取子表单商品单位
  1921. String unit =depotItem.getMaterialUnit();
  1922. BigDecimal oNumber = depotItem.getActualQuantityInStorage();
  1923. //设置基础数量
  1924. if (StringUtil.isNotEmpty(unitInfo.getName())) {
  1925. String basicUnit = unitInfo.getBasicUnit(); //基本单位
  1926. if (unit.equals(basicUnit)) { //如果等于基本单位
  1927. depotItem.setBasicNumber(oNumber); //数量一致
  1928. } else if (unit.equals(unitInfo.getOtherUnit())) { //如果等于副单位
  1929. depotItem.setBasicNumber(oNumber.multiply(unitInfo.getRatio())); //数量乘以比例
  1930. } else if (unit.equals(unitInfo.getOtherUnitTwo())) { //如果等于副单位2
  1931. depotItem.setBasicNumber(oNumber.multiply(unitInfo.getRatioTwo())); //数量乘以比例
  1932. } else if (unit.equals(unitInfo.getOtherUnitThree())) { //如果等于副单位3
  1933. depotItem.setBasicNumber(oNumber.multiply(unitInfo.getRatioThree())); //数量乘以比例
  1934. } else {
  1935. depotItem.setBasicNumber(oNumber); //数量一致
  1936. }
  1937. } else {
  1938. depotItem.setBasicNumber(oNumber); //其他情况
  1939. }
  1940. }
  1941. depotItem.setWarehousingUser(user.getId());
  1942. //添加单据子表
  1943. depotItemService.insertDepotItemWithObj(depotItem);
  1944. //修改商品生产日期
  1945. materialExtendService.update(new UpdateWrapper<MaterialExtend>().set("production_date",materialMap.get(batchNumber).getProductionDate()).eq("id", materialExtend.getId()));
  1946. }
  1947. //修改采购订单状态完成
  1948. this.update(new UpdateWrapper<DepotHead>().set("status", "2").eq("id", pdaDepotHeadDTO.getId()));
  1949. return true;
  1950. }
  1951. }