12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031 |
- <?php
- namespace app\admin\controller\qingdongams\customer;
- use addons\qingdongams\model\BusinessStatus;
- use addons\qingdongams\model\Customer;
- use addons\qingdongams\model\Field;
- use addons\qingdongams\model\File;
- use addons\qingdongams\model\BusinessProduct;
- use addons\qingdongams\model\FormField;
- use addons\qingdongams\model\Product;
- use addons\qingdongams\model\Staff;
- use app\admin\controller\qingdongams\Base;
- use addons\qingdongams\model\BusinessOther;
- use addons\qingdongams\model\Form;
- use addons\qingdongams\model\Contract;
- use addons\qingdongams\model\Record;
- use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
- use PhpOffice\PhpSpreadsheet\Reader\Csv;
- use PhpOffice\PhpSpreadsheet\Reader\Xls;
- use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
- use PhpOffice\PhpSpreadsheet\RichText\RichText;
- use think\Db;
- use think\Exception;
- /**
- * 商机管理
- * @icon fa fa-handshake-o
- */
- class Business extends Base
- {
- protected $relationSearch = true;
- /**
- * @var \addons\qingdongams\model\Business
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \addons\qingdongams\model\Business;
- }
- /**
- * 查看
- */
- public function index()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
- $type = input('type', 0);
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- switch ($type) {
- case 1:
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 2:
- $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
- break;
- case 3:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach ($record as $k => $v) {
- $whereRe['id'] = array('gt', $v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if ($recordData == 0) {
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in', $relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 4:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach ($record as $k => $v) {
- $whereRe['id'] = array('gt', $v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if ($recordData >= 1) {
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in', $relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 5:
- $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
- $wheres['id'] = array('not in', $record);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- default:
- $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
- break;
- }
- $ids = [];
- $group_id = input('group_id');
- $staff_id = input('staff_id');
- if ($group_id) {//角色组
- $ids = Staff::getGroupStaffIds($group_id);
- }
- if ($staff_id) {
- $ids = $staff_id;
- }
- if ($group_id || $staff_id) {
- $wheres['owner_staff_id'] = ['in', $ids];
- }
- $list = $this->model->where($where)
- ->where($wheres)
- ->with([
- 'customer',
- 'ownerStaff',
- 'product'
- ])->order($sort, $order)->paginate($limit);
- foreach ($list as $k => $v) {
- $types = BusinessStatus::where(array('business_id' => $v['id']))->order('id desc')->value('type');
- $list[$k]['type'] = $types ? (int)$types : 0;
- }
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- $field = FormField::getFields(FormField::BUSINESS_TYPE);
- $this->assignconfig('fields', $field);
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params);
- if ($result !== true) {
- $this->error($result);
- }
- $result = false;
- Db::startTrans();
- try {
- $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);
- if ($params['product']) {
- $params['product'] = json_decode($params['product'], true);
- }
- $result = $this->model::createBusiness($params);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $customer_id = input('customer_id');
- $this->assign('customer_id', $customer_id);
- $this->assign('customer', Customer::get($customer_id));
- $this->assign('staffs', Staff::allList());
- $this->assign('form_data', Form::getDataValue('business'));
- return $this->view->fetch();
- }
- /**
- * 修改
- */
- public function edit($ids = null)
- {
- $map['id'] = $ids;
- if ($this->request->isAjax()) {
- $params = $this->request->post('row/a');
- $params = $this->preExcludeFields($params);
- $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params, $ids);
- if ($result !== true) {
- $this->error($result);
- }
- Db::startTrans();
- try {
- $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);
- $params['id'] = $ids;
- $result = $this->model::updateBusiness($params);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $row = $this->model->where($map)->with(['customer'])->find();
- $product = BusinessProduct::where(['business_id' => $ids])->with(['productinfo'])->select();
- foreach ($product as $k => $v) {
- if ($v['productinfo']) {
- $v['product_name'] = $v['productinfo']['name'];
- $v['cost_price'] = $v['productinfo']['cost_price'];
- $v['type'] = $v['productinfo']['type'];
- if ($v['productinfo']['goods']) {
- $v['goods_name'] = $v['productinfo']['goods']['name'];
- }
- }
- $product[$k] = $v;
- }
- $row['product'] = json_encode($product);
- $row = $row->toArray();
- $row = BusinessOther::getOther($row);
- $this->view->assign("row", $row);
- $this->assign('customers', Customer::getList());
- $this->assign('form_data', Form::getDataValue('business', $row));
- return $this->view->fetch();
- }
- /**
- * 详情
- */
- public function detail($ids = null)
- {
- $row = $this->model->where(['id' => $ids])->with([
- 'customer',
- 'ownerStaff'
- ])->find();
- if (empty($row)) {
- $this->error(__('No Results were found'));
- }
- $row = $row->toArray();
- $row = BusinessOther::getOther($row);
- //跟进记录
- $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
- $type = BusinessStatus::where(array('business_id' => $ids))->order('id desc')->value('type');
- $row['type'] = $type ? (int)$type : 0;
- $this->assign('row', $row);
- $this->assign('ids', $ids);
- $this->assign('form_data', Form::getDataValue('business', $row));
- $this->assignconfig("idinfo", ['id' => $ids]);
- return $this->view->fetch();
- }
- /**
- * 添加跟进
- */
- public function record($ids = null)
- {
- if ($this->request->isPost()) {
- $params = $this->request->post('row/a');
- $params['relation_type'] = 5;
- $params['relation_id'] = $ids;
- if (!empty($params['files'])) {
- $params['files'] = File::getId($params['files']);
- }
- $reminds_id = $this->request->post('reminds_id/a');
- $params['reminds_id']='';
- if($reminds_id){
- $params['reminds_id'] = implode(',',$reminds_id);
- }
- Db::startTrans();
- try {
- $result = Record::createRecord($params);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result) {
- $this->success('创建跟进记录成功');
- }
- $this->error('创建失败');
- }
- $staff = Staff::where(['status'=>1])->column('name', 'id');
- $follow = Field::getField('商机阶段');
- $this->assign('follow', $follow);
- $this->assign('ids', $ids);
- $this->assign('staff', $staff);
- return $this->view->fetch();
- }
- /**
- * 批量转移商机
- */
- public function batch_change($ids = null)
- {
- $ids = json_decode($ids, true);
- $ids = $this->model->where([
- 'id' => ['in', $ids]
- ])->column('id');
- if (empty($ids)) {
- $this->error(__('No Results were found'));
- }
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- $result = false;
- Db::startTrans();
- try {
- $result = $this->model::batchTransfer($ids, $params['owner_staff_id']);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $staffs = Staff::getList();
- $this->assign('staffs', $staffs);
- $this->assign('ids', json_encode($ids));
- return $this->view->fetch();
- }
- /**
- * 产品信息
- */
- public function product()
- {
- $this->request->filter(['strip_tags']);
- if ($this->request->isAjax()) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $business_id = input('business_id');
- $wheres['business_product.business_id'] = $business_id;
- $list = BusinessProduct::where($where)->where($wheres)->with(['product'])->order($sort, $order)->paginate($limit);
- foreach ($list as $k => $v) {
- if (!$v['product']['id']) {
- unset($list[$k]);
- }
- }
- $row = $list->items();
- $result = array("total" => $list->total(), "rows" => $row);
- return json($result);
- }
- return $this->view->fetch();
- }
- /**
- * 获取相关合同
- */
- public function get_contract()
- {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $business_id = input('business_id');
- $wheres['business_id'] = $business_id;
- $list = Contract::where([
- 'business_id' => $business_id,
- ])->with('customer')->paginate($limit);
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- /**
- * 删除商机
- */
- public function delete($ids = null)
- {
- if (!$ids) {
- $this->error('参数不正确');
- }
- $data = $this->model->where([
- 'id' => $ids
- ])->column('id');
- if (empty($data)) {
- $this->error('商机不存在');
- }
- $result = $this->model->where(array('id' => $ids))->update(array('updatetime' => time(), 'deletetime' => time()));
- if (!$result) {
- $this->error('删除失败');
- }
- $this->success('删除成功');
- }
- /**
- * 推进商机
- */
- public function batch_status($ids = null)
- {
- $ids = $this->model->where([
- 'id' => $ids
- ])->value('id');
- if (empty($ids)) {
- $this->error('商机不存在');
- }
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- if (!empty($params['file'])) {
- $params['file'] = File::getId($params['file']);
- }
- $result = false;
- Db::startTrans();
- try {
- $params['id'] = $ids;
- $result = $this->model::batchStatus($params);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error('推进失败');
- }
- }
- $this->error('推进失败');
- }
- return $this->view->fetch();
- }
- /**
- * 获取推进商机
- */
- public function get_business_status()
- {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $business_id = input('business_id');
- $wheres['business_id'] = $business_id;
- $list = BusinessStatus::where([
- 'business_id' => $business_id,
- ])->order('id desc')->paginate($limit);
- foreach ($list as $k => $v) {
- if ($v['file']) {
- $list[$k]['file'] = File::where(array('id' => ['in', $v['file']]))->select();
- }
- }
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- /**
- * 导入客户
- * @return string|void
- */
- public function import()
- {
- set_time_limit(0);
- if ($this->request->isPost()) {
- $file = $this->request->request('file');
- $staff_id = $this->request->request('staff_id', 0);
- if (!$file) {
- $this->error(__('Parameter %s can not be empty', 'file'));
- }
- $filePath = ROOT_PATH . 'public' . $file;
- if (!is_file($filePath)) {
- $this->error(__('No results were found'));
- }
- //实例化reader
- $ext = pathinfo($filePath, PATHINFO_EXTENSION);
- if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
- $this->error(__('Unknown data format'));
- }
- if ($ext === 'csv') {
- $file = fopen($filePath, 'r');
- $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
- $fp = fopen($filePath, "w");
- $n = 0;
- while ($line = fgets($file)) {
- $line = rtrim($line, "\n\r\0");
- $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
- if ($encoding != 'utf-8') {
- $line = mb_convert_encoding($line, 'utf-8', $encoding);
- }
- if ($n == 0 || preg_match('/^".*"$/', $line)) {
- fwrite($fp, $line . "\n");
- } else {
- fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
- }
- $n++;
- }
- fclose($file) || fclose($fp);
- $reader = new Csv();
- } elseif ($ext === 'xls') {
- $reader = new Xls();
- } else {
- $reader = new Xlsx();
- }
- if (!$PHPExcel = $reader->load($filePath)) {
- $this->error(__('Unknown data format'));
- }
- $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
- $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
- $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
- $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
- //开始读取数据
- $fields = [];
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $fields[$currentRow][] = $val;
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? '' : trim($val);
- }
- }
- if (!isset($fields[1])) {
- $this->error('导入文件第一行没有数据');
- }
- $lastid = $this->model->order('id desc')->value('id');
- $lastid = $lastid + 5;//防止重复
- $customerRow = [];
- $errorInfo = [];
- $customerNames = Customer::where([])->column('id,owner_staff_id', 'name');
- $fieldnames = FormField::where(['types' => FormField::BUSINESS_TYPE])->column('field', 'name');
- $fn = [];
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $values[] = is_null($val) ? '' : $val;
- }
- foreach ($values as $l) {
- $fn[] = $fieldnames[$l] ?? '';
- }
- }
- for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? NULL : trim($val);
- }
- $lastid++;
- $addBusiness = ['id' => $lastid];
- $customer = isset($customerNames[$values[0]]) ? $customerNames[$values[0]] : 0;
- if (empty($customer)) {
- $errorInfo[] = "第{$currentRow}行,客户名称不存在;";
- continue;
- }
- $addBusiness['customer_id'] = $customer['id'];
- $addBusiness['owner_staff_id'] = $customer['owner_staff_id'];
- foreach ($values as $kv => $value) {
- if (!isset($fn[$kv]) || empty($fn[$kv])) {
- continue;
- }
- $addBusiness[$fn[$kv]] = $value;
- }
- if (empty($addBusiness['name'])) {
- $errorInfo[] = "第{$currentRow}行,商机名称不能为空;";
- continue;
- }
- $customerRow[] = $addBusiness;
- }
- if (!empty($errorInfo)) {
- $this->error(implode(',', $errorInfo));
- }
- Db::startTrans();
- try {
- $this->model::importBusiness($customerRow);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('导入成功');
- }
- $this->assign('staffs', Staff::getList());
- return $this->view->fetch();
- }
- /**
- * 模板
- */
- public function template()
- {
- $title = ['客户名称'];
- $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);
- foreach ($dataValue as $val) {
- $title[] = $val['config']['label'];
- }
- $file = export_excel($title, [], '商机');
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename=' . $file['fileName']);
- header('Cache-Control: max-age=0');
- $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
- // 以下内容是excel文件的信息描述信息
- $obj->getProperties()->setTitle('导出文件'); //设置标题
- $obj->setActiveSheetIndex(0);
- $obj->getActiveSheet()->setTitle('导出文件');
- /* 循环读取每个单元格的数据 */
- $a = 'A';
- $currentSheet = $obj->getActiveSheet();
- foreach ($title as $key => $value) {
- //读取工作表1
- // 设置第一行加粗
- $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
- //这里是设置单元格的内容
- $currentSheet->getCell($a . '1')->setValue($value);
- $a++;
- }
- $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
- $PHPWriter->save('php://output');
- }
- /**
- * 导出信息
- */
- public function export()
- {
- $this->request->filter(['strip_tags', 'trim']);
- $ids = input('ids');
- $isall = input('isall', 1);
- $wheres = array();
- //导出其中几条
- if (isset($ids) && $ids) {
- $wheres['id'] = array('in', $ids);
- }
- //导出全部
- if ($isall == 3) {
- unset($wheres['id']);
- }
- //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
- $type = input('type', 0);
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $staff = Staff::info();
- $staff_id = $staff->id;
- switch ($type) {
- case 1:
- $wheres['owner_staff_id'] = $staff_id;
- break;
- case 2:
- $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
- break;
- case 3:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach ($record as $k => $v) {
- $whereRe['id'] = array('gt', $v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if ($recordData == 0) {
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in', $relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 4:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach ($record as $k => $v) {
- $whereRe['id'] = array('gt', $v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if ($recordData >= 1) {
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in', $relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 5:
- $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
- $wheres['id'] = array('not in', $record);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- default:
- $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
- break;
- }
- $list = $this->model->with([
- 'ownerStaff', 'businessOther', 'customer'
- ])->where($where)->where($wheres)->order($sort, $order)->select();
- $list = collection($list)->toArray();
- if (!$list) {
- $this->error('无导出数据');
- }
- $title = [
- '序号',
- '客户名称',
- '负责人',
- '创建时间',
- '下次联系时间',
- ];
- $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);
- foreach ($dataValue as $val) {
- $title[] = $val['config']['label'];
- }
- foreach ($list as $k => $v) {
- if ($v['business_other']) {//其他客户
- $other = $v['business_other']['otherdata'];
- $other = json_decode($other, true);
- $v = array_merge($v, $other);
- }
- $field = array(
- $v['id'],
- $v['customer']['name'],
- $v['owner_staff']['name'],
- date('Y-m-d H:i:s', $v['createtime']),
- $v['next_time'],
- );
- foreach ($dataValue as $val) {
- if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
- $field[] = $v[$val['id'] . '_str'] ?? '';
- } else {
- $field[] = ($v[$val['id']] ?? '');
- }
- }
- $data[] = $field;
- }
- $file = export_excel($title, $data, '商机');
- if ($file['filePath']) {
- $this->success('导出成功', '', $file);
- }
- $this->error('导出失败');
- }
- /**
- * 导入产品明细
- * @return string|void
- */
- public function import_product()
- {
- set_time_limit(0);
- if ($this->request->isPost()) {
- $file = $this->request->request('file');
- if (!$file) {
- $this->error(__('Parameter %s can not be empty', 'file'));
- }
- $filePath = ROOT_PATH . 'public' . $file;
- if (!is_file($filePath)) {
- $this->error(__('No results were found'));
- }
- //实例化reader
- $ext = pathinfo($filePath, PATHINFO_EXTENSION);
- if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
- $this->error(__('Unknown data format'));
- }
- if ($ext === 'csv') {
- $file = fopen($filePath, 'r');
- $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
- $fp = fopen($filePath, "w");
- $n = 0;
- while ($line = fgets($file)) {
- $line = rtrim($line, "\n\r\0");
- $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
- if ($encoding != 'utf-8') {
- $line = mb_convert_encoding($line, 'utf-8', $encoding);
- }
- if ($n == 0 || preg_match('/^".*"$/', $line)) {
- fwrite($fp, $line . "\n");
- } else {
- fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
- }
- $n++;
- }
- fclose($file) || fclose($fp);
- $reader = new Csv();
- } elseif ($ext === 'xls') {
- $reader = new Xls();
- } else {
- $reader = new Xlsx();
- }
- if (!$PHPExcel = $reader->load($filePath)) {
- $this->error(__('Unknown data format'));
- }
- $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
- $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
- $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
- $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
- //开始读取数据
- $fields = [];
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $fields[$currentRow][] = $val;
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? '' : trim($val);
- }
- }
- if (!isset($fields[1])) {
- $this->error('导入文件第一行没有数据');
- }
- $lastid = BusinessProduct::order('id desc')->value('id');
- $lastid = $lastid + 5;//防止重复
- $businessProductRow = [];
- $errorInfo = [];
- $businessName = $this->model::where([])->column('id,name,money', 'name');
- $productName = Product::where([])->column('id,price', 'name');
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $values[] = is_null($val) ? '' : $val;
- }
- }
- for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? NULL : trim($val);
- }
- $lastid++;
- $addContractProduct = ['id' => $lastid];
- $business = isset($businessName[$values[0]]) ? $businessName[$values[0]] : 0;
- if (empty($business)) {
- $errorInfo[] = "第{$currentRow}行,商机名称不存在;";
- continue;
- }
- $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
- if (empty($product)) {
- $errorInfo[] = "第{$currentRow}行,产品名称不存在;";
- continue;
- }
- if (empty($values[2])) {
- $errorInfo[] = "第{$currentRow}行,产品数量不能为空;";
- continue;
- }
- if (empty($values[3])) {
- $errorInfo[] = "第{$currentRow}行,产品售价不能为空;";
- continue;
- }
- $addContractProduct['business_id'] = $business['id'];
- $addContractProduct['product_id'] = $product['id'];
- $addContractProduct['number'] = $values[2];
- $addContractProduct['price'] = $values[3];
- $businessProductRow[] = $addContractProduct;
- }
- if (!empty($errorInfo)) {
- $this->error(implode(',', $errorInfo));
- }
- Db::startTrans();
- try {
- BusinessProduct::importProduct($businessProductRow);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('导入成功');
- }
- $this->assign('staffs', Staff::getList());
- return $this->view->fetch();
- }
- /**
- * 模板
- */
- public function template_product()
- {
- $title = [
- '商机名称',
- '商品名称',
- '数量',
- '售价',
- ];
- $file = export_excel($title, [], '产品明细');
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename=' . $file['fileName']);
- header('Cache-Control: max-age=0');
- $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
- // 以下内容是excel文件的信息描述信息
- $obj->getProperties()->setTitle('导出文件'); //设置标题
- $obj->setActiveSheetIndex(0);
- $obj->getActiveSheet()->setTitle('导出文件');
- /* 循环读取每个单元格的数据 */
- $a = 'A';
- $currentSheet = $obj->getActiveSheet();
- foreach ($title as $key => $value) {
- //读取工作表1
- // 设置第一行加粗
- $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
- //这里是设置单元格的内容
- $currentSheet->getCell($a . '1')->setValue($value);
- $a++;
- }
- $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
- $PHPWriter->save('php://output');
- }
- /**
- * 导出信息
- */
- public function export_product()
- {
- $this->request->filter(['strip_tags', 'trim']);
- $ids = input('ids');
- $type = input('type');
- $wheres = array();
- //导出其中几条
- if (isset($ids)) {
- $wheres['business_id'] = array('in', $ids);
- }
- //导出全部
- if (isset($type)) {
- if ($type == 3) {
- unset($wheres['business_id']);
- }
- }
- $list = BusinessProduct::where($wheres)->with(['business', 'productinfo'])->select();
- $list = collection($list)->toArray();
- if (!$list) {
- $this->error('无导出数据');
- }
- $title = [
- '序号',
- '商机名称',
- '商品名称',
- '售价',
- '批发价',
- '产品',
- '规格',
- '数量',
- ];
- foreach ($list as $k => $v) {
- $field = array(
- $v['id'],
- $v['business']['name'],
- $v['productinfo']['name'] ?? '',
- $v['price'] ?? '',
- $v['productinfo']['cost_price'] ?? '',
- $v['productinfo']['goods']['name'] ?? '',
- $v['productinfo']['unit'] ?? '',
- $v['number'] ?? '',
- );
- $data[] = $field;
- }
- $file = export_excel($title, $data, '产品明细');
- if ($file['filePath']) {
- $this->success('导出成功', '', $file);
- }
- $this->error('导出失败');
- }
- }
|