Facrm.php
17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
<?php
namespace addons\facrm;
use app\admin\model\facrm\Contract;
use app\common\library\Menu;
use fast\Tree;
use think\Addons;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;
use think\Cookie;
/**
* 插件
*/
class Facrm extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
$menu = [];
$config_file = ADDON_PATH . "facrm" . DS . 'config' . DS . "menu.php";
if (is_file($config_file)) {
$menu = include $config_file;
}
if ($menu) {
Menu::create($menu);
}
/**
* 增加手机号字段
*/
$database=config('database');
$isexits=Db::query("SELECT 1 FROM information_schema.COLUMNS WHERE table_name='{$database['prefix']}admin' AND COLUMN_NAME='mobile' limit 1");
if (!$isexits){
Db::query("ALTER TABLE {$database['prefix']}admin ADD mobile VARCHAR(20) NULL COMMENT '手机'");
}
//首次安装创建表并导入测试数据
\think\addons\Service::importsql('facrm');
if (version_compare(config('fastadmin.version'), '1.3.0', '<') && Db::name("facrm_customer")->count() == 0) {
$this->importData('testdata','');
}
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
$info = get_addon_info('facrm');
Menu::delete(isset($info['first_menu']) ? $info['first_menu'] : 'facrm');
return true;
}
/**
* 插件启用方法
*/
public function enable()
{
$info = get_addon_info('facrm');
Menu::enable(isset($info['first_menu']) ? $info['first_menu'] : 'facrm');
}
/**
* 插件禁用方法
*/
public function disable()
{
$info = get_addon_info('facrm');
Menu::disable(isset($info['first_menu']) ? $info['first_menu'] : 'facrm');
}
/**
* 插件升级方法
*/
public function upgrade()
{
$menu = include ADDON_PATH . 'facrm' . DS . 'config' . DS . 'menu.php';
Menu::upgrade('facrm', $menu);
/**
* 增加手机号字段
*/
$database=config('database');
$isexits=Db::query("SELECT 1 FROM information_schema.COLUMNS WHERE table_name='{$database['prefix']}admin' AND COLUMN_NAME='mobile' limit 1");
if (!$isexits){
Db::query("ALTER TABLE {$database['prefix']}admin ADD mobile VARCHAR(20) NULL COMMENT '手机'");
}
}
/**
* 登录后 不跟进和未成交的客户处理
*/
public function adminLoginInit()
{
$config = $this->getConfig();
//不跟进 lose_day1 //不成交lose_day2
if ($config['lose_day1'] > 0 || ($config['lose_day2'] > 0)) {
$customerModel = model('\app\admin\model\facrm\Customer');
$customerModel->where('deal_status', 0)->where('owner_user_id', 'gt', 0);
if ($config['lose_day1'] > 0 && $config['lose_day2'] > 0) {
//如果不跟进和不成交都开启,掉入公海逻辑
$customerModel->where(function ($query) use ($config) {
$query->where('follow_time', '<', (time() - $config['lose_day1'] * 86400))->where('follow_time', 'gt', 0)->whereOr('collect_time', '<', (time() - $config['lose_day2'] * 86400));
});
} elseif ($config['lose_day1'] > 0 && ($config['lose_day2'] <= 0)) {
//如果只开启不跟进,掉入公海逻辑
$customerModel->where('follow_time', '<', (time() - $config['lose_day1'] * 86400))->where('follow_time', 'gt', 0);
} elseif ($config['lose_day1'] <= 0 && $config['lose_day2'] > 0) {
//如果只开启不成交,掉入公海逻辑
$customerModel->where('collect_time', '<', (time() - $config['lose_day2'] * 86400));
} else {
return true;
}
$lists = $customerModel->fetchSql(false)->select();
if ($lists) {
foreach ($lists as $row) {
$owner_user_id = $row->owner_user_id;
$row->discard();
\app\admin\model\AdminLog::create([
'title' => __("客户过期自动加入公海"),
'content' => json_encode(['id' => $row->id, 'name' => $row->name], JSON_UNESCAPED_UNICODE),
'url' => "customer/discard",
'admin_id' => $owner_user_id,
]);
}
}
}
}
/**
* 登录后
*/
public function adminLoginAfter($request){
$exten_type=$request->request('exten_type','');
$from_exten=$request->request('from_exten','','htmlentities');//工号
\think\Cookie::set("facrm_extentype", $exten_type?$exten_type:'',86400 * 7);//云呼通话方式
Cookie::set("facrm_from_exten", $from_exten?$from_exten:'',86400 * 7);
if($from_exten){
\app\admin\model\facrm\Cloudcall::edit('','',$from_exten,true);
}
}
/**
* 审核成功钩子
* @param $param
*/
public function facrmFlowVerify(&$param)
{
if (!isset($param['types'])) return false;
$check_status=($param['is_end'] == 1&&$param['status']==1)?2:(($param['status']==0)?3:1);
switch ($param['types']) {
case 'receivables':
if ($param['is_end'] == 1 && $param['status'] == 1) {
$receivablesModel = new \app\admin\model\facrm\contract\Receivables();
//$contractModel=new \app\admin\model\facrm\Contract();
$receivables = $receivablesModel::get($param['types_id']);
$receivables->contract()->setInc('return_money', $receivables->money);
$receivables->plan()->update(['status'=>2,'return_money'=>\think\Db::raw("`return_money`+{$receivables['money']}")]);
}
//1审核中、2审核通过、3审核未通过
break;
case "contract":
if ($param['is_end'] == 1 && $param['status'] == 1) {
$contractModel = new \app\admin\model\facrm\Contract();
$contract = $contractModel::get($param['types_id']);
$contract->customer()->update([
'deal_status' => 1, 'deal_time' => time(),
'purchase_times'=> Db::raw('purchase_times+1'),
'purchase_total'=> Db::raw('purchase_total+'.$contract->money),
]);
//如果有商机也改成成交状态
if ($contract->business_id) {
$contract->business()->update(['is_end' => 1, 'deal_time' => time()]);//把商机改成成交状态
}
}
break;
default:
}
//消息通知
try {
Queue::push("addons\\facrm\\library\\notice\queue\\Flow" . ucfirst($param['types']) . "Job",
['model_id' => $param['types_id'], 'data' => ['check_status' => $check_status]]);
} catch (\Exception $e) {
}
//消息通知end
return true;
}
/**
* 用户注册成功钩子
*/
public function userRegisterSuccessed(&$user)
{
return \addons\facrm\library\Helper::synUser($user);
}
/**
* 发送邮件成功钩子
*param_data types类型如customer,contacts| typesid对应的ID
*send_data发送邮件的内容
*types_data 当前对象的数据
* @param $param
*/
public function facrmSendEmailSuccess($param)
{
if (!isset($param['param_data']) || !$param['param_data'] || !isset($param['send_data']) || !$param['send_data']) return false;
return $this->addRecord($param['param_data'], $param['send_data'], __("发送邮件"));
}
/**
* 发送短息成功钩子
*param_data types类型如customer,contacts| typesid对应的ID
*send_data发送短息的内容
*types_data 当前对象的数据
* @param $param
*/
public function facrmSendSmsSuccess($param)
{
if (!isset($param['param_data']) || !$param['param_data'] || !isset($param['send_data']) || !$param['send_data']) return false;
return $this->addRecord($param['param_data'], $param['send_data'], __("发送短息"));
}
/**
* 自动添加跟进
* @param $param_data
* @param $send_data
* @param string $df_content
* @return bool
* @throws \think\exception\DbException
*/
private function addRecord($param_data, $send_data, $df_content = "")
{
$result = false;
$record_data = array();
if ($param_data && $param_data['types']) {
switch ($param_data['types']) {
case "customer":
//跟进客户
$customer = model('\app\admin\model\facrm\Customer');
$rowc = $customer->get($param_data['typesid']);
if (!$rowc) return false;
$rowc->follow_time = time();
$rowc->save();
$record_data['types'] = "customer";
$record_data['types_id'] = $rowc->id;
break;
case "business":
$business = model('\app\admin\model\facrm\Business');
$row = $business->get($param_data['typesid']);
if (!$row) return false;
//更新客户表
$row->customer()->update(["follow_time" => time()]);
$row->save();
$record_data['types'] = "business";
$record_data['types_id'] = $row->id;
break;
case "contacts":
//跟进客户
$contactsModel = model('\app\admin\model\facrm\customer\Contacts');
$contacts = $contactsModel->get($param_data['typesid']);
if (!$contacts || !$contacts->customer) return false;
$contacts->customer->follow_time = time();
$contacts->customer->save();
$record_data['types'] = "customer";
$record_data['types_id'] = $contacts->customer_id;
$send_data['content']=(isset($send_data['content']) ? $send_data['content'] : $df_content)."【联系人:{$contacts['name']}】";
break;
case "clues":
//跟进线索
$cluesModel = model('\app\admin\model\facrm\Clues');
$rowc = $cluesModel->get($param_data['typesid']);
if (!$rowc) return false;
$rowc->follow_time = time();
$rowc->save();
$record_data['types'] = "clues";
$record_data['types_id'] = $rowc->id;
break;
default:
break;
}
}
if ($record_data) {
(new \app\admin\model\facrm\Record)->allowField(true)->save(array_merge($record_data, [
'content' => strip_tags(isset($send_data['content']) ? $send_data['content'] : $df_content),
'record_type' => isset($send_data['record_type']) ? $send_data['record_type'] : 0,//跟进类型
'create_user_id' => isset($send_data['create_user_id']) ? $send_data['create_user_id'] : 0,
]));
}
return $result;
}
/**
* 导入数据
*/
protected function importData($sqlname="",$dir='config')
{
$sqlFile = ADDON_PATH . 'facrm' . ($dir?DS.$dir:'').DS .$sqlname.'.sql';
if (is_file($sqlFile)) {
$lines = file($sqlFile);
$templine = '';
foreach ($lines as $line) {
if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*') {
continue;
}
$templine .= $line;
if (substr(trim($line), -1, 1) == ';') {
$templine = str_ireplace('__PREFIX__', config('database.prefix'), $templine);
$templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);
try {
Db::getPdo()->exec($templine);
} catch (\Exception $e) {
echo $e->getMessage();
}
$templine = '';
}
}
}
}
/**
* 手机号脚本替换
*/
public function viewFilter(& $content)
{
$module = strtolower(request()->module());
$controller=strtolower(request()->controller());
$action=strtolower(request()->action());
if ($module == 'admin'&&$controller=='auth.admin'&&version_compare(config('fastadmin.version'), '1.3.4', '<')) {
$view=\think\View::instance();
$mobile=isset($view->row->mobile)?$view->row->mobile:'';
$str_rp='<div class="form-group hidden layer-footer">';
$new_rp='<div class="form-group"><label for="mobile" class="control-label col-xs-12 col-sm-2">手机:</label><div class="col-xs-12 col-sm-8"><input type="mobile" class="form-control" id="mobile" name="row[mobile]" value="'.$mobile.'" /></div></div>';
$content = preg_replace_callback("/{$str_rp}/i", function ($matches) use ($new_rp,$str_rp){
return $new_rp.$str_rp;
}, $content);
}
if ($module == 'admin'&&$controller=='index'&&$action=='index') {
$view=\think\View::instance();
if (!isset($view->auth)) return true;
//获取合同\,回款待审批
$contractModel= new Contract();
$receivablesModel=new \app\admin\model\facrm\contract\Receivables();
$invoiceModel=new \app\admin\model\facrm\Invoice();
$filter_w['check_status'] =['in',[0,1]];
$total = $contractModel->where($filter_w)->where('','exp','FIND_IN_SET('. $view->auth->id.',flow_admin_id)')->fetchSql(false)->count();
$total +=$receivablesModel->where($filter_w)->where('','exp','FIND_IN_SET('.$view->auth->id.',flow_admin_id)')->fetchSql(false)->count();
$total +=$invoiceModel->where($filter_w)->where('','exp','FIND_IN_SET('.$view->auth->id.',flow_admin_id)')->fetchSql(false)->count();
$content =$content."<script>function setsidebar(){Backend.api.sidebar({'facrm/backlog':{$total},'facrm':{$total}})}; setTimeout('setsidebar()','5000');</script>";
}
//云呼方式
if ($module == 'admin'&&$controller=='index'&&$action=='login') {
//获取云呼配置
$all_types = \addons\facrm\library\cloudcall\Call::getProviders();
$keys = "";
foreach ($all_types as $v) {
$keys .= $keys ? ',' .'cloudcall'. $v : 'cloudcall' . $v;
}
$settingModel = new \app\admin\model\facrm\Setting();
$setting= $settingModel->where('key', 'in', $keys)->where('status', 1)->find();//只找一条云呼通道
if (!$setting) return true;
$setting=$setting['values'];
$exten_type=Cookie::get("facrm_extentype");//云呼通话方式
$from_exten=htmlentities(Cookie::get("facrm_from_exten"));//云呼通话坐席工号
$str_rp='<div class="form-group checkbox">';
$new_rp="";
if (isset($setting['open_exten'])&&$setting['open_exten']){
$new_rp=' <div class="input-group">
<div class="input-group-addon"><span class="glyphicon fa fa-phone" aria-hidden="true"></span></div>
<input type="text" class="form-control" placeholder="云呼工号,如不知道可留空" name="from_exten" value="'.$from_exten.'" />
</div>';
}
$new_rp.=' <div class="input-group">
<div class="input-group-addon"><span class="glyphicon fa fa-phone" aria-hidden="true"></span></div>
<select class="form-control selectpicker" name="exten_type"><option value=""> 请选择云呼方式</option>
<option value="Local" '.($exten_type=='Local'?'selected':'').'>工作手机</option>
<option value="sip" '.($exten_type=='sip'?'selected':'').'>软电话</option>
<option value="gateway" '.($exten_type=='gateway'?'selected':'').'>话机方式</option>
</select>
</div>';
$content = preg_replace_callback("/{$str_rp}/i", function ($matches) use ($new_rp,$str_rp){
return $new_rp.$str_rp;
}, $content);
}
}
/**
* 发票开具钩子
* @param $param
*/
public function facrmInvoiceOpener($param){
//通知
Queue::push("addons\\facrm\\library\\notice\queue\\InvoiceJob", [
'model_id'=>$param['id'],
]);
}
}