enterpriseId = $enterpriseId; $this->onlineUserId = $userCenterId; parent::__construct($enterpriseId, $userCenterId); $this->objDInventoryIn = new DInventoryIn('stock'); $this->objDInventoryInDetails = new DInventoryInDetails('stock'); $this->objMInventory = new MInventory($enterpriseId, $this->onlineUserId); $this->objDInventoryIn->setTable($this->objDInventoryIn->get_Table().'_'.$enterpriseId); $this->objDInventoryInDetails->setTable($this->objDInventoryInDetails->get_Table().'_'.$enterpriseId); $this->objDInventoryIn->setSearchIndex('inventory_in_search')->setType('inventory_in'); } /** * 入库添加 * @param $params * @return ResultWrapper * @throws Exception */ public function addInventoryIn($params) { //接收参数 // 生成编号 $dbResult = $this->objDInventoryIn->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc'); if ($dbResult === false) { return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } if(empty($dbResult)){ $InventoryInAddData['no'] = createSerialNumberByDate(''); }else{ $InventoryInAddData['no'] = createSerialNumberByDate($dbResult['no']); } //$InventoryInAddData['no'] = createOrderSn(StatusCode::$source['manage'], $params['type'],$params['operatorId'] ); $InventoryInAddData['sourceId'] = $params['sourceId']; $InventoryInAddData['sourceNo'] = $params['sourceNo']; $InventoryInAddData['originNo'] = $params['originNo']; $InventoryInAddData['merchantId'] = isset($params['merchantId']) ? $params['merchantId'] : 0; $InventoryInAddData['originId'] = $params['originId']; $InventoryInAddData['shopId'] = isset($params['shopId']) ? $params['shopId'] : ''; $InventoryInAddData['materielNum'] = $params['materielNum']; $InventoryInAddData['amount'] = $params['amount']; $InventoryInAddData['warehouseId'] = $params['warehouseId']; $InventoryInAddData['warehouseName'] = $params['warehouseName']; $InventoryInAddData['operatorId'] = $params['operatorId']; $InventoryInAddData['operatorName'] = $params['operatorName']; $InventoryInAddData['auditId'] = 0; $InventoryInAddData['auditName'] = ''; $InventoryInAddData['source'] = $params['source']; $InventoryInAddData['type'] = $params['type']; $InventoryInAddData['deleteStatus'] = StatusCode::$standard; $InventoryInAddData['auditStatus'] = StatusCode::$auditStatus['auditing']; $InventoryInAddData['createTime'] = time(); $InventoryInAddData['updateTime'] = time(); $InventoryInAddData['auditTime'] = 0; $InventoryInAddData['extend'] = null; //拿出详情数组 $paramsDetailsAddData = $params['orderGoodsData']; //开启事务 $beginStatus = $this->objDInventoryIn->beginTransaction(); //插入基础表 $dbResult = $this->objDInventoryIn->insert($InventoryInAddData); if($dbResult === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $InventoryInId = $dbResult; unset($dbResult); //定义固定参数 $InventoryInDetailsAddData = []; foreach($paramsDetailsAddData as $v){ $detailsAddData = []; $detailsAddData['linkId'] = $InventoryInId; $detailsAddData['linkNo'] = $InventoryInAddData['no']; $detailsAddData['materielId'] = $v['materielId']; $detailsAddData['materielName'] = $v['materielName']; $detailsAddData['materielCode'] = $v['materielCode']; $detailsAddData['skuId'] = $v['skuId']; $detailsAddData['num'] = $v['num']; $detailsAddData['otherNum'] = $v['otherNum']; $detailsAddData['unitPrice'] = $v['unitPrice']; $detailsAddData['unitName'] = isset($v['unitName']) ? $v['unitName'] : ''; $detailsAddData['skuName'] = isset($v['skuName']) ? $v['skuName'] : ''; $detailsAddData['totalPrice'] = bcmul($detailsAddData['unitPrice'], $detailsAddData['num'], 4); $detailsAddData['createTime'] = time(); $detailsAddData['updateTime'] = time(); $InventoryInDetailsAddData[] = $detailsAddData; } //插入详情表 $dbResult = $this->objDInventoryInDetails->insert($InventoryInDetailsAddData, true); if($dbResult === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryInDetails->error(), ErrorCode::$dberror); } //增加es搜索 /* $modelResult = self::updateEsData($InventoryInAddData, $InventoryInId, true); if(!$modelResult->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); }*/ //删除redis $objCacheStock = new Stock($this->enterpriseId); $cacheResult = $objCacheStock->deleteCacheStatistics('InventoryIn'); if(!$cacheResult && $cacheResult !== 0){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail('删除缓存失败', ErrorCode::$paramError); } $beginStatus && $this->objDInventoryIn->commit(); return ResultWrapper::success($InventoryInId); } /** * 入库单明细删除 * */ public function deleteDetailByInventoryInId($params) { $updateData = [ 'deleteStatus' => StatusCode::$delete, 'updateTime' => time(), ]; $dbResult = $this->objDInventoryInDetails->update($updateData, ['linkId'=>$params['inventoryInId'],'id'=>$params['inventoryInDetailIds']]); if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryInDetails->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * 入库单驳回 * @param $params */ public function rejectInventory($params) { // 获取入库单主单据信息 $InventoryInData = $this->objDInventoryIn->get(['id' => $params['inventoryInId']] ); if($InventoryInData === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } // 删除 $updateData = [ 'deleteStatus' => StatusCode::$delete, 'updateTime' => time(), ]; // 删除入库单主单据信息 $InventoryIn = $this->objDInventoryIn->update($updateData,['id' => $params['inventoryInId']] ); if($InventoryIn === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } // 删除入库详情数据 $dbResult = $this->objDInventoryInDetails->update($updateData, ['linkId'=>$params['inventoryInId'],'id'=>$params['inventoryInDetailIds']]); if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryInDetails->error(), ErrorCode::$dberror); } unset($updateData); // 修改采购表(审核状态改为待审核) $purchaseUpdateData = [ 'auditStatus' => StatusCode::$auditStatus['auditing'], 'updateTime' => time(), ]; // 采购表 $objDPurchase = new DPurchase(); $objDPurchase->setTable($objDPurchase->get_Table().'_'.$this->enterpriseId); $purchaseResult = $objDPurchase->update($purchaseUpdateData, ['id' => $InventoryInData['originId']]); if($purchaseResult === false){ return ResultWrapper::fail($objDPurchase->error(), ErrorCode::$dberror); } if($dbResult && $purchaseResult == true){ return ResultWrapper::success($purchaseResult); } } /** * 入库审核 * @param $params * @return ResultWrapper * @throws Exception */ public function updateInventoryInStatus($params) { $where['id'] = $params['id']; unset($params['id']); $updateDetails = isset($params['details']) ? $params['details'] : []; unset($params['details']); if(empty($params['inNumTotal']) || $params['inNumTotal'] == 0){ return ResultWrapper::fail('入库数量为空', ErrorCode::$paramError); } unset($params['inNumTotal']); $params['updateTime'] = time(); $params['auditTime'] = time(); $params['auditStatus'] = StatusCode::$auditStatus['auditPass']; // 获取入库单主单据信息 $InventoryInData = $this->objDInventoryIn->get($where); if($InventoryInData === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } if(empty($InventoryInData)){ return ResultWrapper::fail('要审核的单据不存在', ErrorCode::$contentNotExists); } if($InventoryInData['auditStatus'] == StatusCode::$auditStatus['auditPass']){ return ResultWrapper::fail('该单据已审核', ErrorCode::$paramError); } // 判断商城设置 是否开启保质期 $objEnterpriseCache = new EnterpriseCache(); $cacheResult = $objEnterpriseCache->getEnterpriseData($this->enterpriseId, 'shelfLifeSetUp'); if($cacheResult == StatusCode::$standard){ if(empty($updateDetails)){ return ResultWrapper::fail('details参数错误', ErrorCode::$paramError); } foreach($updateDetails as $value){ if(empty($value['productionData'])){ return ResultWrapper::fail('productionData参数错误', ErrorCode::$paramError); } if(empty($value['inCost']) || $value['inCost'] <= 0){ return ResultWrapper::fail('入库成本参数错误', ErrorCode::$paramError); } if(empty($value['inCostTotal']) || $value['inCostTotal'] <= 0){ return ResultWrapper::fail('入库成本参数错误', ErrorCode::$paramError); } } } $beginStatus = $this->objDInventoryIn->beginTransaction(); // 修改入库状态为已审核 if(!empty($updateDetails)){ // 用实际入库成本重新计算采购入库单总成本 $params['amount'] = 0; // 用实际入库数量重新计算采购入库单sku数量 $params['materielNum'] = 0; //修改单据详情 生产日期 foreach($updateDetails as $value){ if( isset($value['id']) ){ $update = [ 'productionData' => getArrayItem($value,'productionData',0), 'inNum' => $value['inNum'], 'otherNum' => $value['otherNum'], 'areaId' => $value['areaId'], 'areaName' => $value['areaName'], 'areaCode' => $value['areaCode'], 'storageLocationId' => $value['storageLocationId'], 'storageLocationName' => $value['storageLocationName'], 'storageLocationCode' => $value['storageLocationCode'], 'inCost' => $value['inCost'], 'inCostTotal' => $value['inCostTotal'] ]; $dbResult = $this->objDInventoryInDetails->update($update, ['id'=>$value['id']]); if($dbResult === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryInDetails->error(), ErrorCode::$dberror); } }else{ $dbResult = $this->objDInventoryInDetails->insert($value); if($dbResult === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryInDetails->error(), ErrorCode::$dberror); } } $params['amount'] += $value['inCostTotal']; $params['materielNum'] += 1; } } $dbResult = $this->objDInventoryIn->update($params, $where); if($dbResult === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $returnData = $dbResult; unset($dbResult); //合并修改数据 $InventoryInData = array_merge($InventoryInData, $params); //修改es /* $esId = self::esId($InventoryInData['id']); $esResult = $this->objDInventoryIn->esupdateTypeFieldVaule($params, $esId); if(!$esResult){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($esResult, ErrorCode::$paramError); } unset($esResult);*/ // 获取入库单详情信息 $condition = [ 'linkId' => $where['id'], 'linkNo' => $InventoryInData['no'], 'deleteStatus' => StatusCode::$standard, ]; $InventoryInDetailsData = $this->objDInventoryInDetails->select($condition); if($InventoryInDetailsData === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryInDetails->error(), ErrorCode::$dberror); } if(empty($InventoryInDetailsData)){ return ResultWrapper::fail('单据详情数据为空', ErrorCode::$contentNotExists); } $InventoryInData['Details'] = $InventoryInDetailsData; $inNumData = []; $skuIds = []; $skuCostParse = []; foreach($InventoryInData['Details'] as &$value){ $skuIds[] = $value['skuId']; if($value['inNum'] <= 0 || $value['inCost'] <= 0){ unset($value); }else{ $value['num'] = $value['inNum']; $value['unitPrice'] = $value['inCost']; $value['totalPrice'] = $value['inCostTotal']; $inNumData[$value['skuId']]['inNum'] = bcadd($inNumData[$value['skuId']]['inNum'],$value['inNum'],4); $skuCostParse[$value['skuId']] = $value['unitPrice']; unset($value['inNum'], $value['inCost'], $value['inCostTotal']); } } unset($value); //判断如果是调拨入库 查询出库仓库id传过去 if($InventoryInData['type'] == StatusCode::$orderType['allocateIn']){ //查询调拨原始单据信息 $objMAllocate = new MAllocate($this->enterpriseId,$this->onlineUserId); $modelResult = $objMAllocate->getAllocate(['id'=>$InventoryInData['originId']]); if(!$modelResult->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } if(empty($modelResult)){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail('调拨单数据为空', ErrorCode::$paramError); } $allocateData = $modelResult->getData(); unset($modelResult); $InventoryInData['outWarehouseId'] = $allocateData['warehouseId']; } //查询仓库 $objMWarehouse = new MWarehouse($this->enterpriseId); $modelResult = $objMWarehouse->getWarehouse(['id' => $InventoryInData['warehouseId'], 'deleteStatus' => StatusCode::$standard]); if(!$modelResult->isSuccess()){ return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $warehouseData = $modelResult->getData(); unset($modelResult); if(empty($warehouseData)){ return ResultWrapper::fail('仓库查询失败', ErrorCode::$paramError); } //获取计算成本方式 $costType = $warehouseData['costType']; // 操作库存 $result = $this->objMInventory->updateInventory($InventoryInData, $costType); if(!$result->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($result->getData(), $result->getErrorCode()); } //采购入库 if($InventoryInData['type'] == StatusCode::$orderType['purchaseIn'] || $InventoryInData['type'] == StatusCode::$orderType['merchantPurchaseIn']){ //回写负库存商品出库成本 //查询每个skuId采购入库 审核成功的记录 //判断该sku是否是第一次采购 //如果是第一次采购 //查询该skuId出库记录 回写出库成本 //修改流水记录的出库成本 /*//回写负库存商品出库成本 //查询第一次采购的skuId $sql = 'select d.skuId,count(d.skuId) as num from qianniao_inventory_in_'.$this->enterpriseId.' i left join qianniao_inventory_in_details_'.$this->enterpriseId.' d on i.id = d.linkId where d.skuId in('.implode(',', $skuIds).') and i.auditStatus = 2 and i.warehouseId = '.$InventoryInData['warehouseId'].' group by d.skuId having count(d.skuId) < 2'; $dbResult = $this->objDInventoryIn->query($sql); if($dbResult === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $updateCostSkuData = $dbResult; unset($dbResult); if(!empty($updateCostSkuData)){ $updateCostSkuIds = array_column($updateCostSkuData, 'skuId'); //修改库存流水成本 $modelResult = $this->objMInventory->updateSaleOrderOutCostPrise($InventoryInData['warehouseId'], $updateCostSkuIds, $skuCostParse); if(!$modelResult->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $updateCostArray = $modelResult->getData(); unset($modelResult); if(!empty($updateCostArray)){ //回写订单出库成本 $objMOrder = new MOrder($this->onlineUserId, $this->enterpriseId); $modelResult = $objMOrder->updateCostPriceBySku($updateCostArray['orderId'], $updateCostArray['updateOrder']); if(!$modelResult->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } } }*/ //单据回写 修改采购订单入库状态,入库数量 $objMPurchase = new MPurchase($this->onlineUserId ,$this->enterpriseId); $updatePurchase = [ 'inStatus' => StatusCode::$standard, 'details' => $inNumData ]; $modelResult = $objMPurchase->updatePurchaseData($updatePurchase, ['id' => $InventoryInData['originId']]); if(!$modelResult->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } unset($modelResult); // 采购入库 推送生成应付异步任务 if($InventoryInData['type'] == StatusCode::$orderType['purchaseIn']){ $i = 1; do { $postData = [ 'topicName' => 'MyJob', 'topicClass' => 'Jobs\Model\MTopic\Finance\MPayable', 'topicMethon' => 'createPayable', 'topicMethonParams' => [ 'userCenterId' => $this->onlineUserId, 'enterpriseId' => $this->enterpriseId, 'id' => $InventoryInData['originId'], 'inventoryInId' => $where['id'], 'type' => StatusCode::$orderType['purchaseIn'], ], ]; $url = QIANNIAO_QUEUE . '/CAddJob/add'; $result = request($url, $postData); $i++; } while ($result['httpcode'] != 200 && $i <= 3); } } if($InventoryInData['type'] == StatusCode::$orderType['saleReturnIn']){ //查出源订单的userCenterId $stockDbName = Factory::config()->get('db.stock.dbname'); $defaultDbName = Factory::config()->get('db.default.dbname'); if (!$stockDbName || !$defaultDbName) { $this->objDInventoryIn->rollBack(); return ResultWrapper::fail('dbname获取错误', ErrorCode::$dberror); } $sql = 'select a.originId,b.id as orderId,b.userCenterId from `'. $stockDbName .'`.'. $this->objDInventoryIn->get_Table() .' as a join `'. $defaultDbName .'`.qianniao_order_index_'. $this->enterpriseId .' as b on a.originId = b.id and a.originId = '. $InventoryInData['originId'] .' limit 1'; $userResult = $this->objDInventoryIn->query($sql); if ($userResult === false) { $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $user = array_shift($userResult); // 查询订单数据 $objMOrder = new MOrder($this->onlineUserId, $this->enterpriseId, $user['userCenterId']); $orderTableName = $objMOrder->getOrderTable($this->enterpriseId, $user['userCenterId']); $objDOrder = new DOrder('default'); $objDOrder->setTable($orderTableName); $order = $objDOrder->get($InventoryInData['originId']); if($order === false){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($objDOrder->error(), ErrorCode::$dberror); } if(empty($order)){ return ResultWrapper::fail('订单数据为空', ErrorCode::$contentNotExists); } // 已经支付的订单生成退款单 if($order['payStatus'] == StatusCode::$standard){ // 生成财务退款单 $financeRefundData = [ 'originId' => getArrayItem($InventoryInData,'originId',''), 'originNo' => getArrayItem($InventoryInData,'originNo',''), 'sourceId' => getArrayItem($InventoryInData,'id',0), 'sourceNo' => getArrayItem($InventoryInData,'no',''), 'refundTime' => time(), 'createTime' => time(), 'unitId' => getArrayItem($order,'customerId',0), 'unitName' => getArrayItem($order,'customerName',0), 'currentAccountName' => getArrayItem($order,'customerName',''), 'financeType' => '订单退货退款', 'financeTypeId' => 1, 'payType' =>getArrayItem($order,'payType',''), 'shopId' => getArrayItem($order,'shopId',0), 'shopName' => getArrayItem($order,'shopName',0), 'money' => $InventoryInData['amount'], 'operatorId' => $this->onlineUserId, 'type' => StatusCode::$standard, 'auditStatus' => StatusCode::$auditStatus['auditing'], 'remark' => '订单编号:'. $order['no'].'退货,退款金额:'.$InventoryInData['amount'] ]; // 根据订单支付方式规划退款账户 $objMAccount = new MAccount($this->enterpriseId,$this->onlineUserId); $payType = explode(',', $order['payType']); // 包含余额组合支付方式统一返回余额,其他原路返回 if( in_array(StatusCode::$payType['balance'],$payType) ){ $financeAccountData = $objMAccount->getDefaultAccount(StatusCode::$payType['balance']); }else{ $financeAccountData = $objMAccount->getDefaultAccount($payType); } if(!$financeAccountData->isSuccess()){ return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode()); } $financeAccountData = $financeAccountData->getData(); $financeRefundData['accountList'] = [ [ 'accountId' => $financeAccountData['id'], 'accountNumber' => $financeAccountData['accountNumber'], 'accountName' => $financeAccountData['name'], 'money' => $InventoryInData['amount'], ] ]; $objMRefund = new MRefund($this->enterpriseId,$this->onlineUserId); $result = $objMRefund->addRefund($financeRefundData); if(!$result->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($objMRefund->getData(),$objMRefund->getErrorCode()); } } // 生成应收单数据 $i = 1; do { $postData = [ 'topicName' => 'MyJob', 'topicClass' => 'Jobs\Model\MTopic\Finance\MReceivable', 'topicMethon' => 'createReceivable', 'topicMethonParams' => [ 'userCenterId' => $user['userCenterId'], 'enterpriseId' => $this->enterpriseId, 'id' => $InventoryInData['id'], 'type' => StatusCode::$orderType['saleReturnIn'], ], ]; $url = QIANNIAO_QUEUE . '/CAddJob/add'; $result = request($url, $postData); $i++; } while ($result['httpcode'] != 200 && $i <= 3); } //销售退货单入库状态回写 if($InventoryInData['type'] == StatusCode::$orderType['saleReturnIn']){ $objMOrderReturn = new MOrderReturn($this->enterpriseId, $this->onlineUserId); $modelResult = $objMOrderReturn->updateOrderReturnData(['inStatus'=>StatusCode::$standard, 'updateTime'=>time()], ['no'=>$InventoryInData['sourceNo']]); if(!$modelResult->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } } // 修改仓库初始化状态(有采购之后,仓库不让初始化) if($warehouseData['beginningStatus'] == StatusCode::$standard){ $modelResult = $objMWarehouse->updateWarehouse(['beginningStatus' => StatusCode::$delete, 'updateTime' => time()], ['id' => $InventoryInData['warehouseId']]); if(!$modelResult->isSuccess()){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } unset($modelResult); } // 删除redis采购入库总数统计项 $objCacheStock = new Stock($this->enterpriseId); $cacheResult = $objCacheStock->deleteCacheStatistics('InventoryIn'); if(!$cacheResult && $cacheResult !== 0){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail('删除缓存失败', ErrorCode::$paramError); } $beginStatus && $this->objDInventoryIn->commit(); return ResultWrapper::success($returnData); } /** * 入库列表 * @param $selectParams * @param $export //导出标识字段 * @return ResultWrapper */ public function getAllInventoryIn($selectParams,$export = 0) { $limit = $selectParams['limit']; unset($selectParams['limit']); $offset = $selectParams['offset']; unset($selectParams['offset']); $selectParams['deleteStatus'] = StatusCode::$standard; $type = $selectParams['type']; $selectParams = self::formatSqlWhere($selectParams); if($export){ $whereSql = ''; if(isset($type) && !empty($type)){ $whereSql = ' i.type= '.$type.' and '; } $linkedTab =' qianniao_inventory_in_'.$this->enterpriseId.' as i left join qianniao_inventory_in_details_'.$this->enterpriseId.' as d ON i.id=d.linkId '; $where = $whereSql.' i.deleteStatus='.StatusCode::$standard.' ORDER BY i.createTime desc'; $sql ='select * from '.$linkedTab.' where '.$where; $exportDbResult = $this->objDInventoryIn->query($sql); if ($exportDbResult === false) { return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $inventoryInData = parent::formatOrderMan($this->enterpriseId, $exportDbResult); self::exportInventoryIn($inventoryInData); exit; } $dbResult = $this->objDInventoryIn->select($selectParams, '*', 'createTime desc', $limit, $offset); if ($dbResult === false) { return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $total = $this->objDInventoryIn->count($selectParams); $return = [ 'data' => parent::formatOrderMan($this->enterpriseId, $dbResult), 'total' => ($total) ? intval($total) : 0, ]; if($return === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); }else{ return ResultWrapper::success($return); } } /** * 入库导出方法 * @param $inventoryInData */ public function exportInventoryIn($inventoryInData) { //导出到本地 header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=入库管理.csv"); header('Cache-Control: max-age=0'); $fp = fopen('php://output', 'a'); $head = ['ID', '入库单号','仓库名称', '入库类型', '入库商品','审核人员','制单人员', '来源单号', '审核状态', '制单日期','商品名称','商品编码','规格','采购数量','采购成本','采购总成本','入库数量','其他单位','入库成本','入库总成本','生产日期','库区库位','商品条码','货架编码']; //定义标题 foreach ($head as $i => $v) { $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码 } fputcsv($fp, $head); $limit = 10000; $num = 0;//计数器 foreach ($inventoryInData as $value) {//循环数据 $num++; if ($num == $limit) { ob_flush();//释放内存 flush(); } $rows['id'] = isset($value['linkId']) ? $value['linkId'] : null; // ID $rows['no'] = isset($value['no']) ? $value['no'] : null; // 入库单号 $rows['warehouseName'] = isset($value['warehouseName']) ? $value['warehouseName'] : null; // 仓库名称 $rows['typeName'] = isset($value['typeName']) ? $value['typeName'] : null; // 入库类型 $rows['materielNum'] = isset($value['materielNum']) ? $value['materielNum'] : null; // 入库商品 $rows['auditName'] = isset($value['auditName']) ? $value['auditName'] : null; // 审核人员 $rows['operatorName'] = isset($value['operatorName']) ? $value['operatorName'] : null; // 制单人员 $rows['sourceNo'] = isset($value['sourceNo']) ? $value['sourceNo'] : null; // 来源单号 $rows['auditStatus'] = isset($value['auditStatus'])&& $value['auditStatus']== 1 ?'未审核':'已审核';// 审核状态 $rows['createTime'] = isset($value['createTime']) ? date("Y-m-d H:i:s",$value['createTime']) : null; // 制单日期date('Y-m-d H:i:s') $rows['materielName'] = isset($value['materielName']) ? $value['materielName'] : null; // 商品名称 $rows['materielCode'] = isset($value['materielCode']) ? $value['materielCode'] : null; // 商品编码 $rows['specs'] = !empty($value['unitName']) && !empty($value['skuName']) ? $value['unitName'].';'.$value['skuName'] : $value['unitName']; // 规格 $rows['num'] = isset($value['num']) ? $value['num'] : null; // 采购数量 $rows['unitPrice'] = isset($value['unitPrice']) ? $value['unitPrice'] : null; // 采购成本 $rows['totalPrice'] = isset($value['totalPrice']) ? $value['totalPrice'] : null; // 采购总成本 $rows['inNum'] = isset($value['inNum']) ? $value['inNum'] : null; // 入库数量 $rows['otherNum'] = isset($value['otherNum']) ? $value['otherNum'] : null; // 其他单位 $rows['inUnitPrice'] = isset($value['unitPrice']) ? $value['unitPrice'] : null; // 入库成本 $rows['inTotalPrice'] = isset($value['totalPrice']) ? $value['totalPrice'] : null; // 入库总成本 $rows['productionData'] = isset($value['productionData']) ? date("Y-m-d",$value['productionData']) : null; // 生产日期 $rows['storageLocationName'] = isset($value['storageLocationName']) ? $value['storageLocationName'] : null; // 库区库位 $rows['barCode'] = isset($value['barCode']) ? $value['barCode'] : null; // 商品条码 $rows['storage'] = isset($value['storage']) ? $value['storage'] : null; // 货架编码 foreach ($rows as $kk => $vv) { $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码 } fputcsv($fp, $rs); $rows = []; } } /** * 入库列表搜索 * @param $params * @return ResultWrapper * @throws Exception */ public function searchAllInventoryIn($params) { $defaultDSL = ['from' => $params['offset'],'size' => $params['limit'],'sort' => ['createTime' => ['order' => 'desc']]]; $selectParams = []; $selectParams[] = ['term' => ['deleteStatus' => StatusCode::$standard]]; $selectParams[] = ['term' => ['enterpriseId' => $this->enterpriseId]]; !empty($params['type']) && $selectParams[] = ['term' => ['type' => $params['type']]]; !empty($params['shopId']) && $selectParams[] = ['term' => ['shopId' => $params['shopId']]]; !empty($params['warehouseId']) && $selectParams[] = ['term' => ['warehouseId' => $params['warehouseId']]]; !empty($params['auditStatus']) && $selectParams[] = ['terms' => ['auditStatus' => is_array($params['auditStatus']) ? $params['auditStatus'] : [$params['auditStatus']]]]; (!empty($params['start']) && !empty($params['end'])) && $selectParams[] = ['range' => ['createTime' => ['gte' => $params['start'],'lte' => $params['end']]]]; !empty($params['search']) && $selectParams[] = ['multi_match' => ['fields' => ['no', 'operatorName'],'query' => $params['search'],'fuzziness' => 'AUTO']]; $dsl = []; !empty($selectParams) && $dsl['query']['bool']['must'][] = $selectParams; $dsl = array_merge($defaultDSL, $dsl); $dbResult = $this->objDInventoryIn->getSearchQueryDsl($dsl); if(isset($dbResult['error'])){ if($dbResult['error']['reason'] == 'no such index'){ return ResultWrapper::success(['data'=>[],'total'=>[]]); } return ResultWrapper::fail($dbResult, ErrorCode::$dberror); } $returnData = parent::formatEsSelectData($dbResult); $objMCommon = new MCommon(); foreach($returnData['data'] as &$value){ $value['typeName'] = $objMCommon->formatOrderSource($value['type']); } unset($value); return ResultWrapper::success($returnData); } /** * 入库统计 * @param $type * @param int $shopId * @return ResultWrapper * @throws Exception */ public function statisticsAllInventoryIn($type, $shopId = 0) { if($shopId){ $sql = "select `type`,count(id) as count from ".$this->objDInventoryIn->get_Table()." where deleteStatus = ".StatusCode::$standard." and shopId = ".$shopId." GROUP BY `type`"; $dbResult = $this->objDInventoryIn->query($sql); if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $typeData = []; foreach($dbResult as $value){ $typeData[$value['type']] = $value['count']; } $cacheData = []; foreach($type as $value){ $cacheData[] = [ 'type' => $value, 'count' => isset($typeData[$value]) ? $typeData[$value] : 0, ]; } return ResultWrapper::success($cacheData); } $cacheKey = 'InventoryIn'; $objCacheStock = new Stock($this->enterpriseId); $cacheData = []; //判断redis里有没有这个key $cacheResult = $objCacheStock->getCacheStatisticsCount($cacheKey); $issetCacheKey = $cacheResult; unset($cacheResult); foreach($type as $value){ $cacheResult = $objCacheStock->getCacheStatistics($value,$cacheKey); $cacheData[] = [ 'type' => $value, 'count' => $cacheResult ? $cacheResult : 0, ]; unset($cacheResult); } //如果有就拿出来 当做值返回 if($issetCacheKey) return ResultWrapper::success($cacheData); //如果没有 从数据库里查一遍 删除redis 存到redis 值返回 $sql = "select `type`,count(id) as count from ".$this->objDInventoryIn->get_Table()." where deleteStatus = ".StatusCode::$standard." GROUP BY `type`"; $dbResult = $this->objDInventoryIn->query($sql);//销售出库 if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $typeData = []; foreach($dbResult as $value){ $typeData[$value['type']] = $value['count']; } $cacheData = []; $cacheResult = $objCacheStock->deleteCacheStatistics($cacheKey); if(!$cacheResult && $cacheResult !== 0){ $this->objDInventoryIn->rollBack(); return ResultWrapper::fail('删除缓存失败', ErrorCode::$paramError); } unset($cacheResult); foreach($type as $value){ $cacheData[] = [ 'type' => $value, 'count' => isset($typeData[$value]) ? $typeData[$value] : 0, ]; if(isset($typeData[$value])){ $objCacheStock->createCacheStatistics($value,$typeData[$value], $cacheKey); } } return ResultWrapper::success($cacheData); } /** * 根据no单号查询入库信息 * @param $nos * @return ResultWrapper */ public function getAllInventoryInByNo($nos) { if(empty($nos)) return ResultWrapper::success($nos); $dbResult = $this->objDInventoryIn->select(['sourceNo'=>$nos], 'sourceNo,auditStatus'); if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } $formatData = []; foreach($dbResult as $value){ $formatData[$value['sourceNo']] = $value; } return ResultWrapper::success($formatData); } /** * 入库详情 * @param $params * @return ResultWrapper * @throws Exception */ public function getInventoryInInfo($params) { $params['deleteStatus'] = StatusCode::$standard; $dbResult = $this->objDInventoryIn->get($params); if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } if(empty($dbResult)){ return ResultWrapper::fail('未查询到入库单据', ErrorCode::$paramError); } $condition = [ 'linkId' => $dbResult['id'], 'deleteStatus' => StatusCode::$standard, ]; $dbResult['details'] = $this->objDInventoryInDetails->select($condition); if($dbResult['details'] === false){ return ResultWrapper::fail($this->objDInventoryInDetails->error(), ErrorCode::$dberror); } $dbResult = parent::formatOrderMan($this->enterpriseId,$dbResult); $objMPrintNum = new MPrintNum($this->enterpriseId); $dbResult['printNum'] = $objMPrintNum->getObjectPrintNum($dbResult['no'], StatusCode::$orderType['purchaseIn']); if($dbResult['type'] == StatusCode::$orderType['allocateIn']){ // 映射仓库名称 $objMAllocate = new MAllocate($this->enterpriseId,$this->onlineUserId); $data = $objMAllocate->getAllocateInfoByWarehouseName([$dbResult]); if(!$data->isSuccess()){ return ResultWrapper::fail($objMAllocate->error(), ErrorCode::$dberror); } $dbResult = $data->getData(); foreach ($dbResult as $key=>$value){ $dbResult[$key]['outWarehouseId'] = $dbResult[$key]['warehouseId']; $dbResult[$key]['outWarehouseName'] = $dbResult[$key]['warehouseName']; unset($dbResult[$key]['warehouseId']); unset($dbResult[$key]['warehouseName']); } $dbResult = array_pop($dbResult); } return ResultWrapper::success($dbResult); } /** * 查询入库数据 * @param $where * @return ResultWrapper */ public function getInventoryInData($where) { $dbResult = $this->objDInventoryIn->select($where); if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * 添加es * @param $data * @param $id * @param bool $type & false:修改 true:新增 * @return ResultWrapper */ public function updateEsData($data, $id, $type = false) { $addEsData = [ 'id' => $id, 'enterpriseId' => $this->enterpriseId, 'no' => isset($data['no']) ? StatusCode::$noPrefix[$data['type']].$data['no'] : false, 'sourceId' => isset($data['sourceId']) ? $data['sourceId'] : false, 'sourceNo' => isset($data['sourceNo']) ? StatusCode::$noPrefix[$data['source']].$data['sourceNo'] : false, 'originId' => isset($data['originId']) ? $data['originId'] : false, 'originNo' => isset($data['originNo']) ? StatusCode::$noPrefix[$data['source']].$data['originNo'] : false, 'materielNum' => isset($data['materielNum']) ? $data['materielNum'] : false, 'amount' => isset($data['amount']) ? $data['amount'] : false, 'warehouseId' => isset($data['warehouseId']) ? $data['warehouseId'] : false, 'warehouseName' => isset($data['warehouseName']) ? $data['warehouseName'] : false, 'operatorId' => isset($data['operatorId']) ? $data['operatorId'] : false, 'operatorName' => isset($data['operatorName']) ? $data['operatorName'] : false, 'auditId' => isset($data['auditId']) ? $data['auditId'] : false, 'auditName' => isset($data['auditName']) ? $data['auditName'] : false, 'deleteStatus' => isset($data['deleteStatus']) ? $data['deleteStatus'] : false, 'source' => isset($data['source']) ? $data['source'] : false, 'type' => isset($data['type']) ? $data['type'] : false, 'auditStatus' => isset($data['auditStatus']) ? $data['auditStatus'] : false, 'auditTime' => isset($data['auditTime']) ? $data['auditTime'] : false, 'createTime' => isset($data['createTime']) ? $data['createTime'] : false, 'updateTime' => isset($data['updateTime']) ? $data['updateTime'] : false, ]; foreach($addEsData as $key => $value){ if($value === false){ if($type){ return ResultWrapper::fail($key.'ES字段未设置', ErrorCode::$paramError); }else{ unset($addEsData[$key]); } } } $addEsData['remark'] = isset($data['remark']) ? $data['remark'] : ''; //创建es id $esId = self::esId($id); $result = $this->objDInventoryIn->addUpSearchIndexDocument($addEsData, $esId); // var_dump($result); if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) { return ResultWrapper::success(isset($result['_id']) ? $result['_id'] : false); } return ResultWrapper::fail($result['error']['reason'], ErrorCode::$paramError); } /** * 拼接es id * @param $id * @return string */ public function esId($id) { return 'EnterpriseId_' . $this->enterpriseId . '_InventoryInId_' . $id; } /** * 格式化入库es */ public function formatInventoryInEsData() { //查询列表数据 $dbResult = $this->objDInventoryIn->select([],'*'); if($dbResult === false){ return ResultWrapper::fail($this->objDInventoryIn->error(), ErrorCode::$dberror); } if(empty($dbResult)){ return ResultWrapper::fail('格式化数据为空', ErrorCode::$dberror); } //循环插入es foreach($dbResult as $value){ //增加es搜索 $modelResult = self::updateEsData($value, $value['id'], true); if(!$modelResult->isSuccess()){ return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } } return ResultWrapper::success('格式化成功'); } /** * 成本均摊 */ public function countPurchaseCost($params) { $total = 0; $num = 0; foreach($params['skuData'] as $value){ $total = bcadd($total, $value['money']); $num = bcadd($num, $value['num']); } $skuData = []; if($params['type'] == StatusCode::$standard){ $moneyOne = ceil( bcdiv($params['money'], $total,4) * 10000 / 100) / 100; // 保留两位小数向上取整 foreach($params['skuData'] as $value){ if($moneyOne > 0){ $skuData[$value['skuId']]['cost'] = bcdiv(bcadd($value['money'], bcmul($moneyOne,$value['money'])), $value['num'], 2); $skuData[$value['skuId']]['money'] = bcadd($value['money'], bcmul($moneyOne,$value['money'])); }else{ $skuData[$value['skuId']]['cost'] = $value['cost']; $skuData[$value['skuId']]['money'] = $value['money']; } } }else{ $numOne = ceil( bcdiv($params['money'], $num,4) * 10000 / 100) / 100; // 保留两位小数向上取整 foreach($params['skuData'] as $value){ if($numOne > 0){ $skuData[$value['skuId']]['cost'] = bcadd($value['cost'], $numOne); $skuData[$value['skuId']]['money'] = bcadd($value['money'], bcmul($numOne,$value['num'])); }else{ $skuData[$value['skuId']]['cost'] = $value['cost']; $skuData[$value['skuId']]['money'] = $value['money']; } } } return ResultWrapper::success($skuData); } }