Receivables.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. <?php
  2. namespace app\admin\controller\qingdong\customer;
  3. use addons\qingdong\model\Flow;
  4. use addons\qingdong\model\FormField;
  5. use addons\qingdong\model\Staff;
  6. use addons\qingdong\model\ReceivablesPlan;
  7. use app\admin\controller\qingdong\Base;
  8. use app\common\library\Auth;
  9. use addons\qingdong\model\ExamineRecord;
  10. use addons\qingdong\model\Customer;
  11. use addons\qingdong\model\Form;
  12. use addons\qingdong\model\Contract;
  13. use addons\qingdong\model\ReceivablesOther;
  14. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  15. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  16. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  17. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  18. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  19. use think\Db;
  20. use think\Exception;
  21. /**
  22. * 回款管理
  23. * 操作文档:https://doc.fastadmin.net/qingdong
  24. * 软件介绍:https://www.fastadmin.net/store/qingdong.html
  25. * 售后微信:qingdong_crm
  26. */
  27. class Receivables extends Base {
  28. protected $relationSearch = true;
  29. protected $searchFields = 'id';
  30. /**
  31. * @var \addons\qingdong\model\Receivables
  32. */
  33. protected $model = null;
  34. public function _initialize() {
  35. parent::_initialize();
  36. $this->model = new \addons\qingdong\model\Receivables;
  37. }
  38. /**
  39. * 查看
  40. */
  41. public function index() {
  42. $this->request->filter(['strip_tags', 'trim']);
  43. if ($this->request->isAjax()) {
  44. //0:全部 1:我负责的 2:下属负责的
  45. $type = input('type',0);
  46. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  47. switch($type){
  48. case 1:
  49. $staff = Staff::info();
  50. $wheres['owner_staff_id'] = $staff->id;
  51. break;
  52. case 2:
  53. $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
  54. break;
  55. default:
  56. $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
  57. break;
  58. }
  59. $ids=[];
  60. $group_id=input('group_id');
  61. $staff_id=input('staff_id');
  62. if ($group_id) {//角色组
  63. $ids = Staff::getGroupStaffIds($group_id);
  64. }
  65. if ($staff_id) {
  66. $ids = $staff_id;
  67. }
  68. if ($group_id || $staff_id) {
  69. $wheres['owner_staff_id'] = ['in', $ids];
  70. }
  71. $list = $this->model->where($where)
  72. ->where($wheres)->with(['customer', 'contract','ownerStaff'])->order($sort, $order)->paginate($limit);
  73. $result = array("total" => $list->total(), "rows" => $list->items());
  74. return json($result);
  75. }
  76. $field = FormField::getFields(FormField::RECEIVABLES_TYPE);
  77. $this->assignconfig('fields', $field);
  78. return $this->view->fetch();
  79. }
  80. /**
  81. * 添加
  82. */
  83. public function add($ids=null) {
  84. if ($this->request->isPost()) {
  85. $params = $this->request->post("row/a");
  86. if ($params) {
  87. $params = $this->preExcludeFields($params);
  88. // 表单验证
  89. if (($result = $this->qingdongValidate($params, 'Receivables', 'create')) !== true) {
  90. $this->error($result);
  91. }
  92. $result = FormField::checkFields(FormField::RECEIVABLES_TYPE, $params);
  93. if ($result !== true) {
  94. $this->error($result);
  95. }
  96. if ($this->model->where(['number' => $params['number'], 'contract_id' => $params['contract_id']])->find()) {
  97. $this->error('回款编号已存在');
  98. }
  99. $contract=Contract::where(['id'=>$params['contract_id']])->find();
  100. if(empty($contract)){
  101. $this->error('合同不存在');
  102. }
  103. // if($contract['check_status'] != 2){
  104. // $this->error('当前合同未审核通过');
  105. // }
  106. $result = false;
  107. Db::startTrans();
  108. try {
  109. $params = Form::updateFormParams('examine', $params);
  110. $params['owner_staff_id'] = $contract['owner_staff_id'];
  111. $result=$this->model::createReceivables($params);
  112. Db::commit();
  113. } catch (Exception $e) {
  114. Db::rollback();
  115. $this->error($e->getMessage());
  116. }
  117. if ($result !== false) {
  118. $this->success();
  119. } else {
  120. $this->error(__('No rows were inserted'));
  121. }
  122. }
  123. $this->error(__('Parameter %s can not be empty', ''));
  124. }
  125. $staff=Staff::where([])->column('name','id');
  126. $this->assign('staff', $staff);
  127. $flow= Flow::getsteplist(Flow::RECEIVABLES_STATUS);
  128. if (empty($flow)) {
  129. $this->error('无可用审批流,请联系管理员','qingdong/work/flow');
  130. }
  131. $customer_id = input('customer_id');
  132. $contract_id = input('contract_id');
  133. $this->assign('contract_id', $contract_id);
  134. $this->assign('customer_id', $customer_id);
  135. $this->assign('customer', Customer::get($customer_id));
  136. $this->assign('contract', Contract::get($contract_id));
  137. $this->assign('flow',$flow);
  138. $this->view->assign('ids',$ids);
  139. $this->view->assign('form_data', Form::getDataValue('examine'));
  140. $this->assign('createNum', get_num('receivables'));
  141. return $this->view->fetch();
  142. }
  143. /**
  144. * 回款详情
  145. */
  146. public function detail($ids = null) {
  147. $row = $this->model->where(['id' => $ids])->with(['customer', 'contract','plan','ownerStaff'])->find();
  148. $status = [0 => '待审核', 1 => '审核中', 2 => '审核通过', 3 => '审核未通过', 4 => '撤销', 5 => '未提交'];
  149. $this->assign('status', $status);
  150. $row = $row->toArray();
  151. $row = ReceivablesOther::getOther($row);
  152. $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::RECEIVABLES_TYPE,$ids));
  153. $this->assign('flow',Flow::getstepdetail(Flow::RECEIVABLES_STATUS, $ids));
  154. $this->assign('row', $row);
  155. $this->assign('form_data', Form::getDataValue('examine',$row));
  156. $this->assign('ids', $ids);
  157. $this->assignconfig("idinfo", ['id' => $ids]);
  158. return $this->view->fetch();
  159. }
  160. /**
  161. * 删除
  162. */
  163. public function del($ids = "") {
  164. if (!$this->request->isPost()) {
  165. $this->error(__("Invalid parameters"));
  166. }
  167. $ids = $ids ? $ids : $this->request->post("ids");
  168. $row = $this->model->get($ids);
  169. $this->modelValidate = true;
  170. if (!$row) {
  171. $this->error(__('No Results were found'));
  172. }
  173. Auth::instance()->delete($row['id']);
  174. $this->success();
  175. }
  176. /**
  177. * 获取客户列表
  178. */
  179. public function getcustomer()
  180. {
  181. $pageSize = input('pageSize');
  182. $pageNumber = input('pageNumber');
  183. $where = [];
  184. if ($keyValue = $this->request->request("keyValue")) {
  185. $where['id'] = $keyValue;
  186. }
  187. $name = input('name');
  188. if (!empty($name)) {
  189. $where['name'] = ['like', '%' . $name . '%'];
  190. }
  191. $staff = Staff::info();
  192. $staff_id = $staff->id;
  193. $whereStaff = function ($query) use ($staff_id) {
  194. $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
  195. ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
  196. ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
  197. };
  198. $customer = Customer::where($whereStaff)->where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  199. return json(['list' => $customer->items(), 'total' => $customer->total()]);
  200. }
  201. /**
  202. * 获取合同列表
  203. */
  204. public function getcontract()
  205. {
  206. $pageSize = input('pageSize');
  207. $pageNumber = input('pageNumber');
  208. $customer_id = input('customer_id', 0);
  209. $where = [];
  210. if ($keyValue = $this->request->request("keyValue")) {
  211. $where['id'] = $keyValue;
  212. }
  213. $name = input('name');
  214. if(!empty($name)){
  215. $where['name'] = ['like','%'.$name.'%'];
  216. }
  217. $where['check_status'] = 2;
  218. $where['customer_id'] = $customer_id;
  219. $contacts = Contract::where($where)->field('id,name,num')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  220. $data = [];
  221. $item=$contacts->items();
  222. foreach ($item as $v) {
  223. $v->name=$v['num'] . "({$v['name']})";
  224. }
  225. return json(['list' => $item, 'total' =>$contacts->total()]);
  226. }
  227. /**
  228. * 获取审批人列表
  229. */
  230. public function getstaff(){
  231. $pageSize = input('pageSize');
  232. $pageNumber = input('pageNumber');
  233. $where = [];
  234. if ($keyValue = $this->request->request("keyValue")) {
  235. $where['id'] = ['in',$keyValue];
  236. }
  237. $name = input('name');
  238. if(!empty($name)){
  239. $where['name'] = ['like','%'.$name.'%'];
  240. }
  241. $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  242. return json(['list' => $staff->items(), 'total' => $staff->total()]);
  243. }
  244. /**
  245. * 导入回款信息
  246. * @return string|void
  247. */
  248. public function import()
  249. {
  250. set_time_limit(0);
  251. if ($this->request->isPost()) {
  252. $file = $this->request->request('file');
  253. if (!$file) {
  254. $this->error(__('Parameter %s can not be empty', 'file'));
  255. }
  256. $filePath = ROOT_PATH . 'public' . $file;
  257. if (!is_file($filePath)) {
  258. $this->error(__('No results were found'));
  259. }
  260. //实例化reader
  261. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  262. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  263. $this->error(__('Unknown data format'));
  264. }
  265. if ($ext === 'csv') {
  266. $file = fopen($filePath, 'r');
  267. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  268. $fp = fopen($filePath, "w");
  269. $n = 0;
  270. while ($line = fgets($file)) {
  271. $line = rtrim($line, "\n\r\0");
  272. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  273. if ($encoding != 'utf-8') {
  274. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  275. }
  276. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  277. fwrite($fp, $line . "\n");
  278. } else {
  279. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  280. }
  281. $n++;
  282. }
  283. fclose($file) || fclose($fp);
  284. $reader = new Csv();
  285. } elseif ($ext === 'xls') {
  286. $reader = new Xls();
  287. } else {
  288. $reader = new Xlsx();
  289. }
  290. if (!$PHPExcel = $reader->load($filePath)) {
  291. $this->error(__('Unknown data format'));
  292. }
  293. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  294. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  295. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  296. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  297. //开始读取数据
  298. $fields = [];
  299. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  300. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  301. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  302. $fields[$currentRow][] = $val;
  303. if ($val instanceof RichText) {//富文本转换字符串
  304. $val = $val->__toString();
  305. }
  306. $values[] = is_null($val) ? NULL : trim($val);
  307. }
  308. }
  309. if (!isset($fields[1])) {
  310. $this->error('导入文件第一行没有数据');
  311. }
  312. $lastid = $this->model->withTrashed()->order('id desc')->value('id');
  313. $lastid = $lastid + 5;//防止重复
  314. $contractRow = [];
  315. $errorInfo = [];
  316. $fieldnames = FormField::where(['types' => FormField::RECEIVABLES_TYPE])->column('field', 'name');
  317. if(!$fieldnames){
  318. $this->error('请在系统管理->字段管理中保存回款管理表单生成回款导入字段');
  319. }
  320. $customerNames=Customer::where([])->column('id,owner_staff_id','name');
  321. $contractNames=Contract::where([])->column('id,name,num','num');
  322. $fn = [];
  323. $nums=$this->model->where([])->column('number');
  324. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  325. $values = [];
  326. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  327. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  328. $values[] = is_null($val) ? '' : $val;
  329. }
  330. foreach ($values as $l) {
  331. $fn[] = $fieldnames[$l] ?? '';
  332. }
  333. }
  334. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  335. $values = [];
  336. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  337. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  338. if ($val instanceof RichText) {//富文本转换字符串
  339. $val = $val->__toString();
  340. }
  341. $values[] = is_null($val) ? NULL : trim($val);
  342. }
  343. $lastid++;
  344. $addReceivables = ['id' => $lastid];
  345. $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
  346. if(empty($customer)){
  347. $errorInfo[] = "第{$currentRow}行,客户名称不存在;";
  348. continue;
  349. }
  350. $contract=isset($contractNames[$values[1]])?$contractNames[$values[1]]:0;
  351. if(empty($contract)){
  352. $errorInfo[] = "第{$currentRow}行,合同编号不存在;";
  353. continue;
  354. }
  355. $addReceivables['contract_id']=$contract['id'];
  356. $addReceivables['customer_id']=$customer['id'];
  357. $addReceivables['owner_staff_id']=$customer['owner_staff_id'];
  358. $addReceivables['create_staff_id']=$customer['owner_staff_id'];
  359. foreach ($values as $kv => $value) {
  360. if (!isset($fn[$kv]) || empty($fn[$kv])) {
  361. continue;
  362. }
  363. $addReceivables[$fn[$kv]] = $value;
  364. }
  365. if (empty($addReceivables['number'])) {
  366. $errorInfo[] = "第{$currentRow}行,回款编号不能为空;";
  367. continue;
  368. }
  369. if (in_array($addReceivables['number'], $nums)) {
  370. $errorInfo[] = "第{$currentRow}行,回款编号`{$addReceivables['number']}`已存在;";
  371. continue;
  372. }
  373. $contractRow[] = $addReceivables;
  374. }
  375. if (!empty($errorInfo)) {
  376. $this->error(implode(',', $errorInfo));
  377. }
  378. Db::startTrans();
  379. try {
  380. $this->model::importReceivables($contractRow);
  381. Db::commit();
  382. } catch (Exception $e) {
  383. Db::rollback();
  384. $this->error($e->getMessage());
  385. }
  386. $this->success('导入成功');
  387. }
  388. return $this->view->fetch();
  389. }
  390. /**
  391. * 模板
  392. */
  393. public function template()
  394. {
  395. $title = [
  396. '客户名称',
  397. '合同编号',
  398. ];
  399. $contractData = Form::getDataValue(Form::RECEIVABLES_TYPE);
  400. foreach ($contractData as $val) {
  401. $title[] = $val['config']['label'];
  402. }
  403. $file = export_excel($title, [], '回款');
  404. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  405. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  406. header('Cache-Control: max-age=0');
  407. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  408. // 以下内容是excel文件的信息描述信息
  409. $obj->getProperties()->setTitle('导出文件'); //设置标题
  410. $obj->setActiveSheetIndex(0);
  411. $obj->getActiveSheet()->setTitle('导出文件');
  412. /* 循环读取每个单元格的数据 */
  413. $a = 'A';
  414. $currentSheet = $obj->getActiveSheet();
  415. foreach ($title as $key => $value) {
  416. //读取工作表1
  417. // 设置第一行加粗
  418. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  419. //这里是设置单元格的内容
  420. $currentSheet->getCell($a . '1')->setValue($value);
  421. $a++;
  422. }
  423. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  424. $PHPWriter->save('php://output');
  425. }
  426. /**
  427. * 导出信息
  428. */
  429. public function export()
  430. {
  431. $this->request->filter(['strip_tags', 'trim']);
  432. $ids = input('ids');
  433. $isall = input('isall',0);
  434. $wheres = array();
  435. //导出其中几条
  436. if (isset($ids)) {
  437. $wheres['id'] = array('in', $ids);
  438. }
  439. //导出全部
  440. if ($isall == 3) {
  441. unset($wheres['id']);
  442. }
  443. //0:全部 1:我负责的 2:下属负责的
  444. $type = input('type',0);
  445. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  446. switch($type){
  447. case 1:
  448. $staff = Staff::info();
  449. $wheres['owner_staff_id'] = $staff->id;
  450. break;
  451. case 2:
  452. $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
  453. break;
  454. default:
  455. $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
  456. break;
  457. }
  458. $list = $this->model->with(['customer', 'contract','ownerStaff','receivablesOther'])->where($where)->where($wheres)->order($sort, $order)->select();
  459. $list = collection($list)->toArray();
  460. if (!$list) {
  461. $this->error('无导出数据');
  462. }
  463. $title = [
  464. '序号',
  465. '客户名称',
  466. '合同名称',
  467. '合同编号',
  468. '负责人',
  469. '创建时间',
  470. ];
  471. $dataValue = Form::getDataValue(Form::RECEIVABLES_TYPE);
  472. foreach ($dataValue as $val) {
  473. $title[] = $val['config']['label'];
  474. }
  475. foreach ($list as $k => $v) {
  476. if($v['receivables_other']){//其他客户
  477. $other=$v['receivables_other']['otherdata'];
  478. $other=json_decode($other,true);
  479. $v = array_merge($v, $other);
  480. }
  481. $field = array(
  482. $v['id'],
  483. $v['customer']['name'] ?? '',
  484. $v['contract']['name'] ?? '',
  485. $v['contract']['num'] ?? '',
  486. $v['owner_staff']['name'] ?? '',
  487. $v['createtime'],
  488. );
  489. foreach ($dataValue as $val) {
  490. if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
  491. $field[] = $v[$val['id'] . '_str'] ?? '';
  492. } else {
  493. $field[] = ($v[$val['id']] ?? '');
  494. }
  495. }
  496. $data[] = $field;
  497. }
  498. $file = export_excel($title, $data, '回款');
  499. if ($file['filePath']) {
  500. $this->success('导出成功', '', $file);
  501. }
  502. $this->error('导出失败');
  503. }
  504. /*
  505. * 回款计划列表
  506. */
  507. public function plan(){
  508. $customer_id = input('customer_id');
  509. $contract_id = input('contract_id');
  510. $list= [];
  511. if($customer_id && $contract_id){
  512. $where['customer_id'] = $customer_id;
  513. $where['contract_id'] = $contract_id;
  514. $where['status'] = 0;
  515. $list = ReceivablesPlan::where($where)->select();
  516. }
  517. $this->success('请求成功','',$list);
  518. }
  519. }