Joywork/cron/getLeadsFromPromit.php
2026-05-22 21:21:54 +03:00

222 lines
7.8 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
require "../config.php";
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
/** GET CSV FROM SOURCE
* @param file_path - путь к файлу на сервере (URL)
* @return body - массив лидов без шапки CSV или false, если файл не открыт
*/
function getCSV($file_path, &$head)
{
$body = array();
if (($handle = fopen($file_path, "r")) !== false) {
while (($row = fgetcsv($handle, 0, ",")) !== false) {
array_push($body, $row);
}
$head = array_shift($body);
fclose($handle);
return $body;
} else {
return false;
}
}
/** NORMALIZE PHONE
* @param phone - телефон
* @return phone - телефон вида +79999999999
*/
function normalizePhone($phone)
{
$phone = trim($phone);
$phone = '+' . preg_replace("/[^0-9A-Za-z]/", '', $phone);
return $phone;
}
/** CHECK LEAD IN DB
* @param phone - телефон, по которому ищем
* @param $agencyID - агентство, в котором ищем
* @return id - возвращаем ИД лида или 0, если нет ничего
*/
function checkLeadInDB($phone, $agencyID)
{
$sql = "SELECT id, source, deleted, opis FROM `clients` WHERE phone = '$phone' and id_agent in (select id from users where id = $agencyID or id_manager=$agencyID or id_manager in (select id from users where id_manager=$agencyID))";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
$lead = mysql_fetch_assoc($result);
} else {
$lead = 0;
}
return $lead;
}
function setLeadSource($source, $leadId)
{
$sql = "UPDATE `clients` SET source = '$source' WHERE id= $leadId";
$result = mysql_query($sql);
}
function checkLeadRenew($opis, $newDate)
{
$pos = strpos($opis, $newDate);
if ($pos === false) {
return true;
} else {
return false;
}
}
function setLeadNonDelete($leadId, $opis)
{
$opis = mysql_real_escape_string($opis);
$sql = "UPDATE `clients` SET deleted = 0, denial = 0, opis = '$opis', reason = '' WHERE id= $leadId";
$result = mysql_query($sql);
}
/** GET ID SOURCE IN AGENCY
* @param input - искомый источник
* @param agencyID - ID агенства
* @return id - возвращает ID источника или 0
*/
function getIDSource($input, $agencyID)
{
$sql = "SELECT id FROM `advertising_sources` WHERE user_id = '$agencyID' AND source = '$input'";
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) {
$id = mysql_fetch_assoc($res)['id'];
} else {
$id = 0;
}
return $id;
}
/** Class for lead */
class Lead
{
private $fio;
private $email;
private $phone;
private $comment;
private $source;
private $funnel;
private $role;
public function __construct($fio, $email, $phone, $comment = '', $source, $funnel = 438, $userType = false)
{
$this->fio = $fio;
$this->email = $email;
$this->phone = normalizePhone($phone);
$this->comment = $comment;
$this->source = $source;
$this->funnel = $funnel;
$this->role = $userType;
}
public function addLeadToDB($userID)
{
$fio = $this->fio;
$email = $this->email;
$phone = $this->phone;
$opis = mysql_real_escape_string($this->comment);
$source = $this->source;
$funnel = $this->funnel;
$who_work = $userID;
$date_add = date("Y-m-d H:i:s");
$role = $this->role ? '[&quot;'.$this->role.'&quot;]' : '';
$sql = "INSERT INTO clients (`fio`, `email`, `phone`, `opis`, `source`, `type`, `who_work`,`id_agent`,`date_add`,`deleted`,`stage`,`confirm`,`funnel_id`,`budget`,`status`, `role`)
VALUES ('$fio','$email','$phone','$opis','$source','','0','$who_work','$date_add',0,1,0,'$funnel','','', '$role')";
$res = mysql_query($sql);
if ($res) {
$id = mysql_insert_id();
$client = new Clients;
$client->get_class_etap($id, $funnel);
} else {
$id = 0;
}
return $id;
}
}
// DO IT!
/*$agencyID = 7864; // Restate.Agency
$userID = 9426; // Новак Алексей Сергеевич
$head = array(); // на всякий случай сохранятся шапка
$leads = getCSV('http://tk.promit.ru/lead-send.csv?key=7da0e684609e4e1cc077f046be79e0be', $head);
if (is_array($leads) && !empty($leads)) {
foreach ($leads as $lead) {
// Получаем телефон лида (по-другому его не идентифицировать в нашей базе)
$phone = normalizePhone($lead[6]);
$comment = "Дата поступления: $lead[1]<br>Регион: $lead[2]<br>Стоимость квартиры: $lead[3]<br>Нужна ли ипотека: $lead[4]<br>Срок сдачи: $lead[8]<br>Первоначальный взнос: $lead[9]<br>Покупка планируется: $lead[10]<br>Продажа перед покупкой: $lead[11]<br>Название: $lead[12]<br>Комменатарий: $lead[15]<br>";
// Смотрим есть ли источник
$source = 0;
if (!empty($lead[21])) {
$source = getIDSource($lead[21], $agencyID);
if ($source == 0) {
$comment .= '<br><br>Источник: ' . $lead[21] . '<br>';
}
}
$userType = false;
if (!empty($lead[22])) {
switch ($lead[22]){
case 'Купить':
$userType = 'Покупатель';
break;
case 'Продать':
$userType = 'Продавец';
break;
case 'Снять':
$userType = 'Арендатор';
break;
case 'Сдать':
$userType = 'Арендодатель';
break;
}
}
$funnelId = 438;
if (!empty($lead[23])) {
$type = $lead[23];
if (strpos($type, 'Квартира в новостройке') !== false) {
$funnelId = 438;
}
if (strpos($type, 'Квартира (вторичка)') !== false) {
$funnelId = 121;
}
}
if ($lead[16] != '') {
$comment .= '<br><br>Послушать аудио по ссылке: <a href="' . $lead[16] . '">ссылка</a>';
}
$leadInDB = checkLeadInDB($phone, $agencyID);
if (is_array($leadInDB)) {
$leadSource = $leadInDB['source'];
$leadDeleted = $leadInDB['deleted'];
$leadId = $leadInDB['id'];
if ((empty($leadSource) || $leadSource == 0) && $source != 0) {
setLeadSource($source, $leadId);
}
if ($leadDeleted == 1) {
// Если дата с CSV отлична от даты в комментарии лида
if (checkLeadRenew($leadInDB['opis'], $lead[1])) {
$newComment = 'Восстановлен.<br>' . $comment;
setLeadNonDelete($leadId, $newComment);
}
}
} else {
$newLead = new Lead($lead[5], $lead[7], $phone, $comment, $source, $funnelId, $userType);
$newLeadID = $newLead->addLeadToDB($userID);
// Send event Telegram
$event = 'add'; // событие: Добавлен
$from = $userID; //
$sqlEvent = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`, send_telegramm) VALUES ('" . $userID . "', '" . $newLeadID . "', '" . $from . "', '" . $event . "', '2', '0')";
$resultEvent = mysql_query($sqlEvent);
}
}
}*/