MInventoryOut.Class.php 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  1. <?php
  2. /**
  3. * 销售出库管理Model
  4. * Created by PhpStorm.
  5. * User: 小威
  6. * Date: 2019/11/11
  7. * Time: 14:00
  8. */
  9. namespace JinDouYun\Model\Stock;
  10. use Exception;
  11. use JinDouYun\Dao\Goods\DGoods;
  12. use Mall\Framework\Core\ErrorCode;
  13. use Mall\Framework\Core\StatusCode;
  14. use Mall\Framework\Core\ResultWrapper;
  15. use JinDouYun\Cache\Stock;
  16. use JinDouYun\Cache\OverviewCache;
  17. use JinDouYun\Model\MBaseModel;
  18. use JinDouYun\Model\Order\MOrder;
  19. use JinDouYun\Model\Common\MCommon;
  20. use JinDouYun\Model\Purchase\MPurchaseOut;
  21. use JinDouYun\Model\System\MPrintNum;
  22. use JinDouYun\Controller\Common\Logger;
  23. use JinDouYun\Dao\Order\DOrder;
  24. use JinDouYun\Dao\Order\DOrderIndex;
  25. use JinDouYun\Model\Goods\MGoods;
  26. use JinDouYun\Model\Order\MOrderGoods;
  27. use JinDouYun\Model\Shop\MShop;
  28. use JinDouYun\Model\System\MProcessSetting;
  29. use JinDouYun\Model\Finance\MRefund;
  30. use JinDouYun\Model\Finance\MAccount;
  31. use JinDouYun\Model\System\MSystemPushMessage;
  32. use JinDouYun\Model\System\MDriver;
  33. use JinDouYun\Dao\Purchase\DPurchase;
  34. use JinDouYun\Dao\Stock\DInventoryOut;
  35. use JinDouYun\Dao\Stock\DInventoryOutDetails;
  36. use JinDouYun\Dao\Customer\DCustomer;
  37. use JinDouYun\Dao\GoodsManage\DGoodsBasic;
  38. use Jindouyun\Dao\GoodsManage\DSku;
  39. class MInventoryOut extends MBaseModel
  40. {
  41. private $objDInventoryOut;
  42. private $objDInventoryOutDetails;
  43. private $enterpriseId;
  44. private $userCenterId;
  45. /**
  46. * @var int 单表数据量
  47. */
  48. private $cutTable = 200000;
  49. /**
  50. * @var Stock
  51. */
  52. private $objStockCache;
  53. /**
  54. * MInventoryOut constructor.
  55. * @param $enterpriseId
  56. * @param $userCenterId
  57. * @throws Exception
  58. */
  59. public function __construct($enterpriseId, $userCenterId)
  60. {
  61. $this->userCenterId = $userCenterId;
  62. $this->enterpriseId = $enterpriseId;
  63. parent::__construct($enterpriseId, $userCenterId);
  64. $this->objDInventoryOut = new DInventoryOut('stock');
  65. $this->objDInventoryOutDetails = new DInventoryOutDetails('stock');
  66. $this->objDInventoryOut->setTable($this->objDInventoryOut->get_Table() . '_' . $enterpriseId);
  67. $this->objDInventoryOutDetails->setTable($this->objDInventoryOutDetails->get_Table() . '_' . $enterpriseId);
  68. //$this->objDInventoryOut->setSearchIndex('inventory_out_search')->setType('inventory_out');
  69. $this->objStockCache = new Stock($this->enterpriseId);
  70. }
  71. /**
  72. * Doc: (des="获取订单出库单数量")
  73. * User: XMing
  74. * Date: 2021/2/23
  75. * Time: 10:41 上午
  76. * @param int $orderId
  77. * @return ResultWrapper
  78. */
  79. public function getTotalByOrderId(int $orderId): ResultWrapper
  80. {
  81. $where = [
  82. 'sourceId' => $orderId,
  83. 'source' => StatusCode::$orderType['saleOrder'],
  84. 'deleteStatus' => StatusCode::$standard
  85. ];
  86. $total = $this->objDInventoryOut->count($where);
  87. if ($total === false){
  88. return ResultWrapper::fail($this->objDInventoryOut->error(),ErrorCode::$dberror);
  89. }
  90. return ResultWrapper::success($total);
  91. }
  92. /**
  93. * 出库添加
  94. * @param $InventoryOutAddData
  95. * @return ResultWrapper
  96. * @throws Exception
  97. */
  98. public function addInventoryOut($InventoryOutAddData)
  99. {
  100. //接收参数
  101. //拿出详情数组
  102. $InventoryOutDetailsAddData = $InventoryOutAddData['orderGoodsData'];
  103. unset($InventoryOutAddData['orderGoodsData']);
  104. //定义固定参数
  105. $InventoryOutAddData['deleteStatus'] = StatusCode::$standard;
  106. $InventoryOutAddData['auditStatus'] = StatusCode::$auditStatus['auditing'];
  107. $InventoryOutAddData['outStatus'] = 1;
  108. $InventoryOutAddData['auditId'] = null;
  109. $InventoryOutAddData['auditName'] = null;
  110. $InventoryOutAddData['auditTime'] = null;
  111. $InventoryOutAddData['createTime'] = time();
  112. $InventoryOutAddData['updateTime'] = time();
  113. $InventoryOutAddData['deliveryType'] = isset($InventoryOutAddData['deliveryType']) ? $InventoryOutAddData['deliveryType'] : StatusCode::$deliveryType['logistics'];
  114. //no编号
  115. $dbResult = $this->objDInventoryOut->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
  116. if ($dbResult === false) {
  117. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  118. }
  119. if(empty($dbResult)){
  120. $InventoryOutAddData['no'] = createSerialNumberByDate('');
  121. }else{
  122. $InventoryOutAddData['no'] = createSerialNumberByDate($dbResult['no']);
  123. }
  124. //$InventoryOutAddData['no'] = createOrderSn(StatusCode::$source['manage'], $InventoryOutAddData['type'], $this->enterpriseId);
  125. $InventoryOutAddData['serialNum'] = $this->objStockCache->createSerialSn();
  126. //开启事务
  127. $beginStatus = $this->objDInventoryOut->beginTransaction();
  128. //插入基础表
  129. $dbResult = $this->objDInventoryOut->insert($InventoryOutAddData);
  130. if ($dbResult === false) {
  131. $this->objStockCache->createSerialSn(1);
  132. $this->objDInventoryOut->rollBack();
  133. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  134. }
  135. $InventoryOutId = $dbResult;
  136. //查询货架编码
  137. $params['details'] = $InventoryOutDetailsAddData;
  138. $modelResult = self::formatOutDetails($params);
  139. if(!$modelResult->isSuccess()){
  140. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  141. }
  142. $returnData = $modelResult->getData();
  143. unset($modelResult);
  144. $InventoryOutDetailsAddData = $returnData['details'];
  145. //定义固定参数
  146. foreach ($InventoryOutDetailsAddData as &$v) {
  147. $v['createTime'] = time();
  148. $v['updateTime'] = time();
  149. $v['linkId'] = $InventoryOutId;
  150. $v['linkNo'] = $InventoryOutAddData['no'];
  151. }
  152. unset($dbResult);
  153. //插入详情表
  154. $dbResult = $this->objDInventoryOutDetails->insert($InventoryOutDetailsAddData, true);
  155. if ($dbResult === false) {
  156. $this->objStockCache->createSerialSn(1);
  157. $this->objDInventoryOut->rollBack();
  158. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  159. }
  160. //增加es搜索
  161. /*
  162. $modelResult = self::updateEsData($InventoryOutAddData, $InventoryOutId);
  163. if (!$modelResult->isSuccess()) {
  164. $this->objStockCache->createSerialSn(1);
  165. $this->objDInventoryOut->rollBack();
  166. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  167. }*/
  168. //删除redis
  169. $objCacheStock = new Stock($this->enterpriseId);
  170. $cacheResult = $objCacheStock->deleteCacheStatistics('InventoryOut');
  171. if (!$cacheResult && $cacheResult !== 0) {
  172. $this->objStockCache->createSerialSn(1);
  173. $this->objDInventoryOut->rollBack();
  174. return ResultWrapper::fail('删除缓存失败', ErrorCode::$paramError);
  175. }
  176. if(!empty($InventoryOutAddData['shopId'])){
  177. //删除未出库统计redis
  178. $objOverviewCache = new OverviewCache();
  179. $objOverviewCache->delStatisticsCountInventoryOut($this->enterpriseId, $InventoryOutAddData['shopId']);
  180. }
  181. $beginStatus && $this->objDInventoryOut->commit();
  182. return ResultWrapper::success($InventoryOutId);
  183. }
  184. /**
  185. * 删除出库单
  186. * @param $where
  187. * @return ResultWrapper
  188. * @throws Exception
  189. */
  190. public function delInventoryOutStatus($where)
  191. {
  192. $update = [
  193. 'deleteStatus' => StatusCode::$delete,
  194. 'updateTime' => time(),
  195. ];
  196. $dbResult = $this->objDInventoryOut->get($where);
  197. if($dbResult === false){
  198. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  199. }
  200. $inventoryOut = $dbResult;
  201. unset($dbResult);
  202. if(empty($inventoryOut)){
  203. return ResultWrapper::fail('出库单不存在', ErrorCode::$dberror);
  204. }
  205. $dbResult = $this->objDInventoryOut->update($update, $where);
  206. if($dbResult === false){
  207. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  208. }
  209. /*
  210. $modelResult = self::updateEs($update,$inventoryOut['id']);
  211. if(!$modelResult->isSuccess()){
  212. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  213. }
  214. unset($modelResult); */
  215. //删除redis
  216. $objCacheStock = new Stock($this->enterpriseId);
  217. $cacheResult = $objCacheStock->deleteCacheStatistics('InventoryOut');
  218. if (!$cacheResult && $cacheResult !== 0) {
  219. $this->objDInventoryOut->rollBack();
  220. return ResultWrapper::fail('删除缓存失败', ErrorCode::$paramError);
  221. }
  222. //删除未出库统计redis
  223. $objOverviewCache = new OverviewCache();
  224. $objOverviewCache->delStatisticsCountInventoryOut($this->enterpriseId, $inventoryOut['shopId']);
  225. return ResultWrapper::success($dbResult);
  226. }
  227. /**
  228. * 出库审核
  229. * @param $params
  230. * @return ResultWrapper
  231. * @throws Exception
  232. */
  233. public function updateInventoryOutStatus($params)
  234. {
  235. // 手动审核分配出库物料数据
  236. if(isset($params['autoAudit']) && $params['autoAudit'] == StatusCode::$delete){
  237. $saveOutInventoryParams['outWarehouseData'] = $params['outWarehouseData'];
  238. $saveOutInventoryParams['UnassignedSkuData'] = $params['UnassignedSkuData'];
  239. }else{
  240. // 查询出库详情 计算出库仓库
  241. $modelResult = self::getInventoryOutInfo(['id' => $params['id']]);
  242. if(!$modelResult->isSuccess()){
  243. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  244. }
  245. $inventoryOutData = $modelResult->getData();
  246. //出库单包含抄码商品禁止自动审核
  247. $inventoryOutIsEq = StatusCode::$delete;
  248. foreach($inventoryOutData['details'] as $value){
  249. if($inventoryOutIsEq == StatusCode::$standard) break;
  250. if($value['isEq'] == StatusCode::$standard) $inventoryOutIsEq = StatusCode::$standard;
  251. }
  252. if($inventoryOutIsEq == StatusCode::$standard) return ResultWrapper::fail('抄码商品禁止自动审核', ErrorCode::$paramError);
  253. $saveOutInventoryParams['outWarehouseData'] = isset($inventoryOutData['outWarehouseData']) ? $inventoryOutData['outWarehouseData'] : [];
  254. $saveOutInventoryParams['UnassignedSkuData'] = isset($inventoryOutData['UnassignedSkuData']) ? $inventoryOutData['UnassignedSkuData'] : [];
  255. }
  256. unset($params['outWarehouseData'], $params['UnassignedSkuData'],$params['autoAudit']);
  257. $where['id'] = $params['id'];
  258. unset($params['id']);
  259. $params['updateTime'] = time();
  260. $params['auditTime'] = time();
  261. $params['auditStatus'] = StatusCode::$auditStatus['auditPass'];
  262. $updateExpress = [
  263. 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '',
  264. 'expressName' => isset($params['expressName']) ? $params['expressName'] : '',
  265. 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0,
  266. 'logisticsData' => isset($params['logisticsData']) ? $params['logisticsData'] : null,
  267. ];
  268. unset($params['logisticsData'],$params['deliveryNo'],$params['expressName'],$params['expressId']);
  269. // 获取出库单数据
  270. $InventoryOutData = $this->objDInventoryOut->get($where);
  271. if ($InventoryOutData === false) {
  272. $this->objDInventoryOut->rollBack();
  273. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  274. }
  275. if (empty($InventoryOutData)) {
  276. return ResultWrapper::fail('要审核的出库单不存在!', ErrorCode::$contentNotExists);
  277. }
  278. if ($InventoryOutData['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
  279. //return ResultWrapper::fail('出库单已经审核过了!', ErrorCode::$notAllowAccess);
  280. }
  281. $updateExpress['deliveryType'] = $InventoryOutData['deliveryType'];
  282. //销售出库 已取消订单 不能审核
  283. $objMOrder = new MOrder($this->userCenterId, $this->enterpriseId);
  284. $order = [];
  285. if ($InventoryOutData['type'] == StatusCode::$orderType['saleOut']) {
  286. $modelResult = $objMOrder->getOrderIndexData(['no' => $InventoryOutData['sourceNo']]);
  287. if(!$modelResult->isSuccess()){
  288. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  289. }
  290. $order = $modelResult->getData();
  291. unset($modelResult);
  292. if(empty($order)){
  293. return ResultWrapper::fail('关联订单不存在', ErrorCode::$paramError);
  294. }
  295. if($order['orderStatus'] == StatusCode::$orderStatus['close']){
  296. return ResultWrapper::fail('关联订单已取消', ErrorCode::$paramError);
  297. }
  298. }
  299. $beginStatus = $this->objDInventoryOut->beginTransaction();
  300. $modelResult = self::saveOutInventory($saveOutInventoryParams, ['id' => $where['id']]);
  301. if(!$modelResult->isSuccess()){
  302. $this->objDInventoryOut->rollBack();
  303. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  304. }
  305. //查询出库物料
  306. $InventoryOutDetailsResult = $this->objDInventoryOutDetails->select(['linkId' => $where['id'], 'linkNo' => $InventoryOutData['no']]);
  307. if ($InventoryOutDetailsResult === false) {
  308. $this->objDInventoryOut->rollBack();
  309. return ResultWrapper::fail($this->objDInventoryOutDetails->error(), ErrorCode::$dberror);
  310. }
  311. //组装出库单数据
  312. $InventoryOutDetailsData = [];
  313. $outWarehouseIds = [];
  314. $outInventoryMap = [];
  315. $inventoryOutMoney = 0;
  316. foreach($InventoryOutDetailsResult as $value){
  317. if(!empty($value['outWarehouse'])){
  318. $value['outWarehouse'] = json_decode($value['outWarehouse'], true);
  319. foreach($value['outWarehouse'] as $outWarehouse){
  320. if(!in_array($outWarehouse['warehouseId'],$outWarehouseIds)){
  321. $outWarehouseIds[] = $outWarehouse['warehouseId'];
  322. }
  323. if($outWarehouse['num'] <= 0){
  324. $this->objDInventoryOut->rollBack();
  325. return ResultWrapper::fail($value['materielName'].'出库数量不能小于等于0', ErrorCode::$paramError);
  326. }
  327. $value['num'] = $outWarehouse['num'];
  328. // $value['otherNum'] = $outWarehouse['otherNum'];
  329. $InventoryOutDetailsData[$outWarehouse['warehouseId']][] = $value;
  330. if (!isset($outInventoryMap[$value['skuId']])){
  331. $outInventoryMap[$value['skuId']] = 0;
  332. }
  333. $outInventoryMap[$value['skuId']] = bcadd($outInventoryMap[$value['skuId']],$outWarehouse['num'],2);
  334. // 计算实际出库单出库总金额
  335. $inventoryOutMoney = bcadd( $value['totalPrice'], $inventoryOutMoney, 2);
  336. }
  337. }
  338. }
  339. // 获取计算成本方式
  340. $objMWarehouse = new MWarehouse($this->enterpriseId);
  341. $modelResult = $objMWarehouse->selectWarehouse(['id' => $outWarehouseIds]);
  342. if(!$modelResult->isSuccess()){
  343. $this->objDInventoryOut->rollBack();
  344. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  345. }
  346. $warehouseResult = $modelResult->getData();
  347. unset($modelResult);
  348. $warehouseData = [];
  349. foreach($warehouseResult as $value){
  350. $warehouseData[$value['id']] = $value;
  351. }
  352. // 修改出库单状态
  353. // $params['amount'] = $inventoryOutMoney;
  354. $dbResult = $this->objDInventoryOut->update($params, $where);
  355. if ($dbResult === false) {
  356. $this->objDInventoryOut->rollBack();
  357. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  358. }
  359. $InventoryOutData = array_merge($InventoryOutData, $params);
  360. // 操作库存
  361. $objMInventory = new MInventory($this->enterpriseId, $this->userCenterId);
  362. foreach($InventoryOutDetailsData as $warehouseId => $value){
  363. $costType = isset($warehouseData[$warehouseId]) ? $warehouseData[$warehouseId]['costType'] : StatusCode::$costType['mwa'];
  364. $InventoryOutData['warehouseId'] = $warehouseId;
  365. $InventoryOutData['Details'] = $value;
  366. $result = $objMInventory->updateInventory($InventoryOutData, $costType);
  367. if (!$result->isSuccess()) {
  368. $this->objDInventoryOut->rollBack();
  369. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  370. }
  371. }
  372. //采购退货
  373. if ($InventoryOutData['type'] == StatusCode::$orderType['purchaseReturnOut']) {
  374. //出库状态回写
  375. $objMPurchaseOut = new MPurchaseOut($this->userCenterId, $this->enterpriseId);
  376. $modelResult = $objMPurchaseOut->updatePurchaseOutData(['outStatus' => StatusCode::$standard, 'updateTime' => time()], ['no' => $InventoryOutData['sourceNo']]);
  377. if (!$modelResult->isSuccess()) {
  378. $this->objDInventoryOut->rollBack();
  379. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  380. }
  381. }
  382. // 销售出库
  383. if ($InventoryOutData['type'] == StatusCode::$orderType['saleOut']) {
  384. // 回写销售订单出库状态
  385. $modelResult = $objMOrder->updateOutStatus(['orderStatus' => StatusCode::$orderStatus['waitReceive'], 'outTime' => time(), 'outStatus' => StatusCode::$standard, 'updateTime' => time()], ['no' => $InventoryOutData['sourceNo']], $outInventoryMap);
  386. if (!$modelResult->isSuccess()) {
  387. $this->objDInventoryOut->rollBack();
  388. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  389. }
  390. //修改发货信息
  391. // $updateExpressResult = $objMOrder->editOrderExpress($InventoryOutData['sourceNo'],$updateExpress);
  392. // if (!$updateExpressResult->isSuccess()){
  393. // $this->objDInventoryOut->rollBack();
  394. // return ResultWrapper::fail($updateExpressResult->getData(),$updateExpressResult->getErrorCode());
  395. // }
  396. $objDCustomer = new DCustomer('default');
  397. $objDCustomer->setTable('qianniao_customer_' . $this->enterpriseId);
  398. $customerData = $objDCustomer->get( $InventoryOutData['customerId'],'userCenterId,openId');
  399. if ($customerData === false) {
  400. $this->objDInventoryOut->rollBack();
  401. return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
  402. }
  403. $userCenterId = getArrayItem($customerData, 'userCenterId', StatusCode::$noneUserCenter);
  404. // 推送生成应收异步任务
  405. $i = 1;
  406. do {
  407. $postData = [
  408. 'topicName' => 'MyJob',
  409. 'topicClass' => 'Jobs\Model\MTopic\Finance\MReceivable',
  410. 'topicMethon' => 'createReceivable',
  411. 'topicMethonParams' => [
  412. 'userCenterId' => $userCenterId,
  413. 'enterpriseId' => $this->enterpriseId,
  414. 'id' => $InventoryOutData['id'], // 下推成出库单id
  415. 'type' => StatusCode::$orderType['saleOut'],
  416. ],
  417. ];
  418. $url = QIANNIAO_QUEUE . '/CAddJob/add';
  419. $result = request($url, $postData);
  420. $i++;
  421. } while ($result['httpcode'] != 200 && $i <= 3);
  422. self::runProcessNextFinish($order['id'], $order);
  423. //判断有没有设置配送司机信息
  424. // 格式化 extend
  425. if (!empty($InventoryOutData['extend'])){
  426. $InventoryOutData['extend'] = json_decode($InventoryOutData['extend'],true);
  427. }
  428. $logistics = $InventoryOutData['extend'];
  429. $truckTel =''; //司机电话
  430. $truckName =''; //司机车牌
  431. $driverName =''; //司机名称
  432. if(!empty($logistics)){
  433. foreach ($logistics as $key => $value){
  434. $truckTel = $value['truckTel'];
  435. $truckName = $value['truckName'];
  436. $driverName = $value['driverName'];
  437. }
  438. if (isset($customerData['openId']) && !empty($customerData['openId'])) {
  439. // 发送小程序订阅消息
  440. $sendMessageData = [
  441. 'time1' => ['value' => date('Y-m-d H:i:s',time())], // 发货时间
  442. 'character_string2' => ['value' => StatusCode::$noPrefix[1].'-'.$order['no']], // 订单编号
  443. 'thing3' => ['value' => $driverName], // 司机
  444. 'phone_number4' => ['value' => $truckTel], // 司机电话
  445. 'car_number5' => ['value' => $truckName], // 车牌号
  446. ];
  447. $objMSystemPushMessage = new MSystemPushMessage($this->userCenterId, $this->enterpriseId);
  448. $result = $objMSystemPushMessage->sendWeiXinPushMessage(8,$customerData['openId'],$sendMessageData, '/pagesT/order/orderDetail?id='.$order['id']);
  449. if (!$result->isSuccess()) {
  450. file_put_contents('/www/wwwroot/logs/api.junhailan.com/deliverGoods.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND);
  451. }
  452. }
  453. }else{
  454. if (isset($customerData['openId']) && !empty($customerData['openId'])) {
  455. // 发送小程序订阅消息
  456. $sendMessageData = [
  457. 'time3' => ['value' => date('Y-m-d H:i:s',time())], // 发货时间
  458. 'character_string7' => ['value' => StatusCode::$noPrefix[1].'-'.$order['no']], // 订单编号
  459. 'amount11' => ['value' => $InventoryOutData['amount']], // 订单金额
  460. 'date13' => ['value' => date('Y-m-d H:i:s',$order['createTime'])], // 下单时间
  461. 'thing20' => ['value' => date('Y-m-d H:i:s',time())], // 配送时间
  462. ];
  463. $objMSystemPushMessage = new MSystemPushMessage($this->userCenterId, $this->enterpriseId);
  464. $result = $objMSystemPushMessage->sendWeiXinPushMessage(2,$customerData['openId'],$sendMessageData, '/pagesT/order/orderDetail?id='.$order['id']);
  465. if (!$result->isSuccess()) {
  466. file_put_contents('/www/wwwroot/logs/api.junhailan.com/deliverGoods.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND);
  467. }
  468. }
  469. }
  470. }
  471. // 采购退货出库
  472. if ($InventoryOutData['type'] == StatusCode::$orderType['purchaseReturnOut']) {
  473. // 查询采购订单数据
  474. $objDPurchase = new DPurchase();
  475. $objDPurchase->setTable('qianniao_purchase_'.$this->enterpriseId);
  476. $purchaseData = $objDPurchase->get($InventoryOutData['originId']);
  477. if($purchaseData === false){
  478. $this->objDInventoryOut->rollBack();
  479. return ResultWrapper::fail($objDPurchase->error(), ErrorCode::$dberror);
  480. }
  481. if(empty($purchaseData)){
  482. $this->objDInventoryOut->rollBack();
  483. return ResultWrapper::fail('采购订单数据为空', ErrorCode::$contentNotExists);
  484. }
  485. // 推送生成应付异步任务
  486. $i = 1;
  487. do {
  488. $postData = [
  489. 'topicName' => 'MyJob',
  490. 'topicClass' => 'Jobs\Model\MTopic\Finance\MPayable',
  491. 'topicMethon' => 'createPayable',
  492. 'topicMethonParams' => [
  493. 'userCenterId' => $this->userCenterId,
  494. 'enterpriseId' => $this->enterpriseId,
  495. 'id' => $InventoryOutData['id'],
  496. 'type' => StatusCode::$orderType['purchaseReturnOut'],
  497. ],
  498. ];
  499. $url = QIANNIAO_QUEUE . '/CAddJob/add';
  500. $result = request($url, $postData);
  501. $i++;
  502. } while ($result['httpcode'] != 200 && $i <= 3);
  503. }
  504. // 调拨出库审核生成调拨入库单
  505. if ($InventoryOutData['source'] == StatusCode::$orderType['allocate']) {
  506. // 获取调拨单数据
  507. $objMAllocate = new MAllocate($this->enterpriseId, $this->userCenterId);
  508. $modelResult = $objMAllocate->getAllocate(['id' => $InventoryOutData['originId']]);
  509. if (!$modelResult->isSuccess()) {
  510. $this->objDInventoryOut->rollBack();
  511. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  512. }
  513. $allocateData = $modelResult->getData();
  514. unset($modelResult);
  515. if( empty($allocateData) ){
  516. $this->objDInventoryOut->rollBack();
  517. return ResultWrapper::fail('id为'.$inventoryOutIsEq['originId'].' 的调拨单不存在', ErrorCode::$contentNotExists);
  518. }
  519. // 获取调拨入库仓库数据
  520. $modelResult = $objMWarehouse->getWarehouse(['id' => $allocateData['inWarehouseId']]);
  521. if(!$modelResult->isSuccess()){
  522. $this->objDInventoryOut->rollBack();
  523. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  524. }
  525. $inWarehouseData = $modelResult->getData();
  526. unset($modelResult);
  527. if (empty($inWarehouseData)) {
  528. $this->objDInventoryOut->rollBack();
  529. return ResultWrapper::fail('id为'.$inventoryOutIsEq['originId'].' 的调拨单入库仓库查询失败', ErrorCode::$paramError);
  530. }
  531. //增加入库
  532. $inventoryIn['sourceId'] = $InventoryOutData['id'];
  533. $inventoryIn['sourceNo'] = $InventoryOutData['no'];
  534. $inventoryIn['materielNum'] = 0;
  535. $inventoryIn['amount'] = 0;
  536. $inventoryIn['originId'] = $InventoryOutData['originId'];
  537. $inventoryIn['originNo'] = $InventoryOutData['originNo'];
  538. $inventoryIn['warehouseId'] = $allocateData['inWarehouseId'];
  539. $inventoryIn['warehouseName'] = $inWarehouseData['warehouseName'];
  540. $inventoryIn['operatorId'] = $InventoryOutData['auditId'];
  541. $inventoryIn['operatorName'] = $InventoryOutData['auditName'];
  542. $inventoryIn['remark'] = $InventoryOutData['remark'];
  543. $inventoryIn['source'] = StatusCode::$orderType['allocateOut'];
  544. $inventoryIn['type'] = StatusCode::$orderType['allocateIn'];
  545. $inventoryIn['details'] = [];
  546. foreach ($InventoryOutDetailsData as $item) {
  547. foreach($item as $value){
  548. $inventoryIn['materielNum']++;
  549. $inventoryIn['amount'] += bcmul($value['num'], $value['unitPrice'], 4);
  550. $inDetails['materielId'] = $value['materielId'];
  551. $inDetails['materielName'] = $value['materielName'];
  552. $inDetails['materielCode'] = $value['materielCode'];
  553. $inDetails['skuId'] = $value['skuId'];
  554. $inDetails['unitName'] = $value['unitName'];
  555. $inDetails['skuName'] = $value['skuName'];
  556. $inDetails['num'] = $value['num'];
  557. $inDetails['otherNum'] = $value['otherNum'];
  558. $inDetails['unitPrice'] = $value['unitPrice'];
  559. $inventoryIn['orderGoodsData'][] = $inDetails;
  560. }
  561. }
  562. $objMInventoryIn = new MInventoryIn($this->enterpriseId, $this->userCenterId);
  563. $modelResult = $objMInventoryIn->addInventoryIn($inventoryIn);
  564. if (!$modelResult->isSuccess()) {
  565. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  566. }
  567. unset($modelResult);
  568. }
  569. //修改es
  570. /*
  571. $esId = self::esId($InventoryOutData['id']);
  572. $esResult = $this->objDInventoryOut->esupdateTypeFieldVaule($params, $esId);
  573. if(!$esResult){
  574. $this->objDInventoryOut->rollBack();
  575. return ResultWrapper::fail($esResult, ErrorCode::$paramError);
  576. }
  577. unset($esResult);*/
  578. //删除redis
  579. $objCacheStock = new Stock($this->enterpriseId);
  580. $cacheResult = $objCacheStock->deleteCacheStatistics('InventoryOut');
  581. if (!$cacheResult && $cacheResult !== 0) {
  582. $this->objDInventoryOut->rollBack();
  583. return ResultWrapper::fail('删除缓存失败', ErrorCode::$paramError);
  584. }
  585. //删除未出库统计redis
  586. $objOverviewCache = new OverviewCache();
  587. $objOverviewCache->delStatisticsCountInventoryOut($this->enterpriseId, $InventoryOutData['shopId']);
  588. $beginStatus && $this->objDInventoryOut->commit();
  589. return ResultWrapper::success($dbResult);
  590. }
  591. /**
  592. * 出库单分配仓库
  593. * @param $params
  594. * @param $where
  595. * @return ResultWrapper
  596. */
  597. public function saveOutInventory($params, $where)
  598. {
  599. $outInventoryId = $where['id'];
  600. //查询详情数据
  601. $dbResult = $this->objDInventoryOutDetails->select(['linkId' => $outInventoryId]);
  602. if($dbResult === false){
  603. return ResultWrapper::fail($this->objDInventoryOutDetails->error(), ErrorCode::$dberror);
  604. }
  605. $outInventoryDetailsResult = $dbResult;
  606. unset($dbResult);
  607. //格式化详情数据
  608. $outInventoryDetailsData = [];
  609. foreach($outInventoryDetailsResult as $value){
  610. $outInventoryDetailsData[$value['skuId']] = $value;
  611. }
  612. //格式化未分配出库数据
  613. $UnassignedSkuData = [];
  614. if(!empty($params['UnassignedSkuData'])){
  615. foreach($params['UnassignedSkuData'] as $value){
  616. $UnassignedSkuData[$value['skuId']] = $value;
  617. }
  618. }
  619. //循环出库仓库数据
  620. $skuOutNumTotal = [];
  621. foreach($params['outWarehouseData'] as $value){
  622. $warehouseId = $value['warehouseId'];
  623. foreach($value['details'] as $skuData){
  624. if(!isset($skuOutNumTotal[$skuData['skuId']])){
  625. $skuOutNumTotal[$skuData['skuId']] = [
  626. 'num' => 0,
  627. 'otherNum'=>$skuData['otherNum'],
  628. 'areaId' => $skuData['areaId'],
  629. 'areaName' => $skuData['areaName'],
  630. 'areaCode' => $skuData['areaCode'],
  631. 'storageLocationId' => $skuData['storageLocationId'],
  632. 'storageLocationName' => $skuData['storageLocationName'],
  633. 'storageLocationCode' => $skuData['storageLocationCode'],
  634. 'outWarehouse' => [],
  635. 'materielName' => $skuData['materielName']
  636. ];
  637. }
  638. $skuOutNumTotal[$skuData['skuId']]['num'] = isset($skuOutNumTotal[$skuData['skuId']]) ? bcadd($skuOutNumTotal[$skuData['skuId']]['num'], $skuData['num'],8) : $skuData['num'];
  639. $skuOutNumTotal[$skuData['skuId']]['outWarehouse'][] = [
  640. 'warehouseId' => $warehouseId,
  641. 'num' => $skuData['num'],
  642. 'otherNum' => $skuData['otherNum'],
  643. ];
  644. }
  645. }
  646. $updates = [];
  647. foreach($skuOutNumTotal as $skuId => $value){
  648. //出库数量
  649. $outNum = $value['num'];
  650. //未出库数量
  651. $outUnassignedNum = isset($UnassignedSkuData[$skuId]) ? $UnassignedSkuData[$skuId]['num'] : 0;
  652. //总数量
  653. $taotal = isset($outInventoryDetailsData[$skuId]) ? $outInventoryDetailsData[$skuId]['total'] : 0;
  654. if(bccomp(bcadd($outNum,$outUnassignedNum,8),$taotal) != 0){
  655. return ResultWrapper::fail($value['materielName'].'出库数量错误', ErrorCode::$paramError);
  656. }
  657. $update = [
  658. 'outWarehouse' => json_encode($value['outWarehouse']),
  659. 'num' => $outUnassignedNum,
  660. 'otherNum'=>$value['otherNum'],
  661. 'areaId' => $value['areaId'],
  662. 'areaName' => $value['areaName'],
  663. 'areaCode' => $value['areaCode'],
  664. 'storageLocationId' => $value['storageLocationId'],
  665. 'storageLocationName' => $value['storageLocationName'],
  666. 'storageLocationCode' => $value['storageLocationCode'],
  667. 'outNum' => $outNum,
  668. 'updateTime' => time(),
  669. ];
  670. $dbResult = $this->objDInventoryOutDetails->update($update, ['linkId' => $outInventoryId, 'skuId' => $skuId]);
  671. if($dbResult === false){
  672. return ResultWrapper::fail($this->objDInventoryOutDetails->error(), ErrorCode::$dberror);
  673. }
  674. $updates[$skuId] = $update;
  675. }
  676. return ResultWrapper::success($updates);
  677. }
  678. /**
  679. * 查询一个单据所有出库物料出库数量
  680. */
  681. public function getInventoryOutByOriginId($originId, $source)
  682. {
  683. $where = [
  684. 'originId' => $originId,
  685. 'source' => $source,
  686. 'deleteStatus' => StatusCode::$standard,
  687. 'auditStatus' => StatusCode::$auditStatus['auditPass']
  688. ];
  689. $dbResult = $this->objDInventoryOut->select($where);
  690. if($dbResult === false){
  691. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  692. }
  693. $inventoryOut = $dbResult;
  694. unset($dbResult);
  695. if(empty($inventoryOut)){
  696. return ResultWrapper::fail('出库单据不存在', ErrorCode::$paramError);
  697. }
  698. $inventoryOutIds = array_column($inventoryOut, 'id');
  699. $dbResult = $this->objDInventoryOutDetails->select(['linkId' => $inventoryOutIds]);
  700. if($dbResult === false){
  701. return ResultWrapper::fail($this->objDInventoryOutDetails->error(), ErrorCode::$dberror);
  702. }
  703. $details = [];
  704. foreach($dbResult as $value){
  705. if(!isset($details[$value['skuId']])){
  706. $details[$value['skuId']] = [
  707. 'outWarehouse' => json_decode($value['outWarehouse'], true),
  708. 'materielId' => $value['materielId'],
  709. 'materielName' => $value['materielName'],
  710. 'materielCode' => $value['materielCode'],
  711. 'skuId' => $value['skuId'],
  712. 'unitName' => $value['unitName'],
  713. 'skuName' => $value['skuName'],
  714. 'skuStorage' => $value['skuStorage'],
  715. 'num' => $value['outNum'],
  716. 'total' => $value['total'],
  717. 'outStatus' => $value['outStatus'],
  718. ];
  719. }else{
  720. $details[$value['skuId']]['outWarehouse'] = array_merge($details[$value['skuId']]['outWarehouse'], json_decode($value['outWarehouse'], true));
  721. $details[$value['skuId']]['num'] = bcadd($details[$value['skuId']]['num'], $value['outNum'], 8);
  722. }
  723. }
  724. return ResultWrapper::success($details);
  725. }
  726. /**
  727. * Doc: (des="")
  728. * User: XMing
  729. * Date: 2020/11/9
  730. * Time: 9:57 上午
  731. * @param int $orderId
  732. * @param array $order
  733. * @return ResultWrapper
  734. * @throws Exception
  735. */
  736. private function runProcessNextFinish(int $orderId,array $order): ResultWrapper
  737. {
  738. if (empty($orderId)){
  739. return ResultWrapper::success(true);
  740. }
  741. if ($order['orderType'] != StatusCode::$orderType['saleOrder']){
  742. return ResultWrapper::success(true);
  743. }
  744. $objMProcessSetting = new MProcessSetting($this->enterpriseId);
  745. $setResult = $objMProcessSetting->getProcessSettingByType(StatusCode::$processType['sales'],'finish');
  746. if (!$setResult->isSuccess()){
  747. Logger::logs(E_USER_ERROR,'获取流程配置出错',__CLASS__,__LINE__,$setResult->getData());
  748. return ResultWrapper::fail($setResult->getData(),$setResult->getErrorCode());
  749. }
  750. $set = $setResult->getData();
  751. if (empty($set)){
  752. Logger::logs(E_USER_ERROR,'配置为空',__CLASS__,__LINE__,'');
  753. return ResultWrapper::success(true);
  754. }
  755. if (isset($set['enableStatus']) && $set['enableStatus'] == StatusCode::$standard){
  756. Logger::logs(E_USER_ERROR,'配置',__CLASS__,__LINE__,$set);
  757. return ResultWrapper::success(true);
  758. }
  759. $objMOrder = new MOrder($this->userCenterId, $this->enterpriseId);
  760. $params = [
  761. 'orderStatus' => StatusCode::$orderStatus['finish']
  762. ];
  763. $result = $objMOrder->updateOrderStatus($orderId,$params,[]);
  764. if (!$result->isSuccess()){
  765. Logger::logs(E_USER_ERROR,'自动完成订单失败',__CLASS__,__LINE__,$result->getData());
  766. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  767. }
  768. Logger::logs(E_USER_ERROR,'自动完成订单成功',__CLASS__,__LINE__,$orderId);
  769. return ResultWrapper::success(true);
  770. }
  771. /**
  772. * 出库列表
  773. * @param $selectParams
  774. * @return ResultWrapper
  775. * @throws Exception
  776. */
  777. public function getAllInventoryOut($selectParams,$export=0)
  778. {
  779. $limit = $selectParams['limit'];
  780. unset($selectParams['limit']);
  781. $offset = $selectParams['offset'];
  782. unset($selectParams['offset']);
  783. $selectParams['deleteStatus'] = StatusCode::$standard;
  784. if (isset($selectParams['type'])){
  785. $type = $selectParams['type'];
  786. }
  787. $selectParams = self::formatSqlWhere($selectParams);
  788. // 映射仓库名称
  789. $objMAllocate = new MAllocate($this->enterpriseId,$this->userCenterId);
  790. if($export){
  791. $linkedTab =' qianniao_inventory_out_'.$this->enterpriseId.' as o left join qianniao_inventory_out_details_'.$this->enterpriseId.' as d ON o.id=d.linkId ';
  792. $whereSql = '';
  793. if(isset($type) && !empty($type)){
  794. $whereSql = ' o.type= '.$type.' and ';
  795. }
  796. $where = $whereSql.' o.deleteStatus='.StatusCode::$standard.' ORDER BY o.createTime desc';
  797. $sql ='select * from '.$linkedTab.' where '.$where;
  798. $exportDbResult = $this->objDInventoryOut->query($sql);
  799. if ($exportDbResult === false) {
  800. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  801. }
  802. $data = $objMAllocate->getAllocateInfoByWarehouseName($exportDbResult);
  803. if(!$data->isSuccess()){
  804. return ResultWrapper::fail($objMAllocate->error(), ErrorCode::$dberror);
  805. }
  806. $dbResult = $data->getData();
  807. $export = parent::formatOrderMan($this->enterpriseId, $dbResult);
  808. self::exportInventoryOut($export);
  809. exit;
  810. }
  811. $dbResult = $this->objDInventoryOut->select($selectParams, '*', 'createTime desc', $limit, $offset);
  812. if ($dbResult === false) {
  813. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  814. }
  815. $data = $objMAllocate->getAllocateInfoByWarehouseName($dbResult);
  816. if(!$data->isSuccess()){
  817. return ResultWrapper::fail($objMAllocate->error(), ErrorCode::$dberror);
  818. }
  819. $dbResult = $data->getData();
  820. $total = $this->objDInventoryOut->count($selectParams);
  821. $return = [
  822. 'data' => parent::formatOrderMan($this->enterpriseId, $dbResult),
  823. 'total' => ($total) ? intval($total) : 0,
  824. ];
  825. if ($return === false) {
  826. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  827. } else {
  828. return ResultWrapper::success($return);
  829. }
  830. }
  831. /**
  832. * 出库导出方法
  833. * @param $inventoryOutData
  834. */
  835. public function exportInventoryOut($inventoryOutData)
  836. {
  837. //导出到本地
  838. header("Content-type:application/vnd.ms-excel");
  839. header("Content-Disposition:filename=出库管理.csv");
  840. header('Cache-Control: max-age=0');
  841. $fp = fopen('php://output', 'a');
  842. $head = ['ID', '单据编号','制单时间','调出仓库', '客户', '客户电话','来源单号','配送方式', '出库类型', '审核人', '打印次数','商品名称','商品编码','规格','销售量','出库数量','销售单价','销售总金额','销售总金额(优惠后)','货架编码','商品条码']; //定义标题
  843. foreach ($head as $i => $v) {
  844. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  845. }
  846. fputcsv($fp, $head);
  847. $limit = 10000;
  848. $num = 0;//计数器
  849. foreach ($inventoryOutData as $value) {//循环数据
  850. $num++;
  851. if ($num == $limit) {
  852. ob_flush();//释放内存
  853. flush();
  854. }
  855. $rows['id'] = isset($value['linkId']) ? $value['linkId'] : null; // ID
  856. $rows['no'] = isset($value['no']) ? $value['no'] : null; // 单据编号
  857. $rows['createTime'] = isset($value['createTime']) ? date("Y-m-d H:i:s",$value['createTime']) : null; // 制单日期
  858. $rows['warehouseName'] = isset($value['warehouseName']) ? $value['warehouseName'] : null; // 调出仓库
  859. $rows['customerName'] = isset($value['customerName']) ? $value['customerName'] : null; // 客户
  860. $rows['customerMobile'] = isset($value['customerMobile']) ? $value['customerMobile'] : null; // 客户电话
  861. $rows['sourceNo'] = isset($value['sourceNo']) ? $value['sourceNo'] : null; // 来源单号
  862. $rows['deliveryName'] = isset($value['deliveryName']) ? $value['deliveryName'] : null; // 配送方式
  863. $rows['typeName'] = isset($value['typeName']) ? $value['typeName'] : null; // 出库类型
  864. $rows['auditName'] = isset($value['auditName']) ? $value['auditName'] : null; // 审核人
  865. $rows['printNum'] = isset($value['printNum']) ? $value['printNum'] : null; // 打印次数
  866. $rows['materielName'] = isset($value['materielName']) ? $value['materielName'] : null; // 商品名称
  867. $rows['materielCode'] = isset($value['materielCode']) ? $value['materielCode'] : null; // 商品编码
  868. $rows['specs'] = !empty($value['unitName']) && !empty($value['skuName']) ? $value['unitName'].';'.$value['skuName'] : $value['unitName']; // 规格
  869. $rows['total'] = isset($value['total']) ? $value['total'] : null; // 销售量
  870. $rows['outNum'] = isset($value['outNum']) ? $value['outNum'] : null; // 出库数量
  871. $rows['unitPrice'] = isset($value['unitPrice']) ? $value['unitPrice'] : null; // 销售单价
  872. $rows['originTotalPrice'] = bcmul($value['unitPrice'], $value['num'],2); // 销售总金额
  873. $rows['totalPrice'] = isset($value['totalPrice']) ? $value['totalPrice'] : null; // 销售总金额(优惠后)
  874. $rows['skuStorage'] = isset($value['skuStorage']) ? $value['skuStorage'] : null; // 货架编码
  875. $rows['skuBarCode'] = isset($value['skuBarCode']) ? $value['skuBarCode'] : null; // 商品条码
  876. foreach ($rows as $kk => $vv) {
  877. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  878. }
  879. fputcsv($fp, $rs);
  880. $rows = [];
  881. }
  882. }
  883. /**
  884. * 出库列表搜索
  885. * @param $params
  886. * @return ResultWrapper
  887. * @throws Exception
  888. */
  889. public function searchAllInventoryOut($params)
  890. {
  891. $defaultDSL = ['from' => $params['offset'], 'size' => $params['limit'], 'sort' => ['createTime' => ['order' => 'desc']]];
  892. $selectParams = [];
  893. $selectParams[] = ['term' => ['deleteStatus' => StatusCode::$standard]];
  894. $selectParams[] = ['term' => ['enterpriseId' => $this->enterpriseId]];
  895. !empty($params['type']) && $selectParams[] = ['term' => ['type' => $params['type']]];
  896. !empty($params['shopId']) && $selectParams[] = ['term' => ['shopId' => $params['shopId']]];
  897. !empty($params['warehouseId']) && $selectParams[] = ['term' => ['warehouseId' => $params['warehouseId']]];
  898. !empty($params['auditStatus']) && $selectParams[] = ['terms' => ['auditStatus' => is_array($params['auditStatus']) ? $params['auditStatus'] : [$params['auditStatus']]]];
  899. (!empty($params['start']) && !empty($params['end'])) && $selectParams[] = ['range' => ['createTime' => ['gte' => $params['start'], 'lte' => $params['end']]]];
  900. !empty($params['search']) && $selectParams[] = ['multi_match' => ['fields' => ['no', 'sourceNo', 'operatorName', 'customerName', 'customerMobile'], 'query' => $params['search'], 'fuzziness' => 'AUTO']];
  901. $dsl = [];
  902. !empty($selectParams) && $dsl['query']['bool']['must'][] = $selectParams;
  903. $dsl = array_merge($defaultDSL, $dsl);
  904. $dbResult = $this->objDInventoryOut->getSearchQueryDsl($dsl);
  905. if (isset($dbResult['error'])) {
  906. if ($dbResult['error']['reason'] == 'no such index') {
  907. return ResultWrapper::success(['data' => [], 'total' => 0]);
  908. }
  909. return ResultWrapper::fail($dbResult, ErrorCode::$dberror);
  910. }
  911. $returnData = parent::formatEsSelectData($dbResult);
  912. $objMCommon = new MCommon();
  913. foreach($returnData['data'] as &$value){
  914. if (isset($value['deliveryType']) && !empty($value['deliveryType'])) $value['deliveryName'] = StatusCode::$deliveryType[$value['deliveryType']];
  915. $value['typeName'] = $objMCommon->formatOrderSource($value['type']);
  916. }
  917. unset($value);
  918. return ResultWrapper::success($returnData);
  919. }
  920. /**
  921. * 出库统计
  922. * @param $type
  923. * @return ResultWrapper
  924. * @throws Exception
  925. */
  926. public function statisticsAllInventoryOut($type, $shopId = 0)
  927. {
  928. if($shopId){
  929. $sql = "select `type`,count(id) as count from ".$this->objDInventoryOut->get_Table()." where deleteStatus = ".StatusCode::$standard." and shopId = ".$shopId." GROUP BY `type`";
  930. $dbResult = $this->objDInventoryOut->query($sql);
  931. if($dbResult === false){
  932. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  933. }
  934. $typeData = [];
  935. foreach($dbResult as $value){
  936. $typeData[$value['type']] = $value['count'];
  937. }
  938. $cacheData = [];
  939. foreach($type as $value){
  940. $cacheData[] = [
  941. 'type' => $value,
  942. 'count' => isset($typeData[$value]) ? $typeData[$value] : 0,
  943. ];
  944. }
  945. return ResultWrapper::success($cacheData);
  946. }
  947. $cacheKey = 'InventoryOut';
  948. $objCacheStock = new Stock($this->enterpriseId);
  949. $cacheData = [];
  950. //判断redis里有没有这个key
  951. $cacheResult = $objCacheStock->getCacheStatisticsCount($cacheKey);
  952. $issetCacheKey = $cacheResult;
  953. unset($cacheResult);
  954. foreach ($type as $value) {
  955. $cacheResult = $objCacheStock->getCacheStatistics($value, $cacheKey);
  956. $cacheData[] = [
  957. 'type' => $value,
  958. 'count' => $cacheResult ? $cacheResult : 0,
  959. ];
  960. unset($cacheResult);
  961. }
  962. //如果有就拿出来 当做值返回
  963. if ($issetCacheKey) return ResultWrapper::success($cacheData);
  964. //如果没有 从数据库里查一遍 存到redis 值返回
  965. $sql = "select `type`,count(id) as count from " . $this->objDInventoryOut->get_Table() . " GROUP BY `type`";
  966. $dbResult = $this->objDInventoryOut->query($sql);//销售出库
  967. if ($dbResult === false) {
  968. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  969. }
  970. $typeData = [];
  971. foreach ($dbResult as $value) {
  972. $typeData[$value['type']] = $value['count'];
  973. }
  974. $cacheData = [];
  975. $cacheResult = $objCacheStock->deleteCacheStatistics($cacheKey);
  976. if (!$cacheResult && $cacheResult !== 0) {
  977. $this->objDInventoryOut->rollBack();
  978. return ResultWrapper::fail('删除缓存失败', ErrorCode::$paramError);
  979. }
  980. foreach ($type as $value) {
  981. $cacheData[] = [
  982. 'type' => $value,
  983. 'count' => isset($typeData[$value]) ? $typeData[$value] : 0,
  984. ];
  985. if (isset($typeData[$value])) {
  986. $objCacheStock->createCacheStatistics($value, $typeData[$value], $cacheKey);
  987. }
  988. }
  989. return ResultWrapper::success($cacheData);
  990. }
  991. /**
  992. * 出库详情
  993. * @param $params
  994. * @return ResultWrapper
  995. * @throws Exception
  996. */
  997. public function getInventoryOutInfo($params)
  998. {
  999. // 查询出库单数据
  1000. $params['deleteStatus'] = StatusCode::$standard;
  1001. $dbResult = $this->objDInventoryOut->get($params);
  1002. if ($dbResult === false) {
  1003. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1004. }
  1005. if(empty($dbResult)){
  1006. return ResultWrapper::fail('查询单据不存在', ErrorCode::$dberror);
  1007. }
  1008. // 查询出库单明细数据
  1009. $dbResult['details'] = $this->objDInventoryOutDetails->select(['linkId' => $dbResult['id']]);
  1010. if ($dbResult['details'] === false) {
  1011. return ResultWrapper::fail($this->objDInventoryOutDetails->error(), ErrorCode::$dberror);
  1012. }
  1013. // 格式化 extend
  1014. if (!empty($dbResult['extend'])){
  1015. $dbResult['extend'] = json_decode($dbResult['extend'],true);
  1016. }
  1017. // 提取skuid 和 物料id
  1018. $skuIds = array_column($dbResult['details'], 'skuId');
  1019. $materielIds = array_column($dbResult['details'], 'materielId');
  1020. // 查询订单商品表对应商品数据
  1021. $objMOrderGoods = new MOrderGoods($this->userCenterId,$this->enterpriseId);
  1022. if (isset($params['materielId'])){
  1023. $skuValueResult = $objMOrderGoods->formatSkuValue($dbResult['details'],'materielId','skuId',$dbResult['shopId']);
  1024. if (!$skuValueResult->isSuccess()){
  1025. return ResultWrapper::fail($skuValueResult->getData(),$skuValueResult->getErrorCode());
  1026. }
  1027. $dbResult['details'] = $skuValueResult->getData();
  1028. }
  1029. //每个物料的仓库分布
  1030. $dbResult['skuWarehouseData'] = [];
  1031. unset($modelResult);
  1032. //未出库物料数据
  1033. $dbResult['outWarehouseData'] = [];
  1034. //未分配物料数据
  1035. $dbResult['UnassignedSkuData'] = [];
  1036. //每个物料的待出库总数
  1037. $dbResult['skuTotal'] = [];
  1038. $objMShop = new MShop($this->enterpriseId,$this->userCenterId);
  1039. //判断该单据是否分配仓库
  1040. if($dbResult['type'] == StatusCode::$orderType['saleOut'] && $dbResult['auditStatus'] == StatusCode::$auditStatus['auditing']){
  1041. //分配出库
  1042. $dbResult['isDistribution'] = 5;
  1043. //查询商铺绑定仓库
  1044. $modelResult = $objMShop->getShopBindWarehouse($dbResult['shopId']);
  1045. if(!$modelResult->isSuccess()){
  1046. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1047. }
  1048. $shop = $modelResult->getData();
  1049. unset($modelResult);
  1050. if(empty($shop)){
  1051. return ResultWrapper::fail('商铺查询失败', ErrorCode::$dberror);
  1052. }
  1053. $warehouseData = $shop['warehouseData'];
  1054. //获取库存分布
  1055. $objMInventory = new MInventory($this->enterpriseId, $this->userCenterId);
  1056. $modelResult = $objMInventory->getInventoryByShopIdAndSkuIds($dbResult['shopId'], $skuIds);
  1057. if(!$modelResult->isSuccess()){
  1058. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1059. }
  1060. $inventoryData = $modelResult->getData();
  1061. $dbResult['skuWarehouseData'] = $inventoryData;
  1062. //获取负库存设置
  1063. $objMGoods = new MGoods($this->enterpriseId, false, $this->userCenterId);
  1064. $modelResult = $objMGoods->getDistributionByShopIdRelMaterielIds($dbResult['shopId'], $materielIds);
  1065. if(!$modelResult->isSuccess()){
  1066. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1067. }
  1068. $preSale = $modelResult->getData();
  1069. unset($modelResult);
  1070. $dbResult = self::distributionOutInventory($dbResult, $inventoryData, $warehouseData, $preSale);
  1071. }else{
  1072. //不分配出库
  1073. $dbResult['isDistribution'] = 4;
  1074. //查询仓库数据
  1075. $objMWarehouse = new MWarehouse($this->enterpriseId);
  1076. $modelResult = $objMWarehouse->selectWarehouse();
  1077. if(!$modelResult->isSuccess()){
  1078. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1079. }
  1080. $warehouseResult = $modelResult->getData();
  1081. unset($modelResult);
  1082. $warehouseData = [];
  1083. foreach($warehouseResult as $value){
  1084. $warehouseData[$value['id']] = $value;
  1085. }
  1086. $dbResult = self::formatClassCompleteOutInventory($dbResult, $warehouseData);
  1087. }
  1088. $dbResult = parent::formatOrderMan($this->enterpriseId, $dbResult);
  1089. //如果是销售出库单 需要格式化收货人信息 打印次数
  1090. if($dbResult['type'] == StatusCode::$orderType['saleOut']){
  1091. $modelResult = self::formatOrderInventoryOut($dbResult);
  1092. if(!$modelResult->isSuccess()){
  1093. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1094. }
  1095. $dbResult = $modelResult->getData();
  1096. $objMPrintNum = new MPrintNum($this->enterpriseId);
  1097. $modelResult = $objMPrintNum->getObjectPrintNum($dbResult['no'], $dbResult['type']);
  1098. $dbResult['printTimes'] = $modelResult;
  1099. $dbResult['printingNum'] = $modelResult;
  1100. foreach($dbResult['details'] as &$value){
  1101. $value['originTotalPrice'] = bcmul($value['unitPrice'], $value['num'],2);//原始总价
  1102. }
  1103. unset($value);
  1104. }
  1105. $dbResult['selfRuleData'] = [];
  1106. if($dbResult['source'] == StatusCode::$orderType['saleOrder']){
  1107. $ruleResult = self::formatSelfInfo($dbResult['sourceId']);
  1108. if (!$ruleResult->isSuccess()){
  1109. return ResultWrapper::fail($ruleResult->getData(),$ruleResult->getErrorCode());
  1110. }
  1111. $dbResult['selfRuleData'] = empty($ruleResult->getData()) ? [] : $ruleResult->getData();
  1112. $dbResult['receivedName'] = isset($dbResult['receiveData']['realName']) ? $dbResult['receiveData']['realName'] : '';
  1113. $dbResult['receivedMobile'] = isset($dbResult['receiveData']['mobile']) ? $dbResult['receiveData']['mobile'] : '';
  1114. $shopResult = $objMShop->getShopInfo(['id' => $dbResult['shopId']]);
  1115. if (!$shopResult->isSuccess()){
  1116. return ResultWrapper::fail($shopResult->getData(),$shopResult->getErrorCode());
  1117. }
  1118. $shopData = $shopResult->getData();
  1119. $dbResult['shopMobile'] = isset($shopData['mobile']) ? $shopData['mobile'] : '';
  1120. $dbResult['shopAddress'] = isset($shopData['area']) ? $shopData['area'] : [];
  1121. $dbResult['shopDescribe'] = isset($shopData['describe']) ? $shopData['describe'] : '';
  1122. }
  1123. if($dbResult['type'] == StatusCode::$orderType['allocateOut']){
  1124. // 映射仓库名称
  1125. $objMAllocate = new MAllocate($this->enterpriseId,$this->userCenterId);
  1126. $data = $objMAllocate->getAllocateInfoByWarehouseName([$dbResult]);
  1127. if(!$data->isSuccess()){
  1128. return ResultWrapper::fail($objMAllocate->error(), ErrorCode::$dberror);
  1129. }
  1130. $dbResult = $data->getData();
  1131. foreach ($dbResult as $key=>$value){
  1132. $dbResult[$key]['outWarehouseId'] = $dbResult[$key]['warehouseId'];
  1133. $dbResult[$key]['outWarehouseName'] = $dbResult[$key]['warehouseName'];
  1134. unset($dbResult[$key]['warehouseId']);
  1135. unset($dbResult[$key]['warehouseName']);
  1136. }
  1137. $dbResult = array_pop($dbResult);
  1138. }
  1139. return ResultWrapper::success($dbResult);
  1140. }
  1141. /**
  1142. * 自动分配库存
  1143. * @param $outInventory
  1144. * @param $inventoryData
  1145. * @param $warehouseData
  1146. * @param $preSale
  1147. * @return mixed
  1148. */
  1149. public function distributionOutInventory($outInventory, $inventoryData, $warehouseData, $preSale)
  1150. {
  1151. foreach($outInventory['details'] as $key => $value){
  1152. $value['outWarehouse'] = !empty($value['outWarehouse']) ? json_decode($value['outWarehouse'], true) : [];
  1153. $value['isPreSale'] = $preSale[$value['materielId']];//负库存
  1154. $outInventory['details'][$key]['isPreSale'] = $preSale[$value['materielId']];//负库存
  1155. $outInventory['skuTotal'][$value['skuId']] = $value['num'];//订单数量
  1156. $outNum = $value['num'];
  1157. $skuData = $value;
  1158. $value['warehouseSelect'] = [];
  1159. if(!isset($inventoryData[$value['skuId']])){
  1160. continue;
  1161. }
  1162. //物料所在仓库数据
  1163. $skuWarehouses = $inventoryData[$value['skuId']]['warehouseInventory'];
  1164. //可选出库仓库
  1165. foreach($skuWarehouses as $warehouseId => $skuWarehouse){
  1166. $value['warehouseSelect'][] = [
  1167. 'warehouseId' => $warehouseId,
  1168. 'warehouseName' => $warehouseData[$warehouseId]['warehouseName'],
  1169. 'warehouseInventoryNum' => $skuWarehouse['num']
  1170. ];
  1171. }
  1172. //循环分配仓库
  1173. foreach($skuWarehouses as $warehouseId => $skuWarehouse){
  1174. if($outNum == 0){
  1175. //订单数量分配完仓库
  1176. break;
  1177. }
  1178. $value['warehouseId'] = $warehouseId;
  1179. $value['warehouseName'] = $warehouseData[$warehouseId]['warehouseName'];
  1180. if($skuWarehouse['num'] <= 0){
  1181. //仓库库存小于0
  1182. if($value['isPreSale'] == StatusCode::$standard){
  1183. //开启预售(负库存)
  1184. if(!isset($outInventory['outWarehouseData'][$warehouseId])){
  1185. $outInventory['outWarehouseData'][$warehouseId] = [
  1186. 'warehouseId' => $warehouseId,
  1187. 'warehouseName' => $warehouseData[$warehouseId]['warehouseName'],
  1188. 'details' => []
  1189. ];
  1190. }
  1191. //仓库库存剩余=仓库库存-订单数量
  1192. $value['warehouseInventoryNum'] = bcsub($skuWarehouse['num'], $outNum, 8);
  1193. //出库数量就是订单数量
  1194. $outInventory['outWarehouseData'][$warehouseId]['details'][] = $value;
  1195. $outNum = 0;
  1196. }else{
  1197. //没有开启预售(负库存)
  1198. //跳过该仓库
  1199. continue;
  1200. }
  1201. }else{
  1202. //仓库库存大于0
  1203. if($skuWarehouse['num'] >= $outNum){
  1204. //仓库库存大于订单数量
  1205. if(!isset($outInventory['outWarehouseData'][$warehouseId])){
  1206. $outInventory['outWarehouseData'][$warehouseId] = [
  1207. 'warehouseId' => $warehouseId,
  1208. 'warehouseName' => $warehouseData[$warehouseId]['warehouseName'],
  1209. 'details' => []
  1210. ];
  1211. }
  1212. //仓库库存剩余=仓库库存-订单数量
  1213. $value['warehouseInventoryNum'] = bcsub($skuWarehouse['num'], $outNum, 8);
  1214. //出库数量=订单数量
  1215. $value['num'] = $outNum;
  1216. $outInventory['outWarehouseData'][$warehouseId]['details'][] = $value;
  1217. $outNum = 0;
  1218. }else{
  1219. //仓库数量小于订单数量
  1220. //判断是否开启预售
  1221. if($value['isPreSale'] == StatusCode::$standard){
  1222. //开启预售(负库存)
  1223. if(!isset($outInventory['outWarehouseData'][$warehouseId])){
  1224. $outInventory['outWarehouseData'][$warehouseId] = [
  1225. 'warehouseId' => $warehouseId,
  1226. 'warehouseName' => $warehouseData[$warehouseId]['warehouseName'],
  1227. 'details' => []
  1228. ];
  1229. }
  1230. //仓库库存剩余=仓库库存-订单数量
  1231. $value['warehouseInventoryNum'] = bcsub($skuWarehouse['num'], $outNum, 8);
  1232. //出库数量就是订单数量
  1233. $outInventory['outWarehouseData'][$warehouseId]['details'][] = $value;
  1234. $outNum = 0;
  1235. }else{
  1236. //没有开启预售(负库存)
  1237. if(!isset($outInventory['outWarehouseData'][$warehouseId])){
  1238. $outInventory['outWarehouseData'][$warehouseId] = [
  1239. 'warehouseId' => $warehouseId,
  1240. 'warehouseName' => $warehouseData[$warehouseId]['warehouseName'],
  1241. 'details' => []
  1242. ];
  1243. }
  1244. //仓库库存剩余=0
  1245. $value['warehouseInventoryNum'] = 0;
  1246. //出库数量=仓库库存
  1247. $value['num'] = $skuWarehouse['num'];
  1248. $outInventory['outWarehouseData'][$warehouseId]['details'][] = $value;
  1249. $outNum = bcsub($outNum, $skuWarehouse['num'],8);
  1250. continue;
  1251. }
  1252. }
  1253. }
  1254. }
  1255. if($outNum > 0){
  1256. $skuData['num'] = $outNum;
  1257. $outInventory['UnassignedSkuData'][] = $skuData;
  1258. }
  1259. }
  1260. $outInventory['outWarehouseData'] = array_values($outInventory['outWarehouseData']);
  1261. return $outInventory;
  1262. }
  1263. /**
  1264. * 格式化已完成出库单
  1265. * @param $outInventory
  1266. * @param $warehouseData
  1267. * @return mixed
  1268. */
  1269. public function formatClassCompleteOutInventory($outInventory, $warehouseData)
  1270. {
  1271. foreach($outInventory['details'] as $value){
  1272. //已出库数据
  1273. $value['outWarehouse'] = !empty($value['outWarehouse']) ? json_decode($value['outWarehouse'], true) : [];
  1274. $skuData = $value;
  1275. foreach($value['outWarehouse'] as $outWarehouse){
  1276. $warehouseId = $outWarehouse['warehouseId'];
  1277. if(!isset($outInventory['outWarehouseData'][$warehouseId])){
  1278. $outInventory['outWarehouseData'][$warehouseId] = [
  1279. 'warehouseId' => $warehouseId,
  1280. 'warehouseName' => $warehouseData[$warehouseId]['warehouseName'],
  1281. 'details' => []
  1282. ];
  1283. }
  1284. $value['num'] = $outWarehouse['num'];
  1285. $value['warehouseId'] = $warehouseId;
  1286. $value['warehouseName'] = $warehouseData[$warehouseId]['warehouseName'];
  1287. $outInventory['outWarehouseData'][$warehouseId]['details'][] = $value;
  1288. }
  1289. //未出库数据
  1290. if($skuData['num'] > 0){
  1291. $outInventory['UnassignedSkuData'][] = $skuData;
  1292. }
  1293. }
  1294. $outInventory['outWarehouseData'] = array_values($outInventory['outWarehouseData']);
  1295. return $outInventory;
  1296. }
  1297. /**
  1298. * Doc: (des="")
  1299. * User: XMing
  1300. * Date: 2020/10/11
  1301. * Time: 2:23 下午
  1302. * @param $orderId
  1303. * @throws Exception
  1304. * @return ResultWrapper
  1305. */
  1306. public function formatSelfInfo($orderId)
  1307. {
  1308. $objDOrderIndex = new DOrderIndex();
  1309. $objDOrderIndex->setTable('qianniao_order_index_'.$this->enterpriseId);
  1310. $orderIndex = $objDOrderIndex->get(['id'=>$orderId]);
  1311. if ($orderIndex===false){
  1312. return ResultWrapper::fail($objDOrderIndex->error(),ErrorCode::$dberror);
  1313. }
  1314. if (empty($orderIndex)){
  1315. return ResultWrapper::fail('获取订单信息失败',ErrorCode::$paramError);
  1316. }
  1317. if ($orderIndex['deliveryType'] != StatusCode::$deliveryType['selfMention']){
  1318. return ResultWrapper::success([]);
  1319. }
  1320. $objDOrder = new DOrder();
  1321. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);;
  1322. $objDOrder->setTable('qianniao_order_'.$this->enterpriseId.'_'.$fix);
  1323. $order = $objDOrder->get(['id' => $orderId]);
  1324. if ($order === false){
  1325. return ResultWrapper::fail($objDOrder->error(),ErrorCode::$dberror);
  1326. }
  1327. if (empty($order)){
  1328. return ResultWrapper::fail('获取订单信息失败',ErrorCode::$paramError);
  1329. }
  1330. $rule = empty($order['selfRuleData']) ? (object)[] : json_decode($order['selfRuleData'],true);
  1331. return ResultWrapper::success($rule);
  1332. }
  1333. /**
  1334. * 查询出库数据
  1335. * @param $where
  1336. * @return ResultWrapper
  1337. */
  1338. public function getInventoryOutData($where)
  1339. {
  1340. $dbResult = $this->objDInventoryOut->select($where);
  1341. if($dbResult === false){
  1342. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1343. }
  1344. return ResultWrapper::success($dbResult);
  1345. }
  1346. /**
  1347. * 格式化商品货架码 商品条码
  1348. * @param $params
  1349. * @param string $materielIdKey
  1350. * @return ResultWrapper
  1351. * @throws Exception
  1352. */
  1353. public function formatOutDetails($params, $materielIdKey = 'materielId')
  1354. {
  1355. foreach($params['details'] as &$value){
  1356. if(isset($value['storageCode']) && empty($value['storageCode'])){
  1357. $value['skuStorage'] = $value['storageCode'];
  1358. }else{
  1359. if(!isset($value['skuStorage']) || empty($value['skuStorage'])){
  1360. $materielIds[] = $value[$materielIdKey];
  1361. }
  1362. }
  1363. }
  1364. unset($value);
  1365. if(empty($materielIds)){
  1366. return ResultWrapper::success($params);
  1367. }
  1368. $objDGoodsBasic = new DGoodsBasic();
  1369. $sql = 'select * from qianniao_goods_basic_'.$this->enterpriseId.' where id in('.implode(',', $materielIds).')';
  1370. $dbResult = $objDGoodsBasic->query($sql);
  1371. if($dbResult === false){
  1372. return ResultWrapper::fail($objDGoodsBasic->error(), ErrorCode::$dberror);
  1373. }
  1374. $format = [];
  1375. foreach($dbResult as $value){
  1376. $format[$value['id']] = '';
  1377. if(!empty($value['extends'])){
  1378. $extends = json_decode($value['extends'], true);
  1379. if(isset($extends['storage']) && !empty($extends['storage'])){
  1380. $format[$value['id']] = $extends['storage'];
  1381. }
  1382. }
  1383. }
  1384. unset($value);
  1385. foreach($params['details'] as &$value){
  1386. $value['skuStorage'] = isset($format[$value[$materielIdKey]]) ? $format[$value[$materielIdKey]] : '';
  1387. }
  1388. return ResultWrapper::success($params);
  1389. }
  1390. /**
  1391. * 格式化销售出库单
  1392. * @param $data
  1393. * @return ResultWrapper
  1394. * @throws Exception
  1395. */
  1396. public function formatOrderInventoryOut($data)
  1397. {
  1398. if(empty($data)) return ResultWrapper::success($data);
  1399. //查询订单
  1400. $objMOrder = new MOrder($this->userCenterId, $this->enterpriseId);
  1401. $modelResult = $objMOrder->getOrderInfoById($data['originId']);
  1402. if(!$modelResult->isSuccess()){
  1403. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1404. }
  1405. $orderData = $modelResult->getData();
  1406. $data['deliveryName'] = $orderData['deliveryName'];//配送方式名称
  1407. $data['receiveData'] = $orderData['receiveData'];//收货信息
  1408. return ResultWrapper::success($data);
  1409. }
  1410. /**
  1411. * 查询采购退货记录
  1412. * @param $params
  1413. * @return ResultWrapper
  1414. */
  1415. public function getPurchaseReturnData($params)
  1416. {
  1417. if (empty($params)) return ResultWrapper::success([]);
  1418. $originIds = [];
  1419. $materielIds = [];
  1420. foreach ($params as $value) {
  1421. $originIds[] = $value['id'];
  1422. $materielIds[] = $value['materielId'];
  1423. }
  1424. $sql = 'select i.originId,d.materielId,d.num from ' . $this->objDInventoryOut->get_Table() . ' i left join ' . $this->objDInventoryOutDetails->get_Table() . ' d on i.id = d.linkId where i.auditId = ' . StatusCode::$auditStatus['auditPass'] . ' and i.type = ' . StatusCode::$orderType['purchaseReturnOut'] . ' and i.originId in(' . implode(",", $originIds) . ') and d.materielId in(' . implode(",", $materielIds) . ')';
  1425. $dbResult = $this->objDInventoryOut->query($sql);
  1426. if ($dbResult === false) {
  1427. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1428. }
  1429. $formatData = [];
  1430. foreach ($dbResult as $value) {
  1431. $formatData[md5($value['originId'] . $value['materielId'])] = $value;
  1432. }
  1433. unset($dbResult);
  1434. return ResultWrapper::success($formatData);
  1435. }
  1436. /**
  1437. * 查询出库数据
  1438. * @param $where
  1439. * @param string $fields
  1440. * @param string $order
  1441. * @param array $limits
  1442. * @return ResultWrapper
  1443. */
  1444. public function getOutData($where, $fields = '*', $order = 'id asc', $limits = [])
  1445. {
  1446. if ($limits) {
  1447. $limit = $limits['limit'];
  1448. unset($limits['limit']);
  1449. $offset = $limits['offset'];
  1450. unset($limits['offset']);
  1451. $dbResult = $this->objDInventoryOutDetails->select($where, $fields, $order, $limit, $offset);
  1452. } else {
  1453. $dbResult = $this->objDInventoryOutDetails->select($where, $fields, $order);
  1454. }
  1455. if ($dbResult === false) {
  1456. return ResultWrapper::fail($this->objDInventoryOutDetails->error(), ErrorCode::$dberror);
  1457. }
  1458. return ResultWrapper::success($dbResult);
  1459. }
  1460. /**
  1461. * 统计订单未出库总数
  1462. * @param int $shopId
  1463. * @return ResultWrapper
  1464. */
  1465. public function statisticsCountInventoryOut($shopId = 0)
  1466. {
  1467. if(empty($shopId)) $shopId = 0;
  1468. $objOverviewCache = new OverviewCache();
  1469. $result = $objOverviewCache->getStatisticsCountInventoryOut($this->enterpriseId, $shopId);
  1470. if($result){
  1471. return ResultWrapper::success($result);
  1472. }
  1473. $where = [
  1474. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  1475. 'deleteStatus' => StatusCode::$standard,
  1476. 'source' => StatusCode::$orderType['saleOrder'],
  1477. ];
  1478. $dbResult = $this->objDInventoryOut->count($where);
  1479. if($dbResult === false){
  1480. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1481. }
  1482. $allCount = $dbResult;
  1483. unset($dbResult);
  1484. $objOverviewCache->setStatisticsCountInventoryOut($this->enterpriseId, $shopId, $allCount);
  1485. if($shopId){
  1486. $where['shopId'] = $shopId;
  1487. $dbResult = $this->objDInventoryOut->count($where);
  1488. if($dbResult === false){
  1489. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1490. }
  1491. $shopCount = $dbResult;
  1492. unset($dbResult);
  1493. $objOverviewCache->setStatisticsCountInventoryOut($this->enterpriseId, $shopId, $shopCount);
  1494. return ResultWrapper::success($shopCount);
  1495. }
  1496. return ResultWrapper::success($allCount);
  1497. }
  1498. /**
  1499. * 添加es
  1500. * @param $data
  1501. * @param $id
  1502. * @param bool $type
  1503. * @return ResultWrapper
  1504. */
  1505. public function updateEsData($data, $id, $type = false)
  1506. {
  1507. $addEsData = [
  1508. 'id' => $id,
  1509. 'enterpriseId' => $this->enterpriseId,
  1510. 'no' => isset($data['no']) ? StatusCode::$noPrefix[$data['type']].$data['no'] : false,
  1511. 'sourceId' => isset($data['sourceId']) ? $data['sourceId'] : false,
  1512. 'sourceNo' => isset($data['sourceNo']) ? StatusCode::$noPrefix[$data['source']].$data['sourceNo'] : false,
  1513. 'originId' => isset($data['originId']) ? $data['originId'] : false,
  1514. 'originNo' => isset($data['originNo']) ? StatusCode::$noPrefix[$data['source']].$data['originNo'] : false,
  1515. 'materielNum' => isset($data['materielNum']) ? $data['materielNum'] : false,
  1516. 'amount' => isset($data['amount']) ? $data['amount'] : false,
  1517. 'warehouseId' => isset($data['warehouseId']) ? $data['warehouseId'] : false,
  1518. 'warehouseName' => isset($data['warehouseName']) ? $data['warehouseName'] : false,
  1519. 'operatorId' => isset($data['operatorId']) ? $data['operatorId'] : false,
  1520. 'operatorName' => isset($data['operatorName']) ? $data['operatorName'] : false,
  1521. 'auditId' => isset($data['auditId']) ? $data['auditId'] : false,
  1522. 'auditName' => isset($data['auditName']) ? $data['auditName'] : false,
  1523. 'customerId' => isset($data['customerId']) ? $data['customerId'] : false,
  1524. 'customerName' => isset($data['customerName']) ? $data['customerName'] : false,
  1525. 'customerCode' => isset($data['customerCode']) ? $data['customerCode'] : false,
  1526. 'customerMobile' => isset($data['customerMobile']) ? $data['customerMobile'] : false,
  1527. 'remark' => isset($data['remark']) ? $data['remark'] : false,
  1528. 'source' => isset($data['source']) ? $data['source'] : false,
  1529. 'type' => isset($data['type']) ? $data['type'] : false,
  1530. 'deliveryType' => isset($data['deliveryType']) ? $data['deliveryType'] : false,
  1531. 'deleteStatus' => isset($data['deleteStatus']) ? $data['deleteStatus'] : false,
  1532. 'auditStatus' => isset($data['auditStatus']) ? $data['auditStatus'] : false,
  1533. 'auditTime' => isset($data['auditTime']) ? $data['auditTime'] : false,
  1534. 'createTime' => isset($data['createTime']) ? $data['createTime'] : false,
  1535. 'updateTime' => isset($data['updateTime']) ? $data['updateTime'] : false,
  1536. ];
  1537. foreach ($addEsData as $key => $value) {
  1538. if ($value === false) {
  1539. if ($type) {
  1540. return ResultWrapper::fail($key . '字段未设置', ErrorCode::$paramError);
  1541. } else {
  1542. unset($addEsData[$key]);
  1543. }
  1544. }
  1545. }
  1546. //创建es id
  1547. $esId = self::esId($id);
  1548. $result = $this->objDInventoryOut->addUpSearchIndexDocument($addEsData, $esId);
  1549. if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  1550. return ResultWrapper::success(isset($result['_id']) ? $result['_id'] : false);
  1551. }
  1552. return ResultWrapper::fail($result['error']['reason'], ErrorCode::$paramError);
  1553. }
  1554. /**
  1555. * 修改es
  1556. * @param $update
  1557. * @param $id
  1558. * @return ResultWrapper
  1559. */
  1560. public function updateEs($update, $id)
  1561. {
  1562. $esId = self::esId($id);
  1563. $result = $this->objDInventoryOut->esupdateTypeFieldVaule($update, $esId);
  1564. if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  1565. return ResultWrapper::success(isset($result['_id']) ? $result['_id'] : false);
  1566. }
  1567. return ResultWrapper::fail($result['error']['reason'], ErrorCode::$paramError);
  1568. }
  1569. /**
  1570. * 拼接es id
  1571. * @param $id
  1572. * @return string
  1573. */
  1574. public function esId($id)
  1575. {
  1576. return 'EnterpriseId_' . $this->enterpriseId . '_InventoryOutId_' . $id;
  1577. }
  1578. /**
  1579. * 格式化出库es
  1580. */
  1581. public function formatInventoryOutEsData()
  1582. {
  1583. //查询列表数据
  1584. $dbResult = $this->objDInventoryOut->select([],'*');
  1585. if($dbResult === false){
  1586. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1587. }
  1588. if(empty($dbResult)){
  1589. return ResultWrapper::fail('格式化数据为空', ErrorCode::$dberror);
  1590. }
  1591. //循环插入es
  1592. foreach($dbResult as $value){
  1593. //增加es搜索
  1594. $modelResult = self::updateEsData($value, $value['id'], true);
  1595. if(!$modelResult->isSuccess()){
  1596. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1597. }
  1598. }
  1599. return ResultWrapper::success('格式化成功');
  1600. }
  1601. /**
  1602. * 设置物流信息
  1603. */
  1604. public function addLogistics($params)
  1605. {
  1606. if( !isset($params['id']) ){
  1607. return ResultWrapper::fail('出库单id参数错误',ErrorCode::$paramError);
  1608. }
  1609. $id = $params['id'];
  1610. unset($params['id']);
  1611. $extend = [];
  1612. $dbResult = $this->objDInventoryOut->get($id);
  1613. if($dbResult === false){
  1614. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1615. }
  1616. if( empty($dbResult) ){
  1617. return ResultWrapper::fail('要查询的出库单信息为空', ErrorCode::$contentNotExists);
  1618. }
  1619. // 如果司机是手动收入的,先做新增操作
  1620. if( empty($params['driverId']) ){
  1621. $objMDriver = new MDriver($this->enterpriseId, $this->userCenterId);
  1622. $paramsDriver = [
  1623. 'enterpriseId'=> $this->enterpriseId,
  1624. 'driverName' => $params['driverName'],
  1625. 'phone' => $params['truckTel'],
  1626. 'plateNumber' => $params['truckName'],
  1627. 'remark' => $params['remark']
  1628. ];
  1629. $addDriver = $objMDriver->addDriver($paramsDriver);
  1630. if ( !$addDriver->isSuccess() ){
  1631. return ResultWrapper::fail($addDriver->getData(),$addDriver->getErrorCode());
  1632. }
  1633. $driverId = $addDriver->getData();
  1634. $params['driverId']= $driverId;
  1635. }
  1636. $extend['logistics'] = $params;
  1637. $updateLogistics = $this->objDInventoryOut->update(['extend'=>json_encode($extend)]);
  1638. if($updateLogistics === false){
  1639. return ResultWrapper::fail($this->objDInventoryOut->error(), ErrorCode::$dberror);
  1640. }
  1641. return ResultWrapper::success($updateLogistics);
  1642. }
  1643. /**
  1644. * 扫条码加载出库单商品数据
  1645. */
  1646. public function getDetailByGoodsCode($params)
  1647. {
  1648. $objDSku = new DSku('default');
  1649. $objDSku->set_Table('qianniao_sku_'.$this->enterpriseId);
  1650. $dbResult = $objDSku->get(['barCode'=>$params['barCode']]);
  1651. if($dbResult === false){
  1652. return ResultWrapper::fail($objDSku->error(), ErrorCode::$dberror);
  1653. }
  1654. if(empty($dbResult)){
  1655. return ResultWrapper::fail('条码对应商品为空', ErrorCode::$contentNotExists);
  1656. }
  1657. // 查询商品是否支持负库存销售
  1658. $objDGoods = new DGoods('default');
  1659. $objDGoods->set_Table('qianniao_goods_'.$this->enterpriseId);
  1660. $condition = [
  1661. 'basicGoodsId' => $dbResult['goodsId'],
  1662. 'deleteStatus' => StatusCode::$standard,
  1663. ];
  1664. $goodsData = $objDGoods->get($condition);
  1665. if($goodsData === false){
  1666. return ResultWrapper::fail($objDGoods->error(), ErrorCode::$dberror);
  1667. }
  1668. if(empty($goodsData)){
  1669. return ResultWrapper::fail('商品数据为空', ErrorCode::$contentNotExists);
  1670. }
  1671. // 查询出库单明细数据
  1672. $condition = [
  1673. 'skuId' => $dbResult['id'],
  1674. 'linkId' => $params['id'],
  1675. ];
  1676. $dbResult = $this->objDInventoryOutDetails->select($condition);
  1677. if ($dbResult === false) {
  1678. return ResultWrapper::fail($this->objDInventoryOutDetails->error(), ErrorCode::$dberror);
  1679. }
  1680. $dbResult = parent::formatOrderMan($this->enterpriseId, $dbResult);
  1681. // 格式化负库存销售
  1682. foreach ($dbResult as $key => $value){
  1683. $dbResult[$key]['isDistribution'] = $goodsData['isDistribution'];
  1684. }
  1685. return ResultWrapper::success($dbResult);
  1686. }
  1687. }