| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021 |
- <?php
- namespace app\admin\controller\qingdong\customer;
- use addons\qingdong\model\BusinessStatus;
- use addons\qingdong\model\Customer;
- use addons\qingdong\model\Field;
- use addons\qingdong\model\File;
- use addons\qingdong\model\BusinessProduct;
- use addons\qingdong\model\FormField;
- use addons\qingdong\model\Product;
- use addons\qingdong\model\Staff;
- use app\admin\controller\qingdong\Base;
- use addons\qingdong\model\BusinessOther;
- use addons\qingdong\model\Form;
- use addons\qingdong\model\Contract;
- use addons\qingdong\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;
- /**
- * 商机管理
- */
- class Business extends Base
- {
- protected $relationSearch = true;
- /**
- * @var \addons\qingdong\model\Business
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \addons\qingdong\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']);
- }
- 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([])->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->withTrashed()->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');
- if(!$fieldnames){
- $this->error('请在系统管理->字段管理中保存商机管理表单生成商机导入字段');
- }
- $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('导出失败');
- }
- }
|