MRefund.Class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Gss
  5. * Date: 2021/4/8 0008
  6. * Time: 19:35
  7. */
  8. namespace JinDouYun\Model\Finance;
  9. use Jindouyun\Cache\EnterpriseCache;
  10. use JinDouYun\Dao\Customer\DCustomer;
  11. use JinDouYun\Dao\Order\DOrderIndex;
  12. use JinDouYun\Model\System\MSystemPushMessage;
  13. use Mall\Framework\Core\ErrorCode;
  14. use Mall\Framework\Core\StatusCode;
  15. use Mall\Framework\Core\ResultWrapper;
  16. use JinDouYun\Model\Order\MPay;
  17. use JinDouYun\Dao\Finance\DRefund;
  18. use JinDouYun\Dao\Finance\DRefundAccount;
  19. use JinDouYun\Dao\Finance\DRefundIndex;
  20. use JinDouYun\Dao\Order\DOrder;
  21. use JinDouYun\Dao\Finance\DPay;
  22. use JinDouYun\Dao\Finance\DPayReceiptIndex;
  23. use JinDouYun\Dao\Finance\DReceive;
  24. use JinDouYun\Dao\Finance\DReceiveReceiptIndex;
  25. use Util\WeiXin\Pay;
  26. class MRefund
  27. {
  28. private $enterpriseId;
  29. private $userCenterId;
  30. private $objDReceiveReceiptIndex;
  31. private $objDReceive;
  32. private $objDay;
  33. private $objDPayReceiptIndex;
  34. private $objDOrder;
  35. private $objDRefund;
  36. private $objDRefundIndex;
  37. private $objDRefundAccount;
  38. private $objMFinanceType;
  39. private $objMCustomerBalance;
  40. private $objMCustomerBalanceDetail;
  41. private $objMSupplierBalanceDetail;
  42. private $objMSupplierBalance;
  43. private $cutTable = 200000;
  44. /**
  45. * @param $enterpriseId
  46. * @param $userCenterId
  47. * @throws \Exception
  48. */
  49. public function __construct($enterpriseId, $userCenterId)
  50. {
  51. $this->userCenterId = $userCenterId;
  52. $this->enterpriseId = $enterpriseId;
  53. $this->objDReceive = new DReceive('finance');
  54. $this->objDReceiveReceiptIndex = new DReceiveReceiptIndex('finance');
  55. $this->objDay = new DPay('finance');
  56. $this->objDPayReceiptIndex = new DPayReceiptIndex('finance');
  57. $this->objDOrder = new DOrder();
  58. $this->objDRefund = new DRefund('finance');
  59. $this->objDRefundIndex = new DRefundIndex('finance');
  60. $this->objDRefundAccount = new DRefundAccount('finance');
  61. $this->objMFinanceType = new MFinanceType($enterpriseId, $userCenterId);
  62. $this->objMCustomerBalance = new MCustomerBalance($enterpriseId, $userCenterId);
  63. $this->objMCustomerBalanceDetail = new MCustomerBalanceDetail($enterpriseId,$userCenterId);
  64. $this->objMSupplierBalance = new MSupplierBalance($enterpriseId, $userCenterId);
  65. $this->objMSupplierBalanceDetail = new MSupplierBalanceDetail($enterpriseId, $userCenterId);
  66. // $this->objDReceiveOffset->setTable('qianniao_receive_offset_'. $enterpriseId);
  67. $this->objDRefund->setTable('qianniao_refund_' . $enterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3));
  68. $this->objDRefundAccount->setTable('qianniao_refund_account_' . $enterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3));
  69. $this->objDRefundIndex->setTable('qianniao_refund_index_' . $enterpriseId);
  70. $this->objDPayReceiptIndex->setTable('qianniao_pay_receipt_index_'.$this->enterpriseId);
  71. $this->objDReceiveReceiptIndex->setTable('qianniao_receive_receipt_index_'.$this->enterpriseId);
  72. }
  73. /**
  74. * 添加退款单
  75. */
  76. public function addRefund($params, $autoCheck= false)
  77. {
  78. $accountList = $params['accountList'];
  79. unset($params['accountList']);
  80. $beginTransactionStatus = $this->objDRefund->beginTransaction();
  81. // 生成编号
  82. $dbResult = $this->objDRefund->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
  83. if ($dbResult === false) {
  84. return ResultWrapper::fail($this->objDRefund->error(), ErrorCode::$dberror);
  85. }
  86. if(empty($dbResult)){
  87. $params['no'] = createSerialNumberByDate('');
  88. }else{
  89. $params['no'] = createSerialNumberByDate($dbResult['no']);
  90. }
  91. $refundId = $this->objDRefund->insert($params);
  92. if ($refundId === false) {
  93. $this->objDRefund->rollBack();
  94. return ResultWrapper::fail($this->objDRefund->error(), ErrorCode::$dberror);
  95. }
  96. //索引表数据
  97. $indexData = [
  98. 'no' => $params['no'],
  99. 'refundId' => $refundId,
  100. 'unitId' => isset($params['unitId']) ? isset($params['unitId']): '',
  101. 'originId' => isset($params['originId']) ? isset($params['originId']): '',
  102. 'originNo' => isset($params['originNo']) ? isset($params['originNo']): '',
  103. 'type' => getArrayItem($params,'type',''),
  104. 'payType' => getArrayItem($params,'payType',''),
  105. 'currentAccountName' => $params['currentAccountName'],//制单人
  106. 'sourceNo' => $params['sourceNo'],
  107. 'auditStatus' => $params['auditStatus'],
  108. 'financeTypeId' => $params['financeTypeId'],
  109. 'financeType' => $params['financeType'],
  110. 'createTime' => $params['createTime'],
  111. 'updateTime' => $params['updateTime'],
  112. 'refundTime' => $params['refundTime'],
  113. ];
  114. $result = $this->objDRefundIndex->insert($indexData);
  115. if ($result === false) {
  116. $this->objDRefund->rollBack();
  117. return ResultWrapper::fail($this->objDRefundIndex->error(), ErrorCode::$dberror);
  118. }
  119. unset($result);
  120. //收款账户数据
  121. foreach ($accountList as $account) {
  122. $account['operatorId'] = $this->userCenterId;
  123. $account['refundId'] = $refundId;
  124. $account = self::buildAccountData($account);
  125. $result = $this->objDRefundAccount->insert($account);
  126. if ($result === false) {
  127. $this->objDRefund->rollBack();
  128. return ResultWrapper::fail($this->objDRefundAccount->error(), ErrorCode::$dberror);
  129. }
  130. unset($result);
  131. }
  132. if( $beginTransactionStatus ){
  133. $this->objDRefund->commit();
  134. }
  135. return ResultWrapper::success($refundId);
  136. }
  137. public static function buildAccountData(array $params)
  138. {
  139. return [
  140. 'refundId' => isset($params['refundId']) ? $params['refundId'] : 0,
  141. 'accountId' => isset($params['accountId']) ? $params['accountId'] : 0,
  142. 'accountNumber' => isset($params['accountNumber']) ? $params['accountNumber'] : 0,
  143. 'accountName' => getArrayItem($params, 'accountName', ''),
  144. 'money' => isset($params['money']) ? $params['money'] : 0,
  145. 'payWay' => isset($params['payWay']) ? $params['payWay'] : 0,
  146. 'remark' => isset($params['remark']) ? $params['remark'] : '',
  147. 'createTime' => time(),
  148. 'updateTime' => time(),
  149. 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : 0,
  150. ];
  151. }
  152. /**
  153. * 修改退款单
  154. */
  155. public function editRefund($params)
  156. {
  157. $this->objDRefund->setTable('qianniao_refund_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
  158. $this->objDRefundAccount->setTable('qianniao_refund_account_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
  159. $beginTransactionstatus = $this->objDRefund->beginTransaction();
  160. $accountList = $params['accountList'];
  161. unset($params['accountList']);
  162. $params['money'] = 0;
  163. foreach ($accountList as $account) {
  164. $params['money'] += $account['money'];
  165. }
  166. $refundId = $params['id'];
  167. unset($params['id']);
  168. $dbResult = $this->objDRefund->update($params, $refundId);
  169. if ($dbResult === false) {
  170. $this->objDRefund->rollBack();
  171. return ResultWrapper::fail($this->objDRefund->error(), ErrorCode::$dberror);
  172. }
  173. //索引表数据
  174. $indexData = [
  175. 'refundId' => $refundId,
  176. 'unitId' => isset($params['unitId']) ? isset($params['unitId']): '',
  177. 'originId' => isset($params['originId']) ? isset($params['originId']): '',
  178. 'originNo' => isset($params['originNo']) ? isset($params['originNo']): '',
  179. 'type' => getArrayItem($params,'type',''),
  180. 'currentAccountName' => $params['currentAccountName'],
  181. 'no' => $params['no'],
  182. 'sourceNo' => $params['sourceNo'],
  183. 'auditStatus' => $params['auditStatus'],
  184. 'financeTypeId' => $params['financeTypeId'],
  185. 'financeType' => $params['financeType'],
  186. 'createTime' => $params['createTime'],
  187. 'updateTime' => $params['updateTime'],
  188. 'refundTime' => $params['refundTime'],
  189. ];
  190. $result = $this->objDRefundIndex->update($indexData,['refundId'=>$refundId]);
  191. if ($result === false) {
  192. $this->objDRefund->rollBack();
  193. return ResultWrapper::fail($this->objDRefundIndex->error(), ErrorCode::$dberror);
  194. }
  195. unset($result);
  196. //收款账户数据
  197. foreach ($accountList as $account) {
  198. if (isset($account['id'])) {
  199. $account['refundId'] = $refundId;
  200. $account['operatorId'] = $this->userCenterId;
  201. $account['updateTime'] = $params['updateTime'];
  202. $result = $this->objDRefundAccount->update($account, $account['id']);
  203. if ($result === false) {
  204. $this->objDRefund->rollBack();
  205. return ResultWrapper::fail($this->objDRefundAccount->error(), ErrorCode::$dberror);
  206. }
  207. unset($result);
  208. }
  209. }
  210. if($beginTransactionstatus){
  211. $this->objDRefund->commit();
  212. }
  213. return ResultWrapper::success($dbResult);
  214. }
  215. /**
  216. * 退款单审核
  217. */
  218. public function updateRefundStatus($params)
  219. {
  220. $this->objDRefund->setTable('qianniao_refund_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
  221. $this->objDRefundAccount->setTable('qianniao_refund_account_' . $this->enterpriseId . '_' . date('Y', $params['createTime']) . '_' . ceil(date('m', $params['createTime']) / 3));
  222. // 查询退款单数据
  223. $refundData = $this->objDRefund->get(['id' => $params['id']]);
  224. if ($refundData === false) {
  225. return ResultWrapper::fail($this->objDRefund->error(), ErrorCode::$dberror);
  226. }
  227. if(empty($refundData)){
  228. return ResultWrapper::fail('要操作得单据不存在', ErrorCode::$contentNotExists);
  229. }
  230. if($refundData['auditStatus'] == StatusCode:: $auditStatus['auditPass']){
  231. return ResultWrapper::fail('当前退款单已经审核过了', ErrorCode::$notAllowAccess);
  232. }
  233. // 1,根据退款单中的originId(来源订单id)查询订单的source来源是否为销售订单
  234. $orderIndexId = $refundData['originId'];
  235. $objDOrderIndex = new DOrderIndex('default');
  236. $objDOrderIndex->setTable('qianniao_order_index_' . $this->enterpriseId);
  237. $orderData = $objDOrderIndex->get($orderIndexId);
  238. if($orderData === false){
  239. return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
  240. }
  241. if( empty($orderData) ){
  242. return ResultWrapper::fail('该订单为空', ErrorCode::$contentNotExists);
  243. }
  244. // 根据订单的来源判断是否为销售订单
  245. if($orderData['source'] == StatusCode::$orderType['saleOrder']){
  246. // 根据客户id (customerId) 获取 openId
  247. $customerId = $orderData['customerId'];
  248. $objDCustomer = new DCustomer('default');
  249. $objDCustomer->setTable('qianniao_customer_' . $this->enterpriseId);
  250. $customerData = $objDCustomer->get($customerId);
  251. if($customerData === false){
  252. return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
  253. }
  254. if( empty($customerData) ){
  255. return ResultWrapper::fail('查找不到该客户数据', ErrorCode::$contentNotExists);
  256. }
  257. // 小程序订阅消息退款通知
  258. if (isset($customerData['openId']) && !empty($customerData['openId'])) {
  259. // 发送小程序订阅消息
  260. $sendMessageData = [
  261. 'time8' => ['value' => date('Y-m-d H:i:s',$orderData['createTime'])], // 下单时间
  262. 'character_string7' => ['value' => StatusCode::$noPrefix[1].'-'.$orderData['no']], // 订单编号
  263. 'amount9' => ['value' => '¥'.$refundData['money']], // 支付金额
  264. 'amount3' => ['value' => '¥'.$refundData['money']], // 退款金额
  265. 'thing1' => ['value' =>'退款成功(店主已同意退款)'], // 退款状态
  266. ];
  267. $objMSystemPushMessage = new MSystemPushMessage($this->userCenterId,$this->enterpriseId);
  268. $result = $objMSystemPushMessage->sendWeiXinPushMessage(7,$customerData['openId'],$sendMessageData);
  269. if (!$result->isSuccess()) {
  270. file_put_contents('/www/wwwroot/logs/api.junhailan.com/sendMessageError.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND);
  271. }
  272. }
  273. }
  274. $beginTransactionStatus = $this->objDRefund->beginTransaction();
  275. // 更新退款单审核状态
  276. $dbResult = $this->objDRefund->update(['auditStatus' => StatusCode:: $auditStatus['auditPass']], ['id' => $params['id']]);
  277. if ($dbResult === false) {
  278. $this->objDRefund->rollBack();
  279. return ResultWrapper::fail($this->objDRefund->error(), ErrorCode::$dberror);
  280. }
  281. // 更新退款单索引表审核状态
  282. $dbResult = $this->objDRefundIndex->update(['auditStatus' => StatusCode:: $auditStatus['auditPass']], ['refundId' => $params['id']]);
  283. if ($dbResult === false) {
  284. $this->objDRefund->rollBack();
  285. return ResultWrapper::fail($this->objDRefundIndex->error(), ErrorCode::$dberror);
  286. }
  287. if (isset($refundData['offsetId'])){//有核销id说明有应收单id
  288. //自动核销
  289. //self::autoMoney($refundData['offsetId'],$refundData['money'],$refundData['createTime'],$refundData['type']);
  290. }
  291. if ($refundData['type'] == StatusCode::$standard){//客户
  292. // 获取客户往来余额
  293. $customerBalance = $this->objMCustomerBalance->getCustomerBalance($refundData['unitId']);
  294. $detailData = [
  295. 'customerId' => $refundData['unitId'],//'客户id',
  296. 'receiptTime' => $refundData['createTime'],//'单据日期',
  297. 'sourceNo' => $refundData['no'],//'单据编号',
  298. 'sourceId' => $refundData['id'],//'单据编号',
  299. 'financeType' => $refundData['financeType'],//'财务类型名称',
  300. 'financeTypeId' => $refundData['financeTypeId'],//'财务类型id',
  301. 'originId' => $refundData['sourceId'], //
  302. 'originNo' => $refundData['sourceNo'],//
  303. 'salesAmount' => 0,//总金额
  304. 'discountMoney' => 0,// '优惠金额',
  305. 'customerAmount' => 0,// '客户承担金额',
  306. 'receivableAmount' => 0,// '应收金额',
  307. 'actualReceivableAmount' => 0,//'实际收款金额',
  308. 'refundMoney' => $refundData['money'],
  309. 'receivableBalance' => bcadd($customerBalance , $refundData['money'], 4),//'应收后余额',
  310. 'remark' => '退款单审核通过,本次退款' . $refundData['money'] . '元',//'备注',
  311. 'createTime' => time(),//'创建日期',
  312. 'updateTime' => time(),//'修改日期',
  313. ];
  314. // 添加客户往来余额明细
  315. $result = $this->objMCustomerBalanceDetail->addCustomerBalanceDetail($detailData);
  316. if (!$result->isSuccess()) {
  317. $this->objDRefund->rollBack();
  318. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  319. }
  320. // 编辑客户往来余额
  321. $changedMoney = $refundData['money'] < 0 ? -1 * $refundData['money'] : abs($refundData['money']);
  322. $result = $this->objMCustomerBalance->addCustomerBalance($refundData['unitId'], $changedMoney);
  323. if (!$result->isSuccess()) {
  324. $this->objDRefund->rollBack();
  325. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  326. }
  327. // 如果是订单生成的退款单,同步操作订单
  328. if ( !empty($refundData['originId']) && !empty($refundData['payType'])){
  329. // 获取订单outerTradeNo
  330. $tableName = $this->objDOrder->getTableName('qianniao_order_' . $this->enterpriseId, $this->userCenterId, $this->cutTable);
  331. $this->objDOrder->setTable($tableName);
  332. $orderDate = $this->objDOrder->get($refundData['originId']);
  333. if( $orderDate === false ){
  334. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  335. }
  336. if( empty($orderDate) ){
  337. return ResultWrapper::fail('查询指定订单数据为空', ErrorCode::$contentNotExists);
  338. }
  339. // 读取后台设置的退款返还方式
  340. $refundWay = StatusCode::$standard;
  341. $objEnterpriseCache = new EnterpriseCache();
  342. $enterSettingData = $objEnterpriseCache->getEnterpriseSetting($this->enterpriseId);
  343. if( isset($enterSettingData['returnWay'])){
  344. $refundWay = $enterSettingData['returnWay'];
  345. }
  346. // 进行退款操作
  347. $objMPay = new MPay($this->enterpriseId, $this->userCenterId);
  348. $result = $objMPay->refund($orderDate, false, $refundData, $refundWay);
  349. if(!$result->isSuccess()){
  350. $this->objDRefund->rollBack();
  351. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  352. }
  353. //判断退款金额
  354. if($refundData['money'] < $orderDate['payAmount']){
  355. $payStatus = StatusCode::$payStatus['partRefund'];
  356. }else{
  357. $payStatus = StatusCode::$payStatus['refund'];
  358. }
  359. // 修改订单支付状态为已经退款
  360. $updateData = [
  361. 'isRet' => StatusCode::$standard,
  362. 'retTime' => time(),
  363. 'retMoney' => $refundData['money'],
  364. 'payStatus' => $payStatus
  365. ];
  366. $dbResult = $this->objDOrder->update($updateData, $orderDate['id']);
  367. if($dbResult == false){
  368. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  369. }
  370. $objDOrderIndex = new DOrderIndex('default');
  371. $objDOrderIndex->setTable('qianniao_order_index_'.$this->enterpriseId);
  372. $updateData = [
  373. 'isRet' => StatusCode::$standard,
  374. 'payStatus' => $payStatus
  375. ];
  376. $orderIndex = $objDOrderIndex->update($updateData, $orderDate['id']);
  377. if ($orderIndex===false){
  378. return ResultWrapper::fail($objDOrderIndex->error(),ErrorCode::$dberror);
  379. }
  380. }
  381. }
  382. if($refundData['type'] == StatusCode::$delete){
  383. // 查询供应商当前的余额
  384. $supplierMoney = $this->objMSupplierBalance->getSupplierBalance($refundData['unitId']);
  385. // 组装供应商余额明细数据
  386. $detailData = [
  387. 'supplierId' => $refundData['unitId'],
  388. 'receiptTime' => $refundData['createTime'],//'单据日期',
  389. 'no' => $refundData['no'],//'单据编号',
  390. 'financeType' => $refundData['financeType'],//'财务类型名称',
  391. 'financeTypeId' => $refundData['financeTypeId'],//'财务类型id',
  392. 'sourceId' => $refundData['sourceId'], //
  393. 'sourceNo' => $refundData['sourceNo'],
  394. 'salesAmount' => $refundData['money'],
  395. 'discountMoney' => 0.00,// '优惠金额',
  396. 'supplierAmount' => 0.00,
  397. 'shouldPayAmount' => 0.00,//实际应付金额
  398. 'actualPaidAmount' => 0,
  399. 'refundMoney' => $refundData['money'],
  400. // 'actualPaidAmount' => $refundData['money'],
  401. // 'shouldPayBalance' => bcadd($supplierMoney,$refundData['money'],2),//应付款余额 当前供应商余额 + 退款金额
  402. 'shouldPayBalance' => 0, // 退款直接记录退款金额
  403. 'remark' => '退款单审核通过,应付供应商'.$refundData['payMoney'].'元',//'备注',
  404. 'createTime' => time(),//'创建日期',
  405. 'updateTime' => time(),//'修改日期',
  406. ];
  407. //供应商余额明细
  408. $result = $this->objMSupplierBalanceDetail->addSupplierBalanceDetail($detailData);
  409. if ($result->isSuccess() === false) {
  410. $this->objDRefund->rollBack();
  411. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  412. }
  413. //供应商余额
  414. $changedMoney = $refundData['money'];
  415. $changedMoney = $changedMoney > 0 ? -1 * $refundData['money'] : abs($refundData['money']);
  416. $result = $this->objMSupplierBalance->addSupplierBalance($refundData['unitId'], $changedMoney);
  417. if ($result->isSuccess() === false) {
  418. $this->objDRefund->rollBack();
  419. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  420. }
  421. }
  422. if ($beginTransactionStatus){
  423. $this->objDRefund->commit();
  424. }
  425. return ResultWrapper::success($dbResult);
  426. }
  427. /**
  428. * 自动核销退款单
  429. */
  430. public function autoMoney($offsetId,$money,$createTime,$type)
  431. {
  432. if($type == StatusCode::$standard){//type 5 说明是订单退款
  433. //查询负应收
  434. $suffix = date('Y', $createTime) . '_' . ceil(date('m', $createTime) / 3);
  435. $this->objDReceive->setTable('qianniao_receive_receipt_' . $this->enterpriseId . '_' . $suffix);
  436. $receiveDate = $this->objDReceive->get(['id'=>$offsetId]);
  437. if ($receiveDate === false) {
  438. return ResultWrapper::fail($this->objDReceive->error(), ErrorCode::$dberror);
  439. }
  440. if(empty($receiveDate)){
  441. return ResultWrapper::fail('要操作得应收单据不存在', ErrorCode::$contentNotExists);
  442. }
  443. //判断如果金额为负
  444. if($receiveDate['receiveMoney'] < 0){
  445. $updata = [ // 负应收没有核销金额一说
  446. // $offsetMoney = $money,
  447. // $notOffsetMoney = 0,
  448. 'offsetStatus' => StatusCode::$standard,
  449. ];
  450. $updataIndex = [
  451. 'offsetStatus' => StatusCode::$standard,
  452. ];
  453. $updataReceive = $this->objDReceive->update($updata,['id'=>$receiveDate['id']]);
  454. if ($updataReceive === false) {
  455. $this->objDRefund->rollBack();
  456. return ResultWrapper::fail($this->objDReceive->error(), ErrorCode::$dberror);
  457. }
  458. //更新index表核销状态
  459. $updataReceivesIndex = $this->objDReceiveReceiptIndex->update($updataIndex,['id'=>$receiveDate['id']]);
  460. if ($updataReceivesIndex === false) {
  461. $this->objDRefund->rollBack();
  462. return ResultWrapper::fail($this->objDReceiveReceiptIndex->error(), ErrorCode::$dberror);
  463. }
  464. }
  465. }else{// 说明是采购单
  466. //查询负应付
  467. $suffix = date('Y', $createTime) . '_' . ceil(date('m', $createTime) / 3);
  468. $this->objDay->setTable('qianniao_pay_receipt_' . $this->enterpriseId . '_' . $suffix);
  469. $payDate = $this->objDay->get(['id'=>$offsetId]);
  470. if ($payDate === false) {
  471. return ResultWrapper::fail($this->objDay->error(), ErrorCode::$dberror);
  472. }
  473. if(empty($payDate)){
  474. return ResultWrapper::fail('要操作得单据不存在', ErrorCode::$contentNotExists);
  475. }
  476. //判断如果金额为负,并且财务类型为采购退款单
  477. if($payDate['financeType'] == '采购退款单' && $payDate['payMoney'] == $money){
  478. $updata = [
  479. $offsetMoney = $money,
  480. $notOffsetMoney = 0,
  481. $offsetStatus = StatusCode::$standard,
  482. ];
  483. $updataIndex = [
  484. $offsetStatus = StatusCode::$standard,
  485. ];
  486. $updataPay = $this->objDay->update($updata,['id'=>$payDate['id']]);
  487. if ($updataPay === false) {
  488. $this->objDRefund->rollBack();
  489. return ResultWrapper::fail($this->objDay->error(), ErrorCode::$dberror);
  490. }
  491. //更新index表核销状态
  492. $updataPayIndex = $this->objDPayReceiptIndex->update($updataIndex,['id'=>$payDate['id']]);
  493. if ($updataPayIndex === false) {
  494. $this->objDRefund->rollBack();
  495. return ResultWrapper::fail($this->objDPayReceiptIndex->error(), ErrorCode::$dberror);
  496. }
  497. }
  498. }
  499. return ResultWrapper::success([]);
  500. }
  501. /**
  502. * 获取指定退款单信息
  503. * @throws \Exception
  504. */
  505. public function getRefundInfo($refundParams)
  506. {
  507. $this->objDRefund->setTable('qianniao_refund_' . $this->enterpriseId . '_' . date('Y', $refundParams['createTime']) . '_' . ceil(date('m', $refundParams['createTime']) / 3));
  508. $this->objDRefundAccount->setTable('qianniao_refund_account_' . $this->enterpriseId . '_' . date('Y', $refundParams['createTime']) . '_' . ceil(date('m', $refundParams['createTime']) / 3));
  509. $dbResult = $this->objDRefund->get($refundParams['id']);
  510. if ($dbResult === false) {
  511. return ResultWrapper::fail($this->objDRefund->error(), ErrorCode::$dberror);
  512. }
  513. //渲染前缀
  514. // $dbResult['no'] = StatusCode::$noPrefix[17] . '-' . $dbResult['no'];
  515. $accountData = $this->objDRefundAccount->select(['refundId' => $refundParams['id']]);
  516. if ($accountData === false) {
  517. return ResultWrapper::fail($this->objDRefundAccount->error(), ErrorCode::$dberror);
  518. }
  519. $accountData = array_shift($accountData);
  520. $dbResult['accountList'] = $accountData;
  521. //查出客户当前余额
  522. $dbResult['currentBalanceMoney'] = !empty($dbResult['unitId']) && $dbResult['type'] == 1 ? $this->objMCustomerBalance->getCustomerBalance($dbResult['unitId']) : 0;
  523. return ResultWrapper::success($dbResult);
  524. }
  525. /**
  526. * 后台所有收款单列表
  527. */
  528. public function getAllRefund($selectParams)
  529. {
  530. $limit = $selectParams['limit'];
  531. unset($selectParams['limit']);
  532. $offset = $selectParams['offset'];
  533. unset($selectParams['offset']);
  534. $type = $selectParams['type'];
  535. unset($selectParams['type']);
  536. //组装sql where条件
  537. $whereSql = '';
  538. if (isset($selectParams['no']) && !empty($selectParams['no'])) {
  539. //no编号切割
  540. $explodeNo = explode("-",$selectParams['no']);
  541. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  542. $whereSql .= $where . ' no = "' . $explodeNo[1] . '-' . $explodeNo[2] . '"';
  543. }
  544. if (isset($selectParams['financeTypeId']) && !empty($selectParams['financeTypeId'])) {
  545. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  546. $whereSql .= $where . ' financeTypeId = ' . $selectParams['financeTypeId'];
  547. }
  548. if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
  549. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  550. $whereSql .= $where . ' auditStatus = ' . $selectParams['auditStatus'];
  551. }
  552. if (isset($selectParams['unitId']) && !empty($selectParams['unitId'])) {
  553. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  554. $whereSql .= $where . ' unitId = ' . $selectParams['unitId'];
  555. }
  556. if (isset($selectParams['type']) && !empty($selectParams['type'])) {
  557. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  558. $whereSql .= $where . ' type = ' . $selectParams['type'];
  559. }
  560. if ( (isset($selectParams['start']) && !empty($selectParams['start']))&&(isset($selectParams['end']) && !empty($selectParams['end'])) ) {
  561. $where = empty($whereSql) ? ' WHERE ' : ' AND ';
  562. $whereSql .= $where . ' createTime BETWEEN ' . $selectParams['start'] . ' AND '. $selectParams['end'];
  563. }
  564. $sql = 'SELECT * FROM ' .$this->objDRefundIndex->get_Table(). $whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
  565. $refundIndexResult = $this->objDRefundIndex->query($sql);
  566. $tableSuffix = [];
  567. foreach ($refundIndexResult as $refundIndex) {
  568. $k = date('Y', $refundIndex['createTime']) . '_' . ceil(date('m', $refundIndex['createTime']) / 3);
  569. $tableSuffix[$k][] = $refundIndex['refundId'];
  570. }
  571. $refundResult = [];
  572. foreach ($tableSuffix as $suffix => $refundIds) {
  573. $this->objDRefund->setTable('qianniao_refund_' . $this->enterpriseId . '_' . $suffix);
  574. $dbResult = $this->objDRefund->select($refundIds, '*', 'createTime desc');
  575. if ($dbResult === false) {
  576. return ResultWrapper::fail($this->objDRefund->error(), ErrorCode::$dberror);
  577. }
  578. // if (!empty($dbResult)){
  579. // //渲染前缀
  580. // foreach ($dbResult as $key => $value){
  581. // $dbResult[$key]['no'] = StatusCode::$noPrefix[17] . '-' . $value['no'];
  582. // }
  583. // }
  584. $refundResult = array_merge($refundResult, $dbResult);
  585. }
  586. $totalSql = 'SELECT COUNT(1) as count FROM ' .$this->objDRefundIndex->get_Table() . $whereSql;
  587. $dbTotalResult = $this->objDRefundIndex->query($totalSql);
  588. if ($dbTotalResult === false) {
  589. return ResultWrapper::fail($this->objDRefundIndex->error(), ErrorCode::$dberror);
  590. }
  591. if(empty($dbTotalResult)){
  592. return ResultWrapper::success([]);
  593. }
  594. $return = [
  595. 'data' => self::format($refundResult),
  596. 'total' => $dbTotalResult[0]['count']
  597. ];
  598. return ResultWrapper::success($return);
  599. }
  600. public function format($data)
  601. {
  602. foreach( $data as $k => $v ){
  603. $data[$k]['no'] = StatusCode::$noPrefix[20].'-'.$v['no'];
  604. switch ($v['financeType']){
  605. case '订单退货退款':
  606. $data[$k]['originNo'] = StatusCode::$noPrefix[1].'-'.$v['originNo'];
  607. $data[$k]['sourceNo'] = StatusCode::$noPrefix[15].'-'.$v['sourceNo'];
  608. break;
  609. case '采购退货收款':
  610. $data[$k]['originNo'] = StatusCode::$noPrefix[2].'-'.$v['originNo'];
  611. $data[$k]['sourceNo'] = StatusCode::$noPrefix[4].'-'.$v['sourceNo'];
  612. break;
  613. case '订单完结退款':
  614. $data[$k]['originNo'] = StatusCode::$noPrefix[1].'-'.$v['originNo'];
  615. $data[$k]['sourceNo'] = StatusCode::$noPrefix[1].'-'.$v['sourceNo'];
  616. break;
  617. case '订单取消退款':
  618. $data[$k]['originNo'] = StatusCode::$noPrefix[1].'-'.$v['originNo'];
  619. $data[$k]['sourceNo'] = StatusCode::$noPrefix[1].'-'.$v['sourceNo'];
  620. }
  621. }
  622. return $data;
  623. }
  624. }