MPay.Class.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. <?php
  2. /**
  3. * 应付单管理模块
  4. * Created by PhpStorm.
  5. * User: wxj
  6. * Date: 2019/10/30
  7. * Time: 14:02
  8. */
  9. namespace JinDouYun\Model\Finance;
  10. use JinDouYun\Dao\Finance\DPaid;
  11. use JinDouYun\Dao\Finance\DPaidOffset;
  12. use JinDouYun\Model\MBaseModel;
  13. use Mall\Framework\Core\ErrorCode;
  14. use Mall\Framework\Core\StatusCode;
  15. use Mall\Framework\Core\ResultWrapper;
  16. use JinDouYun\Dao\Finance\DPay;
  17. use JinDouYun\Dao\Finance\DPayReceiptIndex;
  18. use JinDouYun\Model\Finance\MSupplierBalanceDetail;
  19. use JinDouYun\Model\Finance\MSupplierBalance;
  20. class MPay extends MBaseModel
  21. {
  22. private $objDPay;
  23. private $objDPaid;
  24. private $objDPaidOffset;
  25. private $objDPayReceiptIndex;
  26. private $objMSupplierBalanceDetail;
  27. private $objMSupplierBalance;
  28. private $enterpriseId;
  29. private $userCenterId;
  30. public function __construct($enterpriseId, $userCenterId)
  31. {
  32. parent::__construct($enterpriseId, $userCenterId);
  33. $this->enterpriseId = $enterpriseId;
  34. $this->userCenterId = $userCenterId;
  35. $this->objMSupplierBalanceDetail = new MSupplierBalanceDetail($enterpriseId, $userCenterId);
  36. $this->objMSupplierBalance = new MSupplierBalance($enterpriseId, $userCenterId);
  37. $this->objDPay = new DPay('finance');
  38. $this->objDPayReceiptIndex = new DPayReceiptIndex('finance');
  39. $this->objDPaid = new DPaid('finance');
  40. $this->objDPaidOffset = new DPaidOffset('finance');
  41. $this->objDPaidOffset->setTable('qianniao_paid_offset_'.$enterpriseId);
  42. $this->objDPay->setTable('qianniao_pay_receipt_' . $enterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3));
  43. $this->objDPayReceiptIndex->setTable('qianniao_pay_receipt_index_' . $enterpriseId);
  44. //$this->objDPay->setSearchIndex('should_pay_receipt_search')->setType('should_pay_receipt');
  45. }
  46. /**
  47. * 临时财务脚本解决索引表id重复问题
  48. */
  49. public function tmp1()
  50. {
  51. // 查询应付索引表
  52. $result = $this->objDPayReceiptIndex->select('id > 273');
  53. if ($result === false) {
  54. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  55. }
  56. foreach ($result as $key => $value){
  57. $suffix = date('Y', $value['createTime']) . '_' . ceil(date('m', $value['createTime']) / 3);
  58. $this->objDPay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
  59. echo 'qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix.PHP_EOL;
  60. $dbResult = $this->objDPay->get($value['payReceiptId']);
  61. if ($dbResult === false) {
  62. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  63. }
  64. if(empty($dbResult)){
  65. return ResultWrapper::fail($value['payReceiptId'].'对应应付不存在', ErrorCode::$contentNotExists);
  66. }
  67. // 把应付单id改成索引表的自增id
  68. $dbResult = $this->objDPay->update(['id'=>$value['id']], $value['payReceiptId']);
  69. if ($dbResult === false) {
  70. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  71. }
  72. // 把索引表应付id改成空
  73. $result = $this->objDPayReceiptIndex->update(['payReceiptId'=>0], $value['id']);
  74. if ($result === false) {
  75. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  76. }
  77. echo $value['id'].'操作完成'.PHP_EOL;
  78. }
  79. return ResultWrapper::success('全部更新完成');
  80. }
  81. /**
  82. * 添加应付单
  83. *
  84. * @param array $params 应付单数据
  85. *
  86. * @return ResultWrapper
  87. */
  88. public function addPay($params)
  89. {
  90. $this->objDPay->beginTransaction();
  91. // 生成编号
  92. $dbResult = $this->objDPay->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
  93. if ($dbResult === false) {
  94. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  95. }
  96. if(empty($dbResult)){
  97. $params['no'] = createSerialNumberByDate('');
  98. }else{
  99. $params['no'] =createSerialNumberByDate($dbResult['no']);
  100. }
  101. //索引表数据
  102. $indexData = [
  103. 'payReceiptId' => 0,
  104. 'customerId' => $params['customerId'],
  105. 'sourceNo' => $params['sourceNo'],
  106. 'auditStatus' => $params['auditStatus'],
  107. 'offsetStatus' => ($params['PayMoney']<0) ? 5 : 4,
  108. 'financeTypeId' => $params['financeTypeId'],
  109. 'financeType' => $params['financeType'],
  110. 'shopId' => $params['shopId'],
  111. 'createTime' => $params['createTime'],
  112. 'updateTime' => $params['updateTime'],
  113. ];
  114. $payReceiptId = $this->objDPayReceiptIndex->insert($indexData);
  115. if ($payReceiptId === false) {
  116. $this->objDPay->rollBack();
  117. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  118. }
  119. $params['offsetStatus'] = ($params['PayMoney']<0) ? 5 : 4;
  120. $params['id'] = $payReceiptId;
  121. $payId = $this->objDPay->insert($params);
  122. if ($payId === false) {
  123. $this->objDPay->rollBack();
  124. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  125. }
  126. $this->objDPay->commit();
  127. // $_id = self::createEsDocumentId($payId, $params['createTime']);
  128. // $esData = $params;
  129. // $esData['id'] = $payId;
  130. // $esData['enterpriseId'] = $this->enterpriseId;
  131. // $result = $this->objDPay->addUpSearchIndexDocument($esData, $_id);
  132. // if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  133. // //echo "es操作成功";die;
  134. // }else {
  135. // 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);
  136. // }
  137. return ResultWrapper::success($payId);
  138. }
  139. private function createEsDocumentId($payId, $time)
  140. {
  141. $t = date('Y', $time) . '_' . ceil(date('m', $time) / 3);
  142. return 'EnterpriseId_' . $this->enterpriseId . '_' . $t .'_payId_' . $payId;
  143. }
  144. public function getPayInfo($params)
  145. {
  146. $suffix = date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3);
  147. $this->objDPay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
  148. unset($params['createTime']);
  149. $dbResult = $this->objDPay->get($params);
  150. if ($dbResult === false) {
  151. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  152. }
  153. if(!empty($dbResult)){
  154. //渲染前缀
  155. $dbResult['no'] = StatusCode::$noPrefix[18] . '-' . $dbResult['no'];
  156. $dbResult['purchaseNo'] = StatusCode::$noPrefix[2] . '-' . $dbResult['purchaseNo'];
  157. $dbResult['supplierCode'] = createCode(StatusCode::$code['supplier']['prefix'], $dbResult['supplierId'], StatusCode::$code['supplier']['length']);
  158. }
  159. return ResultWrapper::success($dbResult);
  160. }
  161. /**
  162. * 修改应付单核销状态
  163. */
  164. public function updateOffsetStatus($id,$offsetMoney,$createTime)
  165. {
  166. $suffix = date('Y', $createTime) . '_' . ceil(date('m', $createTime) / 3);
  167. $this->objDPay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
  168. $shouldPayData = $this->objDPay->get($id);
  169. if ($shouldPayData === false) {
  170. $this->objDPay->rollBack();
  171. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  172. }
  173. if( empty($shouldPayData) ){
  174. return ResultWrapper::fail('要审核的单据不存在', ErrorCode::$contentNotExists);
  175. }
  176. // $notOffsetMoney = bcsub($shouldPayData['payMoney'], $offsetMoney, 4);
  177. $updateData = [
  178. 'offsetMoney' => bcadd($shouldPayData['offsetMoney'],abs($offsetMoney),4),
  179. 'notOffsetMoney' => bcsub($shouldPayData['notOffsetMoney'], abs($offsetMoney),4),
  180. 'offsetStatus' => StatusCode::$delete
  181. ];
  182. switch (true)
  183. {
  184. case $updateData['notOffsetMoney'] == 0;
  185. $updateData['offsetStatus'] = StatusCode::$standard;
  186. break;
  187. case $updateData['notOffsetMoney'] == $shouldPayData['payMoney'];
  188. $updateData['offsetStatus'] = StatusCode::$delete;
  189. break;
  190. case $updateData['notOffsetMoney'] > 0 && $updateData['notOffsetMoney'] < $shouldPayData['payMoney'];
  191. $updateData['offsetStatus'] = StatusCode::$partion;
  192. break;
  193. }
  194. $beginTransactionStatus = $this->objDPay->beginTransaction();
  195. unset($dbResult);
  196. $dbResult = $this->objDPay->update($updateData, $id);
  197. if ($dbResult === false) {
  198. $this->objDPay->rollBack();
  199. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  200. }
  201. //修改索引表状态
  202. unset($dbResult);
  203. $dbResult = $this->objDPayReceiptIndex->update(['offsetStatus' => $updateData['offsetStatus']], ['payReceiptId' => $id, 'createTime'=>$createTime]);
  204. if ($dbResult === false) {
  205. $this->objDPay->rollBack();
  206. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  207. }
  208. if($beginTransactionStatus){
  209. $this->objDPay->commit();
  210. }
  211. return ResultWrapper::success($dbResult);
  212. }
  213. /**
  214. * 应付单启用和禁用
  215. * @param array $params
  216. * @return ResultWrapper
  217. * @throws \Exception
  218. */
  219. public function updatePayStatus($params)
  220. {
  221. $suffix = date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3);
  222. $this->objDPay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
  223. $shouldPayData = $this->objDPay->get($params['id']);
  224. if ($shouldPayData === false) {
  225. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  226. }
  227. if( empty($shouldPayData) ){
  228. return ResultWrapper::fail('要审核的单据不存在', ErrorCode::$contentNotExists);
  229. }
  230. if( $shouldPayData['auditStatus'] == StatusCode::$auditStatus['auditPass'] ){
  231. return ResultWrapper::fail('该单据已经审核过了', ErrorCode::$notAllowAccess);
  232. }
  233. $this->objDPay->beginTransaction();
  234. $dbResult = $this->objDPay->update(['auditStatus' => StatusCode::$auditStatus['auditPass']], $params['id']);
  235. if ($dbResult === false) {
  236. $this->objDPay->rollBack();
  237. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  238. }
  239. //修改索引表状态
  240. $dbResult = $this->objDPayReceiptIndex->update(['auditStatus' => StatusCode::$auditStatus['auditPass']], ['payReceiptId' => $params['id']]);
  241. if ($dbResult === false) {
  242. $this->objDPay->rollBack();
  243. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  244. }
  245. //供应商余额明细
  246. $supplierMoney = $this->objMSupplierBalance->getSupplierBalance($shouldPayData['supplierId']);
  247. //自动核销
  248. $autoOffset = self::autoOffset($supplierMoney,$params['id'],$params['createTime']);
  249. if (!$autoOffset->isSuccess()) {
  250. $this->objDPay->rollBack();
  251. return ResultWrapper::fail($autoOffset->getData(), $autoOffset->getErrorCode());
  252. }
  253. $detailData = [
  254. 'supplierId' => $shouldPayData['supplierId'],
  255. 'receiptTime' => $shouldPayData['createTime'],//'单据日期',
  256. 'no' => $shouldPayData['no'],//'单据编号',
  257. 'financeType' => $shouldPayData['financeType'],//'财务类型名称',
  258. 'financeTypeId' => $shouldPayData['financeTypeId'],//'财务类型id',
  259. 'sourceNo' => $shouldPayData['sourceNo'],
  260. 'salesAmount' => bcadd($shouldPayData['payMoney'], $shouldPayData['discountMoney'], 4),
  261. 'discountMoney' => $shouldPayData['discountMoney'],// '优惠金额',
  262. 'supplierAmount' => 0.00,
  263. 'shouldPayAmount' => $shouldPayData['payMoney'],//实际应付金额
  264. 'actualPaidAmount' => 0.00,
  265. 'shouldPayBalance' => bcadd($supplierMoney,$shouldPayData['payMoney'],2),//应付款余额
  266. 'remark' => '应付单审核通过,应付供应商'.$shouldPayData['payMoney'].'元',//'备注',
  267. 'createTime' => time(),//'创建日期',
  268. 'updateTime' => time(),//'修改日期',
  269. ];
  270. //供应商余额明细
  271. $result = $this->objMSupplierBalanceDetail->addSupplierBalanceDetail($detailData);
  272. if ($result->isSuccess() === false) {
  273. $this->objDPay->rollBack();
  274. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  275. }
  276. //供应商余额
  277. //$changedMoney = $shouldPayData['payMoney'] > 0 ? $shouldPayData['payMoney'] : -1*$shouldPayData['payMoney'];
  278. $changedMoney = $shouldPayData['payMoney'];
  279. $result = $this->objMSupplierBalance->addSupplierBalance($shouldPayData['supplierId'], $changedMoney);
  280. if ($result->isSuccess() === false) {
  281. $this->objDPay->rollBack();
  282. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  283. }
  284. $this->objDPay->commit();
  285. /*
  286. $_id = self::createEsDocumentId($params['id'], $params['createTime']);
  287. $this->objDPay->esupdateTypeFieldVaule(['auditStatus'=>StatusCode::$auditStatus['auditPass']], $_id);
  288. */
  289. return ResultWrapper::success($dbResult);
  290. }
  291. /**
  292. * 获取所有应付单数据
  293. * @param array $selectParams 过滤条件
  294. * @return ResultWrapper
  295. * @throws \Exception
  296. */
  297. public function getAllPay($selectParams, $isExport = false)
  298. {
  299. $limit = $selectParams['limit'];
  300. $offset = $selectParams['offset'];
  301. unset($selectParams['limit']);
  302. unset($selectParams['offset']);
  303. // 导出动作
  304. if($isExport){
  305. $limit = 9999;
  306. $offset = 0;
  307. }
  308. $whereSql = '';
  309. if (isset($selectParams['supplierId']) && !empty($selectParams['supplierId'])) {
  310. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  311. $whereSql .= $where . ' supplierId = ' . $selectParams['supplierId'];
  312. }
  313. // 原单据搜索
  314. if (isset($selectParams['sourceNo']) && !empty($selectParams['sourceNo'])) {
  315. $tmpNo = explode('-',$selectParams['sourceNo']);
  316. if(count($tmpNo) == 3){
  317. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  318. $whereSql .= $where . ' sourceNo like "%' . $tmpNo[1].'-'.$tmpNo[2].'%"';
  319. }else{
  320. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  321. $whereSql .= $where . ' sourceNo like "%' . $selectParams['sourceNo'].'%"';
  322. }
  323. }
  324. if (isset($selectParams['offsetStatus']) && !empty($selectParams['offsetStatus'])) {
  325. // if(is_array($selectParams['offsetStatus'])){
  326. // 数组转字符串
  327. $selectParams['offsetStatus'] = implode(',',$selectParams['offsetStatus']);
  328. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  329. $whereSql .= $where . ' offsetStatus in( ' . $selectParams['offsetStatus'].')';
  330. // }
  331. }
  332. if (isset($selectParams['payReceiptIds']) && !empty($selectParams['payReceiptIds'])) {
  333. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  334. $whereSql .= $where . ' payReceiptId in (' . implode(',', $selectParams['payReceiptIds']).')';
  335. }
  336. if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
  337. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  338. $whereSql .= $where . ' auditStatus = ' . $selectParams['auditStatus'];
  339. }
  340. if (isset($selectParams['warehouseId']) && !empty($selectParams['warehouseId'])) {
  341. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  342. $whereSql .= $where . ' warehouseId = ' . $selectParams['warehouseId'];
  343. }
  344. if ( (isset($selectParams['start']) && !empty($selectParams['start']))&&(isset($selectParams['end']) && !empty($selectParams['end'])) ) {
  345. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  346. $whereSql .= $where . ' createTime BETWEEN ' . $selectParams['start'] . ' AND '. $selectParams['end'];
  347. }
  348. $sql = 'SELECT * FROM ' .$this->objDPayReceiptIndex->get_Table().$whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
  349. $PayReceiptIndexResult = $this->objDPayReceiptIndex->query($sql);
  350. if($PayReceiptIndexResult === false){
  351. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  352. }
  353. $tableSuffix = [];
  354. foreach ($PayReceiptIndexResult as $PayReceiptIndex) {
  355. $k = date('Y', $PayReceiptIndex['createTime']) . '_' . ceil(date('m', $PayReceiptIndex['createTime']) / 3);
  356. $tableSuffix[$k][] = $PayReceiptIndex['id'];
  357. }
  358. $PayReceiptResult = [];
  359. foreach ($tableSuffix as $suffix => $payReceiptIds) {
  360. $this->objDPay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
  361. if($isExport){
  362. $dbResult = $this->objDPay->exportSelect($payReceiptIds, '*', 'createTime desc');
  363. $tmpArray = [];
  364. foreach($dbResult as $key => $value){
  365. $tmpArray[] = $value;
  366. }
  367. $dbResult = $tmpArray;
  368. }else{
  369. $dbResult = $this->objDPay->select(['id'=>$payReceiptIds], '*', 'createTime desc');
  370. //$dbResult = $this->objDPay->select(['supplierId' => $selectParams['supplierId']], '*', 'createTime desc');
  371. }
  372. if ($dbResult === false) {
  373. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  374. }
  375. if(!empty($dbResult)){
  376. //渲染前缀
  377. foreach ($dbResult as $key => $value){
  378. $dbResult[$key]['no'] = StatusCode::$noPrefix[18] . '-' . $value['no'];
  379. $dbResult[$key]['sourceNo'] = StatusCode::$noPrefix[3] . '-' . $value['sourceNo'];
  380. $dbResult[$key]['purchaseNo'] = StatusCode::$noPrefix[2] . '-' . $value['purchaseNo'];
  381. }
  382. $PayReceiptResult = array_merge($PayReceiptResult, self::format($dbResult));
  383. }
  384. }
  385. //$total = $this->objDPayReceiptIndex->count($selectParams);
  386. $totalSql = 'SELECT COUNT(1) as count FROM ' .$this->objDPayReceiptIndex->get_Table() . $whereSql;
  387. $dbTotalResult = $this->objDPayReceiptIndex->query($totalSql);
  388. if ($dbTotalResult === false) {
  389. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  390. }
  391. if(empty($dbTotalResult)){
  392. return ResultWrapper::success([]);
  393. }
  394. $return = [
  395. 'data' => $PayReceiptResult,
  396. 'total' => ($dbTotalResult[0]['count']) ? intval($dbTotalResult[0]['count']) : 0,
  397. ];
  398. if($isExport){
  399. self::export($return['data']);
  400. }
  401. return ResultWrapper::success($return);
  402. }
  403. /**
  404. * 审核成功调用(预充余额)
  405. * @param array $params
  406. * @return ResultWrapper
  407. * @throws \Exception
  408. */
  409. public function autoOffset($supplierMoney, $payId, $createTime)
  410. {
  411. $suffix = date('Y', $createTime) . '_' . ceil(date('m', $createTime) / 3);
  412. $this->objDPay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
  413. $this->objDPaid->setTable('qianniao_paid_' . $this->enterpriseId . '_' . date('Y', $createTime) . '_' . ceil(date('m', $createTime) / 3));
  414. //根据id查出客户id(查询客户表有无预付款)
  415. $shouldPayData = $this->objDPay->get($payId);
  416. if ($shouldPayData === false) {
  417. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  418. }
  419. if (empty($shouldPayData)) {
  420. return ResultWrapper::fail('应收单id'.$payId.'数据为空', ErrorCode::$dberror);
  421. }
  422. $offsetMoney = 0;
  423. $notOffsetMoney = 0;
  424. $offsetStatus = 5;
  425. if ($supplierMoney < 0 && $shouldPayData['payMoney'] > 0){//说明供应商是预收款进行自动核销
  426. switch (true)
  427. {
  428. case bcsub(abs($supplierMoney),$shouldPayData['payMoney'],4) > 0;//说明预收款完全核销应收单金额
  429. $offsetMoney = $shouldPayData['payMoney'];
  430. break;
  431. case bcsub(abs($supplierMoney),$shouldPayData['payMoney'],4) == 0;//说明预收款刚好完全核销
  432. $offsetMoney = $shouldPayData['payMoney'];
  433. break;
  434. case bcsub(abs($supplierMoney),$shouldPayData['payMoney'],4) < 0;//说明预收款不够核销应收单金额
  435. $offsetMoney = abs($supplierMoney);
  436. $notOffsetMoney = bcadd($supplierMoney,$shouldPayData['payMoney'],4);
  437. $offsetStatus = StatusCode::$partion;
  438. }
  439. //更新应付单核销状态
  440. $updateOffsetStatus = $this->objDPay->update(['offsetMoney'=>$offsetMoney,'notOffsetMoney'=>$notOffsetMoney,'offsetStatus'=>$offsetStatus],['id'=>$payId]);
  441. if ($updateOffsetStatus === false) {
  442. $this->objDPay->rollBack();
  443. return ResultWrapper::fail($this->objDPay->error(), ErrorCode::$dberror);
  444. }
  445. //更新应付单索引表核销状态
  446. unset($dbResult);
  447. $dbResult = $this->objDPayReceiptIndex->update(['offsetStatus' => $offsetStatus], ['payReceiptId' => $payId,'createTime'=>$createTime]);
  448. if ($dbResult === false) {
  449. $this->objDPay->rollBack();
  450. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  451. }
  452. unset($dbResult);
  453. //查询付款单,找到能核销的
  454. $dbResult = $this->objDPaid->query('select * from '.$this->objDPaid->get_Table().' where supplierId='.$shouldPayData['supplierId'].' and offsetStatus != '. StatusCode::$standard.' order by createTime asc');
  455. if ($dbResult === false) {
  456. return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
  457. }
  458. $paidOffsetMoney = $shouldPayData['payMoney'];
  459. foreach ($dbResult as $key => $value){
  460. if($paidOffsetMoney<=0){
  461. break;
  462. }
  463. switch (true){
  464. case bcsub($value['notOffsetMoney'],$shouldPayData['payMoney'],2)>0: // 说明收款单能完全核销应收
  465. $paidOffset = [
  466. 'offsetMoney' => bcadd($paidOffsetMoney,$value['offsetMoney'],2),
  467. 'notOffsetMoney' => bcsub($value['notOffsetMoney'],$paidOffsetMoney,2),
  468. 'offsetStatus' => StatusCode::$partion,
  469. ];
  470. $paidOffsetMoney = abs(bcsub($paidOffsetMoney,$paidOffset['offsetMoney'],2));
  471. break;
  472. case bcsub($value['notOffsetMoney'],$shouldPayData['payMoney'],2) == 0: // 说明收款单能完全核销应收
  473. $paidOffset = [
  474. 'offsetMoney' => $value['totalFinalMoney'],
  475. 'notOffsetMoney' => 0,
  476. 'offsetStatus' => StatusCode::$standard,
  477. ];
  478. $paidOffsetMoney = abs(bcsub($value['totalFinalMoney'],$paidOffset['offsetMoney'],2));
  479. break;
  480. case bcsub($value['notOffsetMoney'],$shouldPayData['payMoney'],2) < 0: // 说明收款单不能完全核销应收
  481. $paidOffset = [
  482. 'offsetMoney' => $value['totalFinalMoney'],
  483. 'notOffsetMoney' => 0,
  484. 'offsetStatus' => StatusCode::$standard,
  485. ];
  486. $paidOffsetMoney = abs(bcsub($value['totalFinalMoney'],$paidOffset['offsetMoney'],2));
  487. }
  488. // 更新核销
  489. $updatePaidOffset = $this->objDPaid->update($paidOffset,['id'=>$value['id']]);
  490. if ($updatePaidOffset === false) {
  491. $this->objDPay->rollBack();
  492. return ResultWrapper::fail($this->objDPaid->error(), ErrorCode::$dberror);
  493. }
  494. //记录核销明细
  495. $updateOffset = [
  496. 'payReceiptId' => $payId,
  497. 'paidId' => $value['id'],
  498. 'offsetMoney' => $offsetMoney,
  499. 'payCreateTime' => $shouldPayData['createTime'],
  500. // 'type' => StatusCode::$delete
  501. ];
  502. $result = $this->objDPaidOffset->insert($updateOffset);
  503. if ($result === false) {
  504. $this->objDPay->rollBack();
  505. return ResultWrapper::fail($this->objDPaidOffset->error(), ErrorCode::$dberror);
  506. }
  507. }
  508. }
  509. //报错修改
  510. //return ResultWrapper::success($dbResult);
  511. return ResultWrapper::success(null);
  512. }
  513. /**
  514. * 导出方法
  515. *
  516. * @param $exportData
  517. */
  518. private static function export($exportData)
  519. {
  520. //导出到本地
  521. header("Content-type:application/vnd.ms-excel");
  522. header("Content-Disposition:filename=应收单列表.csv");
  523. header('Cache-Control: max-age=0');
  524. $fp = fopen('php://output', 'a');
  525. $head = ['应付单编号', '源订单号', '供应商名称', '单据日期', '优惠金额', '实际应付金额', '商铺', '单据类型', '状态']; //定义标题
  526. foreach ($head as $i => $v) {
  527. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  528. }
  529. fputcsv($fp, $head);
  530. $limit = 10000;
  531. $num = 0;//计数器
  532. foreach ($exportData as $v) {
  533. //循环数据
  534. $num++;
  535. if ($num == $limit) {
  536. ob_flush();//释放内存
  537. flush();
  538. }
  539. $rows['no'] = $v['no'];
  540. $rows['sourceNo'] = $v['sourceNo'];
  541. $rows['supplierName'] = $v['supplierName'];
  542. $rows['createTime'] = date('Y-m-d H:i:s', $v['createTime']);
  543. $rows['discountMoney'] = $v['discountMoney'];
  544. $rows['payMoney'] = $v['payMoney'];
  545. $rows['shopName'] = $v['shopName'];
  546. $rows['receiptTypeName'] = $v['receiptTypeId'] ? '采购订单' : '采购退货单';
  547. $rows['auditStatus'] = StatusCode::$auditStatus[$v['auditStatus']];
  548. foreach ($rows as $kk => $vv) {
  549. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  550. }
  551. fputcsv($fp, $rs);
  552. $rows = [];
  553. }
  554. exit;
  555. }
  556. public function format($data)
  557. {
  558. foreach ($data as $k => $v) {
  559. $data[$k]['supplierCode'] = createCode(StatusCode::$code['supplier']['prefix'], $v['supplierId'], StatusCode::$code['supplier']['length']);
  560. }
  561. return $data;
  562. }
  563. //搜索的where条件拼接
  564. public function setWhere($selectParams)
  565. {
  566. $defaultDSL = [
  567. 'from' => $selectParams['offset'],
  568. 'size' => $selectParams['limit'],
  569. 'sort' => [
  570. 'createTime' => [
  571. 'order' => 'desc'
  572. ],
  573. ],
  574. ];
  575. $dsl = [];
  576. $dsl['query']['bool']['must'][] = [
  577. 'term' => ['enterpriseId' => $this->enterpriseId],
  578. ];
  579. if (isset($selectParams['keyword'])) {
  580. if (!empty($selectParams['keyword'])) {
  581. $dsl['query']['bool']['must'][] = [
  582. 'multi_match' => [
  583. 'fields' => ['no', 'sourceNo', 'customerName'],
  584. 'query' => $selectParams['keyword'],
  585. 'fuzziness' => 'AUTO',
  586. ]
  587. ];
  588. }
  589. }
  590. if (!empty($selectParams['shopId'])) {
  591. $dsl['query']['bool']['must'][] = [
  592. 'term' => ['shopId' => $selectParams['shopId']],
  593. ];
  594. }
  595. if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
  596. $dsl['query']['bool']['must'][] = [
  597. 'range' => [
  598. 'createTime' => [
  599. 'gte' => $selectParams['start'],
  600. 'lte' => strtotime(date('Y-m-d',$selectParams['end']).'23:59:59'),
  601. ]
  602. ]
  603. ];
  604. } else {
  605. if (!empty($selectParams['start'])) {
  606. $dsl['query']['bool']['must'][] = [
  607. 'range' => [
  608. 'createTime' => [
  609. 'gte' => $selectParams['start'],
  610. ]
  611. ]
  612. ];
  613. }
  614. if (!empty($selectParams['end'])) {
  615. $dsl['query']['bool']['must'][] = [
  616. 'range' => [
  617. 'createTime' => [
  618. 'lte' => strtotime(date('Y-m-d',$selectParams['end']).'23:59:59'),
  619. ]
  620. ]
  621. ];
  622. }
  623. }
  624. if (isset($selectParams['receiptTypeId'])) {
  625. if (!empty($selectParams['receiptTypeId'])) {
  626. $dsl['query']['bool']['filter'][] =
  627. ['term' => ['receiptTypeId' => $selectParams['receiptTypeId']]];
  628. }
  629. }
  630. if (isset($selectParams['auditStatus'])) {
  631. if (!empty($selectParams['auditStatus'])) {
  632. $dsl['query']['bool']['filter'][] =
  633. ['term' => ['auditStatus' => $selectParams['auditStatus']]];
  634. }
  635. }
  636. $dsl = array_merge($defaultDSL, $dsl);
  637. return $dsl;
  638. }
  639. public function search($selectParams)
  640. {
  641. $is_export = $selectParams['isExport'];
  642. unset($selectParams['isExport']);
  643. if($is_export){
  644. unset($selectParams['limit']);
  645. unset($selectParams['offset']);
  646. }
  647. $dsl = $this->setWhere($selectParams);
  648. //导出
  649. if ($is_export) self::exportSearch($dsl);
  650. $result = $this->objDPay->getSearchQueryDsl($dsl);
  651. if (isset($result['status']) && $result['status'] == 400) {
  652. if ($result['error']['reason'] == 'all shards failed') {
  653. return ResultWrapper::success([
  654. 'data' => [],
  655. 'total' => 0
  656. ]);
  657. }
  658. return ResultWrapper::fail('获取应付数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  659. }
  660. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  661. return ResultWrapper::success([
  662. 'data' => [],
  663. 'total' => 0
  664. ]);
  665. }
  666. $total = $result['hits']['total'];
  667. $dbResult = $result['hits']['hits'];
  668. $list = [];
  669. foreach ($dbResult as $key => &$value) {
  670. $data = [];
  671. $data = $value['_source'];
  672. $list[] = $data;
  673. }
  674. $return = [
  675. 'data' => self::format($list),
  676. 'total' => ($total) ? intval($total) : 0,
  677. ];
  678. return ResultWrapper::success($return);
  679. }
  680. /**
  681. * 检索导出(ES)
  682. *
  683. * @param $dsl
  684. * @return ResultWrapper
  685. * @throws \Exception
  686. */
  687. private function exportSearch($dsl)
  688. {
  689. $result = $this->objDPay->getScrollSearchQueryDsl($dsl);
  690. if (isset($result['status']) && $result['status'] == 400) {
  691. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  692. }
  693. if (!isset($result['hits']) && $result['hits']['total'] == 0) {
  694. return ResultWrapper::fail('导出数据为空' . $result['error']['reason'], ErrorCode::$apiNotResult);
  695. }
  696. $dbResult = $result['hits']['hits'];
  697. $list = [];
  698. foreach ($dbResult as $key => &$value) {
  699. $list[] = $value['_source'];
  700. }
  701. self::export($list);
  702. }
  703. /**
  704. * 查询所有未审核的应付单
  705. */
  706. public function getAllAuditingPay()
  707. {
  708. $condition = [
  709. 'deleteStatus' => StatusCode::$standard,
  710. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  711. ];
  712. $result = $this->objDPayReceiptIndex->select($condition);
  713. if ($result === false) {
  714. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  715. }
  716. if(empty($result)){
  717. return ResultWrapper::success([]);
  718. }
  719. return ResultWrapper::success($result);
  720. }
  721. }