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