Customer.php 55 KB

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