Customer.php 56 KB

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