true /** * @var OverviewCache */ private $objOverviewCache; /** * @var string */ private $orderStatisticsTableName = 'order_statistics'; /** * @var MAccount */ private $objMAccount; /** * @var MReceived */ private $objMReceived; /** * @var ActivityLimitCache */ private $objActivityLimitCache; /** * @var SaleOrder 销售单 */ private $objSaleOrder; /** * @var bool 销售单是否打印小票 */ private $isEnablePrint = false; /** * @var DOrderReceive */ private $objDOrderReceive; /** * @var DCustomer */ private $objDCustomer; /** * @var int */ private $loginUserCenterId; /** * @var array */ private $expressMap = [ 'express_hundred' => 'kuaidi100', 'express_bird' => 'kdniao' ]; /** * @var bool */ private $isCashier; /** * @var MProcessSetting */ private $objMProcessSetting; use TStdOrder; /** * MOrder constructor. * @param $onlineUserId * @param $onlineEnterpriseId * @param null $loginUserCenterId * @param bool $isFront * @throws \Exception */ public function __construct($onlineUserId, $onlineEnterpriseId, $loginUserCenterId = null, $isFront = false, $isCashier = false) { $this->isCashier = $isCashier; $this->isFront = $isFront; $this->onlineUserId = $onlineUserId; $this->onlineEnterpriseId = $onlineEnterpriseId; $this->loginUserCenterId = $loginUserCenterId; parent::__construct($this->onlineEnterpriseId, $loginUserCenterId); $this->objDOrder = new DOrder('default'); self::orderSubTable($onlineEnterpriseId, $onlineUserId); $this->objDOrderIndex = new DOrderIndex(); $this->objDOrderGoods = new DOrderGoods('default'); $this->objDOrderReceive = new DOrderReceive(); $this->objDOrderStatistics = new DOrderStatistics('default'); $this->objMAccount = new MAccount($onlineEnterpriseId, $onlineUserId); $this->objMReceived = new MReceived($onlineEnterpriseId, $onlineUserId); $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $this->objDOrderStatistics->setTable($this->objDOrderStatistics->get_Table() . '_' . $this->onlineEnterpriseId); $this->objDOrder->setSearchIndex('order_search')->setType('order'); $this->objActivityLimitCache = new ActivityLimitCache($this->onlineEnterpriseId); $this->objOverviewCache = new OverviewCache(); $this->objSaleOrder = new SaleOrder(); $this->objDCustomer = new DCustomer(); $this->objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId); $this->objMProcessSetting = new MProcessSetting($this->onlineEnterpriseId); } /** * 订单分表 分表规则:企业id_(客户/200000) * @param $enterpriseId (企业id) * @param $userId (用户id) * @throws \Exception */ public function orderSubTable($enterpriseId, $userId) { $tableName = $this->objDOrder->getTableName('qianniao_order_' . $enterpriseId, $userId, $this->cutTable); self::existsTable($tableName); $this->objDOrder->setTable($tableName); } /** * 获取订单表表名 */ public function getOrderTable($enterpriseId, $userId){ return $this->objDOrder->getTableName('qianniao_order_' . $enterpriseId, $userId, $this->cutTable); } /** * 统计订单信息 * * @param $data * @param $className */ private static function noticeStatistics($data, $className) { $i = 1; do { $postData = [ 'topicName' => 'MyJob', 'topicClass' => "Jobs\Model\MTopic\Order\\" . $className, 'topicMethon' => 'push', 'topicMethonParams' => [ 'userCenterId' => $data['userCenterId'], 'enterpriseId' => $data['enterpriseId'], 'customerId' => $data['customerId'], 'no' => $data['no'], 'noticeType' => $data['noticeType'], ], ]; $url = QIANNIAO_QUEUE . '/CAddJob/add'; $result = request($url, $postData); $i++; } while ($result['httpcode'] != 200 && $i <= 3); } /** * 分表后缀+月日+订单id * @param $orderId * @return string */ private function createVerifyCode($orderId) { $fix = ceil($this->onlineUserId / $this->cutTable); return $fix . '-' . date('nj') . '-' . $orderId; } /** * Doc: (des="") * User: XMing * Date: 2020/12/25 * Time: 2:11 下午 * @param $data * @return ResultWrapper */ public function checkLimit($data) { foreach ($data as $goods) { if (isset($goods['activityId'])) { //获取活动商品剩余数量 $surplusNum = $this->objActivityLimitCache->getLen($goods['activityId'], $goods['goodsId'], $goods['skuId']); if ($surplusNum < $goods['buyNum']) { return ResultWrapper::fail($goods['title'] . '活动剩余数量不足', ErrorCode::$paramError); } } } return ResultWrapper::success($data); } /** * Doc: (des="订单编辑") * User: XMing * Date: 2020/11/5 * Time: 10:07 上午 * @param array $params * @param $id * @return ResultWrapper * @throws \Exception */ public function edit(array $params, $id): ResultWrapper { $orderIndex = $this->objDOrderIndex->get($id); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError); } /*if ($orderIndex['payStatus'] == StatusCode::$standard) { return ResultWrapper::fail('订单已支付,不能编辑', ErrorCode::$paramError); } if ($orderIndex['auditStatus'] != StatusCode::$auditStatus['auditing']) { return ResultWrapper::fail('订单已审核不能编辑', ErrorCode::$paramError); }*/ if ( in_array($orderIndex['orderStatus'], [StatusCode::$orderStatus['waitReceive'], StatusCode::$orderStatus['finish'], StatusCode::$orderStatus['close']]) ) { return ResultWrapper::fail('此订单不能编辑', ErrorCode::$paramError); } $fix = ceil((empty($params['userCenterId']) ? 1 : $params['userCenterId']) / $this->cutTable); $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix); $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix); $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId); $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId); $customerResult = self::getCustomerInfoByUserCenterId($params['userCenterId']); if (!$customerResult->isSuccess()) { return ResultWrapper::fail($customerResult->getData(), $customerResult->getErrorCode()); } $customer = $customerResult->getData(); isset($customer['customerType']) && $params['customerType'] = $customer['customerType']; isset($customer['salesManId']) && $params['salesManId'] = $customer['salesManId']; isset($customer['salesManName']) && $params['salesManName'] = $customer['salesManName']; $params['customerOwe'] = $objMCustomerBalance->getCustomerBalance($customer['id']);//获取客户当前欠款 $address = []; $selfRule = []; switch ($params['deliveryType']) { case StatusCode::$deliveryType['goodsDelivery']: $addressResult = self::getAddressInfo($params['addressId']); if (!$addressResult->isSuccess()) { return ResultWrapper::fail($addressResult->getData(), $addressResult->getErrorCode()); } $address = $addressResult->getData(); break; case StatusCode::$deliveryType['selfMention']: $selfRuleResult = self::getSelfRuleData($params['selfRuleId']); if (!$selfRuleResult->isSuccess()) { return ResultWrapper::fail($selfRuleResult->getData(), $selfRuleResult->getErrorCode()); } $selfRule = $selfRuleResult->getData(); break; } $status = $this->objDOrder->beginTransaction(); $updateIndexResult = $this->objDOrderIndex->update( [ 'userCenterId' => isset($params['userCenterId']) ? $params['userCenterId'] : 0, 'deliveryType' => isset($params['deliveryType']) ? $params['deliveryType'] : 0, 'customerId' => isset($params['customerId']) ? $params['customerId'] : 0, 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '', 'expressName' => isset($params['expressName']) ? $params['expressName'] : '', 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0, 'selfRuleId' => isset($params['selfRuleId']) ? $params['selfRuleId'] : 0, 'updateTime' => time(), ], $id ); if ($updateIndexResult === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $updateOrder = [ 'customerName' => isset($params['customerName']) ? $params['customerName'] : '', 'customerId' => isset($params['customerId']) ? $params['customerId'] : 0, 'deliveryType' => isset($params['deliveryType']) ? $params['deliveryType'] : 0, 'remark' => isset($params['remark']) ? $params['remark'] : '', 'salesManId' => isset($params['salesManId']) ? $params['salesManId'] : 0, 'salesManName' => isset($params['salesManName']) ? $params['salesManName'] : '', 'customerType' => isset($params['customerType']) ? $params['customerType'] : 0, 'userCenterId' => isset($params['userCenterId']) ? $params['userCenterId'] : 0, 'customerOwe' => isset($params['customerOwe']) ? $params['customerOwe'] : 0, 'preferential' => isset($params['preferential']) ? $params['preferential'] : 0, 'vipDiscount' => isset($params['vipDiscount']) ? $params['vipDiscount'] : 0, 'expressMoney' => isset($params['expressMoney']) ? $params['expressMoney'] : 0, 'expressName' => isset($params['expressName']) ? $params['expressName'] : '', 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0, 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '', 'selfRuleId' => isset($params['selfRuleId']) ? $params['selfRuleId'] : 0, 'originPayAmount' => isset($params['originPayAmount']) ? $params['originPayAmount'] : 0, 'payAmount' => isset($params['payMoney']) ? $params['payMoney'] : 0, 'totalMoney' => isset($params['totalMoney']) ? $params['totalMoney'] : 0, 'receivedMoney' => isset($params['receivedMoney']) ? $params['receivedMoney'] : 0, "accountList" => isset($params['accountList']) ? json_encode($params['accountList']) : null, "currentAccountName" => isset($params['currentAccountName']) ? $params['currentAccountName'] : '', "totalReduceMoney" => isset($params['totalReduceMoney']) ? $params['totalReduceMoney'] : 0, "selfRuleData" => empty($selfRule) ? null : json_encode($selfRule), "updateTime" => time(), ]; $updateOrderResult = $this->objDOrder->update($updateOrder, $id); if ($updateOrderResult === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (!empty($address)) { $updateReceiveResult = $this->objDOrderReceive->update([ 'customerId' => $address['customerId'], 'customerCode' => $address['customerCode'], 'realName' => $address['name'], 'mobile' => $address['mobile'], 'address' => $address['address'], 'provinceCode' => $address['provinceCode'], 'cityCode' => $address['cityCode'], 'districtCode' => $address['districtCode'], 'updateTime' => time() ], ['orderId' => $id]); if ($updateReceiveResult === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror); } } //编辑商品 if ($orderIndex['payStatus'] != StatusCode::$standard || $orderIndex['auditStatus'] != StatusCode::$auditStatus['auditPass']) { //解锁库存 $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId); $unlockResult = $objMInventory->unlockInventory([$id], StatusCode::$orderType['saleOrder'], $orderIndex['createTime']); if (!$unlockResult->isSuccess()) { $this->objDOrder->rollBack(); Logger::logs(E_USER_ERROR, '编辑订单,库存解锁失败', __CLASS__, __LINE__, $unlockResult->getData()); return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror); } $editResult = $objMOrderGoods->edit($params, $id,$orderIndex['no']); if (!$editResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($editResult->getData(), $editResult->getErrorCode()); } } /* //跟新es $_id = self::createEsDocumentId($id); $this->objDOrder->esupdateTypeFieldVaule($updateOrder, $_id);*/ if ($status){ $this->objDOrder->commit(); } return ResultWrapper::success(true); } /** * Doc: (des="代客下单,销售订单") * User: XMing * Date: 2020/12/19 * Time: 2:38 下午 * @param $params * @return ResultWrapper * @throws \Exception */ public function add($params): ResultWrapper { $params['orderType'] = getArrayItem($params,'orderType',StatusCode::$orderType['saleOrder']); $goodsNameStr = self::createGoodsName($params['lists']); $commonParamsResult = self::formatCommonParams($params); // 格式化订单关联数据 if (!$commonParamsResult->isSuccess()){ return ResultWrapper::fail($commonParamsResult->getData(),$commonParamsResult->getErrorCode()); } $params = $commonParamsResult->getData(); $lists = $params['lists']; unset($params['lists']); $groupShopDataResult = self::buildGoodsByShop($lists,$params); if (!$groupShopDataResult->isSuccess()){ return ResultWrapper::fail($groupShopDataResult->getData(),$groupShopDataResult->getErrorCode()); } $shopGoodsData = $groupShopDataResult->getData(); //锁定库存 查询商铺对应的仓库 $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $modelResult = $objMShop->getShopDataByShopIds(array_column($shopGoodsData, 'shopId')); // 根据shopIds获取商铺数据 if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $shopMap = $modelResult->getData(); $buildGroupResult = self::groupSupplierOrderData($shopGoodsData,$params,$shopMap); // 将商品数据按照指定的字段分组 if (!$buildGroupResult->isSuccess()){ return ResultWrapper::fail($buildGroupResult->getData(),$buildGroupResult->getErrorCode()); } $buildGroup = $buildGroupResult->getData(); $insertOrderResult = self::insertOrder($buildGroup,$params); if (!$insertOrderResult->isSuccess()){ return ResultWrapper::fail($insertOrderResult->getData(),$insertOrderResult->getErrorCode()); } $orderIds = $insertOrderResult->getData(); /* 拣货信息 */ /* 功能临时屏蔽 $orderNum = 0; $notOutNum = 0; $notPickingNum = 0; $otherNum = 0; foreach ($lists as $listKey => $listValue){ $notOutNum = bcadd($notOutNum,$listValue['buyNum'],4); $notPickingNum = bcadd($notPickingNum,$listValue['buyNum'],4); $otherNum = bcadd($otherNum,$listValue['otherNum']); $orderNum = bcadd($orderNum,$listValue['buyNum']); } //组装订单拣货信息 $orderPickingDate = [ 'orderId' => $orderIds[0], 'sort' => 0, 'outNum' => 0, 'notOutNum' => $notOutNum, 'orderNum' => $orderNum, 'notPickingNum' => $notPickingNum, 'pickingNum' => 0, 'outTime' => 0, 'otherNum' => $otherNum, 'mangeId' => getArrayItem($params,'operatorId',0), 'mangeName' => getArrayItem($params,'operatorName',''), ]; $objOrderPicking = new MOrderPicking($this->onlineUserId,$this->onlineEnterpriseId); $orderPickingResult = $objOrderPicking->addOrderPick($orderPickingDate); //临时注释 if(!$orderPickingResult->isSuccess()){ return ResultWrapper::fail($orderPickingResult->getData(), $orderPickingResult->getErrorCode()); }*/ parent::sendMessage($this->onlineEnterpriseId,'NewOrder'); $params['orderType'] == StatusCode::$orderType['saleOrder'] && self::runProcessNextAudit($orderIds); return ResultWrapper::success($orderIds); } /** * Doc: (des="商品名称") * User: XMing * Date: 2020/11/18 * Time: 3:27 下午 * @param $goods * @return string */ public static function createGoodsName($goods): string { $str = ''; foreach ($goods as $val){ if (isset($val['goodsName']) && !empty($val['goodsName'])){ $str .= (string)$val['goodsName'].' '; } } return $str; } /** * Doc: (des="执行订单的下一步操作") * User: XMing * Date: 2020/11/6 * Time: 5:03 下午 * @param array $ids 订单ids * @return ResultWrapper * @throws \Exception */ private function runProcessNextAudit(array $ids): ResultWrapper { Logger::logs(E_USER_ERROR,'订单自动审核',__CLASS__,__LINE__,$ids); if (empty($ids)){ return ResultWrapper::success(true); } $setResult = $this->objMProcessSetting->getProcessSettingByType(StatusCode::$processType['sales'],'audit'); if (!$setResult->isSuccess()){ Logger::logs(E_USER_ERROR,'获取流程配置出错',__CLASS__,__LINE__,$setResult->getData()); return ResultWrapper::fail($setResult->getData(),$setResult->getErrorCode()); } $set = $setResult->getData(); if (empty($set)){ Logger::logs(E_USER_ERROR,'配置为空',__CLASS__,__LINE__,''); return ResultWrapper::success(true); } if (isset($set['enableStatus']) && $set['enableStatus'] == StatusCode::$standard){ Logger::logs(E_USER_ERROR,'配置',__CLASS__,__LINE__,$set); return ResultWrapper::success(true); } foreach ($ids as $id){ $params = [ 'id' => $id, 'audit' => '自动审核', 'auditId' => $this->onlineUserId, 'auditStatus' => StatusCode::$auditStatus['auditPass'], ]; $auditResult = $this->updateAuditStatus($params); if (!$auditResult->isSuccess()){ Logger::logs(E_USER_ERROR,'自动审核订单出错',__CLASS__,__LINE__,$auditResult->getData()); return ResultWrapper::fail($auditResult->getData(),$auditResult->getErrorCode()); } } Logger::logs(E_USER_ERROR,'自动审核订单成功',__CLASS__,__LINE__,$ids); return ResultWrapper::success(true); } /** * Doc: (des="根据客户id获取客户信息") * User: XMing * Date: 2020/11/3 * Time: 2:11 下午 * @param int $id * @return ResultWrapper * @throws \Exception */ private function getCustomerInfoByUserCenterId(int $id): ResultWrapper { $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); //获取客户信息 $customerData = $objMCustomer->getCustomerInfoByUserCenterId($id); if (!$customerData->isSuccess()) { return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode()); } $customerData = $customerData->getData(); if (empty($customerData)) { return ResultWrapper::fail('未获取到客户信息', ErrorCode::$paramError); } return ResultWrapper::success($customerData); } /** * Doc: (des="根据id查询自提点信息") * User: XMing * Date: 2020/11/3 * Time: 11:49 上午 * @param int $id * @return ResultWrapper * @throws \Exception */ private function getSelfRuleData(int $id): ResultWrapper { $objMDeliverySetting = new MDeliverySetting($this->onlineUserId, $this->onlineEnterpriseId); $selfRuleDataResult = $objMDeliverySetting->getSelfRuleInfo($id); if (!$selfRuleDataResult->isSuccess()) { return ResultWrapper::fail($selfRuleDataResult->getData(), $selfRuleDataResult->getErrorCode()); } $selfRuleData = $selfRuleDataResult->getData(); $selfRuleData = isset($selfRuleData['setData']) ? $selfRuleData['setData'] : []; return ResultWrapper::success($selfRuleData); } /** * Doc: (des="根据id获取收货地址信息") * User: XMing * Date: 2020/11/3 * Time: 11:52 上午 * @param int $id * @return ResultWrapper */ private function getAddressInfo($id): ResultWrapper { $objMShippingAddress = new MShippingAddress($this->onlineEnterpriseId); $result = $objMShippingAddress->getShippingAddressInfo($id); if (!$result->isSuccess()) { return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } $addressData = $result->getData(); if (empty($addressData)) { return ResultWrapper::fail('未获取到收货地址信息', ErrorCode::$dberror); } return ResultWrapper::success($addressData); } /** * Doc: (des="小程序下单") * User: XMing * Date: 2020/12/18 * Time: 11:39 上午 * @param $params * @param $ip * @param $token * @param $auth * @return ResultWrapper * @throws \Exception */ public function addOrder($params, $ip, $token, $auth): ResultWrapper { $goodsData = getArrayItem($params,'goodsData',[]); unset($params['goodsData']); $shopGoodsData = getArrayItem($goodsData,'goodsData',[]);//商品数据 unset($goodsData['goodsData']); $common = array_merge($params,$goodsData); $params = $common;//公共数据 unset($common); $params['token'] = $token; $params['auth'] = $auth; $params['orderType'] = StatusCode::$orderType['saleOrder']; $params['userCenterId'] = $this->onlineUserId; $params['orderStatus'] = StatusCode::$orderStatus['waitPay']; // 货到付款和银行打款 修改订单状态为待发货 if( in_array($params['payType'],[StatusCode::$payType['cashPay']]) ){ $params['orderStatus'] = StatusCode::$orderStatus['waitDelivery']; } $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId); $params['outerTradeNo'] = $tmpOuterTradeNo; // 格式化订单关联数据 $commonParamsResult = self::formatCommonParams($params); if (!$commonParamsResult->isSuccess()){ return ResultWrapper::fail($commonParamsResult->getData(),$commonParamsResult->getErrorCode()); } $params = $commonParamsResult->getData(); //查询商铺对应的仓库 $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $modelResult = $objMShop->getShopDataByShopIds(array_column($shopGoodsData, 'shopId')); if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $shopMap = $modelResult->getData(); // 将商品数据按照指定的字段分组 $buildGroupResult = self::groupSupplierOrderData($shopGoodsData,$params,$shopMap); if (!$buildGroupResult->isSuccess()){ return ResultWrapper::fail($buildGroupResult->getData(),$buildGroupResult->getErrorCode()); } $buildGroup = $buildGroupResult->getData(); //mysql写入数据 $insertOrderResult = self::insertOrder($buildGroup,$params); if (!$insertOrderResult->isSuccess()){ return ResultWrapper::fail($insertOrderResult->getData(),$insertOrderResult->getErrorCode()); } $orderIds = $insertOrderResult->getData(); // 处理支付 $payResult = self::toPay($tmpOuterTradeNo,$params,$orderIds,$ip); if (!$payResult->isSuccess()){ return ResultWrapper::fail($payResult->getData(),$payResult->getErrorCode()); } // 发送新订单提醒 // parent::sendMessage($this->onlineEnterpriseId,'NewOrder'); $params['orderType'] == StatusCode::$orderType['saleOrder'] && self::runProcessNextAudit($orderIds); $customerData = $this->objDCustomer->get($buildGroup['orderIndex'][0]['customerId']); if ($customerData === false) { return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } if(isset($customerData['openId']) && !empty($customerData['openId'])){ $orderData = $this->objDOrder->get($orderIds); if($orderData === false){ return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if( empty($orderData) ){ return ResultWrapper::fail('查找不到该订单数据', ErrorCode::$contentNotExists); } foreach($buildGroup['order'] as $key => $value){ // 发送小程序订阅消息 $sendMessageData = [ 'character_string6' => [ 'value' => StatusCode::$noPrefix[1].'-'.$key ], // 订单编号 'amount10' => [ 'value' => $value['payAmount'] ], // 订单金额 'thing15' => [ 'value' => $buildGroup['orderReceive'][$key]['realName'] ], // 收货人姓名 'phone_number16' => [ 'value' => $buildGroup['orderReceive'][$key]['mobile'] ], // 收货人电话 'phrase19' => [ 'value' => $orderData['payStatus'] == StatusCode::$delete ? '待支付':'已支付'], // 支付状态 ]; $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMSystemPushMessage->sendWeiXinPushMessage(1, $customerData['openId'], $sendMessageData, '/pagesT/order/orderDetail?id='.array_pop($orderIds)); if(!$result->isSuccess()){ file_put_contents('/www/wwwroot/logs/api.junhailan.com/phperstar.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND); } } } return ResultWrapper::success($payResult->getData()); } /** * Doc: (des="支付") * User: XMing * Date: 2020/12/18 * Time: 4:17 下午 * @param string $tmpOuterTradeNo 临时订单号 * @param array $params 公共参数 * @param array $orderIds 所有订单号 * @param $ip * @return ResultWrapper * @throws \Exception */ public function toPay($tmpOuterTradeNo,$params,$orderIds,$ip): ResultWrapper { // 获取支付金额 $payMoney = getArrayItem($params,'payMoney',0); if (empty($payMoney)){ return ResultWrapper::fail('支付金额异常',ErrorCode::$paramError); } // 处理支付方式 $payType = explode(',', $params['payType']); rsort($payType); $objSystemCache = new SystemCache(); // 后台代客下单/货到付款/银行打款不需要返回支付配置 if ( $params['source'] == StatusCode::$source['manage'] || in_array(StatusCode::$payType['cashPay'], $payType) ) { return ResultWrapper::success($orderIds); } $payment = []; $payParams = ''; $payStatus = StatusCode::$partion; $orderStatus = StatusCode::$orderStatus['waitPay']; $notPayMoney = $payMoney; foreach($payType as $k => $v){ //判断支付状态(有银行打款是5,没有直接给3) // 除了余额支付其他方式都要获取支付配置 if($v != StatusCode::$payType['balance'] && $v != StatusCode::$payType['bankLoans']){ $objMPaymentSetting = new MPaymentSetting($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMPaymentSetting->getPayData($v); if (!$result->isSuccess() || empty($result->getData())) { return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor); } $payment = $result->getData(); } switch (true){ case in_array(StatusCode::$payType['balance'], $payType): //减少余额() $status = $this->objDOrderIndex->beginTransaction(); //新增会员流水记录 $memberBalanceDetailData = [ 'customerId' => $params['id'], 'type' => StatusCode::$delete, 'userCenterId' => $this->onlineUserId, 'purpose' => '创建订单消费', 'orderIds' =>implode(',',$orderIds), 'remark' => '订单id'.implode(',',$orderIds), 'financeType' => '会员余额消费' ]; // 组合支付方式 if( !empty($params['admixPayData']) ) { foreach ($params['admixPayData'] as $key => $value) { if ($value['payType'] == StatusCode::$payType['balance']) { // 本次混合支付余额支付金额 $memberBalanceDetailData['money'] = $value['payMoney']; // 总金额 - 余额支付金额 = 剩余需要搭配支付金额 $payMoney = bcsub($payMoney, $value['payMoney'], 2); $notPayMoney = $payMoney; } } }else{ $orderStatus = StatusCode::$orderStatus['waitDelivery']; $payStatus = StatusCode::$standard; $memberBalanceDetailData['money'] = $payMoney; $notPayMoney = 0; } $objMMemberBalanceDetail = new MMemberBalanceDetail($this->onlineEnterpriseId,$this->onlineUserId); $memberBalanceDbResult = $objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData); if (!$memberBalanceDbResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($memberBalanceDbResult->getData(), $memberBalanceDbResult->getErrorCode()); } // 查询余额对应的银行账户 $defaultAccountResult = $this->objMAccount->getDefaultAccount(StatusCode::$payType['balance']); if ($defaultAccountResult->isSuccess() == false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($defaultAccountResult->getData(), $defaultAccountResult->getErrorCode()); } if(empty($defaultAccountResult->getData())){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail('没有默认的'.StatusCode::$payType[$payType['balance']].'账户', ErrorCode::$notAllowAccess); } $defaultAccount = $defaultAccountResult->getData(); //修改订单状态 $time = time(); $this->objDOrderIndex->setTable('qianniao_order_index_'.$this->onlineEnterpriseId); $fix = ceil($params['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); foreach ($orderIds as $orderId){ $updateIndexResult = $this->objDOrderIndex->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'updateTime' => $time],$orderId); if ($updateIndexResult === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } $updateIndex = $this->objDOrder->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'payTime'=> $time,'updateTime' => $time,'notPayMoney'=>$notPayMoney],$orderId); if ($updateIndex === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } $orderInfo = $this->objDOrder->get($orderId); if($orderInfo == false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } // 生成收款单 $receivedData = [ 'customerId' => $orderInfo['customerId'], 'customerName' => $orderInfo['customerName'], 'currentAccountName' => $orderInfo['shopName'], 'financeType' => '销售收款', 'financeTypeId' => StatusCode::$systemFinanceType['saleReceipt'], 'shopId' => $orderInfo['shopId'], 'shopName' => $orderInfo['shopName'], 'receiptTime' => time(), 'operatorId' => $this->onlineUserId, 'originId' => $orderId, 'originNo' => $orderInfo['no'], 'sourceId' => $orderId, 'sourceNo' => $orderInfo['no'], 'sourceNoMoney' => $orderInfo['totalMoney'], //原单据订单总金额 'auditStatus' => StatusCode::$auditStatus['auditing'], 'createTime' => time(), 'updateTime' => time(), 'accountList' => [ [ "accountId" => isset($defaultAccount['id']) ? $defaultAccount['id'] : 0, "accountNumber" => isset($defaultAccount['accountNumber']) ? $defaultAccount['accountNumber'] : '', 'accountName' => isset($defaultAccount['name']) ? $defaultAccount['name'] : '', "money" => $memberBalanceDetailData['money'], "discountMoney" => 0, "finalMoney" => $memberBalanceDetailData['money'], "payWay" => '余额支付', "remark" => "在线余额支付自动生成收款单" ] ], ]; $result = $this->objMReceived->addReceived($receivedData, true); if ($result->isSuccess() == false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($result->getData(), $result->getErrorCode()); } unset($receivedData); unset($result); } // 根据客户id (customerId) 获取 openId if(!empty($orderInfo['customerId'])){ $customerId = $orderInfo['customerId']; $objDCustomer = new DCustomer('default'); $objDCustomer->setTable($objDCustomer->get_Table() . '_' . $this->onlineEnterpriseId); $customerData = $objDCustomer->get($customerId); if($customerData === false){ return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror); } if( empty($customerData) ){ return ResultWrapper::fail('查找不到该客户数据', ErrorCode::$contentNotExists); } // 小程序订阅消息 if (isset($customerData['openId']) && !empty($customerData['openId'])) { // 发送小程序订阅消息 $sendMessageData = [ 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfo['no']], // 订单编号 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfo['createTime'])], // 下单时间 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间 'thing7' => ['value' => '余额支付'], // 支付方式 'name8' => ['value' => substr($orderInfo['shopName'],0,30)] // 商家名称 ]; $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customerData['openId'], $sendMessageData); if (!$result->isSuccess()) { file_put_contents('/www/wwwroot/logs/api.junhailan.com/systemPushMessage.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND); } } } $status && $this->objDOrderIndex->commit(); $payParams = ResultWrapper::success(['code'=>100,'msg'=>'余额支付成功']); break; case in_array(StatusCode::$payType['aliPay'], $payType): //ali /*********读取支付宝支付参数(原配置)*********/ /**$aliPayConfigData = Factory::config()->get('alipay'); * if (empty($aliPayConfigData)) { * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor); * }*/ $payOrderData = [ 'subject' => '千鸟云商', 'out_trade_no' => $tmpOuterTradeNo, 'total_amount' => $payMoney, 'passback_params' => $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', $orderIds), ]; $aliPayConfigData = [ 'appid' => $payment['appid'], 'rsaPrivateKey' => $payment['rsaPrivateKey'], 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'], ]; $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']); $payParams = $objAliPay->appPay($payOrderData); break; case in_array(StatusCode::$payType['wxPay'], $payType): //wx /********************生成小程序唤起支付用到的参数(原配置)*****/ /**$weixinConfigData = Factory::config()->get('weixin'); * if (empty($weixinConfigData)) { * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor); * }*/ // 获取当前登录企业的小程序配置 $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId); if (empty($miniprogramSetting)) { return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor); } $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid // 获取配置文件微信公众号 $weixinConfigData = Factory::config()->getAppoint('weixin', 'offiaccount'); switch ($params['source']) { case StatusCode::$source['weiXinBrowser']; if (empty($weixinConfigData)) { return ResultWrapper::fail('微信公众号配置错误', ErrorCode::$configEroor); } $appid = $weixinConfigData['appid']; $paySource = 'weiXinBrowser'; break; case StatusCode::$source['H5']; if (empty($weixinConfigData)) { return ResultWrapper::fail('微信公众号配置错误', ErrorCode::$configEroor); } $appid = $weixinConfigData['appid']; $paySource = 'H5'; break; case StatusCode::$source['miniProgram']; $appid = $miniprogramSetting['appid']; $paySource = 'miniProgram'; break; default : $appid = $payment['mobileAppid']; $paySource = 'APP'; break; } $weixinConfigData = [ 'mch_id' => $payment['mchId'], 'apiPartnerKey' => $payment['apiPartnerKey'], 'appid' => $appid ]; $attach = $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', $orderIds); //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old //判断是否是子商户,优先选择子商户 if(isset($payment['sub_mch_id']) && !empty($payment['sub_mch_id']) && $payMoney['mch_type'] == 2 ){ $sub_mch_id = $payment['sub_mch_id']; $sub_weixinConfigData = Factory::config()->get('weixin'); if (empty($sub_weixinConfigData)) { return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor); } $objPay = new Pay($appid, $sub_weixinConfigData['service_pay']['mch_id'], $sub_weixinConfigData['service_pay']['apiPartnerKey']); $payParams = $objPay->unifiedorder($tmpOuterTradeNo,$payMoney, $ip, $paySource, '千鸟云商', $params['openId'], $attach,$sub_mch_id); break; } $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']); $payParams = $objPay->unifiedorder($tmpOuterTradeNo,$payMoney, $ip, $paySource, '千鸟云商', $params['openId'], $attach); break; case in_array(StatusCode::$payType['byte'],$payType): //字节跳动 $mweb_url = ''; //读取缓存配置 //$objSystemCache->getByteDanceSetting($this->onlineEnterpriseId); // 获取配置文件字节小程序 $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay'); if (empty($byteDanceConfigData)) { return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor); } $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']); unset($payParams); $payParams = $objbytePay->pay($tmpOuterTradeNo, $payMoney, '千鸟云商', $ip, $mweb_url); break; case in_array(StatusCode::$payType['bankLoans'], $payType): foreach ($orderIds as $orderId){ $orderInfo = $this->objDOrder->get($orderId); if($orderInfo == false){ return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } } // 根据客户id (customerId) 获取 openId if(!empty($orderInfo['customerId'])){ $customerId = $orderInfo['customerId']; $objDCustomer = new DCustomer('default'); $objDCustomer->setTable($objDCustomer->get_Table() . '_' . $this->onlineEnterpriseId); $customerData = $objDCustomer->get($customerId); if($customerData === false){ return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror); } if( empty($customerData) ){ return ResultWrapper::fail('查找不到该客户数据', ErrorCode::$contentNotExists); } // 小程序订阅消息 if (isset($customerData['openId']) && !empty($customerData['openId'])) { // 发送小程序订阅消息 $sendMessageData = [ 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfo['no']], // 订单编号 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfo['createTime'])], // 下单时间 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间 'thing7' => ['value' => '银行打款'], // 支付方式 'name8' => ['value' => substr($orderInfo['shopName'],0,30)] // 商家名称 ]; $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customerData['openId'], $sendMessageData); if (!$result->isSuccess()) { file_put_contents('/www/wwwroot/logs/api.junhailan.com/systemPushMessage.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND); } } } $payParams = ResultWrapper::success($orderIds); break; default: //TODO return ResultWrapper::fail('暂未开放的支付方式',ErrorCode::$paramError); break; } unset($payType[$k]); if (!$payParams->isSuccess()) { return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode()); } } return ResultWrapper::success($payParams->getData()); } /** * Doc: (des="已审核未出库订单,审核驳回") * User: XMing * Date: 2021/2/25 * Time: 9:41 上午 * @param int $orderId * @return ResultWrapper * @throws \Exception */ public function revokeAudit(int $orderId): ResultWrapper { $orderIndex = $this->objDOrderIndex->get($orderId); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError); } $fix = ceil((empty($params['userCenterId']) ? 1 : $params['userCenterId']) / $this->cutTable); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $orderData = $this->objDOrder->get($orderId); if ($orderData === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } if (empty($orderData)){ return ResultWrapper::fail('为获取到指定的订单信息',ErrorCode::$paramError); } if ($orderData['auditStatus'] != StatusCode::$auditStatus['auditPass']){ return ResultWrapper::fail('订单审核状态异常,不能驳回',ErrorCode::$paramError); } if ($orderData['outStatus'] != StatusCode::$delete){ return ResultWrapper::fail('订单已经出库,不能驳回',ErrorCode::$paramError); } if ($orderData['orderStatus'] == StatusCode::$orderStatus['close']){ return ResultWrapper::fail('订单已关闭,不嫩驳回',ErrorCode::$paramError); } $this->objDOrderIndex->beginTransaction(); $time = time(); //update order $updateOrder = $this->objDOrder->update([ 'auditStatus' => StatusCode::$auditStatus['auditing'], 'updateTime' => $time, 'revokeTime' => $time ],$orderId); if ($updateOrder === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } //update orderIndex $updateOrderIndex = $this->objDOrderIndex->update([ 'auditStatus' => StatusCode::$auditStatus['auditing'], 'updateTime' => $time ],$orderId); if ($updateOrderIndex === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } //update stock $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId); $stockOutResult = $objMInventoryOut->delInventoryOutStatus([ 'sourceId' => $orderId, 'type' => StatusCode::$orderType['saleOut'] ]); if (!$stockOutResult->isSuccess()){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($stockOutResult->getData(),$stockOutResult->getErrorCode()); } // 删除已生成的收款单 $objDReceivedIndex = new DReceivedIndex('finance'); $objDReceivedIndex->setTable('qianniao_received_index_' . $this->onlineEnterpriseId); $deleteReceive = $objDReceivedIndex->delete(['sourceId'=>$orderIndex['id']]); if ($deleteReceive === false) { return ResultWrapper::fail($objDReceivedIndex->error(), ErrorCode::$dberror); } /* //update es $_id = self::createEsDocumentId($orderId); $this->objDOrder->esupdateTypeFieldVaule([ 'auditStatus' => StatusCode::$auditStatus['auditing'], 'updateTime' => $time ], $_id);*/ $this->objDOrderIndex->commit(); return ResultWrapper::success(true); } /** * Doc: (des="") * User: XMing * Date: 2021/3/9 * Time: 5:13 下午 * @param int $orderId * @return ResultWrapper * @throws \Exception */ public function reStockOut(int $orderId): ResultWrapper { // 获取订单索引表数据 $orderIndex = $this->objDOrderIndex->get($orderId); if ($orderIndex === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } if (empty($orderIndex)){ return ResultWrapper::fail('未获取到指定地订单信息',ErrorCode::$paramError); } // 获取订单数据 $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $orderData = $this->objDOrder->get($orderId); if ($orderData === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } if (empty($orderData)){ return ResultWrapper::fail('未获取到指定的订单信息',ErrorCode::$paramError); } if ($orderData['outStatus'] == StatusCode::$standard){ return ResultWrapper::fail('订单已经出库,请不要重复出库',ErrorCode::$paramError); } // 查询销售订单是否还有未审核的出库单,必须先处理完,再生成新的出库单 $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId); $condition = [ 'originId' => $orderData['id'], 'deleteStatus' => StatusCode::$standard, 'auditStatus' => StatusCode::$auditStatus['auditing'], ]; $result = $objMInventoryOut->getInventoryOutData($condition); if (!$result->isSuccess()) { return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } $inventoryOutData = $result->getData(); if( !empty($inventoryOutData) ){ return ResultWrapper::fail('当前销售订单还有未审核的出库单,单号:'.StatusCode::$noPrefix[5].'-'.$inventoryOutData[0]['no'].',请先处理完成', ErrorCode::$notAllowAccess); } // 查询订单商品表数据 $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix); $orderGoodsData = $this->objDOrderGoods->select(['orderId' => $orderId,'deleteStatus' => StatusCode::$standard]); if ($orderGoodsData === false){ return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } if (empty($orderGoodsData)){ return ResultWrapper::fail('订单商品获取失败',ErrorCode::$paramError); } // 组装出库单数据 $saleOutData = [ 'sourceId' => $orderData['id'], 'sourceNo' => $orderData['no'], 'originNo' => $orderData['no'], 'originId' => $orderData['id'], 'shopId' => $orderData['shopId'], 'shopName' => $orderData['shopName'], 'amount' => $orderData['payAmount'], 'operatorId' => $orderData['auditId'],//操作人id 'operatorName' => $orderData['audit'],//操作人信息 'customerId' => $orderData['customerId'], 'customerName' => $orderData['customerName'], 'customerCode' => createCode(StatusCode::$code['customer']['prefix'], $orderData['customerId'], StatusCode::$code['customer']['length']), 'customerMobile' => $orderData['customerMobile'], 'source' => StatusCode::$orderType['saleOrder'], //订单来源(出库类型) 'type' => StatusCode::$orderType['saleOut'], 'deliveryType' => $orderData['deliveryType'],//配送方式 'remark' => $orderData['remark'], ]; $saleOutData['materielNum'] = 0; //获取sku $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId); $skuIds = array_column(array_values($orderGoodsData), 'skuId'); $modelResult = $objMSku->getSkuDataBySkuIds($skuIds); if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $skuData = $modelResult->getData(); unset($modelResult); foreach ($orderGoodsData as $key => $value) { if ($value['outOfNum'] > 0 && $value['isEq'] == StatusCode::$delete){ $saleOutData['materielNum']++; $totalMoney = bcsub(bcsub($value['totalMoney'], $value['vipDiscount']), $value['preferential']);//销售总价 !优惠后 $saleOutData['orderGoodsData'][] = [ 'materielId' => $value['goodsBasicId'], 'materielName' => $value['goodsName'], 'materielCode' => createCode(StatusCode::$code['goodsBasic']['prefix'], $value['goodsBasicId'], StatusCode::$code['goodsBasic']['length']), 'skuId' => $value['skuId'], 'num' => $value['outOfNum'], 'otherNum' => $value['otherNum'], 'outNum' => 0, 'total' => $value['outOfNum'], 'unitName' => isset($value['unitName']) ? $value['unitName'] : '', 'skuName' => isset($skuData[$value['skuId']]) ? $skuData[$value['skuId']]['skuName'] : '', 'unitPrice' => $value['price'],//单价 不优惠 'totalPrice' => $totalMoney,//销售总价 !优惠后 ]; } } if (empty($saleOutData['orderGoodsData'])){ return ResultWrapper::fail('此订单没有需要出库的商品',ErrorCode::$paramError); } // 新增出库单 $dbResult = $objMInventoryOut->addInventoryOut($saleOutData); if (!$dbResult->isSuccess()){ return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode()); } return ResultWrapper::success($dbResult->getData()); } /** * Doc: (des="") * User: XMing * Date: 2021/3/18 * Time: 6:55 下午 * @param int $orderId * @return ResultWrapper * @throws \Exception */ public function retAmount(int $orderId) { $message = '退款成功'; // 从订单索引表查询订单数据 $orderIndex = $this->objDOrderIndex->get($orderId); if ($orderIndex === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } if (empty($orderIndex)){ return ResultWrapper::fail('未获取到订单数据',ErrorCode::$paramError); } // 从订单和订单商品查询订单数据 $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix); $order = $this->objDOrder->get($orderId); if ($order === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } if ( empty($order) ){ return ResultWrapper::fail('未获取到指定订单信息',ErrorCode::$paramError); } $sql = 'SELECT * FROM qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix.' WHERE orderId = '.$orderId.' AND deleteStatus = '.StatusCode::$standard.' AND outOfNum > 0'; $rows = $this->objDOrderGoods->query($sql); if ($rows === false){ return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } if (empty($rows)){ return ResultWrapper::fail('未获取到指定订单的商品信息',ErrorCode::$paramError); } // 根据实际订单未出库数量计算退款金额 $receiveMoney = 0; foreach ($rows as $row){ if ($row['outOfNum'] <= 0) continue; $receiveMoney = bcadd($receiveMoney,bcmul($row['price'],$row['outOfNum'], 4),4); } // 保留4位判断金额是否异常 if ($receiveMoney <= 0){ return ResultWrapper::fail('退款金额异常',ErrorCode::$paramError); } $receiveMoney = bcadd($receiveMoney, '0', 2); // 实际退款保留两位 $status = $this->objDOrder->beginTransaction(); $payType = explode(',', $orderIndex['payType']); // 未支付订单不生成退款单 if( $order['payStatus'] == StatusCode::$standard){ // 小于1分钱不做退款处理 if ($receiveMoney >= 0.01){ // 根据订单支付方式规划退款账户 $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId); // 包含余额组合支付方式统一返回余额,其他原路返回 if( in_array(StatusCode::$payType['balance'],$payType) ){ $financeAccountData = $objMAccount->getDefaultAccount(StatusCode::$payType['balance']); }else if( in_array(StatusCode::$payType['bankLoans'],$payType) ){ $extends = json_decode($order['extends'], true); if( isset($extends['bankData']['id']) && !empty($extends['bankData']['id'])){ $accountId = $extends['bankData']['id']; //获取银行打款账户信息 $financeAccountData = $objMAccount->getAccountInfo($accountId); }else{ $financeAccountData = ResultWrapper::fail('获取打款账户错误'); } } else{ $financeAccountData = $objMAccount->getDefaultAccount($payType); } if(!$financeAccountData->isSuccess()){ return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode()); } $financeAccountData = $financeAccountData->getData(); //记录负应收的id //$financeRefundData['offsetId'] = (int)$addReceiveResult->getData(); // 生成财务退款单 $financeRefundData = [ 'originId' => getArrayItem($order,'id',0), 'originNo' => getArrayItem($order,'no',''), 'sourceId' => getArrayItem($order,'id',0), 'sourceNo' => getArrayItem($order,'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' => $receiveMoney, 'operatorId' => $this->onlineUserId, 'type' => StatusCode::$standard, 'auditStatus' => StatusCode::$auditStatus['auditing'], 'remark' => '订单一键完结,订单编号:'. getArrayItem($order,'no','').'完结后需退款金额:'.$receiveMoney ]; $financeRefundData['accountList'] = [ [ 'accountId' => $financeAccountData['id'], 'accountNumber' => $financeAccountData['accountNumber'], 'accountName' => $financeAccountData['name'], 'money' => $receiveMoney, ] ]; $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId); $result = $objMRefund->addRefund($financeRefundData); if(!$result->isSuccess()){ $this->objDOrder->rollBack(); return ResultWrapper::fail($result->getData(),$result->getErrorCode()); } // 应收自动审核队列 //Factory::cache('finance')->zadd('salesOutReceive::'.$this->onlineEnterpriseId, time(), $addReceiveResult->getData()); }else{ $message = '退款金额少于0.01,不做退款处理,退款成功'; } } $updateIndexData = [ 'updateTime' => time(), 'isRet' => StatusCode::$standard, ]; $updateOrderIndex = $this->objDOrderIndex->update($updateIndexData, $orderId); if ($updateOrderIndex === false){ $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } $update = [ 'updateTime' => time(), 'retTime' => time(), 'retMoney' => $receiveMoney, 'isRet' => StatusCode::$standard, ]; $updateOrder = $this->objDOrder->update($update,$orderId); if ($updateOrder === false){ $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } //订单解锁 $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId); $unlockResult = $objMInventory->unlockInventory([$orderId], StatusCode::$orderType['saleOrder'], $orderIndex['createTime']); if (!$unlockResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror); } $status && $this->objDOrder->commit(); return ResultWrapper::success($message); } /** * Doc: (des="创建分销") * User: XMing * Date: 2020/7/29 * Time: 6:41 下午 * @param string $token * @param string $auth * @param int $customerId * @param int $orderId */ private function taskCreateCommission(string $token, string $auth, int $customerId, int $orderId) { $i = 1; do { $postData = [ 'topicName' => 'MyJob', 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder', 'topicMethon' => 'push', 'topicMethonParams' => [ 'Authorization' => $auth, 'Token' => $token, 'orderId' => $orderId, 'customerId' => $customerId, 'PROJECT_DOMAIN' => PROJECT_DOMAIN ], ]; $url = QIANNIAO_QUEUE . '/CAddJob/add'; $result = request($url, $postData); $i++; } while ($result['httpcode'] != 200 && $i <= 3); Logger::logs(E_USER_ERROR, '投递任务成功', __CLASS__, __LINE__, $postData); } /** * Doc: (des="修改订单的退货状态") * User: XMing * Date: 2020/7/14 * Time: 3:54 下午 * @param $params * @return ResultWrapper * @throws \Exception */ public function editOrder($params) { if (empty($params['id'])) { return ResultWrapper::fail('没有订单id', ErrorCode::$paramError); } $id = $params['id']; unset($params['id']); $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $orderIndex = $this->objDOrderIndex->get(['id' => $id], 'userCenterId'); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $this->objDOrderIndex->beginTransaction(); $updateResult = $this->objDOrderIndex->update([ 'updateTime' => $params['updateTime'], 'returnStatus' => $params['returnStatus'], ], ['id' => $id]); if ($updateResult === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $tableNum = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $tableNum); $dbResult = $this->objDOrder->update([ 'updateTime' => $params['updateTime'], 'returnStatus' => $params['returnStatus'], ], $id); if ($dbResult === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $this->objDOrderIndex->commit(); /*//修改es数据 $_id = self::createEsDocumentId($id); $this->objDOrder->esupdateTypeFieldVaule(['returnStatus' => $params['returnStatus'], 'updateTime' => $params['updateTime']], $_id);*/ return ResultWrapper::success($dbResult); } /** * 更新ES * @param $orderId * @param $order * @param $addressData * @param $addOrderGoodsName * @param int $userCenterId */ public function updateEsData($orderId, $order, $addressData, $addOrderGoodsName, $userCenterId = 0) { $orderEsData = [ /*订单表信息*/ 'id' => $orderId,//订单编号, 'no' => $order['no'],//订单编号, 'outerTradeNo' => '',//'外部流水号(支付宝/微信返回的流水号)' 'shopId' => $order['shopId'], 'shopName' => $order['shopName'], 'enterpriseId' => $this->onlineEnterpriseId, 'userCenterId' => $userCenterId != 0 ? $userCenterId : $this->onlineUserId, 'totalMoney' => $order['totalMoney'], 'payAmount' => $order['payAmount'], 'buyTotal' => isset($order['buyTotal']) ? $order['buyTotal'] : 0,//购买总数 'customerName' => $order['customerName'],//客户姓名 'customerId' => $order['customerId'],//客户id 'customerType' => isset($order['customerType']) ? $order['customerType'] : 0,//客户类型 'payStatus' => StatusCode::$delete,//'支付状态 默认4 未支付 5已支付' 'orderStatus' => StatusCode::$orderStatus['waitPay'],//订单状态 默认1 创建 2待支付 3代发货 4待收货 5已完成 6已关闭 'payType' => $order['payType'],//'支付方式 1微信 2支付宝 3货到付款 4上门自提' 'deliveryType' => $order['deliveryType'],//'配送方式 1商品配送 2上门自提' 'source' => $order['source'],//订单来源 默认1 ios 2android 3小程序 4后台创建 'remark' => $order['remark'],//订单备注 'auditStatus' => $order['auditStatus'],// '审核状态 默认1 待审 2审核通过 3 审核未通过 4 审核中' //'payTime' => '',//'付款时间' 'createTime' => $order['createTime'],//'创建时间' 'updateTime' => $order['updateTime'],//'修改时间', 'salesManId' => isset($order['salesManId']) ? $order['salesManId'] : 0, 'salesManName' => isset($order['salesManName']) ? $order['salesManName'] : '', 'returnStatus' => StatusCode::$orderReturn['notReturn'], 'outStatus' => StatusCode::$delete, 'verifyCode' => $order['verifyCode'],//核销码 /*收货人信息*/ 'realName' => isset($addressData['realName']) ? $addressData['realName'] : '',//收货人姓名 'mobile' => isset($addressData['mobile']) ? $addressData['mobile'] : '',//收货人电话 'address' => isset($addressData['address']) ? $addressData['address'] : '',//收货详细地址 'provinceCode' => isset($addressData['provinceCode']) ? $addressData['provinceCode'] : '',//收货人省份编码 'cityCode' => isset($addressData['cityCode']) ? $addressData['cityCode'] : '',//收货人城市编码 'districtCode' => isset($addressData['districtCode']) ? $addressData['districtCode'] : '',//收货人区编码 /*优惠信息*/ 'preferential' => $order['preferential'],//优惠券优惠金额 'vipDiscount' => $order['vipDiscount'],//会员卡优惠金额 'vipDoubleDiscount' => $order['vipDoubleDiscount'],//会员卡折上折优惠金额 /*商品信息*/ 'goodsName' => $addOrderGoodsName, 'orderType' => isset($order['orderType']) ? $order['orderType'] : StatusCode::$orderType['salesSlip'], ]; isset($order['salesManName']) && $orderEsData['salesManName'] = $order['salesManName']; $_id = self::createEsDocumentId($orderId); $result = $this->objDOrder->addUpSearchIndexDocument($orderEsData, $_id); if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) { //echo "es操作成功"; //return; } //echo "es操作失败"; } /** * 创建文档id * * @param $orderId * @return string */ private function createEsDocumentId($orderId) { return 'EnterpriseId_' . $this->onlineEnterpriseId . '_OrderId_' . $orderId; } /** * Doc: (des="获取订单创建时间,用于其它业务计算分表使用") * User: XMing * Date: 2020/12/25 * Time: 2:16 下午 * @param $orderId * @return ResultWrapper * @throws \Exception */ public function getOrderCreateTime($orderId) { $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $orderIndexRes = $this->objDOrderIndex->get_by('id', $orderId); if ($orderIndexRes === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($orderIndexRes)) { return ResultWrapper::fail('未找到订单信息', ErrorCode::$paramError); } return ResultWrapper::success($orderIndexRes); } /** * Doc: (des="获取订单详情") * User: XMing * Date: 2020/7/14 * Time: 6:25 下午 * @param $id * @return ResultWrapper * @throws \Exception */ public function getOrderInfoById($id): ResultWrapper { $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $orderIndexRes = $this->objDOrderIndex->get_by('id', $id); if ($orderIndexRes === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($orderIndexRes)) { return ResultWrapper::fail('未找到订单信息', ErrorCode::$paramError); } //切换分表 self::orderSubTable($this->onlineEnterpriseId, $orderIndexRes['userCenterId']); $dbResult = $this->objDOrder->get_by('id', $id); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $formatData = self::format($dbResult); if (!$formatData->isSuccess()){ return ResultWrapper::fail($formatData->getData(),$formatData->getErrorCode()); } $dbResult = $formatData->getData(); //添加订单打印的数据 $printResult = self::printInfo($dbResult); if (!$printResult->isSuccess()){ return ResultWrapper::fail($printResult->getData(),$printResult->getErrorCode()); } $dbResult = $printResult->getData(); //logisticsData $dbResult['logisticsData'] = json_decode($dbResult['logisticsData'],true); // 查询订单退货对应退货单的状态 if($dbResult['returnStatus']){ $objMOrderReturn = new MOrderReturn($this->onlineEnterpriseId, $this->onlineUserId); $result = $objMOrderReturn->getAuditStatusByOrderId($id); $dbResult['returnAuditStatus'] = StatusCode::$auditStatus['auditing']; if($result->isSuccess()){ $dbResult['returnAuditStatus'] = $result->getData(); } } return ResultWrapper::success($dbResult); } /** * 补充打印订单字段信息 * * @param $dbResult * @return ResultWrapper * @throws \Exception */ public function printInfo($dbResult) { if ($dbResult['source'] == StatusCode::$source['manage']){ $dbResult['receivable'] = $dbResult['totalMoney'];//应收 }else{ $dbResult['receivable'] = $dbResult['payAmount'];//应收 } if ($dbResult['payType'] == StatusCode::$payType['cashPay'] || $dbResult['payType'] == StatusCode::$payType['bankLoans'] ) { //货到付款 已支付 = payAmount金额 if ($dbResult['source'] == StatusCode::$source['manage']){ $dbResult['netReceipts'] = isset($dbResult['receivedMoney']) ? $dbResult['receivedMoney'] : 0; }else{ if ($dbResult['payStatus'] == StatusCode::$standard) { $dbResult['netReceipts'] = $dbResult['payAmount'];//实收 } else { $dbResult['netReceipts'] = 0;//实收 } } } else { //在线支付 已支付 = payAmount金额 if ($dbResult['payStatus'] == StatusCode::$standard) { $dbResult['netReceipts'] = $dbResult['payAmount'];//实收 } else { $dbResult['netReceipts'] = 0;//实收 } } $dbResult['currentShortage'] = bcsub($dbResult['receivable'], $dbResult['netReceipts'], 2);//本单欠 $dbResult['upOwe'] = $dbResult['customerOwe'];//上欠 $dbResult['totalDeficit'] = bcadd($dbResult['currentShortage'], $dbResult['upOwe'], 2); $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $shopData = $objMShop->getShopInfo(['id' => $dbResult['shopId']]); if (!$shopData->isSuccess()) { return ResultWrapper::fail($shopData->getData(),$shopData->getErrorCode()); } else { $shopData = $shopData->getData(); } $dbResult['shopAddress'] = isset($shopData['area']) ? $shopData['area'] : []; $dbResult['shopMobile'] = isset($shopData['mobile']) ? $shopData['mobile'] : ''; $dbResult['shopDescribe'] = isset($shopData['describe']) ? $shopData['describe'] : ''; $dbResult['partnerPhone'] = isset($shopData['mobile']) ? $shopData['mobile'] : '';//合伙人联系电弧 $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId); $accountName = ''; if ($dbResult['payType'] == StatusCode::$payType['wxPay'] || $dbResult['payType'] == StatusCode::$payType['aliPay']){ $accountResult = $objMAccount->getDefaultAccount($dbResult['payType']); if (!$accountResult->isSuccess()){ return ResultWrapper::fail($accountResult->getData(),$accountResult->getErrorCode()); } $account = $accountResult->getData(); $accountName = isset($account['name']) ? $account['name'] : ''; }else{ $account = isset($dbResult['accountList']) ? array_shift($dbResult['accountList']) : []; $accountName = isset($account['accountName']) ? $account['accountName'] : ''; } $dbResult['accountName'] = $accountName;//收款账户 $pbjMPrintNum = new MPrintNum($this->onlineEnterpriseId); $dbResult['printingNum'] = $pbjMPrintNum->getObjectPrintNum($dbResult['no'], $dbResult['orderType']); return ResultWrapper::success($dbResult); } /** * 检索导出(ES) * * @param $dsl * @return ResultWrapper * @throws \Exception */ private function exportSearch($dsl) { $result = $this->objDOrder->getScrollSearchQueryDsl($dsl); if (isset($result['status']) && $result['status'] == 400) { return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult); } if (!isset($result['hits']) && $result['hits']['total'] == 0) { return ResultWrapper::fail('导出数据为空' . $result['error']['reason'], ErrorCode::$apiNotResult); } $dbResult = $result['hits']['hits']; $list = []; foreach ($dbResult as $key => &$value) { $data = []; $data = $value['_source']; $list[] = $data; } self::exportOrder($list, 'es'); } /** * 导出方法 * * @param $allOrderData */ private static function export($allOrderData) { //导出到本地 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 ($allOrderData as $v) { //循环数据 $num++; if ($num == $limit) { ob_flush();//释放内存 flush(); } $rows['id'] = $v['id']; $rows['no'] = $v['no']; $rows['createTime'] = date('Y-m-d H:i:s', $v['createTime']); $rows['customerName'] = $v['customerName']; $rows['realName'] = $v['realName']; $rows['salesManName'] = $v['salesManName']; $rows['mobile'] = $v['mobile']; $rows['payAmount'] = $v['payAmount']; $rows['orderStatus'] = StatusCode::$orderStatus[$v['orderStatus']]; $rows['payStatus'] = StatusCode::$standard == $v['payStatus'] ? '已支付' : '未支付'; $rows['deliveryType'] = ($v['deliveryType'] != StatusCode::$deliveryType['goodsDelivery'] && $v['deliveryType'] != StatusCode::$deliveryType['selfMention']) ? '' : StatusCode::$deliveryType[$v['deliveryType']]; $rows['source'] = StatusCode::$source[$v['source']]; $rows['auditStatus'] = StatusCode::$auditStatus[$v['auditStatus']]; foreach ($rows as $kk => $vv) { $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码 } fputcsv($fp, $rs); $rows = []; } exit; } /** * 导出列表(数据库) * * @param string $sql * @return ResultWrapper * @throws \Exception */ public function exportAllOrder(string $sql) { $objDOrderIndex = new DOrderIndex(); $dbResult = $objDOrderIndex->query($sql); if ($dbResult === false) { return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror); } $allOrderData = []; $allGroupData = []; foreach ($dbResult as $key => $val) { $tableNum = (int)ceil($val['userCenterId'] / $this->cutTable); //这里感觉没有必要使用对主索引表的订单id进行分组,可以通过条件直接查询表下的数据 $allGroupData[$tableNum][] = $val['id']; } $fields = 'o.id,o.no,o.createTime,o.customerName,o.salesManName,o.payAmount,o.orderStatus,o.payStatus,o.source,o.deliveryType,o.auditStatus,r.realName,r.mobile'; foreach ($allGroupData as $k => $orderId) { $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k); $sql = 'SELECT ' . $fields . ' FROM qianniao_order_' . $this->onlineEnterpriseId . '_' . $k . ' AS o LEFT JOIN qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k . ' AS r ON o.id=r.orderId WHERE o.id IN(' . implode(',', $orderId) . ') ORDER BY o.createTime DESC'; $dbResult = $this->objDOrder->query($sql); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $allOrderData = array_merge($dbResult, $allOrderData); } self::export($allOrderData); } /** * Doc: (des="订单导出,构建查询数据") * User: XMing * Date: 2020/8/22 * Time: 10:25 上午 * @param array|string $data * @param string $field * @return ResultWrapper */ private function buildSelectGroupDataByCondition($data, string $field) { switch ($field) { case 'db': $result = self::getAllOrderIdsBySql($data); break; case 'es': $result = self::getAllOrderIdsBySearchResult($data); break; } if (!$result->isSuccess()) { return ResultWrapper::fail($result->getData(), $result->getErrorCode()); } return ResultWrapper::success($result->getData()); } /** * Doc: (des="将es检索数据,进行数据分组转化为统一格式") * [[表后缀]=>[订单id,]] * User: XMing * Date: 2020/8/22 * Time: 10:15 上午 * @param array $data * @return ResultWrapper */ private function getAllOrderIdsBySearchResult(array $data) { if (empty($data)) { return ResultWrapper::success([]); } $groupMapRes = self::buildGroupMapByArray((array)$data); if (!$groupMapRes->isSuccess()) { return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode()); } return ResultWrapper::success($groupMapRes->getData()); } /** * Doc: (des="") * User: XMing * Date: 2020/8/22 * Time: 10:18 上午 * @param array $data * @return ResultWrapper */ private function buildGroupMapByArray(array $data) { if (empty($data)) { return ResultWrapper::success([]); } $allGroupMap = []; //对所有数据进行分组,[[表后缀]=>[订单id,]] foreach ($data as $key => $val) { $tableNum = (int)ceil($val['userCenterId'] / $this->cutTable); //这里感觉没有必要使用对主索引表的订单id进行分组,可以通过条件直接查询表下的数据 $allGroupMap[$tableNum][] = $val['id']; } return ResultWrapper::success($allGroupMap); } /** * Doc: (des="通过sql,进行数据分组转化为统一格式") * [[表后缀]=>[订单id,]] * User: XMing * Date: 2020/8/22 * Time: 9:55 上午 * @param string $sql * @return ResultWrapper */ private function getAllOrderIdsBySql(string $sql) { if (empty($sql)) { return ResultWrapper::success([]); } $list = $this->objDOrderIndex->exportQuery($sql); if ($list === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $list = self::getGeneratorData($list); if (empty($list)) { return ResultWrapper::success([]); } $groupMapRes = self::buildGroupMapByArray((array)$list); if (!$groupMapRes->isSuccess()) { return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode()); } return ResultWrapper::success($groupMapRes->getData()); } /** * Doc: (des="获取export查询方法返回的数据集合") * User: XMing * Date: 2020/8/22 * Time: 11:42 上午 * @param $object * @return array */ private static function getGeneratorData($object) { $arrayList = []; foreach ($object as $value) { $arrayList[] = $value; } return $arrayList; } /** * Doc: (des="格式化导出数据,统一根据订单id格式化数据") * User: XMing * Date: 2020/8/22 * Time: 9:44 上午 * @param array|string $data * @param string $source * @return ResultWrapper * @throws \Exception */ private function exportOrder($data, string $source) { if (empty($data)) { return ResultWrapper::success([]); } $groupMapRes = self::buildSelectGroupDataByCondition($data, $source); if (!$groupMapRes->isSuccess()) { return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode()); } $groupMap = $groupMapRes->getData(); if (empty($groupMap)) { return ResultWrapper::fail('导出数据构建失败', ErrorCode::$paramError); } //查询需要导出的数据 $orderFields = '*'; $orderReceiveFields = '*'; $orderGoodsFields = '*'; $allOrderData = [];//订单集 $allOrderReceiveData = [];//订单收货地址集 $allOrderGoodsData = [];//订单商品信息 foreach ($groupMap as $k => $orderIds) { //订单表 $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k); $orderResult = $this->objDOrder->exportSelect(['id' => $orderIds], $orderFields, 'createTime desc');//查询订单 if ($orderResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $orderResult = self::getGeneratorData($orderResult); //订单收货表 $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k); $orderReceiveResult = $this->objDOrderReceive->exportSelect(['orderId' => $orderIds], $orderReceiveFields, 'createTime desc');//订单收货 if ($orderReceiveResult === false) { return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror); } $orderReceiveResult = self::getGeneratorData($orderReceiveResult); //订单商品表 $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $k); $orderGoodsResult = $this->objDOrderGoods->exportSelect(['orderId' => $orderIds], $orderGoodsFields, 'createTime desc'); if ($orderGoodsResult === false) { return ResultWrapper::fail($this->objDOrderGoods->error(), ErrorCode::$dberror); } $orderGoodsResult = self::getGeneratorData($orderGoodsResult); //对数据进行合并 $allOrderData = array_merge($orderResult, $allOrderData); $allOrderReceiveData = array_merge($orderReceiveResult, $allOrderReceiveData); $allOrderGoodsData = array_merge($orderGoodsResult, $allOrderGoodsData); } $formatResult = self::formatManageOrderList($allOrderData, $allOrderReceiveData, $allOrderGoodsData); if (!$formatResult->isSuccess()) { return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode()); } $exportData = $formatResult->getData(); if (empty($exportData)) { return ResultWrapper::fail('构建导出数据为空', ErrorCode::$paramError); } //将数据导出 self::exportCsv($exportData); } /** * Doc: (des="") * User: XMing * Date: 2020/8/22 * Time: 2:24 下午 * @param array $area * @param string $address * @return string */ private static function createAddress($area, $address) { $str = ''; if (isset($area['provinceName']) && !empty($area['provinceName'])) { $str .= $area['provinceName']; } if (isset($area['cityName']) && !empty($area['cityName'])) { $str .= $area['cityName']; } if (isset($area['districtName']) && !empty($area['districtName'])) { $str .= $area['districtName']; } $str .= $address; return $str; } /** * Doc: (des="生成规格名字") * User: XMing * Date: 2020/8/22 * Time: 2:47 下午 * @param array $specGroup * @return string */ private static function createSpecName($specGroup) { if(empty($specGroup)){ return "无"; } $str = ''; foreach ($specGroup as $value) { empty($str) && $str .= ' '; $str .= $value['specName'] . ':'; $str .= $value['specValueName']; } return $str; } /** * Doc: (des="将数据导出到表格") * User: XMing * Date: 2020/8/22 * Time: 11:09 上午 * @param array $data */ private function exportCsv(array $data) { //导出到本地 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;//计数器 $rows = []; foreach ($data as $v) { //循环数据 $num++; if ($num == $limit) { ob_flush();//释放内存 flush(); } foreach ($v['goodsData'] as $index => $item) { self::buildExportData($rows, $v, $item, $index); foreach ($rows as $kk => $vv) { $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码 } fputcsv($fp, $rs); $rows = []; } } exit; } /** * Doc: (des="") * User: XMing * Date: 2020/8/22 * Time: 3:28 下午 * @param array $rows * @param array $v * @param array $item * @param int $index */ private static function buildExportData(&$rows, array $v, array $item, int $index) { $rows['id'] = ''; $rows['no'] = ''; $rows['totalMoney'] = ''; $rows['subMoney'] = ''; $rows['payMoney'] = ''; $rows['orderMsg'] = ''; $rows['payTypeMsg'] = ''; $rows['payMsg'] = ''; $rows['deliveryMsg'] = ''; $rows['sourceMsg'] = ''; $rows['auditMsg'] = ''; $rows['createTime'] = ''; $rows['customerName'] = ''; $rows['receiveName'] = ''; $rows['receiveMobile'] = ''; $rows['receiveAddress'] = ''; $rows['shopName'] = ''; $rows['salesManName'] = ''; $rows['otherNum'] = ''; $rows['id'] = $v['id']; $rows['no'] = $v['no']; $rows['totalMoney'] = $v['totalMoney']; $rows['subMoney'] = bcsub($v['payAmount'], $v['totalMoney'], 2); $rows['payMoney'] = $v['payAmount']; $rows['orderMsg'] = $v['orderMsg']; $rows['payTypeMsg'] = $v['payTypeMsg']; $rows['payMsg'] = $v['payMsg']; $rows['deliveryMsg'] = $v['deliveryMsg']; $rows['sourceMsg'] = $v['sourceMsg']; $rows['auditMsg'] = $v['auditMsg']; $rows['createTime'] = date('Y-m-d H:i:s', $v['createTime']); $rows['customerName'] = $v['customerName']; $rows['receiveName'] = $v['receiveData']['realName']; $rows['receiveMobile'] = $v['receiveData']['mobile']; $rows['receiveAddress'] = self::createAddress($v['receiveData']['area'], $v['receiveData']['address']); $rows['shopName'] = $v['shopName']; $rows['salesManName'] = $v['salesManName']; $rows['goodsCode'] = $item['goodsCode']; $rows['goodsName'] = $item['goodsName']; $rows['unitName'] = $item['unitName']; $rows['specName'] = self::createSpecName((isset($item['specGroup']) && !empty($item['specGroup'])) ? json_decode($item['specGroup'], true) : []); $rows['buyNum'] = $item['buyNum']; $rows['unitPrice'] = $item['price']; $rows['totalPrice'] = $item['totalMoney']; $rows['otherNum'] = $item['otherNum']; } /** * 获取所有订单 * * @param $selectParams * @param $search * @param bool $is_export * @return ResultWrapper * @throws \Exception * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1 * @waitOutStock:待出库 orderStatus != 6 auditPass = 2 * @hasOutStock:已出库 orderStatus = 4 auditPass = 2 * @finish:已完成 orderStatus = 5 auditPass 2 * @close:已关闭 orderStatus = 6 * * 新订单列表 {"page":1,"pageSize":10,"search":{"auditStatus":1}} * 订单查询 {"page":1,"pageSize":10,"search":{"auditStatus":2}} 订单查询:此页面只展示新订单审核后的订单,订单状态为【待出库】,订单出库后,页面会显示出【确认收货】的按钮,订单在出库管理进行出库后,订单状态为【已出库】,客户或后台操作【确认收货】后,订单状态为【已完成】。 * 自提订单 {"page":1,"pageSize":10,"search":{"deliveryType":2}} * 取消订单 {"page":1,"pageSize":10,"search":{"orderStatus":6}} * */ public function getAllOrder($selectParams, $search, $is_export = false) { $objDOrderIndex = new DOrderIndex(); $selectParams = array_merge($selectParams, $search); // 组装检索sql语句 $buildSql = self::setOrderStatusSqlAttr($selectParams); $sql = $buildSql['sql']; if ($is_export === true) self::exportOrder($sql, 'db');//导出数据 $total = $objDOrderIndex->query($buildSql['countSql']); if (isset($selectParams['limit']) && isset($selectParams['offset'])) { $sql .= ' limit ' . $selectParams['offset'] . ',' . $selectParams['limit']; } $dbResult = $objDOrderIndex->query($sql); if ($dbResult === false) { return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror); } $allOrderData = [];//订单集 $allOrderReceiveData = [];//订单收货地址集 $allGroupData = []; if (!empty($dbResult)) { foreach ($dbResult as $key => $val) { $tableNum = ceil($val['userCenterId'] / $this->cutTable); $allGroupData[$tableNum][] = $val['id']; } foreach ($allGroupData as $k => $orderId) { $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k); $dbResult = $this->objDOrder->select(['id' => $orderId], '*', 'createTime desc');//查询订单 if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } //物流信息展示 if( !empty($dbResult['logisticsData']) ){ json_decode($dbResult['logisticsData'],true); } $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k); $orderReceiveResult = $this->objDOrderReceive->select(['orderId' => $orderId], '*', 'createTime desc');//订单收货 if ($orderReceiveResult === false) { return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror); } $allOrderData = array_merge($dbResult, $allOrderData);//订单集 $allOrderReceiveData = array_merge($orderReceiveResult, $allOrderReceiveData);//订单收货地址集 } } // 格式化后台订单列表 $formatResult = self::formatManageOrderList($allOrderData, $allOrderReceiveData); if (!$formatResult->isSuccess()) { return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode()); } $return = [ 'data' => $formatResult->getData(), 'total' => isset($total[0]['total']) ? $total[0]['total'] : 0, ]; return ResultWrapper::success($return); } /** * Doc: (des="获取检索订单数据") *订单列表搜索商品名称、商品编码、收货人、电话 * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1 * @waitOutStock:待出库 orderStatus != 6 auditPass = 2 * @hasOutStock:已出库 orderStatus = 4 auditPass = 2 * @finish:已完成 orderStatus = 5 auditPass 2 * @close:已关闭 orderStatus = 6 * @param $export * @param $selectParams */ public function keywordSearch($selectParams,$export = '') { // 组装检索sql $whereSql = ''; if(!empty($selectParams['keywordType']) && !empty($selectParams['keyword'])){ $whereSql = self::assemblySql($selectParams['keywordType'],$selectParams['keyword']); } $orderTab ='qianniao_order_'.$this->onlineEnterpriseId.'_'.'1'; $orderGoodsTab ='qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.'1'; $orderReceive ='qianniao_order_receive_'.$this->onlineEnterpriseId.'_'.'1'; // 初始化表 $this->objDOrder->setTable($orderTab); $this->objDOrder->setTable($orderGoodsTab); $this->objDOrder->setTable($orderReceive); $condition = ''; $limit = ''; if(!$export){ if (isset($selectParams['limit']) && isset($selectParams['offset'])) { $limit .= ' limit ' . $selectParams['offset'] . ',' . $selectParams['limit']; } } // 时间筛选 if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){ $condition .= ' AND o.createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime']; } //userCenterId if (isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])) { $condition .= ' and o.userCenterId = ' . $selectParams['userCenterId']; } //customerId if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) { $condition .= ' and o.customerId = ' . $selectParams['customerId']; } //shopId if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) { $condition .= ' and o.shopId = ' . $selectParams['shopId']; } // 付款状态 支付状态 默认4 未支付 5已支付 if (isset($selectParams['payStatus']) && !empty($selectParams['payStatus'])) { $condition .= ' and o.payStatus = ' . $selectParams['payStatus']; } //支付方式 if (isset($selectParams['payType']) && !empty($selectParams['payType'])) { $condition .= ' and find_in_set('.$selectParams['payType'].',o.payType) '; } // 客户类型 if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])){ $condition .= ' AND o.customerType = '.$selectParams['customerType']; } // 订单来源 订单来源 默认1 ios 2android 3小程序 4后台创建 if (isset($selectParams['source']) && !empty($selectParams['source'])){ $condition .= ' AND o.source = '.$selectParams['source']; } //出库状态 if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) { $condition .= ' and o.outStatus = ' . $selectParams['outStatus']; } //退货状态 if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) { if (is_array($selectParams['returnStatus'])) { $returnStatusStr = implode(',', $selectParams['returnStatus']); $condition .= ' and o.returnStatus in(' . $returnStatusStr . ') '; } else { $condition .= ' and o.returnStatus = ' . $selectParams['returnStatus']; } } //订单状态 if (isset($selectParams['state']) && !empty($selectParams['state'])) { $condition = self::orderStateSql($condition, $selectParams['state']); } if($export){ $sql ='SELECT o.*,g.goodsCode,g.goodsName,g.unitName,g.specGroup,g.buyNum,g.price,g.otherNum,g.preferential,g.totalMoney,r.realName, r.mobile,r.provinceCode,r.cityCode,r.districtCode,r.address FROM '.$orderTab.' AS o LEFT JOIN '.$orderGoodsTab.' as g ON o.id =g.orderId LEFT JOIN '.$orderReceive.' AS r on o.id= r.orderId WHERE o.deleteStatus='.StatusCode::$standard.$whereSql.$condition.' order by o.id desc '; $orderGoodsData = $this->objDOrder->exportQuery($sql); if ($orderGoodsData === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $result = self::exportOrderList($orderGoodsData); exit; } $sql ='SELECT o.* FROM '.$orderTab.' AS o LEFT JOIN '.$orderGoodsTab.' as g ON o.id =g.orderId LEFT JOIN '.$orderReceive.' AS r on o.id= r.orderId WHERE o.deleteStatus='.StatusCode::$standard.$whereSql.$condition.' GROUP BY o.id order by o.createTime desc '.$limit; $dbResult = $this->objDOrder->query($sql); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } // 格式化后台订单列表 $formatResult = self::formatManageOrderList($dbResult,[]); if (!$formatResult->isSuccess()) { return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode()); } $sqlTotal ='SELECT count( DISTINCT o.id) as total FROM '.$orderTab.' AS o LEFT JOIN '.$orderGoodsTab.' as g ON o.id =g.orderId LEFT JOIN '.$orderReceive.' AS r on o.id= r.orderId WHERE o.deleteStatus='.StatusCode::$standard.$whereSql.$condition; $total = $this->objDOrder->query($sqlTotal); if ($total === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $return = [ 'data' => $formatResult->getData(), 'total' => isset($total[0]['total']) ? $total[0]['total'] : 0, ]; return ResultWrapper::success($return); } /** * 获取检索订单数据导出 * @param $orderListData * @return ResultWrapper */ public function exportOrderList($orderListData) { //导出到本地 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 ($orderListData as $value) {//循环数据 $orderReceiveData[]= [ 'orderId' => $value['id'], 'provinceCode' => $value['provinceCode'], 'cityCode' => $value['cityCode'], 'districtCode' => $value['districtCode'], 'allAddress' => $value['allAddress'] ]; // 格式化后台订单列表 $fromatValue = self::formatManageOrderList([$value],$orderReceiveData); if (!$fromatValue->isSuccess()) { echo($fromatValue->getData()); exit(); } $fromatValue = array_pop($fromatValue->getData()); $value = array_merge($value, $fromatValue); $num++; if ($num == $limit) { ob_flush();//释放内存 flush(); } $rows['id'] = isset($value['id']) ? $value['id'] : null; // ID $rows['no'] = isset($value['no']) ? $value['no'] : null; // 订单编号 $rows['totalMoney'] = isset($value['totalMoney']) ? $value['totalMoney'] : null; // 订单金额 $rows['subMoney'] = isset($value['payAmount']) && isset($value['totalMoney']) ? bcsub($value['payAmount'], $value['totalMoney'], 2): 0; // 订单金额 $rows['payAmount'] = isset($value['payAmount']) ? $value['payAmount'] : null; // 付款金额 $rows['orderMsg'] = isset($value['orderMsg']) ? $value['orderMsg'] : null; // 订单状态 $rows['payTypeMsg'] = isset($value['payTypeMsg']) ? $value['payTypeMsg'] : null; // 支付方式 $rows['payMsg'] = isset($value['payMsg']) ? $value['payMsg'] : null; // 付款状态 $rows['deliveryMsg'] = isset($value['deliveryMsg']) ? $value['deliveryMsg'] : null; // 配送方式 $rows['sourceMsg'] = isset($value['sourceMsg']) ? $value['sourceMsg'] : null; // 订单来源 $rows['auditMsg'] = isset($value['auditMsg']) ? $value['auditMsg'] : null; // 审核状态 $rows['createTime'] = isset( $value['createTime']) ? date('Y-m-d H:i:s', $value['createTime']) : null; // 下单时间 $rows['customerName'] = isset($value['customerName']) ? $value['customerName'] : null; // 客户名称 $rows['receiveName'] = isset($value['realName']) ? $value['realName']: null; // 收货人 $rows['receiveMobile'] = isset($value['mobile']) ? $value['mobile'] : null; // 收货人电话 $rows['receiveAddress'] = isset($value['receiveData']['allAddress']) ? $value['receiveData']['allAddress'] : null;// '收货人地址' $rows['shopName'] = isset($value['shopName']) ? $value['shopName'] : null; // ,'所属店铺', $rows['salesManName'] = isset($value['salesManName']) ? $value['salesManName'] : null; // '业务员' $rows['otherNum'] = getArrayItem($value, 'otherNum', 0); //件数 $rows['goodsCode'] = getArrayItem($value, 'goodsCode'); // '商品编码' $rows['goodsName'] = getArrayItem($value, 'goodsName'); // '商品名称 $rows['unitName'] = getArrayItem($value, 'unitName'); // 单位 $rows['specName'] = self::createSpecName((isset($value['specGroup']) && !empty($value['specGroup'])) ? json_decode($value['specGroup'], true) : []); $rows['buyNum'] = getArrayItem($value, 'buyNum', 0); $rows['unitPrice'] = getArrayItem($value, 'price', 0); $rows['preferential'] = getArrayItem($value, 'preferential', 0); $rows['totalPrice'] = getArrayItem($value, 'totalMoney', 0); // '销售单价(元)' foreach ($rows as $kk => $vv) { $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码 } fputcsv($fp, $rs); $rows = []; } } /** * 根据订单列表 keywordType 拼装sql * @param $keywordType * @param $keyword */ public function assemblySql($keywordType,$keyword) { $whereSql = ''; switch ($keywordType){ case 1: // 单据编号 order if(strpos($keyword,StatusCode::$noPrefix[1]) !== false){ $orderNo = explode('-',$keyword); if(count($orderNo)==3){ $orderNo = $orderNo[1].'-'.$orderNo[2]; }elseif(count($orderNo)==2){ $orderNo = $orderNo[1]; }else{ $orderNo = $keyword; } $whereSql .= ' and o.no = "'.$orderNo.'"'; }else{ $whereSql .= ' and o.no = "'.$keyword.'"'; } break; case 2: // 自提码 order $whereSql .= ' and o.verifyCode ="'.$keyword.'"'; break; case 3: // 商品名称 order_goods $whereSql .=' and g.goodsName LIKE "%' .$keyword. '%" '; break; case 4: // 商品编码 order_goods $whereSql .=' and g.goodsCode ="'.$keyword.'"'; break; case 5: // 收货人 order_receive $whereSql .=' and r.realName LIKE "%' .$keyword. '%" '; break; case 6: // 电话 order_receive $whereSql .=' and r.mobile ="'.$keyword.'"'; break; case 7: // 业务员 order $whereSql .=' and o.salesManName LIKE "%' .$keyword. '%" '; break; case 8: // 详细地址 order_receive $whereSql .=' and r.address LIKE "%' .$keyword. '%" '; } return $whereSql; } /** * Doc: (des="state标示多选sql处理") * */ private static function orderStateSql($sql, $states) { if (is_array($states)) { if (in_array('all', $states)) { return $sql; } foreach ($states as $index => $state) { $sql .= $index == 0 ? ' and (' . self::orderstate($state) : ' or ' . self::orderstate($state); } $sql .= ') '; } else { if ($states == 'all') { return $sql; } $stateSql = self::orderstate($states); if (!empty($stateSql)) { $sql .= ' and ' . self::orderstate($states); } } return $sql; } /** * Doc: (des="state标示对应sql") */ private static function orderstate($state) { $sql = ''; switch ($state) { case 'waitAudit'://待审核 $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditing'] . ' and o.orderStatus != ' . StatusCode::$orderStatus['close'] . ')'; break; case 'waitOutStock'://待出库 $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and (o.orderStatus = ' . StatusCode::$orderStatus['waitPay'] . ' or orderStatus = ' . StatusCode::$orderStatus['waitDelivery'] . ')) '; break; case 'hasOutStock'://已出库 $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and o.orderStatus = ' . StatusCode::$orderStatus['waitReceive'] . ')'; break; case 'finish'://已完成 $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and o.orderStatus = ' . StatusCode::$orderStatus['finish'] . ')'; break; case 'close'://已关闭 $sql .= ' (o.orderStatus = ' . StatusCode::$orderStatus['close'] . ')'; break; case 'all'://全部订单 break; } return $sql; } /** * Doc: (des="格式化后台订单列表") * User: XMing * Date: 2020/7/11 * Time: 5:02 下午 * @param array $orderData * @param array $orderReceiveData * @param array $orderGoodsData * @return ResultWrapper */ public function formatManageOrderList(array $orderData, array $orderReceiveData, array $orderGoodsData = []) { $returnData = []; if (empty($orderData)) { return ResultWrapper::success($returnData); } $receiveMap = []; if (!empty($orderReceiveData)) { $orderReceiveData = self::formatSysArea($orderReceiveData);// 订单收货地址集渲染 foreach ($orderReceiveData as $key => &$item) { $receiveMap[$item['orderId']] = [ 'customerId' => getArrayItem($item, 'customerId', 0), 'address' => getArrayItem($item, 'address'), 'allAddress' => $item['area']['provinceName'].$item['area']['cityName'].$item['area']['districtName'].getArrayItem($item, 'address'), 'realName' => getArrayItem($item, 'realName'), 'mobile' => getArrayItem($item, 'mobile'), 'area' => getArrayItem($item, 'area', []) ]; } unset($item); } $orderData = self::formatOrderStatus($orderData); // 格式化订单状态 $goodsMap = []; if (!empty($orderGoodsData)) { foreach ($orderGoodsData as $key => $item) { $goodsMap[$item['orderId']][] = $item; } } unset($item); // 映射下打印次数 $allOrderNos = []; foreach ($orderData as $key => $value){ $allOrderNos[] = $value['no']; } $pbjMPrintNum = new MPrintNum($this->onlineEnterpriseId); $printNumData = $pbjMPrintNum->getObjectPrintNumByNos($allOrderNos); // 批量获取打印次数 $orderNoBindPritNum = []; if(!empty($printNumData)){ foreach ($printNumData as $key => $value){ $orderNoBindPritNum[$value['objectNo']] = $value['printNum']; } } foreach ($orderData as $key => $datum) { $returnData[$key] = [ 'id' => $datum['id'], 'no' => self::formatSn($datum['no']), 'shopId' => $datum['shopId'], 'shopName' => isset($datum['shopName']) ? $datum['shopName'] : '', 'customerId' => $datum['customerId'], 'customerName' => $datum['customerName'], 'userCenterId' => $datum['userCenterId'], 'payAmount' => $datum['payAmount'], 'retMoney' => $datum['retMoney'], 'totalMoney' => $datum['totalMoney'], 'payStatus' => $datum['payStatus'], 'auditStatus' => $datum['auditStatus'], 'returnStatus' => $datum['returnStatus'], 'outStatus' => $datum['outStatus'], 'deliveryType' => $datum['deliveryType'], 'payType' => $datum['payType'], 'salesManName' => empty($datum['salesManName']) ? '' : $datum['salesManName'], 'salesman' => !isset($datum['salesman']) || is_null($datum['salesman']) ? '' : $datum['salesman'], 'salesManId' => $datum['salesManId'], 'createTime' => $datum['createTime'], 'source' => $datum['source'], 'orderStatus' => $datum['orderStatus'], 'receiveData' => isset($receiveMap[$datum['id']]) ? $receiveMap[$datum['id']] : [], 'orderMsg' => $datum['orderMsg'], 'payMsg' => $datum['payMsg'], 'deliveryMsg' => $datum['deliveryMsg'], 'payTypeMsg' => $datum['payTypeMsg'], 'sourceMsg' => $datum['sourceMsg'], 'auditMsg' => $datum['auditMsg'], 'extends' => json_decode($datum['extends'],true), 'printingNum' => getArrayItem($orderNoBindPritNum, $datum['no'], 0), ]; if (!empty($orderGoodsData)) { $returnData[$key]['goodsData'] = isset($goodsMap[$datum['id']]) ? $goodsMap[$datum['id']] : []; } } return ResultWrapper::success($returnData); } private static function formatSn($no): string { return StatusCode::$noPrefix[StatusCode::$orderType['saleOrder']].'-'.$no; } /** * Doc: (des="订单查询index表 sql生成") * User: XMing * Date: 2020/7/11 * Time: 11:23 上午 * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1 * @waitOutStock:待出库 orderStatus != 6 auditPass = 2 * @hasOutStock:已出库 orderStatus = 4 auditPass = 2 * @finish:已完成 orderStatus = 5 auditPass 2 * @close:已关闭 orderStatus = 6 * @param array $selectParams * @return array */ public function setOrderStatusSqlAttr(array $selectParams): array { $fields = 'id,userCenterId,no,customerId'; $countFields = ' COUNT(id) AS total '; //订单类型 $whereSql = ''; if (isset($selectParams['orderType']) && !empty($selectParams['orderType'])) { if (is_array($selectParams['orderType'])) { $orderTypeStr = implode(',', $selectParams['orderType']); $whereSql .= ' and orderType in(' . $orderTypeStr . ') '; } else { $whereSql .= ' and orderType = ' . $selectParams['orderType']; } } else { $whereSql .= ' and orderType = ' . StatusCode::$orderType['saleOrder']; } if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])){ if (strstr($selectParams['keyword'],StatusCode::$noPrefix['1'])){ $selectParams['keyword']= substr($selectParams['keyword'],strlen(StatusCode::$noPrefix[StatusCode::$orderType['saleOrder']])+1); } $keyword = '"%'.$selectParams['keyword'].'%"'; $whereSql .= ' and no LIKE '.$keyword.' or verifyCode LIKE '.$keyword; } if (isset($selectParams['orderType']) && $selectParams['orderType'] == StatusCode::$orderType['cashierOrder']) { $selectParams['cashierUid'] = $this->onlineUserId; } if (isset($selectParams['isAll']) && $selectParams['isAll'] == StatusCode::$standard) { unset($selectParams['cashierUid']); } //userCenterId if (isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])) { $whereSql .= ' and userCenterId = ' . $selectParams['userCenterId']; } //customerId if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) { $whereSql .= ' and customerId = ' . $selectParams['customerId']; } //收银员id if (isset($selectParams['cashierStaffId']) && !empty($selectParams['cashierStaffId'])) { $whereSql .= ' and cashierStaffId = ' . $selectParams['cashierStaffId']; } //no if (isset($selectParams['no']) && !empty($selectParams['no'])) { $whereSql .= ' and no = "' . $selectParams['no'].'"'; } //shopId if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) { $whereSql .= ' and shopId = ' . $selectParams['shopId']; } //收银员id if (isset($selectParams['cashierUid']) && !empty($selectParams['cashierUid'])) { $whereSql .= ' and cashierUid = ' . $selectParams['cashierUid']; } //审核状态 if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) { $whereSql .= ' and auditStatus = ' . $selectParams['auditStatus']; } //出库状态 if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) { $whereSql .= ' and outStatus = ' . $selectParams['outStatus']; } //退货状态 if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) { if (is_array($selectParams['returnStatus'])) { $returnStatusStr = implode(',', $selectParams['returnStatus']); $whereSql .= ' and returnStatus in(' . $returnStatusStr . ') '; } else { $whereSql .= ' and returnStatus = ' . $selectParams['returnStatus']; } } //配送方式 if (isset($selectParams['deliveryType']) && !empty($selectParams['deliveryType'])) { $whereSql .= ' and deliveryType = ' . $selectParams['deliveryType']; } //支付方式 if (isset($selectParams['payType']) && !empty($selectParams['payType'])) { $whereSql .= ' and find_in_set('.$selectParams['payType'].',payType) '; } if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){ $whereSql .= ' AND createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime']; } if (isset($selectParams['source']) && !empty($selectParams['source'])){ $whereSql .= ' AND source = '.$selectParams['source']; } if (isset($selectParams['salesManId']) && !empty($selectParams['salesManId'])){ $whereSql .= ' AND salesManId = '.$selectParams['salesManId']; } if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])){ $whereSql .= ' AND customerType = '.$selectParams['customerType']; } //订单状态 if (isset($selectParams['state']) && !empty($selectParams['state'])) { $whereSql = self::buildStateSqlAttr($whereSql, $selectParams['state']); } //数据域 if (isset($selectParams['orderType']) && $selectParams['orderType'] == StatusCode::$orderType['cashierOrder'] && isset($selectParams['cashierUid']) && !empty($selectParams['cashierUid'])) { //收银台列表 } else { $whereSql = parent::getSalesManQueryParams($whereSql); } $whereSql = parent::getShopIdQueryParams($whereSql); $whereSql .= ' order by createTime desc'; $sql = 'select ' . $fields . ' from qianniao_order_index_' . $this->onlineEnterpriseId . ' where deleteStatus = ' . StatusCode::$standard.$whereSql; $countSql = 'select ' . $countFields . ' from qianniao_order_index_' . $this->onlineEnterpriseId . ' where deleteStatus = ' . StatusCode::$standard.$whereSql; return [ 'sql' => $sql, 'countSql' => $countSql ]; } /** * Doc: (des="state标示多选sql处理") * User: XMing * Date: 2020/7/13 * Time: 9:38 上午 * @param string $sql * @param mixed $states * @return string */ private static function buildStateSqlAttr(string $sql, $states) { if (is_array($states)) { if (in_array('all', $states)) { return $sql; } foreach ($states as $index => $state) { $sql .= $index == 0 ? ' and (' . self::stateSql($state) : ' or ' . self::stateSql($state); } $sql .= ') '; } else { if ($states == 'all') { return $sql; } $stateSql = self::stateSql($states); if (!empty($stateSql)) { $sql .= ' and ' . self::stateSql($states); } } return $sql; } /** * Doc: (des="state标示对应sql") * User: XMing * Date: 2020/7/13 * Time: 9:43 上午 * @param string $state * @return string */ private static function stateSql(string $state) { $sql = ''; switch ($state) { case 'waitAudit'://待审核 $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditing'] . ' and orderStatus != ' . StatusCode::$orderStatus['close'] . ')'; break; case 'waitOutStock'://待出库 $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and (orderStatus = ' . StatusCode::$orderStatus['waitPay'] . ' or orderStatus = ' . StatusCode::$orderStatus['waitDelivery'] . ')) '; break; case 'hasOutStock'://已出库 $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and orderStatus = ' . StatusCode::$orderStatus['waitReceive'] . ')'; break; case 'finish'://已完成 $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and orderStatus = ' . StatusCode::$orderStatus['finish'] . ')'; break; case 'close'://已关闭 $sql .= ' (orderStatus = ' . StatusCode::$orderStatus['close'] . ')'; break; case 'all'://全部订单 break; } return $sql; } /** * 删除订单视图 */ public function dropView() { $sql = 'DROP VIEW ' . $this->orderStatisticsTableName . '_' . $this->onlineEnterpriseId; $dbResult = $this->objDOrder->query($sql); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } return ResultWrapper::success('删除成功'); } /** * 判断表是否存在 * @param $tableName */ public function existsTable($tableName) { $exists = $this->objDOrder->existsTable($tableName); if (!$exists) { //不存在删除视图 self::dropView(); } } /** * 添加银行打款数据 */ public function addOrderBankData($orderBankData) { //切换分表 $fix = $fix = ceil($this->onlineUserId / $this->cutTable); $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix); foreach ($orderBankData['orderId'] as $key => $value){ //获取订单信息 $orderData = $this->objDOrder->get(['id' => $value]); if ($orderData === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if(empty($orderData)){ return ResultWrapper::fail('订单不存在', ErrorCode::$contentNotExists); } $orderData['extends'] = json_decode($orderData['extends'], true); $orderData['extends']['bankData'] = $orderBankData['bankData']; $orderData['extends'] = json_encode($orderData['extends']); $dbReuslt = $this->objDOrder->update(['extends'=>$orderData['extends'],'updateTime'=>time()], $value); if ($dbReuslt === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } } return ResultWrapper::success($dbReuslt); } /** * Doc: (des="审核订单,到出库单") * User: XMing * Date: 2020/7/14 * Time: 6:38 下午 * @param array $params * @return ResultWrapper * @throws \Exception */ public function updateAuditStatus(array $params) { $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $orderIndex = $this->objDOrderIndex->get(['id' => $params['id']]); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('没有找到订单信息', ErrorCode::$paramError); } if ($orderIndex['auditStatus'] == StatusCode::$auditStatus['auditPass']) { return ResultWrapper::fail('当前订单已经审核通过!', ErrorCode::$paramError); } if ($this->isCashier === false) { //在线支付的订单必须是已支付才能审核 if ($orderIndex['payType'] == StatusCode::$payType['wxPay'] || $orderIndex['payType'] == StatusCode::$payType['aliPay']) { if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass'] && $orderIndex['payStatus'] == StatusCode::$delete) { return ResultWrapper::fail('订单尚未支付,不能审核', ErrorCode::$notAllowAccess); } } } //切换分表 $fix = $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix); //获取订单信息 $orderData = $this->objDOrder->get(['id' => $params['id']]); if ($orderData === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } // 银行打款支付方式审核之前需要判断是否上传凭证 if( $orderData['payType'] == StatusCode::$payType['bankLoans'] ){ $extends = json_decode($orderData['extends'],true); if (!array_key_exists('bankData',$extends)){ return ResultWrapper::fail('该订单未上传银行打款凭证', ErrorCode::$paramError); } $customerData = $this->objDCustomer->get(['id'=>$orderData['customerId']]); if ($customerData === false) { return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } if(isset($customerData['openId']) && !empty($customerData['openId'])){ // 银行打款上传凭证小程序订阅消息 $sendMessageData = [ 'date4' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime'])], // 提交时间 'thing10' => [ 'value' => $customerData['name'] ], // 申请人 'thing2' => [ 'value' => '银行打款凭证是否通过'], // 审核内容 'date3' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 审核时间 'phrase1' => [ 'value' => $orderData['auditStatus'] == StatusCode::$auditStatus['auditPass'] ? '审核通过':'审核未通过'], // 审核结果 ]; $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMSystemPushMessage->sendWeiXinPushMessage(4, $customerData['openId'], $sendMessageData); if(!$result->isSuccess()){ file_put_contents('/www/wwwroot/logs/api.junhailan.com/wexinPushMessage.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND); } } } $this->objDOrderIndex->beginTransaction(); // 生成收款单 $receivedResult = self::createReceived($orderData); if (!$receivedResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode()); } $update = [ 'auditStatus' => $params['auditStatus'], 'updateTime' => time(), ]; if ( $orderData['payType'] == StatusCode::$payType['bankLoans'] ){//银行打款更新payStatus,orderStatus $update = [ 'auditStatus' => $params['auditStatus'], 'payStatus' => StatusCode::$standard, 'orderStatus' => StatusCode::$orderStatus['waitDelivery'], 'updateTime' => time(), ]; } //操作索引表 $orderIndexUpdate = $this->objDOrderIndex->update($update, ['id' => $params['id']]); if ($orderIndexUpdate === false) { $this->objDOrderIndex->rollBack(); Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $this->objDOrderIndex->error()); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } //操作订单表 $orderUpdate = $this->objDOrder->update($update, $params['id']); if ($orderUpdate === false) { $this->objDOrderIndex->rollBack(); Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $this->objDOrder->error()); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } //订单审核出库 $outId = 0; if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass']) { $orderData['auditId'] = $params['auditId']; $orderData['audit'] = $params['audit']; $addInventoryOutResult = self::addInventoryOut($params['id'], $orderData, $orderData['userCenterId']); if (!$addInventoryOutResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($addInventoryOutResult->getData(), $addInventoryOutResult->getErrorCode()); } $outId = $addInventoryOutResult->getData(); } $this->objDOrderIndex->commit(); /* //跟新es $_id = self::createEsDocumentId($params['id']); $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/ self::runProcessNextOut($outId,$orderData); if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass']) { return ResultWrapper::success($outId); } if(isset($customerData['openId']) && !empty($customerData['openId'])){ // 订单审核通过 $sendMessageData = [ 'date4' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime'])], // 提交时间 'thing2' => [ 'value' => '银行打款凭证是否通过'], // 审核内容 'phrase1' => [ 'value' => $orderData['auditStatus'] == 2 ? '审核通过':'审核未通过'], // 审核结果 'date3' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 审核时间 ]; $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMSystemPushMessage->sendWeiXinPushMessage(6, $customerData['openId'], $sendMessageData); if(!$result->isSuccess()){ file_put_contents('/www/wwwroot/logs/api.junhailan.com/shenhe.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND); } } return ResultWrapper::success('操作成功'); } /** * Doc: (des="step 3: 审核出库") * User: XMing * Date: 2020/11/9 * Time: 9:24 上午 * @param array $order * @param int $outId * @return ResultWrapper * @throws \Exception */ private function runProcessNextOut(int $outId,array $order): ResultWrapper { if (empty($outId)){ return ResultWrapper::success(true); } if ($order['orderType'] != StatusCode::$orderType['saleOrder']){ return ResultWrapper::success(true); } $setResult = $this->objMProcessSetting->getProcessSettingByType(StatusCode::$processType['sales'],'out'); if (!$setResult->isSuccess()){ Logger::logs(E_USER_ERROR,'获取流程配置出错',__CLASS__,__LINE__,$setResult->getData()); return ResultWrapper::fail($setResult->getData(),$setResult->getErrorCode()); } $set = $setResult->getData(); if (empty($set)){ Logger::logs(E_USER_ERROR,'配置为空',__CLASS__,__LINE__,''); return ResultWrapper::success(true); } if (isset($set['enableStatus']) && $set['enableStatus'] == StatusCode::$standard){ Logger::logs(E_USER_ERROR,'配置',__CLASS__,__LINE__,$set); return ResultWrapper::success(true); } $params = [ 'id' => $outId, 'auditId' => $this->onlineUserId,//操作人id 'auditName' => '自动审核',//操作人姓名 ]; $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId); $result = $objMInventoryOut->updateInventoryOutStatus($params); if (!$result->isSuccess()){ Logger::logs(E_USER_ERROR,'自动审核出库单出错',__CLASS__,__LINE__,$result->getData()); return ResultWrapper::fail($result->getData(),$result->getErrorCode()); } Logger::logs(E_USER_ERROR,'自动审核出库单成功',__CLASS__,__LINE__,$outId); return ResultWrapper::success(true); } /** * Doc: (des="后台代客下单创建收款单") * User: XMing * Date: 2020/11/5 * Time: 5:31 下午 * @param array $orderData * @return ResultWrapper * @throws \Exception */ private function createReceived(array $orderData): ResultWrapper { // 银行打款 if ($orderData['payType'] == StatusCode::$payType['bankLoans']){ $orderExtendsData = json_decode($orderData['extends'], true); // 组装收款单账户数据 $accountListData[] = [ 'discountMoney' => 0, 'money' => $orderData['payAmount'], 'payWay' => StatusCode::$payType[4], 'remark' => '银行打款生成收款', 'accountId' => ($orderExtendsData['bankData']['id']) ? : 0, 'accountName' => ($orderExtendsData['bankData']['name']) ? : '', 'accountNumber' => ($orderExtendsData['bankData']['accountNumber']) ? : '', 'finalMoney' => $orderData['payAmount'], ]; $orderData['accountList'] = json_encode($accountListData); $orderData['currentAccountName'] = ($orderExtendsData['bankData']['name']) ? : ''; } //生成收款单 if ( ($orderData['orderType'] == StatusCode::$orderType['saleOrder'] || $orderData['orderType'] == StatusCode::$orderType['salesSlip']) && $orderData['source'] == StatusCode::$source['manage'] && !empty($orderData['accountList']) && !empty(floatval($orderData['receivedMoney'])) || ( $orderData['payType'] == StatusCode::$payType['bankLoans'] )//银行打款也生成收款单 ) { $this->objDOrderIndex->beginTransaction(); //生成收款单 $objMReceived = new MReceived($this->onlineEnterpriseId, $this->onlineUserId); //创建收款单 $received = [ 'currentAccountName' => $orderData['currentAccountName'], 'financeType' => '银行打款收款', 'financeTypeId' => 2, 'shopId' => $orderData['shopId'], 'shopName' => $orderData['shopName'], 'receiptTime' => time(), 'operatorId' => $this->onlineUserId, 'accountList' => json_decode($orderData['accountList'], true), 'customerId' => $orderData['customerId'], 'customerName' => $orderData['customerName'], 'sourceNo' => $orderData['no'], 'sourceId' => $orderData['id'], 'originId' => $orderData['id'], 'originNo' => $orderData['originNo'], 'sourceNoMoney' => $orderData['receivedMoney'], 'extends' => isset($orderExtendsData['bankData']) ? json_encode($orderExtendsData['bankData']) : '[]', 'createTime' => time(), 'auditStatus' => StatusCode::$auditStatus['auditing'], 'updateTime' => time(), ]; $receivedResult = $objMReceived->addReceived($received, true); if (!$receivedResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode()); } $up = []; if ($orderData['receivedMoney'] >= $orderData['payAmount']) { $up = [ 'payStatus' => StatusCode::$standard, 'updateTime' => time(), ]; }else{ if ($orderData['receivedMoney'] != 0){ $up = [ 'payStatus' => StatusCode::$offline,//部分收款 'updateTime' => time(), ]; } } if (!empty($up)){ $result = $this->objDOrderIndex->update($up, $orderData['id']); if ($result === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $result = $this->objDOrder->update($up, $orderData['id']); if ($result === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } } $this->objDOrderIndex->commit(); } return ResultWrapper::success(true); } /** * Doc: (des="订单审核出库,使用此方法一定要注意在上文获取当前订单的userCenterId用于下文切换分表") * User: XMing * Date: 2020/7/15 * Time: 9:48 上午 * @param array $orderData * @param int $id * @param int $thisOnlineUserId 当前订单的用户id,用来切换分表 * @return ResultWrapper * @throws \Exception */ private function addInventoryOut(int $id, array $orderData, int $thisOnlineUserId) { //查询订单商品表 $objMOrderGoods = new MOrderGoods($thisOnlineUserId, $this->onlineEnterpriseId); $selectData = ['orderId' => $id]; $orderGoodsDataObj = $objMOrderGoods->getOrderGoodsByOrderIds($selectData); if (!$orderGoodsDataObj->isSuccess()) { return ResultWrapper::fail($orderGoodsDataObj->getData(), ErrorCode::$dberror); } $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId); $totalResult = $objMInventoryOut->getTotalByOrderId($orderData['id']); if (!$totalResult->isSuccess()){ return ResultWrapper::fail($totalResult->getData(),$totalResult->getErrorCode()); } $total = (int)$totalResult->getData(); if ($total > 0){ //已经生成过出库单了 Logger::logs(E_USER_ERROR, '订单id:'.$orderData['id'].',重复生成出库单', __CLASS__, __LINE__,$orderData); return ResultWrapper::fail('不要重复操作,避免生成成多个出库单',ErrorCode::$paramError); } //查询商铺id对应的仓库数据 $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $modelResult = $objMShop->getShopDataByShopIds([$orderData['shopId']]); if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $shopData = $modelResult->getData(); unset($modelResult); //获取订单收货信息 $orderReceiveDbResult = []; if ($orderData['deliveryType'] == StatusCode::$deliveryType['goodsDelivery']) { $fix = ceil($thisOnlineUserId / $this->cutTable); $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix); $orderReceiveDbResult = $this->objDOrderReceive->get(['orderId' => $id]); if ($orderReceiveDbResult === false) { return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror); } if (empty($orderReceiveDbResult)) { return ResultWrapper::fail('订单收货地址查询失败', ErrorCode::$dberror); } } $objMCustomer = new MCustomer($this->onlineEnterpriseId,$this->onlineUserId); $customerResult = $objMCustomer->getCustomerByCustomerId($orderData['customerId']); if (!$customerResult->isSuccess()){ return ResultWrapper::fail($customerResult->getData(),$customerResult->getErrorCode()); } $customer = $customerResult->getData(); $orderGoodsData = $orderGoodsDataObj->getData();//订单商品数据 $saleOutData = [ 'sourceId' => $orderData['id'], 'sourceNo' => $orderData['no'], 'originNo' => $orderData['no'], 'originId' => $orderData['id'], 'shopId' => $orderData['shopId'], 'shopName' => $orderData['shopName'], 'amount' => $orderData['payAmount'], 'operatorId' => $orderData['auditId'],//操作人id 'operatorName' => $orderData['audit'],//操作人信息 'customerId' => $orderData['customerId'], 'customerName' => $orderData['customerName'], 'customerCode' => createCode(StatusCode::$code['customer']['prefix'], $orderData['customerId'], StatusCode::$code['customer']['length']), 'customerMobile' => isset($customer['mobile']) ? $customer['mobile'] : '', 'source' => StatusCode::$orderType['saleOrder'], //订单来源(出库类型) 'type' => StatusCode::$orderType['saleOut'], 'deliveryType' => $orderData['deliveryType'],//配送方式 'remark' => $orderData['remark'], ]; $saleOutData['materielNum'] = 0; //获取sku $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId); $skuIds = array_column(array_values($orderGoodsData), 'skuId'); $modelResult = $objMSku->getSkuDataBySkuIds($skuIds); if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $skuData = $modelResult->getData(); unset($modelResult); foreach ($orderGoodsData as $key => $value) { $saleOutData['materielNum']++; $totalMoney = bcsub(bcsub($value['totalMoney'], $value['vipDiscount']), $value['preferential']);//销售总价 !优惠后 $saleOutData['orderGoodsData'][] = [ 'materielId' => $value['goodsBasicId'], 'materielName' => $value['goodsName'], 'materielCode' => createCode(StatusCode::$code['goodsBasic']['prefix'], $value['goodsBasicId'], StatusCode::$code['goodsBasic']['length']), 'skuId' => $value['skuId'], 'num' => $value['buyNum'], 'otherNum' => $value['otherNum'], 'outNum' => 0, 'total' => $value['buyNum'], 'unitName' => isset($value['unitName']) ? $value['unitName'] : '', 'skuName' => isset($skuData[$value['skuId']]) ? $skuData[$value['skuId']]['skuName'] : '', 'unitPrice' => $value['price'],//单价 不优惠 'totalPrice' => $totalMoney,//销售总价 !优惠后 'extend' => $value['extends'], 'isEq' => $value['isEq'], ]; } $dbResult = $objMInventoryOut->addInventoryOut($saleOutData); if (!$dbResult->isSuccess()) { Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $dbResult->getData()); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } self::noticeStatistics([ 'userCenterId' => $thisOnlineUserId, 'enterpriseId' => $this->onlineEnterpriseId, 'customerId' => $orderData['customerId'], 'no' => $orderData['no'], 'noticeType' => 'audit',//审核 ], 'MOrderStatistics'); //添加日志 parent::saveLog([ 'no' => $orderData['no'], 'actionType' => '审核通过', 'operationData' => '', 'userCenterId' => $this->onlineUserId, 'enterpriseId' => $this->onlineEnterpriseId, 'createTime' => time(), ]); self::sendMessage($this->onlineEnterpriseId,'NewOrder','stockOut'); return ResultWrapper::success($dbResult->getData()); } /** * 批量审核 * @param array $params * @return ResultWrapper * @throws \Exception */ public function batchUpdateAuditStatus(array $params) { $auditParam = [ 'audit' => $params['audit'], 'auditId' => $params['auditId'], 'auditStatus' => $params['auditStatus'] ]; foreach ($params['ids'] as $id) { $auditParam['id'] = $id; $result = self::updateAuditStatus($auditParam); if (!$result->isSuccess()) { return ResultWrapper::fail($result->getData(), $result->getErrorCode()); } } return ResultWrapper::success("审核成功"); } /** * Doc: (des="修改订单的状态,orderStatus") * User: XMing * Date: 2020/7/14 * Time: 5:25 下午 * @param $id * @param $selectParams * @param array $header * @return ResultWrapper * @throws \Exception */ public function updateOrderStatus($id, $selectParams, array $header) { // 查询订单索引表数据 $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $orderIndex = $this->objDOrderIndex->get(['id' => $id], 'userCenterId,payStatus,createTime,customerId,no,updateTime'); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('订单信息不存在', ErrorCode::$paramError); } // 后台设置的审核通过不能取消订单 $objEnterpriseCache = new EnterpriseCache(); $enterSettingData = $objEnterpriseCache->getEnterpriseSetting($this->onlineEnterpriseId); if(isset($enterSettingData['cancelOrder']) && $enterSettingData['cancelOrder'] == StatusCode::$delete && $orderIndex['auditStatus'] == StatusCode::$auditStatus['auditPass'] && $selectParams['orderStatus'] == StatusCode::$orderStatus['close']){ return ResultWrapper::fail('当前订单已经审核通过,暂不支持取消,请联系客服处理', ErrorCode::$notAllowAccess); } if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close'] && isset($orderIndex['outStatus']) && $orderIndex['outStatus'] == StatusCode::$standard) { return ResultWrapper::fail('已经发货订单不能取消', ErrorCode::$paramError); } // 切换订单分表,查询订单主单据数据 $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);; $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix); $orderData = $this->objDOrder->get(['id' => $id]); if($orderData === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if(empty($orderData)){ return ResultWrapper::fail('要操作的订单不存在', ErrorCode::$contentNotExists); } $this->objDOrderIndex->beginTransaction(); $selectParams['cancelbeforeOrderStatus'] = $orderData["orderStatus"]; // 更新订单表 $orderData['extends'] = json_decode($orderData['extends'], true); if( !empty($selectParams['cancelReason']) ){ $orderData['extends']['cancelReason'] = $selectParams['cancelReason']; $orderData['extends']['cancelbeforeOrderStatus'] = $selectParams['cancelbeforeOrderStatus']; $selectParams['successFullyTime'] = time(); } if( !empty($selectParams['cancelRejectReason']) ){ $orderData['extends']['cancelRejectReason'] = $selectParams['cancelRejectReason']; $selectParams['orderStatus'] = $orderData['extends']['cancelbeforeOrderStatus']; // 取消被拒恢复到取消之前的订单状态 } // 更新索引表 $orderIndexUpdate = $this->objDOrderIndex->update([ 'orderStatus' => $selectParams['orderStatus'], 'updateTime' => time() ], ['id' => $id]); if ($orderIndexUpdate === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $selectParams['extends'] = json_encode($orderData['extends']); $selectParams['updateTime'] = time(); unset($selectParams['cancelReason']); unset($selectParams['cancelRejectReason']); unset($selectParams['cancelbeforeOrderStatus']); $orderUpdate = $this->objDOrder->update($selectParams, ['id' => $id]); if ($orderUpdate === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } // 取消订单 if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close']) { // 解锁库存 $unlockResult = self::unlockInventory($id, $orderData); if (!$unlockResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($unlockResult->getData(), $unlockResult->getErrorCode()); } // 已经支付订单做自动退款处理 if($orderData['payStatus'] == StatusCode::$standard){ // 生成财务退款单 $financeRefundData = [ 'originId' => getArrayItem($orderData,'id',0), 'originNo' => getArrayItem($orderData,'no',''), 'sourceId' => getArrayItem($orderData,'id',0), 'sourceNo' => getArrayItem($orderData,'no',''), 'refundTime' => time(), 'createTime' => time(), 'updateTime' => time(), 'unitId' => getArrayItem($orderData,'customerId',0), 'unitName' => getArrayItem($orderData,'customerName',0), 'currentAccountName' => getArrayItem($orderData,'customerName',''), 'financeType' => '订单取消退款', 'financeTypeId' => 1, 'payType' =>getArrayItem($orderData,'payType',''), 'shopId' => getArrayItem($orderData,'shopId',0), 'shopName' => getArrayItem($orderData,'shopName',0), 'money' => $orderData['payAmount'], 'operatorId' => $this->onlineUserId, 'type' => StatusCode::$standard, 'auditStatus' => StatusCode::$auditStatus['auditing'], 'remark' => '订单取消,订单编号:'. getArrayItem($orderData,'no','').'需退款金额:'.$orderData['payAmount'], ]; // 根据订单支付方式规划退款账户 $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId); $extends = is_array($orderData['extends'])?$orderData['extends']: json_decode($orderData['extends'], true); if(isset($extends['admixPayData'])){ // 组合支付 foreach ($extends['admixPayData'] as $key => $value){ $financeAccountData = $objMAccount->getDefaultAccount($value['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' => $value['payMoney'], ]; } }else{ $financeAccountData = $objMAccount->getDefaultAccount($orderData['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' => $orderData['payAmount'], ] ]; } $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId); $result = $objMRefund->addRefund($financeRefundData); if(!$result->isSuccess()){ return ResultWrapper::fail($result->getData(),$result->getErrorCode()); } // 自动审核退款单 $result = $objMRefund->updateRefundStatus(['id'=>$result->getData(),'createTime'=>time()]); if(!$result->isSuccess()){ return ResultWrapper::fail($result->getData(),$result->getErrorCode()); } } // 订单审核待出库时取消订单 同步删除销售出库单 if($orderData['auditStatus'] == StatusCode::$auditStatus['auditPass']){ $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId); $inventoryOutResult = $objMInventoryOut->delInventoryOutStatus(['originId' => $orderData['id']]); if (!$inventoryOutResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($inventoryOutResult->getData(), $inventoryOutResult->getErrorCode()); } } $customerData = $this->objDCustomer->get(['id'=>$orderData['customerId']]); if ($customerData === false) { return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } if(isset($customerData['openId']) && !empty($customerData['openId'])){ // 后台取消订单小程序订阅消息 $sendMessageData = [ 'character_string13' => [ 'value' => StatusCode::$noPrefix[1] . '-' . $orderData['no']], // 订单编号 'date10' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime']) ], // 下单时间 'thing14' => [ 'value' => substr($orderData['shopName'],0,30)], // 门店名称 'date2' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 取消时间 ]; $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMSystemPushMessage->sendWeiXinPushMessage(5, $customerData['openId'], $sendMessageData); if(!$result->isSuccess()){ file_put_contents('/www/wwwroot/logs/api.junhailan.com/quxiao.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND); } } } //订单完成 if ($selectParams['orderStatus'] == StatusCode::$orderStatus['finish'] && !empty($header)) { // 计算分销订单提成 $i = 1; do { $postData = [ 'topicName' => 'MyJob', 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder', 'topicMethon' => 'updateBalance', 'topicMethonParams' => [ 'Authorization' => $header['Authorization'], 'Token' => $header['Token'], 'orderId' => $id, 'PROJECT_DOMAIN' => PROJECT_DOMAIN ], ]; $url = QIANNIAO_QUEUE . '/CAddJob/add'; $result = request($url, $postData); $i++; } while ($result['httpcode'] != 200 && $i <= 3); // 计算用户积分 start // 查询客户信息 $customerData = $this->objDCustomer->get($orderIndex['customerId']); if ($customerData === false) { return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } // 查询订单商品数据 $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix); $orderGoodsData = $this->objDOrderGoods->select(['deleteStatus'=>StatusCode::$standard,'orderId'=>$id]); if ($orderGoodsData === false) { return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } // 调用计算积分方法 $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $result = $objMCustomer->addCustomerIntegralByOrder(0, $customerData, $orderData, $orderGoodsData); if(!$result->isSuccess()){ return ResultWrapper::fail($result->getData(), $result->getErrorCode()); } //调用计算提成方法 $objMStaff = new MStaff($this->onlineEnterpriseId, $this->onlineUserId); $result = $objMStaff->addStaffRewardByOrder(0, $customerData, $orderData, $orderGoodsData); if(!$result->isSuccess()){ return ResultWrapper::fail($result->getData(), $result->getErrorCode()); } //订单完成商户结算金额 $objMMerchantSettlement = new MMerchantSettlement($this->onlineEnterpriseId, $this->onlineUserId); $updateMerchantSettlement = $objMMerchantSettlement->updateMerchantSettlement(['orderId'=>$orderData['id']]); if(!$updateMerchantSettlement->isSuccess()){ return ResultWrapper::fail($updateMerchantSettlement->getData(), $updateMerchantSettlement->getErrorCode()); } //只有小程序微信支付订单才可以计算分佣 if(!empty($orderData) && $orderData["payAmount"]>0 && $orderData["payType"]==1 && $orderData["source"]==3){ $checkData = [ "parentPath"=>$customerData["parentPath"], "payAmount"=>$orderData["payAmount"], ]; // PartnerTools::addTask($orderData["id"], $this->onlineEnterpriseId,$checkData); } } //取消订单 if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close'] && !empty($header)) { $i = 1; do { $postData = [ 'topicName' => 'MyJob', 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder', 'topicMethon' => 'cancelSubCommission', 'topicMethonParams' => [ 'Authorization' => $header['Authorization'], 'Token' => $header['Token'], 'orderId' => $id, 'PROJECT_DOMAIN' => PROJECT_DOMAIN ], ]; $url = QIANNIAO_QUEUE . '/CAddJob/add'; $result = request($url, $postData); $i++; } while ($result['httpcode'] != 200 && $i <= 3); } /* //ES更新 $_id = self::createEsDocumentId($id); $this->objDOrder->esupdateTypeFieldVaule(['orderStatus' => $selectParams['orderStatus']], $_id);*/ $this->objDOrderIndex->commit(); return ResultWrapper::success('操作成功'); } /** * Doc: (des="取消订单解锁库存") * User: XMing * Date: 2020/7/14 * Time: 5:54 下午 * @param int $id 订单id * @param array $params 订单数据 * @return ResultWrapper */ private function unlockInventory(int $id, array $params) { //解锁库存 $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId); $unlockResult = $objMInventory->unlockInventory([$id], StatusCode::$orderType['saleOrder'], $params['createTime']); if (!$unlockResult->isSuccess()) { //暂时关闭,没发现有锁定的地方 // return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror); } self::noticeStatistics([ 'userCenterId' => $this->onlineUserId, 'enterpriseId' => $this->onlineEnterpriseId, 'customerId' => $params['customerId'], 'no' => $params['no'], 'data' => $params, 'noticeType' => 'close',//取消订单 ], 'MOrderStatistics'); //记录日志 parent::saveLog([ 'no' => $params['no'], 'actionType' => '取消订单', 'operationData' => '', 'userCenterId' => $this->onlineUserId, 'enterpriseId' => $this->onlineEnterpriseId, 'createTime' => time(), ]); return ResultWrapper::success($unlockResult->getData()); } /** * Doc: (des="订单出库状态") * User: XMing * Date: 2020/12/28 * Time: 10:38 上午 * @param array $params * @param array $where * @param array $outInventoryMap * @return ResultWrapper * @throws \Exception * @oaram $outInventoryMap */ public function updateOutStatus(array $params,array $where,array $outInventoryMap): ResultWrapper { if (empty($where)) { return ResultWrapper::fail('参数为空', ErrorCode::$paramError); } $orderIndex = $this->objDOrderIndex->get($where); if ($orderIndex === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } if (empty($orderIndex)){ return ResultWrapper::fail('未获取到指定的订单信息',ErrorCode::$paramError); } $orderId = getArrayItem($orderIndex,'id',0); $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix); $this->objDOrderIndex->beginTransaction(); foreach ($outInventoryMap as $skuId => $outNum){ $row = $this->objDOrderGoods->get(['orderId' => $orderId, 'skuId' => $skuId, 'deleteStatus' => StatusCode::$standard]); if ($row === false){ $this->objDOrderIndex->rollback(); return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } $update = [ 'outNum' => bcadd($row['outNum'],$outNum,2), 'outOfNum' => bcsub($row['outOfNum'],$outNum,2), 'updateTime' => time(), ]; if ($update['outOfNum'] < 0){ Logger::logs(E_USER_ERROR,'企业:'.$this->onlineEnterpriseId.' 订单:'.$orderId.' 出库数量异常',__CLASS__,__LINE__,$row); $this->objDOrderIndex->rollback(); return ResultWrapper::fail('出库数量异常',ErrorCode::$paramError); } $updateGoodsResult = $this->objDOrderGoods->update($update,['id' => $row['id']]); if ($updateGoodsResult === false){ Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDOrderGoods->error()); $this->objDOrderIndex->rollback(); return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$paramError); } } $outStatusResult = self::checkStockOutStatus($orderId); if (!$outStatusResult->isSuccess()){ $this->objDOrderIndex->rollback(); return ResultWrapper::fail($outStatusResult->getData(),$outStatusResult->getErrorCode()); } $outStatus = (int)$outStatusResult->getData(); $params['outStatus'] = $outStatus;//出库状态 $updateIndex = $this->objDOrderIndex->update($params,$orderId); if ($updateIndex === false){ $this->objDOrderIndex->rollback(); return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } $updateOrder = $this->objDOrder->update($params,$orderId); if ($updateOrder === false){ $this->objDOrderIndex->rollback(); return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } /* $_id = self::createEsDocumentId($orderId); $this->objDOrder->esupdateTypeFieldVaule($params, $_id);*/ $this->objDOrderIndex->commit(); return ResultWrapper::success($orderId); } /** * Doc: (des="返回订单的出库") * User: XMing * Date: 2021/3/10 * Time: 10:35 上午 * @param int $orderId * @return ResultWrapper */ public function checkStockOutStatus(int $orderId): ResultWrapper { //检测是否都已经出库 $lists = $this->objDOrderGoods->select(['orderId' => $orderId,'deleteStatus' => StatusCode::$standard]); if ($lists === false){ Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDOrderGoods->error()); return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } if (empty($lists)){ return ResultWrapper::fail('订单商品获取失败',ErrorCode::$paramError); } foreach ($lists as $item){ if ($item['outOfNum'] > 0){ //还有未出库商品 return ResultWrapper::success(6); } } return ResultWrapper::success(5); } /** * Doc: (des="修改订单的支付状态") * User: XMing * Date: 2020/7/14 * Time: 5:18 下午 * @param $orderData * @param $condition * @param bool $isNotify * @return ResultWrapper * @throws \Exception */ public function updateOrderPayData($orderData, $condition, $isNotify = false): ResultWrapper { $total_fel = 0; if ($isNotify) { $total_fel = $orderData['total_fel']; unset($orderData['total_fel']); } if (isset($orderData['pay_way'])) { $pay_way = $orderData['pay_way']; unset($orderData['pay_way']); } // 查询订单数据 $orderInfoData = $this->objDOrder->select($condition); if (empty($orderInfoData)) { return ResultWrapper::fail('查询订单数据为空', ErrorCode::$paramError); } if ($orderInfoData === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } // 回调通知判断订单是否已经修改过订单状态 if ($isNotify == true && $orderInfoData[0]['payStatus'] == StatusCode::$standard) { return ResultWrapper::fail('支付状态已经修改过了', ErrorCode::$notAllowAccess); } $this->objDOrder->beginTransaction(); // 如果之前是组合支付方式,修改支付方式的时候不能直接修改 if( in_array(StatusCode::$payType['balance'], explode(',', $orderInfoData[0]['payType'])) ){ $orderData['payType'] = $orderData['payType'].','.StatusCode::$payType['balance']; $orderData['notPayMoney'] = bcsub($orderData['notPayMoney'], $orderData['total_fel'], 2); } $dbResult = $this->objDOrder->update($orderData, $condition); if ($dbResult === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } unset($dbResult); if (!isset($condition['id'])) { //查询订单id $dbResult = $this->objDOrder->get($condition, 'id'); if ($dbResult === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($dbResult) || !isset($dbResult['id'])) { $this->objDOrder->rollBack(); return ResultWrapper::fail('订单数据为空', ErrorCode::$dberror); } $condition['id'][] = $dbResult['id']; unset($dbResult); } unset($orderData['notPayMoney']); $dbResult = self::updateOrderIndex($orderData, $condition); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } if (!is_array($condition['id'])){ $condition['id'] = [$condition['id']]; } /* foreach ($condition['id'] as $key => $value) { $_id = self::createEsDocumentId($value); $this->objDOrder->esupdateTypeFieldVaule($orderData, $_id); }*/ //线上支付生成收款单$orderData['payStatus'] $condition['id'] 支付完成后回调这两个有值 if (isset($pay_way) && isset($orderData['payStatus']) && isset($condition['id'])) { if ($orderData['payStatus'] == StatusCode::$standard) { //拿到微信默认账户 $defaultAccountResult = $this->objMAccount->getDefaultAccount($pay_way); if ($defaultAccountResult->isSuccess() == false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($defaultAccountResult->getData(), $defaultAccountResult->getErrorCode()); } $defaultAccount = $defaultAccountResult->getData(); if(empty($defaultAccount)){ return ResultWrapper::fail('支付方式对应的银行账户为空', ErrorCode::$contentNotExists); } foreach ($orderInfoData as $orderInfo) { // 组合支付,收款单金额重新计算 if( in_array(StatusCode::$payType['balance'], explode(',', $orderInfoData[0]['payType'])) ){ $orderInfo['extends'] = json_decode($orderInfo['extends'], true); if( isset($orderInfo['extends']['admixPayData']) ){ foreach ($orderInfo['extends']['admixPayData'] as $key => $value){ if($value['payType'] == StatusCode::$payType['wxPay']){ $orderInfo['payAmount'] = $value['payMoney']; } } } } //循环订单数据,拼接生成收款单 $receivedData = [ 'customerId' => $orderInfo['customerId'], 'customerName' => $orderInfo['customerName'], 'currentAccountName' => $orderInfo['shopName'], 'financeType' => '线上支付收款', 'financeTypeId' => StatusCode::$systemFinanceType['saleReceipt'], 'shopId' => $orderInfo['shopId'], 'shopName' => $orderInfo['shopName'], 'receiptTime' => time(), 'operatorId' => 0, 'originId' => $orderInfo['id'], 'originNo' => $orderInfo['no'], 'sourceId' => $orderInfo['id'], 'sourceNo' => $orderInfo['no'], 'sourceNoMoney' => $orderInfo['payAmount'], 'auditStatus' => StatusCode::$auditStatus['auditing'], 'offsetMoney' => 0, 'notOffsetMoney' => 0, 'offsetStatus' => StatusCode::$delete, 'createTime' => time(), 'updateTime' => time(), 'accountList' => [ [ "accountId" => isset($defaultAccount['id']) ? $defaultAccount['id'] : 0, "accountNumber" => isset($defaultAccount['accountNumber']) ? $defaultAccount['accountNumber'] : '请设置默认的收款账户', "money" => $orderInfo['payAmount'], "discountMoney" => 0, "finalMoney" => $orderInfo['payAmount'], "payWay" => isset($pay_way) ? $pay_way . "支付" : '在线支付', "remark" => "在线支付自动生成收款单" ] ], ]; $result = $this->objMReceived->addReceived($receivedData, true); if ($result->isSuccess() == false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($result->getData(), $result->getErrorCode()); } // 微信生成的收款单自动审核 if( in_array(StatusCode::$payType['wxPay'], explode(',', $orderInfoData[0]['payType'])) ){ $updateReceived = $this->objMReceived->updateReceivedStatus(['id'=>$result->getData(),'createTime'=>time()]); if (!$updateReceived->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($updateReceived->getData(), $updateReceived->getErrorCode()); } } unset($receivedData); unset($result); } } } if ($isNotify) { self::runProcessNextAudit($condition['id']); $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $customer = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$customer->isSuccess()) { return ResultWrapper::fail($customer->getData(), $customer->getErrorCode()); } $customer = $customer->getData(); parent::coupon([ 'userCenterId' => $this->onlineUserId, 'enterpriseId' => $this->onlineEnterpriseId, 'customerId' => isset($customer['id']) ? $customer['id'] : '', 'payAmount' => isset($total_fel) ? $total_fel : 0, ], 'MOnlinePayCoupon'); $objCustomerCache = new CustomerCache(); $objCustomerCache->delInterestCustomerAfterPay($customer['id'], $this->onlineEnterpriseId); if (isset($customer['openId']) && !empty($customer['openId'])) { /* $payment = ''; //判断支付方式 switch ($orderInfoData[0]['payType']) { case StatusCode::$payType['wxPay']: $payment = StatusCode::$payType[1]; break; case StatusCode::$payType['balance']: $payment = StatusCode::$payType[7]; break; case StatusCode::$payType['cashPay']: $payment = StatusCode::$payType[3]; break; case StatusCode::$payType['bankLoans']: $payment = StatusCode::$payType[4]; break; } $orderInfoData[0]['extends'] = json_decode($orderInfoData[0]['extends'], true); if (isset($orderInfoData[0]['extends']['admixPayData'])) { $payment = '组合支付'; }*/ // 发送小程序订阅消息 $sendMessageData = [ 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfoData[0]['no']], // 订单编号 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfoData[0]['createTime'])], // 下单时间 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间 'thing7' => ['value' => '微信支付'], // 支付方式 'name8' => ['value' => substr($orderInfoData[0]['shopName'],0,30)] // 商家名称 ]; $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customer['openId'], $sendMessageData); if (!$result->isSuccess()) { file_put_contents('/www/wwwroot/logs/api.junhailan.com/systemPushMessage.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND); } } } $this->objDOrder->commit(); $objMMerchantFlow = new MMerchantFlow($this->onlineEnterpriseId,$this->onlineUserId); if ($isNotify == true || $orderData['payStatus'] == StatusCode::$standard){ foreach ($condition['id'] as $key => $id) { $objMMerchantFlow->calculation($id); } } return ResultWrapper::success('操作成功'); } /** * 更新索引表订单状态,支付状态,支付方式 * @param $orderData * @param $params * @return ResultWrapper * @throws \Exception */ private function updateOrderIndex($orderData, $params) { $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $updateData = []; isset($orderData['payType']) && $updateData['payType'] = $orderData['payType']; isset($orderData['payStatus']) && $updateData['payStatus'] = $orderData['payStatus']; isset($orderData['orderStatus']) && $updateData['orderStatus'] = $orderData['orderStatus']; isset($orderData['outStatus']) && $updateData['outStatus'] = $orderData['outStatus']; $where['id'] = $params['id']; $dbResult = $this->objDOrderIndex->update($updateData, $where); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * 格式化返回数据 * @param $data * @return array * @throws \Exception * @return ResultWrapper */ private function format($data): ResultWrapper { // 提取所有订单id $allOrderIds = []; $allShopIds = []; $allOrderNo = []; $customerIds = []; $allCustomerTypeIds = []; if (isset($data['id'])) { $dimension = $data; unset($data); $data[] = $dimension; } foreach ($data as $key => $value) { $allOrderNo[] = $value['no']; $allOrderIds[] = $value['id']; $allShopIds[] = $value['shopId']; $allCustomerTypeIds = $value['customerType']; $customerIds[] = $value['customerId']; $this->onlineUserId = $value['userCenterId']; if ($value['auditStatus'] == StatusCode::$auditStatus['auditing']) { $data[$key]['orderMsg'] = '待审核'; } if ($value['auditStatus'] == StatusCode::$auditStatus['auditPass']) { $data[$key]['orderMsg'] = '待出库'; if ($value['orderStatus'] == StatusCode::$orderStatus['waitReceive']) { $data[$key]['orderMsg'] = '已出库'; if ($value['outStatus'] == 6 && $value['isRet'] != StatusCode::$standard){ $data[$key]['orderMsg'] = '部分出库'; } } if ($value['orderStatus'] == StatusCode::$orderStatus['finish']) { $data[$key]['orderMsg'] = '已完成'; } } switch ($value['orderStatus']){ case StatusCode::$orderStatus['close']: $data[$key]['orderMsg'] = '已关闭'; break; case StatusCode::$orderStatus['cancelIng']; $data[$key]['orderMsg'] = '待取消'; break; } if (isset($value['payType'])) { $data[$key]['payTypeMsg'] = isset(StatusCode::$payType[$value['payType']]) ? StatusCode::$payType[$value['payType']] : ''; } } //获取客户类型 $customerTypeMap = []; if (!empty($allCustomerTypeIds)) { $objDCustomerSource = new DCustomerSource(); $customerSourceLists = $objDCustomerSource->select(['id' => $allCustomerTypeIds], 'id,name'); if ($customerSourceLists != false) { foreach ($customerSourceLists as $val) { $customerTypeMap[$val['id']] = $val['name']; } } } //获取店铺信息 $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $shopData = $objMShop->getShopName($allShopIds); /********************************订单商品 start****************************/ $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId); $dbResult = $objMOrderGoods->getOrderGoodsByOrderIds(['orderId' => $allOrderIds, 'deleteStatus' => StatusCode::$standard]); $orderGoodsData = [];//订单商品信息 if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode()); } $orderGoodsData = $dbResult->getData(); unset($dbResult); //查询sku信息 $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId); //查询商品数据 $allGoodsIds = array_unique(array_column($orderGoodsData, 'goodsId')); $allGoodsBasicIds = array_unique(array_column($orderGoodsData, 'goodsBasicId')); $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId); $goodsData = $objMGoods->getGoodsNames($allGoodsIds); //获取商品的库存 $inventorySelectParams = []; $objMInventory = new MInventory($this->onlineEnterpriseId, ''); foreach ($orderGoodsData as $item){ $inventorySelectParams[$item['shopId']][] = $item['skuId']; } $inventoryMap = []; foreach ($inventorySelectParams as $shopId => $skuIds){ $inventoryResult = $objMInventory->getInventoryByShopIdAndSkuIds($shopId,$skuIds); if (!$inventoryResult->isSuccess()) { return ResultWrapper::fail($inventoryResult->getData(),$inventoryResult->getErrorCode()); } $inventoryMap[$shopId] = $inventoryResult->getData(); } //sku信息 $skuResult = $objMSku->getSpecNameBySkuId(array_column($orderGoodsData, 'skuId')); if (!$skuResult->isSuccess()) { return ResultWrapper::fail($skuResult->getData(),$skuResult->getErrorCode()); } $allSku = $skuResult->getData(); $goods = []; $allSkuIds = []; foreach ($orderGoodsData as $val){ if (!in_array($val['skuId'],$allSkuIds)){ $allSkuIds[] = $val['skuId']; } } foreach ($orderGoodsData as $key => &$value) { $value['isNew'] = isset($allSku[$value['skuId']]['isNew']) ? $allSku[$value['skuId']]['isNew'] : StatusCode::$delete; $value['barCode'] = isset($allSku[$value['skuId']]['barCode']) ? $allSku[$value['skuId']]['barCode'] : ''; $value['unitName'] = isset($allSku[$value['skuId']]['unitName']) ? $allSku[$value['skuId']]['unitName'] : ''; $value['specGroup'] = isset($allSku[$value['skuId']]['specGroup']) ? $allSku[$value['skuId']]['specGroup'] : []; $value['images'] = isset($goodsData[$value['goodsId']]['images']) ? json_decode($goodsData[$value['goodsId']]['images'], true) : ''; $value['returnPrice'] = bcdiv(bcsub(bcsub($value['totalMoney'], $value['preferential']), $value['vipDiscount']), $value['buyNum']); $value['isMater'] = isset($allSku[$value['skuId']]['isMaster']) ? $allSku[$value['skuId']]['isMaster'] : StatusCode::$delete; $value['conversion'] = isset($allSku[$value['skuId']]['conversion']) ? $allSku[$value['skuId']]['conversion'] : 0; $value['inventory'] = isset($inventoryMap[$value['shopId']][$value['skuId']]['num']) ? $inventoryMap[$value['shopId']][$value['skuId']]['num'] : 0; // 处理订单商品表扩展字段 if( !empty($value['extends']) ){ $extends = json_decode($value['extends'], true); if(!empty($extends)){ foreach($extends as $keys => $item){ $value[$keys] = $item; } } } $allOrderGoodsData[$value['orderId']][] = $value; if (!isset($goods[$value['orderId']]['goodsPreferential'])) { $goods[$value['orderId']]['goodsPreferential'] = 0; } $goods[$value['orderId']]['goodsPreferential'] = bcadd($goods[$value['orderId']]['goodsPreferential'], bcmul($value['preferential'], $value['buyNum']), 2); } unset($dbResult); /********************************收货信息 start******************************/ $objMOrderReceive = new MOrderReceive($this->onlineUserId, $this->onlineEnterpriseId); $dbResult = $objMOrderReceive->getOrderReceiveByOrderIds(['orderId' => $allOrderIds]); $orderReceiveData = [];//订单收货信息 if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode()); } $orderReceiveData = self::formatSysArea($dbResult->getData()); foreach ($orderReceiveData as $key => $value) { $allOrderReceiveData[$value['orderId']] = $value; } unset($dbResult); /*********************************订单操作记录*********************************/ $objMOrderLog = new MOrderLog($this->onlineEnterpriseId); $orderLog = $objMOrderLog->getOrderLog(['no' => $allOrderNo]); /**********************************获取基本配置*********************************/ $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId); $setupResult = $objMBasicSetup->getBasicField('allowReturnDay'); if (!$setupResult->isSuccess()) { return ResultWrapper::fail($setupResult->getData(),$setupResult->getErrorCode()); } $setupResult = $setupResult->getData(); $allowReturnDay = empty($setupResult['allowReturnDay']) ? 0 : $setupResult['allowReturnDay']; /********************************映射数据 start******************************/ $nowTime = time(); foreach ($data as $key => $value) { $data[$key]['no'] = StatusCode::$noPrefix[1].'-'.$value['no']; $data[$key]['extends'] = !empty($value['extends']) ? json_decode($value['extends'], true) : (object)[]; $data[$key]['goodsData'] = isset($allOrderGoodsData[$value['id']]) ? $allOrderGoodsData[$value['id']] : []; $data[$key]['receiveData'] = isset($allOrderReceiveData[$value['id']]) ? $allOrderReceiveData[$value['id']] : []; $data[$key]['deliveryNo'] = isset($value['deliveryNo']) ? $value['deliveryNo'] : ''; $data[$key]['payAmount'] = bcsub($value['payAmount'],$value['retMoney'],2); $data[$key]['expressMoney'] = isset($value['expressMoney']) ? $value['expressMoney'] : ''; $data[$key]['expressName'] = isset($value['expressName']) ? $value['expressName'] : ''; $data[$key]['deliveryName'] = isset(StatusCode::$deliveryType[$value['deliveryType']]) ? StatusCode::$deliveryType[$value['deliveryType']] : '';//配送方式名称 $data[$key]['orderPreferential'] = bcsub($data[$key]['totalMoney'], bcsub($data[$key]['payAmount'], $data[$key]['expressMoney'], 2), 2);//订单优惠 $data[$key]['goodsPreferential'] = isset($goods[$value['id']]['goodsPreferential']) ? $goods[$value['id']]['goodsPreferential'] : '';//商品优惠 $data[$key]['coupon'] = '0.00'; $data[$key]['salesman'] = $value['salesManName']; $data[$key]['shopName'] = isset($shopData[$value['shopId']]['name']) ? $shopData[$value['shopId']]['name'] : ''; $data[$key]['shopLogo'] = isset($shopData[$value['shopId']]['logo']) ? $shopData[$value['shopId']]['logo'] : ''; $data[$key]['orderLog'] = isset($orderLog[$value['no']]) ? $orderLog[$value['no']] : []; $data[$key]['allowReturn'] = StatusCode::$standard;//允许退货 if ($allowReturnDay == 0) { //TODO(没有设置可退货时间,默认都可以退) $data[$key]['allowReturn'] = StatusCode::$standard;//允许退货 } else { $expire = ($allowReturnDay * 86400) + $value['successFullyTime']; if ($nowTime > $expire) { $data[$key]['allowReturn'] = StatusCode::$delete;//不允许退货 } } $data[$key]['allowReturnDay'] = $allowReturnDay; if ($value['source'] == StatusCode::$source['manage']){ $data[$key]['orderPreferential'] = isset($value['totalReduceMoney']) ? $value['totalReduceMoney'] : 0; }else{ $data[$key]['orderPreferential'] = bcsub($value['totalMoney'], bcsub($value['payAmount'], $value['expressMoney'], 2), 2);//订单总优惠 } $data[$key]['paidAmount'] = $value['payStatus'] == StatusCode::$standard ? $value['payAmount'] : '0';//已付款金额 $data[$key]['customerTypeName'] = isset($customerTypeMap[$value['customerType']]) ? $customerTypeMap[$value['customerType']] : ''; $data[$key]['cashierName'] = $value['cashierName']; $data[$key]['customerMobile'] = $value['customerMobile'];//客户手机号码 $data[$key]['guideName'] = $value['guideName']; $data[$key]['changeAmount'] = $value['changeSubMoney']; $data[$key]['accountList'] = empty($value['accountList']) ? [] : json_decode($value['accountList'], true); $data[$key]['receivedName'] = isset($allOrderReceiveData[$value['id']]['realName']) ? $allOrderReceiveData[$value['id']]['realName'] : '';//收货人 $data[$key]['receivedMobile'] = isset($allOrderReceiveData[$value['id']]['mobile']) ? $allOrderReceiveData[$value['id']]['mobile'] : '';//收货电话 $data[$key]['reservoir'] = !empty($value['reservoir']) ? json_decode($value['reservoir'],true) : []; //$data[$key]['selfRuleData'] = empty($value['selfRuleData']) ? (object)[] : json_decode($value['selfRuleData'],true); } $data = array_shift($data); if ($this->isFront === false) { $data['expressData'] = (object)[]; if ($data['deliveryType'] == StatusCode::$deliveryType['goodsDelivery'] && $data['deliveryNo']) { $expressResult = self::getExpressInfoByOrderId($data['id']); if ($expressResult->isSuccess()) { $data['expressData'] = $expressResult->getData(); } } } return ResultWrapper::success($data); } /** * 地区 * @param $data * @return mixed */ public function formatSysArea($data) { if (empty($data)) { return $data; } $objMSysAreaChina = new MSysAreaChina(); foreach ($data as $key => $val) { if (isset($val['provinceCode']) && isset($val['cityCode']) && isset($val['districtCode'])) { $areaName = $objMSysAreaChina->getNameByCode([ $val['provinceCode'], $val['cityCode'], $val['districtCode'] ]); $data[$key]['area']['provinceName'] = isset($areaName[$val['provinceCode']]) ? $areaName[$val['provinceCode']] : ''; $data[$key]['area']['cityName'] = isset($areaName[$val['cityCode']]) ? $areaName[$val['cityCode']] : ''; $data[$key]['area']['districtName'] = isset($areaName[$val['districtCode']]) ? $areaName[$val['districtCode']] : ''; } } return $data; } /** * 查询订单 * 全部 {"page": 1,"pageSize": 10,"orderStatus": 0} * 待付款 {"page": 1,"pageSize": 10,"orderStatus": 2} * 待发货 {"page": 1,"pageSize": 10,"orderStatus": 3} * 待收货 {"page": 1,"pageSize": 10,"orderStatus": 4} * @param $selectParams * @return ResultWrapper * @throws \Exception */ public function getOrderSelect($selectParams) { $limit = $selectParams['limit']; unset($selectParams['limit']); $offset = $selectParams['offset']; unset($selectParams['offset']); unset($selectParams['page']); unset($selectParams['pageSize']); $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $customerId = $objMCustomer->getCustomerIdByUserCenterId($this->onlineUserId); if (empty($customerId)) { return ResultWrapper::fail('没有找到客户信息', ErrorCode::$paramError); } $selectParams['customerId'] = $customerId; $selectParams['deleteStatus'] = StatusCode::$standard; $dbResult = $this->objDOrder->select($selectParams, 'id,payType,outerTradeNo,payStatus,outStatus,verifyCode,totalMoney,payAmount,notPayMoney,shopId,no,orderStatus,createTime,deliveryType,auditStatus,isRet', 'createTime DESC,updateTime DESC', $limit, $offset); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $total = $this->objDOrder->count($selectParams); $return = [ 'data' => self::formatAndGoods($dbResult), 'total' => ($total) ? intval($total) : 0, ]; return ResultWrapper::success($return); } /** * 格式化商品数据 * * @param $data * @return mixed * @throws \Exception */ private function formatAndGoods($data) { $allOrderIds = []; $allShopIds = []; foreach ($data as $key => $value) { $allShopIds[] = $value['shopId']; $allOrderIds[] = $value['id']; } $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId); $selectParams = [ 'orderId' => $allOrderIds, 'deleteStatus' => StatusCode::$standard, ]; $dbResult = $objMOrderGoods->getOrderGoodsByOrderIds($selectParams); $orderGoodsData = [];//订单商品信息 if ($dbResult->isSuccess()) { $orderGoodsData = $dbResult->getData(); } $allGoodsIds = array_unique(array_column($orderGoodsData, 'goodsId')); unset($dbResult); $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId); $goodsData = $objMGoods->getGoodsNames($allGoodsIds); if (empty($goodsData)) { return $data; } $allOrderGoodsData = []; foreach ($orderGoodsData as $key => &$value) { $value['extends'] = !empty($value['extends']) ? json_decode($value['extends'], true) : []; $value['images'] = isset($goodsData[$value['goodsId']]['images']) ? json_decode($goodsData[$value['goodsId']]['images'], true) : ''; // 如果是抄码商品,订单商品购买数量按照件算 if( $value['isEq'] == StatusCode::$standard){ $value['buyNum'] = isset($value['extends']['u_1_buy']) ? $value['extends']['u_1_buy'] : $value['buyNum']; } $allOrderGoodsData[$value['orderId']][] = $value; } $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $shopData = $objMShop->getShopName($allShopIds); foreach ($data as $key => $val) { $data[$key]['deliveryTypeMsg'] = isset(StatusCode::$deliveryType[$val['deliveryType']]) ? StatusCode::$deliveryType[$val['deliveryType']] : ''; $data[$key]['goodsNum'] = isset($allOrderGoodsData[$val['id']]) ? array_sum(array_column($allOrderGoodsData[$val['id']], 'buyNum')) : ''; $data[$key]['shopName'] = isset($shopData[$val['shopId']]['name']) ? $shopData[$val['shopId']]['name'] : ''; $data[$key]['shopLogo'] = isset($shopData[$val['shopId']]['logo']) ? $shopData[$val['shopId']]['logo'] : ''; $data[$key]['goodsData'] = isset($allOrderGoodsData[$val['id']]) ? array_values($allOrderGoodsData[$val['id']]) : ''; } return $data; } /** * Doc: (des="订单检索条件") * User: XMing * Date: 2020/7/11 * Time: 9:48 上午 * @param $selectParams * @param bool $is_export * @return ResultWrapper * @throws \Exception */ public function search($selectParams, $is_export = false) { $defaultDSL = [ 'sort' => [ 'createTime' => [ 'order' => 'desc' ], ], ]; if ($is_export === false) { $defaultDSL['from'] = $selectParams['offset']; $defaultDSL['size'] = $selectParams['limit']; } $dsl = []; $dsl['query']['bool']['must'][] = [ 'term' => ['enterpriseId' => $this->onlineEnterpriseId], ]; //订单编号,收货人,商品名称 if (!empty($selectParams['keyword'])) { $dsl['query']['bool']['must'][] = [ 'multi_match' => [ 'fields' => ['no', 'verifyCode', 'mobile', 'goodsName', 'salesManName', 'customerName', 'remark'], 'query' => $selectParams['keyword'], //'fuzziness' => 'AUTO', "type" => "best_fields", "tie_breaker" => 0.3, "minimum_should_match" => "100%" ], ]; } //销售单/订单 if (isset($selectParams['orderType']) && !empty($selectParams['orderType'])) { $dsl['query']['bool']['filter'][] = ['term' => ['orderType' => $selectParams['orderType']]]; } //订单状态 if (isset($selectParams['orderStatus']) && !empty($selectParams['orderStatus'])) { $dsl['query']['bool']['filter'][] = ['term' => ['orderStatus' => $selectParams['orderStatus']]]; } //出库状态 if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) { $dsl['query']['bool']['filter'][] = ['term' => ['outStatus' => $selectParams['outStatus']]]; } //退货状态 if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) { $dsl['query']['bool']['filter'][] = ['term' => ['returnStatus' => $selectParams['returnStatus']]]; } //配送方式 if (isset($selectParams['deliveryType']) && !empty($selectParams['deliveryType'])) { $dsl['query']['bool']['filter'][] = ['term' => ['deliveryType' => $selectParams['deliveryType']]]; } //支付状态 if (isset($selectParams['payType']) && !empty($selectParams['payType'])) { $dsl['query']['bool']['filter'][] = ['term' => ['payType' => $selectParams['payType']]]; } //店铺id parent::getAccessShopIds(); if (parent::$shopIds) { $dsl['query']['bool']['filter'][] = [ 'terms' => ['shopId' => parent::$shopIds] ]; } //省code if (isset($selectParams['provinceCode']) && !empty($selectParams['provinceCode'])) { $dsl['query']['bool']['filter'][] = ['term' => ['provinceCode' => $selectParams['provinceCode']]]; } //市code if (isset($selectParams['cityCode']) && !empty($selectParams['cityCode'])) { $dsl['query']['bool']['filter'][] = ['term' => ['cityCode' => $selectParams['cityCode']]]; } //区code if (isset($selectParams['districtCode']) && !empty($selectParams['districtCode'])) { $dsl['query']['bool']['filter'][] = ['term' => ['districtCode' => $selectParams['districtCode']]]; } if (!empty($selectParams['start']) && !empty($selectParams['end'])) { $dsl['query']['bool']['must'][] = [ 'range' => [ 'createTime' => [ 'gte' => $selectParams['start'], 'lte' => $selectParams['end'], ] ] ]; } else { if (isset($selectParams['start']) && !empty($selectParams['start'])) { $dsl['query']['bool']['must'][] = [ 'range' => [ 'createTime' => [ 'gte' => $selectParams['start'], ] ] ]; } if (isset($selectParams['end']) && !empty($selectParams['end'])) { $dsl['query']['bool']['must'][] = [ 'range' => [ 'createTime' => [ 'lte' => $selectParams['end'], ] ] ]; } } //店铺id if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) { $dsl['query']['bool']['filter'][] = ['term' => ['shopId' => $selectParams['shopId']]]; } //客户id if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) { $dsl['query']['bool']['filter'][] = ['term' => ['customerId' => $selectParams['customerId']]]; } //客户类型 if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])) { $dsl['query']['bool']['filter'][] = ['term' => ['customerType' => $selectParams['customerType']]]; } $flag = true; //业务员id if (isset($selectParams['salesManId']) && !empty($selectParams['salesManId'])) { $dsl['query']['bool']['filter'][] = ['term' => ['salesManId' => $selectParams['salesManId']]]; } //销售员id parent::getAccessSalesManIds(); if (!empty(parent::$salesManIds) && empty($selectParams['salesManId'])) { $dsl['query']['bool']['filter'][] = [ 'terms' => ['salesManId' => parent::$salesManIds] ]; } if (!empty(parent::$salesManIds) && !empty($selectParams['salesManId'])) { if (!in_array($selectParams['salesManId'], parent::$salesManIds)) { $flag = false; } } //订单来源 if (isset($selectParams['source']) && !empty($selectParams['source'])) { $dsl['query']['bool']['filter'][] = ['term' => ['source' => $selectParams['source']]]; } //按照标示进行检索,等级最高 if (isset($selectParams['state']) && !empty($selectParams['state'])) { $dsl = self::setOrderStatusDslAttr($dsl, $selectParams['state']); } $dsl = array_merge($defaultDSL, $dsl); //导出 if ($is_export === true) self::exportSearch($dsl); //V($dsl); $result = $flag ? $this->objDOrder->getSearchQueryDsl($dsl) : []; if (isset($result['status']) && $result['status'] == 400) { //return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult); return ResultWrapper::success([ 'data' => [], 'total' => 0 ]); } if (!isset($result['hits']) || $result['hits']['total'] == 0) { return ResultWrapper::success([ 'data' => [], 'total' => 0 ]); } $total = $result['hits']['total']; $dbResult = $result['hits']['hits']; $list = []; foreach ($dbResult as $key => &$value) { $data = []; $data = $value['_source']; //$data['id'] = $value['_id']; $data['receiveData'] = [ 'realName' => $data['realName'], 'mobile' => $data['mobile'] ]; unset($data['realName']); unset($data['mobile']); $list[] = $data; } $buildData = self::shiftEsReceiveData($list); $formatResult = self::formatManageOrderList($buildData['allOrderData'], $buildData['allOrderReceiveData']); if (!$formatResult->isSuccess()) { return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode()); } $return = [ 'data' => $formatResult->getData(), 'total' => ($total) ? intval($total) : 0, ]; return ResultWrapper::success($return); } /** * Doc: (des="将es中查询出来的数据,统一转化为标准格式进行格式化") * User: XMing * Date: 2020/7/11 * Time: 6:13 下午 * @param $data * @return array */ private static function shiftEsReceiveData($data) { $orderData = []; $orderReceiveData = []; foreach ($data as $item) { $orderData[] = $item; $orderReceiveData[] = [ 'orderId' => $item['id'], 'customerId' => $item['customerId'], 'address' => $item['address'], 'realName' => $item['receiveData']['realName'], 'mobile' => $item['receiveData']['mobile'], 'provinceCode' => $item['provinceCode'], 'cityCode' => $item['cityCode'], 'districtCode' => $item['districtCode'] ]; } return [ 'allOrderData' => $orderData, 'allOrderReceiveData' => $orderReceiveData ]; } /** * 格式化订单状态 * @param $data * @return mixed */ private static function formatOrderStatus($data) { if (empty($data)) return $data; foreach ($data as $key => $value) { if ($value['auditStatus'] == StatusCode::$auditStatus['auditing']) { $data[$key]['orderMsg'] = '待审核'; } if ($value['auditStatus'] == StatusCode::$auditStatus['auditPass']) { $data[$key]['orderMsg'] = '待出库'; if ($value['orderStatus'] == StatusCode::$orderStatus['waitReceive']) { $data[$key]['orderMsg'] = '已出库'; if ($value['outStatus'] == 6 && $value['isRet'] != StatusCode::$standard){ $data[$key]['orderMsg'] = '部分出库'; } } if ($value['orderStatus'] == StatusCode::$orderStatus['finish']) { $data[$key]['orderMsg'] = '已完成'; } } switch ($value['orderStatus']){ case StatusCode::$orderStatus['close']: $data[$key]['orderMsg'] = '已关闭'; break; case StatusCode::$orderStatus['cancelIng']; $data[$key]['orderMsg'] = '待取消'; break; // case StatusCode::$orderStatus['waitReceive']; // $data[$key]['orderMsg'] = '待收货'; // break; } if (isset($value['payStatus'])) { $data[$key]['payMsg'] = $value['payStatus'] == StatusCode::$standard ? '已支付' : '未支付'; } if (isset($value['deliveryType'])) { $data[$key]['deliveryMsg'] = isset(StatusCode::$deliveryType[$value['deliveryType']]) ? StatusCode::$deliveryType[$value['deliveryType']] : ''; } if (isset($value['payType'])) { $payTypeMsg = ''; if( isset(StatusCode::$payType[$value['payType']]) ){ $payTypeMsg = StatusCode::$payType[$value['payType']]; }else{// 组合支付渲染金额 if($value['extends']){ $admixPayData = json_decode($value['extends'],true); $payTypeMsg = '组合支付('; if(!empty($admixPayData)){ foreach ($admixPayData['admixPayData'] as $admixKey => $admixValue){ $payTypeMsg .= $admixValue['title'].'支付'.$admixValue['payMoney'].','; } } $payTypeMsg .= ")"; } } $data[$key]['payTypeMsg'] = $payTypeMsg; //$data[$key]['payTypeMsg'] = isset(StatusCode::$payType[$value['payType']]) ? StatusCode::$payType[$value['payType']] : '组合支付'; } if (isset($value['source'])) { $data[$key]['sourceMsg'] = isset(StatusCode::$source[$value['source']]) ? StatusCode::$source[$value['source']] : ''; } if (isset($value['auditStatus'])) { $data[$key]['auditMsg'] = isset(StatusCode::$auditStatus[$value['auditStatus']]) ? StatusCode::$auditStatus[$value['auditStatus']] : ''; } } return $data; } /** * Doc: (des="订单标示的dsl拼接") * User: XMing * Date: 2020/7/11 * Time: 9:15 上午 * @param array $dsl * * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1 * @waitOutStock:待出库 orderStatus != 6 auditPass = 2 * @hasOutStock:已出库 orderStatus = 4 auditPass = 2 * @finish:已完成 orderStatus = 5 auditPass 2 * @close:已关闭 orderStatus = 6 * @param string $states * @return array|mixed */ public static function setOrderStatusDslAttr(array $dsl, $states) { if (is_array($states)) { $allAuditStatus = []; $allOrderStatus = []; foreach ($states as $state) { $auditStatus = self::auditStatusAttrDsl($state); $orderStatus = self::orderStatusAttrDsl($state); $allAuditStatus = array_merge($auditStatus, $allAuditStatus); $allOrderStatus = array_merge($orderStatus, $allOrderStatus); } } else { $allAuditStatus = self::auditStatusAttrDsl($states); $allOrderStatus = self::orderStatusAttrDsl($states); } if (!empty($allAuditStatus)) { $dsl['query']['bool']['filter'][] = [ 'terms' => [ 'auditStatus' => $allAuditStatus ] ]; } if (!empty($allOrderStatus)) { $dsl['query']['bool']['filter'][] = [ 'terms' => [ 'orderStatus' => $allOrderStatus ] ]; } return $dsl; } /** * Doc: (des="state对应审核状态映射") * User: XMing * Date: 2020/7/13 * Time: 10:36 上午 * @param string $state * @return array|mixed */ public static function auditStatusAttrDsl(string $state) { $map = [ 'waitAudit' => [StatusCode::$auditStatus['auditing']], 'waitOutStock' => [StatusCode::$auditStatus['auditPass']], 'hasOutStock' => [StatusCode::$auditStatus['auditPass']], 'finish' => [StatusCode::$auditStatus['auditPass']], 'close' => [], 'all' => [] ]; return isset($map[$state]) ? $map[$state] : []; } /** * Doc: (des="state对应订单状态映射") * User: XMing * Date: 2020/7/13 * Time: 10:43 上午 * @param string $state * @return array|mixed */ public static function orderStatusAttrDsl(string $state) { $map = [ 'waitAudit' => [StatusCode::$orderStatus['waitPay'], StatusCode::$orderStatus['waitDelivery']], 'waitOutStock' => [StatusCode::$orderStatus['waitPay'], StatusCode::$orderStatus['waitDelivery']], 'hasOutStock' => [StatusCode::$orderStatus['waitReceive']], 'finish' => [StatusCode::$orderStatus['finish']], 'close' => [StatusCode::$orderStatus['close']], 'all' => [] ]; return isset($map[$state]) ? $map[$state] : []; } /** * 再次支付 * * @param $params * @param $ip * @return ResultWrapper * @throws \Exception */ public function payOrder($params, $ip) { // file_put_contents('/www/wwwroot/logs/api.junhailan.com/pay_params.log', date('Y-m-d H:i:s') . '再次支付订单数据:' . var_export($params, true) . PHP_EOL, FILE_APPEND); //order表切表 $fix = 1; $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $this->objDOrderIndex->setTable('qianniao_order_index_'.$this->onlineEnterpriseId); $status = $this->objDOrder->beginTransaction(); //再次支付更新extend值 $extend = []; // 处理混合支付数据 if( !empty($params['admixPayData']) ){ $extend['admixPayData'] = $params['admixPayData']; } // 处理银行打款数据 if( !empty($params['bankData']) ){ $extend['bankData'] = $params['bankData']; } $extend = json_encode($extend); //再次付款更新extend(付款信息) $updateExtend = $this->objDOrder->update(['extends'=>$extend],['no' => $params['no']]); if ($updateExtend === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if($status){ $this->objDOrder->commit(); } $orderData = $this->objDOrder->get(['no' => $params['no']]); if ($orderData === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($orderData)) { return ResultWrapper::fail('没有找到订单', ErrorCode::$paramError); } $params['payType'] = explode(',', $params['payType']); $this->objDOrder->beginTransaction(); //再次支付时订单支付方式改为了货到付款 //if ($params['payType'] == StatusCode::$payType['cashPay']) { if ( in_array(StatusCode::$payType['cashPay'], $params['payType']) || in_array(StatusCode::$payType['bankLoans'],$params['payType'])) { //修改订单的支付方式 if(in_array(StatusCode::$payType['cashPay'], $params['payType'])){//货到付款 订单状态为待发货 $update = [ 'payType' => StatusCode::$payType['cashPay'], 'orderStatus' => StatusCode::$orderStatus['waitDelivery'] ]; } else{//银行打款 订单状态为代发货 $update = [ 'payType' => StatusCode::$payType['bankLoans'], 'orderStatus' => StatusCode::$orderStatus['waitPay'], 'payStatus' => StatusCode::$delete ]; } $dbResult = $this->objDOrder->update($update, ['no' => $params['no']]); if ($dbResult === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } unset($dbResult); //修改索引表支付方式 $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $dbResult = $this->objDOrderIndex->update($update, ['id' => $orderData['id']]); if ($dbResult === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } /* //修改ES,支付方式 $_id = self::createEsDocumentId($orderData['id']); $this->objDOrder->esupdateTypeFieldVaule(['payType' => StatusCode::$payType['cashPay']], $_id);*/ $this->objDOrder->commit(); //订单是否自动审核 $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId); //获取基本配置 $setupResult = $objMBasicSetup->getBasicField('autoAuditOrder'); $autoAuditOrder = []; if ($setupResult->isSuccess()) { $autoAuditOrder = $setupResult->getData();//自动审核配置数据 $autoAuditOrder = isset($autoAuditOrder['autoAuditOrder']) ? $autoAuditOrder['autoAuditOrder'] : []; } //货到付款是否开启了自动审核 $autoAudit = isset($autoAuditOrder['cashPay']) ? $autoAuditOrder['cashPay'] : StatusCode::$delete; if ($autoAudit == StatusCode::$standard) { //开启了自动审核,审核订单 $auditResult = self::updateAuditStatus([ 'id' => $orderData['id'], 'audit' => '自动审核', 'auditId' => $this->onlineUserId, 'auditStatus' => StatusCode::$auditStatus['auditPass'] ]); } return ResultWrapper::success($dbResult); } //获取客户信息 $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $customerData = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$customerData->isSuccess()) { return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode()); } $customerData = $customerData->getData(); $payType = $params['payType']; rsort($payType); $payment = []; $payParams = ''; $payStatus = StatusCode::$partion; $orderStatus = StatusCode::$orderStatus['waitPay']; if( in_array(StatusCode::$payType['bankLoans'],$payType) ){ $payStatus = StatusCode::$delete; $orderStatus = StatusCode::$orderStatus['waitPay']; } foreach($payType as $k => $v){ // 除了余额支付其他方式都要获取支付配置 if($v != StatusCode::$payType['balance']){ $objMPaymentSetting = new MPaymentSetting($this->onlineUserId, $this->onlineEnterpriseId); $result = $objMPaymentSetting->getPayData($v); if (!$result->isSuccess() || empty($result->getData())) { return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor); } $payment = $result->getData(); } switch (true){ case in_array(StatusCode::$payType['balance'], $payType): //余额支付 //$objMCustomer = new MCustomer($this->onlineEnterpriseId,$this->onlineUserId); //减少余额() $status = $this->objDOrderIndex->beginTransaction(); //新增会员流水记录 $memberBalanceDetailData = [ 'customerId' => $orderData['customerId'], 'type' => StatusCode::$delete, 'userCenterId' => $this->onlineUserId, 'purpose' => '创建订单消费', 'orderIds' =>implode(',',[$orderData['id']]), 'remark' => '订单id'.implode(',',[$orderData['id']]), 'financeType' => '会员余额消费' ]; // 组合支付方式 if( !empty($params['admixPayData']) ) { foreach ($params['admixPayData'] as $key => $value) { if ($value['payType'] == StatusCode::$payType['balance']) { // 本次混合支付余额支付金额 $memberBalanceDetailData['money'] = $value['payMoney']; // 总金额 - 余额支付金额 = 剩余需要搭配支付金额 $orderData['payAmount'] = bcsub($orderData['payAmount'], $value['payMoney'], 2); } } }else{ $payStatus = StatusCode::$standard; $orderStatus = StatusCode::$orderStatus['waitDelivery']; $memberBalanceDetailData['money'] = $orderData['payAmount']; } $objMMemberBalanceDetail = new MMemberBalanceDetail($this->onlineEnterpriseId,$this->onlineUserId); $memberBalanceDbResult = $objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData); if (!$memberBalanceDbResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($memberBalanceDbResult->getData(), $memberBalanceDbResult->getErrorCode()); } //扣除失败->订单未支付 if ($memberBalanceDbResult->isSuccess()){ $time = time(); //扣除成功->订单支付成功\ foreach ([$orderData['id']] as $orderId){ $updateIndexResult = $this->objDOrderIndex->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'updateTime' => $time],$orderId); if ($updateIndexResult === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } $updateIndex = $this->objDOrder->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'payTime'=> $time,'updateTime' => $time,'payAmount'=>$memberBalanceDetailData['money']],$orderId); if ($updateIndex === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } } } $status && $this->objDOrderIndex->commit(); $payParams = ResultWrapper::success([]); break; case in_array(StatusCode::$payType['aliPay'], $payType): //ali /*********读取支付宝支付参数(原配置)*********/ /**$aliPayConfigData = Factory::config()->get('alipay'); * if (empty($aliPayConfigData)) { * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor); * }*/ $payOrderData = [ 'subject' => '千鸟云商', 'out_trade_no' => $orderData['no'], 'total_amount' => $orderData['payAmount'], 'passback_params' => $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', [$orderData['id']]), ]; $aliPayConfigData = [ 'appid' => $payment['appid'], 'rsaPrivateKey' => $payment['rsaPrivateKey'], 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'], ]; $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']); $payParams = $objAliPay->appPay($payOrderData); break; case in_array(StatusCode::$payType['wxPay'], $payType): //wx /********************生成小程序唤起支付用到的参数(原配置)*****/ /**$weixinConfigData = Factory::config()->get('weixin'); * if (empty($weixinConfigData)) { * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor); * }*/ // 获取当前登录企业的小程序配置 $objSystemCache = new SystemCache(); $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId); if (empty($miniprogramSetting)) { return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor); } $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid // 获取配置文件微信公众号 /**$weixinConfigData = Factory::config()->get('weixin'); * if (empty($weixinConfigData)) { * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor); * }*/ switch ($params['source']) { case StatusCode::$source['ByteProgram']; //$appid = $weixinConfigData['offiaccount']['appid']; $appid = $miniprogramSetting['appid']; $paySource = 'byteDanceH5'; break; case StatusCode::$source['miniProgram']; $appid = $miniprogramSetting['appid']; $paySource = 'miniProgram'; break; default : $appid = $payment['mobileAppid']; $paySource = 'APP'; break; } $weixinConfigData = [ 'mch_id' => $payment['mchId'], 'apiPartnerKey' => $payment['apiPartnerKey'], 'appid' => $appid ]; $attach = $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', [$orderData['id']]); //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']); $payParams = $objPay->unifiedorder($orderData['no'],$orderData['payAmount'], $ip, $paySource, '千鸟云商', $customerData['openId'], $attach); break; case in_array(StatusCode::$payType['byte'],$payType): //字节跳动 $mweb_url = ''; //读取缓存配置 //$objSystemCache->getByteDanceSetting($this->onlineEnterpriseId); // 获取配置文件字节小程序 $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay'); if (empty($byteDanceConfigData)) { return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor); } $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']); unset($payParams); $payParams = $objbytePay->pay($orderData['no'],$orderData['payAmount'], '千鸟云商', $ip, $mweb_url); break; case in_array(StatusCode::$payType['bankLoans'], $payType): $payParams = ResultWrapper::success([$orderData['id']]); break; default: //TODO return ResultWrapper::fail('暂未开放的支付方式',ErrorCode::$paramError); break; } unset($payType[$k]); if (!$payParams->isSuccess()) { return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode()); } } return ResultWrapper::success($payParams->getData()); } /** * 增加打印次数 * @param $id * @return ResultWrapper */ public function printIncr($id) { $dbResult = $this->objDOrder->set_inc('printingNum', ['id' => $id]); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * todo(保存编辑(废弃)) * * @param $params * @return ResultWrapper * @throws \Exception */ public function saveEdit($params) { $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId); $objMShippingAddress = new MShippingAddress($this->onlineEnterpriseId); $objMOrderReceive = new MOrderReceive($this->onlineUserId, $this->onlineEnterpriseId); $order = $this->objDOrder->get(['id' => $params['orderId']]); if ($order === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($order)) { return ResultWrapper::fail('订单不存在', ErrorCode::$paramError); } if (!isset($order['auditStatus']) || $order['auditStatus'] == StatusCode::$auditStatus['auditPass'] || $order['payStatus'] == StatusCode::$standard ) { return ResultWrapper::fail('订单不能编辑', ErrorCode::$paramError); } //根据地址id获取地址信息 $dbResult = $objMShippingAddress->getShippingAddressInfo($params['receiveAddressId']); if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } $addressData = $dbResult->getData(); if (empty($addressData)) { return ResultWrapper::fail('收货地址信息不存在', ErrorCode::$dberror); } //锁定库存 查询商铺对应的仓库 $objMWarehouse = new MWarehouse($this->onlineEnterpriseId); $warehouseData = $objMWarehouse->getWarehouseInfo(['shopId' => $params['goodsData']['goodsData'][0]['shopId']]); if (!$warehouseData->isSuccess()) { return ResultWrapper::fail($params['goodsData']['goodsData'][0]['shopId'] . $warehouseData->getData(), $warehouseData->getErrorCode()); } $warehouse = $warehouseData->getData(); $commonData = $params['goodsData']; $this->objDOrder->beginTransaction(); //先解锁库存 // $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId); // $unlockResult = $objMInventory->unlockInventory([$order['id']], StatusCode::$orderType['saleOrder'], $order['createTime']); // if (!$unlockResult->isSuccess()) { // $this->objDOrder->rollBack(); // return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror); // } $dbResult = $this->objDOrderIndex->update(['deliveryType' => $params['deliveryType']], ['id' => $params['orderId']]); if ($dbResult === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } //修改Order表中的数据 $dbResult = $this->objDOrder->update([ 'totalMoney' => $commonData['totalMoney'], 'payAmount' => $commonData['payMoney'], 'deliveryType' => $params['deliveryType'], 'buyTotal' => array_sum(array_column($commonData['goodsData'], 'buyNum')) ], ['id' => $params['orderId']]); if ($dbResult === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } unset($dbResult); //修改OrderGoods表中的数据 if (!empty($params['delOrderGoodsIds'])) { $dbResult = $objMOrderGoods->updateDetails(['deleteStatus' => StatusCode::$delete], ['id' => $params['delOrderGoodsIds']]); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } unset($dbResult); } //查询当前订单商品,进行比对 $dbResult = $objMOrderGoods->getDetails([ 'orderId' => $params['orderId'], 'deleteStatus' => StatusCode::$standard, ]); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } $oldGoodsData = $dbResult->getData(); $hash = []; foreach ($oldGoodsData as $goods) { $hash[] = md5($goods['goodsId'] . $goods['skuId']); } $lockInventoryData = []; foreach ($commonData['goodsData'] as $value) { foreach ($value['shopGoodsData'] as $key => $val) { $rowHash = md5($val['goodsId'] . $val['skuId']); if (in_array($rowHash, $hash)) { //update $dbResult = $objMOrderGoods->updateDetails( [ 'buyNum' => $val['buyNum'], 'price' => $val['price'], 'originPrice' => $val['originPrice'], 'totalMoney' => $val['totalMoney'], ], ['orderId' => $params['orderId'], 'goodsId' => $val['goodsId'], 'skuId' => $val['skuId']] ); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } } else { //insert $dbResult = $objMOrderGoods->addOrderGoods([ 'no' => $order['no'], 'orderId' => $params['orderId'], 'goodsId' => $val['goodsId'], 'goodsName' => $val['goodsName'], 'shopId' => $val['shopId'],//商铺id 'shopName' => $val['shopName'],//商铺名称 'originPrice' => $val['originPrice'], 'price' => $val['price'], 'buyNum' => $val['buyNum'], 'totalMoney' => $val['totalMoney'], 'skuId' => $val['skuId'], 'goodsBasicId' => $val['goodsBasicId'], 'goodsCode' => $val['goodsCode'], 'deliverNum' => $val['buyNum'],//发货数量=购买数量 'unitName' => $val['unitName'],//单位名称 'conversion' => $val['conversion'],//换算比率 'preferential' => $val['preferential'],//优惠券优惠金额 'vipDiscount' => $val['vipDiscount'],//会员卡优惠金额 ]); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } } //锁定库存数据 $lockInventoryData[] = [ 'warehouseId' => $warehouse['id'], 'materielId' => $val['goodsBasicId'], 'lockingNum' => empty((float)($val['conversion'])) ? $val['buyNum'] : bcdiv($val['buyNum'], $val['conversion']), 'originId' => $params['orderId'], 'originNo' => $order['no'], 'source' => StatusCode::$orderType['saleOrder'], 'sourceNo' => $order['no'], 'operatorId' => $order['customerId'], 'operatorName' => $order['customerName'], 'skuId' => $val['skuId'], ]; } } //锁定库存 // $lockInventoryResult = $objMInventory->updateLockInventory($lockInventoryData); // if (!$lockInventoryResult->isSuccess()) { // $this->objDOrder->rollBack(); // return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode()); // } //修改收货人 $dbResult = $objMOrderReceive->updateReceive( [ 'customerCode' => $addressData['customerCode'],//客户编码 'realName' => $addressData['name'],//收货人姓名 'mobile' => $addressData['mobile'],//收货人电话 'address' => $addressData['address'],//收货人详细地址 'provinceCode' => $addressData['provinceCode'], 'cityCode' => $addressData['cityCode'], 'districtCode' => $addressData['districtCode'], ], [ 'orderId' => $params['orderId'] ] ); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } $this->objDOrder->commit(); /* $_id = self::createEsDocumentId($params['orderId']); $this->objDOrder->esupdateTypeFieldVaule([ 'totalMoney' => $commonData['totalMoney'], 'payAmount' => $commonData['payMoney'], 'buyTotal' => array_sum(array_column($commonData['goodsData'], 'buyNum')),//购买总数 'deliveryType' => $params['deliveryType'], 'realName' => $addressData['name'],//收货人姓名 'mobile' => $addressData['mobile'],//收货人电话 'address' => $addressData['address'],//收货详细地址 'provinceCode' => $addressData['provinceCode'],//收货人省份编码 'cityCode' => $addressData['cityCode'],//收货人城市编码 'districtCode' => $addressData['districtCode'],//收货人区编码 ], $_id); //修改es中的数据*/ return ResultWrapper::success('操作成功'); } /** * 订单编辑(现在只能编辑订单支付金额) * @param $params * @return ResultWrapper */ public function orderEdit($params) { $order = $this->objDOrder->get(['id' => $params['orderId']]); if ($order === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($order)) { return ResultWrapper::fail('订单不存在', ErrorCode::$paramError); } if (!isset($order['auditStatus']) || $order['auditStatus'] == StatusCode::$auditStatus['auditPass'] || $order['payStatus'] == StatusCode::$standard ) { return ResultWrapper::fail('订单不能编辑', ErrorCode::$paramError); } //修改payAmount,将payAmount复制到字段originPayAmount $update = [ 'payAmount' => sprintf("%.2f", $params['editAmount']), 'originPayAmount' => $order['payAmount'],//原付款金额 ]; $dbResult = $this->objDOrder->update($update, ['id' => $params['orderId']]); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } /* //修改es中的数据 $_id = self::createEsDocumentId($params['orderId']); $this->objDOrder->esupdateTypeFieldVaule([ 'payAmount' => $update['payAmount'], 'originPayAmount' => $update['originPayAmount'],//原付款金额 ], $_id);*/ return ResultWrapper::success('操作成功'); } /** * Doc: (des="") * User: XMing * Date: 2020/9/2 * Time: 9:16 上午 * @param array $params * @return ResultWrapper * * @throws \Exception */ public function cashierOrder(array $params) { $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId); $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId); $objMCart = new MCart($this->onlineUserId, $this->onlineEnterpriseId); $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId); $objDStaff = new DStaff(); $objStockCache = new Stock($this->onlineEnterpriseId); $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId); $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $goodsCommonData = $params['goodsData']; //锁定库存 查询商铺对应的仓库 $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $modelResult = $objMShop->getShopDataByShopIds(array_column($goodsCommonData['goodsData'], 'shopId')); if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $shopData = $modelResult->getData(); if (empty($shopData)) { return ResultWrapper::fail('获取店铺数据失败', ErrorCode::$paramError); } //获取收银员信息 $allUids = [$this->loginUserCenterId]; if (isset($params['guideUids']) && !empty($params['guideUids'])) { $ids = explode(',', $params['guideUids']); $allUids = array_merge($allUids, $ids); } $userMap = []; if (!empty($allUids)) { $staffList = $objDStaff->select(['userCenterId' => $allUids], 'userCenterId,staffName'); if ($staffList === false) { return ResultWrapper::fail($objDStaff->error(), ErrorCode::$dberror); } foreach ($staffList as $value) { $userMap[$value['userCenterId']] = $value['staffName']; } } $params['cashierName'] = isset($userMap[$this->loginUserCenterId]) ? $userMap[$this->loginUserCenterId] : '超级管理员'; $nameStr = ''; if (!empty($ids)) { foreach ($ids as $uid) { if (!empty($nameStr)) { $nameStr .= ','; } $nameStr .= isset($userMap[$uid]) ? $userMap[$uid] : ''; } } $params['guideName'] = $nameStr; $params['customerMobile'] = ''; //获取客户信息 $customerOwe = 0; if ($this->onlineUserId == StatusCode::$noneUserCenter) { $customerData = [ 'id' => StatusCode::$noneCustomer, 'name' => '匿名客户' ]; } else { $customerDataResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$customerDataResult->isSuccess()) { return ResultWrapper::fail($customerDataResult->getData(), $customerDataResult->getErrorCode()); } $customerData = $customerDataResult->getData(); //获取客户当前欠款 if (isset($customerData['id'])) { $customerOwe = $objMCustomerBalance->getCustomerBalance($customerData['id']); } //获取客户手机号 $objDUserCenter = new DUserCenter(); $userInfo = $objDUserCenter->get(['id' => $this->onlineUserId], 'mobile'); if ($userInfo === false) { return ResultWrapper::fail($objDUserCenter->error(), ErrorCode::$dberror); } $params['customerMobile'] = isset($userInfo['mobile']) ? $userInfo['mobile'] : ''; } // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号 $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['cashierOrder'], $this->onlineUserId); $lockInventoryData = [];//锁定库存物料 $goodsSaleData = [];//销售数据 $allSn = [];//所有单号 $allOrderIds = [];//所有订单 $mapDetails = [];//订单商品 $createTime = time(); $allCartIds = []; $shopName = ''; $shopId = 0;//目前只有一个 $this->objDOrder->beginTransaction(); foreach ($goodsCommonData['goodsData'] as $key => $val) { $sn = createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId); //将数据写入索引表 $shopId = $val['shopId']; $orderIndexData = [ 'shopId' => $val['shopId'], 'userCenterId' => $params['userCenterId'], 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0, 'createTime' => time(), 'updateTime' => time(), 'deleteStatus' => StatusCode::$standard, 'auditStatus' => StatusCode::$auditStatus['auditing'], 'payStatus' => StatusCode::$delete, 'orderStatus' => StatusCode::$orderStatus['waitPay'], 'outStatus' => StatusCode::$delete, 'returnStatus' => StatusCode::$orderReturn['notReturn'], 'deliveryType' => $params['deliveryType'], 'payType' => $params['payType'], 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0, 'no' => $sn, 'orderType' => StatusCode::$orderType['cashierOrder'], 'selfRuleId' => 0, 'cashierUid' => $this->loginUserCenterId, 'guideUids' => $params['guideUids'] ]; //1. 先写索引表 $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $orderId = $this->objDOrderIndex->insert($orderIndexData); if ($orderId === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } //3。上门自提订单,生成核销码 $verifyCode = self::createVerifyCode($orderId); //兼容以前代码 $updateRes = $this->objDOrderIndex->update(['verifyCode' => $verifyCode], ['id' => $orderId]); if ($updateRes === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } //订单数据 $shopName = $val['shopName'];//现在就一个店铺 $masterOrder = [ 'id' => $orderId,//订单id 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0, 'userCenterId' => $params['userCenterId'], 'shopId' => $val['shopId'], 'shopName' => $val['shopName'], 'no' => $sn, 'outerTradeNo' => $tmpOuterTradeNo, 'totalMoney' => $goodsCommonData['totalMoney'], 'payAmount' => $goodsCommonData['payMoney'], 'customerName' => isset($customerData['name']) ? $customerData['name'] : '', 'remark' => $params['remark'], 'deliveryType' => $params['deliveryType'],//配送方式 'payType' => $params['payType'],//支付方式 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0, 'salesManName' => isset($customerData['salesManName']) ? $customerData['salesManName'] : '', 'customerType' => isset($customerData['type']) ? $customerData['type'] : 0, 'buyTotal' => array_sum(array_column($val['shopGoodsData'], 'buyNum')), 'source' => $params['source'],//来源 'orderStatus' => StatusCode::$orderStatus['waitPay'], 'returnStatus' => StatusCode::$orderReturn['notReturn'], 'outStatus' => StatusCode::$delete, 'createTime' => time(), 'updateTime' => time(), 'customerOwe' => $customerOwe,//客户当前欠款 'auditStatus' => StatusCode::$auditStatus['auditing'], 'preferential' => $goodsCommonData['preferential'],//优惠券优惠金额 'vipDiscount' => isset($goodsCommonData['vipDiscount']) ? $goodsCommonData['vipDiscount'] : 0,//会员卡优惠金额 'vipDoubleDiscount' => isset($goodsCommonData['vipDoubleDiscount']) ? $goodsCommonData['vipDoubleDiscount'] : 0,//会员卡折上折优惠金额 'originPayAmount' => $goodsCommonData['payMoney'],//原支付金额, 'orderType' => StatusCode::$orderType['cashierOrder'], 'verifyCode' => $verifyCode, 'expressMoney' => isset($goodsCommonData['expressMoney']) ? $goodsCommonData['expressMoney'] : 0, 'cashierUid' => $this->loginUserCenterId, 'guideUids' => $params['guideUids'], 'cashierName' => $params['cashierName'], 'guideName' => $params['guideName'], 'remMoney' => isset($goodsCommonData['rem_money']) ? $goodsCommonData['rem_money'] : 0, 'changeSubMoney' => isset($goodsCommonData['subPrice']) ? $goodsCommonData['subPrice'] : 0, 'isNoneUser' => $this->onlineUserId == StatusCode::$noneUserCenter ? StatusCode::$standard : StatusCode::$delete, 'customerMobile' => $params['customerMobile'], 'serialNum' => $objStockCache->createSerialSn(0,'Order'), 'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : '', 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : 0, ]; $allOrderIds[] = $orderId; //2。订单表 $orderId = $this->objDOrder->insert($masterOrder); if ($orderId === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $masterOrder['goodsName'] = ''; foreach ($val['shopGoodsData'] as $k => &$v) { $addOrderGoods = [ 'no' => $sn, 'orderId' => $orderId, 'goodsId' => $v['goodsId'], 'goodsName' => $v['goodsName'], 'shopId' => $val['shopId'],//商铺id 'shopName' => $val['shopName'],//商铺名称 'originPrice' => $v['originPrice'], 'price' => $v['price'], 'buyNum' => $v['buyNum'], 'totalMoney' => $v['totalMoney'], 'skuId' => $v['skuId'], 'goodsBasicId' => $v['goodsBasicId'], 'goodsCode' => $v['goodsCode'], 'deliverNum' => $v['buyNum'],//发货数量=购买数量 'unitName' => $v['unitName'],//单位名称 'conversion' => $v['conversion'],//换算比率 'preferential' => $v['preferential'],//优惠券优惠金额 'vipDiscount' => $v['vipDiscount'],//会员卡优惠金额 'categoryPath' => isset($v['categoryPath']) ? $v['categoryPath'] : '',//分类路径 'brandId' => isset($v['brandId']) ? $v['brandId'] : 0,//品牌id 'specGroup' => isset($v['specGroup']) && !empty($v['specGroup']) ? json_encode($v['specGroup']) : NULL, 'goodsImages' => isset($v['goodsImages']) && is_string($v['goodsImages']) ? $v['goodsImages'] : '', 'barCode' => isset($v['barCode']) ? $v['barCode'] : '', 'storageCode' => isset($v['storageCode']) ? $v['storageCode'] : '', 'categoryName' => isset($v['categoryName']) ? $v['categoryName'] : '', 'brandName' => isset($v['brandName']) ? $v['brandName'] : '', 'expressMoney' => isset($v['expressMoney']) ? $v['expressMoney'] : 0, 'outNum' => 0,//已出库数量 'outOfNum' => getArrayItem($v, 'buyNum', 0),//未出库数量 'isEq' => getArrayItem($v,'isEq',StatusCode::$delete), 'extends' => json_encode(getArrayItem($v, 'extends', null)), ]; $lockInventoryData[] = [ 'warehouseId' => $shopData[$v['shopId']]['warehouseId'], 'materielId' => $v['goodsBasicId'], 'materielCode' => $v['goodsCode'], 'lockingNum' => $v['buyNum'], 'originId' => $orderId, 'originNo' => $sn, 'source' => StatusCode::$orderType['saleOrder'], 'sourceNo' => $sn, 'operatorId' => $masterOrder['customerId'], 'operatorName' => $masterOrder['customerName'], 'skuId' => $v['skuId'], ]; $goodsSaleData [] = [ 'goodsId' => $addOrderGoods['goodsId'], 'skuId' => $addOrderGoods['skuId'], 'buyNum' => $addOrderGoods['buyNum'], ]; //活动商品数据 if ($this->isFront) { if (isset($v['activityId']) && $v['activityId'] != 0) { $activityData[] = [ 'goodsId' => $v['goodsId'], 'skuId' => $v['skuId'], 'activityId' => $v['activityId'], 'buyNum' => $v['buyNum'] ]; } } $masterOrder['goodsName'] .= $v['goodsName'] . ' '; $result = $objMOrderGoods->addOrderGoods($addOrderGoods); if (!$result->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } $allCartIds[] = $v['cartId']; } //存入ES $masterOrder['verifyCode'] = isset($verifyCode) ? $verifyCode : ''; self::updateEsData($orderId, $masterOrder, [], $masterOrder['goodsName']); $allSn[] = $sn;//所有订单号 } $this->objDOrder->commit(); $this->objDOrder->beginTransaction(); //删除购物车内已生成订单商品 $objMCashierCart = new MCashierCart($this->onlineUserId, $this->onlineEnterpriseId, $this->loginUserCenterId); $result = $objMCashierCart->delCart($allCartIds, true); if (!$result->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } //将优惠券改为已使用 if (isset($goodsCommonData['useCoupon']) && !empty($goodsCommonData['useCoupon'])) { $result = $objMUserCoupon->updateIsUse(['id' => $goodsCommonData['useCoupon']['id']], ['isUse' => StatusCode::$delete, 'useTime' => time()]); if (!$result->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } } //锁定库存商品数量 $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId); $lockInventoryResult = $objMInventory->updateLockInventory($shopId,$lockInventoryData); if (!$lockInventoryResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode()); } //增加销量 $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId); if (!empty($goodsSaleData)) { foreach ($goodsSaleData as $value) { $res = $objMGoods->updateSalesNum($value['goodsId'], $value['skuId'], $value['buyNum']); if ($res === false) { Logger::logs(E_USER_ERROR, '错误', __CLASS__, __LINE__, '商品增加销量失败'); } } } //file_put_contents('/www/wwwroot/logs/api.junhailan.com/MSaleOrder_error.log', date('Y-m-d H:i:s') . '数据:' . var_export($mapDetails, true) . PHP_EOL, FILE_APPEND); $this->objSaleOrder->setGoodsDetails($mapDetails); //统计订单信息 self::noticeStatistics([ 'userCenterId' => $params['userCenterId'], 'enterpriseId' => $this->onlineEnterpriseId, 'customerId' => $params['customerId'], 'no' => $allSn, 'noticeType' => 'create', ], 'MOrderStatistics'); //写日志 foreach ($allSn as $sn) { parent::saveLog([ 'no' => $sn, 'actionType' => '创建订单',//创建订单 'operationData' => '', 'userCenterId' => $params['userCenterId'], 'enterpriseId' => $this->onlineEnterpriseId, 'createTime' => time(), ]); } //自动审核订单 $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId); foreach ($allOrderIds as $key => $id) { //自动审核订单 $auditResult = self::updateAuditStatus([ 'id' => $id, 'audit' => '自动审核', 'auditId' => $this->onlineUserId, 'auditStatus' => StatusCode::$auditStatus['auditPass'] ]); if (!$auditResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($auditResult->getData(), $auditResult->getErrorCode()); } $outId = $auditResult->getData();//出库单id //自动出库 $dbResult = $objMInventoryOut->updateInventoryOutStatus(['id' => $outId, 'auditId' => $this->loginUserCenterId, 'auditName' => '销售自动审核']); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } } //确认收款 $dbResult = self::updateOrderPayData(['payStatus' => StatusCode::$standard, 'payTime' => time()], ['id' => $allOrderIds]); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } //确认收货 foreach ($allOrderIds as $orderId) { $dbResult = self::updateOrderStatus($orderId, ['orderStatus' => StatusCode::$orderStatus['finish']], []); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } $objMCashier = new MCashier($this->onlineUserId, $this->onlineEnterpriseId); $cashierResult = $objMCashier->calculatePushMoney($orderId); if (!$cashierResult->isSuccess()) { Logger::logs(E_USER_ERROR, '订单提成计算失败', __CLASS__, __LINE__, $cashierResult->getData()); } } //创建收款单 $received = [ 'currentAccountName' => $params['currentAccountName'], 'financeType' => '销售收款', 'financeTypeId' => 2, 'shopId' => $shopId, 'shopName' => $shopName, 'receiptTime' => time(), 'operatorId' => $this->loginUserCenterId, 'accountList' => $params['accountList'], 'customerId' => $customerData['id'], 'customerName' => $customerData['name'], 'sourceNo' => $sn, 'sourceNoMoney' => $goodsCommonData['payMoney'], 'createTime' => time(), 'auditStatus' => StatusCode::$auditStatus['auditing'], 'updateTime' => time(), ]; $objMReceived = new MReceived($this->onlineEnterpriseId, $this->loginUserCenterId); $receivedResult = $objMReceived->addReceived($received, true); if (!$receivedResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode()); } $this->objDOrder->commit(); if ($this->onlineUserId == StatusCode::$noneUserCenter) { $objDCashierCustomerPrice = new DCashierCustomerPrice(); $objDCashierCustomerPrice->setTable('qianniao_cashier_customer_price_' . $this->onlineEnterpriseId); $objDCashierCustomerPrice->delete(['cashierUid' => $this->loginUserCenterId, 'customerUid' => StatusCode::$noneUserCenter]); } return ResultWrapper::success($orderId); } /** * 订单打印小票 */ public function printOrder() { $data = []; $goodsDetails = $this->objSaleOrder->getGoodsDetails(); foreach ($goodsDetails as $value) { $data[$value['goodsId']]['title'] = $value['goodsName']; $data[$value['goodsId']]['skuData'][] = [ 'skuName' => isset($value['specName']) ? $value['specName'] : '', 'unitName' => isset($value['unitName']) ? $value['unitName'] : '', 'unitPrice' => isset($value['unitPrice']) ? $value['unitPrice'] : 0.00, 'num' => isset($value['buyNum']) ? $value['buyNum'] : 0, 'amountPrice' => isset($value['totalMoney']) ? $value['totalMoney'] : 0 ]; } $printData = [ 'createTime' => $this->objSaleOrder->getCreateTime(), 'shopName' => $this->objSaleOrder->getShopName(), 'title' => $this->objSaleOrder->getReceiptTitle(), 'codeName' => $this->objSaleOrder->getCodeName(), 'code' => $this->objSaleOrder->getNo(), 'userName' => $this->objSaleOrder->getCustomerName(), 'mobile' => $this->objSaleOrder->getCustomerMobile(), 'preferential' => $this->objSaleOrder->getPreferentialAmount(), //优惠金额 'totalMoney' => $this->objSaleOrder->getTotalAmount(), 'payAmount' => $this->objSaleOrder->getPayAmount(), 'address' => $this->objSaleOrder->getAddress(), 'details' => $data ]; $formatPrint = parent::formatMsg($printData); $objCloudPrint = new CloudPrint(); $objCloudPrint->sendMsg($formatPrint, $this->onlineEnterpriseId); } /** * 将所有商品库存转换为主单位sku * @param $data * @return array|ResultWrapper * @throws \Exception */ public function formatMerge($data) { //将相同的商品合并到一起并启用到主单位的 $allMapping = []; if (empty($data)) return $data; $allMapping = []; $all = []; $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId); $res = $objMSku->getMaterSkuId(['goodsId' => array_values(array_unique(array_column($data, 'goodsBasicId'))), 'isMaster' => StatusCode::$standard, 'deleteStatus' => StatusCode::$standard]); if (!$res->isSuccess()) { return ResultWrapper::fail($res->getData(), ErrorCode::$dberror); } $skuData = $res->getData(); foreach ($data as &$goods) { $goods['masterSkuId'] = $skuData[$goods['goodsBasicId']]; $allMapping[$goods['goodsId']][] = [ 'buyNum' => $goods['conversion'] == 0 ? $goods['buyNum'] : bcdiv($goods['buyNum'], $goods['conversion'], 2), 'skuId' => $goods['skuId'], 'conversion' => $goods['conversion'], 'goodsId' => $goods['goodsId'], 'masterSkuId' => $goods['masterSkuId'] ]; } unset($goods); foreach ($allMapping as $key => $goods) { $all[] = [ 'buyNum' => array_sum(array_column($allMapping[$key], 'buyNum')), 'goodsId' => $goods[0]['goodsId'], 'skuId' => $goods[0]['masterSkuId'],//都换算成主单位的 ]; } return ResultWrapper::success($all); } /** * 确认收款检测出库状态 * @param $id * @return ResultWrapper */ public function checkOutOrderStatus($id) { $dbResult = $this->objDOrder->get_field('outStatus', ['id' => $id]); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($dbResult)) { return ResultWrapper::fail('没有找到订单信息', ErrorCode::$paramError); } if ($dbResult == StatusCode::$delete) { return ResultWrapper::fail('订单未出库暂时不能确认收款', ErrorCode::$paramError); } return ResultWrapper::success($dbResult); } /** * 销售订单毛利明细 * @param $params * @return ResultWrapper * @throws \Exception */ public function getOrderProfit($params,$export = 0) { $limit = $params['limit']; unset($params['limit']); $offset = $params['offset']; unset($params['offset']); if($export){ $limit = 999; $offset = 0; } $modelResult = self::formatOrderTableName($params); if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $tables = $modelResult->getData(); if (empty($tables)) { return ResultWrapper::fail('表后缀计算失败', ErrorCode::$paramError); } $whereSql = ' where o.shopId = ' . $params['shopId'] . ' and g.goodsId = ' . $params['goodsId'] . ' and o.createTime between ' . $params['start'] . ' and ' . $params['end']; if (isset($params['customerId']) && !empty($params['customerId'])) { $whereSql .= ' and customerId = ' . $params['customerId']; } $field = 'o.id as orderId,o.no,o.customerId,o.customerName,o.createTime,o.shopId,o.shopName,o.orderStatus,o.outStatus,o.orderType,g.goodsId,g.goodsCode,g.goodsName,g.price,g.buyNum,(g.preferential + g.vipDiscount) as discount, g.outCostPrice,g.goodsBasicId,g.skuId,g.totalMoney'; $sql = ''; foreach ($tables as $value) { !empty($sql) && $sql = $sql . ' union all '; $orderTableName = 'qianniao_order_' . $this->onlineEnterpriseId . '_' . $value; $orderGoodsTableName = 'qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $value; $sql = '(select ' . $field . ' from ' . $orderGoodsTableName . ' g left join ' . $orderTableName . ' o on o.id = g.orderId ' . $whereSql . ')'; } $twoField = 'orderId,no,customerId,customerName,createTime,shopId,shopName,orderStatus,outStatus,orderType,goodsId,goodsCode,goodsName,price,buyNum,discount,outCostPrice,goodsBasicId,skuId,totalMoney'; $sql = 'select ' . $twoField . ' from (' . $sql . ') as details '; $selectSql = $sql . 'order by createTime desc limit ' . $offset . ',' . $limit; $dbResult = $this->objDOrder->query($selectSql); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$paramError); } //提取客户数据 if (empty($dbResult)) { return ResultWrapper::fail('查询结果为空', ErrorCode::$dberror); } $customerData = []; foreach ($dbResult as &$value) { if (!isset($customerData[$value['customerId']])) { $customerData[$value['customerId']] = [ 'id' => $value['customerId'], 'name' => $value['customerName'], ]; } //销售成本 $value['saleCostAmount'] = bcmul($value['buyNum'], $value['outCostPrice'], 4); //销售毛利 $value['saleProfitAmount'] = bcsub($value['totalMoney'], $value['saleCostAmount'], 8); //毛利率 $value['saleProfitRate'] = "0.00"; if ($value['saleProfitAmount'] > 0 && $value['saleCostAmount'] > 0) { $value['saleProfitRate'] = bcmul(bcdiv($value['saleProfitAmount'], $value['totalMoney'], 8), 100, 4); } } unset($value); if($export){ self::exportOrderProfit($dbResult); exit; } $countSql = 'select count(orderId) as count from ( ' . $sql . ' ) as selectDetails'; $totalDbResult = $this->objDOrder->query($countSql); if ($totalDbResult === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $total = array_shift($totalDbResult)['count']; $return['data']['customerData'] = array_values($customerData); $return['data']['data'] = $dbResult; $return['total'] = ($total) ? intval($total) : 0; return ResultWrapper::success($return); } /** * 计算表名后缀 * @param $params * @return ResultWrapper * @throws \Exception */ public function formatOrderTableName($params) { $whereSql = ''; if (isset($params['shopId']) && !empty($params['shopId'])) { $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and '; $whereSql .= ' shopId = ' . $params['shopId']; } if (isset($params['customerId']) && !empty($params['customerId'])) { $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and '; $whereSql .= ' customerId = ' . $params['customerId']; } if (isset($params['start']) && !empty($params['start']) && isset($params['end']) && !empty($params['end'])) { $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and '; $whereSql .= ' createTime between ' . $params['start'] . ' and ' . $params['end']; } $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $indexSql = 'select userCenterId from ' . $this->objDOrderIndex->get_Table() . $whereSql; $dbResult = $this->objDOrderIndex->query($indexSql); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$paramError); } if (empty($dbResult)) { return ResultWrapper::success([]); } $tables = []; foreach ($dbResult as $value) { //格式化数据 根据userCenterId 计算所有goods表名 $num = (int)ceil($value['userCenterId'] / $this->cutTable); $tableName = 'qianniao_order_' . $this->onlineEnterpriseId . '_' . $num; $existsTable = $this->objDOrder->existsTable($tableName); if ($existsTable && !in_array($num, $tables)) { $tables[] = $num; } } return ResultWrapper::success($tables); } /************************************************统计项 start******************************************************/ /** * @param $key * @param $shopId * @return ResultWrapper */ public function businessOverview($key, $shopId) { $result = $this->objOverviewCache->getBusinessOverview($this->onlineEnterpriseId, $key, $shopId); return $result; } /** * 客单价 * @param $key * @param $shopId * @return int|string */ public function customerAverageMoney($key, $shopId) { $objCustomerCache = new CustomerCache(); $orderConfirmedMoney = $this->objOverviewCache->getBusinessOverview($this->onlineEnterpriseId, 'orderConfirmedMoney', $shopId);//营业额 $customerNum = array_sum($objCustomerCache->getTodayCustomerOrderInfo($this->onlineEnterpriseId, null, $shopId)); if ($orderConfirmedMoney == 0 || $customerNum == 0) return 0; return bcdiv($orderConfirmedMoney, $customerNum, 2); } /** * 后置操作 */ public function __destruct() { // TODO: Implement __destruct() method. if ($this->isEnablePrint) self::printOrder(); } /** * 今日下单客户数量 * @param $shopId * @return int */ public function getTodayCustomerOrderNum($shopId = null) { $todayStart = date('Y-m-d 00:00:00', time()); $todayEnd = date('Y-m-d 23:59:59', time()); $fields = 'id'; $sql = 'SELECT ' . $fields . ' FROM qianniao_order_index_' . $this->onlineEnterpriseId . ' WHERE auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' AND createTime BETWEEN ' . strtotime($todayStart) . ' AND ' . strtotime($todayEnd); if (!empty($shopId)) { $sql .= ' and shopId = ' . $shopId; } $sql .= ' GROUP BY customerId'; $result = $this->objDOrder->query($sql); if ($result === false) { Logger::logs(E_USER_ERROR, '查询错误', __CLASS__, __LINE__, $this->objDOrder->error()); return 0; } return count((array)$result); } /** * 今日客单价 * @param null $shopId * @return int|string|null */ public function getTodayOrder($shopId = null) { $todayStart = date('Y-m-d 00:00:00', time()); $todayEnd = date('Y-m-d 23:59:59', time()); $fields = 'userCenterId'; if (!empty($shopId)) { $shopId = ' and shopId = ' . $shopId; }else{ $shopId = ''; } $sql = 'select count(distinct '.$fields.') as num ,sum(payAmount) as money from qianniao_order_'. $this->onlineEnterpriseId .'_1' . ' where auditStatus = ' . StatusCode::$auditStatus['auditPass'] .' and createTime BETWEEN '.strtotime($todayStart). ' and '. strtotime($todayEnd).$shopId; $result = $this->objDOrder->query($sql); if ($result === false) { return 0; } $num = $result[0]['num']; $money = $result[0]['money']; if (empty($money) || empty($num)) { return 0; } return bcdiv($money, $num, 2); } /** * Doc: (des="订单分配业务员") * User: XMing * Date: 2020/8/26 * Time: 3:39 下午 * @param array $params * @return ResultWrapper * @throws \Exception */ public function setSalesMan(array $params) { //在索引表中查询订单 $orderIndex = $this->objDOrderIndex->get(['id' => $params['orderId']]); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('未查询到指定订单', ErrorCode::$paramError); } if (!empty($orderIndex['salesManId'])) { return ResultWrapper::fail('已分配过业务员', ErrorCode::$paramError); } $dbResult = $this->objDCustomer->get(['id' => $orderIndex['customerId']]); if ($dbResult === false) { return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } $customerInfo = $dbResult; if (empty($customerInfo)) { return ResultWrapper::fail('未查询到指定客户', ErrorCode::$dberror); } if($params['ifSalesMan'] == StatusCode::$delete){ if ( !empty($customerInfo['salesManId']) && $customerInfo['salesManId'] != $params['salesManId'] ) { return ResultWrapper::fail('客户只能分配当前 -'.$customerInfo['salesManName'].' -业务员', ErrorCode::$paramError); } $salesManId = $params['salesManId']; $salesManName = $params['salesManName']; }else{ $salesManId = $customerInfo['salesManId']; $salesManName = $customerInfo['salesManName']; } //更新数据 $time = time(); $beginStatus = $this->objDOrderIndex->beginTransaction(); //给客户分配业务员 if($params['ifSalesMan'] == StatusCode::$delete){ $dbResult = $this->objDCustomer->update(['salesManId' => $salesManId, 'salesManName' => $salesManName], ['id' => $orderIndex['customerId']]); if ($dbResult === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } } //更新订单表 //只更新该订单 $dbResult = $this->objDOrderIndex->update(['salesManId' => $salesManId, 'updateTime' => $time], ['id' => $params['orderId']]); if($dbResult === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $updateData = ['salesManId' => $salesManId, 'salesManName' => $salesManName, 'updateTime' => $time]; $dbResult = $this->objDOrder->update($updateData, ['id' => $params['orderId']]); if($dbResult === false){ $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } /* //获取此客户未分配业务员的订单 $orderIndexLists = $this->objDOrderIndex->select(['salesManId' => 0, 'customerId' => $orderIndex['customerId']]); if ($orderIndexLists === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndexLists)) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail('未查询到需要更新的数据', ErrorCode::$paramError); } //计算数据的分表 $updateData = ['salesManId' => $params['salesManId'], 'salesManName' => $params['salesManName'], 'updateTime' => $time]; $allGroupData = []; $allOrderIds = []; foreach ($orderIndexLists as $key => $val) { $tableNum = ceil($val['userCenterId'] / $this->cutTable); $allGroupData[$tableNum][] = $val['id']; $allOrderIds[] = $val['id']; } //更新订单索引表 $updateOrderIndex = $this->objDOrderIndex->update(['salesManId' => $params['salesManId'], 'updateTime' => $time], ['id' => $allOrderIds]); if ($updateOrderIndex === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } //在对应分表中更新数据 foreach ($allGroupData as $k => $orderIds) { $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k); $updateOrder = $this->objDOrder->update($updateData, ['id' => $orderIds]); if ($updateOrder === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } }*/ /* //修改es foreach ($allOrderIds as $orderId) { $_id = self::createEsDocumentId($orderId); $this->objDOrder->esupdateTypeFieldVaule($updateData, $_id); }*/ $beginStatus && $this->objDOrderIndex->commit(); return ResultWrapper::success('操作成功'); } /** * Doc: (des="") * User: XMing * Date: 2020/9/4 * Time: 12:21 下午 * @param string $verifyCode * @return ResultWrapper * @throws \Exception */ public function getOrderByVerifyCode(string $verifyCode) { $orderId = $this->objDOrderIndex->get_field('id', ['verifyCode' => $verifyCode]); if ($orderId === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderId)) { return ResultWrapper::fail('核销码已失效或不存在', ErrorCode::$paramError); } $orderInfoResult = self::getOrderInfoById($orderId); if (!$orderInfoResult->isSuccess()) { return ResultWrapper::fail($orderInfoResult->getData(), $orderInfoResult->getErrorCode()); } return ResultWrapper::success($orderInfoResult->getData()); } /** * Doc: (des="核销订单") * User: XMing * Date: 2020/9/4 * Time: 2:34 下午 * @param int $id * @param array $header * @return ResultWrapper * @throws \Exception */ public function verification(int $id, $header) { $orderInfo = $this->objDOrderIndex->get(['id' => $id]); if ($orderInfo === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderInfo)) { return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError); } if ($orderInfo['orderStatus'] == StatusCode::$orderStatus['close']) { return ResultWrapper::fail('订单已取消', ErrorCode::$paramError); } if ($orderInfo['orderStatus'] == StatusCode::$orderStatus['finish']) { return ResultWrapper::fail('订单已经核销过了', ErrorCode::$paramError); } if ($orderInfo['auditStatus'] != StatusCode::$auditStatus['auditPass']) { return ResultWrapper::fail('订单尚未审核', ErrorCode::$paramError); } if ($orderInfo['outStatus'] != StatusCode::$standard) { return ResultWrapper::fail('订单还没有出库,不能进行核销操作', ErrorCode::$paramError); } $orderResult = self::updateOrderStatus($id, ['orderStatus' => StatusCode::$standard], $header); if (!$orderResult->isSuccess()) { return ResultWrapper::fail($orderResult->getData(), $orderResult->getErrorCode()); } return ResultWrapper::success($orderResult->getData()); } /** * Doc: (des="") * User: XMing * Date: 2020/9/8 * Time: 7:14 下午 * @param int $id * @return ResultWrapper */ public function getExpressInfoByOrderId(int $id) { $orderIndex = $this->objDOrderIndex->get(['id' => $id]); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('为获取到指定订单', ErrorCode::$paramError); } if (empty($orderIndex['deliveryNo']) || empty($orderIndex['expressId'])) { return ResultWrapper::success([]); } $objDExpressCode = new DExpressCode(); $expressCode = $objDExpressCode->get(['id' => $orderIndex['expressId']]); if ($expressCode === false) { return ResultWrapper::fail($objDExpressCode->error(), ErrorCode::$dberror); } if (empty($expressCode)) { return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError); } $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId); $basicSetupResult = $objMBasicSetup->getBasicField('logistics_form'); if (!$basicSetupResult->isSuccess()) { return ResultWrapper::fail($basicSetupResult->getData(), $basicSetupResult->getErrorCode()); } $basicSetup = $basicSetupResult->getData(); $basicSetup = isset($basicSetup['logistics_form']) ? $basicSetup['logistics_form'] : []; if (!isset($basicSetup['express_type']) || empty($basicSetup['express_type'])) { return ResultWrapper::fail('未配置物流接口', ErrorCode::$paramError); } $map = []; $return = [ 'list' => [], 'stateMsg' => '', 'nu' => $orderIndex['deliveryNo'], 'expressName' => $expressCode['name'] ]; switch ($basicSetup['express_type']) { case 'express_hundred': $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix); $mobile = $this->objDOrderReceive->get_field('mobile', ['orderId' => $orderIndex['id']]); if ($mobile === false) { return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror); } if (!isset($basicSetup['express_hundred'])) { return ResultWrapper::fail('快递100未进行配置', ErrorCode::$paramError); } $express_hundred = $basicSetup['express_hundred']; if (!isset($express_hundred['customerCode']) || empty($express_hundred['customerCode']) || !isset($express_hundred['accessKey']) || empty($express_hundred['accessKey'])) { return ResultWrapper::fail('快递100配置有误', ErrorCode::$paramError); } /*$kuaidi100Config = Factory::config()->get('kuaidi100'); if(empty($kuaidi100Config) || !isset($kuaidi100Config['customer']) || !isset($kuaidi100Config['key']) ){ return ResultWrapper::fail('快递100配置有误',ErrorCode::$paramError); }*/ //$objQuery = new Query($kuaidi100Config['customer'], $kuaidi100Config['key']); /*$kuaidiData = [ 'com' => 'yunda', 'num' => '3103922659603', 'phone' => 17600105150, ];*/ $objQuery = new Query($express_hundred['customerCode'], $express_hundred['accessKey']); $kuaidiData = [ 'com' => $expressCode['kuaidi100'], 'num' => $orderIndex['deliveryNo'], 'phone' => $mobile, ]; $result = $objQuery->pollQuery($kuaidiData); if (!$result->isSuccess()) { return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError); } $resultData = $result->getData(); $list = isset($resultData['data']) ? $resultData['data'] : []; $return['stateMsg'] = $objQuery->getState(isset($resultData['state']) ? $resultData['state'] : 0); $map = self::formatExpressList($list, 'express_hundred'); break; case 'express_bird': if (!isset($basicSetup['express_bird'])) { return ResultWrapper::fail('快递鸟未进行配置', ErrorCode::$paramError); } $express_bird = $basicSetup['express_bird']; if (!isset($express_bird['userId']) || empty($express_bird['userId']) || !isset($express_bird['apiKey']) || empty($express_bird['apiKey'])) { return ResultWrapper::fail('快递鸟配置有误', ErrorCode::$paramError); } /*$kdniaoConfig = Factory::config()->get('kdniao'); if(empty($kdniaoConfig) || !isset($kdniaoConfig['EBusinessID']) || !isset($kdniaoConfig['key']) ){ return ResultWrapper::fail('快递鸟配置错误', ErrorCode::$configEroor); }*/ //$objQuery = new KDNiaoQuery($kdniaoConfig['EBusinessID'], $kdniaoConfig['key']); /*$kuaidiData = [ 'com' => 'HTKY', 'num' => '557021498255630', ];*/ $objQuery = new KDNiaoQuery($express_bird['userId'], $express_bird['apiKey']); $kuaidiData = [ 'com' => $expressCode['kdniao'], 'num' => $orderIndex['deliveryNo'], ]; $result = $objQuery->EbusinessOrderHandle($kuaidiData); if (!$result->isSuccess()) { return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError); } $resultData = $result->getData(); $list = isset($resultData['Traces']) ? $resultData['Traces'] : []; $return['stateMsg'] = $objQuery->getState(isset($resultData['State']) ? $resultData['State'] : 0); $map = self::formatExpressList($list, 'express_bird'); break; } $return['list'] = $map; return ResultWrapper::success($return); } /** * Doc: (des="修改订单的发货信息") * User: XMing * Date: 2020/9/9 * Time: 11:12 上午 * @param string $no * @param array $params * @param int $orderId * @return ResultWrapper * @throws \Exception */ public function editOrderExpress(string $no, array $params, int $orderId = 0) { if (empty($orderId)) { $orderIndex = $this->objDOrderIndex->get(['no' => $no]); } else { $orderIndex = $this->objDOrderIndex->get(['id' => $orderId]); } if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('未获取到指定订单信息' . $no, ErrorCode::$paramError); } $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix); $this->objDOrderIndex->beginTransaction(); if (isset($params['deliveryType']) && $params['deliveryType'] == StatusCode::$deliveryType['logistics']){ $update = [ 'logisticsData' => json_encode($params['logisticsData']), 'updateTime' => time(), ]; }else{ $update = [ 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '', 'expressName' => isset($params['expressName']) ? $params['expressName'] : '', 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0, 'updateTime' => time(), ]; $updateIndex = $this->objDOrderIndex->update($update, ['id' => $orderIndex['id']]); if ($updateIndex === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } } $updateOrder = $this->objDOrder->update($update, ['id' => $orderIndex['id']]); if ($updateOrder === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } //记录司机id $driverId = isset($params['logisticsData']['id']) ? $params['logisticsData']['id'] : ''; $updatedriverId = $this->objDOrder->update(['driverId'=>$driverId],['id' => $orderIndex['id']]); if ($updatedriverId === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } /* $_id = self::createEsDocumentId($orderIndex['id']); $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/ $this->objDOrderIndex->commit(); return ResultWrapper::success(true); } /** * Doc: (des="") * User: XMing * Date: 2020/9/8 * Time: 8:47 下午 * @param array $list * @param string $type * @return array */ private function formatExpressList(array $list, string $type) { $map = []; switch ($type) { case 'express_hundred': foreach ($list as $value) { $map[] = [ 'context' => $value['context'], 'time' => $value['time'] ]; } break; case 'express_bird': foreach ($list as $value) { $map[] = [ 'context' => $value['AcceptStation'], 'time' => $value['AcceptTime'] ]; } $map = array_reverse($map); break; } return $map; } /** * Doc: (des="") * User: XMing * Date: 2020/10/12 * Time: 5:31 下午 * @param array $params * @return ResultWrapper * @throws \Exception */ public function create(array $params) { $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId); $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId); $objMCart = new MCart($this->onlineUserId, $this->onlineEnterpriseId); $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId); $objDStaff = new DStaff(); $objStockCache = new Stock($this->onlineEnterpriseId); $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId); $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $goodsCommonData = $params['goodsData']; //锁定库存 查询商铺对应的仓库 $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId); $modelResult = $objMShop->getShopDataByShopIds(array_column($goodsCommonData['goodsData'], 'shopId')); if (!$modelResult->isSuccess()) { return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode()); } $shopData = $modelResult->getData(); if (empty($shopData)) { return ResultWrapper::fail('获取店铺数据失败', ErrorCode::$paramError); } $paramsResult = self::getIdsCashierMap($params); if (!$paramsResult->isSuccess()) { return ResultWrapper::fail($paramsResult->getData(), $paramsResult->getErrorCode()); } $params = $paramsResult->getData(); //获取客户信息 $customerOwe = 0; if ($this->onlineUserId == StatusCode::$noneUserCenter) { $customerData = [ 'id' => StatusCode::$noneCustomer, 'name' => '匿名客户' ]; } else { $customerDataResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$customerDataResult->isSuccess()) { return ResultWrapper::fail($customerDataResult->getData(), $customerDataResult->getErrorCode()); } $customerData = $customerDataResult->getData(); //获取客户当前欠款 if (isset($customerData['id'])) { $customerOwe = $objMCustomerBalance->getCustomerBalance($customerData['id']); } //获取客户手机号 $objDUserCenter = new DUserCenter(); $userInfo = $objDUserCenter->get(['id' => $this->onlineUserId], 'mobile'); if ($userInfo === false) { return ResultWrapper::fail($objDUserCenter->error(), ErrorCode::$dberror); } $params['customerMobile'] = isset($userInfo['mobile']) ? $userInfo['mobile'] : ''; } // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号 $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['cashierOrder'], $this->onlineUserId); $lockInventoryData = [];//锁定库存物料 $goodsSaleData = [];//销售数据 $allSn = [];//所有单号 $allOrderIds = [];//所有订单 $mapDetails = [];//订单商品 $createTime = time(); $allCartIds = []; $shopName = ''; $shopId = 0;//目前只有一个 $this->objDOrder->beginTransaction(); foreach ($goodsCommonData['goodsData'] as $key => $val) { $sn = createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId); //将数据写入索引表 $shopId = $val['shopId']; $orderIndexData = [ 'shopId' => $val['shopId'], 'userCenterId' => $params['userCenterId'], 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0, 'createTime' => time(), 'updateTime' => time(), 'deleteStatus' => StatusCode::$standard, 'auditStatus' => StatusCode::$auditStatus['auditing'], 'payStatus' => StatusCode::$delete, 'orderStatus' => StatusCode::$orderStatus['waitPay'], 'outStatus' => StatusCode::$delete, 'returnStatus' => StatusCode::$orderReturn['notReturn'], 'deliveryType' => $params['deliveryType'], 'payType' => $params['payType'], 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0, 'no' => $sn, 'orderType' => StatusCode::$orderType['cashierOrder'], 'selfRuleId' => 0, 'cashierUid' => $this->loginUserCenterId, 'guideUids' => isset($params['guideUids']) ? $params['guideUids'] : '', ]; //1. 先写索引表 $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $orderId = $this->objDOrderIndex->insert($orderIndexData); if ($orderId === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($$this->objDOrderIndex->error(), ErrorCode::$dberror); } //3。上门自提订单,生成核销码 $verifyCode = self::createVerifyCode($orderId); //兼容以前代码 $updateRes = $this->objDOrderIndex->update(['verifyCode' => $verifyCode], ['id' => $orderId]); if ($updateRes === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($$this->objDOrderIndex->error(), ErrorCode::$dberror); } //订单数据 $shopName = $val['shopName'];//现在就一个店铺 $masterOrder = [ 'id' => $orderId,//订单id 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0, 'userCenterId' => $params['userCenterId'], 'shopId' => $val['shopId'], 'shopName' => $val['shopName'], 'no' => $sn, 'outerTradeNo' => $tmpOuterTradeNo, 'totalMoney' => $goodsCommonData['totalMoney'], 'payAmount' => $goodsCommonData['payMoney'], 'customerName' => isset($customerData['name']) ? $customerData['name'] : '', 'remark' => $params['remark'], 'deliveryType' => $params['deliveryType'],//配送方式 'payType' => $params['payType'],//支付方式 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0, 'salesManName' => isset($customerData['salesManName']) ? $customerData['salesManName'] : '', 'customerType' => isset($customerData['type']) ? $customerData['type'] : 0, 'buyTotal' => array_sum(array_column($val['shopGoodsData'], 'buyNum')), 'source' => $params['source'],//来源 'orderStatus' => StatusCode::$orderStatus['waitPay'], 'returnStatus' => StatusCode::$orderReturn['notReturn'], 'outStatus' => StatusCode::$delete, 'createTime' => time(), 'updateTime' => time(), 'customerOwe' => $customerOwe,//客户当前欠款 'auditStatus' => StatusCode::$auditStatus['auditing'], 'preferential' => $goodsCommonData['preferential'],//优惠券优惠金额 'vipDiscount' => isset($goodsCommonData['vipDiscount']) ? $goodsCommonData['vipDiscount'] : 0,//会员卡优惠金额 'vipDoubleDiscount' => isset($goodsCommonData['vipDoubleDiscount']) ? $goodsCommonData['vipDoubleDiscount'] : 0,//会员卡折上折优惠金额 'originPayAmount' => $goodsCommonData['payMoney'],//原支付金额, 'orderType' => StatusCode::$orderType['cashierOrder'], 'verifyCode' => $verifyCode, 'expressMoney' => isset($goodsCommonData['expressMoney']) ? $goodsCommonData['expressMoney'] : 0, 'cashierUid' => $this->loginUserCenterId, 'guideUids' => isset($params['guideUids']) ? $params['guideUids'] : '', 'cashierName' => $params['cashierName'], 'guideName' => $params['guideName'], 'remMoney' => isset($goodsCommonData['rem_money']) ? $goodsCommonData['rem_money'] : 0, 'changeSubMoney' => isset($goodsCommonData['subPrice']) ? $goodsCommonData['subPrice'] : 0, 'isNoneUser' => $this->onlineUserId == StatusCode::$noneUserCenter ? StatusCode::$standard : StatusCode::$delete, 'customerMobile' => $params['customerMobile'], 'serialNum' => $objStockCache->createSerialSn(0,'Order'), 'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : '', 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : 0, ]; $allOrderIds[] = $orderId; //2。订单表 $orderId = $this->objDOrder->insert($masterOrder); if ($orderId === false) { $this->objDOrder->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } $masterOrder['goodsName'] = ''; foreach ($val['shopGoodsData'] as $k => &$v) { $addOrderGoods = [ 'no' => $sn, 'orderId' => $orderId, 'goodsId' => $v['goodsId'], 'goodsName' => $v['goodsName'], 'shopId' => $val['shopId'],//商铺id 'shopName' => $val['shopName'],//商铺名称 'originPrice' => $v['originPrice'], 'price' => $v['price'], 'buyNum' => $v['buyNum'], 'totalMoney' => $v['totalMoney'], 'skuId' => $v['skuId'], 'goodsBasicId' => $v['goodsBasicId'], 'goodsCode' => $v['goodsCode'], 'deliverNum' => $v['buyNum'],//发货数量=购买数量 'unitName' => $v['unitName'],//单位名称 'conversion' => $v['conversion'],//换算比率 'preferential' => $v['preferential'],//优惠券优惠金额 'vipDiscount' => $v['vipDiscount'],//会员卡优惠金额 'categoryPath' => isset($v['categoryPath']) ? $v['categoryPath'] : '',//分类路径 'brandId' => isset($v['brandId']) ? $v['brandId'] : 0,//品牌id 'specGroup' => isset($v['specGroup']) && !empty($v['specGroup']) ? json_encode($v['specGroup']) : NULL, 'goodsImages' => isset($v['goodsImages']) && is_string($v['goodsImages']) ? $v['goodsImages'] : '', 'barCode' => isset($v['barCode']) ? $v['barCode'] : '', 'storageCode' => isset($v['storageCode']) ? $v['storageCode'] : '', 'categoryName' => isset($v['categoryName']) ? $v['categoryName'] : '', 'brandName' => isset($v['brandName']) ? $v['brandName'] : '', 'expressMoney' => isset($v['expressMoney']) ? $v['expressMoney'] : 0, ]; $lockInventoryData[] = [ 'warehouseId' => $shopData[$v['shopId']]['warehouseId'], 'materielId' => $v['goodsBasicId'], 'materielCode' => $v['goodsCode'], 'lockingNum' => $v['buyNum'], 'originId' => $orderId, 'originNo' => $sn, 'source' => StatusCode::$orderType['saleOrder'], 'sourceNo' => $sn, 'operatorId' => $masterOrder['customerId'], 'operatorName' => $masterOrder['customerName'], 'skuId' => $v['skuId'], ]; $goodsSaleData [] = [ 'goodsId' => $addOrderGoods['goodsId'], 'skuId' => $addOrderGoods['skuId'], 'buyNum' => $addOrderGoods['buyNum'], ]; //活动商品数据 if ($this->isFront) { if (isset($v['activityId']) && $v['activityId'] != 0) { $activityData[] = [ 'goodsId' => $v['goodsId'], 'skuId' => $v['skuId'], 'activityId' => $v['activityId'], 'buyNum' => $v['buyNum'] ]; } } $masterOrder['goodsName'] .= $v['goodsName'] . ' '; $result = $objMOrderGoods->addOrderGoods($addOrderGoods); if (!$result->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } $allCartIds[] = $v['cartId']; } //存入ES $masterOrder['verifyCode'] = isset($verifyCode) ? $verifyCode : ''; self::updateEsData($orderId, $masterOrder, [], $masterOrder['goodsName']); $allSn[] = $sn;//所有订单号 } //将优惠券改为已使用 if (isset($goodsCommonData['useCoupon']) && !empty($goodsCommonData['useCoupon'])) { $result = $objMUserCoupon->updateIsUse(['id' => $goodsCommonData['useCoupon']['id']], ['isUse' => StatusCode::$delete, 'useTime' => time()]); if (!$result->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } } //锁定库存商品数量 $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId); $lockInventoryResult = $objMInventory->updateLockInventory($lockInventoryData); if (!$lockInventoryResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode()); } //增加销量 $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId); if (!empty($goodsSaleData)) { foreach ($goodsSaleData as $value) { $res = $objMGoods->updateSalesNum($value['goodsId'], $value['skuId'], $value['buyNum']); if ($res === false) { Logger::logs(E_USER_ERROR, '错误', __CLASS__, __LINE__, '商品增加销量失败'); } } } //file_put_contents('/www/wwwroot/logs/api.junhailan.com/MSaleOrder_error.log', date('Y-m-d H:i:s') . '数据:' . var_export($mapDetails, true) . PHP_EOL, FILE_APPEND); $this->objSaleOrder->setGoodsDetails($mapDetails); //统计订单信息 self::noticeStatistics([ 'userCenterId' => $params['userCenterId'], 'enterpriseId' => $this->onlineEnterpriseId, 'customerId' => $params['customerId'], 'no' => $allSn, 'noticeType' => 'create', ], 'MOrderStatistics'); //写日志 foreach ($allSn as $sn) { parent::saveLog([ 'no' => $sn, 'actionType' => '创建订单',//创建订单 'operationData' => '', 'userCenterId' => $params['userCenterId'], 'enterpriseId' => $this->onlineEnterpriseId, 'createTime' => time(), ]); } $this->objDOrder->commit(); return ResultWrapper::success(['orderId' => $orderId, 'shopName' => $shopName, 'out_trade_no' => $tmpOuterTradeNo, 'total_fee' => $goodsCommonData['payMoney']]); } /** * Doc: (des="订单确认收款") * User: XMing * Date: 2020/10/12 * Time: 4:11 下午 * @param array $params * @return ResultWrapper * @throws \Exception */ public function confirm(array $params) { $orderIndex = $this->objDOrderIndex->get(['id' => $params['orderId']]); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('获取订单信息失败', ErrorCode::$paramError); } if ($orderIndex['payStatus'] != StatusCode::$delete) { return ResultWrapper::fail('订单已付款', ErrorCode::$paramError); } $fix = $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);; $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix); $orderData = $this->objDOrder->get(['id' => $params['orderId']]); if ($orderData === false) { return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } if (empty($orderData)) { return ResultWrapper::fail('获取订单信息失败', ErrorCode::$paramError); } $paramsResult = self::getIdsCashierMap($params); if (!$paramsResult->isSuccess()) { return ResultWrapper::fail($paramsResult->getData(), $paramsResult->getErrorCode()); } $params = $paramsResult->getData(); $this->objDOrderIndex->beginTransaction(); //修稿订单信息 $update = [ 'payType' => $params['payType'], 'updateTime' => time(), 'cashierUid' => $this->loginUserCenterId, 'guideUids' => $params['guideUids'], ]; $updateIndex = $this->objDOrderIndex->update($update, ['id' => $params['orderId']]); if ($updateIndex === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } $update['guideName'] = $params['guideName']; $updateOrder = $this->objDOrder->update($update, ['id' => $params['orderId']]); if ($updateOrder === false) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror); } /* //更新es $_id = self::createEsDocumentId($params['orderId']); $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/ //清空此收银员的购物车 $objMCashierCart = new MCashierCart($this->onlineUserId, $this->onlineEnterpriseId, $this->loginUserCenterId); $result = $objMCashierCart->clearCart(); if (!$result->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($result->getData(), ErrorCode::$dberror); } //自动审核订单 $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId); $auditResult = self::updateAuditStatus([ 'id' => $params['orderId'], 'audit' => '自动审核', 'auditId' => $this->onlineUserId, 'auditStatus' => StatusCode::$auditStatus['auditPass'] ]); if (!$auditResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($auditResult->getData(), $auditResult->getErrorCode()); } $outId = $auditResult->getData();//出库单id //自动出库 $dbResult = $objMInventoryOut->updateInventoryOutStatus(['id' => $outId, 'auditId' => $this->loginUserCenterId, 'auditName' => '销售自动审核']); if (!$dbResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } //确认收款 $dbResult = self::updateOrderPayData(['payStatus' => StatusCode::$standard, 'payTime' => time()], ['id' => [$params['orderId']]]); if (!$dbResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } //确认收货 $dbResult = self::updateOrderStatus($params['orderId'], ['orderStatus' => StatusCode::$orderStatus['finish']], []); if (!$dbResult->isSuccess()) { $this->objDOrder->rollBack(); return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } $objMCashier = new MCashier($this->onlineUserId, $this->onlineEnterpriseId); $cashierResult = $objMCashier->calculatePushMoney($params['orderId']); if (!$cashierResult->isSuccess()) { Logger::logs(E_USER_ERROR, '订单提成计算失败', __CLASS__, __LINE__, $cashierResult->getData()); } //创建收款单 $received = [ 'currentAccountName' => $params['currentAccountName'], 'financeType' => '销售收款', 'financeTypeId' => 2, 'shopId' => $orderData['shopId'], 'shopName' => $orderData['shopName'], 'receiptTime' => time(), 'operatorId' => $this->loginUserCenterId, 'accountList' => $params['accountList'], 'customerId' => $orderData['customerId'], 'customerName' => $orderData['customerName'], 'sourceNo' => $orderData['no'], 'sourceNoMoney' => $orderData['payAmount'], 'createTime' => time(), 'auditStatus' => StatusCode::$auditStatus['auditing'], 'updateTime' => time(), ]; $objMReceived = new MReceived($this->onlineEnterpriseId, $this->loginUserCenterId); $receivedResult = $objMReceived->addReceived($received, true); if (!$receivedResult->isSuccess()) { $this->objDOrderIndex->rollBack(); return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode()); } $this->objDOrderIndex->commit(); if ($this->onlineUserId == StatusCode::$noneUserCenter) { $objDCashierCustomerPrice = new DCashierCustomerPrice(); $objDCashierCustomerPrice->setTable('qianniao_cashier_customer_price_' . $this->onlineEnterpriseId); $objDCashierCustomerPrice->delete(['cashierUid' => $this->loginUserCenterId, 'customerUid' => StatusCode::$noneUserCenter]); } return ResultWrapper::success(true); } /** * Doc: (des="获取收银员工信息") * User: XMing * Date: 2020/10/12 * Time: 5:50 下午 * @param array $params * @return ResultWrapper * @throws \Exception */ private function getIdsCashierMap(array $params) { $objDStaff = new DStaff(); $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId); //获取收银员信息 $allUids = [$this->loginUserCenterId]; if (isset($params['guideUids']) && !empty($params['guideUids'])) { $ids = explode(',', $params['guideUids']); $allUids = array_merge($allUids, $ids); } $userMap = []; if (!empty($allUids)) { $staffList = $objDStaff->select(['userCenterId' => $allUids], 'userCenterId,staffName'); if ($staffList === false) { return ResultWrapper::fail($objDStaff->error(), ErrorCode::$dberror); } foreach ($staffList as $value) { $userMap[$value['userCenterId']] = $value['staffName']; } } $params['cashierName'] = isset($userMap[$this->loginUserCenterId]) ? $userMap[$this->loginUserCenterId] : '超级管理员'; $nameStr = ''; if (!empty($ids)) { foreach ($ids as $uid) { if (!empty($nameStr)) { $nameStr .= ','; } $nameStr .= isset($userMap[$uid]) ? $userMap[$uid] : ''; } } $params['guideName'] = $nameStr; $params['customerMobile'] = ''; return ResultWrapper::success($params); } public function fix_ex() { $_id = self::createEsDocumentId(144); $this->objDOrder->esupdateTypeFieldVaule(['salesManId' => 1, 'salesManName' => '杨明霞', 'updateTime' => time()], $_id); } /** * 查询索引表信息 */ public function getOrderIndexData($where) { $dbResult = $this->objDOrderIndex->get($where); if ($dbResult === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * Doc: (des="根据订单id获取订单信息") * User: XMing * Date: 2020/12/7 * Time: 4:05 下午 * @param int $id * @return ResultWrapper * @throws \Exception */ public function getOrderByOrderId(int $id): ResultWrapper { $orderIndex = $this->objDOrderIndex->get($id); if ($orderIndex === false){ return ResultWrapper::fail($this->objDOrderIndex->error,ErrorCode::$dberror); } if (empty($orderIndex)){ return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError); } $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $order = $this->objDOrder->get($id); if ($order === false){ return ResultWrapper::fail($this->objDOrder->error,ErrorCode::$paramError); } if (empty($order)){ return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError); } return ResultWrapper::success($order); } /** * Doc: (des="") * User: XMing * Date: 2020/12/8 * Time: 10:43 上午 * @param int $id * @return ResultWrapper * @throws \Exception */ public function updateSettel(int $id): ResultWrapper { $orderIndex = $this->objDOrderIndex->get($id); if ($orderIndex === false){ return ResultWrapper::fail($this->objDOrderIndex->error,ErrorCode::$dberror); } if (empty($orderIndex)){ return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError); } $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $order = $this->objDOrder->update(['isSettel' => StatusCode::$standard],$id); if ($order === false){ return ResultWrapper::fail($this->objDOrder->error,ErrorCode::$paramError); } return ResultWrapper::success(true); } /** * Doc: (des="") * User: XMing * Date: 2021/2/4 * Time: 12:06 下午 * @param array $selectParams * @return ResultWrapper */ public function getStatistics(array $selectParams):ResultWrapper { //默认今日的 $todayStart = strtotime(date('Y-m-d 00:00:00', time())); $todayEnd = strtotime(date('Y-m-d 23:59:59', time())); if (isset($selectParams['start']) && !empty($selectParams['start'])){ $todayStart = $selectParams['start']; } if (isset($selectParams['end']) && !empty($selectParams['end'])){ $todayEnd = $selectParams['end']; } $sql = "SELECT SUM(order_view.returnTotalPrice) as returnTotalPrice,order_view.goodsId,order_view.outCostPrice,SUM(order_view.totalMoney) as totalMoney,order_view.specGroup,order_view.unitName,order_view.skuId,order_view.title,SUM(order_view.num) as rnum,SUM(order_view.o_num) as onum ,SUM(order_view.otherNum) AS otherNum, order_view.goodsBasicId FROM ( SELECT g.goodsId,g.specGroup,g.unitName,g.goodsName as title,g.skuId,@c:=0 as num,@a:=1 as isOrder,g.buyNum as o_num,g.totalMoney,(g.outCostPrice * g.buyNum) as outCostPrice,@d:=0 as returnTotalPrice ,JSON_EXTRACT(g.extends,'$.u_1_buy') AS otherNum,g.goodsBasicId AS goodsBasicId FROM qianniao_order_".$this->onlineEnterpriseId.'_1 as o LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id WHERE o.outStatus in(5,6) AND g.deleteStatus = 5 AND o.createTime BETWEEN '.$todayStart.' AND '.$todayEnd.' UNION ALL SELECT d.goodsId,d.skuName as specGroup,d.unitName,d.goodsName as title,d.skuId,d.num as num,@a:=2 as isOrder,@b:=0 as o_num,@c:= 0 as totalMoney,@d:= 0 as outCostPrice,d.returnTotalPrice, @g:= 0 as otherNum ,@g:= 0 as goodsBasicId FROM qianniao_order_return_'.$this->onlineEnterpriseId.' as r LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' as d ON d.linkId=r.id WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' ) AS order_view GROUP BY skuId'; $countSql = 'SELECT order_view.id as id FROM ( SELECT o.id,g.skuId FROM qianniao_order_'.$this->onlineEnterpriseId.'_1 as o LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id WHERE o.outStatus in(5,6) AND g.deleteStatus = 5 AND o.createTime BETWEEN '.$todayStart.' AND '.$todayEnd.' UNION ALL SELECT r.id,d.skuId FROM qianniao_order_return_'.$this->onlineEnterpriseId.' as r LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' as d ON d.linkId=r.id WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' ) AS order_view GROUP BY skuId'; $sql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit']; $lists = $this->objDOrderIndex->query($sql); if ($lists === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } $goodsBasicDate = []; //获取商品资料 $goodsBasicIds = array_column($lists,'goodsBasicId'); $objGoodsDate = new MGoodsBasic($this->onlineUserId,$this->onlineEnterpriseId); $result = $objGoodsDate->getBasicGoodsFieldByIds($goodsBasicIds); if ( !$result->isSuccess() ){ return ResultWrapper::fail($result->getData(),$result->getErrorCode()); } $goodsBasicDate = $result->getData(); $skuIds = []; foreach ($lists as &$list){ $list['isEq'] = isset($goodsBasicDate[$list['goodsBasicId']]['isEq']) ? $goodsBasicDate[$list['goodsBasicId']]['isEq'] : 4; $list['specGroup'] = json_decode($list['specGroup'],true); if (is_array($list['specGroup'])){ $arr = array_column($list['specGroup'],'specValueName'); $str = implode('_',$arr); $list['specGroup'] = $str; } $list['subProMoney'] = floatval(bcsub($list['totalMoney'],$list['outCostPrice'],2));//毛利 $skuIds[] = $list['skuId']; } unset($list); $thisRetMap = [];//本期 $lastRetMap = [];//上期 if (!empty($skuIds)){ $str = implode(',',$skuIds); //本期退货数量 $fields = ' SUM(d.num) as thisRetNum,d.skuId as skuId,SUM(d.returnTotalPrice) as thisReturnTotalPrice '; $sql = 'SELECT '.$fields.' FROM qianniao_order_' . $this->onlineEnterpriseId . '_1 AS o LEFT JOIN qianniao_order_return_'.$this->onlineEnterpriseId.' AS r ON r.originId = o.id LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' AS d ON d.linkId = r.id WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND o.createTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND d.skuId IN('.$str.') GROUP BY d.skuId'; $retLists = $this->objDOrderIndex->query($sql); if ($retLists === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } unset($sql); //上期退货 $fields = ' SUM(d.num) as lastRetNum,d.skuId as skuId,SUM(d.returnTotalPrice) as lastReturnTotalPrice '; $sql = 'SELECT '.$fields.' FROM qianniao_order_' . $this->onlineEnterpriseId . '_1 AS o LEFT JOIN qianniao_order_return_'.$this->onlineEnterpriseId.' AS r ON r.originId = o.id LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' AS d ON d.linkId = r.id WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND o.createTime < '.$todayStart.' AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND d.skuId IN('.$str.') GROUP BY d.skuId'; $lastRetLists = $this->objDOrderIndex->query($sql); if ($lastRetLists === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } unset($sql); foreach ($retLists as $val){ $thisRetMap[$val['skuId']] = [ 'thisRetNum' => $val['thisRetNum'], 'thisReturnTotalPrice' => $val['thisReturnTotalPrice'], ]; } foreach ($lastRetLists as $val){ $lastRetMap[$val['skuId']] = [ 'lastRetNum' => $val['lastRetNum'], 'lastReturnTotalPrice' => $val['lastReturnTotalPrice'] ]; } } foreach ($lists as &$item){ if (!isset($thisRetMap[$item['skuId']])){ $item['thisRetNum'] = 0; $item['thisReturnTotalPrice'] = 0; }else{ $item['thisRetNum'] = floatval($thisRetMap[$item['skuId']]['thisRetNum']); $item['thisReturnTotalPrice'] = floatval($thisRetMap[$item['skuId']]['thisReturnTotalPrice']); } if (!isset($lastRetMap[$item['skuId']])){ $item['lastRetNum'] = 0; $item['lastReturnTotalPrice'] = 0; }else{ $item['lastRetNum'] = floatval($lastRetMap[$item['skuId']]['lastRetNum']); $item['lastReturnTotalPrice'] = floatval($lastRetMap[$item['skuId']]['lastReturnTotalPrice']); } $item['retNum'] = bcadd($item['thisRetNum'],$item['lastRetNum'],2); $item['returnTotalPrice'] = bcadd($item['thisReturnTotalPrice'],$item['lastReturnTotalPrice'],2); } unset($item); $count = $this->objDOrderIndex->query($countSql); if ($count === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } $data = [ 'total' => count($count), 'data' => $lists ]; return ResultWrapper::success($data); } /** * Doc: (des="") * User: XMing * Date: 2021/3/10 * Time: 11:05 上午 * @param array $params * @return ResultWrapper * @throws \Exception */ public function getGoodsListsByUserCenterId(array $params): ResultWrapper { $fix = 1; if (isset($params['userCenterId']) && !empty($params['userCenterId'])){ $fix = ceil($params['userCenterId'] / $this->cutTable); } $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); $fields = ' id,customerName,customerId '; $where = ''; if (isset($params['startTime']) && !empty($params['startTime']) && isset($params['endTime']) && !empty($params['endTime'])){ $where .= ' AND `createTime` BETWEEN '.$params['startTime'].' AND '.$params['endTime']; } $sql = 'SELECT '.$fields.' FROM qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix.' WHERE deleteStatus = '.StatusCode::$standard.$where; if (isset($params['userCenterId']) && !empty($params['userCenterId'])){ $sql .= ' AND userCenterId = '.$params['userCenterId']; } $sql .= ' order by createTime desc'; $lists = $this->objDOrder->query($sql); if ($lists === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } if (empty($lists)){ return ResultWrapper::success(['data' => [],'total' => 0]); } unset($sql); unset($where); unset($fields); $orderIds = []; $orderRelMap = []; foreach ($lists as $item){ $orderIds[] = $item['id']; $orderRelMap[$item['id']] = $item; } $fields = ' goodsBasicId,createTime,orderId,goodsName,goodsCode,goodsImages,unitName,specGroup,shopId,shopName,price,SUM(buyNum) AS buyNum,(price * SUM(buyNum)) AS totalMoney,categoryName,brandName,barCode,outNum ,SUM(JSON_EXTRACT(extends,"$.u_1_buy")) AS otherNum '; $where = ''; if (!empty($orderIds)){ $str = trim(implode(',',$orderIds),','); $where .= ' AND `orderId` IN ('.$str.')'; } if (isset($params['categoryId']) && !empty($params['categoryId'])){ $categoryId = (int)$params['categoryId']; $where .= ' AND FIND_IN_SET('.$categoryId.',`categoryPath`) '; } if (isset($params['brandId']) && !empty($params['brandId'])){ $brandId = (int)$params['brandId']; $where .= ' AND `brandId` = '.$brandId; } if (isset($params['barCode']) && !empty($params['barCode'])){ $barCode = (string)$params['barCode']; $where .= ' AND `barCode` = "'.$barCode.'"'; } if (isset($params['shopId']) && !empty($params['shopId'])){ $shopId = (int)$params['shopId']; $where .= ' AND `shopId` = '.$shopId; } if (isset($params['keyword']) && !empty($params['keyword'])){ $keyword = '"%'.$params['keyword'].'%"'; $where .= ' AND (`goodsName` LIKE '.$keyword.' OR `goodsCode` LIKE '.$keyword.') '; } $sql = 'SELECT '.$fields.' FROM qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix.' WHERE `deleteStatus` = '.StatusCode::$standard.$where.' GROUP BY skuId ORDER BY createTime DESC '; $count = $this->objDOrderGoods->query($sql); if ($count === false){ return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } if (isset($params['limit']) && !empty($params['limit'])){ $sql .= ' LIMIT '.$params['offset'].','.$params['limit']; } $lists = $this->objDOrderGoods->query($sql); if ($lists === false){ return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } if (empty($lists)){ return ResultWrapper::success(['data'=>[],'total'=>0]); } if ($lists === false){ return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } $goodsBasicDate = []; //获取商品资料 $goodsBasicIds = array_column($lists,'goodsBasicId'); $objGoodsDate = new MGoodsBasic($this->onlineUserId,$this->onlineEnterpriseId); $result = $objGoodsDate->getBasicGoodsFieldByIds($goodsBasicIds); if ( !$result->isSuccess() ){ return ResultWrapper::fail($result->getData(),$result->getErrorCode()); } $goodsBasicDate = $result->getData(); foreach ($lists as &$item){ if (isset($item['specGroup']) && !empty($item['specGroup'])){ $item['specGroup'] = json_decode($item['specGroup'],true); } $item['customerName'] = isset($orderRelMap[$item['orderId']]) ? $orderRelMap[$item['orderId']]['customerName'] : ''; $item['customerId'] = isset($orderRelMap[$item['orderId']]) ? $orderRelMap[$item['orderId']]['customerId'] : 0; $item['isEq'] = isset($goodsBasicDate[$item['goodsBasicId']]['isEq']) ? $goodsBasicDate[$item['goodsBasicId']]['isEq'] : 4; } return ResultWrapper::success([ 'data' => $lists, 'total' => (int)count($count) ]); } /** * Doc: (des="缺货单列表") * User: XMing * Date: 2021/3/11 * Time: 6:44 下午 * @param array $selectParams * @return ResultWrapper * @throws \Exception */ public function getDistributionAll(array $selectParams): ResultWrapper { //{"page":1,"pageSize":10,"search":{},"state":"all"} $selectParams['state'] = 'state'; $selectParams['outStatus'] = 6; $orderListsResult = self::getAllOrder($selectParams,[]); if (!$orderListsResult->isSuccess()){ return ResultWrapper::fail($orderListsResult->getData(),$orderListsResult->getErrorCode()); } $total = $orderListsResult->getData()['total']; $orderLists = $orderListsResult->getData()['data']; if (empty($orderLists)){ return ResultWrapper::success(['data' => [],'total' => 0]); } $arrayLists = []; $orderIds = []; foreach ($orderLists as $item){ $infoResult = self::getOrderInfoById($item['id']); if (!$infoResult->isSuccess()){ return ResultWrapper::fail($infoResult->getData(),$infoResult->getErrorCode()); } $infoResult = $infoResult->getData(); $goodsData = $infoResult['goodsData']; foreach ($goodsData as $key => $item){ if ($item['outOfNum'] == 0){ unset($goodsData[$key]); continue; } $infoResult['goodsData'] = array_values($goodsData); } $arrayLists[] = $infoResult; } return ResultWrapper::success(['data' => $arrayLists,'total' => $total]); } /** * Doc: (des="业务员销售排行") * User: XMing * Date: 2021/3/15 * Time: 10:09 上午 * @param array $params * @param $export * @return ResultWrapper */ public function salesManRank(array $params,$export = 0): ResultWrapper { $sortFields = ['dealCustomerNum','orderNum','dealAmount','skuNum','buyNum']; $sort = ['ASC','DESC']; if (!in_array($params['sortField'],$sortFields)){ return ResultWrapper::fail('sortField字段异常',ErrorCode::$paramError); } if (!in_array($params['sort'],$sort)){ return ResultWrapper::fail('sort字段异常',ErrorCode::$paramError); } $where = ''; $fields = ' o.salesManName,o.salesManId,COUNT(DISTINCT o.id) as orderNum,COUNT(DISTINCT o.customerId) as dealCustomerNum,SUM(DISTINCT o.payAmount) as dealAmount,COUNT(DISTINCT g.skuId) as skuNum,SUM(g.buyNum) as buyNum '; if (isset($params['startTime']) && !empty($params['startTime']) && isset($params['endTime']) && !empty($params['endTime'])){ $where .= ' AND o.createTime BETWEEN '.$params['startTime'].' AND '.$params['endTime']; } if ( !empty($params['orderStatus'])&& isset($params['orderStatus']) ){//删选 $orderStatus = implode(',',$params['orderStatus']); $where .= ' AND o.orderStatus IN ('.$orderStatus.')'; } $sql = 'SELECT '.$fields.' FROM qianniao_order_'.$this->onlineEnterpriseId.'_1 as o LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id WHERE o.deleteStatus = 5 AND o.salesManId IS NOT NULL AND o.salesManId != 0 '.$where; $sql .= ' GROUP BY o.salesManName '; if (isset($params['sortField']) && !empty($params['sortField']) && isset($params['sort']) && !empty($params['sort'])){ $sql .= ' ORDER BY '.$params['sortField'].' '.$params['sort']; } $count = $this->objDOrder->query($sql); if ($count === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } if (count((array)$count) == 0){ return ResultWrapper::success(['data' => [],'total' => 0]); } if($export){ $params['limit'] = null; $params['offset'] = null; } if (isset($params['limit']) && !empty($params['limit'])){ $sql .= ' LIMIT '.$params['offset'].','.$params['limit']; } //导出 if($export){ $lists = $this->objDOrder->query($sql); if ($lists === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } self::exportsalesManRank($lists); exit; }else{ $lists = $this->objDOrder->query($sql); if ($lists === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } foreach ($lists as &$list){ $list['dealAmount'] = sprintf('%.2f', $list['dealAmount']); } } return ResultWrapper::success(['data' => $lists,'total' => count($count)]); } /** * Doc: (des="") * User: XMing * Date: 2021/3/17 * Time: 10:47 上午 * @param array $orderIds * @param array $params * @return ResultWrapper * @throws \Exception */ public function updateCostPriceBySku(array $orderIds,array $params): ResultWrapper { Logger::logs(E_USER_ERROR,'params',__CLASS__,__LINE__,$params); Logger::logs(E_USER_ERROR,'orderIds',__CLASS__,__LINE__,$orderIds); if (empty($orderIds)){ return ResultWrapper::success(); } $lists = $this->objDOrderIndex->select($orderIds,'id,userCenterId'); if ($lists === false){ return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } $tables = []; foreach ($lists as $list){ $fix = ceil($list['userCenterId'] / $this->cutTable); $tables[$fix][] = $list['id']; } if (empty($tables)){ return ResultWrapper::success('没有更新的表'); } $status = $this->objDOrderGoods->beginTransaction(); foreach ($params as $value){ $where = $value['where']; $update = $value['update']; foreach ($tables as $fix => $orderIds){ $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix); Logger::logs(E_USER_ERROR,'update',__CLASS__,__LINE__,$update); Logger::logs(E_USER_ERROR,'where',__CLASS__,__LINE__,$where); $updateResult = $this->objDOrderGoods->update($update,$where); if ($updateResult === false){ $this->objDOrderGoods->rollBack(); return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror); } } } $status && $this->objDOrderGoods->commit(); return ResultWrapper::success(true); } /* * 设置物流信息 * */ public function addLogistics($params) { $logisticsData = $params['logisticsData']; if(empty($logisticsData['id'])){ $objMDriver = new MDriver($this->onlineEnterpriseId, $this->onlineUserId); $paramsDriver = [ 'enterpriseId'=> $this->onlineEnterpriseId, 'driverName' => $logisticsData['name'], 'phone' => $logisticsData['truckTel'], 'plateNumber' => $logisticsData['truckName'], 'remark' => $logisticsData['remark'] ]; $addDriver = $objMDriver->addDriver($paramsDriver); if ( !$addDriver->isSuccess() ){ return ResultWrapper::fail($addDriver->getData(),$addDriver->getErrorCode()); } $driverId = $addDriver->getData(); $params['logisticsData']['id']= $driverId; } //去掉订单id剩下的数据就是物流数据 $orderId = $params['orderId']; unset($params['orderId']); $orderNo = $params['no']; unset($params['no']); $updateLogistics = self::editOrderExpress($orderNo,$params,$orderId); if (!$updateLogistics->isSuccess()){ $this->objDOrder->rollBack(); return ResultWrapper::fail($updateLogistics->getData(),$updateLogistics->getErrorCode()); } return ResultWrapper::success($updateLogistics); } /** * 业务员订单表导出方法 * @param $result * @return void * @throws Exception */ public function exportsalesManRank($result) { //导出到本地 header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=业务员订单记录表.csv"); header('Cache-Control: max-age=0'); $fp = fopen('php://output', 'a'); $head = ['销售员','成交客户','sku数量','订单数','销售数量','成交金额']; //定义标题 foreach ($head as $i => $v) { $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码 } fputcsv($fp, $head); $limit = 10000; $num = 0; //计数器 foreach ($result as $v) { //循环数据 $num++; if ($num == $limit) { ob_flush(); //释放内存 flush(); } $rows['salesManName'] = isset($v['salesManName']) ? $v['salesManName'] : '';//销售员 $rows['dealCustomerNum'] = isset($v['dealCustomerNum']) ? $v['dealCustomerNum'] : '';//成交客户 $rows['skuNum'] = isset($v['skuNum']) ? $v['skuNum'] : '';//SKU数量 $rows['orderNum'] = isset($v['orderNum']) ? $v['orderNum'] : '';//订单数 $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//销售数量 $rows['dealAmount'] = isset($v['dealAmount']) ? $v['dealAmount'] : '';//成交金额 foreach ($rows as $kk => $vv) { $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码 } fputcsv($fp, $rs); $rows = []; } } /** * 导出方法 * * @param $orderProfit */ private static function exportOrderProfit($orderProfit) { //导出到本地 header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=销售毛利明细表记录.csv"); header('Cache-Control: max-age=0'); $fp = fopen('php://output', 'a'); $head = ['商品名','单据类型', '单据日期', '客户名', '数量','其他单位','销售价', '成本价', '销售收入','销售成本', '销售毛利', '销售毛利率']; //定义标题 foreach ($head as $i => $v) { $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码 } fputcsv($fp, $head); $limit = 10000; $num = 0;//计数器 foreach ($orderProfit as $v) { //循环数据 $num++; if ($num == $limit) { ob_flush();//释放内存 flush(); } $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : '';//商品名 $rows['orderType'] = $v['orderType'] === 1 ? '销售订单' : '销售单';//单据类型 $rows['createTime'] = isset($v['createTime']) ? date('Y-m-d H:i:s',$v['createTime']) : '';//单据日期 $rows['customerName'] = isset($v['customerName']) ? $v['customerName'] : '';//客户名 $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//数量 $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : 0;//其他单位 $rows['price'] = isset($v['price']) ? $v['price'] : '';//销售价 $rows['outCostPrice'] = isset($v['outCostPrice']) ? $v['outCostPrice'] : '';//成本价 $rows['totalMoney'] = isset($v['totalMoney']) ? $v['totalMoney'] : '';//销售收入 $rows['saleCostAmount'] = isset($v['saleCostAmount']) ? $v['saleCostAmount'] : '';//销售成本 $rows['saleProfitAmount'] = isset($v['saleProfitAmount']) ? $v['saleProfitAmount'] : '';//销售毛利 $rows['saleProfitRate'] = isset($v['saleProfitRate']) ? $v['saleProfitRate'].'%' : '';//销售毛利率 foreach ($rows as $kk => $vv) { $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码 } fputcsv($fp, $rs); $rows = []; } exit; } /** * 拣货回写订单拣货状态 */ public function updateOrderPicking($orderIds,$orderPickStatus) { $tableName = $this->objDOrder->getTableName('qianniao_order_' . $this->onlineEnterpriseId, $this->onlineUserId, $this->cutTable); $this->objDOrder->setTable($tableName); if(!empty($orderIds)){ foreach ($orderIds as $orderId){ $dbResult = $this->objDOrder->update(['pickingStatus'=>$orderPickStatus],['id'=>$orderId]); if ($dbResult === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } } } return ResultWrapper::success([]); } /** * *用户订单状态数量统计 */ public function getOrderStatusNum() { // 2待支付 3代发货 4待收货 5已完成 10退货 $returnData = [ '2' => 0, '3' => 0, '4' => 0, '5' => 0, '10' => 0 ]; // 查询订单各状态对应的总条数 $sql = 'SELECT count(orderStatus) as total,orderStatus FROM qianniao_order_index_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard.' AND userCenterId = '.$this->onlineUserId.' GROUP BY orderStatus'; $dbResult = $this->objDOrderIndex->query($sql); if($dbResult === false){ return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (!empty($dbResult)){ foreach ($dbResult as $key => $value){ $returnData[$value['orderStatus']] = $value['total']; } } // 查询退货状态总条数 unset($dbResult); $sql = 'SELECT count(id) as total FROM qianniao_order_return_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard.' AND userCenterId = '.$this->onlineUserId; $dbResult = $this->objDOrderIndex->query($sql); if($dbResult === false){ return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (!empty($dbResult)){ $returnData[10] = $dbResult[0]['total']; } return ResultWrapper::success($returnData); } }