Customer.php 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. <?php
  2. namespace app\admin\controller\qingdong\customer;
  3. use addons\qingdong\model\AdminConfig;
  4. use addons\qingdong\model\BusinessStatus;
  5. use addons\qingdong\model\ContactsOther;
  6. use addons\qingdong\model\FormField;
  7. use addons\qingdong\model\Remind;
  8. use addons\qingdong\model\Seastype;
  9. use addons\qingdong\model\WordTemplate;
  10. use app\admin\controller\qingdong\Base;
  11. use addons\qingdong\model\CustomerOther;
  12. use addons\qingdong\model\Form;
  13. use addons\qingdong\model\Record;
  14. use addons\qingdong\model\Staff;
  15. use addons\qingdong\model\Consume;
  16. use addons\qingdong\model\Contacts;
  17. use addons\qingdong\model\Contract;
  18. use addons\qingdong\model\Receivables;
  19. use addons\qingdong\model\ReceivablesPlan;
  20. use addons\qingdong\model\CustomerFile;
  21. use addons\qingdong\model\StaffSignIn;
  22. use addons\qingdong\model\File;
  23. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  24. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  25. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  26. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  27. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  28. use addons\qingdong\model\Business;
  29. use PhpOffice\PhpWord\TemplateProcessor;
  30. use PhpOffice\PhpWord\Settings;
  31. use think\Db;
  32. use think\Exception;
  33. /**
  34. * 客户管理
  35. * 操作文档:https://doc.fastadmin.net/qingdong
  36. * 软件介绍:https://www.fastadmin.net/store/qingdong.html
  37. * 售后微信:qingdong_crm
  38. */
  39. class Customer extends Base
  40. {
  41. protected $relationSearch = true;
  42. protected $searchFields = 'id,name';
  43. /**
  44. * @var \addons\qingdong\model\Customer
  45. */
  46. protected $model = null;
  47. public function _initialize()
  48. {
  49. parent::_initialize();
  50. $this->model = new \addons\qingdong\model\Customer;
  51. }
  52. /**
  53. * 查看111
  54. */
  55. public function index()
  56. {
  57. $staff_info = $this->_staff;
  58. $group_ids = $staff_info['group_ids'];
  59. //设置过滤方法
  60. $this->request->filter(['strip_tags', 'trim']);
  61. $staff = Staff::info();
  62. $staff_id = $staff->id;
  63. if ($this->request->isAjax()) {
  64. if ($this->request->request('keyField')) {
  65. return $this->selectpage();
  66. }
  67. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  68. $type = input('type', 0);
  69. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  70. switch ($type) {
  71. case 1://我负责
  72. $wheres[] = Db::raw("FIND_IN_SET($staff_id, owner_staff_id)");
  73. break;
  74. case 2://下属负责
  75. $lowerStaffIds = Staff::getLowerStaffId();
  76. $subConditions = [];
  77. foreach ($lowerStaffIds as $id) {
  78. $subConditions[] = Db::raw("FIND_IN_SET($id, owner_staff_id)");
  79. }
  80. $wheres[] = Db::raw('(' . implode(' OR ', $subConditions) . ')');
  81. break;
  82. case 3:
  83. $start = date('Y-m-d 00:00:00');
  84. $end = date('Y-m-d 23:59:59');
  85. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  86. $relationId = [];
  87. foreach ($record as $k => $v) {
  88. $whereRe['id'] = array('gt', $v['id']);
  89. $whereRe['relation_id'] = $v['relation_id'];
  90. $recordData = Record::where($whereRe)->count();
  91. if ($recordData == 0) {
  92. $relationId[] = $v['relation_id'];
  93. }
  94. }
  95. $wheres['id'] = array('in', $relationId);
  96. $staff = Staff::info();
  97. $wheres[] = Db::raw("FIND_IN_SET($staff_id, owner_staff_id)");
  98. break;
  99. case 4:
  100. $start = date('Y-m-d 00:00:00');
  101. $end = date('Y-m-d 23:59:59');
  102. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  103. $relationId = [];
  104. foreach ($record as $k => $v) {
  105. $whereRe['id'] = array('gt', $v['id']);
  106. $whereRe['relation_id'] = $v['relation_id'];
  107. $recordData = Record::where($whereRe)->count();
  108. if ($recordData >= 1) {
  109. $relationId[] = $v['relation_id'];
  110. }
  111. }
  112. $wheres['id'] = array('in', $relationId);
  113. $staff = Staff::info();
  114. $wheres[] = Db::raw("FIND_IN_SET($staff_id, owner_staff_id)");
  115. break;
  116. case 5:
  117. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
  118. $wheres['id'] = array('not in', $record);
  119. $staff = Staff::info();
  120. $wheres[] = Db::raw("FIND_IN_SET($staff_id, owner_staff_id)");
  121. break;
  122. default:
  123. $wheres[] = Db::raw("FIND_IN_SET($staff_id, owner_staff_id)");
  124. break;
  125. }
  126. // $list = $this->model->where($where)->with(['ownerStaff'])
  127. // ->where($wheres)
  128. // ->where('owner_staff_id != 0 and owner_staff_id is not null')
  129. // ->order($sort, $order)->paginate($limit);
  130. if($group_ids>1){
  131. $list = $this->model->where($where)
  132. ->where($wheres)
  133. ->where('owner_staff_id != 0 and owner_staff_id is not null')
  134. ->order($sort, $order)->paginate($limit);
  135. }else{
  136. $list = $this->model->where($where)
  137. ->where('owner_staff_id != 0 and owner_staff_id is not null')
  138. ->order($sort, $order)->paginate($limit);
  139. }
  140. $rows = $list->items();
  141. foreach ($rows as &$v) {
  142. $v['operation_team'] = 'read';
  143. if ($v['owner_staff_id'] == $this->_staff->id ||
  144. in_array($v['owner_staff_id'], Staff::getLowerStaffId()) ||
  145. in_array($this->_staff->id, explode(',', $v['rw_staff_id']))) {
  146. if (in_array($this->_staff->id, explode(',', $v['rw_staff_id']))) {
  147. $v['operation_team'] = 'update';//可修改客户不可操作其他
  148. }
  149. $v['operation'] = 'update';//修改权限
  150. } else {
  151. $v['operation'] = 'read';//只读权限
  152. }
  153. if($v['create_staff_id'] == $this->_staff->id){
  154. $v['operation'] = 'update';//修改权限
  155. }
  156. $names = Staff::where('id', 'in', $v['owner_staff_id'])->column('name');
  157. $v['owner_staff']['name'] = implode(',', $names);
  158. }
  159. $result = array("total" => $list->total(), "rows" => $list->items(),"staff_id" => $staff_id);
  160. return json($result);
  161. }
  162. $field = FormField::getFields(FormField::CUSTOMER_TYPE);
  163. $this->assign('staff_group', $staff->group_ids);
  164. $this->assignconfig('fields', $field);
  165. return $this->view->fetch();
  166. }
  167. /**
  168. * 添加
  169. */
  170. public function add()
  171. {
  172. if ($this->request->isPost()) {
  173. $params = $this->request->post("row/a");
  174. if ($params) {
  175. $params = $this->preExcludeFields($params);
  176. // 表单验证
  177. if (($result = $this->qingdongValidate($params, 'Customer', 'create')) !== true) {
  178. $this->error($result);
  179. }
  180. $mobile='';
  181. if(isset($params['mobile']) && $params['mobile']){
  182. $mobile = $params['mobile'];
  183. }
  184. if(isset($params['name']) && $params['name']){
  185. $customerData = $this->model->where(['name'=>$params['name']])->find();
  186. if($customerData){
  187. $this->error('客户名称已存在');
  188. }
  189. }
  190. $result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params);
  191. if ($result !== true) {
  192. $this->error($result);
  193. }
  194. $result = false;
  195. Db::startTrans();
  196. try {
  197. $params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
  198. $result = $this->model::createCustomer($params);
  199. if($mobile){
  200. $retC = array(
  201. 'customer_id'=>$result,
  202. 'is_major'=>1,
  203. 'name'=>$params['name'],
  204. 'mobile'=>$mobile,
  205. 'next_time'=>date('Y-m-d H:i:s'),
  206. 'create_staff_id'=>$this->_staff->id,
  207. 'owner_staff_id'=>$this->_staff->id,
  208. );
  209. Contacts::create($retC);
  210. }
  211. Db::commit();
  212. } catch (Exception $e) {
  213. Db::rollback();
  214. $this->error($e->getMessage());
  215. }
  216. if ($result !== false) {
  217. $this->success();
  218. } else {
  219. $this->error(__('No rows were inserted'));
  220. }
  221. }
  222. $this->error(__('Parameter %s can not be empty', ''));
  223. }
  224. $this->assign('form_data', Form::getDataValue(Form::CUSTOMER_TYPE));
  225. $remind = Remind::where(['type' => Remind::CUSTOMER_TYPE])->find();
  226. $staff_ids = $remind['staff_ids'] ?? '';
  227. $this->assign('seastype', Seastype::where([])->column('name', 'id'));
  228. $this->assign('staff_ids', $staff_ids);
  229. $this->assign('staff', Staff::where([])->column('name', 'id'));
  230. return $this->view->fetch();
  231. }
  232. /**
  233. * 修改
  234. */
  235. public function edit($ids = null)
  236. {
  237. $row = $this->model->where([
  238. 'id' => $ids,
  239. ])->find();
  240. if (empty($row)) {
  241. $this->error(__('No Results were found'));
  242. }
  243. // if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
  244. //
  245. // if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
  246. // !in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
  247. // $this->error('权限不足');
  248. // }
  249. // }
  250. $staff = Staff::info();
  251. $ownerarray = explode(',', $row['owner_staff_id']);
  252. if (!in_array($staff->id, $ownerarray)) {
  253. $this->error('权限不足');
  254. }
  255. if ($this->request->isPost()) {
  256. $params = $this->request->post("row/a");
  257. if ($params) {
  258. $params = $this->preExcludeFields($params);
  259. // 表单验证
  260. if (($result = $this->qingdongValidate($params, 'Customer', 'create')) !== true) {
  261. $this->error($result);
  262. }
  263. $result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params,$ids);
  264. if ($result !== true) {
  265. $this->error($result);
  266. }
  267. $mobile='';
  268. if(isset($params['mobile']) && $params['mobile']){
  269. $mobile = $params['mobile'];
  270. }
  271. $result = false;
  272. Db::startTrans();
  273. try {
  274. $params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
  275. $params['id'] = $ids;
  276. $result = $this->model::updateCustomer($params);
  277. if($mobile){
  278. Contacts::where(array('customer_id'=>$ids,'is_major'=>1))->update(array('mobile'=>$mobile,'updatetime'=>time()));
  279. }
  280. Db::commit();
  281. } catch (Exception $e) {
  282. Db::rollback();
  283. $this->error($e->getMessage());
  284. }
  285. if ($result !== false) {
  286. $this->success();
  287. } else {
  288. $this->error(__('No rows were inserted'));
  289. }
  290. }
  291. $this->error(__('Parameter %s can not be empty', ''));
  292. }
  293. $row = $row->toArray();
  294. $row = CustomerOther::getOther($row);
  295. $form = Form::getDataValue(Form::CUSTOMER_TYPE, $row);
  296. $this->assign('seastype', Seastype::where([])->column('name', 'id'));
  297. $this->assign('row', $row);
  298. $this->assign('form_data', $form);
  299. return $this->view->fetch();
  300. }
  301. /**
  302. * 搜索下拉列表
  303. */
  304. public function stafflist()
  305. {
  306. $data = ['searchlist' => Staff::getList()];
  307. $this->success('', null, $data);
  308. }
  309. /**
  310. * 转移客户
  311. */
  312. public function change($ids = null)
  313. {
  314. $row = $this->model->where([
  315. 'id' => $ids,
  316. ])->find();
  317. if (empty($row)) {
  318. $this->error(__('No Results were found'));
  319. }
  320. if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
  321. if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
  322. !in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
  323. $this->error('权限不足');
  324. }
  325. }
  326. if ($this->request->isPost()) {
  327. $params = $this->request->post("row/a");
  328. if ($params) {
  329. $params = $this->preExcludeFields($params);
  330. $result = false;
  331. Db::startTrans();
  332. try {
  333. $result = $this->model::transfer($ids, $params['owner_staff_id']);
  334. Db::commit();
  335. } catch (Exception $e) {
  336. Db::rollback();
  337. $this->error($e->getMessage());
  338. }
  339. if ($result !== false) {
  340. $this->success();
  341. } else {
  342. $this->error(__('No rows were inserted'));
  343. }
  344. }
  345. $this->error(__('Parameter %s can not be empty', ''));
  346. }
  347. $staffs = Staff::getList();
  348. $this->assign('staffs', $staffs);
  349. $this->assign('row', $row);
  350. return $this->view->fetch();
  351. }
  352. /**
  353. * 批量转移客户
  354. */
  355. public function batch_change($ids = null)
  356. {
  357. $ids = json_decode($ids, true);
  358. $ids = $this->model->where([
  359. 'id' => ['in', $ids]
  360. ])->column('id');
  361. if (empty($ids)) {
  362. $this->error(__('No Results were found'));
  363. }
  364. if ($this->request->isPost()) {
  365. $params = $this->request->post("row/a");
  366. if ($params) {
  367. $params = $this->preExcludeFields($params);
  368. $result = false;
  369. Db::startTrans();
  370. try {
  371. $result = $this->model::batchTransfer($ids, $params['owner_staff_id']);
  372. Db::commit();
  373. } catch (Exception $e) {
  374. Db::rollback();
  375. $this->error($e->getMessage());
  376. }
  377. if ($result !== false) {
  378. $this->success();
  379. } else {
  380. $this->error(__('No rows were inserted'));
  381. }
  382. }
  383. $this->error(__('Parameter %s can not be empty', ''));
  384. }
  385. $staffs = Staff::getList();
  386. $this->assign('staffs', $staffs);
  387. $this->assign('ids', json_encode($ids));
  388. return $this->view->fetch();
  389. }
  390. /**
  391. * 客户详情
  392. */
  393. public function detail($ids = null)
  394. {
  395. $row = $this->model->with(['create_staff', 'owner_staff'])->where([
  396. 'id' => $ids,
  397. ])->find();
  398. if (empty($row)) {
  399. $this->error(__('No Results were found'));
  400. }
  401. if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
  402. //
  403. // if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
  404. // !in_array($this->_staff->id, explode(',', $row['ro_staff_id'])) ) {//是否在团队内
  405. // $this->error('权限不足');
  406. // }
  407. if(!in_array($this->_staff->id, explode(',', $row['owner_staff_id']))){
  408. $this->error('权限不足');
  409. }
  410. }
  411. $row = $row->toArray();
  412. $row = CustomerOther::getOther($row);
  413. $row['operation_team'] = 'read';
  414. if ($row['owner_staff_id'] == $this->_staff->id ||
  415. in_array($row['owner_staff_id'], Staff::getLowerStaffId()) ||
  416. in_array($this->_staff->id, explode(',', $row['rw_staff_id']))) {
  417. if (in_array($this->_staff->id, explode(',', $row['rw_staff_id']))) {
  418. $row['operation_team'] = 'update';//可修改客户不可操作其他
  419. }
  420. $row['operation'] = 'update';//修改权限
  421. } else {
  422. $row['operation'] = 'read';//只读权限
  423. }
  424. if($row['create_staff_id'] == $this->_staff->id){
  425. $row['operation'] = 'update';//修改权限
  426. }
  427. $form = Form::getDataValue(Form::CUSTOMER_TYPE, $row);
  428. foreach ($form as $ks => $vs) {
  429. //备注显示
  430. if ($vs['component'] == 'textarea' && ($vs['config']['label'] == '备注信息' || $vs['config']['label'] == '备注')) {
  431. $row[$vs['id']] = isset($row[$vs['id']]) ? $row[$vs['id']] : $row['remarks'];
  432. }
  433. }
  434. $this->assign('records', Record::getList(Record::CUSTOMER_TYPE, $ids));
  435. $this->assign('form_data', $form);
  436. $this->assign('row', $row);
  437. $this->assign('ids', $ids);
  438. $this->assignconfig("idinfo", ['id' => $ids, 'operation' => $row['operation'], 'operation_team' => $row['operation_team']]);
  439. return $this->view->fetch();
  440. }
  441. /**
  442. * 获取相关联系人
  443. * @param null $ids
  444. * @return \think\response\Json
  445. */
  446. public function get_contacts($ids = null)
  447. {
  448. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  449. $list = Contacts::where(['customer_id' => $ids])->order('id desc')->paginate($limit);
  450. $result = array("total" => $list->total(), "rows" => $list->items());
  451. return json($result);
  452. }
  453. /**
  454. * 获取相关合同
  455. */
  456. public function get_contract($ids = null)
  457. {
  458. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  459. $list = Contract::where([
  460. 'customer_id' => $ids,
  461. ])->with('customer')->order('id desc')->paginate($limit);
  462. $result = array("total" => $list->total(), "rows" => $list->items());
  463. return json($result);
  464. }
  465. /**
  466. * 添加费用
  467. */
  468. public function add_consume($ids = null)
  469. {
  470. if ($this->request->isPost()) {
  471. $params = $this->request->post("row/a");
  472. if ($params) {
  473. // 表单验证
  474. if (($result = $this->qingdongValidate($params, 'Consume', 'create')) !== true) {
  475. $this->error($result);
  476. }
  477. Db::startTrans();
  478. try {
  479. $result = Consume::createConsume($params);
  480. Db::commit();
  481. } catch (Exception $e) {
  482. Db::rollback();
  483. $this->error($e->getMessage());
  484. }
  485. if ($result) {
  486. $this->success('添加费用成功');
  487. }
  488. }
  489. $this->error(__('Parameter %s can not be empty', ''));
  490. }
  491. $customer = $this->model->where(['id' => $ids])->find();
  492. $this->assign('staff', Staff::where([])->column('name', 'id'));
  493. $this->view->assign('customer', $customer);
  494. return $this->view->fetch();
  495. }
  496. /**
  497. * 获取费用
  498. */
  499. public function get_consume($ids = null)
  500. {
  501. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  502. $list = Consume::where([
  503. 'customer_id' => $ids,
  504. ])->with('follow_staff')->order('id desc')->paginate($limit);
  505. $result = array("total" => $list->total(), "rows" => $list->items());
  506. return json($result);
  507. }
  508. /**
  509. * 获取团队成员
  510. * @param null $ids
  511. */
  512. public function getteam($ids = null)
  513. {
  514. $customer = $this->model::get($ids);
  515. if (empty($customer)) {
  516. $this->error('客户不存在');
  517. }
  518. $where = [];
  519. if ($keyValue = $this->request->request("keyValue")) {
  520. $where['id'] = ['eq', $keyValue];
  521. }
  522. if ($where) {
  523. $owner_staff = Staff::where($where)->find();
  524. $rw_staffs = [];
  525. $ro_staffs = [];
  526. } else {
  527. $owner_staff = Staff::where(['id' => $customer->owner_staff_id])->find();
  528. $rw_staffs = Staff::where(['id' => ['in', explode(',', $customer->rw_staff_id)]])->select();
  529. $ro_staffs = Staff::where(['id' => ['in', explode(',', $customer->ro_staff_id)]])->select();
  530. }
  531. $staffs = [];
  532. if ($owner_staff) {
  533. $staffs[] = [
  534. 'id' => $owner_staff->id,
  535. 'name' => $owner_staff->name,
  536. 'img' => $owner_staff->img,
  537. 'post' => $owner_staff->post,
  538. 'roles' => '负责人',
  539. 'is_edit' => '读写',
  540. 'customer_id' => $customer->id,
  541. ];
  542. }
  543. foreach ($rw_staffs as $v) {
  544. $staffs[] = [
  545. 'id' => $v->id,
  546. 'name' => $v->name,
  547. 'img' => $v->img,
  548. 'post' => $v->post,
  549. 'roles' => '普通员工',
  550. 'is_edit' => '读写',
  551. 'customer_id' => $customer->id,
  552. ];
  553. }
  554. foreach ($ro_staffs as $v) {
  555. $staffs[] = [
  556. 'id' => $v->id,
  557. 'name' => $v->name,
  558. 'img' => $v->img,
  559. 'post' => $v->post,
  560. 'roles' => '普通员工',
  561. 'is_edit' => '只读',
  562. 'customer_id' => $customer->id,
  563. ];
  564. }
  565. $result = array("total" => count($staffs), "rows" => $staffs);
  566. return json($result);
  567. }
  568. /**
  569. * 添加团队成员
  570. */
  571. public function addteam($ids = null)
  572. {
  573. $customer = \addons\qingdong\model\Customer::get($ids);
  574. if (empty($customer)) {
  575. $this->error('客户不存在');
  576. }
  577. if ($this->request->isPost()) {
  578. $params = $this->request->post("row/a");
  579. $staff_ids = $params['staff_id'];
  580. if (empty($staff_ids)) {
  581. $this->error('员工不存在');
  582. }
  583. $staff_ids = explode(',', $staff_ids);
  584. foreach ($staff_ids as $k => $id) {
  585. if ($id == $customer->owner_staff_id) {
  586. unset($staff_ids[$k]);
  587. }
  588. }
  589. $ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
  590. $rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
  591. if ($params['rules'] == 1) {//读写
  592. $rw_staff_id = array_merge($rw_staff_id, $staff_ids);
  593. $rw_staff_id = array_unique($rw_staff_id);
  594. } else {
  595. $ro_staff_id = array_merge($ro_staff_id, $staff_ids);
  596. $ro_staff_id = array_unique($ro_staff_id);
  597. }
  598. $ro_staff_id = array_diff($ro_staff_id, $rw_staff_id);
  599. $rw_staff_id = implode(',', $rw_staff_id);
  600. $ro_staff_id = implode(',', $ro_staff_id);
  601. $result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
  602. 'ro_staff_id' => ",{$ro_staff_id},"]);
  603. if ($result === false) {
  604. $this->error('修改失败');
  605. }
  606. $this->success('修改成功');
  607. }
  608. $owner_staff = Staff::where(['id' => $customer->owner_staff_id])->find();
  609. $rw_staffs = Staff::where(['id' => ['in', explode(',', $customer->rw_staff_id)]])->select();
  610. $ro_staffs = Staff::where(['id' => ['in', explode(',', $customer->ro_staff_id)]])->select();
  611. $staffs = [];
  612. if ($owner_staff) {
  613. $staffs[] = [
  614. 'id' => $owner_staff->id,
  615. 'name' => $owner_staff->name,
  616. 'img' => $owner_staff->img,
  617. 'post' => $owner_staff->post,
  618. 'mobile' => $owner_staff->mobile,
  619. 'roles' => 1,
  620. 'is_edit' => 1,
  621. ];
  622. }
  623. foreach ($rw_staffs as $v) {
  624. $staffs[] = [
  625. 'id' => $v->id,
  626. 'name' => $v->name,
  627. 'img' => $v->img,
  628. 'post' => $v->post,
  629. 'mobile' => $v->mobile,
  630. 'roles' => 2,
  631. 'is_edit' => 1,
  632. ];
  633. }
  634. foreach ($ro_staffs as $v) {
  635. $staffs[] = [
  636. 'id' => $v->id,
  637. 'name' => $v->name,
  638. 'img' => $v->img,
  639. 'post' => $v->post,
  640. 'mobile' => $v->mobile,
  641. 'roles' => 2,
  642. 'is_edit' => 0,
  643. ];
  644. }
  645. $this->assign('staffs', $staffs);
  646. return $this->view->fetch();
  647. }
  648. /**
  649. * 修改团队成员
  650. */
  651. public function editteam($ids = null)
  652. {
  653. $customer_id = input('customer_id');
  654. $customer = $this->model->get($customer_id);
  655. if (empty($customer)) {
  656. $this->error('客户不存在');
  657. }
  658. if ($this->request->isPost()) {
  659. $params = $this->request->post("row/a");
  660. $staff_id = $params['staff_id'];
  661. if (empty($staff_id)) {
  662. $this->error('员工不存在');
  663. }
  664. $ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
  665. $rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
  666. if ($params['rules'] == 1) {//读写
  667. $rw_staff_id[] = $staff_id;
  668. $rw_staff_id = array_unique($rw_staff_id);
  669. } else {
  670. foreach ($rw_staff_id as $k => $id) {
  671. if ($id == $staff_id) {
  672. unset($rw_staff_id[$k]);
  673. }
  674. }
  675. $ro_staff_id[] = $staff_id;
  676. $ro_staff_id = array_unique($ro_staff_id);
  677. }
  678. $ro_staff_id = array_diff($ro_staff_id, $rw_staff_id);
  679. $rw_staff_id = implode(',', $rw_staff_id);
  680. $ro_staff_id = implode(',', $ro_staff_id);
  681. $result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
  682. 'ro_staff_id' => ",{$ro_staff_id},"]);
  683. if ($result === false) {
  684. $this->error('修改失败');
  685. }
  686. $this->success('修改成功');
  687. $this->success('修改成功');
  688. }
  689. if (in_array($ids, explode(',', $customer->rw_staff_id))) {
  690. $is_edit = 1;
  691. } else {
  692. $is_edit = 0;
  693. }
  694. $this->assign('is_edit', $is_edit);
  695. $this->assign('staff_id', $ids);
  696. return $this->view->fetch();
  697. }
  698. /**
  699. * 删除团队成员
  700. */
  701. public function delteam()
  702. {
  703. $customer_id = input('customer_id');
  704. $customer = $this->model->get($customer_id);
  705. if (empty($customer)) {
  706. $this->error('客户不存在');
  707. }
  708. if ($this->request->isPost()) {
  709. $staff_id = input('staff_id');
  710. if (empty($staff_id)) {
  711. $this->error('员工不存在');
  712. }
  713. $ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
  714. $rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
  715. foreach ($ro_staff_id as $k => $id) {
  716. if ($id == $staff_id || empty($id)) {
  717. unset($ro_staff_id[$k]);
  718. }
  719. }
  720. foreach ($rw_staff_id as $k => $id) {
  721. if ($id == $staff_id || empty($id)) {
  722. unset($rw_staff_id[$k]);
  723. }
  724. }
  725. $rw_staff_id = implode(',', $rw_staff_id);
  726. $ro_staff_id = implode(',', $ro_staff_id);
  727. $result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
  728. 'ro_staff_id' => ",{$ro_staff_id},"]);
  729. if ($result === false) {
  730. $this->error('删除失败');
  731. }
  732. $this->success('删除成功');
  733. }
  734. }
  735. /**
  736. * 获取回款计划
  737. * @param null $ids
  738. */
  739. public function get_receivables_plan($ids = null)
  740. {
  741. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  742. $list = ReceivablesPlan::where(['customer_id' => $ids])->with([
  743. 'customer',
  744. 'contract'
  745. ])->order('id desc')->paginate($limit);
  746. $result = array("total" => $list->total(), "rows" => $list->items());
  747. return json($result);
  748. }
  749. /**
  750. * 获取回款记录
  751. */
  752. public function get_receivables($ids = null)
  753. {
  754. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  755. $list = Receivables::where(['customer_id' => $ids])->with([
  756. 'customer',
  757. 'contract',
  758. 'ownerStaff',
  759. ])->order('id desc')->paginate($limit);
  760. $result = array("total" => $list->total(), "rows" => $list->items());
  761. return json($result);
  762. }
  763. /**
  764. * 获取附件记录
  765. */
  766. public function get_file($ids = null)
  767. {
  768. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  769. $list = CustomerFile::where(['customer_id' => $ids])->with(['file'])->order('id desc')->field('file_id')->paginate($limit);
  770. $result = array("total" => $list->total(), "rows" => $list->items());
  771. return json($result);
  772. }
  773. /**
  774. * 移入公海
  775. */
  776. public function seas($ids = "")
  777. {
  778. $row = $this->model->where([
  779. 'id' => $ids,
  780. 'owner_staff_id' => ['in', Staff::getMyStaffIds()]
  781. ])->find();
  782. if (empty($row)) {
  783. $this->error(__('No Results were found'));
  784. }
  785. if ($this->request->isPost()) {
  786. $result = false;
  787. Db::startTrans();
  788. try {
  789. $result = $this->model::moveSeas($ids);
  790. Db::commit();
  791. } catch (Exception $e) {
  792. Db::rollback();
  793. $this->error($e->getMessage());
  794. }
  795. if ($result !== false) {
  796. $this->success();
  797. } else {
  798. $this->error(__('No rows were inserted'));
  799. }
  800. $this->error(__('Parameter %s can not be empty', ''));
  801. }
  802. }
  803. /**
  804. * 领取客户
  805. */
  806. public function receive($ids = "")
  807. {
  808. $row = $this->model->where([
  809. 'id' => $ids,
  810. 'owner_staff_id' => 0
  811. ])->find();
  812. if (empty($row)) {
  813. $this->error(__('No Results were found'));
  814. }
  815. if ($this->request->isPost()) {
  816. $result = false;
  817. Db::startTrans();
  818. try {
  819. $result = $this->model::receive($ids);
  820. Db::commit();
  821. } catch (Exception $e) {
  822. Db::rollback();
  823. $this->error($e->getMessage());
  824. }
  825. if ($result !== false) {
  826. $this->success('领取客户成功');
  827. }
  828. $this->error(__('Parameter %s can not be empty', ''));
  829. }
  830. }
  831. /**
  832. * 删除
  833. */
  834. public function del($ids = "")
  835. {
  836. if (!$this->request->isPost()) {
  837. $this->error(__("Invalid parameters"));
  838. }
  839. $ids = $ids ? $ids : $this->request->post("ids");
  840. $row = $this->model->where([
  841. 'id' => $ids,
  842. 'owner_staff_id' => ['in', Staff::getMyStaffIds()]
  843. ])->find();
  844. $this->modelValidate = true;
  845. if (!$row) {
  846. $this->error(__('No Results were found'));
  847. }
  848. //如果有合同和回款,不可删除客户
  849. $Contract = Contract::where(array('customer_id' => $ids))->find();
  850. if ($Contract) {
  851. $this->error('已创建合同不可删除');
  852. }
  853. $Receivables = Receivables::where(array('customer_id' => $ids))->find();
  854. if ($Receivables) {
  855. $this->error('已创建回款不可删除');
  856. }
  857. $map['id'] = $ids;
  858. $result = $this->model->destroy($map);
  859. if (!$result) {
  860. $this->error('删除失败');
  861. }
  862. $this->success();
  863. }
  864. /**
  865. * 获取团队人员列表
  866. */
  867. public function getstaff()
  868. {
  869. $pageSize = input('pageSize');
  870. $pageNumber = input('pageNumber');
  871. $where = [];
  872. if ($keyValue = $this->request->request("keyValue")) {
  873. $where['id'] = ['in', $keyValue];
  874. }
  875. $name = input('name');
  876. if (!empty($name)) {
  877. $where['name'] = ['like', '%' . $name . '%'];
  878. }
  879. $staff = Staff::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  880. return json(['list' => $staff->items(), 'total' => $staff->total()]);
  881. }
  882. /**
  883. * 地图
  884. */
  885. public function map()
  886. {
  887. $key = AdminConfig::getConfigValue('map_key', 'wechat');
  888. $this->assign('key', $key);
  889. return $this->view->fetch();
  890. }
  891. /**
  892. * 获取签到记录
  893. */
  894. public function get_sign()
  895. {
  896. $customerId = input('customer_id', '');
  897. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  898. $list = StaffSignIn::where([
  899. 'customer_id' => $customerId,
  900. ])->order('id desc')->paginate($limit);
  901. $result = array("total" => $list->total(), "rows" => $list->items());
  902. return json($result);
  903. }
  904. /**
  905. * 获取签到记录
  906. */
  907. public function get_sign_detail($ids = null)
  908. {
  909. $staffSign = StaffSignIn::where(['id' => $ids])->find();
  910. if (empty($staffSign)) {
  911. $this->error('数据不存在');
  912. }
  913. if ($staffSign['other']) {
  914. $other = json_decode($staffSign['other'], true);
  915. $form = Form::getDataValue(Form::SIGNIN_TYPE);
  916. foreach ($form as $k => $v) {
  917. if ($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile') {
  918. $other[$v['id'] . '_str'] = '';
  919. if (key_exists($v['id'], $other)) {
  920. if (isset($other[$v['id']]) && $other[$v['id']]) {
  921. $whereT['id'] = array('in', $other[$v['id']]);
  922. $fileinfo = File::where($whereT)->field('id,name,file_path,save_name')->select();
  923. if ($fileinfo) {
  924. $other[$v['id']] = $fileinfo;
  925. $fileinfodata = '';
  926. foreach ($fileinfo as $kss => $vss) {
  927. $fileinfodata = $vss['save_name'] . ',' . $fileinfodata;
  928. }
  929. $other[$v['id'] . '_str'] = rtrim($fileinfodata, ',');
  930. }
  931. }
  932. }
  933. }
  934. }
  935. $staffSign['other'] = $other;
  936. }
  937. $this->assign('form_data', Form::getDataValue(Form::SIGNIN_TYPE, $staffSign['other']));
  938. $this->assign('row', $staffSign['other']);
  939. return $this->view->fetch();
  940. }
  941. /**
  942. * 获取相关商机
  943. * @param null $ids
  944. * @return \think\response\Json
  945. */
  946. public function get_business()
  947. {
  948. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  949. $customer_id = input('customer_id');
  950. $list = Business::where(['customer_id' => $customer_id])->order('id desc')->paginate($limit);
  951. foreach ($list as $k => $v) {
  952. $types = BusinessStatus::where(array('business_id' => $v['id']))->order('id desc')->value('type');
  953. $list[$k]['type'] = $types ? (int)$types : 0;
  954. }
  955. $result = array("total" => $list->total(), "rows" => $list->items());
  956. return json($result);
  957. }
  958. /**
  959. * 导入客户
  960. * @return string|void
  961. */
  962. public function import()
  963. {
  964. set_time_limit(0);
  965. if ($this->request->isPost()) {
  966. $file = $this->request->request('file');
  967. $staff_id = $this->request->request('staff_id', 0);
  968. $seas_type_id = input('seas_type_id',0);
  969. if (!$file) {
  970. $this->error(__('Parameter %s can not be empty', 'file'));
  971. }
  972. $filePath = ROOT_PATH . 'public' . $file;
  973. if (!is_file($filePath)) {
  974. $this->error(__('No results were found'));
  975. }
  976. //实例化reader
  977. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  978. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  979. $this->error(__('Unknown data format'));
  980. }
  981. if ($ext === 'csv') {
  982. $file = fopen($filePath, 'r');
  983. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  984. $fp = fopen($filePath, "w");
  985. $n = 0;
  986. while ($line = fgets($file)) {
  987. $line = rtrim($line, "\n\r\0");
  988. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  989. if ($encoding != 'utf-8') {
  990. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  991. }
  992. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  993. fwrite($fp, $line . "\n");
  994. } else {
  995. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  996. }
  997. $n++;
  998. }
  999. fclose($file) || fclose($fp);
  1000. $reader = new Csv();
  1001. } elseif ($ext === 'xls') {
  1002. $reader = new Xls();
  1003. } else {
  1004. $reader = new Xlsx();
  1005. }
  1006. if (!$PHPExcel = $reader->load($filePath)) {
  1007. $this->error(__('Unknown data format'));
  1008. }
  1009. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  1010. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  1011. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  1012. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  1013. //开始读取数据
  1014. $fields = [];
  1015. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  1016. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1017. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  1018. $fields[$currentRow][] = $val;
  1019. if ($val instanceof RichText) {//富文本转换字符串
  1020. $val = $val->__toString();
  1021. }
  1022. $values[] = is_null($val) ? '' : trim($val);
  1023. }
  1024. }
  1025. if (!isset($fields[1])) {
  1026. $this->error('导入文件第一行没有数据');
  1027. }
  1028. $lastid = $this->model->withTrashed()->order('id desc')->value('id');
  1029. $lastid = $lastid + 5;//防止重复
  1030. $customerRow = [];
  1031. $errorInfo = [];
  1032. $formrow = [];
  1033. $names = $this->model->where([])->column('name');
  1034. $fieldnames = FormField::where(['types' => FormField::CUSTOMER_TYPE])->column('field', 'name');
  1035. if(!$fieldnames){
  1036. $this->error('请在系统管理->字段管理中保存客户管理表单生成客户导入字段');
  1037. }
  1038. $forms = Form::getDataValue(Form::CUSTOMER_TYPE);
  1039. foreach($forms as $k=>$v){
  1040. $formrow[$v['id']] = $v['name'];
  1041. }
  1042. $fn = [];
  1043. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  1044. $values = [];
  1045. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1046. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  1047. $values[] = is_null($val) ? '' : $val;
  1048. }
  1049. foreach ($values as $l) {
  1050. $fn[] = $fieldnames[$l] ?? '';
  1051. }
  1052. }
  1053. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  1054. $values = [];
  1055. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1056. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  1057. if ($val instanceof RichText) {//富文本转换字符串
  1058. $val = $val->__toString();
  1059. }
  1060. $values[] = is_null($val) ? NULL : trim($val);
  1061. }
  1062. $lastid++;
  1063. $addCustomers = ['id' => $lastid, 'owner_staff_id' => $staff_id, 'create_staff_id' => $staff_id];
  1064. foreach ($values as $kv => $value) {
  1065. if (!isset($fn[$kv]) || empty($fn[$kv])) {
  1066. continue;
  1067. }
  1068. $addCustomers[$fn[$kv]] = $value;
  1069. }
  1070. //日期格式处理
  1071. foreach($formrow as $k=>$v){
  1072. if($v=='日期选择框'){
  1073. if(isset($addCustomers[$k]) && $addCustomers[$k]){
  1074. $addCustomers[$k] =date("Y-m-d", ($addCustomers[$k] - 25569) * 24 * 3600);
  1075. }
  1076. }
  1077. if($v=='时间选择框'){
  1078. if(isset($addCustomers[$k]) && $addCustomers[$k]){
  1079. $addCustomers[$k] =date("Y-m-d H:i:s", ($addCustomers[$k] - 25569) * 24 * 3600);
  1080. }
  1081. }
  1082. }
  1083. if (empty($addCustomers['name'])) {
  1084. $errorInfo[] = "第{$currentRow}行,客户名称不能为空;";
  1085. continue;
  1086. }
  1087. if (in_array($addCustomers['name'], $names)) {
  1088. $errorInfo[] = "第{$currentRow}行,客户名称`{$addCustomers['name']}`已存在;";
  1089. continue;
  1090. }
  1091. $addCustomers['seas_id']=",{$seas_type_id},";
  1092. $customerRow[] = $addCustomers;
  1093. }
  1094. if (!empty($errorInfo)) {
  1095. $this->error(implode(',', $errorInfo));
  1096. }
  1097. Db::startTrans();
  1098. try {
  1099. $this->model::importCustomer($customerRow);
  1100. Db::commit();
  1101. } catch (Exception $e) {
  1102. Db::rollback();
  1103. $this->error($e->getMessage());
  1104. }
  1105. $this->success('导入成功');
  1106. }
  1107. $this->assign('seas_type', Seastype::where([])->field('id,name')->select());
  1108. $this->assign('staffs', Staff::getList());
  1109. return $this->view->fetch();
  1110. }
  1111. /**
  1112. * 模板
  1113. */
  1114. public function template()
  1115. {
  1116. $title = [];
  1117. $dataValue = Form::getDataValue(Form::CUSTOMER_TYPE);
  1118. foreach ($dataValue as $val) {
  1119. $title[] = $val['config']['label'];
  1120. }
  1121. $file = export_excel($title, [], '客户');
  1122. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1123. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  1124. header('Cache-Control: max-age=0');
  1125. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  1126. // 以下内容是excel文件的信息描述信息
  1127. $obj->getProperties()->setTitle('导出文件'); //设置标题
  1128. $obj->setActiveSheetIndex(0);
  1129. $obj->getActiveSheet()->setTitle('导出文件');
  1130. /* 循环读取每个单元格的数据 */
  1131. $a = 'A';
  1132. $currentSheet = $obj->getActiveSheet();
  1133. foreach ($title as $key => $value) {
  1134. //读取工作表1
  1135. // 设置第一行加粗
  1136. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  1137. //这里是设置单元格的内容
  1138. $currentSheet->getCell($a . '1')->setValue($value);
  1139. $a++;
  1140. }
  1141. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  1142. $PHPWriter->save('php://output');
  1143. }
  1144. /**
  1145. * 导出信息
  1146. */
  1147. public function export()
  1148. {
  1149. $this->request->filter(['strip_tags', 'trim']);
  1150. $ids = input('ids');
  1151. $isall = input('isall');
  1152. $wheres = array();
  1153. //导出其中几条
  1154. if (isset($ids)) {
  1155. $wheres['id'] = array('in', $ids);
  1156. }
  1157. //导出全部
  1158. if (isset($isall)) {
  1159. if ($isall == 3) {
  1160. unset($wheres['id']);
  1161. }
  1162. }
  1163. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  1164. $type = input('type', 0);
  1165. $staff = Staff::info();
  1166. $staff_id = $staff->id;
  1167. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  1168. switch ($type) {
  1169. case 1://我负责
  1170. $wheres['owner_staff_id'] = $staff_id;
  1171. break;
  1172. case 2://下属负责
  1173. $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
  1174. break;
  1175. case 3:
  1176. $start = date('Y-m-d 00:00:00');
  1177. $end = date('Y-m-d 23:59:59');
  1178. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  1179. $relationId = [];
  1180. foreach ($record as $k => $v) {
  1181. $whereRe['id'] = array('gt', $v['id']);
  1182. $whereRe['relation_id'] = $v['relation_id'];
  1183. $recordData = Record::where($whereRe)->count();
  1184. if ($recordData == 0) {
  1185. $relationId[] = $v['relation_id'];
  1186. }
  1187. }
  1188. $wheres['id'] = array('in', $relationId);
  1189. $staff = Staff::info();
  1190. $wheres['owner_staff_id'] = $staff->id;
  1191. break;
  1192. case 4:
  1193. $start = date('Y-m-d 00:00:00');
  1194. $end = date('Y-m-d 23:59:59');
  1195. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  1196. $relationId = [];
  1197. foreach ($record as $k => $v) {
  1198. $whereRe['id'] = array('gt', $v['id']);
  1199. $whereRe['relation_id'] = $v['relation_id'];
  1200. $recordData = Record::where($whereRe)->count();
  1201. if ($recordData >= 1) {
  1202. $relationId[] = $v['relation_id'];
  1203. }
  1204. }
  1205. $wheres['id'] = array('in', $relationId);
  1206. $staff = Staff::info();
  1207. $wheres['owner_staff_id'] = $staff->id;
  1208. break;
  1209. case 5:
  1210. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
  1211. $wheres['id'] = array('not in', $record);
  1212. $staff = Staff::info();
  1213. $wheres['owner_staff_id'] = $staff->id;
  1214. break;
  1215. default:
  1216. $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
  1217. break;
  1218. }
  1219. $owner_staff_id = $wheres['owner_staff_id'];
  1220. // $owner_staff_id_arr = explode(',',$owner_staff_id);
  1221. // foreach ($owner_staff_id_arr as $k=>$v){
  1222. // if($k==0){
  1223. //
  1224. // }
  1225. // }
  1226. unset($wheres['owner_staff_id']);
  1227. $list = $this->model->where($where)->with(['ownerStaff','customerOther'])
  1228. ->where($wheres)
  1229. // ->where(function ($query) use ($staff_id, $owner_staff_id, $type) {
  1230. // if ($type == 0) {//全部
  1231. // $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
  1232. // ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
  1233. // ->whereOr(['owner_staff_id' => $owner_staff_id]);
  1234. // } else {
  1235. // $query->where(['owner_staff_id' => $owner_staff_id]);
  1236. // }
  1237. // })
  1238. ->where('owner_staff_id != 0 and owner_staff_id is not null')->order($sort, $order)->select();
  1239. $list = collection($list)->toArray();
  1240. outFileLog($list,'customer','list-export');
  1241. if (!$list) {
  1242. $this->error('无导出数据');
  1243. }
  1244. $title = [
  1245. '序号',
  1246. '归属人',
  1247. '创建时间',
  1248. '下次联系时间',
  1249. '最后跟进时间',
  1250. ];
  1251. $dataValue = Form::getDataValue(Form::CUSTOMER_TYPE);
  1252. foreach ($dataValue as $val) {
  1253. $title[] = $val['config']['label'];
  1254. }
  1255. outFileLog($dataValue,'customer','list-export-$dataValue');
  1256. $data=[];
  1257. foreach ($list as $k => $v) {
  1258. if($v['customer_other']){//其他客户
  1259. $other=$v['customer_other']['otherdata'];
  1260. $other=json_decode($other,true);
  1261. $v = array_merge($v, $other);
  1262. }
  1263. $field = array(
  1264. $v['id'],
  1265. 3,
  1266. $v['createtime'],
  1267. $v['next_time'],
  1268. $v['last_time'],
  1269. );
  1270. foreach ($dataValue as $val) {
  1271. if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
  1272. $field[] = $v[$val['id'] . '_str'] ?? '';
  1273. } else {
  1274. $field[] = ($v[$val['id']] ?? '');
  1275. }
  1276. }
  1277. $data[] = $field;
  1278. }
  1279. $file = export_excel($title, $data, '客户');
  1280. if ($file['filePath']) {
  1281. $this->success('导出成功', '', $file);
  1282. }
  1283. $this->error('导出失败');
  1284. }
  1285. /**
  1286. * 导出word
  1287. */
  1288. public function words($ids = null)
  1289. {
  1290. if ($this->request->isPost()) {
  1291. $file = input('file', '');
  1292. $is_template=input('is_template',0);
  1293. $template_name=input('template_name','');
  1294. if (empty($file)) {
  1295. $this->error('导出模板');
  1296. }
  1297. if($is_template == 1){
  1298. if(empty($template_name)){
  1299. $this->error('模板名称不能为空');
  1300. }
  1301. $create=[
  1302. 'type'=>'customer',
  1303. 'name'=>$template_name,
  1304. 'url'=>$file
  1305. ];
  1306. $wordTemplateModel = new WordTemplate();
  1307. $wordTemplateModel->save($create);
  1308. }
  1309. $tmp = new TemplateProcessor('.' . $file);
  1310. Settings::setCompatibility(true);
  1311. Settings::setOutputEscapingEnabled(true);
  1312. $row = $this->model::get($ids);
  1313. $row = $row->toArray();
  1314. $row = CustomerOther::getOther($row);
  1315. $form = Form::getDataValue(Form::CUSTOMER_TYPE);
  1316. $imgNames=[];
  1317. foreach($form as $k=>$v){
  1318. if($v['component'] == 'uploadImage'){
  1319. $imgNames[]=$v['id'];
  1320. }
  1321. }
  1322. foreach ($row as $key => $item) {
  1323. if(in_array($key,$imgNames) && $item ){
  1324. if(is_array($item)){
  1325. foreach ($item as $it){
  1326. $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
  1327. }
  1328. }else{
  1329. $fileinfo = File::where(['id'=>['in',$item]])->field('id,name,file_path,save_name')->select();
  1330. foreach ($fileinfo as $it){
  1331. $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
  1332. }
  1333. }
  1334. }else{
  1335. if(is_array($item)){
  1336. $tmp->setValue($key , '');//
  1337. continue;
  1338. }
  1339. $tmp->setValue($key , $item);//
  1340. }
  1341. }
  1342. $contacts = Contacts::where(['customer_id' => $ids])->find();
  1343. if ($contacts) {
  1344. $contacts=$contacts->toArray();
  1345. $contacts = ContactsOther::getOther($contacts);
  1346. foreach ($contacts as $key => $item) {
  1347. if(is_array($item)){
  1348. continue;
  1349. }
  1350. if ($key == 'name') {
  1351. $key = 'con_name';
  1352. }
  1353. if ($key == 'subname') {
  1354. $key = 'con_subname';
  1355. }
  1356. $tmp->setValue($key, $item);//
  1357. }
  1358. }else{
  1359. $form = Form::getDataValue(Form::CONTACTS_TYPE);
  1360. foreach ($form as $f) {
  1361. if ($f['id'] == 'name') {
  1362. $f['id'] = 'con_name';
  1363. }
  1364. if ($f['id'] == 'subname') {
  1365. $f['id'] = 'con_subname';
  1366. }
  1367. $tmp->setValue($f['id'], '');//
  1368. }
  1369. }
  1370. //end 配置
  1371. $filename = $row['name'];
  1372. $filepath = $filename . '.docx';
  1373. $fileurl = './uploads/' . date('Ymd') . '/';
  1374. if (!file_exists($fileurl)) {
  1375. mkdir($fileurl);
  1376. }
  1377. $tmp->saveAs($fileurl . $filepath);//另存为
  1378. $model = new File();
  1379. $data = [
  1380. 'types' => 'file',
  1381. 'name' => $filepath,
  1382. 'save_name' => $fileurl . $filepath,
  1383. 'size' => filesize($fileurl . $filepath),
  1384. 'file_path' => trim($fileurl, '.') . $filepath,
  1385. ];
  1386. $model->save($data);
  1387. $lastid = $model->id;
  1388. $file = cdnurl($model::getUrl($lastid), true);
  1389. $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filepath]);
  1390. }
  1391. $form = Form::getDataValue(Form::CUSTOMER_TYPE);
  1392. $column = array();
  1393. foreach ($form as $k => $v) {
  1394. if ($v['config']['label'] == '备注信息') {
  1395. $v['config']['label'] = '客户备注';
  1396. }
  1397. $column[] = array(
  1398. 'key' => $v['id'],
  1399. 'name' => $v['config']['label'],
  1400. );
  1401. }
  1402. $templates=WordTemplate::where(['type'=>'customer'])->select();
  1403. $contacts = Form::getDataValue(Form::CONTACTS_TYPE);
  1404. $columns = array();
  1405. foreach ($contacts as $k => $v) {
  1406. if ($v['id'] == 'name') {
  1407. $v['id'] = 'con_name';
  1408. }
  1409. if ($v['id'] == 'subname') {
  1410. $v['id'] = 'con_subname';
  1411. }
  1412. if ($v['config']['label'] == '备注信息') {
  1413. $v['config']['label'] = '联系人备注';
  1414. }
  1415. $columns[] = array(
  1416. 'key' => $v['id'],
  1417. 'name' => $v['config']['label'],
  1418. );
  1419. }
  1420. $column = array_merge($column, $columns);
  1421. $this->assign('column', $column);
  1422. $this->assign('templates', $templates);
  1423. $this->assign('ids', $ids);
  1424. return $this->view->fetch();
  1425. }
  1426. }