Contract.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 商业智能-员工业绩分析
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\bi\controller;
  8. use app\admin\controller\ApiCommon;
  9. use app\bi\traits\SortTrait;
  10. use app\crm\model\Contract as ContractModel;
  11. use app\crm\model\Receivables as ReceivablesModel;
  12. use think\Db;
  13. use think\Hook;
  14. use think\Request;
  15. use app\bi\logic\ExcelLogic;
  16. class Contract extends ApiCommon
  17. {
  18. use SortTrait;
  19. /**
  20. * 用于判断权限
  21. * @permission 无限制
  22. * @allow 登录用户可访问
  23. * @other 其他根据系统设置
  24. **/
  25. public function _initialize()
  26. {
  27. $action = [
  28. 'permission' => [''],
  29. 'allow' => [
  30. 'analysis',
  31. 'summary',
  32. 'invoice',
  33. 'excelexport'
  34. ]
  35. ];
  36. Hook::listen('check_auth', $action);
  37. $request = Request::instance();
  38. $a = strtolower($request->action());
  39. if (!in_array($a, $action['permission'])) {
  40. parent::_initialize();
  41. }
  42. if (!checkPerByAction('bi', 'contract', 'read')) {
  43. header('Content-Type:application/json; charset=utf-8');
  44. exit(json_encode(['code' => 102, 'error' => '无权操作']));
  45. }
  46. }
  47. /**
  48. * 合同数量分析/金额分析/回款金额分析
  49. *
  50. * @param string $param
  51. * @return array|\think\response\Json
  52. * @throws \think\db\exception\DataNotFoundException
  53. * @throws \think\db\exception\ModelNotFoundException
  54. * @throws \think\exception\DbException
  55. */
  56. public function analysis($param='')
  57. {
  58. $userModel = new \app\admin\model\User();
  59. $adminModel = new \app\admin\model\Admin();
  60. if ($param['excel_type'] != 1) {
  61. $param = $this->param;
  62. }
  63. $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); // 权限范围内userIds
  64. $whereArr = $adminModel->getWhere($param, '', $perUserIds); // 统计条件
  65. $userIds = $whereArr['userIds'];
  66. $year = !empty($param['year']) ? $param['year'] : date('Y');
  67. $start_time = strtotime(date(($year - 1) . '-01-01'));
  68. $end_time = strtotime('+2 year', $start_time) - 1;
  69. $time = getTimeArray($start_time, $end_time);
  70. if ($param['type'] == 'back' || $param['excel_type'] == 'back') {
  71. $model = new ReceivablesModel;
  72. $time_field = 'return_time';
  73. } else {
  74. $model = new ContractModel;
  75. $time_field = 'order_date';
  76. }
  77. if ($param['type'] == 'count' || $param['$excel_type'] == 'count') {
  78. $field['COUNT(*)'] = 'total';
  79. } else {
  80. $field['SUM(`money`)'] = 'total';
  81. }
  82. $between_time = [date('Y-m-d', $time['between'][0]), date('Y-m-d', $time['between'][1])];
  83. $field["SUBSTR(`{$time_field}`, 1, 7)"] = 'type';
  84. $sql = $model->field($field)
  85. ->where([
  86. 'owner_user_id' => ['IN', $userIds],
  87. 'check_status' => 2,
  88. $time_field => ['BETWEEN', $between_time]
  89. ])
  90. ->group('type')
  91. ->fetchSql()
  92. ->select();
  93. $res = queryCache($sql);
  94. $res = array_column($res, null, 'type');
  95. $data = [];
  96. for ($i = 12; $i < 24; $i++) {
  97. $k = $time['list'][$i]['type'];
  98. $k2 = $time['list'][$i - 1]['type'];
  99. $k3 = $time['list'][$i - 12]['type'];
  100. $item['month'] = ($i - 11) < 10 ? $param['year']. '0' . $i - 11 : $param['year'] . $i - 11;
  101. $item['thisMonth'] = $res[$k] ? $res[$k]['total'] : 0; # 本月
  102. $item['lastMonthGrowth'] = $res[$k2] ? $res[$k2]['total'] : 0; # 上月
  103. $item['lastYearGrowth'] = $res[$k3] ? $res[$k3]['total'] : 0; # 上年本月
  104. # 环比
  105. $item['chain_ratio'] = $item['thisMonth'] && $item['lastMonthGrowth'] ? round(($item['thisMonth'] / $item['lastMonthGrowth']) * 100, 4) : 0;
  106. # 同比
  107. $item['year_on_year'] = $item['thisMonth'] && $item['lastYearGrowth'] ? round(($item['thisMonth'] / $item['lastYearGrowth']) * 100, 4) : 0;
  108. $data[] = $item;
  109. }
  110. //导出使用
  111. if (!empty($param['excel_type'])) {
  112. return $data;
  113. }
  114. return resultArray(['data' => $data]);
  115. }
  116. /**
  117. * 合同汇总表
  118. *
  119. * @return \think\response\Json
  120. * @throws \think\db\exception\DataNotFoundException
  121. * @throws \think\db\exception\ModelNotFoundException
  122. * @throws \think\exception\DbException
  123. */
  124. public function summary($param='')
  125. {
  126. $userModel = new \app\admin\model\User();
  127. $adminModel = new \app\admin\model\Admin();
  128. if($param['excel_type']!=1){
  129. $param = $this->param;
  130. }
  131. $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); //权限范围内userIds
  132. $whereArr = $adminModel->getWhere($param, '', $perUserIds); //统计条件
  133. $userIds = $whereArr['userIds'];
  134. if (empty($param['type']) && empty($param['start_time'])) {
  135. $param['type'] = 'month';
  136. }
  137. $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
  138. $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
  139. unset($param['sort_field']);
  140. unset($param['sort_value']);
  141. $year = !empty($param['year']) ? $param['year'] : date('Y');
  142. $start_time = strtotime($year . '-01-01');
  143. $end_time = strtotime('+1 year', $start_time) - 1;
  144. $time = getTimeArray($start_time, $end_time);
  145. $ax = 7;
  146. if ($time['time_format'] == '%Y-%m-%d') {
  147. $ax = 10;
  148. }
  149. $between_time = [date('Y-m-d', $time['between'][0]), date('Y-m-d', $time['between'][1])];
  150. $sql = ContractModel::field([
  151. 'SUBSTR(`order_date`, 1, ' . $ax . ')' => 'type',
  152. 'COUNT(*)' => 'count',
  153. 'SUM(`money`)' => 'money'
  154. ])
  155. ->where([
  156. 'owner_user_id' => ['IN', $userIds],
  157. 'check_status' => 2,
  158. 'order_date' => ['BETWEEN', $between_time]
  159. ])
  160. ->group('type')
  161. ->fetchSql()
  162. ->select();
  163. $contract_data = queryCache($sql);
  164. $contract_data = array_column($contract_data, null, 'type');
  165. $sql = ReceivablesModel::field([
  166. 'SUBSTR(`return_time`, 1, ' . $ax . ')' => 'type',
  167. 'SUM(`money`)' => 'money'
  168. ])
  169. ->where([
  170. 'owner_user_id' => ['IN', $userIds],
  171. 'check_status' => 2,
  172. 'return_time' => ['BETWEEN', $between_time]
  173. ])
  174. ->group('type')
  175. ->fetchSql()
  176. ->select();
  177. $receivables_data = queryCache($sql);
  178. $receivables_data = array_column($receivables_data, null, 'type');
  179. $items = [];
  180. $count_zong = 0;
  181. $money_zong = 0;
  182. $back_zong = 0;
  183. foreach ($time['list'] as $val) {
  184. $item = ['type' => $val['type']];
  185. $count_zong += $item['count'] = $contract_data[$val['type']]['count'] ?: 0;
  186. $money_zong += $item['money'] = $contract_data[$val['type']]['money'] ?: 0;
  187. $back_zong += $item['back'] = $receivables_data[$val['type']]['money'] ?: 0;
  188. $items[] = $item;
  189. }
  190. $data = [
  191. 'list' => $items,
  192. 'count_zong' => $count_zong,
  193. 'money_zong' => $money_zong,
  194. 'back_zong' => $back_zong,
  195. 'w_back_zong' => $money_zong - $back_zong,
  196. ];
  197. if (!empty($data['list'])) $data['list'] = $this->sortCommon($data['list'], $sortField, $sortValue);
  198. //导出使用
  199. if (!empty($param['excel_type'])) return $data;
  200. return resultArray(['data' => $data]);
  201. }
  202. /**
  203. * 发票统计分析
  204. *
  205. * @return \think\response\Json
  206. * @throws \think\db\exception\DataNotFoundException
  207. * @throws \think\db\exception\ModelNotFoundException
  208. * @throws \think\exception\DbException
  209. */
  210. public function invoice($param='')
  211. {
  212. $userModel = new \app\admin\model\User();
  213. $adminModel = new \app\admin\model\Admin();
  214. if($param['excel_type']!=1){
  215. $param = $this->param;
  216. }
  217. $perUserIds = $userModel->getUserByPer('bi', 'contract', 'read'); //权限范围内userIds
  218. $whereArr = $adminModel->getWhere($param, '', $perUserIds); //统计条件
  219. $userIds = $whereArr['userIds'];
  220. if (empty($param['type']) && empty($param['start_time'])) {
  221. $param['type'] = 'month';
  222. }
  223. $sortField = !empty($param['sort_field']) ? $param['sort_field'] : '';
  224. $sortValue = !empty($param['sort_value']) ? $param['sort_value'] : '';
  225. unset($param['sort_field']);
  226. unset($param['sort_value']);
  227. $time = getTimeArray();
  228. $ax = 7;
  229. if ($time['time_format'] == '%Y-%m-%d') {
  230. $ax = 10;
  231. }
  232. $between_time = [date('Y-m-d', $time['between'][0]), date('Y-m-d', $time['between'][1])];
  233. $sql = Db::name('crm_invoice')->field([
  234. 'SUBSTR(`invoice_date`, 1, ' . $ax . ')' => 'type',
  235. 'SUM(`invoice_money`)' => 'money'
  236. ])
  237. ->where([
  238. 'owner_user_id' => ['IN', $userIds],
  239. 'check_status' => 2,
  240. 'invoice_status' => 1,
  241. 'invoice_date' => ['BETWEEN', $between_time]
  242. ])
  243. ->group('type')
  244. ->fetchSql()
  245. ->select();
  246. $invoice_data = queryCache($sql);
  247. $invoice_data = array_column($invoice_data, null, 'type');
  248. $sql = ReceivablesModel::field([
  249. 'SUBSTR(`return_time`, 1, ' . $ax . ')' => 'type',
  250. 'SUM(`money`)' => 'money'
  251. ])
  252. ->where([
  253. 'owner_user_id' => ['IN', $userIds],
  254. 'check_status' => 2,
  255. 'return_time' => ['BETWEEN', $between_time]
  256. ])
  257. ->group('type')
  258. ->fetchSql()
  259. ->select();
  260. $receivables_data = queryCache($sql);
  261. $receivables_data = array_column($receivables_data, null, 'type');
  262. $items = [];
  263. $invoiceCount = 0;
  264. $receivablesCount = 0;
  265. foreach ($time['list'] as $val) {
  266. $receivablesModel = !empty($receivables_data[$val['type']]['money']) ? $receivables_data[$val['type']]['money'] : 0;
  267. $invoiceModel = !empty($invoice_data[$val['type']]['money']) ? $invoice_data[$val['type']]['money'] : 0;
  268. $items[] = [
  269. 'type' => $val['type'],
  270. 'receivables_money' => $receivablesModel,
  271. 'invoice_money' => $invoiceModel,
  272. 'not_invoice' => $receivablesModel - $invoiceModel > 0 ? $receivablesModel - $invoiceModel : 0,
  273. 'not_receivables' => $invoiceModel - $receivablesModel > 0 ? $invoiceModel - $receivablesModel : 0
  274. ];
  275. $invoiceCount += $invoiceModel;
  276. $receivablesCount += $receivablesModel;
  277. }
  278. $data = [
  279. 'list' => $items,
  280. 'receivables_count' => $receivablesCount,
  281. 'invoice_count' => $invoiceCount
  282. ];
  283. if (!empty($data['list'])) $data['list'] = $this->sortCommon($data['list'], $sortField, $sortValue);
  284. //导出使用
  285. if (!empty($param['excel_type'])) return $data;
  286. return resultArray(['data' => $data]);
  287. }
  288. /**
  289. * 导出
  290. * @param $type
  291. * @param $types
  292. */
  293. public function excelExport()
  294. {
  295. $param = $this->param;
  296. $excel_type = $param['excel_type'];
  297. $type=[];
  298. $type['excel_types']=$param['excel_types'];
  299. switch ($param['excel_types']) {
  300. case 'analysis':
  301. if ($param['type'] == 'count') {
  302. $type['type'] = '合同数量分析';
  303. } elseif ($param['type'] == 'back') {
  304. $type['type'] = '回款金额分析';
  305. } else {
  306. $type['type'] = '金额分析';
  307. }
  308. $list = $this->analysis($param);
  309. break;
  310. case 'summary':
  311. $list = $this->summary($excel_type);
  312. $list=$list['list'];
  313. $type['type'] = '合同汇总表';
  314. break;
  315. case 'invoice':
  316. $list = $this->invoice($excel_type);
  317. $list=$list['list'];
  318. $type['type'] = '发票统计分析表';
  319. break;
  320. }
  321. if(empty($list)){
  322. return resultArray(['data'=>'数据不存在']);
  323. }
  324. $excelLogic = new ExcelLogic();
  325. $data = $excelLogic->contractExcel($type, $list);
  326. return $data;
  327. }
  328. }