123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836 |
- <?php
- namespace addons\qingdongams\controller;
- use addons\qingdongams\model\AttendanceRule;
- use addons\qingdongams\model\AttendanceStatisc;
- use addons\qingdongams\model\AttendanceTime;
- use addons\qingdongams\library\JuheExpress;
- use addons\qingdongams\model\Attendance;
- use addons\qingdongams\model\Leads;
- use addons\qingdongams\library\ReceiveMail;
- use addons\qingdongams\model\AdminConfig;
- use addons\qingdongams\model\Contract;
- use addons\qingdongams\model\Customer;
- use addons\qingdongams\model\CustomerType;
- use addons\qingdongams\model\Message;
- use addons\qingdongams\model\Receivables;
- use addons\qingdongams\model\Staff;
- use addons\qingdongams\model\StaffSignIn;
- use addons\qingdongams\model\StaffTeam;
- use addons\qingdongams\model\StaffTeamList;
- use addons\qingdongams\model\Quote;
- use addons\qingdongams\model\Workorder;
- use addons\qingdongams\model\WorkorderLogistics;
- use addons\qingdongams\model\WorkReport;
- use addons\qingdongams\model\Event;
- use addons\qingdongams\model\Record;
- use fast\Http;
- use think\Db;
- use think\Exception;
- use think\Log;
- @header('Content-type: text/html;charset=UTF-8');
- error_reporting(0);
- ignore_user_abort(); // run script in background
- set_time_limit(0); // run script forever
- date_default_timezone_set('Asia/Shanghai');
- class Autotask
- {
- public $mailServer = "pophz.qiye.163.com";
- public $serverType = "pop3";
- public $port = "110";
- protected $now = 0;
- protected $savePath;
- protected $webPath;
- protected $formater = ['gif', 'jpeg', 'png', 'jpg', 'bmp'];
- public function __construct()
- {
- try{
- \think\Db::execute("SET @@sql_mode='';");
- }catch (Exception $e){
- }
- $this->prikey = AdminConfig::where(array('type'=>'wechat','field'=>'email_key'))->value('value');
- $this->savePath = ROOT_PATH;
- $this->webPath = "../emails/";
- }
- //合同到期提醒
- public function contract()
- {
- $endDate = date('Y-m-d', strtotime('+3 day'));
- $contracts = Contract::where(['check_status' => 2, 'contract_status' => 0, 'end_time' => ['lt', $endDate]])->select();
- try {
- //合同即将到期通知
- foreach ($contracts as $v) {
- Message::addMessage(Message::CONTRACT_EXPIRE_TYPE, $v['id'], $v['owner_staff_id'], 0,'合同即将到期,请尽快跟进回款');
- }
- } catch (Exception $e) {
- return $e->getMessage();
- }
- $this->plan();
- $this->visitWorkorderMessage();
- return 'success';
- }
- //回款计划通知
- public function plan()
- {
- $endDate = date('Y-m-d', strtotime('+1 day'));
- //进行中 -- 待回款
- $plans = \addons\qingdongams\model\ReceivablesPlan::where(['status' => 0, 'remind_date' => ['lt', $endDate]])->select();
- try {
- //合同即将到期通知
- foreach ($plans as $v) {
- Message::addMessage(Message::PLAN_EXPIRE_TYPE, $v['contract_id'], $v['owner_staff_id'],0, '已到计划回款约定时间,请尽快跟进回款');
- }
- } catch (Exception $e) {
- return $e->getMessage();
- }
- return 'success';
- }
- //日程提醒
- public function event()
- {
- $endDate = date('Y-m-d H:i:s');
- $events = \addons\qingdongams\model\Event::where(['status' => 0, 'remind_time' => ['lt', $endDate]])->select();
- $endIds = \addons\qingdongams\model\Event::where([
- 'status' => ['in', [0, 1]],
- 'end_time' => ['lt', $endDate]
- ])->column('id');
- try {
- //日程自动结束
- Event::where(['id' => ['in', $endIds]])->update(['status' => 2]);
- //日程时间提醒
- foreach ($events as $v) {
- if (Message::where([
- 'relation_type' => Message::EVENT_TYPE,
- 'relation_id' => $v['id'],
- 'to_staff_id' => $v['staff_id']
- ])->count()) {
- //已经提醒过了
- continue;
- }
- Message::addMessage(Message::EVENT_TYPE, $v['id'], $v['staff_id'],0, $v['title'] . '日程即将开始');
- }
- } catch (Exception $e) {
- return $e->getMessage();
- }
- return 'success';
- }
- //公海
- public function seas()
- {
- if (AdminConfig::getConfigValue('auto', AdminConfig::TYPE_SEAS)) {//自动回收客户
- if (AdminConfig::getConfigValue('genjing', AdminConfig::TYPE_SEAS) == 1) {//未跟进客户回收
- $day = AdminConfig::getConfigValue('genjing_day', AdminConfig::TYPE_SEAS);
- $genjing_c_name = AdminConfig::getConfigValue('genjing_c_name', AdminConfig::TYPE_SEAS);
- $where = [
- 'receivetime' => ['<', strtotime('-' . $day . ' day')],
- 'last_time' => ['<', date('Y-m-d H:i:s', strtotime('-' . $day . ' day'))]];
- if ($genjing_c_name) {
- $where['name'] = ['like', "%{$genjing_c_name}%"];
- }
- if (AdminConfig::getConfigValue('genjing_success', AdminConfig::TYPE_SEAS) == 1) {
- $where['contract_status'] = 0;
- }
- $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
- try {
- foreach ($customers as $c) {
- Customer::moveSeas($c['id']);
- Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0, "您的客户`{$c['name']}`长时间未跟进,已被系统自动回收到公海池内。");
- }
- } catch (Exception $e) {
- Log::error($e->getMessage());
- }
- }
- if (AdminConfig::getConfigValue('chengjiao', AdminConfig::TYPE_SEAS) == 1) {//未成交客户回收
- $day = AdminConfig::getConfigValue('chengjiao_day', AdminConfig::TYPE_SEAS);
- $chengjiao_c_name = AdminConfig::getConfigValue('chengjiao_c_name', AdminConfig::TYPE_SEAS);
- $where = [
- 'receivetime' => ['<', strtotime('-' . $day . ' day')],
- 'contract_status' => 0
- ];
- if ($chengjiao_c_name) {
- $where['name'] = ['like', "%{$chengjiao_c_name}%"];
- }
- $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
- try {
- foreach ($customers as $c) {
- Customer::moveSeas($c['id']);
- Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0, "您的客户`{$c['name']}`长时间未成交,已被系统自动回收到公海池内。");
- }
- } catch (Exception $e) {
- Log::error($e->getMessage());
- }
- }
- }
- return 'success';
- }
- /**
- * 线索池分配
- */
- public function leadpool(){
- if(AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD)){
- $leadauto = AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD);
- $lead_day = AdminConfig::getConfigValue('lead_day', AdminConfig::TYPE_LEAD);
- $attendance = AdminConfig::getConfigValue('leadcard', AdminConfig::TYPE_LEAD);
- $department = AdminConfig::getConfigValue('department', AdminConfig::TYPE_LEAD);
- //开启分配
- if($leadauto == 1 && $lead_day>0 && $department){
- $leadpool = Leads::where('owner_staff_id is null or owner_staff_id = 0')->order('id desc')->limit(100)->column('id');
- if($leadpool){
- $department = explode(',',$department);
- $staffinfo = array();
- foreach($department as $k=>$v){
- $staffids = Staff::where('', 'exp', Db::raw('FIND_IN_SET(' . $v . ',group_ids)'))->where(['status'=>1])->column('id');
- $staffinfo[] = $staffids;
- }
- if(!$staffinfo){
- return '无数据';
- }
- $staffinfos =[];
- foreach($staffinfo as $k=>$v){
- foreach($v as $ks=>$vs){
- $staffinfos[] = $vs;
- }
- }
- $staff = array_unique($staffinfos);
- foreach($leadpool as $ks=>$vs){
- $stafflead =[];
- foreach($staff as $k=>$v){
- if($attendance == 1){ //打卡
- $whereC['staff']= $v;
- $whereC['createtime'] = array(array('egt',strtotime(date('Y-m-d 00:00:00'))),array('elt',strtotime(date('Y-m-d 23:59:59'))));
- $leadcard = Attendance::where($whereC)->find();
- if(!$leadcard){//未打卡不分配
- continue;
- }
- }
- $wherelead['owner_staff_id'] = $v;
- $wherelead['receive_time'] = array(array('egt',strtotime('-'.$lead_day.' days',time())),array('elt',time()));
- $lead = Leads::where($wherelead)->count();
- $stafflead[] = array(
- 'id'=>$v,
- 'num'=>$lead
- );
- }
- if($stafflead){
- $num_count = array_column($stafflead,'num');//返回数组中指定的一列
- array_multisort($num_count,SORT_ASC,$stafflead);
- Leads::where(array('id'=>$vs))->update(array('owner_staff_id'=>$stafflead[0]['id'],'receive_time'=>time()));
- }
- }
- }
- }
- }
- return 'success';
- }
- //工作报告 日志
- public function dayWorkorder()
- {
- $type=input('type');
- if ($type == '日') {
- $time = date('Y-m-d', strtotime('-1 day'));
- $startDate = strtotime($time);
- //月底
- $endDate = strtotime($time . '+1 day') - 1;
- } elseif ($type == '周') {
- $time = date('Y-m-d', strtotime('-1 monday', time()));
- $startDate = strtotime($time);
- //月底
- $endDate = strtotime($time . '+1 week') - 1;
- } elseif ($type == '月') {
- $time = date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));;
- $startDate = strtotime($time);
- //月底
- $endDate = strtotime($time . '+1 month') - 1;
- } elseif ($type == '季') {
- $season = ceil((date('n')) / 3) - 1;
- $time = date('Y-m-d', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
- $startDate = strtotime($time);
- //月底
- $endDate = strtotime($time . '+3 month') - 1;
- } elseif ($type == '年') {
- $time = date('Y-1-1', strtotime('-1 year'));
- $startDate = strtotime($time);
- //月底
- $endDate = strtotime($time . '+1 year') - 1;
- } else {
- return '链接必须带参数';
- }
- $workreportModel = new WorkReport();
- $find = $workreportModel->where([
- 'report_date' => $time,
- 'type' => $type
- ])->find();
- if ($find) {
- return '已生成日报';
- }
- //跟进记录
- $followUp = Record::where([
- 'relation_type' => 1,
- 'createtime' => ['between', [$startDate, $endDate]],
- ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list')->select();
- $followUp = $this->setStaffList($followUp);
- //获客 客户
- $customer = Customer::where([
- 'createtime' => ['between', [$startDate, $endDate]],
- ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
- $customer = $this->setStaffList($customer);
- //合同
- $contract = Contract::where([
- 'createtime' => ['between', [$startDate, $endDate]],
- 'check_status' => 2
- ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list,sum(money) as money')->select();
- $contract = $this->setStaffList($contract);
- //报价
- $quote = Quote::where([
- 'createtime' => ['between', [$startDate, $endDate]],
- 'check_status' => 2
- ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
- $quote = $this->setStaffList($quote);
- //
- $order = \addons\qingdongams\model\Order::where([
-
- 'createtime' => ['between', [$startDate, $endDate]],
- ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
- $order = $this->setStaffList($order);
- //回款次数
- $receivables = Receivables::where([
- 'createtime' => ['between', [$startDate, $endDate]],
- 'check_status' => 2
- ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list,sum(money) as money')->select();
- $receivables = $this->setStaffList($receivables);
- //拜访次数
- $visit = Event::where([
- 'event_type' => ['like',"客户服务%"],
- 'actual_end_time' => ['between', [$startDate, $endDate]],
- 'status' => 2
- ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list,sum(use_time) as time')->select();
- $visit = $this->setStaffList($visit);
- //新建工单
- $workorder = Workorder::where([
- 'createtime' => ['between', [$startDate, $endDate]]
- ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
- $workorder = $this->setStaffList($workorder);
- //完成工单数量
- $completeWorkorder = Workorder::where([
- 'status' => 3,
- 'end_time' => ['between', [$startDate, $endDate]]
- ])->group('owner_staff_id')->field('owner_staff_id,count(*) as count,group_concat(id) as id_list,sum(money) as money')->select();
- $completeWorkorder = $this->setStaffList($completeWorkorder);
- //好评工单
- $goodWorkorder = Workorder::where([
- 'comment_score' => 5,
- 'status' => 3,
- 'end_time' => ['between', [$startDate, $endDate]]
- ])->group('owner_staff_id')->field('owner_staff_id,count(*) as count,group_concat(id) as id_list')->select();
- $goodWorkorder = $this->setStaffList($goodWorkorder);
- //未完成日程
- $notEvent = Event::where([
- 'createtime' => ['between', [$startDate, $endDate]],
- 'status' => ['in', [0, 1]]
- ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list')->select();
- $notEvent = $this->setStaffList($notEvent);
- //完成日程及任务
- $completeEvent = Event::where([
-
- 'actual_end_time' => ['between', [$startDate, $endDate]],
- 'status' => 2
- ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list,sum(use_time) as time')->select();
- $completeEvent = $this->setStaffList($completeEvent);
- $staff = Staff::where(['status'=>1])->field('id,name')->select();
- $insertAll = [];
- foreach ($staff as $v) {
- $customerinfo = $customer[$v['id']] ?? '';
- $visitinfo = $visit[$v['id']] ?? '';
- $quoteinfo = $quote[$v['id']] ?? '';
- $contractinfo = $quote[$v['id']] ?? '';
- $orderinfo = $order[$v['id']] ?? '';
- $receivablesinfo = $receivables[$v['id']] ?? '';
- $workorderinfo = $workorder[$v['id']] ?? '';
- $complete_workorderinfo = $completeWorkorder[$v['id']] ?? '';
- $good_workorderinfo = $goodWorkorder[$v['id']] ?? '';
- $not_eventinfo=$notEvent[$v['id']] ?? '';
- $complete_eventinfo = $completeEvent[$v['id']] ?? '';
- $follow_upinfo = $followUp[$v['id']] ?? '';
- if(!$customerinfo && !$visitinfo && !$quoteinfo && !$contractinfo && !$orderinfo && !$receivablesinfo &&
- !$workorderinfo && !$complete_workorderinfo && !$good_workorderinfo && !$not_eventinfo && !$complete_eventinfo && !$follow_upinfo){
- continue;
- }
- $insertAll[] = [
- 'staff_id' => $v['id'],
- 'report_date' => $time,
- 'type' => $type,
- 'customer' => $customer[$v['id']] ?? '',//获客
- 'visit' => $visit[$v['id']] ?? '',//拜访
- 'quote' => $quote[$v['id']] ?? '',//拜访
- 'contract' => $contract[$v['id']] ?? '',//合同
- 'order' => $order[$v['id']] ?? '',//订单
- 'receivables' => $receivables[$v['id']] ?? '',//回款
- 'workorder' => $workorder[$v['id']] ?? '',//工单
- 'complete_workorder' => $completeWorkorder[$v['id']] ?? '',//完成工单数量
- 'good_workorder' => $goodWorkorder[$v['id']] ?? '',//好评工单数量
- 'not_event' => $notEvent[$v['id']] ?? '',//未完成日程
- 'complete_event' => $completeEvent[$v['id']] ?? '',//已完成日程
- 'follow_up' => $followUp[$v['id']] ?? '',//跟进
- ];
- }
- if(!$insertAll){
- return '数据为空';
- }
- if ($workreportModel->allowField(true)->isUpdate(false)->saveAll($insertAll) == false) {
- return '保存失败';
- }
- $list = $workreportModel->where([ 'report_date' => $time, 'type' => $type])->select();
- foreach ($list as $v) {
- if ($type == '日') {
- $content = $time . '个人日报已经生成';
- } elseif ($type == '周') {
- $content = $time . '上周周报已经生成';
- } elseif ($type == '月') {
- $content = $time . '上月月报已经生成';
- } elseif ($type == '季') {
- $content = $time . '上季季报已经生成';
- } elseif ($type == '年') {
- $content = $time . '上年年报已经生成';
- }
- Message::addMessage(Message::WORKREPORT_TYPE, $v['id'], $v['staff_id'], 0, $content, 7);
- }
- return '成功';
- }
- //查询快递
- public function getCompanys()
- {
- $logistics = WorkorderLogistics::where(['status' => 0])->select();
- $juheExpress = new JuheExpress();
- $workorderLogistics = new WorkorderLogistics();
- foreach ($logistics as $v) {
- $result = $juheExpress->getResult('sf', $v['number'],'7836');
- if(empty($result)){
- continue;
- }
- $list = $result['list'];
- $data = [];
- foreach ($list as $ves) {
- $data[] = ['text' => $ves['datetime'], 'desc' => $ves['remark']];
- }
- $lastList = $data[count($data) - 1];
- $workorderLogistics->where(['id' => $v['id']])->update([
- 'content' => json_encode($data),
- 'current_status' => json_encode($lastList),
- 'status' => $result['status'],
- ]);
- }
- return 'success';
- }
- //生成列表
- private function setStaffList($list)
- {
- $list = collection($list)->toArray();
- $data = [];
- foreach ($list as $v) {
- $staff_id = $v['create_staff_id'] ?? $v['staff_id'] ?? $v['owner_staff_id'];
- $data[$staff_id] = json_encode($v);
- }
- return $data;
- }
- // 销售消息提醒
- public function staffCusTypeRemain(){
- $typeList = CustomerType::where(['cus_status'=>1])->column('days_cus','name');
- if(!$typeList){
- echo '未开启提醒';exit;
- }
- foreach($typeList as $k=>$v){
- $date = date("Y-m-d",strtotime("-$v days"));
- $this->typeStaffMessage($k,$date,$v);
- }
- $this->leaderCusTypeRemain();
- echo "over";
- }
- // 领导消息提醒
- public function leaderCusTypeRemain(){
- $typeList = CustomerType::where(['pid_status'=>1])->column('(days_pid+days_cus)','name');
- if(!$typeList){
- echo '未开启提醒';exit;
- }
- $staffTeam = StaffTeamList::where([])->column('team_id','staff_id');// 员工团队表
- $teamInfo = StaffTeam::where([])->column('staff_id','id');// 团队详情
- foreach($typeList as $k=>$v){
- $date = date("Y-m-d",strtotime("-$v days"));
- $this->typeLeaderMessage($k,$date,$v,$staffTeam,$teamInfo);
- }
- echo "over";
- }
- // 消息提醒
- public function typeStaffMessage($k,$date,$days){
- $customerModel = new Customer();
- $list = collection($customerModel->where(['contract_status'=>0,'type'=>$k,'claimdate'=>$date])->select())->toArray();
- if(!$list) return true;
- foreach ($list as $key=>$v){
- $content = $k.'类客户['.$v['name'].']已领用'.$days.'天,但仍未成交';
- Message::addMessage(Message::CUSTOMER_NODEAL, $v['id'], $v['owner_staff_id'], 0, $content, 10);
- }
- }
- // 消息提醒给领导
- public function typeLeaderMessage($k, $date, $days, $staffTeam, $teamInfo){
- $customerModel = new Customer();
- $list = collection($customerModel->with('ownerStaff')->where(['contract_status'=>0,'type'=>$k,'claimdate'=>$date])->select())->toArray();
- if(!$list) return true;
- foreach ($list as $key=>$v){
- $hasMessage = Message::where(['relation_type'=>Message::CUSTOMER_TYPE_MESSAGE,'relation_id'=>$v['id'],'from_staff_id'=>$v['owner_staff_id']])->find();
- if($hasMessage){
- continue;
- }
- $content = '['.$v['owner_staff']['name'].']下'.$k.'类客户['.$v['name'].']已领用'.$days.'天,但仍未成交';
- $toMessageId = $teamInfo[$staffTeam[$v['owner_staff_id']]];
- Message::addMessage(Message::CUSTOMER_NODEAL, $v['id'], $toMessageId, 0, $content, 10);
- }
- }
- //回访工单提醒
- public function visitWorkorderMessage()
- {
- $workorders = Workorder::where(['status' => 3,
- 'is_visit' => 0,
- 'workorder_type' => ['in', Workorder::getVisitType()],
- 'end_time' => ['lt', time()-86400*3]])->select();
- foreach ($workorders as $v) {
- $content = "工单[{$v['title']}]完成3天后未回访客户,请及时跟进!";
- Message::addMessage(Message::WORKORDER_TYPE, $v['id'], $v['create_staff_id'], 0, $content, 10);
- Message::addMessage(Message::WORKORDER_TYPE, $v['id'], $v['owner_staff_id'], 0, $content, 10);
- }
- return 'success';
- }
- //解析客户地址
- public function customerAddress(){
- $customer=Customer::where('lng','null')->where(['address'=>['neq',''],'address_detail'=>['neq','']])->field('id,address,address_detail')->select();
- foreach ($customer as $v){
- $address=$v['address'].$v['address_detail'];
- if(empty($address)){
- continue;
- }
- $url="https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key=";
- $result=file_get_contents($url);
- $result=json_decode($result,true);
- if(empty($result)){
- continue;
- }
- if($result['status'] == 0){
- $lng=$result['result']['location']['lng'];
- $lat=$result['result']['location']['lat'];
- }else{
- $lng=1;
- $lat=1;
- }
- Customer::where(['id'=>$v['id']])->update(['lng'=>$lng,'lat'=>$lat]);
- }
- return 'success';
- }
- // 邮箱定时 pop 服务器直接请求
- public function autogetemails()
- {
- set_time_limit(0);
- $where['email'] = [['not null',''],['neq',''],'and'];
- $where['email_code'] = [['not null',''],['neq',''],'and'];
- $where['status'] = 1;
- $list = \addons\qingdongams\model\Staff::where($where)->field('id,email,email_code,name')->select();
- if (count($list) < 1) {
- return '失败';
- }
- $list = collection($list)->toArray();
- $emailModel = new \addons\qingdongams\model\ReceiveEmail();
- $genjinModel = new StaffSignIn();
- foreach ($list as $K => $v) {
- $addList = $genjinList = [];
- $obj = new ReceiveMail($v['email'], $v['email_code'], $v['email'], $this->mailServer, $this->serverType, $this->port, false);
- //Connect to the Mail Box
- $res = $obj->connect();
- if (!$res) {
- echo "Error: Connecting to mail server";
- continue;
- }
- // Get Total Number of Unread Email in mail box
- $tot = $obj->getTotalMails(); //Total Mails in Inbox Return integer value
- echo $tot . '封邮件';
- if ($tot < 1) { //如果信件数为0,显示信息
- echo "No Message for " . $v['email'];
- continue;
- } else {
- Db::startTrans();
- try {
- $customerId = '';// 客户id
- for ($i = $tot; $i > 0; $i--) {
- $head = $obj->getHeaders($i); // Get Header Info Return Array Of Headers **Array Keys are (subject,to,toOth,toNameOth,from,fromName)
- Log::write($v['name'] . $i . '头部内容'.json_encode($head));
- if(!$head) continue;
- if ($emailModel->where(['uuid' => $head['udate']])->find()) {
- Log::write($v['name'] . '邮箱:' . $v['email'] . $head['udate'] . '已存储');
- continue;
- }
- $detail = [
- 'uuid' => $head['udate'],
- 'staff_id' => $v['id'],
- 'staff_name' => $v['name'],
- 'from_account' => $head['fromBy'],
- 'from_name' => $head['fromName'],
- 'receivetime' => $head['mailDate'],
- 'theme' => $head['subject'],
- ];
- $customerId = \addons\qingdongams\model\Contacts::where(['email' => $head['fromBy']])->value('customer_id');
- //处理邮件附件
- $files = $obj->GetAttach($i, $this->savePath); // 获取邮件附件,返回的邮件附件信息数组
- Log::write($v['name'] . $i . '附件:----' . json_encode($files));
- $imageList = $attachIds = $imgIds = array();
- if ($files) {
- foreach ($files as $k => $file) {
- //type=1为附件,0为邮件内容图片
- if ($file['type'] == 0) {
- $imageList[$file['title']] = $file['pathname'];
- }
- //附件列表
- $file_path = str_replace('public', '', $file['pathname']);
- $attach = [
- 'types' => 'file',
- 'name' => $file['title'],
- 'save_name' => $file['pathname'],
- 'size' => is_numeric($file['size']) ? $file['size'] : 0,
- 'file_path' => $file_path,
- 'file_path_thumb' => '',
- 'create_staff_id' => $v['id'],
- 'createtime' => time(),
- 'updatetime' => time(),
- ];
- if (in_array($file['extension'], $this->formater)) {
- $attach['types'] = 'image';
- }
- if (!$file = \addons\qingdongams\model\File::create($attach)) {
- // Log::write(\addons\qingdongams\model\File::getError().'----'.\addons\qingdongams\model\File::getLastSql());
- throw new Exception(\addons\qingdongams\model\File::getError() . '----' . \addons\qingdongams\model\File::getLastSql());
- }
- if($attach['types'] == 'image'){
- $imgIds[] = $file->id;
- }else{
- $attachIds[] = $file->id;
- }
- }
- }
- $detail['imgs'] = implode(',', $imgIds);
- $detail['attach'] = implode(',', $attachIds);
- $genjin = [
- 'staff_id' => $v['id'],
- 'location' => '',
- 'lng' => '',
- 'lat' => '',
- 'files' => $detail['attach'],
- 'customer_id' => $customerId,//客户id
- 'relation_type' => StaffSignIn::CUSTOMER_TYPE,//日程类型 客户
- 'relation_id' => $customerId,//签到关联发送邮件id
- 'relation_process' => '邮箱回复',//进度
- 'content' => $head['subject'],
- 'distance' => '',
- ];
- $body = $obj->getBody($i, $this->webPath, $imageList);
- $detail['content'] = $body;
- $addList[] = $detail;
- $genjinList[] = $genjin;
- Log::write($v['name'] . $i . '内容:----' . $body);
- }
- $res = $emailModel->saveAll($addList);
- $res1 = $genjinModel->saveAll($genjinList);
- if ($res === false) {
- Log::write($v['name'] . $i . '存储失败:----' . $emailModel->getError().'===='. $emailModel->getLastSql());
- throw new Exception($emailModel->getError() . '----' . $emailModel->getLastSql());
- }
- Db::commit();
- $content = '您有新邮件,请注意查收!';
- Message::addMessage(Message::CUSTOMER_TYPE, $customerId, $v['id'], 0, $content, 8);
- } catch (Exception $e) {
- Log::write('错误信息:' . $e->getMessage());
- Db::rollback();
- }
- }
- $obj->close_mailbox(); //Close Mail Box
- }
- echo 'over';
- }
- // 邮箱定时 api接口形式
- public function getEmailList()
- {
- $domain = 'qdsd.vip';
- $product = 'qdsd_hzqiye_ntesmail_com';
- $accounts = 'admin';
- $params = ['fids' => [1], 'order' => 'receivedDate', 'desc' => true, 'start' => 0, 'limit' => 100, 'returnTotal' => true];
- $time = date(time()) . '000';
- $res = openssl_pkey_get_private($this->prikey);
- $src = "account_name=" . $accounts . "&domain=" . $domain . "¶ms=" . json_encode($params) . "&product=" . $product . "&time=" . $time;
- if (openssl_sign($src, $out, $res)) {
- $sign = bin2hex($out);
- $url = "http://apihz.qiye.163.com/qiyeservice/api/mailbox/listMessages";
- $pram = $src . "&sign=" . $sign;
- echo $url . "?" . $pram . "<br>";
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $pram);
- $data = curl_exec($ch);
- curl_close($ch);
- $res = json_decode($data, true);
- dump($res);
- }
- }
- // 邮箱定时 api接口形式 开始时间到结束时间
- public function getEmails()
- {
- $domain = 'qdsd.vip';
- $product = 'qdsd_hzqiye_ntesmail_com';
- $accounts = 'admin';
- $start = date("Y-m-d", '-30day');
- $end = date("Y-m-d H:i:s");
- $page_num = "1";
- $page_size = "10";
- $time = date(time()) . '000';
- $res = openssl_pkey_get_private($this->prikey);
- // $src = "accounts=" . $accounts . "&domain=" . $domain . "&end=" . $end . "&page_num=" . $page_num . "&page_size=" . $page_size . "&product=" . $product . "&start=" . $start . "&time=" . $time;
- $src = "accounts=" . $accounts . "&domain=" . $domain . "&end=" . $end . "&page_num=" . $page_num . "&page_size=" . $page_size . "&product=" . $product . "&start=" . $start . "&time=" . $time;
- if (openssl_sign($src, $out, $res)) {
- $sign = bin2hex($out);
- $url = "http://apihz.qiye.163.com/qiyeservice/api/mail/getReceivedMailLogs";
- $pram = $src . "&sign=" . $sign;
- echo $url . "?" . $pram . "<br>";
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $pram);
- $data = curl_exec($ch);
- curl_close($ch);
- $res = json_decode($data, true);
- dump($res);
- }
- }
- /**
- * 打卡定时任务
- */
- public function attendance()
- {
- $w = date('w');
- $date = [
- 1 => 'monday',
- 2 => 'tuesday',
- 3 => 'wednesday',
- 4 => 'thursday',
- 5 => 'friday',
- 6 => 'saturday',
- 0 => 'weekday',
- ];
- $weekname = $date[$w];
- $times = AttendanceTime::where([$weekname => 1])->select();
- if (empty($times)) {
- return '未设置规则';
- }
- $row = AttendanceStatisc::where(['time' => date('Y-m-d')])->find();
- if (!empty($row)) {
- return '规则已生成';
- }
- $times = collection($times)->toArray();
- $rule = AttendanceRule::where([])->find();
- $statiscs = AttendanceStatisc::where(['time' => date('Y-m-d', strtotime('-1 day'))])->select();
- foreach ($statiscs as $v) {
- $update = [];
- if (empty($t['clock_in']) && !empty($t['clock_out'])) {//缺卡
- $update['clock_in_status'] = 1;
- }
- if (empty($t['clock_out']) && !empty($t['clock_in'])) {//缺卡
- $update['clock_out_status'] = 1;
- }
- if (empty($t['clock_in']) && empty($t['clock_out'])) {//旷工
- $update['clock_in_status'] = 2;
- $update['clock_out_status'] = 2;
- }
- if ($update) {
- $statiscModel = new AttendanceStatisc();
- $statiscModel->save($update, ['id' => $v['id']]);
- }
- }
- $staff_ids = explode(',', $rule['staff_id']);
- $statisc = [];
- foreach ($staff_ids as $sid) {
- foreach ($times as $t) {
- $statisc[] = [
- 'staff_id' => $sid,
- 'number' => $t['number'],
- 'time' => date('Y-m-d'),
- 'start_time' => $t['start_time'],
- 'end_time' => $t['end_time'],
- 'ustart_time' => $t['ustart_time'],
- 'uend_time' => $t['uend_time'],
- 'dstart_time' => $t['dstart_time'],
- 'dend_time' => $t['dend_time'],
- 'start_status' => $t['start_status'],
- 'end_status' => $t['end_status'],
- ];
- }
- }
- $statiscModel = new AttendanceStatisc();
- $result = $statiscModel->allowField(true)->saveAll($statisc);
- if (empty($result)) {
- return '生成规则失败';
- }
- return '生成规则成功';
- }
- }
|