Files
spacestation/common/models/receiver/Receiver_customers_model.php
T

634 lines
25 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* Created by Vim
* User: lcc
* Date: 2021/06/29
* Time: 13:47
*/
defined('BASEPATH') or exit('No direct script access allowed');
class Receiver_customers_model extends HD_Model
{
private $table_name = 'lc_receiver_customers';
private $status_arr = [-1 => '删除', 0 => '未见客户', 1 => '到店客户', 2 => '订单客户', 3 => '战败客户'];
private $level = ['H', 'A', 'B', 'C'];
private $cfrom_arr = ['自有资源', '平台分配'];
private $cfrom_clues_arr = ['自然进店', '外展', 'DM', '转介绍', '其它', '网站', '外展外拓', '垂直媒体', '自媒体'];
private $buy_time = [3 => '3天(H级)', 7 => '7天(A级)', 15 => '15天(B级)', 30 => '30天(C级)'];
private $follow_channel = ['见面', '电话', '微信'];
public function __construct()
{
parent::__construct($this->table_name, 'default');
}
/**
* Notes:根据id获取数据
* @param $ids array() id 数组
* @param string $fileds
* @return array
*/
public function get_map_by_ids($ids, $fileds = '')
{
$rows = [];
$ids = array_filter($ids);
if ($ids) {
$cf_ids = implode(',', $ids);
$where = [
"id in ($cf_ids)" => null
];
$rows = $this->map('id', '', $where, '', '', '', $fileds);
}
return $rows;
}
public function get_status()
{
return $this->status_arr;
}
public function get_sdata($type = 'cfrom')
{
switch ($type) {
case 'cfrom':
$result = $this->cfrom_arr;
break;
case 'cfrom_clues':
$result = $this->cfrom_clues_arr;
break;
case 'btime':
$result = $this->buy_time;
break;
case 'level':
$result = $this->level;
break;
case 'follow_channel':
$result = $this->follow_channel;
break;
default:
$result = '';
}
return $result;
}
/**
* Notes:线下来源
* Created on: 2022/3/4 16:54
* Created by: dengbw
* @param int $id
* @return mixed
*/
public function offlineSources_search($id = 0)
{
return $this->offlineSources($id);
}
public function offlineSources($id = 0, $title = 1)
{
$this->load->model('receiver/receiver_clues_cfrom_model', 'clues_cfrom_model');
$arr = [];
if ($id) {
$row = $this->clues_cfrom_model->get(['id' => $id], 'title');
$lists = [];
if ($row) {
$rows = $this->clues_cfrom_model->select(['pid' => $id], '', 0, 0, 'id,title');
foreach ($rows as $item) {
if ($title) {
$lists[$item['id']] = $item['title'];
} else {
$tmp = explode('-', $item['title']);
$lists[$item['id']] = $tmp[1] ? $tmp[1] : $tmp[0];
}
}
}
$arr['name'] = $row['title'];
$arr['list'] = $lists;
} else {
$rows = $this->clues_cfrom_model->select(['status' => 1], 'pid asc', 0, 0, 'id,pid,title');
foreach ($rows as $key => $val) {
if (!$val['pid']) { //父级
$arr[$val['id']]['name'] = $val['title'];
} else {
$arr[$val['pid']] && $arr[$val['pid']]['list'][$val['id']] = $val['title'];
}
}
}
return $arr;
}
/**
* Notes:企微好友状态
* Created on: 2022/5/10 10:00
* Created by: dengbw
* @param int $id
* @return array|mixed
*/
public function wxqyAry($id = '')
{
$arr = [0 => '未添加', 1 => '已添加', -1 => '删除'];
if (strlen($id)) {
return $arr[$id];
} else {
return $arr;
}
}
/**
* Notes:个微好友状态
* @param string $id
* @return array|mixed
*/
public function wxgrAry($id = '')
{
$arr = [0 => '未添加', 1 => '已添加'];
if (strlen($id)) {
return $arr[$id];
} else {
return $arr;
}
}
/**
* Notes:好友类型
* Created on: 2022/5/26 10:00
* Created by: dengbw
* @param int $id
* @return array|mixed
*/
public function buddyTypeAry($id = 0)
{
$arr = [1 => '潜客', 2 => '车主', 3 => '亲朋'];
if ($id) {
return $arr[$id];
} else {
return $arr;
}
}
/**
* Notes:改派类型
* Created on: 2023/2/7 17:00
* Created by: qianhy
* @param int $cs_biz_id
* @return array|mixed
*/
public function csbizidAry($cs_biz_id = null)
{
$arr = [-1 => '已改派', 0 => '本店线索', 1 => '接收线索'];
if (!$cs_biz_id && strlen($cs_biz_id) == 0) {
return $arr;
}
if ($cs_biz_id == -1 || $cs_biz_id == 0) {
return $arr[$cs_biz_id];
} elseif ($cs_biz_id > 0) {
return $arr[1];
} else {
return $arr;
}
}
/**
* Notes:改派搜索条件
* Created on: 2023/2/7 17:00
* Created by: qianhy
* @param int $cs_biz_id
* @return string
*/
public function csbizidWhere($cs_biz_id = null)
{
if (!$cs_biz_id && strlen($cs_biz_id) == 0) {
return '1 = 1';
}
if ($cs_biz_id == -1 || $cs_biz_id == 0) {
return 'cs_biz_id = ' . $cs_biz_id;
} elseif ($cs_biz_id == 1) {
return 'cs_biz_id > 0';
} else {
return '1 = 1';
}
}
public function cbrandAry($c_brand = null)
{
$arr = [0 => '综合', 1 => '东风纳米', 4 => '哪吒', 5 => '零跑'];
if (is_numeric($c_brand)) {
return $arr[$c_brand];
} else {
return $arr;
}
}
public function count_order($where)
{
return $this->select_order($where, '', '', '', '', 1);
}
public function select_order($where = array(), $order = '', $page = 0, $page_size = 20, $fileds = '', $count = 0)
{
!$fileds && $fileds = 'lc_receiver_customers.*';
$this->db->distinct()->select($fileds);
$this->db->from('lc_receiver_customers');
$this->db->join('lc_receiver_orders', 'lc_receiver_orders.rid = lc_receiver_customers.id', 'left');
if ($where) {
$this->db->where($where);
}
if ($count) {
return $this->db->count_all_results();
}
if ($order) {
$this->db->order_by($order);
}
if ($page) {
$offset = ($page - 1) * $page_size;
$limit = $page_size;
} else {
$offset = null;
$limit = null;
}
$this->db->limit($limit, $offset);
return $this->db->get()->result_array();
}
/**
* 根据线索id添加客户
* @param $clues_id
* @return MyResponse
*/
public function addCustomerByCluesId($clues_id)
{
$this->load->model("biz/biz_model");
$this->load->model('receiver/receiver_clues_model');
try {
$info = $this->receiver_clues_model->get(['id' => $clues_id]);
if (!$info) {
throw new Exception('数据不存在');
}
$this->load->helper("order");
$biz = $this->biz_model->get(array('id' => $info['biz_id']));
$add = array(
'rid' => $clues_id,
'cid' => create_customer_no($biz['county_id']),
'name' => $info['name'] . $info['sex'],
'mobile' => $info['mobile'],
'biz_id' => $info['biz_id'] ?: 0,
'level' => 'H',
'cf_title' => '数字营销中台',
'of_id' => $info['cf_id'] ?: 0,
'of2_id' => $info['cf2_id'] ?: 0,
'brand_id' => $info['brand_id'] ?: 0,
'series_id' => $info['series_id'] ?: 0,
'p_time' => date('Y-m-d H:i:s'),
'c_time' => time(),
);
$info['province_id'] && $add['province_id'] = $info['province_id'];
$info['city_id'] && $add['city_id'] = $info['city_id'];
$info['county_id'] && $add['county_id'] = $info['county_id'];
$info['cf_pid'] && $add['cf_pid'] = $info['cf_pid'];
$customers_id = $this->add($add);
if (!is_numeric($customers_id)) {
throw new Exception('添加客户失败');
}
$this->clues_model->update(['status' => 1, 'status2' => 2], ['id' => $clues_id]);
//同步线索日志到客户日志
$this->load->library('receiver/customers_entity');
$this->customers_entity->syn_clues($customers_id, $clues_id);
return new MyResponse(EXIT_SUCCESS, 'success');
} catch (Exception $e) {
return new myResponse($e->getCode() ?: EXIT_ERROR, $e->getMessage());
}
}
/**
* 解锁线索并分佣
* @param $id
* @param $bizId
* @return MyResponse
*/
public function unlock($id, $bizId)
{
$log_path = "customer_unlock.log";
$this->load->model('receiver/receiver_clues_model');
$this->load->model('agent/auto_user_coupon_model');
$this->auto_user_coupon_model->set_db('agentdb');
$this->db->trans_begin();
$this->auto_user_coupon_model->db->trans_begin();
try {
$row = $this->get(['id' => $id, 'biz_id' => $bizId]);
debug_log("开始解锁客户id:{$id},biz_id:{$bizId}", $log_path);
if (!$row) {
throw new Exception('数据不存在');
}
//获取优惠券
/** @var MyResponse $couponResult */
$couponResult = $this->receiver_clues_model->getCluesCoupon($row['rid']);
if (!$couponResult->isSuccess()) {
throw new Exception($couponResult->getMessage());
}
$coupon = $couponResult->getData();
$res = $this->customers_model->update(['un_lock' => 1], ['id' => $id]);
if (!$res) {
throw new Exception('更新失败');
}
$unLockBizIds = $coupon['unLockBizIds'] ? explode(',', $coupon['unLockBizIds']) : [];
if (in_array($row['biz_id'], $unLockBizIds)) {
throw new Exception('您已解锁该线索');
}
$unLockBizIds[] = $row['biz_id'];
$updateCoupon = [
'unLockBizIds' => implode(',', $unLockBizIds),
'status' => Auto_user_coupon_model::STATUS_NOT_USED
];
$res = $this->auto_user_coupon_model->update($updateCoupon, ['id' => $coupon['id']]);
if (!is_numeric($res)) {
throw new Exception('更新优惠券状态失败');
}
//线索分佣
// $res = $this->Commissions($row['rid'], $bizId);
//扣除门店金额
$res = $this->deductBizMoney($row['rid'], $bizId);
if (!$res->isSuccess()) {
throw new Exception($res->getMessage());
}
$this->db->trans_commit();
$this->auto_user_coupon_model->db->trans_commit();
return new MyResponse(EXIT_SUCCESS, '解锁成功');
} catch (Exception $e) {
$this->db->trans_rollback();
// $this->auto_user_coupon_model->db->trans_rollback();
debug_log("解锁失败:" . $e->getMessage(), $log_path);
return new MyResponse(EXIT_ERROR, '解锁失败:' . $e->getMessage());
}
}
public function deductBizMoney($cluesId, $bizId)
{
$this->load->helper('string');
$this->load->model('biz/biz_account_model', 'account_model');
$this->load->model('biz/biz_accountLog_model', 'accountlog_model');
$this->load->library('bizAccount');
$this->load->model('receiver/receiver_clues_model');
$this->load->model('agent/auto_product_model');
$this->auto_product_model->set_db('agentdb');
$log_path = 'deductBizMoney.log';
$log_dir = 'clues';
try {
debug_log("开始扣除商家金额:线索id:{$cluesId}_门店id:{$bizId}", $log_path, $log_dir);
$clues = $this->receiver_clues_model->get(['id' => $cluesId, 'app_id' => Receiver_clues_model::APP_ID_ACTIVITY]);
if (!$clues) {
throw new Exception("线索不存在");
}
if (!$clues['out_id']) {
throw new Exception("报名来源不存在");
}
$bizMoney = 0; //商家扣除金额
if ($clues['cf2_id'] == Receiver_clues_model::CF_ID2_PRODUCT) { //产品来源
$product = $this->auto_product_model->get(['id' => $clues['out_id']]);
$bizMoney = $product['cluesCommission'];
}
if ($bizMoney <= 0) {
debug_log("扣除金额结束:扣除金额不能小于等于0{$bizMoney}", $log_path, $log_dir);
return new MyResponse(EXIT_SUCCESS, '保存成功');
}
$bizAccount = new BizAccount();
$account = $bizAccount->getAccountBizId($bizId, true);
$leftMoney = $account['money_left'];
if ($leftMoney < $bizMoney) {
throw new Exception("余额不足");
}
$upData = [
"money_left = money_left-$bizMoney" => null
];
$where = [
"money_left >= " => $bizMoney
];
$upAccount = $this->account_model->update($upData, $where);
if (!(!is_bool($upAccount) && $upAccount)) {
var_dump($this->account_model->db->last_query());
debug_log("扣除金额失败" . $this->account_model->db->last_query(), $log_path, $log_dir);
throw new Exception('余额不足', 0);
}
$ck = md5(time() . random_string() . $bizId);
$logData = [
'account_id' => $account['id'],
'trade_type' => BizAccount::TRADE_TYPE_USE,
'money_type' => BizAccount::MONEY_TYPE_CLUES,
'money_out' => $bizMoney,
'money_left' => $leftMoney,
'ck' => $ck,
'descrip' => '解锁线索',
'c_time' => time(),
'jsondata' => json_encode(['clues_id' => $cluesId]),
'target_id' => $cluesId
];
$ret = $this->accountlog_model->add($logData);
if (!$ret) {
throw new Exception('写入交易日志失败', 0);
}
debug_log("扣除金额结束:{$bizMoney}", $log_path, $log_dir);
return new MyResponse(EXIT_SUCCESS, '保存成功');
} catch (Exception $e) {
debug_log($e->getMessage(), $log_path, $log_dir);
return new MyResponse(EXIT_ERROR, $e->getMessage());
}
}
/**
* 分佣
* @param $cluesId 线索id
* @param $bizId 门店id
* @return MyResponse
*/
public function Commissions($cluesId, $bizId)
{
$this->load->helper('string');
$this->load->model('biz/biz_account_model', 'account_model');
$this->load->model('biz/biz_accountLog_model', 'accountlog_model');
$this->load->library('bizAccount');
$this->load->model('receiver/receiver_clues_model');
$this->load->model('agent/pingan/pingan_users_model');
$this->load->model('agent/organization/organization_cmmssn_model', 'mdOrganizationCmmssn');
$this->load->model('agent/organization/organization_model');
$this->load->model('agent/auto_product_model');
$this->load->model('agent/pingan/pingan_users_cmmssn_model');
$this->pingan_users_model->set_db('agentdb');
$this->mdOrganizationCmmssn->set_db('agentdb');
$this->organization_model->set_db('agentdb');
$this->auto_product_model->set_db('agentdb');
$this->pingan_users_cmmssn_model->set_db('agentdb');
$log_path = 'commissions.log';
$log_dir = 'clues';
try {
debug_log("开始分佣:线索id:{$cluesId}_门店id:{$bizId}", $log_path, $log_dir);
$clues = $this->receiver_clues_model->get(['id' => $cluesId, 'app_id' => Receiver_clues_model::APP_ID_ACTIVITY]);
if (!$clues) {
throw new Exception("线索不存在");
}
if (!$clues['out_id']) {
throw new Exception("报名来源不存在");
}
if (!$clues['pingan_user_id']) {
debug_log("结束分佣:线索不需要分佣", $log_path, $log_dir);
return new MyResponse(EXIT_SUCCESS, '保存成功');
}
$pinanUser = $this->pingan_users_model->get(['id' => $clues['pingan_user_id']]);
if (!$pinanUser['id']) {
throw new Exception("线索不存在绑定用户关系");
}
//获取分佣配置
$cmmssn = $this->mdOrganizationCmmssn->get(['teamId' => $pinanUser['orgTeamId'], 'status' => 0]);
if (!$cmmssn) {
throw new Exception("分佣配置不存在");
}
//团队设置分佣等级
$level = $this->organization_model->getTeamLevel($pinanUser['orgTeamId']);
$brokerage1 = $brokerage2 = $brokerage3 = $brokerage4 = 0;
$sourceId = 0;
if ($clues['cf2_id'] == Receiver_clues_model::CF_ID2_PRODUCT) { //产品来源
$product = $this->auto_product_model->get(['id' => $clues['out_id']]);
if ($product['cluesCommission'] <= 0) {
debug_log("结束分佣:产品未配置线索总用金额", $log_path, $log_dir);
return new MyResponse(EXIT_SUCCESS, '保存成功');
}
$brokerage1 = $product['cluesCommission'] * ($cmmssn['cluesLevel1'] / 100) ?: 0;
$brokerage2 = $product['cluesCommission'] * ($cmmssn['cluesLevel2'] / 100) ?: 0;
$brokerage3 = $product['cluesCommission'] * ($cmmssn['cluesLevel3'] / 100) ?: 0;
$brokerage4 = $product['cluesCommission'] * ($cmmssn['cluesLevel4'] / 100) ?: 0;
$sourceId = $product['id'] ?: 0;
}
debug_log('分佣金额:' . json_encode([$brokerage1, $brokerage2, $brokerage3, $brokerage4]), $log_path, $log_dir);
$cfId = $clues['id'];
$bizMoney = 0; //商家扣除金额
$add_data = [];
if ($brokerage1 && $clues['area_id']) { //一级佣金
$add_data[] = [
'cfId' => $cfId,
'sourceId' => $sourceId,
'cfType' => Pingan_users_cmmssn_model::CF_TYPE_CLUES_TEAM,
'money' => $brokerage1,
'pinganUserId' => $clues['area_id'],
'teamId' => 0,
'depId' => 0,
'areaId' => $clues['area_id'],
'createTime' => date('Y-m-d H:i:s'),
'bizId' => $bizId
];
$bizMoney += $brokerage1;
}
if ($brokerage2 && $clues['dep_id']) { //二级佣金
$add_data[] = [
'cfId' => $cfId,
'sourceId' => $sourceId,
'cfType' => Pingan_users_cmmssn_model::CF_TYPE_CLUES_TEAM,
'money' => $brokerage2,
'pinganUserId' => $clues['dep_id'],
'teamId' => 0,
'depId' => $clues['dep_id'],
'areaId' => $clues['area_id'] ?: 0,
'createTime' => date('Y-m-d H:i:s'),
'bizId' => $bizId
];
$bizMoney += $brokerage2;
}
if ($level >= 4) { //4级
if ($brokerage3 && $clues['team_id']) {
$add_data[] = [
'cfId' => $cfId,
'sourceId' => $sourceId,
'cfType' => Pingan_users_cmmssn_model::CF_TYPE_CLUES_TEAM,
'money' => $brokerage3,
'pinganUserId' => $clues['team_id'],
'teamId' => $clues['team_id'],
'depId' => $clues['dep_id'],
'areaId' => $clues['area_id'] ?: 0,
'createTime' => date('Y-m-d H:i:s'),
'bizId' => $bizId
];
$bizMoney += $brokerage3;
}
if ($brokerage4 && $clues['pingan_user_id']) {
$add_data[] = [
'cfId' => $cfId,
'sourceId' => $sourceId,
'cfType' => Pingan_users_cmmssn_model::CF_TYPE_CLUES_OWN,
'money' => $brokerage4,
'pinganUserId' => $clues['pingan_user_id'],
'teamId' => $clues['team_id'],
'depId' => $clues['dep_id'],
'areaId' => $clues['area_id'] ?: 0,
'createTime' => date('Y-m-d H:i:s'),
'bizId' => $bizId
];
$bizMoney += $brokerage4;
}
} else { //三级
if ($brokerage3 && $clues['pingan_user_id']) {
$add_data[] = [
'cfId' => $cfId,
'sourceId' => $sourceId,
'cfType' => Pingan_users_cmmssn_model::CF_TYPE_CLUES_TEAM,
'money' => $brokerage3,
'pinganUserId' => $clues['team_id'],
'teamId' => 0,
'depId' => $clues['dep_id'],
'areaId' => $clues['area_id'] ?: 0,
'createTime' => date('Y-m-d H:i:s'),
'bizId' => $bizId
];
$bizMoney += $brokerage3;
}
}
$bizAccount = new BizAccount();
$account = $bizAccount->getAccountBizId($bizId, true);
$leftMoney = $account['money_left'];
if ($leftMoney < $bizMoney) {
throw new Exception("余额不足");
}
if (count($add_data)) {
$result = $this->pingan_users_cmmssn_model->add_batch($add_data);
if (!$result) {
throw new Exception("保存失败");
}
$upData = [
"money_left = money_left-$bizMoney" => null
];
$where = [
"money_left >= $bizMoney" => null
];
$upAccount = $this->account_model->update($upData, $where);
if (!(!is_bool($upAccount) && $upAccount)) {
throw new Exception('余额不足', 0);
}
$ck = md5(time() . random_string() . $bizId);
$logData = [
'account_id' => $account['id'],
'trade_type' => BizAccount::TRADE_TYPE_USE,
'money_type' => BizAccount::MONEY_TYPE_CLUES,
'money_out' => $bizMoney,
'money_left' => $leftMoney,
'ck' => $ck,
'descrip' => '线索分佣',
'c_time' => time(),
'jsondata' => json_encode(['clues_id' => $cluesId]),
];
$ret = $this->accountlog_model->add($logData);
if (!$ret) {
throw new Exception('写入交易日志失败', 0);
}
debug_log("商家扣除金额:{$bizMoney}", $log_path, $log_dir);
}
debug_log('分佣结束', $log_path, $log_dir);
return new MyResponse(EXIT_SUCCESS, '保存成功');
} catch (Exception $e) {
debug_log($e->getMessage(), $log_path, $log_dir);
return new MyResponse(EXIT_ERROR, '分佣失败:' . $e->getMessage());
}
}
}