MCustomerBalance.Class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. var_dump("aaa");
  72. if ($detailId === false) {
  73. return ResultWrapper::fail($this->objDCustomerBalance->error(), ErrorCode::$dberror);
  74. }
  75. //新增一条客户余额索引数据
  76. $indexData = [
  77. 'customerId' => $customerId,
  78. 'detailId' => $detailId,
  79. 'createTime' => time(),
  80. 'updateTime' => time()
  81. ];
  82. $indexId = $this->objDCustomerBalanceIndex->insert($indexData);
  83. if ($indexId === false) {
  84. return ResultWrapper::fail($this->objDCustomerBalanceIndex->error(), ErrorCode::$dberror);
  85. }
  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. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  209. }
  210. //修改应收款总金额
  211. $this->objOverviewCache->saveAggregateStatistics($this->enterpriseId, 'totalShouldReceive', $changedMoney);
  212. return ResultWrapper::success($dbResult);
  213. }
  214. /**
  215. * 修改客户付款总额
  216. * @param $customerId
  217. * @param $money
  218. * @return ResultWrapper
  219. */
  220. public function updateCustomerTotalPayMoney($customerId, $money)
  221. {
  222. $dbResult = $this->objDCustomer->set_inc('totalPayMoney', $customerId, $money);
  223. if ($dbResult === false) {
  224. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  225. }
  226. return ResultWrapper::success($dbResult);
  227. }
  228. /**
  229. * 获取客户余额
  230. * @param $customerId
  231. * @return ResultWrapper
  232. */
  233. public function getCustomerBalance($customerId, $field = 'money')
  234. {
  235. $money = $this->objDCustomer->get_field($field, $customerId);
  236. return $money ? $money : 0;
  237. }
  238. /**
  239. * 导出方法
  240. * @param $result
  241. * @return void
  242. * @throws Exception
  243. */
  244. public function exportCustomerBalance($result)
  245. {
  246. //导出到本地
  247. header("Content-type:application/vnd.ms-excel");
  248. header("Content-Disposition:filename=客户往来汇总表记录表.csv");
  249. header('Cache-Control: max-age=0');
  250. $fp = fopen('php://output', 'a');
  251. $head = ['客户名称','初期余额','销售金额','收款金额','期末金额' ,'会员余额']; //定义标题
  252. foreach ($head as $i => $v) {
  253. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  254. }
  255. fputcsv($fp, $head);
  256. $limit = 10000;
  257. $num = 0; //计数器
  258. foreach ($result as $v) {//循环数据
  259. $num++;
  260. if ($num == $limit) {
  261. ob_flush(); //释放内存
  262. flush();
  263. }
  264. $rows['name'] = isset($v['name']) ? $v['name'] : '';//客户名称
  265. $rows['openingBalance'] = isset($v['openingBalance']) ? $v['openingBalance'] : '';//初期余额
  266. $rows['interimBalance1'] = isset($v['interimBalance']) ? $v['interimBalance'] : '';//销售金额
  267. $rows['interimBalance2'] = isset($v['interimBalance']) ? $v['interimBalance'] : '';//收款金额
  268. $rows['endingBalance'] = isset($v['endingBalance']) ? $v['endingBalance'] : '';//期末金额$rows['openingBalance']+$rows['interimBalance']-$rows['interimBalance'];//期末金额 应该是期初+销售-收款=期末
  269. $rows['interimBalance3'] = isset($v['interimBalance']) ? $v['interimBalance'] : '';//会员余额
  270. foreach ($rows as $kk => $vv) {
  271. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  272. }
  273. fputcsv($fp, $rs);
  274. $rows = [];
  275. }
  276. }
  277. /**
  278. * 根据时间获取销售金额,收款金额
  279. */
  280. public function getSaleMoneyByTime($start,$end,$customerId)
  281. {
  282. $saleMoney = 0;// 销售金额
  283. $collectionMoney = 0;// 收款金额
  284. $objReceiveTable = new DReceive('finance');
  285. $objReceivedTable = new DReceived('finance');
  286. $objReceiveIndexTable = new DReceiveReceiptIndex('finance');
  287. $objReceiveIndexTable->setTable('qianniao_receive_receipt_index_'.$this->enterpriseId);
  288. $objReceivedIndexTable = new DReceivedIndex('finance');
  289. $objReceivedIndexTable->setTable('qianniao_received_index_'.$this->enterpriseId);
  290. $receiveIndexSql = 'select * from '.$objReceiveIndexTable->get_Table().' WHERE createTime BETWEEN '.$start.' AND '.$end .' AND customerId='.$customerId .' AND offsetStatus='.StatusCode::$standard;
  291. $receiveIndexDate = $objReceiveIndexTable->query($receiveIndexSql);
  292. if($receiveIndexDate === false){
  293. return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
  294. }
  295. if(!empty($receiveIndexDate)){
  296. foreach ($receiveIndexDate as $receiveKey => $receiveValue){
  297. $suffix = date('Y', $receiveValue['createTime']) . '_' . ceil(date('m', $receiveValue['createTime']) / 3);
  298. $objReceiveTable->setTable('qianniao_receive_receipt_' . $this->enterpriseId . '_' . $suffix);
  299. $receiveDate = $objReceiveTable->get($receiveValue['id']);
  300. $saleMoney = bcadd($saleMoney,$receiveDate['receiveMoney'],2);
  301. }
  302. }
  303. $receivedIndexSql = 'select * from '.$objReceivedIndexTable->get_Table().' WHERE createTime BETWEEN '.$start.' AND '.$end.' AND customerId='.$customerId .' AND offsetStatus='.StatusCode::$standard;
  304. $receivedIndexDate = $objReceivedIndexTable->query($receivedIndexSql);
  305. if($receiveIndexDate === false){
  306. return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
  307. }
  308. if(!empty($receivedIndexDate)){
  309. foreach ($receivedIndexDate as $receivedKey => $receivedValue){
  310. $objReceivedTable->setTable('qianniao_received_' . $this->enterpriseId . '_' . date('Y', $receivedValue['createTime']) . '_' . ceil(date('m', $receivedValue['createTime']) / 3));
  311. $receivedDate = $objReceivedTable->get($receivedValue['id']);
  312. $collectionMoney = bcadd($collectionMoney,isset($receivedDate['totalFinalMoney']) ? $receivedDate['totalFinalMoney'] :0,2);
  313. }
  314. }
  315. return [
  316. 'saleMoney'=>$saleMoney,
  317. 'collectionMoney'=>$collectionMoney
  318. ];
  319. }
  320. }