Receivables.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. <?php
  2. namespace app\admin\controller\qingdongams\customer;
  3. use addons\qingdongams\model\Flow;
  4. use addons\qingdongams\model\FormField;
  5. use addons\qingdongams\model\Message;
  6. use addons\qingdongams\model\Staff;
  7. use app\admin\controller\qingdongams\Base;
  8. use app\common\library\Auth;
  9. use addons\qingdongams\model\ExamineRecord;
  10. use addons\qingdongams\model\Customer;
  11. use addons\qingdongams\model\Form;
  12. use addons\qingdongams\model\Contract;
  13. use addons\qingdongams\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. * @desc 操作文档:https://doc.fastadmin.net/qingdongams
  24. * @desc 软件介绍:https://www.fastadmin.net/store/qingdongams.html
  25. * @desc 售后微信:qingdong_crm
  26. */
  27. class Receivables extends Base {
  28. protected $relationSearch = true;
  29. protected $searchFields = 'id';
  30. /**
  31. * @var \addons\qingdongams\model\Receivables
  32. */
  33. protected $model = null;
  34. public function _initialize() {
  35. parent::_initialize();
  36. $this->model = new \addons\qingdongams\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->qingdongamsValidate($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('无可用审批流,请联系管理员');
  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. //标记通知已读
  153. Message::setRead(Message::RECEIVABLES_TYPE, $ids, $this->_staff->id);
  154. $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::RECEIVABLES_TYPE,$ids));
  155. $this->assign('flow',Flow::getstepdetail(Flow::RECEIVABLES_STATUS, $ids));
  156. $this->assign('row', $row);
  157. $this->assign('form_data', Form::getDataValue('examine',$row));
  158. $this->assign('ids', $ids);
  159. $this->assignconfig("idinfo", ['id' => $ids]);
  160. return $this->view->fetch();
  161. }
  162. /**
  163. * 删除
  164. */
  165. public function del($ids = "") {
  166. if (!$this->request->isPost()) {
  167. $this->error(__("Invalid parameters"));
  168. }
  169. $ids = $ids ? $ids : $this->request->post("ids");
  170. $row = $this->model->get($ids);
  171. $this->modelValidate = true;
  172. if (!$row) {
  173. $this->error(__('No Results were found'));
  174. }
  175. Auth::instance()->delete($row['id']);
  176. $this->success();
  177. }
  178. /**
  179. * 获取客户列表
  180. */
  181. public function getcustomer()
  182. {
  183. $pageSize = input('pageSize');
  184. $pageNumber = input('pageNumber');
  185. $where = [];
  186. if ($keyValue = $this->request->request("keyValue")) {
  187. $where['id'] = $keyValue;
  188. }
  189. $name = input('name');
  190. if (!empty($name)) {
  191. $where['name'] = ['like', '%' . $name . '%'];
  192. }
  193. $staff = Staff::info();
  194. $staff_id = $staff->id;
  195. $whereStaff = function ($query) use ($staff_id) {
  196. $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
  197. ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
  198. ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
  199. };
  200. $customer = Customer::where($whereStaff)->where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  201. return json(['list' => $customer->items(), 'total' => $customer->total()]);
  202. }
  203. /**
  204. * 获取合同列表
  205. */
  206. public function getcontract()
  207. {
  208. $pageSize = input('pageSize');
  209. $pageNumber = input('pageNumber');
  210. $customer_id = input('customer_id', 0);
  211. $where = [];
  212. if ($keyValue = $this->request->request("keyValue")) {
  213. $where['id'] = $keyValue;
  214. }
  215. $name = input('name');
  216. if(!empty($name)){
  217. $where['name'] = ['like','%'.$name.'%'];
  218. }
  219. $where['check_status'] = 2;
  220. $where['customer_id'] = $customer_id;
  221. $contacts = Contract::where($where)->field('id,name,num')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  222. $data = [];
  223. $item=$contacts->items();
  224. foreach ($item as $v) {
  225. $v->name=$v['num'] . "({$v['name']})";
  226. }
  227. return json(['list' => $item, 'total' =>$contacts->total()]);
  228. }
  229. /**
  230. * 获取审批人列表
  231. */
  232. public function getstaff(){
  233. $pageSize = input('pageSize');
  234. $pageNumber = input('pageNumber');
  235. $where = [];
  236. if ($keyValue = $this->request->request("keyValue")) {
  237. $where['id'] = ['in',$keyValue];
  238. }
  239. $name = input('name');
  240. if(!empty($name)){
  241. $where['name'] = ['like','%'.$name.'%'];
  242. }
  243. $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  244. return json(['list' => $staff->items(), 'total' => $staff->total()]);
  245. }
  246. /**
  247. * 导入回款信息
  248. * @return string|void
  249. */
  250. public function import()
  251. {
  252. set_time_limit(0);
  253. if ($this->request->isPost()) {
  254. $file = $this->request->request('file');
  255. if (!$file) {
  256. $this->error(__('Parameter %s can not be empty', 'file'));
  257. }
  258. $filePath = ROOT_PATH . 'public' . $file;
  259. if (!is_file($filePath)) {
  260. $this->error(__('No results were found'));
  261. }
  262. //实例化reader
  263. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  264. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  265. $this->error(__('Unknown data format'));
  266. }
  267. if ($ext === 'csv') {
  268. $file = fopen($filePath, 'r');
  269. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  270. $fp = fopen($filePath, "w");
  271. $n = 0;
  272. while ($line = fgets($file)) {
  273. $line = rtrim($line, "\n\r\0");
  274. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  275. if ($encoding != 'utf-8') {
  276. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  277. }
  278. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  279. fwrite($fp, $line . "\n");
  280. } else {
  281. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  282. }
  283. $n++;
  284. }
  285. fclose($file) || fclose($fp);
  286. $reader = new Csv();
  287. } elseif ($ext === 'xls') {
  288. $reader = new Xls();
  289. } else {
  290. $reader = new Xlsx();
  291. }
  292. if (!$PHPExcel = $reader->load($filePath)) {
  293. $this->error(__('Unknown data format'));
  294. }
  295. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  296. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  297. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  298. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  299. //开始读取数据
  300. $fields = [];
  301. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  302. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  303. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  304. $fields[$currentRow][] = $val;
  305. if ($val instanceof RichText) {//富文本转换字符串
  306. $val = $val->__toString();
  307. }
  308. $values[] = is_null($val) ? NULL : trim($val);
  309. }
  310. }
  311. if (!isset($fields[1])) {
  312. $this->error('导入文件第一行没有数据');
  313. }
  314. $lastid = $this->model->order('id desc')->value('id');
  315. $lastid = $lastid + 5;//防止重复
  316. $contractRow = [];
  317. $errorInfo = [];
  318. $fieldnames = FormField::where(['types' => FormField::RECEIVABLES_TYPE])->column('field', 'name');
  319. $customerNames=Customer::where([])->column('id,owner_staff_id','name');
  320. $contractNames=Contract::where([])->column('id,name,num','num');
  321. $fn = [];
  322. $nums=$this->model->where([])->column('number');
  323. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  324. $values = [];
  325. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  326. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  327. $values[] = is_null($val) ? '' : $val;
  328. }
  329. foreach ($values as $l) {
  330. $fn[] = $fieldnames[$l] ?? '';
  331. }
  332. }
  333. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  334. $values = [];
  335. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  336. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  337. if ($val instanceof RichText) {//富文本转换字符串
  338. $val = $val->__toString();
  339. }
  340. $values[] = is_null($val) ? NULL : trim($val);
  341. }
  342. $lastid++;
  343. $addReceivables = ['id' => $lastid];
  344. $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
  345. if(empty($customer)){
  346. $errorInfo[] = "第{$currentRow}行,客户名称不存在;";
  347. continue;
  348. }
  349. $contract=isset($contractNames[$values[1]])?$contractNames[$values[1]]:0;
  350. if(empty($contract)){
  351. $errorInfo[] = "第{$currentRow}行,合同编号不存在;";
  352. continue;
  353. }
  354. $addReceivables['contract_id']=$contract['id'];
  355. $addReceivables['customer_id']=$customer['id'];
  356. $addReceivables['owner_staff_id']=$customer['owner_staff_id'];
  357. $addReceivables['create_staff_id']=$customer['owner_staff_id'];
  358. foreach ($values as $kv => $value) {
  359. if (!isset($fn[$kv]) || empty($fn[$kv])) {
  360. continue;
  361. }
  362. $addReceivables[$fn[$kv]] = $value;
  363. }
  364. if (empty($addReceivables['number'])) {
  365. $errorInfo[] = "第{$currentRow}行,回款编号不能为空;";
  366. continue;
  367. }
  368. if (in_array($addReceivables['number'], $nums)) {
  369. $errorInfo[] = "第{$currentRow}行,回款编号`{$addReceivables['number']}`已存在;";
  370. continue;
  371. }
  372. $contractRow[] = $addReceivables;
  373. }
  374. if (!empty($errorInfo)) {
  375. $this->error(implode(',', $errorInfo));
  376. }
  377. Db::startTrans();
  378. try {
  379. $this->model::importReceivables($contractRow);
  380. Db::commit();
  381. } catch (Exception $e) {
  382. Db::rollback();
  383. $this->error($e->getMessage());
  384. }
  385. $this->success('导入成功');
  386. }
  387. return $this->view->fetch();
  388. }
  389. /**
  390. * 模板
  391. */
  392. public function template()
  393. {
  394. $title = [
  395. '客户名称',
  396. '合同编号',
  397. ];
  398. $contractData = Form::getDataValue(Form::RECEIVABLES_TYPE);
  399. foreach ($contractData as $val) {
  400. $title[] = $val['config']['label'];
  401. }
  402. $file = export_excel($title, [], '回款');
  403. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  404. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  405. header('Cache-Control: max-age=0');
  406. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  407. // 以下内容是excel文件的信息描述信息
  408. $obj->getProperties()->setTitle('导出文件'); //设置标题
  409. $obj->setActiveSheetIndex(0);
  410. $obj->getActiveSheet()->setTitle('导出文件');
  411. /* 循环读取每个单元格的数据 */
  412. $a = 'A';
  413. $currentSheet = $obj->getActiveSheet();
  414. foreach ($title as $key => $value) {
  415. //读取工作表1
  416. // 设置第一行加粗
  417. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  418. //这里是设置单元格的内容
  419. $currentSheet->getCell($a . '1')->setValue($value);
  420. $a++;
  421. }
  422. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  423. $PHPWriter->save('php://output');
  424. }
  425. /**
  426. * 导出信息
  427. */
  428. public function export()
  429. {
  430. $this->request->filter(['strip_tags', 'trim']);
  431. $ids = input('ids');
  432. $isall = input('isall',0);
  433. $wheres = array();
  434. //导出其中几条
  435. if (isset($ids)) {
  436. $wheres['id'] = array('in', $ids);
  437. }
  438. //导出全部
  439. if ($isall == 3) {
  440. unset($wheres['id']);
  441. }
  442. //0:全部 1:我负责的 2:下属负责的
  443. $type = input('type',0);
  444. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  445. switch($type){
  446. case 1:
  447. $staff = Staff::info();
  448. $wheres['owner_staff_id'] = $staff->id;
  449. break;
  450. case 2:
  451. $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
  452. break;
  453. default:
  454. $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
  455. break;
  456. }
  457. $list = $this->model->with(['customer', 'contract','ownerStaff','receivablesOther'])->where($where)->where($wheres)->order($sort, $order)->select();
  458. $list = collection($list)->toArray();
  459. if (!$list) {
  460. $this->error('无导出数据');
  461. }
  462. $title = [
  463. '序号',
  464. '客户名称',
  465. '合同名称',
  466. '合同编号',
  467. '负责人',
  468. '创建时间',
  469. ];
  470. $dataValue = Form::getDataValue(Form::RECEIVABLES_TYPE);
  471. foreach ($dataValue as $val) {
  472. $title[] = $val['config']['label'];
  473. }
  474. foreach ($list as $k => $v) {
  475. if($v['receivables_other']){//其他客户
  476. $other=$v['receivables_other']['otherdata'];
  477. $other=json_decode($other,true);
  478. $v = array_merge($v, $other);
  479. }
  480. $field = array(
  481. $v['id'],
  482. $v['customer']['name'] ?? '',
  483. $v['contract']['name'] ?? '',
  484. $v['contract']['num'] ?? '',
  485. $v['owner_staff']['name'] ?? '',
  486. $v['createtime'],
  487. );
  488. foreach ($dataValue as $val) {
  489. if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
  490. $field[] = $v[$val['id'] . '_str'] ?? '';
  491. } else {
  492. $field[] = ($v[$val['id']] ?? '');
  493. }
  494. }
  495. $data[] = $field;
  496. }
  497. $file = export_excel($title, $data, '回款');
  498. if ($file['filePath']) {
  499. $this->success('导出成功', '', $file);
  500. }
  501. $this->error('导出失败');
  502. }
  503. }