DepotHeadServiceImpl.java 109 KB

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