Commit e42429be by 马玮

Add customer to db

parent 5e22a2c1
......@@ -15,6 +15,12 @@ source /etc/profile
sudo yum install redis
```
## How to use
```
1.node accountTool.js -t saveAccount -d 1 -w autohome -u 河南明志汽车大迈8054 -p hnmz147852.
2.node boot.js -t fetchClues -T 1
```
## To do list:
- [x] 功能:根据环境变量读取配置
- [x] 功能:集成若快验证码识别
......@@ -30,10 +36,10 @@ sudo yum install redis
- [ ] 功能:代理随机切换
- [ ] 功能:登录错误细分(密码错误、验证码错误等区分处理入库)
- [x] 功能:线索车型映射
- [ ] 功能:线索顾客映射
- [x] 功能:线索顾客映射
- [ ] 功能:线索销售映射(不一定做)
- [x] 功能:线索统计
- [ ] 功能:生成账号记录命令行工具
- [x] 功能:生成账号记录命令行工具
- [ ] 功能:发现第三方车型和本地不匹配将未知车型入库方便开发爬取同步车型
- [ ] 功能:线索入库前对数据进行基础校验(如车型不匹配等如何处理)
- [ ] 功能:Cluster分布式进程调度
......@@ -42,6 +48,7 @@ sudo yum install redis
- [ ] 功能:增加测试用例和工具
- [ ] 功能:通过环境变量设定根目录
- [ ] 功能:抓取线索一半登录失效需要重新登录
- [ ] 优化:所有forEach用for...of替换,对async/await友好
- [ ] 优化:cookie使用redis做一级缓存,缓存不存在时再从db读取
- [ ] 优化:整理所有错误,建立错误继承关系,区分操作错误和程序错误
- [ ] 优化:易车抓取方式尝试破解request,phantomjs方案有点过于缓慢
......
......@@ -9,7 +9,7 @@ const DealerHelper = require('./lib/helpers/Dealer');
program
.version('0.1.0')
.option('-t, --task <task name>', 'Task list: addAccount')
.option('-t, --task <task name>', 'Task list: saveAccount')
.option('-d, --dealerID <thirdparty account ID>', 'Assign dealerID')
.option('-w, --website <thirdparty website>', 'Webname list: autohome, easypass')
.option('-u, --username <thirdparty username>', 'Assign username')
......@@ -32,7 +32,7 @@ if (!program.username) {
if (!program.password) {
commandError.push('缺少password!');
}
const validTasks = ['addAccount'];
const validTasks = ['saveAccount'];
if (program.task && !validTasks.includes(program.task)) {
commandError.push('网站类型不合法!');
}
......@@ -49,10 +49,10 @@ if (commandError.length > 0) {
}
(async () => {
if (program.task === 'addAccount') {
const success = await DealerHelper.addAccount(program);
if (success === true) {
console.log('账号添加成功!');
if (program.task === 'saveAccount') {
const accountID = await DealerHelper.saveAccount(program);
if (accountID) {
console.log(`账号添加成功!accountID: ${accountID}`);
} else {
console.log('账号添加失败!');
}
......
......@@ -112,7 +112,91 @@ class DealerHelper {
}
// 线索车系映射
static async mapClues(params) {
static async getMappedAreas(params) {
return new Promise(async (resolve, reject) => {
const website = params.website || '';
let clues = params.clues || [];
const connection = await DI.getConnection('MASTER_CRM');
// 获取车型车系文本
let areaStrs = clues.map(clue => clue.customerArea).filter((areaStr) => areaStr);
// 车系车系文本去重
areaStrs = Array.from(new Set(areaStrs));
const mappedAreas = [];
let sql;
// areaStrs.push('河南三门峡卢氏', '北京', '上海', '天津天津', '河南濮阳南乐', '河南郑州管城');
console.log(`${connection.escape(areaStrs.join())}`);
const getAreas = async (areaStrs, areaType) => {
// ${connection.escape(areaStrs.join())}
return new Promise(async (resolve, reject) => {
let sql;
if (areaType === 'province_city_county') {
// 样本:河南三门峡卢氏、河南郑州管城、河南濮阳南乐
sql = `SELECT CONCAT(a1.name, a2.name, a3.name) AS areaKey, a3.id AS areaID FROM crm_dd_area AS a1
LEFT JOIN crm_dd_area AS a2 ON a2.pid=a1.id
LEFT JOIN crm_dd_area AS a3 ON a3.pid=a2.id
WHERE a1.level = 1 AND a2.level = 2 AND a3.level = 3
AND ${connection.escape(areaStrs.join())} LIKE CONCAT('%', a1.name, a2.name, a3.name, '%')`;
} else if (areaType === 'province_city') {
// 样本:河南郑州、北京北京
sql = `SELECT CONCAT(a1.name, a2.name) AS areaKey, a2.id AS areaID FROM crm_dd_area AS a1
LEFT JOIN crm_dd_area AS a2 ON a2.pid=a1.id
WHERE a1.level = 1 AND a2.level = 2
AND ${connection.escape(areaStrs.join())} LIKE CONCAT('%', a1.name, a2.name, '%')`;
} else if (areaType === 'municipality') {
// 样本:北京、上海、天津、重庆
sql = `SELECT a2.name AS areaKey, a2.id AS areaID FROM crm_dd_area AS a1
LEFT JOIN crm_dd_area AS a2 ON a2.pid=a1.id
WHERE a1.level = 1 AND a2.level = 2 AND a1.name = a2.name
AND ${connection.escape(areaStrs.join())} LIKE CONCAT('%', a2.name, '%')`;
} else if (areaType === 'province') {
// 样本:江苏、浙江,目前没有遇到这种情况
sql = `SELECT name AS areaKey, id AS areaID FROM crm_dd_area
WHERE ${connection.escape(areaStrs.join())} LIKE CONCAT('%', name, '%')`;
}
connection.query(sql, (err, areas, fields) => {
if (err) {
reject(err);
} else {
resolve(areas);
}
});
});
}
try {
const areaTypes = ['province_city_county', 'province_city', 'municipality', 'province'];
for (let areaType of areaTypes) {
console.log('areaStrs:', areaStrs, '长度:', areaStrs.length);
let areas = await getAreas(areaStrs, areaType);
// for (let [areaKey, areaID] of areas.entries()) {
for (let area of areas) {
console.log(area.areaKey, ':', area.areaID);
if (!mappedAreas[area.areaKey]) {
mappedAreas[area.areaKey] = area.areaID;
}
}
areaStrs = areaStrs.filter(areaStr => !mappedAreas[areaStr]);
if (areaStrs.length === 0) {
break;
}
}
console.log('mappedAreas:', mappedAreas, '长度:', mappedAreas.length);
resolve(mappedAreas);
} catch (e) {
reject(e);
} finally {
connection.release();
}
});
}
// 线索车系映射
static async getMappedIntentions(params) {
return new Promise(async (resolve, reject) => {
const website = params.website || '';
let clues = params.clues || [];
......@@ -135,29 +219,58 @@ class DealerHelper {
console.log('未知类型');
}
connection.query(sql, function(err, intentions, fields) {
connection.query(sql, function(err, mappedIntentions, fields) {
connection.release();
if (err) {
reject(err);
} else {
clues.forEach((clue) => {
clue.createdAt = moment(clue.createdAt).format('X');
intentions.forEach((intention) => {
if (clue.intentionDes.includes(intention.name)) {
clue.intentionID = intention.id;
}
});
});
// console.log(JSON.stringify(intentions));
// console.log(JSON.stringify(mappedIntentions));
// console.log(JSON.stringify(clues));
// reject(err);
resolve(clues);
resolve(mappedIntentions);
}
});
});
}
static async mapClues(params) {
return new Promise(async (resolve, reject) => {
let clues = params.clues || [];
const mappedIntentions = await this.getMappedIntentions(params);
const mappedAreas = await this.getMappedAreas(params);
for (let clue of clues) {
// 匹配客户地区
if (mappedAreas[clue.customerArea]) {
clue.customerAreaID = mappedAreas[clue.customerArea];
} else {
clue.customerAreaID = 0;
}
// 匹配线索车系
mappedIntentions.forEach((intention) => {
if (clue.intentionDes.includes(intention.name)) {
clue.intentionID = intention.id;
}
});
// 线索获取时间格式化为时间戳
clue.createdAt = moment(clue.createdAt).format('X');
clue.customerID = await this.saveCustomer({
phone: clue.customerPhone,
name: clue.customerName,
area: clue.customerAreaID,
createTime: clue.createdAt
});
}
resolve(clues);
});
}
// 保存线索
static async saveClues(params) {
const dealerID = params.dealerID || 0;
......@@ -174,7 +287,7 @@ class DealerHelper {
const connection = await DI.getConnection('MASTER_CRM');
const valuesSql = [];
const _clue = {
customerid: 0,
customerID: 0,
customerName: '',
customerPhone: '',
customerArea: '',
......@@ -191,7 +304,7 @@ class DealerHelper {
let valueSql = '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
// customer_id, shop_name, salesman_id需要映射
let replacements = [
0, clue.customerName, clue.customerPhone, clue.intentionDes, clue.intentionID, '', dealerID, clue.salesmanName, 0,
clue.customerID, clue.customerName, clue.customerPhone, clue.intentionDes, clue.intentionID, '', dealerID, clue.salesmanName, 0,
config.get('CLUE_INPUT_TYPE')[params.website], 4, clue.createdAt
];
......@@ -203,9 +316,9 @@ class DealerHelper {
customer_id, customer_name, customer_phone, intention_des, intention_id, shop_name, shop_id,
salesman_name, salesman_id, clue_input_type, create_type, create_time
) VALUES ${valuesSql.join(',')} ON DUPLICATE KEY UPDATE
customer_id = VALUES(customer_id),
customer_name = VALUES(customer_name),
intention_des = VALUES(intention_des),
shop_name = VALUES(shop_name),
create_type = VALUES(create_type)`;
console.log(sql);
......@@ -260,14 +373,14 @@ class DealerHelper {
});
}
static async addAccount(params) {
static async saveAccount(params) {
return new Promise(async (resolve, reject) => {
try {
params.password = new Buffer(params.password).toString('base64');
const sql = `INSERT INTO crm_dealer_thirdparty_account SET
dealerID = ?, website = ?, username = ?, password = ?, createdAt = UNIX_TIMESTAMP()
ON DUPLICATE KEY UPDATE
username = VALUES(username), password = VALUES(password)`;
id = LAST_INSERT_ID(id), username = VALUES(username), password = VALUES(password)`;
const replacements = [params.dealerID, params.website, params.username, params.password];
console.log(replacements);
const connection = await DI.getConnection('MASTER_CRM');
......@@ -280,7 +393,37 @@ class DealerHelper {
if (err) {
reject(err);
} else {
resolve(true);
console.log(results);
resolve(results.insertId);
}
}
);
} catch (e) {
reject(e);
}
});
}
static async saveCustomer(params) {
return new Promise(async (resolve, reject) => {
try {
const sql = `INSERT INTO crm_customer SET
phone = ?, name = ?, area = ?, create_time = ?
ON DUPLICATE KEY UPDATE
id = LAST_INSERT_ID(id), area = IF(area = 0, VALUES(area), area)`;
const replacements = [params.phone, params.name, params.area, params.createTime];
const connection = await DI.getConnection('MASTER_CRM');
connection.query(
sql,
replacements,
function(err, results, fields) {
connection.release();
if (err) {
reject(err);
} else {
// console.log(results);
resolve(results.insertId);
}
}
);
......
......@@ -255,12 +255,13 @@ class Autohome {
clue.customerId = idMatch[1] || 0;
clue.customerName = (cheerio.load(l.CustomerNameStr).text() || '').trim();
clue.customerPhone = (phoneAreaMatch[1] || '').trim();
clue.customerArea = (phoneAreaMatch[2] || '').trim();
// clue.customerArea = (phoneAreaMatch[2] || '').replace(/\s+/g, '');
clue.salesmanName = (salesMatch[1] || '').trim();
clue.salesPhone = (salesMatch[2] || '').trim();
clue.orderType = l.OrderTypeStr.trim();
clue.orderState = l.OrderStateStr.trim();
clue.licenseArea = l.LicenseCityStr.trim();
clue.licenseArea = l.LicenseCityStr.replace(/\s+/g, '');
clue.customerArea = clue.licenseArea;
clue.intentionDes = l.SpecNameStr.trim();
clue.createdAt = l.LeadTimeStr.trim();
clues.push(clue);
......
......@@ -227,7 +227,7 @@ class Easypass {
const nameAreaMatch = customerNameAreaStr.match(/(.*?)\[(.*?)\]/);
clue.customerName = (nameAreaMatch[1] || '').trim();
clue.licenseArea = (nameAreaMatch[2] || '').trim();
clue.licenseArea = (nameAreaMatch[2] || '').replace(/\s+/g, '');
clue.customerArea = clue.licenseArea;
clue.customerPhone = (ptitlePieces[1] || '').replace('电话', '').trim();
clue.intentionDes = (ptitlePieces[2] || '').replace('订购', '').trim();
......
......@@ -9,6 +9,46 @@ const day = moment().subtract(3, 'days').format('YYYY.MM.DD');
const axios = require('axios');
const config = require('config');
async function test (l) {
await Promise.delay(l*1000).then(async function() {
console.log('过了' + l + '秒');
console.log((new Date()).toLocaleString());
console.log('=======================================');
});
}
(async () => {
console.log((new Date()).toDateString());
// const global_var = '全局变量';
// const test_fun = () => {
// console.log(global_var);
// }
// test_fun();
let list = [1, 2, 3, 4, 5];
for (l of list) {
console.log((new Date()).toLocaleString());
await test(l);
}
})();
return;
function testCatch() {
return new Promise(async (resolve, reject) => {
try {
throw new Error('傻B');
} catch (e) {
console.log('拒绝', e);
reject(e);
} finally {
console.log('finally');
}
});
}
testCatch().catch((e) => {
console.log('逮到你喽', e);
});
return;
const updatedAt = moment().format('YYYY-MM-DD HH:mm:ss');
console.log(moment('2017-08-09 09:56').format('X'));
return;
......@@ -202,26 +242,4 @@ const testHorseman = async () => {
// console.log((new Date()).toLocaleString());
// })
.close();
}
async function test (l) {
await Promise.delay(l*1000).then(async function() {
console.log('过了' + l + '秒');
console.log((new Date()).toLocaleString());
console.log('=======================================');
});
}
(async () => {
console.log((new Date()).toDateString());
// const global_var = '全局变量';
// const test_fun = () => {
// console.log(global_var);
// }
// test_fun();
let list = [1, 2, 3, 4, 5];
for (l of list) {
console.log((new Date()).toLocaleString());
await test(l);
}
})();
\ No newline at end of file
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment