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