MCustomerBalance.Class.php 14 KB

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