MCustomerBalance.Class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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\Controller\Common\Logger;
  11. use JinDouYun\Dao\Finance\DReceive;
  12. use JinDouYun\Dao\Finance\DReceived;
  13. use JinDouYun\Dao\Finance\DReceivedIndex;
  14. use JinDouYun\Dao\Finance\DReceiveReceiptIndex;
  15. use Mall\Framework\Core\ErrorCode;
  16. use Mall\Framework\Core\StatusCode;
  17. use Mall\Framework\Core\ResultWrapper;
  18. use JinDouYun\Model\MBaseModel;
  19. use JinDouYun\Dao\Finance\DCustomerBalance;
  20. use JinDouYun\Dao\Finance\DCustomerBalanceIndex;
  21. use JinDouYun\Dao\Customer\DCustomer;
  22. use JinDouYun\Model\Customer\MCustomer;
  23. use JinDouYun\Cache\OverviewCache;
  24. class MCustomerBalance extends MBaseModel
  25. {
  26. private $objDCustomerBalance;
  27. private $objDCustomerBalanceIndex;
  28. private $objDCustomer;
  29. private $objMCustomer;
  30. private $objOverviewCache;
  31. private $enterpriseId;
  32. private $userCenterId;
  33. private $cutTable = 200000;
  34. public function __construct($enterpriseId, $userCenterId)
  35. {
  36. $this->userCenterId = $userCenterId;
  37. $this->enterpriseId = $enterpriseId;
  38. parent::__construct($enterpriseId, $userCenterId);
  39. $this->objDCustomerBalance = new DCustomerBalance('finance');
  40. $this->objDCustomerBalanceIndex = new DCustomerBalanceIndex('finance');
  41. $this->objDCustomer = new DCustomer('default');
  42. $this->objMCustomer = new MCustomer($enterpriseId, $userCenterId);
  43. $this->objOverviewCache = new OverviewCache();
  44. $this->objDCustomerBalanceIndex->setTable('qianniao_customer_balance_index_' . $enterpriseId);
  45. $this->objDCustomer->setTable('qianniao_customer_' . $enterpriseId);
  46. }
  47. /**
  48. * 添加客户余额
  49. * @param int $customerId
  50. * @param int $changedMoney
  51. * @return ResultWrapper
  52. * @throws \Exception
  53. */
  54. public function addCustomerBalance($customerId, $changedMoney)
  55. {
  56. $tableName = $this->objDCustomerBalance->getTableName('qianniao_customer_balance_' . $this->enterpriseId, $customerId, $this->cutTable);
  57. $this->objDCustomerBalance->setTable($tableName);
  58. //获取客户目前的余额
  59. $money = $this->objDCustomer->get_field('money', $customerId);
  60. //新增一条客户余额
  61. $balanceData = [
  62. 'customerId' => $customerId,
  63. 'openingBalance' => $money,
  64. 'interimBalance' => $changedMoney,
  65. 'endingBalance' => bcadd($money, $changedMoney, 4),
  66. 'createTime' => time(),
  67. 'updateTime' => time()
  68. ];
  69. var_dump("xxx");
  70. $detailId = $this->objDCustomerBalance->insert($balanceData);
  71. if ($detailId === false) {
  72. return ResultWrapper::fail($this->objDCustomerBalance->error(), ErrorCode::$dberror);
  73. }
  74. //新增一条客户余额索引数据
  75. $indexData = [
  76. 'customerId' => $customerId,
  77. 'detailId' => $detailId,
  78. 'createTime' => time(),
  79. 'updateTime' => time()
  80. ];
  81. $indexId = $this->objDCustomerBalanceIndex->insert($indexData);
  82. if ($indexId === false) {
  83. return ResultWrapper::fail($this->objDCustomerBalanceIndex->error(), ErrorCode::$dberror);
  84. }
  85. var_dump("aaa");
  86. //更新客户的最新余额
  87. $result = self::updateCustomerBalance($customerId, $changedMoney);
  88. var_dump("bbb");
  89. if ($result->isSuccess() === false) {
  90. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  91. }
  92. var_dump("cccs");
  93. return ResultWrapper::success($result->getData());
  94. }
  95. /**
  96. * 获取某一日期的余额
  97. * @param $time
  98. * @return int
  99. * @throws \Exception
  100. */
  101. public function getShouldReceiveMoneyByTime($time, $customerId)
  102. {
  103. $tableName = $this->objDCustomerBalanceIndex->get_Table();
  104. $sql = "select * from $tableName where createTime <= $time AND customerId = $customerId order by id desc limit 1";
  105. $result = $this->objDCustomerBalanceIndex->query($sql);
  106. if (empty($result)) {
  107. //没有发生过应收应付
  108. return 0;
  109. }
  110. $data = array_shift($result);
  111. $tableName = $this->objDCustomerBalance->getTableName('qianniao_customer_balance_' . $this->enterpriseId, $customerId, $this->cutTable);
  112. $this->objDCustomerBalance->setTable($tableName);
  113. return $this->objDCustomerBalance->get_field('endingBalance', $data['detailId']);
  114. }
  115. /**
  116. * 获取所有客户余额数据
  117. * @param array $selectParams 过滤条件
  118. * @return ResultWrapper
  119. * @throws \Exception
  120. */
  121. public function getAllCustomerBalance($selectParams,$export = 0)
  122. {
  123. $limit = $selectParams['limit'];
  124. unset($selectParams['limit']);
  125. $offset = $selectParams['offset'];
  126. unset($selectParams['offset']);
  127. if($export){
  128. $limit = null;
  129. $offset = null;
  130. }
  131. $customerId = $selectParams['customerId'];
  132. unset($selectParams['customerId']);
  133. $tag = $selectParams['tag'];
  134. unset($selectParams['tag']);
  135. $start = $selectParams['start'];
  136. unset($selectParams['start']);
  137. $end = $selectParams['end'];
  138. unset($selectParams['end']);
  139. //默认进来不筛选,查出客户当前的余额
  140. if (!$start && !$end) {
  141. $where = ['limit' => $limit, 'offset' => $offset];
  142. if ($customerId) {
  143. $where['id'] = $customerId;
  144. }
  145. if (!empty($tag)) {
  146. $where['tag'] = $tag;
  147. }
  148. $result = $this->objMCustomer->getCustomerMoney($where);
  149. if ($result->isSuccess() === false) {
  150. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  151. }
  152. // if (!$start && !$end)情况下导出
  153. if($export){
  154. self::exportCustomerBalance($result->getData()['data']);
  155. exit;
  156. }
  157. return ResultWrapper::success($result->getData());
  158. }
  159. //期初余额
  160. $startResult = self::getShouldReceiveMoneyByTime($start, $customerId);
  161. //期末余额
  162. $endResult = self::getShouldReceiveMoneyByTime($end, $customerId);
  163. // 销售金额 / 收款金额
  164. $saleResult = self::getSaleMoneyByTime($start,$end,$customerId);
  165. $customerName = $this->objDCustomer->get($customerId);
  166. $return = [
  167. 'data' => [
  168. [
  169. 'customerId' => $customerId,
  170. 'name' => $customerName['name'],
  171. 'memberBalance' => $customerName['memberBalance'],
  172. 'openingBalance' => $startResult,
  173. 'saleMoney'=>$saleResult['saleMoney'],
  174. 'collectionMoney'=>$saleResult['collectionMoney'],
  175. 'endingBalance' => $endResult
  176. ]
  177. ],
  178. 'total' => 1,
  179. ];
  180. //导出
  181. if($export){
  182. self::exportCustomerBalance($return['data']);
  183. exit;
  184. }
  185. return ResultWrapper::success($return);
  186. }
  187. private function format($data)
  188. {
  189. $customerIds = [];
  190. foreach ($data as $k => $v) {
  191. $customerIds[] = $v['customerId'];
  192. }
  193. $customerInfo = $this->objMCustomer->getCustomer(array_unique($customerIds));
  194. $customerData = $customerInfo->getData();
  195. foreach ($data as $k => $v) {
  196. $data[$k]['customerName'] = isset($customerData[$v['customerId']]) ? $customerData[$v['customerId']]['name'] : '';
  197. }
  198. return $data;
  199. }
  200. /**
  201. * 修改客户余额
  202. * @param $customerId
  203. * @param $changedMoney
  204. * @return ResultWrapper
  205. */
  206. public function updateCustomerBalance($customerId, $changedMoney)
  207. {
  208. $dbResult = $this->objDCustomer->set_inc('money', $customerId, $changedMoney);
  209. if ($dbResult === false) {
  210. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  211. }
  212. //修改应收款总金额
  213. $this->objOverviewCache->saveAggregateStatistics($this->enterpriseId, 'totalShouldReceive', $changedMoney);
  214. return ResultWrapper::success($dbResult);
  215. }
  216. /**
  217. * 修改客户付款总额
  218. * @param $customerId
  219. * @param $money
  220. * @return ResultWrapper
  221. */
  222. public function updateCustomerTotalPayMoney($customerId, $money)
  223. {
  224. $dbResult = $this->objDCustomer->set_inc('totalPayMoney', $customerId, $money);
  225. if ($dbResult === false) {
  226. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  227. }
  228. return ResultWrapper::success($dbResult);
  229. }
  230. /**
  231. * 获取客户余额
  232. * @param $customerId
  233. * @return ResultWrapper
  234. */
  235. public function getCustomerBalance($customerId, $field = 'money')
  236. {
  237. $money = $this->objDCustomer->get_field($field, $customerId);
  238. return $money ? $money : 0;
  239. }
  240. /**
  241. * 导出方法
  242. * @param $result
  243. * @return void
  244. * @throws Exception
  245. */
  246. public function exportCustomerBalance($result)
  247. {
  248. //导出到本地
  249. header("Content-type:application/vnd.ms-excel");
  250. header("Content-Disposition:filename=客户往来汇总表记录表.csv");
  251. header('Cache-Control: max-age=0');
  252. $fp = fopen('php://output', 'a');
  253. $head = ['客户名称','初期余额','销售金额','收款金额','期末金额' ,'会员余额']; //定义标题
  254. foreach ($head as $i => $v) {
  255. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  256. }
  257. fputcsv($fp, $head);
  258. $limit = 10000;
  259. $num = 0; //计数器
  260. foreach ($result as $v) {//循环数据
  261. $num++;
  262. if ($num == $limit) {
  263. ob_flush(); //释放内存
  264. flush();
  265. }
  266. $rows['name'] = isset($v['name']) ? $v['name'] : '';//客户名称
  267. $rows['openingBalance'] = isset($v['openingBalance']) ? $v['openingBalance'] : '';//初期余额
  268. $rows['interimBalance1'] = isset($v['interimBalance']) ? $v['interimBalance'] : '';//销售金额
  269. $rows['interimBalance2'] = isset($v['interimBalance']) ? $v['interimBalance'] : '';//收款金额
  270. $rows['endingBalance'] = isset($v['endingBalance']) ? $v['endingBalance'] : '';//期末金额$rows['openingBalance']+$rows['interimBalance']-$rows['interimBalance'];//期末金额 应该是期初+销售-收款=期末
  271. $rows['interimBalance3'] = isset($v['interimBalance']) ? $v['interimBalance'] : '';//会员余额
  272. foreach ($rows as $kk => $vv) {
  273. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  274. }
  275. fputcsv($fp, $rs);
  276. $rows = [];
  277. }
  278. }
  279. /**
  280. * 根据时间获取销售金额,收款金额
  281. */
  282. public function getSaleMoneyByTime($start,$end,$customerId)
  283. {
  284. $saleMoney = 0;// 销售金额
  285. $collectionMoney = 0;// 收款金额
  286. $objReceiveTable = new DReceive('finance');
  287. $objReceivedTable = new DReceived('finance');
  288. $objReceiveIndexTable = new DReceiveReceiptIndex('finance');
  289. $objReceiveIndexTable->setTable('qianniao_receive_receipt_index_'.$this->enterpriseId);
  290. $objReceivedIndexTable = new DReceivedIndex('finance');
  291. $objReceivedIndexTable->setTable('qianniao_received_index_'.$this->enterpriseId);
  292. $receiveIndexSql = 'select * from '.$objReceiveIndexTable->get_Table().' WHERE createTime BETWEEN '.$start.' AND '.$end .' AND customerId='.$customerId .' AND offsetStatus='.StatusCode::$standard;
  293. $receiveIndexDate = $objReceiveIndexTable->query($receiveIndexSql);
  294. if($receiveIndexDate === false){
  295. return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
  296. }
  297. if(!empty($receiveIndexDate)){
  298. foreach ($receiveIndexDate as $receiveKey => $receiveValue){
  299. $suffix = date('Y', $receiveValue['createTime']) . '_' . ceil(date('m', $receiveValue['createTime']) / 3);
  300. $objReceiveTable->setTable('qianniao_receive_receipt_' . $this->enterpriseId . '_' . $suffix);
  301. $receiveDate = $objReceiveTable->get($receiveValue['id']);
  302. $saleMoney = bcadd($saleMoney,$receiveDate['receiveMoney'],2);
  303. }
  304. }
  305. $receivedIndexSql = 'select * from '.$objReceivedIndexTable->get_Table().' WHERE createTime BETWEEN '.$start.' AND '.$end.' AND customerId='.$customerId .' AND offsetStatus='.StatusCode::$standard;
  306. $receivedIndexDate = $objReceivedIndexTable->query($receivedIndexSql);
  307. if($receiveIndexDate === false){
  308. return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
  309. }
  310. if(!empty($receivedIndexDate)){
  311. foreach ($receivedIndexDate as $receivedKey => $receivedValue){
  312. $objReceivedTable->setTable('qianniao_received_' . $this->enterpriseId . '_' . date('Y', $receivedValue['createTime']) . '_' . ceil(date('m', $receivedValue['createTime']) / 3));
  313. $receivedDate = $objReceivedTable->get($receivedValue['id']);
  314. $collectionMoney = bcadd($collectionMoney,isset($receivedDate['totalFinalMoney']) ? $receivedDate['totalFinalMoney'] :0,2);
  315. }
  316. }
  317. return [
  318. 'saleMoney'=>$saleMoney,
  319. 'collectionMoney'=>$collectionMoney
  320. ];
  321. }
  322. }