123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893 |
- <?php
- /**
- * 采购数据模型
- * Created by PhpStorm.
- * User: XiaoMing
- * Date: 2019/11/11
- * Time: 17:49
- */
- namespace JinDouYun\Model\Purchase;
- use Exception;
- use JinDouYun\Cache\Stock;
- use JinDouYun\Controller\Common\Logger;
- use JinDouYun\Dao\Order\DOrder;
- use JinDouYun\Dao\Order\DOrderGoods;
- use JinDouYun\Dao\Stock\DInventoryWarehouse;
- use JinDouYun\Model\Order\MOrder;
- use Mall\Framework\Core\ErrorCode;
- use Mall\Framework\Core\ResultWrapper;
- use Mall\Framework\Core\StatusCode;
- use JinDouYun\Model\Stock\MInventoryIn;
- use JinDouYun\Model\GoodsManage\MSku;
- use JinDouYun\Model\GoodsManage\MGoodsBasic;
- use JinDouYun\Model\MBaseModel;
- use JinDouYun\Model\Stock\MInventory;
- use JinDouYun\Model\Shop\MShop;
- use JinDouYun\Model\Merchant\MMerchant;
- use JinDouYun\Model\Stock\MWarehouse;
- use JinDouYun\Model\System\MPrintNum;
- use JinDouYun\Model\Finance\MRefund;
- use JinDouYun\Dao\Purchase\DPurchase;
- use JinDouYun\Dao\Purchase\DPurchaseGoods;
- use JinDouYun\Dao\Stock\DInventory;
- use JinDouYun\Dao\Shop\DShop;
- use Mall\Framework\Factory;
- use const Grpc\STATUS_ABORTED;
- //use Util\Common\AgentTools;
- class MPurchase extends MBaseModel
- {
- private $objDPurchase;
- private $onlineUserId;
- private $onlineEnterpriseId;
- private $objPurchaseGoods;
- private $objDPurchaseGoods;
- private $objDInventory;
- private $objStock;
- private $cutTable = 200000;
-
-
- private $objDShop;
-
- /**
- * MOrder constructor.
- * @param $onlineUserId
- * @param $onlineEnterpriseId
- * @throws Exception
- */
- public function __construct($onlineUserId, $onlineEnterpriseId)
- {
- $this->onlineUserId = $onlineUserId;
- $this->onlineEnterpriseId = $onlineEnterpriseId;
- parent::__construct($this->onlineEnterpriseId, $this->onlineUserId);
- $this->objDPurchase = new DPurchase('stock');
- $this->objDPurchaseGoods = new DPurchaseGoods('stock');
- $this->objPurchaseGoods = new MPurchaseGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $this->objDInventory = new DInventory('stock');
- $this->objDInventory->setTable('qianniao_inventory_' . $this->onlineEnterpriseId);
- $this->objDPurchase->setTable($this->objDPurchase->get_Table() . '_' . $this->onlineEnterpriseId);
- $this->objDPurchaseGoods->setTable($this->objDPurchaseGoods->get_Table() . '_' . $this->onlineEnterpriseId);
- $this->objDPurchaseGoods->setSearchIndex('purchase_details_search')->setType('purchase_details');
- $this->objStock = new Stock($this->onlineEnterpriseId);
-
- $this->objDShop = new DShop();
- $this->objDShop->setTable('qianniao_shop_1');
-
- }
- /**
- * 增加采购订单
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function addPurchase($params)
- {
- if(isset($params['departmentPath'])){
- $params['extends'] = json_encode(['departmentPath' => (string)$params['departmentPath']]);
- unset($params['departmentPath']);
- }
- $beginStatus = $this->objDPurchase->beginTransaction();
- $goodData = $params['goodsData'];
- unset($params['deleteArray']);
- unset($params['goodsData']);
- $purchaseAmount = 0; //采购总额
- $goodsNum = 0; // 统计采购订单总商品数
- foreach ($goodData as $key => $val) {
- $goodsNum = bcadd($val['buyerNum'], $goodsNum, 2);
- $purchaseAmount = bcadd($purchaseAmount, $val['subtotalPrice'], 4);
- }
- $params['purchaseAmount'] = $purchaseAmount;
- $params['goodsNum'] = $goodsNum;
- $params['createTime'] = time();
- $params['updateTime'] = time();
- //添加采购订单
- //no编号
- $dbResult = $this->objDPurchase->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- if(empty($dbResult)){
- $params['no'] = createSerialNumberByDate('');
- }else{
- $params['no'] = createSerialNumberByDate($dbResult['no']);
- }
- //查询仓库数据
- $objMWarehouse = new MWarehouse($this->onlineEnterpriseId);
- $modelResult = $objMWarehouse->getWarehouse(['id' => $params['warehouseId'], 'deleteStatus' => StatusCode::$standard]);
- if(!$modelResult->isSuccess()){
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $warehouseData = $modelResult->getData();
- unset($modelResult);
- if(empty($warehouseData)){
- return ResultWrapper::fail('仓库信息查询失败', ErrorCode::$paramError);
- }
- $params['warehouseId'] = $warehouseData['id'];
- $params['warehouseName'] = $warehouseData['warehouseName'];
- $params['inStatus'] = StatusCode::$delete;
- $params['returnStatus'] = StatusCode::$orderReturn['notReturn'];
- $params['auditStatus'] = StatusCode::$auditStatus['auditing'];
- $params['auditName'] = '';
- $params['auditId'] = 0;
- $params['auditTime'] = 0;
- $params['deleteStatus'] = StatusCode::$standard;
- $params['serialNum'] = $this->objStock->createSerialSn(0, 'purchase');
- $purchaseId = $this->objDPurchase->insert($params);
- if ($purchaseId === false) {
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $insert = [];
- foreach ($goodData as $details) {
- $insert[] = [
- 'basicGoodsId' => $details['basicGoodsId'],
- 'goodsCode' => $details['goodsCode'],
- 'goodsName' => $details['goodsName'],
- 'skuId' => $details['skuId'],
- 'buyerNum' => $details['buyerNum'],//采购数量
- 'inNum' => 0,//入库数量
- 'otherNum' => $details['otherNum'],
- 'inOfNum' => $details['buyerNum'],//待入库数量
- 'returnOnNum' => 0,//可退数量
- 'returnNum' => 0,//退货数量
- 'buyerUnitPrice' => $details['buyerUnitPrice'],
- 'subtotalPrice' => $details['subtotalPrice'],
- 'couponAmount' => getArrayItem($details, 'couponAmount', 0),
- 'otherAmount' => getArrayItem($details, 'otherAmount', 0),
- 'purchaseId' => $purchaseId,
- 'categoryId' => $details['categoryId'],
- 'categoryName' => $details['categoryName'],
- 'returnStatus' => StatusCode::$orderReturn['notReturn'],
- 'deleteStatus' => StatusCode::$standard,
- 'unitName' => isset($details['unitName']) ? $details['unitName'] : '',//单位名称
- 'skuName' => isset($details['skuName']) ? $details['skuName'] : ''
- ];
- }
- $dbResult = $this->objPurchaseGoods->addPurchaseGoods($insert);
- if (!$dbResult->isSuccess()) {
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- // 增加es数据
- /*
- $ids = $dbResult->getData();
- $modelResult = self::addEsData($insert, $params, $ids);
- if (!$modelResult->isSuccess()) {
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }*/
- $beginStatus && $this->objDPurchase->commit();
- return ResultWrapper::success($purchaseId);
- }
- /**
- * 采购订单详情
- * @param $id
- * @return ResultWrapper
- * @throws Exception
- */
- public function getPurchaseInfoById($id)
- {
- $dbResult = $this->objDPurchase->get($id);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) return ResultWrapper::success([]);
- $purchaseData = $dbResult;
- unset($dbResult);
- $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseData['id'], 'deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$paramError);
- }
- $purchaseData['details'] = $dbResult;
- $purchaseData['type'] = StatusCode::$orderType['purchaseOrder'];
- unset($dbResult);
- $purchaseData['details'] = parent::formatOrderMan($this->onlineEnterpriseId, $purchaseData['details']);
- $objMPrintNum = new MPrintNum($this->onlineEnterpriseId);
- $purchaseData['printNum'] = $objMPrintNum->getObjectPrintNum($purchaseData['no'], StatusCode::$orderType['purchaseIn']);
- return ResultWrapper::success($purchaseData);
- }
- /**
- * 采购订单详情和批次数据(采购退货专用)
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function getPurchaseAndBatchInfoById($params)
- {
- $id = $params['id'];
- $warehouseId = $params['warehouseId'];
- if(empty($warehouseId)){
- return ResultWrapper::fail('查询批次仓库id错误', ErrorCode::$paramError);
- }
- //查询采购数量
- $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $id, 'deleteStatus' => StatusCode::$standard, 'inStatus' => [5,6], 'returnStatus' => [0,1]]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
- }
- $detailsResult = $dbResult;
- unset($dbResult);
- //查询所有单位的主单位
- $skuIds = array_column($detailsResult, 'skuId');
- $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
- $modelResult = $objMSku->getConversion($skuIds);
- if(!$modelResult->isSuccess()){
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $skuResult = $modelResult->getData();
- unset($modelResult);
- foreach($detailsResult as &$value){
- $value['masterSkuId'] = $skuResult[$value['skuId']]['masterSkuId'];
- }
- unset($value);
- //库存剩余
- $sql = 'select * from qianniao_inventory_batch_'.$this->onlineEnterpriseId.'_'.$warehouseId.' where originId = '.$id;
- $dbResult = $this->objDPurchaseGoods->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $batchResult = $dbResult;
- unset($dbResult);
- $batchData = [];
- foreach($batchResult as $value){
- $batchData[$value['skuId']]['num'] += $value['num'];
- }
- //映射数量
- foreach($detailsResult as &$value){
- if(isset($batchData[$value['masterSkuId']])){
- $value['num'] = $batchData[$value['masterSkuId']]['num'];
- }
- }
- //转换数量
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMInventory->conversionMinorSku($detailsResult);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $details = $modelResult->getData();
- unset($modelResult);
- $returnData = parent::formatOrderMan($this->onlineEnterpriseId, $details);
- return ResultWrapper::success($returnData);
- }
- /**
- * 修改采购单 and ESData 库存审核入库用
- * 可公用
- * @param $updateData
- * @param $where
- * @return ResultWrapper
- * @throws Exception
- */
- public function updatePurchaseData($updateData, $where)
- {
- $updateData['updateTime'] = time();
- $updateDetailsData = $updateData['details'];
- unset($updateData['details']);
- //查询详情
- $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
- $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $where['id'], 'deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
- }
- $details = $dbResult;
- unset($dbResult);
- //修改采购单es 入库状态 入库数量
- $updateData['inStatus'] = 5;
- foreach ($details as $value) {
- if($updateDetailsData[$value['skuId']]){
- $inStatus = 5;
- if(bcsub($value['buyerNum'], bcadd($updateDetailsData[$value['skuId']]['inNum'], $value['inNum'])) > 0){
- $updateData['inStatus'] = 6;
- $inStatus = 6;
- }
- $updateDetails = [
- 'inNum' => bcadd($updateDetailsData[$value['skuId']]['inNum'], $value['inNum']),
- 'inOfNum' => bcsub($value['inOfNum'], $updateDetailsData[$value['skuId']]['inNum']),
- 'returnOnNum' => bcadd($updateDetailsData[$value['skuId']]['inNum'], $value['returnOnNum']),
- 'inStatus' => $inStatus,
- 'updateTime' => time(),
- ];
- $dbResult = $this->objDPurchaseGoods->update($updateDetails, ['id' => $value['id'], 'skuId' => $value['skuId']]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
- }
- // $esId = parent::setEsId($this->onlineEnterpriseId, 'PurchaseDetailsId', $value['id']);
- // $esResult = $this->objDPurchaseGoods->esupdateTypeFieldVaule($updateDetails, $esId);
- // if (!$esResult) {
- // return ResultWrapper::fail($esResult, ErrorCode::$dberror);
- // }
- }else{
- $updateData['inStatus'] = 6;
- }
- }
- $dbResult = $this->objDPurchase->update($updateData, $where);
- if ($dbResult === false) {
- ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $returnData = $dbResult;
- unset($dbResult);
- if($updateData['inStatus']==5){
- // $xxx=AgentTools::addTaskNew($where['id'], $this->onlineEnterpriseId);
- }
-
- return ResultWrapper::success($returnData);
- }
- /**
- * 修改采购单退货状态
- * @param $purchaseId
- * @param $detailsData
- * @return ResultWrapper
- * @throws Exception
- */
- public function updatePurchaseDetailsReturnStatus($purchaseId, $detailsData)
- {
- $updateData['updateTime'] = time();
- //默认全部退货
- $updateData['returnStatus'] = StatusCode::$orderReturn['allReturn'];
- //查询详情
- $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
- $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId, 'deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
- }
- $details = $dbResult;
- unset($dbResult);
- $beginStatus = $this->objDPurchaseGoods->beginTransaction();
- //修改采购单es 入库状态
- foreach ($details as $value) {
- if(isset($detailsData[$value['skuId']])){
- if($detailsData[$value['skuId']]['num'] > $value['returnOnNum']){
- $this->objDPurchaseGoods->rollBack();
- return ResultWrapper::fail('退货数量不能大于可退数量', ErrorCode::$paramError);
- }
- $returnStatus = 2;
- if(bcsub($value['returnOnNum'], $detailsData[$value['skuId']]['num']) > 0){
- //部分退货
- $updateData['returnStatus'] = StatusCode::$orderReturn['partReturn'];
- $returnStatus = 1;
- }
- $updateDetails = [
- 'updateTime' => time(),
- 'returnOnNum' => bcsub($value['returnOnNum'], $detailsData[$value['skuId']]['num']),//可退数量
- 'returnNum' => bcadd($detailsData[$value['skuId']]['num'], $value['returnNum']),//退货数量
- 'returnStatus' => $returnStatus
- ];
- //修改数据库
- $dbResult = $this->objDPurchaseGoods->update($updateDetails, ['id' => $value['id'], 'skuId' => $value['skuId']]);
- if($dbResult === false){
- $this->objDPurchaseGoods->rollBack();
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
- }
- //修改es
- /*
- $esId = parent::setEsId($this->onlineEnterpriseId, 'PurchaseDetailsId', $value['id']);
- $esResult = $this->objDPurchaseGoods->esupdateTypeFieldVaule($updateDetails, $esId);
- if (!$esResult) {
- $this->objDPurchaseGoods->rollBack();
- return ResultWrapper::fail($esResult, ErrorCode::$dberror);
- }*/
- }else{
- //部分退货
- $updateData['returnStatus'] = StatusCode::$orderReturn['partReturn'];
- }
- }
- //修改采购单
- $dbResult = $this->objDPurchase->update($updateData, ['id' => $purchaseId]);
- if ($dbResult === false) {
- $this->objDPurchaseGoods->rollBack();
- ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $returnData = $dbResult;
- unset($dbResult);
- $beginStatus && $this->objDPurchaseGoods->commit();
- return ResultWrapper::success($returnData);
- }
- /**
- * 编辑采购订单
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function editPurchase($params)
- {
- if (empty($params['id'])) {
- return ResultWrapper::fail('没有id', ErrorCode::$paramError);
- }
- $id = $params['id'];
- $deleteArray = $params['deleteArray'];
- unset($params['id']);
- unset($params['source']);
- unset($params['deleteArray']);
- $this->objDPurchase->beginTransaction();
- $goodData = $params['goodsData'];
- unset($params['goodsData']);
- $purchaseAmount = 0; //采购总额
- $goodsNum = 0; // 统计采购订单总商品数
- foreach ($goodData as $key => $val) {
- $goodsNum = bcadd($val['buyerNum'], $goodsNum, 2);
- $purchaseAmount = bcadd($purchaseAmount, $val['subtotalPrice'], 4);
- $goodData[$key]['inOfNum'] = $val['buyerNum'];
- }
- $params['purchaseAmount'] = $purchaseAmount;
- $params['goodsNum'] = $goodsNum;
- $dbResult = $this->objDPurchase->update($params, $id);
- if ($dbResult === false) {
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- unset($dbResult);
- $objPurchaseGoods = new MPurchaseGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $dbResult = $objPurchaseGoods->editPurchaseGoods($goodData, ['purchaseId' => $id, 'deleteArray' => $deleteArray]);
- if (!$dbResult->isSuccess()) {
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- $this->objDPurchase->commit();
- return ResultWrapper::success($dbResult);
- }
- /**
- * 更新审核状态
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function updateAuditStatus($params)
- {
- $id = $params['id'];
- unset($params['id']);
- $sql = "select *,p.id as pid,g.id as gid from " . $this->objDPurchase->get_Table() . " p left join qianniao_purchase_goods_" . $this->onlineEnterpriseId . " g on p.id = g.purchaseId where p.id = " . $id . " and p.deleteStatus = " . StatusCode::$standard . ' and g.deleteStatus = ' . StatusCode::$standard;
- $purchaseData = $this->objDPurchase->query($sql);
- if ($purchaseData === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- if (empty($purchaseData)) {
- return ResultWrapper::fail('审核的单据不存在', ErrorCode::$contentNotExists);
- }
- if ($purchaseData[0]['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
- return ResultWrapper::fail('当前单据已经审核通过', ErrorCode::$notAllowAccess);
- }
- $beginStatus = $this->objDPurchase->beginTransaction();
- $dbResult = $this->objDPurchase->update($params, $id);
- if ($dbResult === false) {
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- if($purchaseData[0]['purchaseType'] == StatusCode::$standard){
- $source = StatusCode::$orderType['merchantPurchase'];
- $type = StatusCode::$orderType['merchantPurchaseIn'];
- }else{
- $source = StatusCode::$orderType['purchaseOrder'];
- $type = StatusCode::$orderType['purchaseIn'];
- }
- $purchaseInData = [
- 'sourceId' => $purchaseData[0]['purchaseId'],//来源id
- 'sourceNo' => $purchaseData[0]['no'],//来源单号
- 'materielNum' => 0, //入库数量
- 'merchantId' => $purchaseData[0]['merchantId'],//商户id
- 'originId' => $purchaseData[0]['purchaseId'],//源头id
- 'originNo' => $purchaseData[0]['no'],//源头单号
- 'shopId' => $purchaseData[0]['shopId'],
- 'warehouseId' => $purchaseData[0]['warehouseId'],//仓库id
- 'warehouseName' => $purchaseData[0]['warehouseName'],//仓库名称
- 'operatorId' => $purchaseData[0]['operatorId'], //制单人id
- 'operatorName' => $purchaseData[0]['operatorName'], //制单人姓名
- 'source' => $source,
- 'type' => $type,
- 'orderGoodsData' => []
- ];
- $amount = 0;
- foreach ($purchaseData as $key => $value) {
- $purchaseInData['materielNum']++;
- $amount += $value['subtotalPrice'];
- $purchaseInData['orderGoodsData'][] = [
- 'materielId' => $value['basicGoodsId'],
- 'materielName' => $value['goodsName'],
- 'materielCode' => $value['goodsCode'],
- 'skuId' => $value['skuId'],
- 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
- 'skuName' => isset($value['skuName']) ? $value['skuName'] : '',
- 'num' => $value['buyerNum'],
- 'otherNum' => $value['otherNum'],
- 'unitPrice' => $value['buyerUnitPrice'],
- 'totalPrice' => $value['subtotalPrice'],
- ];
- //更新es审核
- /*
- $esId = parent::setEsId($this->onlineEnterpriseId, 'PurchaseDetailsId', $value['gid']);
- $esResult = $this->objDPurchaseGoods->esupdateTypeFieldVaule($params, $esId);
- if (!$esResult) {
- return ResultWrapper::fail($esResult, ErrorCode::$dberror);
- }*/
- }
- $purchaseInData['operatorId'] = $params['auditId'];
- $purchaseInData['operatorName'] = $params['auditName'];
- $purchaseInData['amount'] = $amount;
- $objMInventoryIn = new MInventoryIn($this->onlineEnterpriseId, $this->onlineUserId);
- $dbResult = $objMInventoryIn->addInventoryIn($purchaseInData);
- if (!$dbResult->isSuccess()) {
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- $beginStatus && $this->objDPurchase->commit();
- return ResultWrapper::success($dbResult->getData());
- }
- /**
- * 删除采购单
- * @param $id
- * @return ResultWrapper
- */
- public function delPurchase($id)
- {
- $dbResult = $this->objDPurchase->update(['deleteStatus' => StatusCode::$delete], $id);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- } else {
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 采购单列表
- * @param $selectParams
- * @param $export
- * @return ResultWrapper
- * @throws Exception
- */
- public function getAllPurchase($selectParams, $export)
- {
- $selectParams = parent::getStaffQueryParams($selectParams, 'buyerId');
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $isSelectInventory = isset($selectParams['isSelectInventory']) ? $selectParams['isSelectInventory'] : true;
- unset($selectParams['isSelectInventory']);
- $selectParams['deleteStatus'] = StatusCode::$standard;
- //查询商铺绑定仓库
- if(isset($selectParams['shopId']) && !empty($selectParams['shopId'])){
- $objMShop = new MShop($this->onlineEnterpriseId);
- $modelResult = $objMShop->getShopBindWarehouse($selectParams['shopId']);
- if(!$modelResult->isSuccess()){
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $shop = $modelResult->getData();
- unset($modelResult);
- if(empty($shop)){
- return ResultWrapper::fail('商铺查询失败', ErrorCode::$dberror);
- }
- $selectParams['warehouseId'] = $shop['warehouseId'];
- }
- if ($export) {
- $modelResult = self::export($selectParams);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- exit;
- }
- $dbResult = $this->objDPurchase->select($selectParams, '*', 'createTime desc', $limit, $offset);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $total = $this->objDPurchase->count($selectParams);
- $purchaseData = self::format($dbResult);
- $return = [
- 'data' => $purchaseData,
- 'total' => ($total) ? intval($total) : 0,
- ];
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- $objMInventory->updateCache = true;
- return ResultWrapper::success($return);
- }
- /**
- * 根据采购单查询批次商品sku剩余库存数量
- * @param $purchaseId
- * @return ResultWrapper
- */
- public function getInventoryBatchNum($purchaseId)
- {
- $dbResult = $this->objDPurchase->get(['id' => $purchaseId, 'deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error, ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::fail('采购单据查询失败', ErrorCode::$dberror);
- }
- $purchaseData = $dbResult;
- unset($dbResult);
- $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId, 'deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchaseGoods->error, ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::fail('采购单据详情查询失败', ErrorCode::$dberror);
- }
- $purchaseData['goodsData'] = $dbResult;
- unset($dbResult);
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- foreach ($purchaseData['goodsData'] as $value) {
- $skuIds[] = $value['skuId'];
- }
- $modelResult = $objMInventory->getBatchDataByOriginId($purchaseData['warehouseId'], $purchaseData['id'], $skuIds);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $batchData = $modelResult->getData();
- if (empty($batchData)) {
- return ResultWrapper::fail('批次数据查询失败', ErrorCode::$paramError);
- }
- // 采购订单有多个入库批次情况
- foreach ($batchData as $key => $value){
- $batchData[$value['skuId']]['num'] += $value['num'];
- }
- foreach ($purchaseData['goodsData'] as &$value) {
- $value['inventoryBatchNum'] = 0;
- if (isset($batchData[$value['skuId']])) {
- $value['inventoryBatchNum'] = $batchData[$value['skuId']]['num'];
- }
- }
- return ResultWrapper::success($purchaseData);
- }
- /**
- * 采购汇总
- * @param $selectParams
- * @param $type
- * @return ResultWrapper
- * @throws Exception
- */
- public function getAllPurchaseByFields($selectParams, $type ,$export = 0)
- {
- $defaultDbName = Factory::config()->get('db.default.dbname');
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $onReturn = $selectParams['onReturn'];
- unset($selectParams['onReturn']);
- if($export){
- $limit = 999;
- $offset = 0;
- }
- $groupBySql = '';
- if ($type == 1) {//商品
- $groupBySql = ' GROUP BY g.basicGoodsId';
- } elseif ($type == 2) {//供应商
- $groupBySql = ' GROUP BY p.supplierId,g.basicGoodsId';
- } elseif ($type == 3) {//采购人员
- $groupBySql = ' GROUP BY p.buyerId,g.basicGoodsId';
- } elseif($type == 4){
- $groupBySql = ' GROUP BY p.shopId,g.basicGoodsId';
- }else {
- return ResultWrapper::fail('type参数错误', ErrorCode::$paramError);
- }
- $whereSql = '';
- if (isset($selectParams['warehouseId']) && !empty($selectParams['warehouseId'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' p.warehouseId = ' . $selectParams['warehouseId'];
- }
- if (isset($selectParams['inStatus']) && !empty($selectParams['inStatus'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' p.inStatus = ' . $selectParams['inStatus'];
- }
- if (isset($selectParams['goodsName']) && !empty($selectParams['goodsName'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' g.goodsName LIKE "%' . $selectParams['goodsName'] . '%" ';
- }
- if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' g.categoryId = ' . $selectParams['categoryId'];
- }
- if (isset($selectParams['start']) && !empty($selectParams['start']) && isset($selectParams['end']) && !empty($selectParams['end'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' p.createTime BETWEEN ' . $selectParams['start'] . ' AND ' . $selectParams['end'];
- }
- if (isset($selectParams['supplierId']) && !empty($selectParams['supplierId'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' p.supplierId = ' . $selectParams['supplierId'];
- }
- if (isset($selectParams['buyerId']) && !empty($selectParams['buyerId'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' p.buyerId = ' . $selectParams['buyerId'];
- }
- if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' p.shopId = ' . $selectParams['shopId'];
- }
-
- //统计已审核 未删除主单据 未删除详情 的采购订单
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' p.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' AND p.deleteStatus = ' . StatusCode::$standard . ' AND g.deleteStatus = ' . StatusCode::$standard;
- $sql = 'SELECT p.warehouseId,p.warehouseName,p.id,p.`no`,p.buyerId,p.buyerName,p.supplierId,p.supplierName,p.operatorId,p.operatorName,p.inStatus,s.name as shopName,g.skuId,g.categoryId,g.categoryName,g.basicGoodsId AS materielId,g.goodsName AS materielName,g.goodsCode AS materielCode,SUM(g.buyerNum) AS allNum,SUM(g.subtotalPrice) AS total,(SUM(g.subtotalPrice) / SUM(g.buyerNum)) AS costPrice, SUM(g.otherNum) AS otherNum '
- . 'FROM ' . $this->objDPurchase->get_Table() . ' p '
- . 'LEFT JOIN `'.$defaultDbName.'`.'.$this->objDShop->get_Table().' s ON s.id = p.shopId '
- . 'LEFT JOIN ' . $this->objDPurchaseGoods->get_Table() . ' g ON p.id = g.purchaseId '
- . $whereSql . ' ' . $groupBySql . ' '
- . 'ORDER BY p.createTime DESC LIMIT ' . $offset . ' , ' . $limit;
- $dbResult = $this->objDPurchase->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $selectData = $dbResult;
- unset($dbResult);
- $totalSql = 'SELECT COUNT(id) AS total FROM (SELECT p.id FROM ' . $this->objDPurchase->get_Table() . ' p '
- . 'LEFT JOIN `'.$defaultDbName.'`.'.$this->objDShop->get_Table().' s ON s.id = p.shopId '
- . 'LEFT JOIN ' . $this->objDPurchaseGoods->get_Table() . ' g ON p.id = g.purchaseId ' . $whereSql . ' ' . $groupBySql . ') AS selectData';
- $dbResult = $this->objDPurchase->query($totalSql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $countData = array_shift($dbResult);
- unset($dbResult);
- //判断是否需要退货
- /*if ($onReturn) {
- //查询所有已退货的采购单 查询条件 已审核 未删除主单据 未删除详情 的采购退货单 关联 采购单
- $objMPurchaseOut = new MPurchaseOut($this->onlineUserId, $this->onlineEnterpriseId);
- $modelResult = $objMPurchaseOut->getReturnDataByShopIds([$selectParams['shopId']]);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $purchaseOutData = $modelResult->getData();
- foreach ($selectData as &$value) {
- if (isset($purchaseOutData[$value['materielId']])) {
- $value['allNum'] = bcsub($value['allNum'], $purchaseOutData[$value['materielId']]['num']);
- $value['total'] = bcmul($value['allNum'], $value['costPrice']);
- }
- }
- unset($value);
- }*/
- $return = [
- 'data' => parent::formatOrderMan($this->onlineEnterpriseId, $selectData),
- 'total' => ($countData['total']) ? intval($countData['total']) : 0,
- ];
- //导出
- if($export){
- self::exportPurchaseByFields($return['data']);
- exit;
- }
- return ResultWrapper::success($return);
- }
- /**
- * 汇总搜索 (暂未使用)
- * @param $params
- * @param $type
- * @param $export
- * @return ResultWrapper
- */
- public function searchAllPurchaseByFields($params, $type, $export)
- {
- $onReturn = $params['onReturn'];
- unset($params['onReturn']);
- $defaultDSL = ['from' => $params['offset'], 'size' => $params['limit'], 'sort' => ['createTime' => ['order' => 'desc']]];
- $selectParams = [];
- $groupBySql = '';
- if ($type == 1) {//商品
- $groupBySql = ' GROUP BY g.basicGoodsId';
- } elseif ($type == 2) {//供应商
- $groupBySql = ' GROUP BY p.supplierId,g.basicGoodsId';
- } elseif ($type == 3) {//采购人员
- $groupBySql = ' GROUP BY p.buyerId,g.basicGoodsId';
- } else {
- return ResultWrapper::fail('type参数错误', ErrorCode::$paramError);
- }
- $selectParams[] = ['term' => ['enterpriseId' => $this->onlineEnterpriseId]];
- !empty($params['categoryId']) && $selectParams[] = ['term' => ['categoryId' => $params['categoryId']]];
- !empty($params['shopId']) && $selectParams[] = ['term' => ['shopId' => $params['shopId']]];
- !empty($params['inStatus']) && $selectParams[] = ['term' => ['inStatus' => $params['inStatus']]];
- (!empty($params['start']) && !empty($params['end'])) && $selectParams[] = ['range' => ['createTime' => ['gte' => $params['start'], 'lte' => $params['end']]]];
- !empty($params['search']) && $selectParams[] = ['multi_match' => ['fields' => ['goodsName', 'goodsCode'], 'query' => $params['search'], 'fuzziness' => 'AUTO']];
- $dsl = [];
- !empty($selectParams) && $dsl['query']['bool']['must'][] = $selectParams;
- $dsl = array_merge($defaultDSL, $dsl);
-
- $dbResult = $this->objDPurchaseGoods->getSearchQueryDsl($dsl);
- if (isset($dbResult['error'])) {
- return ResultWrapper::fail($dbResult, ErrorCode::$dberror);
- }
- $returnData = parent::formatEsSelectData($dbResult, $this->onlineEnterpriseId, StatusCode::$orderType['purchaseOrder']);
- return ResultWrapper::success($returnData);
- }
- /**
- * 查询采购数据和详情数据
- * @param $selectParams
- * @return ResultWrapper
- * @throws Exception
- */
- public function getAllPurchaseAndDetails($selectParams)
- {
- $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $field = 'p.*,g.basicGoodsId,g.goodsName,g.goodsCode,g.skuId,g.buyerNum,g.buyerUnitPrice,g.subtotalPrice';
- $where = ' where p.deleteStatus = ' . StatusCode::$standard;
- isset($selectParams['orderStatus']) && $where .= ' and p.orderStatus = ' . $selectParams['orderStatus'];
- $orderBy = ' order by p.createTime desc ';
- $limitSql = ' limit ' . $offset . ',' . $limit;
- $sql = 'select ' . $field . ' from ' . $this->objDPurchase->get_Table() . ' p left join ' . $this->objDPurchaseGoods->get_Table() . ' g on p.id = g.purchaseId' . $where . $orderBy . $limitSql;
- $dbResult = $this->objDPurchase->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $field = 'count(g.id) as count';
- $sql = 'select ' . $field . ' from ' . $this->objDPurchase->get_Table() . ' p left join ' . $this->objDPurchaseGoods->get_Table() . ' g on p.id = g.purchaseId' . $where;
- $totalData = $this->objDPurchase->query($sql);
- if ($totalData === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $total = array_shift($totalData)['count'];
- $return = [
- 'data' => $dbResult,
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 采购明细页面数据统计
- *
- * @throws Exception
- */
- public function getAllData()
- {
- $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
- //供应商总数
- $objMSupplier = new MSupplier($this->onlineUserId, $this->onlineEnterpriseId);
- $modelResult = $objMSupplier->getAllSupplierNum();
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $data['supplierNum'] = $modelResult->getData();
- unset($modelResult);
- //采购订单总数
- $dbResult = $this->objDPurchase->count(['deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $data['purchaseNum'] = $dbResult;
- unset($dbResult);
- //采购总金额
- $sql = "select sum(purchaseAmount) amount from " . $this->objDPurchase->get_Table() . " where deleteStatus = " . StatusCode::$standard;
- $dbResult = $this->objDPurchase->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $data['purchaseAmount'] = array_shift($dbResult)['amount'];
- unset($dbResult);
- //商品种类数量(根据商品skuId)
- $sql = "SELECT count(1) as count FROM (SELECT skuId FROM " . $this->objDPurchaseGoods->get_Table() . " GROUP BY skuId) as skuData";
- $dbResult = $this->objDPurchaseGoods->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
- }
- $data['skuNum'] = array_shift($dbResult)['count'];
- unset($dbResult);
- //商品总数
- $sql = "select sum(buyerNum) as num from " . $this->objDPurchaseGoods->get_Table() . " where deleteStatus = " . StatusCode::$standard;
- $dbResult = $this->objDPurchaseGoods->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
- }
- $data['goodsNum'] = array_shift($dbResult)['num'];
- unset($dbResult);
- return ResultWrapper::success($data);
- }
- /**
- * 采购明细
- * @param $selectParams
- * @param $export
- * @return ResultWrapper
- * @throws Exception
- */
- public function getAllPurchaseDetails($selectParams, $export = 0)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
- $this->objDPurchase->setTable('qianniao_purchase' . '_' . $this->onlineEnterpriseId);
- $whereSql = '';
- if(!empty($selectParams['merchantId'])){
- $whereSql .= ' and p.merchantId = '.$selectParams['merchantId'];
- }
- if(!empty($selectParams['shopId'])){
- $whereSql .= ' and p.shopId = '.$selectParams['shopId'];
- }
- if(!empty($selectParams['categoryId'])){
- $whereSql .= ' and g.categoryId = '.$selectParams['categoryId'];
- }
- if(!empty($selectParams['supplierId'])){
- $whereSql .= ' and p.supplierId = '.$selectParams['supplierId'];
- }
- if(!empty($selectParams['auditStatus'])){
- $whereSql .= ' and p.auditStatus = '.$selectParams['auditStatus'];
- }
- if(!empty($selectParams['start']) && !empty($selectParams['end'])){
- $whereSql .= ' and p.createTime between '.$selectParams['start'].' and '.$selectParams['end'];
- }
- if(!empty($selectParams['search'])){
- $whereSql .= ' and g.goodsName like "%'.$selectParams['search'].'%" ';
- }
- $sql = "select p.merchantId,p.no,p.inStatus,p.supplierName,p.buyerName,p.remark,p.operatorName,g.id,g.goodsName,g.buyerNum,g.buyerUnitPrice,g.subtotalPrice,g.basicGoodsId,g.skuId,g.otherNum from " . $this->objDPurchase->get_Table() . " p LEFT JOIN " . $this->objDPurchaseGoods->get_Table() . " g on p.id = g.purchaseId where g.deleteStatus = " . StatusCode::$standard . $whereSql . " ORDER BY g.createTime desc ";
- if ($export) {
- $result = $this->objDPurchase->exportQuery($sql);
- if ($result === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $modelResult = self::formatPurchaseDetails($result);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $data = $modelResult->getData();
- self::exportPurchaseDetails($data);
- exit;
- }
- $sql .= " limit " . $offset . "," . $limit;
- $dbResult = $this->objDPurchase->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $sql = "select count(g.id) as count from " . $this->objDPurchase->get_Table() . " p LEFT JOIN " . $this->objDPurchaseGoods->get_Table() . " g on p.id = g.purchaseId where g.deleteStatus = " . StatusCode::$standard. $whereSql;
- $totalData = $this->objDPurchase->query($sql);
- if ($totalData === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $total = array_shift($totalData)['count'];
- $modelResult = self::formatPurchaseDetails($dbResult);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $data = $modelResult->getData();
- $return = [
- 'data' => $data,
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 采购明细搜索
- * @param $params
- * @param $export
- * @return ResultWrapper
- * @throws Exception
- */
- public function searchAllPurchaseDetails($params, $export)
- {
- $defaultDSL = ['from' => $params['offset'], 'size' => $params['limit'], 'sort' => ['createTime' => ['order' => 'desc']]];
- $selectParams = [];
- $selectParams[] = ['term' => ['enterpriseId' => $this->onlineEnterpriseId]];
- !empty($params['categoryId']) && $selectParams[] = ['term' => ['categoryId' => $params['categoryId']]];
- !empty($params['shopId']) && $selectParams[] = ['term' => ['shopId' => $params['shopId']]];
- !empty($params['supplierId']) && $selectParams[] = ['term' => ['supplierId' => $params['supplierId']]];
- !empty($params['auditStatus']) && $selectParams[] = ['term' => ['auditStatus' => $params['auditStatus']]];
- (!empty($params['start']) && !empty($params['end'])) && $selectParams[] = ['range' => ['createTime' => ['gte' => $params['start'], 'lte' => $params['end']]]];
- !empty($params['search']) && $selectParams[] = ['multi_match' => ['fields' => ['goodsName', 'goodsCode'], 'query' => $params['search'], "type" => "best_fields", "tie_breaker" => 0.3, "minimum_should_match" => "50%"]];
- $dsl = [];
- !empty($selectParams) && $dsl['query']['bool']['must'][] = $selectParams;
- $dsl = array_merge($defaultDSL, $dsl);
- //导出
- if ($export) {
- $esResult = $this->objDPurchaseGoods->getScrollSearchQueryDsl($dsl);
- if (isset($esResult['error'])) {
- return ResultWrapper::fail($esResult, ErrorCode::$dberror);
- }
- $formatData = parent::formatEsSelectData($esResult);
- $modelResult = self::formatPurchaseDetails($formatData['data']);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $formatData['data'] = $modelResult->getData();
- self::exportPurchaseDetails($formatData['data']);
- exit;
- }
- $dbResult = $this->objDPurchaseGoods->getSearchQueryDsl($dsl);
- if (isset($dbResult['error'])) {
- return ResultWrapper::fail($dbResult, ErrorCode::$dberror);
- }
- $formatData = parent::formatEsSelectData($dbResult);
- $modelResult = self::formatPurchaseDetails($formatData['data']);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $formatData['data'] = $modelResult->getData();
- return ResultWrapper::success($formatData);
- }
- /**
- * 采购明细导出方法
- * @param $result
- * @return void
- * @throws Exception
- */
- public function exportPurchaseDetails($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 = ['序号', '采购单号', '商品编号', '商品名称', '单位', '属性', '分类', '品牌', '采购数量','其他单位', '采购单价', '采购金额', '入库状态', '供应商']; //定义标题
- 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['id'] = isset($v['id']) ? $v['id'] : null;
- $rows['no'] = isset($v['no']) ? $v['no'] : null;
- $rows['goodsCode'] = isset($v['goodsCode']) ? $v['goodsCode'] : null;
- $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : null;
- $rows['unitName'] = isset($v['unitName']) ? $v['unitName'] : null;
- $rows['skuName'] = isset($v['skuName']) ? $v['skuName'] : null;
- $rows['categoryName'] = isset($v['categoryName']) ? $v['categoryName'] : null;
- $rows['brandName'] = isset($v['brandName']) ? $v['brandName'] : null;
- $rows['buyerNum'] = isset($v['buyerNum']) ? $v['buyerNum'] : null;
- $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : null;
- $rows['buyerUnitPrice'] = isset($v['buyerUnitPrice']) ? $v['buyerUnitPrice'] : null;
- $rows['subtotalPrice'] = isset($v['subtotalPrice']) ? $v['subtotalPrice'] : null;
- $rows['inStatus'] = isset($v['inStatus']) ? $v['inStatus'] == StatusCode::$standard ? '已入库' : '未入库' : null;
- $rows['supplierName'] = isset($v['supplierName']) ? $v['supplierName'] : null;
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- }
- /**
- * 导出方法
- * @param $condition
- * @return ResultWrapper
- * @throws Exception
- */
- public function export($condition)
- {
- $result = $this->objDPurchase->exportSelect($condition, 'id,no,supplierName,purchaseAmount,buyerName,operatorName,createTime,auditStatus');
- if ($result === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- $formatIds = [];
- $formatData = [];
- foreach ($result as $value) {
- $formatData[$value['id']] = $value;
- $formatIds[] = $value['id'];
- }
- $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
- $dbResult = $this->objDPurchaseGoods->exportSelect(['purchaseId' => $formatIds, 'deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$paramError);
- }
- //导出到本地
- 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 ($dbResult as $value) {//循环数据
- $num++;
- if ($num == $limit) {
- ob_flush();//释放内存
- flush();
- }
- $value = parent::formatOrderMan($this->onlineEnterpriseId, $value);
- $v = $formatData[$value['purchaseId']];
- $rows['id'] = isset($v['id']) ? $v['id'] : null;
- $rows['no'] = isset($v['no']) ? $v['no'] : null;
- $rows['supplierName'] = isset($v['supplierName']) ? $v['supplierName'] : null;
- $rows['purchaseAmount'] = isset($v['purchaseAmount']) ? $v['purchaseAmount'] : null;
- $rows['buyerName'] = isset($v['buyerName']) ? $v['buyerName'] : null;
- $rows['operatorName'] = isset($v['operatorName']) ? $v['operatorName'] : null;
- $rows['createTime'] = isset($v['createTime']) ? date('Y-m-d H:i:s', $v['createTime']) : null;
- $rows['auditStatus'] = isset($v['auditStatus']) ? ($v['auditStatus'] == StatusCode::$auditStatus['auditPass'] ? '已审核' : '未审核') : null;
- $rows['goodsName'] = isset($value['goodsName']) ? $value['goodsName'] : null;
- $rows['goodsCode'] = isset($value['goodsCode']) ? $value['goodsCode'] : null;
- $rows['unitName'] = isset($value['unitName']) ? $value['unitName'] : null;
- $rows['categoryName'] = isset($value['categoryName']) ? $value['categoryName'] : null;
- $rows['buyerNum'] = isset($value['buyerNum']) ? $value['buyerNum'] : null;
- $rows['otherNum'] = isset($value['otherNum']) ? $value['otherNum'] : null;
- $rows['buyerUnitPrice'] = isset($value['buyerUnitPrice']) ? $value['buyerUnitPrice'] : null;
- $rows['subtotalPrice'] = isset($value['subtotalPrice']) ? $value['subtotalPrice'] : null;
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- return ResultWrapper::success('成功');
- }
- /**
- * 格式化采购明细列表数据
- * @param $data
- * @return ResultWrapper
- * @throws Exception
- */
- public function formatPurchaseDetails($data)
- {
- if (empty($data)) return ResultWrapper::success($data);
- $skuIds = [];
- $nos = [];
- $basics = [];
- foreach ($data as $value) {
- $skuIds[] = $value['skuId'];
- $nos[] = $value['no'];
- $basics[] = $value['basicGoodsId'];
- }
- //单位name
- $skuNames = [];
- if ($skuIds) {
- $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
- $return = $objMSku->getNameByIds($skuIds);
- if (!$return->isSuccess()) {
- return ResultWrapper::fail($return->getData(), $return->getErrorCode());
- }
- $skuNames = $return->getData();
- unset($return);
- }
- //采购入库 入库状态
- $purchaseInData = [];
- if ($nos) {
- $objMInventoryIn = new MInventoryIn($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMInventoryIn->getAllInventoryInByNo($nos);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $purchaseInData = $modelResult->getData();
- unset($modelResult);
- }
- //分类信息
- $categoryData = [];
- $brandData = [];
- if ($basics) {
- $objMGoodsBasic = new MGoodsBasic($this->onlineUserId, $this->onlineEnterpriseId);
- $modelResult = $objMGoodsBasic->getCategoryByIds($basics);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $categoryData = $modelResult->getData();
- unset($modelResult);
- $modelResult = $objMGoodsBasic->getBrandByIds($basics);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $brandData = $modelResult->getData();
- unset($modelResult);
- }
- foreach ($data as $key => &$value) {
- $value['goodsCode'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $value['basicGoodsId'], StatusCode::$code['goodsBasic']['length']);
- $nos && $value['purchaseInStatus'] = isset($purchaseInData[$value['no']]) ? $purchaseInData[$value['no']]['auditStatus'] : StatusCode::$delete;
- $basics && $value['categoryName'] = isset($categoryData[$value['basicGoodsId']]) ? $categoryData[$value['basicGoodsId']]['title'] : null;
- $basics && $value['brandName'] = isset($brandData[$value['basicGoodsId']]) ? $brandData[$value['basicGoodsId']]['title'] : null;
- }
- $data = parent::formatOrderMan($this->onlineEnterpriseId, $data, StatusCode::$orderType['purchaseOrder']);
- return ResultWrapper::success($data);
- }
- /**
- * 格式化采购列表
- * @param $data
- * @return mixed
- * @throws Exception
- */
- private function format($data)
- {
- if (isset($data['id'])) {
- $dimension = $data;
- unset($data);
- $data[] = $dimension;
- }
- $allPurchaseIds = [];
- foreach ($data as $key => $val) {
- $allPurchaseIds[] = $val['id'];
- }
- $objMPurchaseGoods = new MPurchaseGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $dbResult = $objMPurchaseGoods->getGoodsByPurchaseIds($allPurchaseIds);
- if (!$dbResult->isSuccess()) {
- return $data;
- }
- $goodsData = $dbResult->getData();
- $allSkuIds = array_column($goodsData, 'skuId');
- //sku信息
- $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
- $selectParams = [
- 'id' => $allSkuIds,
- ];
- $skuData = [];
- $dbResult = $objMSku->getSkuInfo($selectParams, '*', false);
- if ($dbResult->isSuccess()) {
- $skuData = $dbResult->getData();
- }
- foreach ($skuData as $key => $value) {
- $allSkuData[$value['id']] = $value;
- }
- foreach ($goodsData as $key => &$value) {
- $value['unit'] = isset($allSkuData[$value['skuId']]) ? $allSkuData[$value['skuId']] : '';
- $allGoodsData[$value['purchaseId']][] = $value;
- }
- //查询商户
- $merchantIds = array_column($data,'merchantId');
- if(!empty($merchantIds)){
- $objMMerchant = new MMerchant($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMMerchant->selectMerchantData(['id' => $merchantIds]);
- $merchantData = [];
- if($modelResult->isSuccess()){
- $merchantResult = $modelResult->getData();
- foreach($merchantResult as $value){
- $merchantData[$value['id']] = $value;
- }
- }
- }
- foreach ($data as $key => &$value) {
- //渲染采购入库前缀
- $value['no'] = StatusCode::$noPrefix[2] .'-'. $value['no'];
- $value['goodsData'] = [];
- if (isset($allGoodsData[$value['id']])) {
- $value['goodsData'] = $allGoodsData[$value['id']];
- }
- $value['merchantName'] = isset($merchantData[$value['merchantId']]) ? $merchantData[$value['merchantId']]['name'] : '';
- }
- return $data;
- }
- /**
- * 根据nos数组查询多条采购订单数据
- * @param $nos
- * @return array|ResultWrapper
- */
- public function getAllPurchaseByNos($nos)
- {
- if (empty($nos)) return $nos;
- $dbResult = $this->objDPurchase->select(['no' => $nos]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) return ResultWrapper::fail('采购订单数据为空', ErrorCode::$paramError);
- $returnData = [];
- foreach ($dbResult as $value) {
- $returnData[$value['no']] = $value;
- }
- return ResultWrapper::success($returnData);
- }
- /**
- * 增加详情es数据
- * @param $data
- * @param $params
- * @param $ids
- * @return ResultWrapper
- */
- // public function addEsData($data, $params, $ids)
- // {
- // foreach ($data as $key => $value) {
- // $value['inStatus'] = StatusCode::$delete;
- // $modelResult = self::updateEsData($value, $params, $ids[$key]);
- // if (!$modelResult->isSuccess()) {
- // return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- // }
- // }
- // return ResultWrapper::success(true);
- // }
- /**
- * 添加详情es
- * @param $data
- * @param $params
- * @param $id
- * @return ResultWrapper
- */
- // public function updateEsData($data, $params, $id)
- // {
- // $addEsData = [
- // 'id' => $id,
- // 'enterpriseId' => $this->onlineEnterpriseId,
- // 'no' => isset($params['no']) ? $params['no'] : false,
- // 'supplierId' => isset($params['supplierId']) ? $params['supplierId'] : false,
- // 'supplierName' => isset($params['supplierName']) ? $params['supplierName'] : false,
- // 'buyerId' => isset($params['buyerId']) ? $params['buyerId'] : false,
- // 'buyerName' => isset($params['buyerName']) ? $params['buyerName'] : false,
- // 'remark' => isset($params['remark']) ? $params['remark'] : false,
- // 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : false,
- // 'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : false,
- // 'returnStatus' => isset($params['returnStatus']) ? $params['returnStatus'] : false,
- // 'inStatus' => isset($params['inStatus']) ? $params['inStatus'] : false,
- // 'auditId' => isset($params['auditId']) ? $params['auditId'] : false,
- // 'auditName' => isset($params['auditName']) ? $params['auditName'] : false,
- // 'auditStatus' => isset($params['auditStatus']) ? $params['auditStatus'] : false,
- // 'auditTime' => isset($params['auditTime']) ? $params['auditTime'] : false,
- // 'deleteStatus' => isset($params['deleteStatus']) ? $params['deleteStatus'] : false,
- // 'createTime' => isset($params['createTime']) ? $params['createTime'] : false,
- // 'updateTime' => isset($params['updateTime']) ? $params['updateTime'] : false,
- //
- // 'basicGoodsId' => isset($data['basicGoodsId']) ? $data['basicGoodsId'] : false,
- // 'goodsName' => isset($data['goodsName']) ? $data['goodsName'] : false,
- // 'goodsCode' => isset($data['goodsCode']) ? $data['goodsCode'] : false,
- // 'skuId' => isset($data['skuId']) ? $data['skuId'] : false,
- // 'unitName' => isset($data['unitName']) ? $data['unitName'] : false,
- // 'skuName' => isset($data['skuName']) ? $data['skuName'] : false,
- // 'categoryId' => isset($data['categoryId']) ? $data['categoryId'] : false,
- // 'categoryName' => isset($data['categoryName']) ? $data['categoryName'] : false,
- // 'buyerNum' => isset($data['buyerNum']) ? $data['buyerNum'] : false,
- // 'buyerUnitPrice' => isset($data['buyerUnitPrice']) ? $data['buyerUnitPrice'] : false,
- // 'subtotalPrice' => isset($data['subtotalPrice']) ? $data['subtotalPrice'] : false,
- // 'purchaseId' => isset($data['purchaseId']) ? $data['purchaseId'] : false,
- // 'detailsReturnStatus' => isset($data['returnStatus']) ? $data['returnStatus'] : false,
- // 'detailsDeleteStatus' => isset($data['deleteStatus']) ? $data['deleteStatus'] : false,
- // ];
- // foreach ($addEsData as $key => $value) {
- // if ($value === false) {
- // return ResultWrapper::fail($key . '---ES字段未设置', ErrorCode::$paramError);
- // }
- // }
- // //创建es id
- // $esId = self::esId($id);
- // $result = $this->objDPurchaseGoods->addUpSearchIndexDocument($addEsData, $esId);
- // if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
- // return ResultWrapper::success(isset($result['_id']) ? $result['_id'] : false);
- // }
- // return ResultWrapper::fail($result['error']['reason'], ErrorCode::$paramError);
- // }
- /**
- * 拼接详情es id
- * @param $id
- * @return string
- */
- // public function esId($id)
- // {
- // return 'EnterpriseId_' . $this->onlineEnterpriseId . '_PurchaseDetailsId_' . $id;
- // }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/12/23
- * Time: 10:29 上午
- * @param array $arr
- * @return string
- */
- public static function formatSpecGroup($arr): string
- {
- $str = '';
- if (empty($arr) || !is_array($arr)) {
- return $str;
- }
- foreach ($arr as $item) {
- if (!empty($str)) {
- $str .= '_';
- }
- $str .= $item['specValueName'];
- }
- return $str;
- }
- /**
- * Doc: (des="获取商品的最近采购成本价格")
- * User: XMing
- * Date: 2021/3/11
- * Time: 10:28 上午
- * @param int $materielId
- * @param int $date
- * @return ResultWrapper
- */
- public function getCostPriceSheetByMaterielId(int $materielId,int $date): ResultWrapper
- {
- $sql = 'SELECT buyerUnitPrice,skuId,createTime FROM '.$this->objDPurchaseGoods->get_Table().' WHERE basicGoodsId = '.$materielId;
- $sql .= ' AND createTime <= '.$date;
- $lists = $this->objDPurchaseGoods->query($sql);
- if ($lists === false){
- Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDPurchaseGoods->error());
- return ResultWrapper::fail($this->objDPurchaseGoods->error(),ErrorCode::$dberror);
- }
- if (empty($lists)){
- return ResultWrapper::success([]);
- }
- $arrayList = [];
- foreach ($lists as $item){
- $arrayList[$item['skuId']][] = [
- 'costPrice' => floatval($item['buyerUnitPrice']),
- 'createTime' => $item['createTime']
- ];
- }
- return ResultWrapper::success($arrayList);
- }
- /**
- * 采购再次入库
- * @param int $orderId
- * @return ResultWrapper
- */
- public function reStockIn($purchaseId)
- {
- // 获取采购单数据
- $purchaseData = $this->objDPurchase->get($purchaseId);
- if ($purchaseData === false){
- return ResultWrapper::fail($this->objDPurchase->error(),ErrorCode::$dberror);
- }
- if (empty($purchaseData)){
- return ResultWrapper::fail('采购订单数据为空',ErrorCode::$paramError);
- }
- if ($purchaseData['inStatus'] == StatusCode::$standard){
- return ResultWrapper::fail('采购订单已经入库,请不要重复入库',ErrorCode::$paramError);
- }
- // 查询采购订单是否还有未审核的入库单,必须先处理完,再生成新的入库单
- $objMInventoryIn = new MInventoryIn($this->onlineEnterpriseId, $this->onlineUserId);
- $condition = [
- 'originId' => $purchaseId,
- 'deleteStatus' => StatusCode::$standard,
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- ];
- $result = $objMInventoryIn->getInventoryInData($condition);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- $inventoryInData = $result->getData();
- if( !empty($inventoryInData) ){
- return ResultWrapper::fail('当前采购订单还有未审核的入库单,单号:'.StatusCode::$noPrefix[3].'-'.$inventoryInData[0]['no'].',请先处理完成', ErrorCode::$notAllowAccess);
- }
- // 查询采购订单商品数据
- $purchaseGoodsData = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId,'deleteStatus' => StatusCode::$standard]);
- if ($purchaseGoodsData === false){
- return ResultWrapper::fail($this->objDPurchaseGoods->error(),ErrorCode::$dberror);
- }
- if (empty($purchaseGoodsData)){
- return ResultWrapper::fail('采购订单商品为空',ErrorCode::$paramError);
- }
- // 组装采购入库单数据
- $purchaseInData = [
- 'sourceId' => $purchaseData['id'],
- 'sourceNo' => $purchaseData['no'],
- 'originNo' => $purchaseData['no'],
- 'originId' => $purchaseData['id'],
- 'shopId' => $purchaseData['shopId'],
- 'shopName' => getArrayItem($purchaseData, 'shopName'),
- 'amount' => $purchaseData['purchaseAmount'],
- 'operatorId' => $purchaseData['operatorId'],//操作人id
- 'operatorName' => $purchaseData['operatorName'],//操作人信息
- 'warehouseId' => $purchaseData['warehouseId'],//仓库id
- 'warehouseName' => $purchaseData['warehouseName'],//仓库名称
- 'source' => StatusCode::$orderType['purchaseOrder'],
- 'type' => StatusCode::$orderType['purchaseIn'],
- 'remark' => $purchaseData['remark'],
- 'merchantId' => $purchaseData['merchantId'],//商户id
- 'orderGoodsData' => []
- ];
- $purchaseInData['materielNum'] = 0;
- $amount = 0;
- foreach ($purchaseGoodsData as $key => $value) {
- if ($value['inOfNum'] > 0 ){
- $amount += bcmul($value['inOfNum'],$value['buyerUnitPrice'],2);
- $purchaseInData['materielNum']++;
- $purchaseInData['orderGoodsData'][] = [
- 'materielId' => $value['basicGoodsId'],
- 'materielName' => $value['goodsName'],
- 'materielCode' => $value['goodsCode'],
- 'skuId' => $value['skuId'],
- 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
- 'skuName' => isset($value['skuName']) ? $value['skuName'] : '',
- 'num' => $value['inOfNum'],
- 'inNum' => 0,
- 'otherNum' => $value['otherNum'],
- 'unitPrice' => $value['buyerUnitPrice'],
- 'totalPrice' => bcmul($value['inOfNum'],$value['buyerUnitPrice'],2),
- ];
- }
- }
- $purchaseInData['amount'] = $amount;
- if (empty($purchaseInData['orderGoodsData'])){
- return ResultWrapper::fail('此采购订单没有需要入库的商品',ErrorCode::$paramError);
- }
- // 新增采购入库单
- $dbResult = $objMInventoryIn->addInventoryIn($purchaseInData);
- if (!$dbResult->isSuccess()) {
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult->getData());
- }
- /**
- * 采购订单直接退款
- */
- public function retMoney($purchaseId)
- {
- $purchaseData = $this->objDPurchase->get($purchaseId);
- if($purchaseData === false){
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- if(empty($purchaseData)){
- return ResultWrapper::fail('采购订单数据为空', ErrorCode::$contentNotExists);
- }
- $purchaseGoodsData = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId,'deleteStatus' => StatusCode::$standard]);
- if ($purchaseGoodsData === false){
- return ResultWrapper::fail($this->objDPurchaseGoods->error(),ErrorCode::$dberror);
- }
- if (empty($purchaseGoodsData)){
- return ResultWrapper::fail('采购订单商品为空',ErrorCode::$paramError);
- }
- /*
- $refundMoney = 0;
- foreach ($purchaseGoodsData as $key => $value) {
- if ($value['inOfNum'] > 0 ){
- $refundMoney += bcmul($value['inOfNum'],$value['buyerUnitPrice'],2);
- }
- }
- // 生成财务退款单
- $financeRefundData = [
- 'originId' => getArrayItem($purchaseData,'id',''),
- 'originNo' => getArrayItem($purchaseData,'no',''),
- 'sourceNo' => getArrayItem($purchaseData,'no',''),
- 'refundTime' => time(),
- 'createTime' => time(),
- 'unitId' => getArrayItem($purchaseData,'supplierId',0),
- 'unitName' => getArrayItem($purchaseData,'supplierName',0),
- 'currentAccountName' => getArrayItem($purchaseData,'supplierName',''),
- 'financeType' => '采购退款',
- 'financeTypeId' => 1,
- 'payType' =>'',
- 'shopId' => getArrayItem($purchaseData,'warehouseId',0),
- 'shopName' => getArrayItem($purchaseData,'warehouseName',0),
- 'money' => $refundMoney,
- 'operatorId' => $this->onlineUserId,
- 'type' => StatusCode::$delete,
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- ];
- // 根据订单支付方式规划退款账户
- /*$objMAccount = new MAccount($this->enterpriseId,$this->userCenterId);
- $payType = explode(',', $order['payType']);
- // 包含余额组合支付方式统一返回余额,其他原路返回
- if( in_array(StatusCode::$payType['balance'],$payType) ){
- $financeAccountData = $objMAccount->getDefaultAccount(StatusCode::$payType['balance']);
- }else{
- $financeAccountData = $objMAccount->getDefaultAccount($payType);
- }
- if(!$financeAccountData->isSuccess()){
- $this->objDInventoryOut->rollBack();
- return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
- }
- $financeAccountData = $financeAccountData->getData();
- $financeRefundData['accountList'] = [
- [
- 'accountId' => $financeAccountData['id'],
- 'accountNumber' => $financeAccountData['accountNumber'],
- 'accountName' => $financeAccountData['name'],
- 'money' => $InventoryOutData['amount'],
- ]
- ];*/
- $beginTransactionStatus = $this->objDPurchase->beginTransaction();
- // 修改采购单退款标识字段
- $result = $this->objDPurchase->update(['havaRefund'=>StatusCode::$standard,'inStatus'=>StatusCode::$standard,'updateTime'=>time()], $purchaseId);
- if($result === false){
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
- }
- // 添加退款单
- /*$financeRefundData['accountList'] = [];
- $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId);
- $result = $objMRefund->addRefund($financeRefundData);
- if(!$result->isSuccess()){
- $this->objDPurchase->rollBack();
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }*/
- if($beginTransactionStatus){
- $this->objDPurchase->commit();
- }
- return ResultWrapper::success($result);
- }
-
- /**
- * 采购总汇表导出方法
- * @param $result
- */
- public function exportPurchaseByFields($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 = ['商品类别', '仓库','商品', '商品编码', '规格','数量', '其他单位', '入库状态', '成本', '总成本']; //定义标题
-
- foreach ($head as $i => $v) {
- $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
- }
-
- fputcsv($fp, $head);
-
- $limit = 10000;
- $num = 0;//计数器
- foreach ($result as $value) {//循环数据
- $num++;
- if ($num == $limit) {
- ob_flush();//释放内存
- flush();
- }
- $rows['categoryName'] = isset($value['categoryName']) ? $value['categoryName'] : null;//商品类别
- $rows['warehouseName'] = isset($value['warehouseName']) ? $value['warehouseName'] : null;//仓库
- $rows['materielName'] = isset($value['materielName']) ? $value['materielName'] : null;//商品
- $rows['materielCode'] = isset($value['materielCode']) ? $value['materielCode'] : null;//商品编码
- $rows['unitName'] = isset($value['unitName']) ? $value['unitName'] : null;//规格
- $rows['total'] = isset($value['total']) ? $value['total'] : null;//数量
- $rows['otherNum'] = isset($value['otherNum']) ? $value['otherNum'] : null;//其他单位
- $rows['inStatus'] = isset($v['inStatus']) ? $v['inStatus'] == StatusCode::$standard ? '已入库' : '未入库' : null;//入库状态
- $rows['costPrice'] = isset($value['costPrice']) ? $value['costPrice'] : null;//成本
- $rows['allNum'] = isset($value['allNum']) ? $value['allNum'] : null;//总成本
-
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- }
- /**
- * 智能采购列表
- */
- public function getAllOrderPurchase($selectParams)
- {
- $stockDbName = Factory::config()->get('db.stock.dbname');
- $objDOrder = new DOrder();
- $objDOrderGoods = new DOrderGoods();
- $objDInventoryWarehouse = new DInventoryWarehouse();
- $objDInventoryWarehouse->setTable('qianniao_inventory_warehouse_'.$this->onlineEnterpriseId);
- $orderTableName = $objDOrder->getTableName('qianniao_order_' . $this->onlineEnterpriseId, $this->onlineUserId, $this->cutTable);
- $objDOrder->setTable($orderTableName);
- $orderGoodsTableName = $objDOrderGoods->getTableName('qianniao_order_goods_' . $this->onlineEnterpriseId, $this->onlineUserId, $this->cutTable);
- $objDOrderGoods->setTable($orderGoodsTableName);
- $returnData = [
- 'data' => [],
- 'total' => 0,
- ];
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $whereSql = '';
- if (isset($selectParams['no']) && !empty($selectParams['no'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' o.no like "%' . $selectParams['no'] .'%"';
- }
- if (isset($selectParams['customerName']) && !empty($selectParams['customerName'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' o.customerName like "%' . $selectParams['customerName'] .'%"';
- }
- if (isset($selectParams['payStatus']) && !empty($selectParams['payStatus'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' o.payStatus = ' . $selectParams['payStatus'];
- }
- if (isset($selectParams['orderStatus']) && !empty($selectParams['orderStatus'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' o.orderStatus = ' . $selectParams['orderStatus'];
- }
- if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' o.auditStatus = ' . $selectParams['auditStatus'];
- }
- if ( (isset($selectParams['start']) && !empty($selectParams['start']))&&(isset($selectParams['end']) && !empty($selectParams['end'])) ) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' o.createTime BETWEEN ' . $selectParams['start'] . ' AND '. $selectParams['end'];
- }
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . 'g.deleteStatus = ' . StatusCode::$standard;
- $sql = 'SELECT g.*,o.*,sum(g.buyNum) as goodsBuyNum,sum(g.otherNum) as goodsOtherNum, w.inventoryNum as inventoryNum,w.otherNum as warehouseOtherNum FROM ' . $objDOrderGoods->get_Table() .' as g left join '. $objDOrder->get_Table() .' as o on o.id=g.orderId left join `'.$stockDbName.'`.'. $objDInventoryWarehouse->get_Table() .' as w on g.skuId=w.skuId '.$whereSql . ' group by g.skuId ORDER BY o.createTime DESC LIMIT ' . $offset . ' , ' . $limit;
- $dbResult = $objDOrder->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDOrder->error(), ErrorCode::$dberror);
- }
- if(empty($dbResult)){
- return ResultWrapper::success($returnData);
- }
- //格式化数据
- foreach ($dbResult as $key => $value){
- if(empty($value['inventoryNum'])){
- $dbResult[$key]['inventoryNum'] = 0;
- }
- if(empty($value['warehouseOtherNum'])){
- $dbResult[$key]['warehouseOtherNum'] = 0;
- }
- }
- $return = [
- 'data' => $dbResult,
- 'total' => count($dbResult),
- ];
- return ResultWrapper::success($return);
- }
- }
|