'avito', 2 => 'cian', 3 => 'yandex', 4 => 'domclick', 5 => 'jcat', 6 => 'zipal', ]; private $_serviceCommonId = [ 1 => 'AVITO_JW_FEED', 2 => 'CIAN_JW_FEED', 3 => 'YANDEX_JW_FEED', 4 => 'DOMCLICK_JW_FEED', 5 => 'EMLS_JW_FEED', ]; public function __construct($db = null, $debug = false) { if ($debug == true) { $this->debug = true; error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1); } if (isset($_SESSION['id'])) { $user_id = intval($_SESSION['id']); $user = new User; $user->get($user_id); $this->_user = $user; } else { $this->_user = null; } if (!is_null($this->_user->id)) { $this->_user_id = (int)$this->_user->id; $this->_agency_id = (int)User::getUserAgencyID($this->_user->id); } if (!is_null($db)) { $this->_db = $db; } else { $pdo = new MysqlPdo(hst, ndb, user, pass); $pdo->query("SET NAMES 'utf8'"); $this->_db = $pdo; } } /** * @return int|null */ public function getAgencyId() { return $this->_agency_id; } public function getUserAmount($user_id = null, $period = 'month', $on_date = null, $off_date = null) { $amounts = []; if (!is_null($user_id)) { if (is_array($user_id)) { foreach ($user_id as $id) { $sql = "SELECT `do_not_reinit_monthly`, `datetime_for_limited` FROM `ads_budgets` WHERE `user_id` = '$id'"; $query = $this->_db->query($sql); if ($this->_db->num_rows($query) > 0) { $row = $this->_db->fetch_assoc($query); if ($row['do_not_reinit_monthly'] == 1) { $amounts = $this->getOneUserAmount($id, $amounts, 'dates', $row['datetime_for_limited'], date('Y-m-d 23:59:59')); } else { $amounts = $this->getOneUserAmount($id, $amounts); } } else { $amounts = $this->getOneUserAmount($id, $amounts); } } } else { $sql = "SELECT `do_not_reinit_monthly`, `datetime_for_limited` FROM `ads_budgets` WHERE `user_id` = '$user_id'"; $query = $this->_db->query($sql); if ($this->_db->num_rows($query) > 0) { $row = $this->_db->fetch_assoc($query); if ($row['do_not_reinit_monthly'] == 1) { $amounts = $this->getOneUserAmount($user_id, $amounts, 'dates', $row['datetime_for_limited'], date('Y-m-d 23:59:59')); } else { $amounts = $this->getOneUserAmount($user_id, $amounts); } } else { $amounts = $this->getOneUserAmount($user_id, $amounts); } } } return $amounts; } private function getOneUserAmount($user_id, $amounts, $period = 'month', $on_date = null, $off_date = null) { $sql1 = "SELECT `user_owner_id`, `destination`, `price`, `price_period`, `days_count` FROM `object_publish_statistic`"; $sql2 = "SELECT `user_owner_id`, `destination`, SUM(`price`) AS `price`, SUM(`price_period`) AS `price_period` FROM `object_publish_statistic`"; $sql = ""; $sql .= " WHERE `user_owner_id` = '$user_id'"; $sql .= " AND `price` != 0 AND `price_period` != 0"; $sql .= " AND `on_moderation` = 0"; $sql .= " AND `destination` IN (" . sprintf("'%s'", implode("', '", array_values($this->_serviceCommonId))) . ")"; if (!is_null($period)) { $dates = getPeriod($period, $on_date, $off_date, true); $date_between = $dates['between']; $start_date = $dates['dateStart']; if ($period == 'dates') { $sql .= " AND `created_at` $date_between"; } $sql .= " AND (`publish_start_date` $date_between OR `publish_end_date` $date_between OR '$start_date' BETWEEN `publish_start_date` AND `publish_end_date`)"; } else { $sql .= " AND DATE_FORMAT(`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-m-01') . " 00:00:00' AND '" . date('Y-m-31') . " 23:59:59'"; } $sql .= " AND `publish_end_date` > DATE(NOW())"; $sql_details = $sql1 . $sql . " LIMIT 10000"; //$_SESSION['_sql'][] = $sql_details; $query = $this->_db->query($sql1 . $sql . " LIMIT 10000"); if ($this->_db->num_rows($query) > 0) { while ($row = $this->_db->fetch_assoc($query)) { $user_owner_id = (int)$row['user_owner_id']; $service_id = $this->getServiceIdByCommonId($row['destination']); $service_name = $this->_serviceList[$service_id]; $amount = 0; if (isset($amounts[$user_owner_id][$service_name])) $amount = $amounts[$user_owner_id][$service_name]; $amount += (double)$row['price_period']; $amounts[$user_owner_id][$service_name] = $amount; } } $sql_total = $sql2 . $sql . " GROUP BY `user_owner_id`, `destination` LIMIT 10000"; //$_SESSION['_sql'][] = $sql_total; $query = $this->_db->query($sql_total); if ($this->_db->num_rows($query) > 0) { while ($row = $this->_db->fetch_assoc($query)) { $user_owner_id = (int)$row['user_owner_id']; $amounts[$user_owner_id]['total'] += (double)$row['price_period']; } } return $amounts; } public function getServiceId($service_id = null) { return $this->_serviceList[(int)$service_id]; } public function getServiceByName($service = null) { return array_search($service, $this->_serviceList); } public function getServiceCommonId($service_id = null) { return $this->_serviceCommonId[(int)$service_id]; } public function getServiceIdByCommonId($common_id = null) { if (!is_null($common_id)) return array_search($common_id, $this->_serviceCommonId); } public function getServiceName($service_id = null, $html = true) { if (!is_null($service_id)) { if (is_numeric($service_id)) $service = $this->_serviceList[$service_id]; else $service = $service_id; if ($service) { switch ($service) { case 'avito': return ($html) ? "Avito" : 'Avito'; case 'cian': return ($html) ? "ЦИАН" : 'ЦИАН'; case 'yandex': return ($html) ? "Я.Недвижимость" : 'Я.Недвижимость'; case 'domclick': return ($html) ? "ДомКлик" : 'ДомКлик'; case 'jcat': return ($html) ? "JCat" : 'JCat'; case 'zipal': return ($html) ? "Zipal" : 'Zipal'; } } } return false; } public function getServiceNameByCommonId($common_id = null, $html = true) { if (!is_null($common_id)) { $service_id = array_search($common_id, $this->_serviceCommonId); return $this->getServiceName($service_id, $html); } return false; } public function getSummaryByUsers($users_ids = null, $object_ids = null, $period = null, $on_date = null, $off_date = null) { $post = clearInputData($_POST); if (is_null($on_date) && !empty($post['onDate'])) $on_date = $post['onDate']; if (is_null($off_date) && !empty($post['offDate'])) $off_date = $post['onDate']; $amounts = []; if (!is_null($users_ids)) { if (!is_null($users_ids) && !is_array($users_ids)) $users_ids = [$users_ids]; if (!is_null($object_ids) && !is_array($object_ids)) $object_ids = [$object_ids]; if (!is_null($object_ids)) $sql = "SELECT `user_owner_id`, `object_id`, `destination`, `price` as `amount` FROM `object_publish_statistic` INNER JOIN objects o ON object_publish_statistic.object_id = o.id WHERE true"; else $sql = "SELECT `user_owner_id`, `object_id`, `destination`, SUM(`price`) as `amount` FROM `object_publish_statistic` INNER JOIN objects o ON object_publish_statistic.object_id = o.id WHERE true"; if (!is_null($period)) { $dates = getPeriod($period, $on_date, $off_date); $date_between = $dates['between']; $start_date = $dates['dateStart']; $sql .= " AND (`publish_start_date` $date_between)"; } else { $sql .= " AND DATE_FORMAT(`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-m-01') . " 00:00:00' AND '" . date('Y-m-31') . " 23:59:59'"; } $sql .= " AND `on_moderation` = 0"; $sql .= " AND `user_owner_id` IN (".implode(',', $users_ids).")"; if (!is_null($object_ids)) { $sql .= " AND `object_id` IN (".implode(',', $object_ids).")"; $sql .= " GROUP BY `object_id`, `destination` LIMIT 10000"; } else { $sql .= " GROUP BY `user_owner_id`, `destination` LIMIT 10000"; } $_SESSION['_sql'][] = $sql; $query = $this->_db->query($sql); if ($this->_db->num_rows($query)) { while($row = $this->_db->fetch_assoc($query)) { $row['service_id'] = $this->getServiceIdByCommonId($row['destination']); unset($row['destination']); $row['user_id'] = intval($row['user_owner_id']); unset($row['user_owner_id']); $amounts[] = $row; } } } return $amounts; } public function getSummaryByObject($object_id = null, $period = null) { $amounts = []; if (!is_null($object_id)) { $users_ids = User::getAllAgencyUsers($this->_agency_id); $sql = "SELECT `statistic`.*, `users`.`agency`, `users`.`manager`, `users`.`fio`, `users`.`last_name`, `users`.`first_name`, `users`.`middle_name` FROM `object_publish_statistic` AS `statistic` LEFT JOIN `users` AS `users` ON `users`.`id`= `statistic`.`user_owner_id` WHERE `statistic`.`object_id` = '$object_id' AND `statistic`.`on_moderation` = 0"; if (!is_null($period)) { switch ($period) { case 'month': $last_day = cal_days_in_month(CAL_GREGORIAN, (int)date('m'), date('Y')); $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y') . "-" . date('m') . "-01 00:00:00' AND '" . date('Y') . "-" . $last_day . "-01 00:00:00'"; break; case 'today': $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date("Y-m-d 00:00:00") . "' AND '" . date("Y-m-d 23:59:59") . "'"; break; case 'quarter': if ((int)date('m') < 4) $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-01-01 00:00:00') . "' AND '" . date('Y-03-31 23:59:59') . "'"; else if ((int)date('m') >= 4 && (int)date('m') < 7) $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-04-01 00:00:00') . "' AND '" . date('Y-06-30 23:59:59') . "'"; else if ((int)date('m') >= 7 && (int)date('m') < 10) $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-07-01 00:00:00') . "' AND '" . date('Y-09-30 23:59:59') . "'"; else if ((int)date('m') >= 10 && (int)date('m') < 13) $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-10-01 00:00:00') . "' AND '" . date('Y-12-31 23:59:59') . "'"; break; case 'week': $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date("Y-m-d 00:00:00", strtotime("monday this week")) . "' AND '" . date("Y-m-d 23:59:59", strtotime("sunday this week")) . "'"; break; case 'dates' : $post = clearInputData($_POST); $onDate = $post['onDate']; $offDate = $post['offDate']; if (empty($offDate)) $offDate = date('Y-m-d 23:59:59'); $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date("Y-m-d 00:00:00", strtotime($onDate)) . "' AND '" . date("Y-m-d 23:59:59", strtotime($offDate)) . "'"; break; case 'year': $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-01-01') . " 00:00:00' AND '" . date('Y-12-31') . " 23:59:59'"; break; default : $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-m-01') . " 00:00:00' AND '" . date('Y-m-31') . " 23:59:59'"; break; } } else { $sql .= " AND DATE_FORMAT(`statistic`.`publish_start_date`, '%Y-%m-%d %H:%i:%s') BETWEEN '" . date('Y-m-01') . " 00:00:00' AND '" . date('Y-m-31') . " 23:59:59'"; } $sql .= " AND `statistic`.`user_owner_id` IN (".implode(',', $users_ids).")"; $sql .= " LIMIT 10000"; $query = $this->_db->query($sql); if ($this->_db->num_rows($query)) { while($row = $this->_db->fetch_assoc($query)) { $row['service_id'] = $this->getServiceIdByCommonId($row['destination']); unset($row['destination']); $row['user_id'] = intval($row['user_owner_id']); unset($row['user_owner_id']); $amounts[(int)$row['object_id']][] = $row; } } } return $amounts[$object_id]; } public function deleteAdvertPrice($id = null) { if (!is_null($id)) { if ($this->_db->query("DELETE FROM `ads_prices` WHERE `agency_id` = '$this->_agency_id' AND `id` = '$id'")) { return [ 'success' => true ]; } } return [ 'success' => false, 'errors' => $this->_db->errorInfo(), ]; } public function getObjectAdvertPrices($object_id = null, $service_id = null, $days = 0) { $regionChildSql = ""; // дочерний регион (город или область) для дополнительной фильтрации $regionChildId = null; // регион объекта $objectRegionId = null; // адрес объекта $objectAddress = null; //ищем регион объекта $sqlRegion = "SELECT `objects`.`id_rf_region` FROM `objects` AS `objects` WHERE `objects`.`id` = $object_id"; $queryRegion = $this->_db->query($sqlRegion); if ($this->_db->num_rows($queryRegion)) { $row = $this->_db->fetch_assoc($queryRegion); $objectRegionId = $row['id_rf_region']; } $foundPrices = []; $hasPricesWithChildRegion = false; //если нашли регион объекта, выбираем ВСЕ ЦЕНЫ для этого региона if ($objectRegionId) { $sqlPrices = "SELECT `prices`.* FROM `ads_prices` AS `prices` WHERE `prices`.`agency_id` = '{$this->_agency_id}' AND `prices`.`region_id` = $objectRegionId"; $queryPrices = $this->_db->query($sqlPrices); if ($this->_db->num_rows($queryPrices)) { while ($row = $this->_db->fetch_assoc($queryPrices)) { $foundPrices[] = $row; if ($row['region_child_id'] != null && $row['region_child_id'] > 0) { $hasPricesWithChildRegion = true; } } } } $nameObl = null; $idObl = null; //если у нас есть записи с указанным городом или областью, надо понять, что у нас в объекте. if ($hasPricesWithChildRegion) { //ищем все дочерние записи для региона объекта и ищем там область $sqlRegionChild = "SELECT * FROM `rf_regions` AS `rf_regions` WHERE `rf_regions`.`parent` = $objectRegionId AND `is_city` = 0"; $queryRegionChild = $this->_db->query($sqlRegionChild); if ($this->_db->num_rows($queryRegionChild)) { $rowRegionChild = $this->_db->fetch_assoc($queryRegionChild); $nameObl = $rowRegionChild['name']; $idObl = $rowRegionChild['id']; } //если у нас есть имя области, то пробуем ее найти в адресе if ($nameObl) { $sqlAddress = "SELECT `object_location`.`address` FROM `object_location` AS `object_location` WHERE `object_location`.`object_id` = $object_id"; $queryAddress = $this->_db->query($sqlAddress); if ($this->_db->num_rows($queryAddress)) { $row = $this->_db->fetch_assoc($queryAddress); $objectAddress = $row['address']; } } if ($objectAddress && (strpos($objectAddress, $nameObl) !== false || strpos($objectAddress, str_replace("область", "обл", $nameObl)) !== false)) { //у нас область foreach ($foundPrices as $pr) { if ($pr['region_child_id'] == $idObl) { $regionChildId = $idObl; } } } else { $idCity = null; // у нас город $sqlRegionChild = "SELECT * FROM `rf_regions` AS `rf_regions` WHERE `rf_regions`.`parent` = $objectRegionId AND `is_city` = 1"; $queryRegionChild = $this->_db->query($sqlRegionChild); if ($this->_db->num_rows($queryRegionChild)) { $rowRegionChild = $this->_db->fetch_assoc($queryRegionChild); $idCity = $rowRegionChild['id']; } if ($idCity != null) { foreach ($foundPrices as $pr) { if ($pr['region_child_id'] == $idCity) { $regionChildId = $idCity; } } } } } if ($regionChildId != null) { $regionChildSql = " `prices`.`region_child_id` = '$regionChildId' AND "; } else { $regionChildSql = " (`prices`.`region_child_id` IS NULL OR `prices`.`region_child_id` = 0) AND "; } $price = null; $owner_user_id = null; $no_criterias = false; $period = $this->_default_advert_period; if ($this->_agency_id && !is_null($object_id)) { $sql = "SELECT `prices`.*, `objects`.`id_add_user` AS `owner_user_id` FROM `ads_prices` AS `prices` JOIN `objects` AS `objects` WHERE `prices`.`agency_id` = '{$this->_agency_id}' AND `prices`.`region_id` = `objects`.`id_rf_region` AND " . $regionChildSql . " `prices`.`operation_type_id` = IF(`objects`.`operation_type` = 0, 2, 1) AND `prices`.`type_id` = `objects`.`type` AND ((`objects`.`operation_type` = 0 AND `prices`.`rent_type_id` = `objects`.`srok`) OR `objects`.`operation_type` != 0) AND ((`objects`.`type` = 4 AND `prices`.`commerce_type_id` = `objects`.`type_category`) OR `objects`.`type` != 4) AND `objects`.`id` = '$object_id' LIMIT 1"; $query = $this->_db->query($sql); if ($this->_db->num_rows($query)) { $row = $this->_db->fetch_assoc($query); $row['price_period'] = ['price']; $price = $row; $owner_user_id = $row['owner_user_id']; $no_criterias = true; } } $budget = null; if (($_SESSION['use_advert_budget']) && $owner_user_id) { $budget = $this->getAdvertBudget($owner_user_id); } if (!is_null($service_id)) { $service_name = $this->getServiceId($service_id); if ($days == 5000) $days = 0; $cost = $price[$service_name]; $price_period = $price[$service_name]; if ((int)$days > 0 && $cost > 0 && (int)$period > 0) $cost = $cost * ceil($days/$period); return [ 'price' => $cost, 'price_period' => $price_period, 'owner_user_id' => $owner_user_id, 'budget' => $budget[$service_name.'_unlimited'] ? null : $budget[$service_name.'_available'], 'is_unlimited' => $budget[$service_name.'_unlimited'], 'is_no_criterias' => $no_criterias, 'sql' => $sql, ]; } else if (!empty($price)) { return array_merge( $price, [ 'owner_user_id' => $owner_user_id, 'budget' => $budget, 'is_no_criterias' => $no_criterias, 'sql' => $sql, ] ); } return null; } public function getAdvertPrices($compare_data = null, $strict_mode = false) { $prices = []; $id = null; if (isset($compare_data['id'])) $id = $compare_data['id']; $region_id = $compare_data['region_id']; $region_child_id = $compare_data['region_child_id']; $operation_type_id = $compare_data['operation_type_id']; $rent_type_id = $compare_data['rent_type_id']; $type_id = $compare_data['type_id']; $commerce_type_id = $compare_data['commerce_type_id']; if ($strict_mode) { if (is_null($region_id) || is_null($operation_type_id) || is_null($rent_type_id) || is_null($type_id) || is_null($commerce_type_id)) { return []; } } if ($this->_agency_id) { $sql = "SELECT `prices`.*, `rf_regions`.`name` AS `region`, `rf_regions_child`.`name` AS `child_region`, `commercial_object`.`name` AS `commerce_type` FROM `ads_prices` AS `prices` LEFT JOIN `rf_regions` as `rf_regions` ON `rf_regions`.`id` = `prices`.`region_id` LEFT JOIN `rf_regions` as `rf_regions_child` ON `rf_regions_child`.`id` = `prices`.`region_child_id` LEFT JOIN `commercial_object` ON `commercial_object`.`id` = `prices`.`commerce_type_id` WHERE `prices`.`agency_id` = '$this->_agency_id'"; } else { $sql = "SELECT `prices`.*, `rf_regions`.`name` AS `region`, `rf_regions_child`.`name` AS `child_region`, `commercial_object`.`name` AS `commerce_type` FROM `ads_prices` AS `prices` LEFT JOIN `rf_regions` ON `rf_regions`.`id` = `prices`.`region_id` LEFT JOIN `rf_regions` as `rf_regions_child` ON `rf_regions_child`.`id` = `prices`.`region_child_id` LEFT JOIN `commercial_object` ON `commercial_object`.`id` = `prices`.`commerce_type_id` WHERE `prices`.`agency_id` = '{$this->_user->id}'"; } if ($id) $sql .= " AND `prices`.`id` = '$id'"; if ($region_id) $sql .= " AND `prices`.`region_id` = '$region_id'"; if ($region_child_id) $sql .= " AND `prices`.`region_child_id` = '$region_child_id'"; if ($operation_type_id) $sql .= " AND `prices`.`operation_type_id` = '$operation_type_id'"; if ($rent_type_id) $sql .= " AND `prices`.`rent_type_id` = '$rent_type_id'"; if ($type_id) $sql .= " AND `prices`.`type_id` = '$type_id'"; if ($commerce_type_id) $sql .= " AND `prices`.`commerce_type_id` = '$commerce_type_id'"; if ($id || $strict_mode) $sql .= " LIMIT 1"; $query = $this->_db->query($sql); if ($this->_db->num_rows($query)) { global $SROK_ARENDY; global $OBJECT_TYPES; while($row = $this->_db->fetch_assoc($query)) { $criteries = []; if (isset($row['operation_type_id'])) { if ((int)$row['operation_type_id'] == 1) { $criteries[] = "Продажа"; } else { if (isset($row['rent_type_id'])) $criteries[] = "Аренда " . $SROK_ARENDY[(int)$row['rent_type_id']]; else $criteries[] = "Аренда"; } } if (isset($row['type_id'])) { if (isset($OBJECT_TYPES[(int)$row['type_id']])) { if ((int)$row['type_id'] == 4) { $criteries[] = ' коммерческой недвижимости: '; if (isset($row['commerce_type'])) $criteries[] = mb_strtolower($row['commerce_type']); } else { $criteries[] = ' ' . mb_strtolower($OBJECT_TYPES[(int)$row['type_id']]); } } } if (isset($row['region'])) $criteries[] = ' в ' . $row['region']; if (isset($row['child_region'])) $criteries[] = ' (' . $row['child_region'] . ')'; $prices[] = [ 'id' => (int)$row['id'], 'region_id' => (int)$row['region_id'], 'region_id_child' => (int)$row['region_child_id'], 'operation_type_id' => (int)$row['operation_type_id'], 'type_id' => (int)$row['type_id'], 'rent_type_id' => (int)$row['rent_type_id'], 'commerce_type_id' => (int)$row['commerce_type_id'], 'avito' => (double)$row['avito'], 'cian' => (double)$row['cian'], 'yandex' => (double)$row['yandex'], 'domclick' => (double)$row['domclick'], 'jcat' => (double)$row['jcat'], 'criteries' => $criteries, ]; } } if ($id && !empty($prices)) return $prices[0]; else return $prices; } public function getAllAgencyUsers($user_id) { $agency_id = \User::getAgencyIdForUser($user_id); if (!empty($agency_id)) { $users_ids = array_map('intval', \User::getAllAgencyUsers($agency_id)); $users_ids[] = (int)$agency_id; } $users_ids[] = (int)$user_id; return array_unique($users_ids); } public function updateObjectCost($object_id = null, $service_id = null) { $errors = []; $updated = []; if ($service_id) { $destination = $this->getServiceCommonId($service_id); if ($object_id && $destination) { //$agents_ids = $this->getAllAgencyUsers($this->_agency_id); $sql = "SELECT * FROM `object_publish_statistic` WHERE `object_id` = '$object_id' AND `on_moderation` = 0 AND `unpublish_user_id` IS NULL AND `destination` = '$destination' AND ( `publish_end_date` IS NULL OR `publish_end_date` = '0000-00-00 00:00:00' OR `publish_end_date` > NOW() )"; if ($query = $this->_db->query($sql)) { if ($this->_db->num_rows($query)) { while($row = $this->_db->fetch_assoc($query)) { $days_count = $this->_default_advert_period; if (isset($row['publish_start_date'])) { $date = new DateTime(); $days_diff = $date->diff(new DateTime($row['publish_start_date']))->format("%a"); if ($days_diff >= 0) { $days_count = $days_diff; } } $price = 0; if (isset($row['price'])) $price = $row['price']; $results = $this->getObjectAdvertPrices($object_id, $service_id, $days_count); if (!is_null($results['price'])) $price = $results['price']; $updated[(int)$row['id']] = [ 'object_id' => $object_id, 'unpublish_user_id' => $this->_user_id, 'publish_start_date' => $row['publish_start_date'], 'publish_end_date' => date('Y-m-d H:i:s'), 'days_count' => $days_count, 'price' => $price, ]; } } } if (!empty($updated)) { foreach ($updated as $row_id => $row) { $sql = "UPDATE `object_publish_statistic` SET `unpublish_user_id` = '$row[unpublish_user_id]', `publish_end_date` = '$row[publish_end_date]', `days_count` = '$row[days_count]', `price` = '$row[price]' WHERE `id` = '$row_id'"; if (!$this->_db->query($sql)) { $errors[] = $this->_db->errorInfo(); } } } } } if (empty($errors)) { return [ 'success' => true, 'object_id' => $object_id, 'service_id' => $service_id, 'updated' => $updated ]; } else { return [ 'success' => false, 'errors' => $errors ]; } } public function setAdvertPrices($data = null) { if (!is_null($data)) { $id = (int)$data['id']; $region_id = (int)$data['region_id']; $region_child_id = (int)$data['region_child_id']; $operation_type_id = (int)$data['operation_type_id']; $rent_type_id = (int)$data['rent_type_id']; $type_id = (int)$data['type_id']; $commerce_type_id = (int)$data['commerce_type_id']; $avito = (double)$data['avito']; $cian = (double)$data['cian']; $domclick = (double)$data['domclick']; $jcat = (double)$data['jcat']; $yandex = (double)$data['yandex']; if (!$id) { $sql = "INSERT INTO `ads_prices` ( `agency_id`, `region_id`, `region_child_id`, `operation_type_id`, `type_id`, `rent_type_id`, `commerce_type_id`, `avito`, `cian`, `yandex`, `domclick`, `jcat`, `created_by` ) VALUES ( '$this->_agency_id', '$region_id', '$region_child_id', '$operation_type_id', '$type_id', '$rent_type_id', '$commerce_type_id', '$avito', '$cian', '$yandex', '$domclick', '$jcat', '{$_SESSION['id']}' )"; } else { $sql = "UPDATE `ads_prices` SET `region_id` = '$region_id', `region_child_id` = '$region_child_id', `operation_type_id` = '$operation_type_id', `type_id` = '$type_id', `rent_type_id` = '$rent_type_id', `commerce_type_id` = '$commerce_type_id', `avito` = '$avito', `cian` = '$cian', `yandex` = '$yandex', `domclick` = '$domclick', `jcat` = '$jcat', `updated_by` = '{$_SESSION['id']}' WHERE `id` = '$id' AND `agency_id` = '$this->_agency_id'"; } if ($this->_db->query($sql)) { if (!$id) $id = $this->_db->insert_id(); return [ 'success' => true, 'id' => $id ]; } } return [ 'success' => false, 'errors' => $this->_db->errorInfo(), ]; } public function getAdvertBudget($user_id = null) { $as_array = false; if (!is_null($user_id)) { if (is_array($user_id)) { $as_array = true; $employee_id = $user_id; } else { $employee_id = (int)$user_id; } } else { $employee_id = $this->_user->id; } if (!empty($employee_id)) { if (is_array($employee_id)) { $employee_id = array_unique($employee_id); if ($this->_agency_id) $sql = "SELECT * FROM `ads_budgets` WHERE `agency_id` = '{$this->_agency_id}' AND `user_id` IN (".implode(',', $employee_id).")"; else $sql = "SELECT * FROM `ads_budgets` WHERE `user_id` IN (".implode(',', $employee_id).")"; $sql .= " GROUP BY `user_id`"; } else { if ($this->agency_id) $sql = "SELECT * FROM `ads_budgets` WHERE `agency_id` = {$this->agency_id} AND `user_id` = '$employee_id'"; else $sql = "SELECT * FROM `ads_budgets` WHERE `user_id` = '$employee_id'"; $sql .= " GROUP BY `user_id` LIMIT 1"; } $data = []; if (!is_array($employee_id)) $users_ids = [$employee_id]; else $users_ids = $employee_id; $users_ids = array_unique($users_ids); $all_agency_amounts = $this->getUserAmount($users_ids); foreach ($users_ids as $user_id) { $amounts = $all_agency_amounts[$user_id]; $avito_amount = (double)$amounts[$user_id]['avito']; $cian_amount = (double)$amounts[$user_id]['cian']; $yandex_amount = (double)$amounts[$user_id]['yandex']; $domclick_amount = (double)$amounts[$user_id]['domclick']; $jcat_amount = (double)$amounts[$user_id]['jcat']; $zipal_amount = (double)$amounts[$user_id]['zipal']; $data[$user_id] = [ 'avito' => 0.0, 'avito_amount' => $avito_amount, 'avito_available' => 0 - $avito_amount, 'cian' => 0.0, 'cian_amount' => $cian_amount, 'cian_available' => 0 - $cian_amount, 'yandex' => 0.0, 'yandex_amount' => $yandex_amount, 'yandex_available' => 0 - $yandex_amount, 'domclick' => 0.0, 'domclick_amount' => $domclick_amount, 'domclick_available' => 0 - $domclick_amount, 'jcat' => 0.0, 'jcat_amount' => $jcat_amount, 'jcat_available' => 0 - $jcat_amount, 'zipal' => 0.0, 'zipal_amount' => $zipal_amount, 'zipal_available' => 0 - $zipal_amount, 'total' => 0.0, 'personal' => 0.0, 'amount' => (double)$amounts[$user_id]['total'], 'balance' => (0 - (double)$amounts[$user_id]['total']), ]; } $query = $this->_db->query($sql); if ($this->_db->num_rows($query) > 0) { while($row = $this->_db->fetch_assoc($query)) { $user_id = (int)$row['user_id']; $user_amount = $all_agency_amounts[$user_id]; $avito_amount = (double)$user_amount['avito']; $cian_amount = (double)$user_amount['cian']; $yandex_amount = (double)$user_amount['yandex']; $domclick_amount = (double)$user_amount['domclick']; $jcat_amount = (double)$user_amount['jcat']; $zipal_amount = (double)$user_amount['zipal']; $data[$user_id] = [ 'avito' => (double)$row['avito'], 'avito_amount' => $avito_amount, 'avito_available' => (double)$row['avito'] - $avito_amount, 'avito_unlimited' => (int)$row['avito_unlimited'], 'cian' => (double)$row['cian'], 'cian_amount' => $cian_amount, 'cian_available' => (double)$row['cian'] - $cian_amount, 'cian_unlimited' => (int)$row['cian_unlimited'], 'yandex' => (double)$row['yandex'], 'yandex_amount' => $yandex_amount, 'yandex_available' => (double)$row['yandex'] - $yandex_amount, 'yandex_unlimited' => (int)$row['yandex_unlimited'], 'domclick' => (double)$row['domclick'], 'domclick_amount' => $domclick_amount, 'domclick_available' => (double)$row['domclick'] - $domclick_amount, 'domclick_unlimited' => (int)$row['domclick_unlimited'], 'jcat' => (double)$row['jcat'], 'jcat_amount' => $jcat_amount, 'jcat_available' => (double)$row['jcat'] - $jcat_amount, 'jcat_unlimited' => (int)$row['jcat_unlimited'], 'zipal' => (double)$row['zipal'], 'zipal_amount' => $zipal_amount, 'zipal_available' => (double)$row['zipal'] - $zipal_amount, 'zipal_unlimited' => (int)$row['zipal_unlimited'], 'total' => (double)$row['total'], 'personal' => (double)$row['personal'], 'do_not_reinit_monthly' => (bool)$row['do_not_reinit_monthly'], 'amount' => (double)$user_amount['total'], 'balance' => ((double)$row['total'] - (double)$user_amount['total']), ]; } if (count($data) == 1 && !$as_array) return array_values($data)[0]; else return $data; } } return null; } public function getAdvertBudgets($user_id = null, $all_agency = false) { if (!empty($user_id)) { $user_id = (int)$user_id; $user = new User(); $user->get($user_id); } else { $user = $this->_user; } if (is_null($user)) return false; $budgets = []; $departments = []; //$users_ids = User::getAllAgencyUsers($this->_agency_id); if(!empty($user_id) && $user_id == 5238){ $usersIds = array(); $agency_id = $this->_agency_id; $usersIds[] = $agency_id; $sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$agency_id or id_manager=$agency_id or id_manager in (select id from users where id_manager=$agency_id or id_manager in (select id from users where id_manager=$agency_id)))"; $q_users = $this->_db->query($sql_users); while($r_users = $this->_db->fetch_assoc($q_users)){ $usersIds[] = (int)$r_users['id']; } $sql_u = "SELECT * FROM users WHERE id in (".implode(',',$usersIds).")"; $q_u = $this->_db->query($sql_u); while($row = $this->_db->fetch_assoc($q_u)){ $list[$row['id']] = $row; } $users = $list; } else{ $users = $user->getMyUsers(true); } if (count($users) > 0) { $agents_ids = []; if(isset($usersIds)){ $agents_ids = $usersIds; } else { if ($all_agency) $agents_ids[] = $this->_agency_id; if ($user_id) $agents_ids[] = $user_id; foreach($users['users'] as $user) { $agents_ids[] = (int)$user['id']; } } $advert_budgets = $this->getAdvertBudget(array_unique($agents_ids)); if ($all_agency) { $sql = "SELECT * FROM users WHERE id_manager=$this->_agency_id AND blocked=0"; $rez = mysql_query($sql); $managers = array(); while($manager = mysql_fetch_assoc($rez)) { $managers[] = $manager['id']; } $agency_avito = 0; $agency_avito_amount = 0; $agency_cian = 0; $agency_cian_amount = 0; $agency_domclick = 0; $agency_domclick_amount = 0; $agency_jcat = 0; $agency_jcat_amount = 0; $agency_yandex = 0; $agency_yandex_amount = 0; $agency_total = 0; $agency_amount = 0; $agency_balance = 0; foreach ($advert_budgets as $key => $budget) { $agency_avito += $budget['avito']; $agency_avito_amount += $budget['avito_amount']; $agency_cian += $budget['cian']; $agency_cian_amount += $budget['cian_amount']; $agency_domclick += $budget['domclick']; $agency_domclick_amount += $budget['domclick_amount']; $agency_jcat += $budget['jcat']; $agency_jcat_amount += $budget['jcat_amount']; $agency_yandex += $budget['yandex']; $agency_yandex_amount += $budget['yandex_amount']; if (in_array($key, $managers)) { $agency_total += $budget['total']; $agency_balance += $budget['balance']; } $agency_amount += $budget['amount']; } return [ 'avito' => $agency_avito, 'avito_amount' => $agency_avito_amount, 'avito_available' => (double)$agency_avito - (double)$agency_avito_amount, 'cian' => $agency_cian, 'cian_amount' => $agency_cian_amount, 'cian_available' => (double)$agency_cian - (double)$agency_cian_amount, 'domclick' => $agency_domclick, 'domclick_amount' => $agency_domclick_amount, 'domclick_available' => (double)$agency_domclick - (double)$agency_domclick_amount, 'jcat' => $agency_jcat, 'jcat_amount' => $agency_jcat_amount, 'jcat_available' => (double)$agency_jcat - (double)$agency_jcat_amount, 'yandex' => $agency_yandex, 'yandex_amount' => $agency_yandex_amount, 'yandex_available' => (double)$agency_yandex - (double)$agency_yandex_amount, 'total' => $agency_total, 'amount' => $agency_amount, 'balance' => $agency_total - $agency_amount ]; } else { if ($this->_agency_id) { $sql = "SELECT d.name AS dep_name, r.name AS role_name, r.role, r.department_id, r.id FROM departments AS d LEFT JOIN `roles` AS r ON d.id = r.department_id WHERE d.agency_id = ".$this->_agency_id; if ($query = $this->_db->query($sql)) { if ($this->_db->num_rows($query)) { while($row = $this->_db->fetch_assoc($query)) { if ($row['id'] > 0) { $departments[(int)$row['id']] = $row; } } } } } foreach($users['users'] as $user) { $isAdminDep = false; $role_id = (int)$user['role_id']; if ($role_id > 0 && ($departments[$role_id]['role'] == 'admin_department')) $isAdminDep = true; $user_budget = $advert_budgets[(int)$user['id']]; //var_dump([$user['id'], $departments[$role_id]['role'], $budget['balance']]); $avito = $user_budget['avito']; $avito_amount = $user_budget['avito_amount']; $avito_unlimited = $user_budget['avito_unlimited']; $cian = $user_budget['cian']; $cian_amount = $user_budget['cian_amount']; $cian_unlimited = $user_budget['cian_unlimited']; $domclick = $user_budget['domclick']; $domclick_amount = $user_budget['domclick_amount']; $domclick_unlimited = $user_budget['domclick_unlimited']; $jcat = $user_budget['jcat']; $jcat_amount = $user_budget['jcat_amount']; $jcat_unlimited = $user_budget['jcat_unlimited']; $yandex = $user_budget['yandex']; $yandex_amount = $user_budget['yandex_amount']; $yandex_unlimited = $user_budget['yandex_unlimited']; $total = $user_budget['total']; $amount = $user_budget['amount']; $balance = $user_budget['balance']; //var_dump([$user['id'], $user_budget['total']]); if ($isAdminDep) { //$managers_dep = \User::getDepManagers($user['department_id']); $users_dep = \User::getAgentsOfManagers($user['id'], true); $agents_dep = \User::getAgentsOfManager($user['id'], true); foreach ($agents_dep as $agent) { $users_dep[] = $agent; } foreach($users_dep as $user_dep) { $isAdminDep = false; $role_id = (int)$user_dep['role_id']; if ($role_id > 0 && ($departments[$role_id]['role'] == 'admin_department' || $departments[$role_id]['role'] == 'manager')) $isAdminDep = true; $user_dep_budget = $advert_budgets[$user_dep['id']]; //var_dump([$user_dep['id'], $departments[$role_id]['role']], $user_dep_budget['balance']); $avito += $user_dep_budget['avito']; $avito_amount += $user_dep_budget['avito_amount']; $cian += $user_dep_budget['cian']; $cian_amount += $user_dep_budget['cian_amount']; $domclick += $user_dep_budget['domclick']; $domclick_amount += $user_dep_budget['domclick_amount']; $jcat += $user_dep_budget['jcat']; $jcat_amount += $user_dep_budget['jcat_amount']; $yandex += $user_dep_budget['yandex']; $yandex_amount += $user_dep_budget['yandex_amount']; //$total += $user_dep_budget['total']; $amount += $user_dep_budget['amount']; //$balance += $user_dep_budget['balance']; if ($isAdminDep) { $agents_dep = \User::getAgentsOfManager($user_dep['id'], true); foreach ($agents_dep as $agent_dep) { $agent_dep_budget = $advert_budgets[$agent_dep['id']]; $avito += $agent_dep_budget['avito']; $avito_amount += $agent_dep_budget['avito_amount']; $cian += $agent_dep_budget['cian']; $cian_amount += $agent_dep_budget['cian_amount']; $domclick += $agent_dep_budget['domclick']; $domclick_amount += $agent_dep_budget['domclick_amount']; $jcat += $agent_dep_budget['jcat']; $jcat_amount += $agent_dep_budget['jcat_amount']; $yandex += $agent_dep_budget['yandex']; $yandex_amount += $agent_dep_budget['yandex_amount']; //$total += $agent_dep_budget['total']; $amount += $agent_dep_budget['amount']; //$balance += $agent_dep_budget['balance']; } } } } else { $agents = \User::getAgentsOfManager($user['id'], true); foreach($agents as $agent) { $agent_budget = $advert_budgets[$agent['id']]; $avito_amount += $agent_budget['avito_amount']; $cian += $agent_budget['cian']; $cian_amount += $agent_budget['cian_amount']; $domclick += $agent_budget['domclick']; $domclick_amount += $agent_budget['domclick_amount']; $jcat += $agent_budget['jcat']; $jcat_amount += $agent_budget['jcat_amount']; $yandex += $agent_budget['yandex']; $yandex_amount += $agent_budget['yandex_amount']; //$total += $agent_budget['total']; $amount += $agent_budget['amount']; //$balance += $agent_budget['balance']; //var_dump([$agent['id'], $agent_budget['total']]); } } $budgets[(int)$user['id']] = [ 'avito' => $avito, 'avito_amount' => $avito_amount, 'avito_available' => (double)$avito - (double)$avito_amount, 'avito_unlimited' => $avito_unlimited, 'cian' => $cian, 'cian_amount' => $cian_amount, 'cian_available' => (double)$cian - (double)$cian_amount, 'cian_unlimited' => $cian_unlimited, 'domclick' => $domclick, 'domclick_amount' => $domclick_amount, 'domclick_available' => (double)$domclick - (double)$domclick_amount, 'domclick_unlimited' => $domclick_unlimited, 'jcat' => $jcat, 'jcat_amount' => $jcat_amount, 'jcat_available' => (double)$jcat - (double)$jcat_amount, 'jcat_unlimited' => $jcat_unlimited, 'yandex' => $yandex, 'yandex_amount' => $yandex_amount, 'yandex_available' => (double)$yandex - (double)$yandex_amount, 'yandex_unlimited' => $yandex_unlimited, 'total' => $total, 'personal' => (double)$user_budget['personal'], 'amount' => $amount, 'balance' => $total - $amount, 'user_id' => (int)$user['id'], ]; } //var_dump($budgets); return $budgets; } } return null; } public function setAdvertBudget($data) { if (isset($this->_user->id)) { if (isset($data['user_id'])) $employee_id = (int)$data['user_id']; else $employee_id = $this->_user->id; if ($this->_agency_id) $sql = "SELECT * FROM `ads_budgets` WHERE `agency_id`={$this->_agency_id} AND `user_id`='{$employee_id}'"; else $sql = "SELECT * FROM `ads_budgets` WHERE `user_id`='{$employee_id}'"; $services_count = 0; $avito = 0; $avito_unlimited = 0; if (!(int)$data['avito_unlimited']) { $avito = (double)$data['avito']; $services_count++; } else { $avito_unlimited = 1; } $cian = 0; $cian_unlimited = 0; if (!(int)$data['cian_unlimited']) { $cian = (double)$data['cian']; $services_count++; } else { $cian_unlimited = 1; } $yandex = 0; $yandex_unlimited = 0; if (!(int)$data['yandex_unlimited']) { $yandex = (double)$data['yandex']; $services_count++; } else { $yandex_unlimited = 1; } $domclick = 0; $domclick_unlimited = 0; if (!(int)$data['domclick_unlimited']) { $domclick = (double)$data['domclick']; $services_count++; } else { $domclick_unlimited = 1; } $jcat = 0; $jcat_unlimited = 0; if (!(int)$data['jcat_unlimited']) { $jcat = (double)$data['jcat']; //$services_count++; } else { $jcat_unlimited = 1; } $do_not_reinit_monthly = 0; $datetime_for_limited = null; if ((int)$data['do_not_reinit_monthly']) { $do_not_reinit_monthly = 1; $datetime_for_limited = date('Y-m-d H:i:s'); } $budgets = $this->getAdvertBudget($employee_id); $amount = (double)$budgets['amount']; $total = (double)$data['total']; $balance = $total - (double)$budgets['amount']; $personal = $data['personal']; $services_summary = array_sum(array_map('doubleval', [$avito, $cian, $yandex, $domclick, $jcat/*, $zipal*/])); $allUnlimited = $domclick_unlimited == 1 && $jcat_unlimited == 1 && $yandex_unlimited == 1 && $cian_unlimited == 1 && $avito_unlimited == 1; if ($personal == '') { $error = "Не указан Личный рекламный бюджет."; $this->errors[] = $error; } else { $user = new \User; $user->get($employee_id); $personal = (double)$personal; if (($user->agent == 1 && $user->manager == 0) || $user->manager == 0) $total = $personal; if ($personal > $total) { //$limit_summ = round(($total * 1.5) - $total); //$new_limit_summ = $total * 1.5; $new_limit_summ = round(($personal - $total) + $total); $limit_summ = $personal - $total; $error = "Личный рекламный бюджет не должен превышать Общий.
Рекомендуем увеличить Общий рекламный бюджет "; $error .= 'на '; $error .= $limit_summ; $this->errors[] = $error . " руб."; } else if ($total < $services_summary) { $limit_summ = round(abs($total - $services_summary)); $new_limit_summ = $total + $limit_summ; if (($user->agent == 1 && $user->manager == 0) || $user->manager == 0) { $error = "Сумма лимитов по площадкам размещения превышает Личный рекламный бюджет.
Рекомендуем увеличить его "; $error .= 'на '; $error .= $limit_summ; $this->errors[] = $error . " руб."; } else { $error = "Сумма лимитов по площадкам размещения превышает Общий рекламный бюджет.
Рекомендуем увеличить его "; $error .= 'на '; $error .= $limit_summ; $this->errors[] = $error . " руб."; } } else if ($total > 0 && $services_summary == 0 && !$allUnlimited) { $limit_summ = round($total/$services_count); $error = "Не указаны лимиты по площадкам. Распределить бюджет пропорционально "; $error .= 'по '; $error .= $limit_summ; $this->errors[] = $error . " руб. на каждую из площадок?"; } else { // Если менеджер пользователя руковод агентства - не проверяем на превышение бюджета, т.к. у руковода его нет (безлим.) if ($user->id_manager !== $user->agencyId) { $manager_budgets = $this->getAdvertBudget($user->id_manager); $budget_total = $manager_budgets['total']; if ($total > $budget_total) { $limit_summ = round(abs((double)$budget_total - $total)); $new_limit_summ = abs($limit_summ - (double)$budget_total - $limit_summ); $error = "Рекламный бюджет превышает Общий рекламный бюджет вышестоящего менеджера/руководителя.
Рекомендуем уменьшить его "; $error .= 'на '; $error .= $limit_summ; $this->errors[] = $error . " руб."; } else if ($personal > $budget_total) { $limit_summ = round(abs((double)$budget_total - $personal)); $new_limit_summ = abs($limit_summ - (double)$budget_total - $limit_summ); $error = "Рекламный бюджет превышает Общий рекламный бюджет вышестоящего менеджера/руководителя.
Рекомендуем уменьшить его "; $error .= 'на '; $error .= $limit_summ; $this->errors[] = $error . " руб."; } } } } if (empty($this->errors)) { $manager_total = 0; $sql2 = "SELECT id FROM `users` WHERE id_manager = $employee_id"; $query2 = $this->_db->query($sql2); if ($this->_db->num_rows($query2) > 0) { $manager_users_ids = []; while($row = $this->_db->fetch_assoc($query2)) { $manager_users_ids[] = $row['id']; } $manager_budgets = $this->getAdvertBudgets(); foreach ($manager_budgets as $manager_user_id => $budget) { if (in_array($manager_user_id, $manager_users_ids) && !is_null($budget)) { $manager_total += (double)$budget['total']; } } } if ($manager_total) { if (($personal + $manager_total) > $total) { $limit_summ = round(($personal + $manager_total) - $total); $new_limit_summ = ($limit_summ + $total); $error = "Суммарный рекламный бюджет подчиненных сотрудников превышает Общий бюджет.
Рекомендуем увеличить Общий рекламный бюджет "; $error .= 'на '; $error .= $limit_summ; $this->errors[] = $error . " руб."; } } /*if ($avito_max) { if ($avito_max > $avito) { $error = "Лимит размещения по площадке Авито не должен превышать.
Рекомендуем увеличить Общий рекламный бюджет "; $error .= 'на '; $error .= $limit_summ; $this->errors[] = $error . " руб."; } }*/ $query = $this->_db->query($sql); if ($this->_db->num_rows($query) > 0) { $fields = [ "`avito` = '" . $avito . "'", "`avito_unlimited` = '" . $avito_unlimited . "'", "`cian` = '" . $cian . "'", "`cian_unlimited` = '" . $cian_unlimited . "'", "`yandex` = '" . $yandex . "'", "`yandex_unlimited` = '" . $yandex_unlimited . "'", "`domclick` = '" . $domclick . "'", "`domclick_unlimited` = '" . $domclick_unlimited . "'", "`jcat` = '" . $jcat . "'", "`jcat_unlimited` = '" . $jcat_unlimited . "'", //"`zipal` = '" . $zipal . "'", "`personal` = '" . $personal . "'", "`total` = '" . $total . "'", "`do_not_reinit_monthly` = '" . $do_not_reinit_monthly . "'", ]; $fields['user_id'] = "`user_id` = '" . (int)$employee_id . "'"; $fields[] = "`updated_at` = '" . date('Y-m-d H:i:s') . "'"; $fields[] = "`updated_by` = '" . (int)$this->_user->id . "'"; if ($datetime_for_limited != null) { $fields[] = "`datetime_for_limited` = '" . $datetime_for_limited . "'"; } else { $fields[] = "`datetime_for_limited` = NULL"; } $sql = "UPDATE `ads_budgets` SET " . implode(',', $fields); if ($this->_agency_id) $sql .= " WHERE `agency_id`='{$this->_agency_id}' AND `user_id`='{$employee_id}'"; else $sql .= " WHERE `user_id`='{$employee_id}'"; } else { $fields = [ '`avito`' => "'" . $avito . "'", '`avito_unlimited`' => "'" . $avito_unlimited . "'", '`cian`' => "'" . $cian . "'", '`cian_unlimited`' => "'" . $cian_unlimited . "'", '`yandex`' => "'" . $yandex . "'", '`yandex_unlimited`' => "'" . $yandex_unlimited . "'", '`domclick`' => "'" . $domclick . "'", '`domclick_unlimited`' => "'" . $domclick_unlimited . "'", '`jcat`' => "'" . $jcat . "'", '`jcat_unlimited`' => "'" . $jcat_unlimited . "'", //'`zipal`' => "'" . $zipal . "'", '`personal`' => "'" . $personal . "'", '`total`' => "'" . $total . "'", '`do_not_reinit_monthly`' => "'" . $do_not_reinit_monthly . "'", ]; if ($this->_agency_id) $fields['agency_id'] = (int)$this->_agency_id; $fields['user_id'] = "'" . (int)$employee_id . "'"; $fields['created_at'] = "'" . date('Y-m-d H:i:s') . "'"; $fields['created_by'] = "'" . (int)$this->_user->id . "'"; if ($datetime_for_limited != null) { $fields['datetime_for_limited'] = "'" . $datetime_for_limited . "'"; } else { $fields['datetime_for_limited'] = "NULL"; } $amount = 0; $balance = $total; $sql = "INSERT `ads_budgets` (" . implode(',', array_keys($fields)) . ") VALUES(" . implode(',', array_values($fields)) . ")"; } if (!$this->_db->query($sql, true)) { $this->errors[] = $this->_db->errorInfo(); } } } if (empty($this->errors)) { return [ 'success' => true, 'total' => $total, 'personal' => $personal, 'amount' => $amount, 'balance' => $balance, ]; } else { return [ 'success' => false, 'errors' => $this->errors, ]; } } } ?>