12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082 |
- <?php
- /**
- * 付款单管理模块
- * Created by PhpStorm.
- * User: wxj
- * Date: 2019/10/30
- * Time: 14:02
- */
- namespace JinDouYun\Model\Finance;
- use JinDouYun\Dao\Finance\DPay;
- use JinDouYun\Dao\Finance\DPayReceiptIndex;
- use Mall\Framework\Core\ErrorCode;
- use Mall\Framework\Core\StatusCode;
- use Mall\Framework\Core\ResultWrapper;
- use JinDouYun\Model\MBaseModel;
- use JinDouYun\Model\Finance\MSupplierBalanceDetail;
- use JinDouYun\Model\Finance\MSupplierBalance;
- use JinDouYun\Model\Finance\MAccount;
- use JinDouYun\Model\Finance\MAccountDetail;
- use JinDouYun\Model\Finance\MFinanceType;
- use JinDouYun\Model\Finance\MPay;
- use JinDouYun\Dao\Finance\DPaidOffset;
- use JinDouYun\Dao\Finance\DPaid;
- use JinDouYun\Dao\Finance\DPaidIndex;
- use JinDouYun\Dao\Finance\DPaidAccount;
- class MPaid extends MBaseModel
- {
- private $objDay;
- private $objDPaid;
- private $objDPaidIndex;
- private $objDPaidAccount;
- private $objMSupplierBalanceDetail;
- private $objMSupplierBalance;
- private $objMAccount;
- private $objMAccountDetail;
- private $enterpriseId;
- private $userCenterId;
- private $objMFinanceType;
- private $objDPaidOffset;
- private $objDPayReceiptIndex;
- public function __construct($enterpriseId, $userCenterId)
- {
- $this->userCenterId = $userCenterId;
- $this->enterpriseId = $enterpriseId;
- parent::__construct($enterpriseId, $userCenterId);
- $this->objMSupplierBalanceDetail = new MSupplierBalanceDetail($enterpriseId, $userCenterId);
- $this->objMSupplierBalance = new MSupplierBalance($enterpriseId, $userCenterId);
- $this->objMAccount = new MAccount($enterpriseId, $userCenterId);
- $this->objMAccountDetail = new MAccountDetail($enterpriseId, $userCenterId);
- $this->objMFinanceType = new MFinanceType($enterpriseId, $userCenterId);
- $this->objDay = new DPay('finance');
- $this->objDPaid = new DPaid('finance');
- $this->objDPaidIndex = new DPaidIndex('finance');
- $this->objDPaidAccount = new DPaidAccount('finance');
- $this->objDPaidOffset = new DPaidOffset('finance');
- $this->objDPayReceiptIndex = new DPayReceiptIndex('finance');
- $this->objDPaidOffset->setTable('qianniao_paid_offset_'. $enterpriseId);
- $this->objDPaidIndex->setTable('qianniao_paid_index_' . $this->enterpriseId);
- $this->objDPayReceiptIndex->setTable('qianniao_pay_receipt_index_'.$this->enterpriseId);
- //$this->objDPaid->setSearchIndex('paid_receipt_search')->setType('paid_receipt');
- }
- /**
- * 添加付款单
- *
- * @param array $params 付款单数据
- *
- * @return ResultWrapper
- */
- public function addPaid($params)
- {
- $offsetDate = $params['receiptOffsetData'];
- unset($params['receiptOffsetData']);
- $accountList = $params['accountList'];
- unset($params['accountList']);
- $beginTransactionStatus = $this->objDPaid->beginTransaction();
- // 生成编号
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3));
- $dbResult = $this->objDPaid->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- if(empty($dbResult)){
- $params['no'] = createSerialNumberByDate('');
- }else{
- $params['no'] = createSerialNumberByDate($dbResult['no']);
- }
- //sourceNo字段剔除前缀
- if(isset($params['sourceNo']) && !empty($params['sourceNo'])){
- $tmpSourceNo = explode('-',$params['sourceNo']);
- if(count($tmpSourceNo) == 3){
- $params['sourceNo'] = $tmpSourceNo[1].'-'.$tmpSourceNo[2];
- }
- }
- //索引表数据
- $indexData = [
- 'no' => $params['no'],
- 'paidId' => 0,
- 'supplierId' => $params['supplierId'],
- 'currentAccountName' => $params['currentAccountName'],
- 'sourceNo' => $params['sourceNo'],
- 'auditStatus' => $params['auditStatus'],
- 'financeTypeId' => $params['financeTypeId'],
- 'financeType' => $params['financeType'],
- 'paidType' => empty($offsetDate) ? StatusCode::$standard : StatusCode::$delete,
- 'createTime' => $params['createTime'],
- 'updateTime' => $params['updateTime'],
- 'receiptTime' => $params['receiptTime'],
- ];
- $PaidId = $this->objDPaidIndex->insert($indexData);
- if ($PaidId === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidIndex->error(), ErrorCode::$dberror);
- }
- $params['id'] = $PaidId;
- $params['totalMoney'] = 0;
- $params['totalDiscountMoney'] = 0;
- $params['totalFinalMoney'] = 0;
- foreach ($accountList as $account) {
- $account['discountMoney'] = !empty($account['discountMoney']) ? $account['discountMoney'] : 0;
- $params['totalMoney'] += $account['money'];
- $params['totalDiscountMoney'] += $account['discountMoney'];
- $params['totalFinalMoney'] += ($account['money'] - $account['discountMoney']);
- $params['offsetMoney'] = 0;
- $params['notOffsetMoney'] = $params['totalFinalMoney'];
- $params['offsetStatus'] = StatusCode::$delete;
- }
- $dbResult = $this->objDPaid->insert($params);
- if ($dbResult === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- //收款账户数据
- foreach ($accountList as $account) {
- if (isset($account['id'])) {
- unset($account['id']);
- }
- $account['paidId'] = $PaidId;
- $account['operatorId'] = $this->userCenterId;
- $account['createTime'] = $params['createTime'];
- $account['updateTime'] = $params['updateTime'];
- $this->objDPaidAccount->setTable('qianniao_paid_account_' . $this->enterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3));
- $result = $this->objDPaidAccount->insert($account);
- if ($result === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidAccount->error(), ErrorCode::$dberror);
- }
- }
- //记录核销明细
- if(empty($offsetDate)){
- if ($beginTransactionStatus){
- $this->objDPaid->commit();
- }
- return ResultWrapper::success($PaidId);
- }
- if(!empty($offsetDate)){
- foreach ($offsetDate as $key => $value){
- $offsetDate[$key]['paidId'] = $PaidId;
- }
- }
- unset($result);
- $result = $this->objDPaidOffset->insert($offsetDate,true);
- if ($result === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
- }
- if ($beginTransactionStatus){
- $this->objDPaid->commit();
- }
- /*
- $_id = self::createEsDocumentId($PaidId, $params['createTime']);
- $esData = $params;
- $esData['id'] = $PaidId;
- $esData['enterpriseId'] = $this->enterpriseId;
- $result = $this->objDPaid->addUpSearchIndexDocument($esData, $_id);
- if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
- //echo "es操作成功";die;
- }else {
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/elasticsearch.log',date('Y-m-d H:i:s').'生成付款单es错误,错误原因'.var_export($result,true).PHP_EOL,FILE_APPEND);
- }
- */
- return ResultWrapper::success($PaidId);
- }
- private function createEsDocumentId($paidId, $time)
- {
- $t = date('Y', $time) . '_' . ceil(date('m', $time) / 3);
- return 'EnterpriseId_' . $this->enterpriseId . '_' . $t .'_paidId_' . $paidId;
- }
- /**
- * 修改付款单
- * @param array $params 付款单数据
- * @return ResultWrapper
- */
- public function editPaid($params)
- {
- $beginTransactionStatus = $this->objDPaid->beginTransaction();
- $accountList = $params['accountList'];
- unset($params['accountList']);
- $offsetDate = $params['receiptOffsetData'];
- unset($params['receiptOffsetData']);
- if(isset($params['sourceNo']) && !empty($params['sourceNo'])){
- unset($params['sourceNo']);
- }
- $params['totalMoney'] = 0;
- $params['totalDiscountMoney'] = 0;
- $params['totalFinalMoney'] = 0;
- foreach ($accountList as $account) {
- $account['discountMoney'] = !empty($account['discountMoney']) ? $account['discountMoney'] : 0;
- $params['totalMoney'] += $account['money'];
- $params['totalDiscountMoney'] += $account['discountMoney'];
- $params['totalFinalMoney'] += ($account['money'] - $account['discountMoney']);
- }
- $paidId = $params['id'];
- unset($params['id']);
- // 根据单据创建时间切表
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
- $dbResult = $this->objDPaid->update($params,$paidId);
- if ($dbResult === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- //索引表数据
- $indexData = [
- 'supplierId' => $params['supplierId'],
- 'currentAccountName' => $params['currentAccountName'],
- 'sourceNo' => $params['sourceNo'],
- 'auditStatus' => $params['auditStatus'],
- 'financeTypeId' => $params['financeTypeId'],
- 'financeType' => $params['financeType'],
- 'paidType' => empty($offsetDate) ? StatusCode::$standard : StatusCode::$delete,
- 'createTime' => $params['createTime'],
- 'updateTime' => $params['updateTime'],
- 'receiptTime' => $params['receiptTime'],
- ];
- $result = $this->objDPaidIndex->update($indexData,['id'=>$paidId]);
- if ($result === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidIndex->error(), ErrorCode::$dberror);
- }
- //收款账户数据
- // 根据单据创建时间切表
- $this->objDPaidAccount->setTable('qianniao_paid_account_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
- foreach ($accountList as $account) {
- if (isset($account['id'])) {
- $account['paidId'] = $paidId;
- $account['operatorId'] = $this->userCenterId;
- $account['createTime'] = $params['createTime'];
- $account['updateTime'] = $params['updateTime'];
- $result = $this->objDPaidAccount->update($account,$account['id']);
- }else{
- $account['paidId'] = $paidId;
- $account['operatorId'] = $this->userCenterId;
- $account['createTime'] = $params['createTime'];
- $result = $this->objDPaidAccount->insert($account);
- }
- if ($result === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidAccount->error(), ErrorCode::$dberror);
- }
- }
- //更新核销明细
- if(empty($offsetDate)){
- if ($beginTransactionStatus){
- $this->objDPaid->commit();
- }
- return ResultWrapper::success($dbResult);
- }
- if(!empty($offsetDate)){
- foreach ($offsetDate as $key => $value){
- $offsetDate[$key]['paidId'] = $paidId;
- unset($result);
- $result = $this->objDPaidOffset->update($value, ['paidId'=>$paidId]);
- }
- }
- if ($result === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
- }
- $this->objDPaid->commit();
- // $_id = self::createEsDocumentId($paidId, $params['createTime']);
- // $esData = $params;
- // $esData['id'] = $paidId;
- // $esData['enterpriseId'] = $this->enterpriseId;
- // $this->objDPaid->esupdateTypeFieldVaule($esData, $_id);
- return ResultWrapper::success($dbResult);
- }
- /**
- * 获取指定付款单信息
- */
- public function getPaidInfo($paidParams)
- {
- // 根据单据创建时间切表
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y', $paidParams['createTime']) . '_' . ceil(date('m', $paidParams['createTime']) / 3));
- $dbResult = $this->objDPaid->get($paidParams['id']);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- //渲染前缀
- $dbResult['no'] = StatusCode::$noPrefix[19] . '-' . $dbResult['no'];
- // 根据单据创建时间切表
- $this->objDPaidAccount->setTable('qianniao_paid_account_' . $this->enterpriseId . '_' . date('Y', $paidParams['createTime']) . '_' . ceil(date('m', $paidParams['createTime']) / 3));
- $dbResult['accountList'] = $this->objDPaidAccount->select(['paidId' => $paidParams['id']]);
- //查出供应商当前余额
- $dbResult['currentBalanceMoney'] = !empty($dbResult['supplierId']) ? $this->objMSupplierBalance->getSupplierBalance($dbResult['supplierId']) : 0;
- //核销明细
- $dbResult['offsetDate']= [];
- $offsetdbResult = $this->objDPaidOffset->select(['paidId' => $paidParams['id']]);
- if ( $offsetdbResult === false ) {
- return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
- }
- if ( !empty($offsetdbResult) ){
- $payReceiptIdBindOffsetMoney = [];
- foreach ($offsetdbResult as $key => $value){
- $payReceiptIdBindOffsetMoney[$value['payReceiptId']] = $value['offsetMoney'];
- }
- $payReceiptIds = array_column($offsetdbResult,'payReceiptId');
- $objMPay = new MPay($this->enterpriseId, $this->userCenterId);
- $selectParams = [
- 'limit' => 200,
- 'offset' => 0,
- 'payReceiptIds' => $payReceiptIds,
- ];
- $payReceiptData = $objMPay->getAllPay($selectParams);
- if(!$payReceiptData->isSuccess()){
- return ResultWrapper::fail($payReceiptData->getData(), $payReceiptData->getErrorCode());
- }
- $payReceiptData = $payReceiptData->getData();
- if(!empty($payReceiptData['total'])){
- foreach ($payReceiptData['data'] as $key => $value){
- $payReceiptData['data'][$key]['offsetMoney'] = getArrayItem($payReceiptIdBindOffsetMoney, $value['id'], 0);
- }
- $dbResult['offsetDate'] = $payReceiptData['data'];
- }
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 付款单审核
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function updatePaidStatus($params)
- {
- // 根据单据创建时间切表
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
- // 获取付款单数据
- $paidData = $this->objDPaid->get(['id' => $params['id']]);
- if ($paidData === false) {
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- if( empty($paidData) ){
- return ResultWrapper::fail('要审核的付款单据不存在', ErrorCode::$contentNotExists);
- }
- // 判断是否已经审核过了
- if($paidData['auditStatus'] == StatusCode::$auditStatus['auditPass']){
- return ResultWrapper::fail('该单据已经审核过了', ErrorCode::$notAllowAccess);
- }
- // 修改付款单审核状态
- $beginTransactionStatus = $this->objDPaid->beginTransaction();
- $dbResult = $this->objDPaid->update(['auditStatus' => StatusCode::$auditStatus['auditPass']], ['id' => $params['id']]);
- if ($dbResult === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- $dbResult = $this->objDPaidIndex->update(['auditStatus' => StatusCode::$auditStatus['auditPass']], ['id' => $params['id']]);
- if ($dbResult === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidIndex->error(), ErrorCode::$dberror);
- }
- $supplierMoney = $this->objMSupplierBalance->getSupplierBalance($paidData['supplierId']);
- $remark = '';
- //查出源单据已支付过的金额
- if (!empty($paidData['sourceNo'])) {
- $beforePaidMoney = 0;
- $where = 'sourceNo = '. $paidData['sourceNo'] . ' AND auditStatus = '.StatusCode::$auditStatus['auditPass'].' AND id !='.$params['id'];
- $sourceNoPaidResult = $this->objDPaidIndex->get($where);
- if(!empty($sourceNoPaidResult)) {
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y', $sourceNoPaidResult['createTime']) . '_' . ceil(date('m', $sourceNoPaidResult['createTime']) / 3));
- $beforePaidMoney = $this->objDPaid->get_field('totalMoney',$sourceNoPaidResult['paidId']);
- }
- $remark = ",剩余应付".($paidData['sourceNoMoney'] - $beforePaidMoney - $paidData['totalMoney']).'元';
- }
- $detailData = [
- 'supplierId' => $paidData['supplierId'],
- 'receiptTime' => $paidData['receiptTime'],//'单据日期',
- 'no' => $paidData['no'],//'单据编号',
- 'financeType' => $paidData['financeType'],//'财务类型名称',
- 'financeTypeId' => $paidData['financeTypeId'],//'财务类型id',
- 'sourceNo' => $paidData['sourceNo'],//'源订单销货号',
- 'salesAmount' => 0.00,//销售金额
- 'discountMoney' => $paidData['totalDiscountMoney'],// '优惠金额',
- 'supplierAmount' => 0.00,//供应商承担金额
- 'shouldPayAmount' => 0.00,
- 'actualPaidAmount' => $paidData['totalFinalMoney'],//'实际付款金额',
- 'shouldPayBalance' => bcsub($supplierMoney,$paidData['totalMoney'],2), //'应付款余额' 当前余额 - 付款金额
- 'remark' => '付款单审核通过,本次付给供应商'.$paidData['totalFinalMoney'].'元,优惠'. $paidData['totalDiscountMoney'] .'元'.$remark,//'备注',
- 'createTime' => time(),//'创建日期',
- 'updateTime' => time(),//'修改日期',
- ];
- //供应商余额明细
- $result = $this->objMSupplierBalanceDetail->addSupplierBalanceDetail($detailData);
- if (!$result->isSuccess()) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- //供应商余额
- $result = $this->objMSupplierBalance->addSupplierBalance($paidData['supplierId'], -1*$paidData['totalMoney']);
- if (!$result->isSuccess()) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- // 查询核销表
- $offsetDbResult = $this->objDPaidOffset->select(['paidId'=>$paidData['id']]);
- if ($offsetDbResult === false) {
- return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
- }
- //如果是负收款不核销
- if($paidData['totalFinalMoney'] > 0){
- // 收款单审核自动核销
- if (!empty($offsetDbResult)){
- foreach ($offsetDbResult as $offsetKey =>$offsetValue){
- //说明此条应收单需要优先核销
- $sql = 'select * from ' . $this->objDPayReceiptIndex->get_Table() . ' where id='.$offsetValue['payReceiptId'];
- $firstOffset = $this->objDPayReceiptIndex->query($sql);
- if ($firstOffset === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
- }
- if(empty($firstOffset)){
- $this->objDPaid->rollBack();
- return ResultWrapper::fail('要操作得应收单不存在', ErrorCode::$contentNotExists);
- }
- if( $firstOffset[0]['offsetStatus'] == StatusCode::$standard ){
- $this->objDPaid->rollBack();
- continue;
- }
- $autoCustomerMoney = self::autoSupplierMoney($paidData['supplierId'],$paidData['totalFinalMoney'],$paidData['id'],$paidData['createTime'],$firstOffset,$offsetValue['payReceiptId']);
- if(!$autoCustomerMoney->isSuccess()){
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($autoCustomerMoney->getData(),$autoCustomerMoney->getErrorCode());
- }
- }
- }else{
- if(empty($paidData['sourceNo'])){ // 如果有sourceNo说明需要核销指定应收,这里不需要操作
- $autoCustomerMoney = self::autoSupplierMoney($paidData['supplierId'],$paidData['totalFinalMoney'],$paidData['id'],$paidData['createTime'],$firstOffsetDate=[],0);
- if(!$autoCustomerMoney->isSuccess()){
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($autoCustomerMoney->getData(),$autoCustomerMoney->getErrorCode());
- }
- }
- }
- }
- //更新供应商总收款金额
- $result = $this->objMSupplierBalance->updateSupplierTotalReceiveMoney($paidData['supplierId'], $paidData['totalFinalMoney']);
- if (!$result->isSuccess()) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- // 根据单据创建时间切表
- $this->objDPaidAccount->setTable('qianniao_paid_account_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
- $accounts = $this->objDPaidAccount->select(['paidId'=>$paidData['id']]);
- foreach ($accounts as $account) {
- //获取账户信息
- $accountResult = $this->objMAccount->getAccountInfo($account['accountId']);
- if(!$accountResult->isSuccess()) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($accountResult->getData(), $accountResult->getErrorCode());
- }
- $accountInfo = $accountResult->getData();
- //账户明细
- $accountDetail = [
- 'accountId'=> $accountInfo['id'],
- 'accountCode'=> $accountInfo['accountCode'],
- 'accountName'=> $accountInfo['name'],
- 'accountNumber'=> $accountInfo['accountNumber'],
- 'sourceNo'=>$paidData['no'],
- 'sourceId'=>$paidData['id'],
- 'financeType'=>$paidData['financeType'],
- 'beginBalance'=>$accountInfo['money'],
- 'shopId'=>$paidData['shopId'],
- 'shopName'=>$paidData['shopName'],
- 'income'=>$paidData['totalFinalMoney']<0 ? -1 * $paidData['totalFinalMoney'] : 0,
- 'expend'=>$paidData['totalFinalMoney']>0 ? $paidData['totalFinalMoney'] : 0,
- 'endBalance'=>$accountInfo['money'] - $paidData['totalFinalMoney'],
- 'contactUnit'=>'供应商名称:'.$paidData['supplierName'],
- 'supplierId'=>$paidData['supplierId'],
- 'customerId'=>0,
- 'operatorId'=>$this->userCenterId,
- 'receiveOrPayPerson'=>$paidData['currentAccountName'],
- 'remark'=>'付款单审核通过,本次付给供应商'.$paidData['totalMoney'].'元,优惠'.$paidData['totalDiscountMoney'].'元,实际付款'.$paidData['totalFinalMoney'].'元',
- 'createTime'=>time(),
- 'updateTime'=>time(),
- ];
- $result = $this->objMAccountDetail->addAccountDetail($accountDetail);
- if (!$result->isSuccess()) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- //给账户减钱
- $changedMoney = $paidData['totalFinalMoney'] > 0 ? -1 * $paidData['totalFinalMoney'] : abs($paidData['totalFinalMoney']);
- $result = $this->objMAccount->updateMoney($account['accountId'], $changedMoney);
- if (!$result->isSuccess()) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- }
- //审核通过记录核销金额,未核销金额,核销状态。
- // $objMPay = new MPay($this->enterpriseId, $this->userCenterId);
- // $offsetDbResult = $this->objDPaidOffset->select(['paidId'=>$paidData['id']]);
- // if ($offsetDbResult === false) {
- // return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
- // }
- // if( !empty($offsetDbResult) ){
- // foreach ($offsetDbResult as $key =>$value){
- // $updateOffsetDbResult = $objMPay->updateOffsetStatus($offsetDbResult[$key]['payReceiptId'],$offsetDbResult[$key]['offsetMoney'],$offsetDbResult[$key]['payCreateTime']);
- // if(!$updateOffsetDbResult->isSuccess()){
- // $this->objDPaid->rollBack();
- // return ResultWrapper::fail($updateOffsetDbResult->getData(), $updateOffsetDbResult->getErrorCode());
- // }
- // }
- // }
- if ($beginTransactionStatus){
- $this->objDPaid->commit();
- }
- /*
- $_id = self::createEsDocumentId($paidData['id'], $paidData['createTime']);
- $this->objDPaid->esupdateTypeFieldVaule(['auditStatus'=>StatusCode::$auditStatus['auditPass']], $_id);*/
- return ResultWrapper::success($dbResult);
- }
- /**
- * 获取所有付款单数据
- * @param array $selectParams 过滤条件
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getAllPaid($selectParams,$export = 0)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- if($export){
- $offset = 0;
- $limit = 9999;
- }
- //组装sql where条件
- $whereSql = '';
- if (isset($selectParams['no']) && !empty($selectParams['no'])) {
- //no编号切割
- $explodeNo = explode("-",$selectParams['no']);
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' no = "' . $explodeNo[1] . '-' . $explodeNo[2] . '"';
- }
- if (isset($selectParams['financeTypeId']) && !empty($selectParams['financeTypeId'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' financeTypeId = ' . $selectParams['financeTypeId'];
- }
- if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' auditStatus = ' . $selectParams['auditStatus'];
- }
- if (isset($selectParams['supplierId']) && !empty($selectParams['supplierId'])) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' supplierId = ' . $selectParams['supplierId'];
- }
- if ( (isset($selectParams['start']) && !empty($selectParams['start']))&&(isset($selectParams['end']) && !empty($selectParams['end'])) ) {
- $where = empty($whereSql) ? ' WHERE ' : ' AND ';
- $whereSql .= $where . ' createTime BETWEEN ' . $selectParams['start'] . ' AND '. $selectParams['end'];
- }
- $sql = 'SELECT * FROM ' .$this->objDPaidIndex->get_Table(). $whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
- $paidIndexResult = $this->objDPaidIndex->query($sql);
- // $paidIndexResult = $this->objDPaidIndex->select($selectParams, '*', 'createTime desc', $limit, $offset);
- $tableSuffix = [];
- foreach ($paidIndexResult as $paidIndex) {
- $k = date('Y', $paidIndex['createTime']) . '_' . ceil(date('m', $paidIndex['createTime']) / 3);
- $tableSuffix[$k][] = $paidIndex['id'];
- }
- $paidResult = [];
- foreach ($tableSuffix as $suffix => $paidIds) {
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . $suffix);
- $dbResult = $this->objDPaid->select($paidIds, '*', 'createTime desc');
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- //渲染前缀
- if (!empty($dbResult)){
- foreach ($dbResult as $key => $value){
- $dbResult[$key]['no'] = StatusCode::$noPrefix[19] . '-' . $value['no'];
- if( !empty($value['sourceNo']) ){
- $dbResult[$key]['sourceNo'] = StatusCode::$noPrefix[2] . '-' . $value['sourceNo'];
- }
- }
- }
- $paidResult = array_merge($paidResult, $dbResult);
- }
- $totalSql = 'SELECT COUNT(1) as count FROM ' .$this->objDPaidIndex->get_Table() . $whereSql;
- $dbTotalResult = $this->objDPaidIndex->query($totalSql);
- //$total = $this->objDPaidIndex->count($selectParams);
- $return = [
- 'data' => self::format($paidResult),
- 'total' => $dbTotalResult[0]['count'],
- ];
- //导出
- if($export){
- self::exportPaid($return['data']);
- exit;
- }
- return ResultWrapper::success($return);
- }
- /**
- * 自动核销供应商余额
- * 客户id,收款单总的money进行自动核销
- */
- public function autoSupplierMoney($supplierId,$money,$id,$createTime,$firstOffset,$payReceiptId)
- {
- $paidDbResult = $this->objDPaid->get($id);
- if ($paidDbResult === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- //根据客户id查询客户所有核销状态不为5的应收单
- if ($payReceiptId == 0){//说明没有优先核销的
- $sql = 'select * from ' . $this->objDPayReceiptIndex->get_Table() . ' where supplierId='.$supplierId.' and offsetStatus != '. StatusCode::$standard;
- $dbResultOffset = $this->objDPayReceiptIndex->query($sql);
- }else{
- $sql = 'select * from ' . $this->objDPayReceiptIndex->get_Table() . ' where supplierId='.$supplierId.' and offsetStatus != '. StatusCode::$standard.' and id !='. $payReceiptId;
- $dbResultOffset = $this->objDPayReceiptIndex->query($sql);
- }
- $dbResultIndex = array_merge($firstOffset,$dbResultOffset);
- if ($dbResultIndex === false) {
- return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
- }
- if(empty($dbResultIndex)){//如果为空,说明当前单子只做付款,预付,不做核销.
- return ResultWrapper::success([]);
- }
- $surplusMoney = $money; // 剩余金额
- $payOffsetMoney = 0; // 收款单累计核销金额
- $payNotOffsetMoney = $money; // 收款累计未核销金额
- foreach ($dbResultIndex as $key => $value){
- // 付款单钱核销完了,则不再进行核销
- if($surplusMoney <=0){
- break;
- }
- //根据index表获取季度表信息
- $suffix = date('Y', $value['createTime']) . '_' . ceil(date('m', $value['createTime']) / 3);
- $this->objDay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
- //查出当前应收单的信息
- $payDate = $this->objDay->get($value['id']);
- if ($payDate === false) {
- return ResultWrapper::fail($this->objDay->error(), ErrorCode::$dberror);
- }
- if(empty($payDate)){
- continue;
- }
- //只核销金额大于0的,小于0是退款单
- if ($payDate['payMoney']<0) {
- continue;
- }
- switch (true)
- {
- case $payDate['notOffsetMoney'] <= $surplusMoney; //说明当前单子刚好核销完
- $offsetMoney = $payDate['notOffsetMoney'];
- $notOffsetMoney = 0;
- $offsetStatus = StatusCode::$standard;
- $payOffsetMoney = bcadd($payOffsetMoney, $payDate['notOffsetMoney'], 2);
- $payNotOffsetMoney = bcsub($payNotOffsetMoney, $payDate['notOffsetMoney'], 2);
- $updatePay = [
- 'offsetMoney' => $payOffsetMoney,
- 'notOffsetMoney' => $payNotOffsetMoney,
- 'offsetStatus' => ($payNotOffsetMoney ==0 ) ? StatusCode::$standard : StatusCode::$partion,
- ];
- $updatePaidIndex = [
- 'offsetStatus' => ($payNotOffsetMoney ==0 ) ? StatusCode::$standard : StatusCode::$partion,
- ];
- break;
- case $payDate['notOffsetMoney'] > $surplusMoney;
- $offsetMoney = $surplusMoney;
- $notOffsetMoney = bcsub($payDate['notOffsetMoney'],$offsetMoney,2);
- $offsetStatus = StatusCode::$partion;
- $payOffsetMoney = bcadd($payOffsetMoney, $surplusMoney, 2);
- $updatePay = [
- 'offsetMoney' => $payOffsetMoney,
- 'notOffsetMoney' => 0,
- 'offsetStatus' => StatusCode::$partion,
- ];
- $updatePaidIndex = [
- 'offsetStatus' => StatusCode::$partion,
- ];
- break;
- }
- $surplusMoney = bcsub($surplusMoney, $payDate['notOffsetMoney'], 2);
- //判断该单据是否已经审核
- if($payDate['auditStatus'] == StatusCode:: $auditStatus['auditPass']){
- $update = [
- 'offsetMoney' => bcadd($payDate['offsetMoney'],$offsetMoney,2),
- 'notOffsetMoney' => $notOffsetMoney,
- 'offsetStatus' => $offsetStatus,
- ];
- }else{
- $update = [
- 'offsetMoney' => bcadd($payDate['offsetMoney'],$offsetMoney,2),
- 'notOffsetMoney' => $notOffsetMoney,
- 'offsetStatus' => $offsetStatus,
- 'auditStatus' =>StatusCode:: $auditStatus['auditPass']
- ];
- }
- //判断index单据是否已经审核
- if($value['auditStatus'] == StatusCode:: $auditStatus['auditPass']){
- $updateIndex = [
- 'offsetStatus' => $offsetStatus,
- ];
- }else{
- $updateIndex = [
- 'offsetStatus' => $offsetStatus,
- 'auditStatus' =>StatusCode:: $auditStatus['auditPass']
- ];
- }
- $updateDPay = $this->objDay->update($update,['id'=>$value['id']]);
- if ($updateDPay === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDay->error(), ErrorCode::$dberror);
- }
- $updateDReceiveReceiptIndex = $this->objDPayReceiptIndex->update($updateIndex,['id'=>$value['id']]);
- if ($updateDReceiveReceiptIndex === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
- }
- //应收核销完成,记录核销信息
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y', $createTime) . '_' . ceil(date('m', $createTime) / 3));
- $updatePayResult = $this->objDPaid->update($updatePay,['id'=>$id]);
- if ($updatePayResult === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- //核销完成更新index表的核销状态
- $updatePayIndexResult = $this->objDPaidIndex->update($updatePaidIndex, ['id' => $id]);
- if ($updatePayIndexResult === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidIndex->error(), ErrorCode::$dberror);
- }
- //如果已经记过,需要剔除
- if (!empty($firstOffset) && count($firstOffset) - 1 >= $key) {//剔除
- continue;
- } else {
- //核销完成,记录核销明细
- $updateOffset = [
- 'payReceiptId' => $value['id'],
- 'paidId' => $id,
- 'offsetMoney' => $offsetMoney,
- 'payCreateTime' => $value['createTime']
- ];
- $result = $this->objDPaidOffset->insert($updateOffset);
- if ($result === false) {
- $this->objDPaid->rollBack();
- return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
- }
- }
- }
- return ResultWrapper::success($updateDPay);
- }
- public function format($data)
- {
- $financeTypeIds = [];
- foreach ($data as $key => $paid) {
- $financeTypeIds[] = $paid['financeTypeId'];
- }
- $financeTypeArr = [];
- if ($financeTypeIds) {
- $financeTypeResult = $this->objMFinanceType->getAllFinanceTypeNoPage(['id'=>array_unique(array_filter($financeTypeIds))]);
- if ($financeTypeResult->isSuccess()) {
- $financeTypeData = $financeTypeResult->getData();
- if (!empty($financeTypeData)) {
- foreach ($financeTypeData as $financeType) {
- $financeTypeArr[$financeType['id']] = $financeType['name'];
- }
- }
- }
- }
- foreach ($data as $key => &$paid) {
- $paid['financeType'] = isset($financeTypeArr[$paid['financeTypeId']]) ? $financeTypeArr[$paid['financeTypeId']] : $paid['financeType'];
- }
- return $data;
- }
- //搜索的where条件拼接
- public function setWhere($selectParams)
- {
- $defaultDSL = [
- 'from' => $selectParams['offset'],
- 'size' => $selectParams['limit'],
- 'sort' => [
- 'createTime' => [
- 'order' => 'desc'
- ],
- ],
- ];
- $dsl = [];
- $dsl['query']['bool']['must'][] = [
- 'term' => ['enterpriseId' => $this->enterpriseId],
- ];
- if (isset($selectParams['keyword'])) {
- if (!empty($selectParams['keyword'])) {
- $dsl['query']['bool']['must'][] = [
- 'multi_match' => [
- 'fields' => ['no', 'sourceNo', 'currentAccountName'],
- 'query' => $selectParams['keyword'],
- 'fuzziness' => 'AUTO',
- ]
- ];
- }
- }
- if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'receiptTime' => [
- 'gte' => $selectParams['start'],
- 'lte' => strtotime(date('Y-m-d',$selectParams['end']).'23:59:59'),
- ]
- ]
- ];
- } else {
- if (!empty($selectParams['start'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'receiptTime' => [
- 'gte' => $selectParams['start'],
- ]
- ]
- ];
- }
- if (!empty($selectParams['end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'receiptTime' => [
- 'lte' => strtotime(date('Y-m-d',$selectParams['end']).'23:59:59'),
- ]
- ]
- ];
- }
- }
- if (isset($selectParams['customerId'])) {
- if (!empty($selectParams['customerId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['customerId' => $selectParams['customerId']]];
- }
- }
- if (isset($selectParams['auditStatus'])) {
- if (!empty($selectParams['auditStatus'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['auditStatus' => $selectParams['auditStatus']]];
- }
- }
- if (isset($selectParams['financeTypeId'])) {
- if (!empty($selectParams['financeTypeId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['financeTypeId' => $selectParams['financeTypeId']]];
- }
- }
- $dsl = array_merge($defaultDSL, $dsl);
- return $dsl;
- }
- public function search($selectParams)
- {
- $dsl = $this->setWhere($selectParams);
- $result = $this->objDPaid->getSearchQueryDsl($dsl);
- if (isset($result['status']) && $result['status'] == 400) {
- if ($result['error']['reason'] == 'all shards failed') {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- return ResultWrapper::fail('获取应收数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
- }
- 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'];
- $list[] = $data;
- }
- $return = [
- 'data' => self::format($list),
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 付款单列表导出方法
- * @param $result
- * @return void
- * @throws Exception
- */
- public function exportPaid($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['no'] = isset($v['no']) ? $v['no'] : '';//单据号
- $rows['sourceNo'] = isset($v['sourceNo']) ? $v['sourceNo'] : '';//原单据号
- $rows['createTime'] = isset($v['createTime']) ? date('Y-m-d',$v['createTime']): '';//单据日期
- $rows['supplierName'] = isset($v['supplierName']) ? $v['supplierName'] : '';//供应商
- $rows['financeType'] = isset($v['financeType']) ? $v['financeType'] : '';//付款类型
- $rows['totalMoney'] = isset($v['totalMoney']) ? $v['totalMoney'] : '';//金额
- $rows['totalDiscountMoney'] = isset($v['totalDiscountMoney']) ? '¥'.$v['totalDiscountMoney'] : '';//优惠金额
- $rows['totalFinalMoney'] = isset($v['totalFinalMoney']) ? '¥'.$v['totalFinalMoney'] : '';//实付金额
- $rows['shopName'] = isset($v['shopName']) ? '¥'.$v['shopName'] : '';//相关店铺
- $rows['auditStatus'] = isset($v['auditStatus']) === 1 ? '待审核' : '已审核';//审核状态
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- }
- /**
- * 付款查询核销记录
- */
- public function getAllPaidOffset($params)
- {
- $paId = $params['paidId'];
- $dbResult = $this->objDPaidOffset->select(['paidId'=>$paId]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
- }
- if(empty($dbResult)){
- return ResultWrapper::success([]);
- }
- foreach ($dbResult as $key => $value){
- $suffix = date('Y', $value['payCreateTime']) . '_' . ceil(date('m', $value['payCreateTime']) / 3);
- $this->objDay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
- $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y', $value['createTime']) . '_' . ceil(date('m', $value['createTime']) / 3));
- // 查询应付
- $payDate = $this->objDay->get($value['payReceiptId']);
- if($payDate === false){
- return ResultWrapper::fail($this->objDay->error(), ErrorCode::$dberror);
- }
- // 查询付款
- $paidDate = $this->objDPaid->get($value['paidId']);
- if($paidDate === false){
- return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
- }
- if(!empty($payDate)){
- $dbResult[$key]['payId'] = $value['payReceiptId'];
- $dbResult[$key]['no'] = StatusCode::$noPrefix[18].'-'.$payDate['no'];
- $dbResult[$key]['offsetMoney'] = $value['offsetMoney'];
- $dbResult[$key]['notOffsetMoney'] = $payDate['notOffsetMoney'];
- $dbResult[$key]['money'] = $paidDate['totalFinalMoney'];
- $dbResult[$key]['purchaseId'] = $payDate['purchaseId'];
- $dbResult[$key]['purchaseNo'] = StatusCode::$noPrefix[2].'-'.$payDate['purchaseNo'];
- $dbResult[$key]['supplierName'] = $payDate['supplierName'];
- }
- }
- return ResultWrapper::success($dbResult);
- }
- }
|