Customer.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  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. unset($wheres['owner_staff_id']);
  1221. $list = $this->model->where($where)->with(['ownerStaff','customerOther'])
  1222. ->where($wheres)
  1223. ->where(function ($query) use ($staff_id, $owner_staff_id, $type) {
  1224. if ($type == 0) {//全部
  1225. $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
  1226. ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
  1227. ->whereOr(['owner_staff_id' => $owner_staff_id]);
  1228. } else {
  1229. $query->where(['owner_staff_id' => $owner_staff_id]);
  1230. }
  1231. })
  1232. ->where('owner_staff_id != 0 and owner_staff_id is not null')->order($sort, $order)->select();
  1233. $list = collection($list)->toArray();
  1234. outFileLog($list,'customer','list-export');
  1235. if (!$list) {
  1236. $this->error('无导出数据');
  1237. }
  1238. $title = [
  1239. '序号',
  1240. '归属人',
  1241. '创建时间',
  1242. '下次联系时间',
  1243. '最后跟进时间',
  1244. ];
  1245. $dataValue = Form::getDataValue(Form::CUSTOMER_TYPE);
  1246. foreach ($dataValue as $val) {
  1247. $title[] = $val['config']['label'];
  1248. }
  1249. $data=[];
  1250. foreach ($list as $k => $v) {
  1251. if($v['customer_other']){//其他客户
  1252. $other=$v['customer_other']['otherdata'];
  1253. $other=json_decode($other,true);
  1254. $v = array_merge($v, $other);
  1255. }
  1256. $field = array(
  1257. $v['id'],
  1258. $v['owner_staff']['name'],
  1259. $v['createtime'],
  1260. $v['next_time'],
  1261. $v['last_time'],
  1262. );
  1263. foreach ($dataValue as $val) {
  1264. if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
  1265. $field[] = $v[$val['id'] . '_str'] ?? '';
  1266. } else {
  1267. $field[] = ($v[$val['id']] ?? '');
  1268. }
  1269. }
  1270. $data[] = $field;
  1271. }
  1272. $file = export_excel($title, $data, '客户');
  1273. if ($file['filePath']) {
  1274. $this->success('导出成功', '', $file);
  1275. }
  1276. $this->error('导出失败');
  1277. }
  1278. /**
  1279. * 导出word
  1280. */
  1281. public function words($ids = null)
  1282. {
  1283. if ($this->request->isPost()) {
  1284. $file = input('file', '');
  1285. $is_template=input('is_template',0);
  1286. $template_name=input('template_name','');
  1287. if (empty($file)) {
  1288. $this->error('导出模板');
  1289. }
  1290. if($is_template == 1){
  1291. if(empty($template_name)){
  1292. $this->error('模板名称不能为空');
  1293. }
  1294. $create=[
  1295. 'type'=>'customer',
  1296. 'name'=>$template_name,
  1297. 'url'=>$file
  1298. ];
  1299. $wordTemplateModel = new WordTemplate();
  1300. $wordTemplateModel->save($create);
  1301. }
  1302. $tmp = new TemplateProcessor('.' . $file);
  1303. Settings::setCompatibility(true);
  1304. Settings::setOutputEscapingEnabled(true);
  1305. $row = $this->model::get($ids);
  1306. $row = $row->toArray();
  1307. $row = CustomerOther::getOther($row);
  1308. $form = Form::getDataValue(Form::CUSTOMER_TYPE);
  1309. $imgNames=[];
  1310. foreach($form as $k=>$v){
  1311. if($v['component'] == 'uploadImage'){
  1312. $imgNames[]=$v['id'];
  1313. }
  1314. }
  1315. foreach ($row as $key => $item) {
  1316. if(in_array($key,$imgNames) && $item ){
  1317. if(is_array($item)){
  1318. foreach ($item as $it){
  1319. $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
  1320. }
  1321. }else{
  1322. $fileinfo = File::where(['id'=>['in',$item]])->field('id,name,file_path,save_name')->select();
  1323. foreach ($fileinfo as $it){
  1324. $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
  1325. }
  1326. }
  1327. }else{
  1328. if(is_array($item)){
  1329. $tmp->setValue($key , '');//
  1330. continue;
  1331. }
  1332. $tmp->setValue($key , $item);//
  1333. }
  1334. }
  1335. $contacts = Contacts::where(['customer_id' => $ids])->find();
  1336. if ($contacts) {
  1337. $contacts=$contacts->toArray();
  1338. $contacts = ContactsOther::getOther($contacts);
  1339. foreach ($contacts as $key => $item) {
  1340. if(is_array($item)){
  1341. continue;
  1342. }
  1343. if ($key == 'name') {
  1344. $key = 'con_name';
  1345. }
  1346. if ($key == 'subname') {
  1347. $key = 'con_subname';
  1348. }
  1349. $tmp->setValue($key, $item);//
  1350. }
  1351. }else{
  1352. $form = Form::getDataValue(Form::CONTACTS_TYPE);
  1353. foreach ($form as $f) {
  1354. if ($f['id'] == 'name') {
  1355. $f['id'] = 'con_name';
  1356. }
  1357. if ($f['id'] == 'subname') {
  1358. $f['id'] = 'con_subname';
  1359. }
  1360. $tmp->setValue($f['id'], '');//
  1361. }
  1362. }
  1363. //end 配置
  1364. $filename = $row['name'];
  1365. $filepath = $filename . '.docx';
  1366. $fileurl = './uploads/' . date('Ymd') . '/';
  1367. if (!file_exists($fileurl)) {
  1368. mkdir($fileurl);
  1369. }
  1370. $tmp->saveAs($fileurl . $filepath);//另存为
  1371. $model = new File();
  1372. $data = [
  1373. 'types' => 'file',
  1374. 'name' => $filepath,
  1375. 'save_name' => $fileurl . $filepath,
  1376. 'size' => filesize($fileurl . $filepath),
  1377. 'file_path' => trim($fileurl, '.') . $filepath,
  1378. ];
  1379. $model->save($data);
  1380. $lastid = $model->id;
  1381. $file = cdnurl($model::getUrl($lastid), true);
  1382. $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filepath]);
  1383. }
  1384. $form = Form::getDataValue(Form::CUSTOMER_TYPE);
  1385. $column = array();
  1386. foreach ($form as $k => $v) {
  1387. if ($v['config']['label'] == '备注信息') {
  1388. $v['config']['label'] = '客户备注';
  1389. }
  1390. $column[] = array(
  1391. 'key' => $v['id'],
  1392. 'name' => $v['config']['label'],
  1393. );
  1394. }
  1395. $templates=WordTemplate::where(['type'=>'customer'])->select();
  1396. $contacts = Form::getDataValue(Form::CONTACTS_TYPE);
  1397. $columns = array();
  1398. foreach ($contacts as $k => $v) {
  1399. if ($v['id'] == 'name') {
  1400. $v['id'] = 'con_name';
  1401. }
  1402. if ($v['id'] == 'subname') {
  1403. $v['id'] = 'con_subname';
  1404. }
  1405. if ($v['config']['label'] == '备注信息') {
  1406. $v['config']['label'] = '联系人备注';
  1407. }
  1408. $columns[] = array(
  1409. 'key' => $v['id'],
  1410. 'name' => $v['config']['label'],
  1411. );
  1412. }
  1413. $column = array_merge($column, $columns);
  1414. $this->assign('column', $column);
  1415. $this->assign('templates', $templates);
  1416. $this->assign('ids', $ids);
  1417. return $this->view->fetch();
  1418. }
  1419. }