$date, 'UF_STATUS' => [3, 8]], 'order' => ['UF_DATE' => 'DESC']])->fetch();
if ($row) {
$rec = static::GetRecordRow($row, 0, []);
$p['control'] = static::GetControlRef($rec['id'], $rec['control_list']);
$p['report'] = static::GetReportRef($rec['id'], $rec['status_id']);
$p['executor'] = $rec['engineer'];
$p['date'] = $rec['date'];
$p['rec'] = $rec;
}
return $p;
}
static public function GetRecord($id, $andObject = 0, $editIds = [])
{
$class = static::GetClass();
$res = [];
$row = $class::getList(['select' => ['*'], 'filter' => ['ID' => $id]])->fetch();
return static::GetRecordRow($row, $andObject, $editIds);
}
public static function GetRecordsFilter($status = 0, $dateFrom = 0, $dateTo = 0, $clientId = 0, $nodeId = 0, $record_id = 0, $isView = 0, $engeneer_id = 0)
{
$fil = [];
if ($record_id)
$fil['ID'] = $record_id;
if ($clientId)
$fil['UF_USER_ID'] = $clientId;
if ($nodeId)
$fil['UF_NODE_ID'] = $nodeId;
// if($q || $nodeId)
// $fil[] = array(
// 'LOGIC' => 'OR',
// 'UF_NODE_ID' => $nodeId,
// 'UF_NODE_ID' => $q
// ) ;
if ($status)
$fil['UF_STATUS'] = $status;
if ($dateFrom)
$fil['>=UF_DATE'] = ConvertTimeStamp($dateFrom + 2 * 60 * 60, 'FULL');
if ($dateTo)
$fil['<=UF_DATE'] = ConvertTimeStamp($dateTo + 2 * 60 * 60, 'FULL');
if ($isView == 1)
$fil['UF_IS_VIEW'] = '1';
else if ($isView == 2)
$fil[] = ["LOGIC" => "OR", 'UF_IS_VIEW' => null, '!UF_IS_VIEW' => 1];
if ($engeneer_id) {
$fil['UF_EXECUTOR'] = $engeneer_id;
} else if (Service::IsEngineer() && $status !== 0) {
global $USER;
// $fil['UF_EXECUTOR'] = $USER->GetId();
// $fil['UF_DOP_EXECUTORS'] = $USER->GetId();
//WSAD
// array_push($fil, array(
// 'LOGIC' => 'OR',
// 'UF_EXECUTOR' => $USER->GetId(),
// 'UF_DOP_EXECUTORS' => $USER->GetId()
// ));
} else if (Service::IsClient()) {
global $USER;
$fil['UF_USER_ID'] = $USER->GetId();
} else if (Service::IsMainEngineer() && !Service::IsAdminEngineer() && $status !== 0) {
global $USER;
$fil[] = ["LOGIC" => "OR", 'UF_USER_ID' => Service::GetEngineerUserIds($USER->GetId()), 'UF_CREATED_BY' => $USER->GetId()];
}
//if($USER->GetId() == )
//
return $fil;
}
public static function GetRecordsTotal($status = 0, $dateFrom = 0, $dateTo = 0, $clientId = 0, $nodeId = 0, $record_id = 0, $isView = 0, $q = 0, $engeneer_id = 0)
{
$class = static::GetClass();
$fil = static::GetRecordsFilter($status, $dateFrom, $dateTo, $clientId, $nodeId, $record_id, $isView, $engeneer_id);
$arSelect = array("ID", "NAME");
$arFilter = array(
"IBLOCK_ID" => 15,
"INCLUDE_SUBSECTIONS" => "Y",
array(
'NAME' => $q
),
);
$nodeIds = [];
$res = CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect);
while ($ob = $res->GetNextElement()) {
$arFields = $ob->GetFields();
array_push($nodeIds, $arFields['ID']);
}
$filter = array(
"NAME" => $q,
);
$usersIds = [];
$rsUsers = CUser::GetList(($by = "NAME"), ($order = "desc"), $filter);
while ($arUser = $rsUsers->Fetch()) {
$usersIds[] = $arUser["ID"];
}
if ($q)
$fil[] =
array(
'LOGIC' => "OR",
'ID' => str_replace('%', '', $q),
'user.WORK_COMPANY' => $q,
'UF_CLIENT_NAME' => $q,
// 'engineer.NAME' => $q,
'UF_NODE_ID' => $nodeIds,
// 'user.LAST_NAME' => $q,
'UF_EXECUTOR' => $usersIds,
"user.UF_ENGINEER" => $usersIds,
'UF_CREATED_BY' => $usersIds,
array(
'LOGIC' => 'AND',
'>=UF_DATE' => ConvertTimeStamp(strtotime(str_replace('%', '', $q)) + 0 * 60 * 60, 'FULL'),
'<=UF_DATE' => ConvertTimeStamp(strtotime(str_replace('%', '', $q)) + 0 * 60 * 60 + 24 * 60 * 60, 'FULL')
)
);
$row = $class::getList(['select' => ['CNT'], 'filter' => $fil, 'runtime' => array(
new \Bitrix\Main\Entity\ExpressionField('CNT', 'COUNT(*)'),
new \Bitrix\Main\Entity\ReferenceField('user', \Bitrix\Main\UserTable::class, \Bitrix\Main\Entity\Query\Join::on('this.UF_USER_ID', 'ref.ID')),
new \Bitrix\Main\Entity\ReferenceField('engineer', \Bitrix\Main\UserTable::class, \Bitrix\Main\Entity\Query\Join::on('this.UF_EXECUTOR', 'ref.ID')),
new \Bitrix\Main\Entity\ExpressionField('e1', "(CASE WHEN %s IS NULL then 1 ELSE 0 END)", 'user.WORK_COMPANY'),
)])->fetch();
return ($row ? $row['CNT'] : 0);
}
public static function GetRecordsTotalWithMarks($status = 0, $dateFrom = 0, $dateTo = 0, $clientId = 0, $nodeId = 0, $record_id = 0, $isView = 0)
{
$class = static::GetClass();
$fil = static::GetRecordsFilter($status, $dateFrom, $dateTo, $clientId, $nodeId, $record_id, $isView);
$fil['UF_REMARKS_MAIN'] = 1;
$row = $class::getList(['select' => ['CNT'], 'filter' => $fil, 'runtime' => array(new \Bitrix\Main\Entity\ExpressionField('CNT', 'COUNT(*)'))])->fetch();
return ($row ? $row['CNT'] : 0);
}
public static function GetRecordsTotalMove($status = 0, $dateFrom = 0, $dateTo = 0, $clientId = 0, $move = 0)
{
$class = static::GetClass();
if ($clientId)
$fil['UF_USER_ID'] = $clientId;
if ($status)
$fil['UF_STATUS'] = $status;
if ($dateFrom)
$fil['>=UF_DATE'] = ConvertTimeStamp($dateFrom + 2 * 60 * 60, 'FULL');
if ($dateTo)
$fil['<=UF_DATE'] = ConvertTimeStamp($dateTo + 2 * 60 * 60, 'FULL');
$fil['=UF_TROUBLE'] = $move;
$row = $class::getList(['select' => ['CNT'], 'filter' => $fil, 'runtime' => array(new \Bitrix\Main\Entity\ExpressionField('CNT', 'COUNT(*)'))])->fetch();
return ($row ? $row['CNT'] : 0);
}
public static function GetRecords(&$total, $sort = 'UF_DATE', $order = 'desc', $status = 0, $dateFrom = 0, $dateTo = 0, $pageNum = 0, $count = 10, $clientId = 0, $nodeId = 0, $record_id = 0, $isView = 0, $editIds = [], $q = 0, $engeneer_id = 0)
{
$class = static::GetClass();
$fil = static::GetRecordsFilter($status, $dateFrom, $dateTo, $clientId, $nodeId, $record_id, $isView, $engeneer_id);
$total = static::GetRecordsTotal($status, $dateFrom, $dateTo, $clientId, $nodeId, $record_id, $isView, $q, $engeneer_id);
if ($sort == 'UF_USER_ID')
$sort = ['e1' => $order, 'user.WORK_COMPANY' => $order, 'UF_CLIENT_NAME' => $order];
else if ($sort == 'UF_EXECUTOR')
$sort = ['engineer.NAME' => $order, 'UF_CLIENT_NAME' => $order];
else
$sort = [$sort => $order];
$arSelect = array("ID", "NAME");
$arFilter = array(
"IBLOCK_ID" => 15,
"INCLUDE_SUBSECTIONS" => "Y",
array(
'NAME' => $q
),
);
$nodeIds = [];
$res = CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect);
while ($ob = $res->GetNextElement()) {
$arFields = $ob->GetFields();
array_push($nodeIds, $arFields['ID']);
}
$filter = array(
"NAME" => $q,
);
$usersIds = [];
$rsUsers = CUser::GetList(($by = "NAME"), ($order = "desc"), $filter);
while ($arUser = $rsUsers->Fetch()) {
$usersIds[] = $arUser["ID"];
}
if ($q)
$fil[] =
array(
'LOGIC' => "OR",
'ID' => str_replace('%', '', $q),
'user.WORK_COMPANY' => $q,
'UF_CLIENT_NAME' => $q,
// 'engineer.NAME' => $q,
'UF_NODE_ID' => $nodeIds,
// 'user.LAST_NAME' => $q,
'UF_DURATION' => $q,
'UF_ADDRESS' => $q,
'UF_CONTACT' => $q,
'UF_PRICE' => $q,
'UF_COMMENT_MAIN' => $q,
'UF_COMMENT_CLIENT' => $q,
'UF_EQUIPMENT' => $q,
'UF_REASON' => $q,
'UF_COMMENT' => $q,
'UF_RECOM' => $q,
'UF_REPAIR_PARTS' => $q,
'UF_EXECUTOR' => $usersIds,
"user.UF_ENGINEER" => $usersIds,
'UF_CREATED_BY' => $usersIds,
array(
'LOGIC' => 'AND',
'>=UF_DATE' => ConvertTimeStamp(strtotime(str_replace('%', '', $q)) + 0 * 60 * 60, 'FULL'),
'<=UF_DATE' => ConvertTimeStamp(strtotime(str_replace('%', '', $q)) + 0 * 60 * 60 + 24 * 60 * 60, 'FULL')
)
);
// \Bitrix\Main\Application::getInstance()->getConnectionPool()->getConnection()->startTracker(true);
$rows = $class::getList([
'select' => ['*', 'user.WORK_COMPANY', 'user.LAST_NAME', 'user.NAME'], 'filter' => $fil, 'order' => $sort, 'offset' => $pageNum * $count, 'limit' => $count,
'runtime' =>
[
new \Bitrix\Main\Entity\ReferenceField('user', \Bitrix\Main\UserTable::class, \Bitrix\Main\Entity\Query\Join::on('this.UF_USER_ID', 'ref.ID')),
new \Bitrix\Main\Entity\ReferenceField('engineer', \Bitrix\Main\UserTable::class, \Bitrix\Main\Entity\Query\Join::on('this.UF_EXECUTOR', 'ref.ID')),
new \Bitrix\Main\Entity\ExpressionField('e1', "(CASE WHEN %s IS NULL then 1 ELSE 0 END)", 'user.WORK_COMPANY'),
]
]);
// echo $rows->getTrackerQuery()->getSql();
$rs = [];
while ($row = $rows->fetch()) {
$rs[] = static::GetRecordRow($row, 0, $editIds);
}
return $rs;
}
public static function GetRecordsWithMarks(&$total, $sort = 'UF_DATE', $order = 'desc', $status = 0, $dateFrom = 0, $dateTo = 0, $pageNum = 0, $count = 10, $clientId = 0, $nodeId = 0, $record_id = 0, $isView = 0, $editIds = [], $q = 0)
{
$class = static::GetClass();
$fil = static::GetRecordsFilter($status, $dateFrom, $dateTo, $clientId, $nodeId, $record_id, $isView);
$total = static::GetRecordsTotalWithMarks($status, $dateFrom, $dateTo, $clientId, $nodeId, $record_id, $isView);
if ($sort == 'UF_USER_ID')
$sort = ['e1' => $order, 'user.WORK_COMPANY' => $order, 'UF_CLIENT_NAME' => $order];
else if ($sort == 'UF_EXECUTOR')
$sort = ['engineer.NAME' => $order, 'UF_CLIENT_NAME' => $order];
else
$sort = [$sort => $order];
$fil['UF_REMARKS_MAIN'] = 1;
$arSelect = array("ID", "NAME");
$arFilter = array(
"IBLOCK_ID" => 15,
"INCLUDE_SUBSECTIONS" => "Y",
array(
'NAME' => $q
),
);
$nodeIds = [];
$res = CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect);
while ($ob = $res->GetNextElement()) {
$arFields = $ob->GetFields();
array_push($nodeIds, $arFields['ID']);
}
$filter = array(
"NAME" => $q,
);
$usersIds = [];
$rsUsers = CUser::GetList(($by = "NAME"), ($order = "desc"), $filter);
while ($arUser = $rsUsers->Fetch()) {
$usersIds[] = $arUser["ID"];
}
if ($q)
$fil[] =
array(
'LOGIC' => "OR",
'ID' => str_replace('%', '', $q),
'user.WORK_COMPANY' => $q,
'UF_CLIENT_NAME' => $q,
// 'engineer.NAME' => $q,
'UF_NODE_ID' => $nodeIds,
// 'user.LAST_NAME' => $q,
'UF_EXECUTOR' => $usersIds,
"user.UF_ENGINEER" => $usersIds,
'UF_CREATED_BY' => $usersIds
);
// \Bitrix\Main\Application::getInstance()->getConnectionPool()->getConnection()->startTracker(true);
$rows_marks = $class::getList([
'select' => ['*', 'user.WORK_COMPANY', 'user.LAST_NAME', 'user.NAME'], 'filter' => $fil, 'order' => $sort, 'offset' => $pageNum * $count, 'limit' => $count,
'runtime' =>
[
new \Bitrix\Main\Entity\ReferenceField('user', \Bitrix\Main\UserTable::class, \Bitrix\Main\Entity\Query\Join::on('this.UF_USER_ID', 'ref.ID')),
new \Bitrix\Main\Entity\ReferenceField('engineer', \Bitrix\Main\UserTable::class, \Bitrix\Main\Entity\Query\Join::on('this.UF_EXECUTOR', 'ref.ID')),
new \Bitrix\Main\Entity\ExpressionField('e1', "(CASE WHEN %s IS NULL then 1 ELSE 0 END)", 'user.WORK_COMPANY'),
]
]);
// echo $rows_marks->getTrackerQuery()->getSql();
$rs_marks = [];
while ($row_marks = $rows_marks->fetch())
$rs_marks[] = static::GetRecordRow($row_marks, 0, $editIds);
return $rs_marks;
}
public static function SaveEngi($user_id, $status_id, $comment, $isReorder = 1)
{
$user = new CUser;
$fields =
[
"UF_STATUS" => $status_id,
"ADMIN_NOTES" => $comment,
];
$user->Update($user_id, $fields);
if (!$isReorder)
return;
$users = []; //все, у кого основной инженер отсутствует
$ids = [null]; //все, у кого инженер отсутствует или не определен
$eds = [];
$engis = Service::GetMainEngineerList();
foreach ($engis as $engi) {
if (in_array(8, $engi['roles']))
continue;
if ($engi['status'] != 10) //9 - отсутствует, 10 - работает
$ids[] = $engi['id'];
else
$eds[] = $engi['id'];
}
$cnt = count($eds);
if (!$cnt)
return;
$res = [];
if ($status_id == 9) //отсутствует
{
$rows = CUser::GetList(($by = array("id" => "asc")), ($order = 'asc'), ["ACTIVE" => "Y", "GROUPS_ID" => array(5), 'UF_ENGINEER' => $ids], ['SELECT' => array('*', "UF_*")]);
while ($row = $rows->fetch())
$users[] = $row['ID'];
$n = 0;
foreach ($users as $user_id) {
$user = new CUser;
$user->Update($user_id, ['UF_RESERVE_ENGINEER' => $eds[$n]]);
echo ' engi: ' . $user_id . '=>' . $eds[$n] . ' ';
++$n;
if ($n == $cnt)
$n = 0;
}
} else if ($status_id == 10) //работает
{
$rows = CUser::GetList(($by = array("id" => "asc")), ($order = 'asc'), ["ACTIVE" => "Y", "GROUPS_ID" => array(5), 'UF_ENGINEER' => $user_id], ['SELECT' => array('*', "UF_*")]);
while ($row = $rows->fetch())
$users[] = $row['ID'];
foreach ($users as $user_id)
$user->Update($user_id, ['UF_RESERVE_ENGINEER' => null]);
}
return $users;
}
public static function Delete($id)
{
$class = static::GetClass();
$prev = $class::getList(['select' => ['*'], 'filter' => ['ID' => $id]])->fetch();
$result = $class::delete($id);
if ($result->isSuccess())
HistoryLog::Add($id, HistoryLog::TYPE_DELETE_RECORD, null, $prev);
return $result->isSuccess();
}
public static function GetLastService($nodeId, $engineerId = 0)
{
$class = static::GetClass();
$fil = ['UF_NODE_ID' => $nodeId, 'UF_STATUS' => [3, 8]];
if ($engineerId)
$fil['UF_EXECUTOR'] = $engineerId;
$row = $class::getList(['select' => ['*'], 'order' => ['UF_DATE' => 'DESC'], 'filter' => $fil, 'limit' => 1])->fetch();
$t = (int)MakeTimeStamp($row['UF_DATE']);
if ($t) {
$time = ConvertTimeStamp($t, 'DD.MM.YYYY');
return ($t < time()) ? $time : '' . $time . '';
}
return '-';
}
public static function GetLastServiceId($nodeId, $engineerId = 0)
{
$class = static::GetClass();
$fil = ['UF_NODE_ID' => $nodeId, 'UF_STATUS' => [3, 8]];
if ($engineerId)
$fil['UF_EXECUTOR'] = $engineerId;
$row = $class::getList(['select' => ['*'], 'order' => ['UF_DATE' => 'DESC'], 'filter' => $fil, 'limit' => 1])->fetch();
return $row['ID'];
}
public static function GetNearService($nodeId, $engineerId = 0)
{
$class = static::GetClass();
$fil = ['UF_NODE_ID' => $nodeId, 'UF_STATUS' => [1, 4, 2]];
if ($engineerId)
$fil['UF_EXECUTOR'] = $engineerId;
$row = $class::getList(['select' => ['*'], 'order' => ['UF_DATE' => 'ASC'], 'filter' => $fil, 'limit' => 1])->fetch();
$t = (int)MakeTimeStamp($row['UF_DATE']);
if ($t) {
$time = ConvertTimeStamp($t, 'DD.MM.YYYY');
return ($t > time()) ? $time : '' . $time . '';
}
return '-';
}
public static function GetNearServiceId($nodeId, $engineerId = 0)
{
$class = static::GetClass();
$fil = ['UF_NODE_ID' => $nodeId, 'UF_STATUS' => [1, 4, 2]];
if ($engineerId)
$fil['UF_EXECUTOR'] = $engineerId;
$row = $class::getList(['select' => ['*'], 'order' => ['UF_DATE' => 'ASC'], 'filter' => $fil, 'limit' => 1])->fetch();
return $row["ID"];
}
public static function GetNearClientService($userId, $engineerId = 0)
{
$class = static::GetClass();
$fil = ['UF_USER_ID' => $userId, 'UF_STATUS' => [1, 2, 4]];
if ($engineerId)
$fil['UF_EXECUTOR'] = $engineerId;
$row = $class::getList(['select' => ['*'], 'order' => ['UF_DATE' => 'ASC'], 'filter' => $fil, 'limit' => 1])->fetch();
$t = (int)MakeTimeStamp($row['UF_DATE']);
if ($t) {
$time = ConvertTimeStamp($t, 'DD.MM.YYYY');
return ($t > time()) ? $time : '' . $time . '';
}
return '-';
}
public static function GetHistory($nodeId, $dateFrom = 0, $dateTo = 0, $count = 0)
{
$class = static::GetClass();
$fil = ['UF_NODE_ID' => $nodeId];
if ($dateFrom)
$fil['>=UF_DATE'] = ConvertTimeStamp($dateFrom, 'FULL');
if ($dateTo)
$fil['<=UF_DATE'] = ConvertTimeStamp($dateTo, 'FULL');
$fil['UF_STATUS'] = array(3, 8);
$rows = $class::getList(['select' => ['*'], 'order' => ['UF_DATE' => 'DESC'], 'filter' => $fil, 'limit' => $count]);
$rs = [];
while ($row = $rows->fetch())
$rs[] = static::GetRecordRow($row);
return $rs;
}
public static function StatusRecord($id, $data)
{
$class = static::GetClass();
if (count($data)) {
$result = $class::update($id, $data);
if ($result->isSuccess())
return $result->getId();
return 0;
}
return $id;
}
public static function StatusRecordClient($id, $status_id, $is_marks, $commentClient = null)
{
$class = static::GetClass();
$data = [];
if ($status_id == 2 || $status_id == 8) //если в работе или завершить
$data['UF_STATUS'] = $status_id;
if (!$status_id || $is_marks) //если не согласовано или есть замечания
$data['UF_REMARKS_CLIENT'] = 1;
else
$data['UF_REMARKS_CLIENT'] = 0;
if ($commentClient !== null)
$data['UF_COMMENT_CLIENT'] = $commentClient;
// AddMessage2Log("StatusRecordClient" . $data['UF_REMARKS_CLIENT']);
if (count($data)) {
$result = $class::update($id, $data);
if ($result->isSuccess()) {
if ($data['UF_REMARKS_CLIENT']) {
$prop = [];
$p = Register::GetRecord($id, true);
if ($p) {
$prop = [];
$prop['ID'] = $id;
$prop['CLIENT'] = $p['client_fullname'] . ' ' . ($p['client_phone'] ? $p['client_phone'] : '') . ' ' . ($p['client_email'] ? $p['client_email'] : '');
$prop['OBJECT'] = $p['object'] ? ($p['object']['name'] . ($p['object']['address'] ? (' (адрес: ' . $p['object']['address'] . ')') : '')) : '';
$prop['DATE'] = $p['date'];
$prop['COMMENT'] = $p['comment_client'];
$prop['ENGINEER_EMAIL'] = $p['main_engi'] ? $p['main_engi']['email'] : '';
if ($prop['ENGINEER_EMAIL'])
$res = CEvent::SendImmediate('SERVICE_COMMENT', 's1', $prop);
}
}
return $result->getId();
}
return 0;
}
return $id;
}
public static function ViewRecord($id, $isViewed)
{
$class = static::GetClass();
$result = $class::update($id, ['UF_IS_VIEW' => (int)$isViewed]);
if ($result->isSuccess())
return $result->getId();
return 0;
}
public static function GetPhotos($id, $userType = 0)
{
$field = 'UF_PHOTOS';
if ($userType == 1)
$field = 'UF_CLIENT_PHOTOS';
if ($userType == 2)
$field = 'UF_REPORT_PHOTOS';
if ($userType == 4)
$field = 'UF_BILL_FILE';
$res = [];
$class = static::GetClass();
$row = $class::getList(['select' => [$field], 'filter' => ['ID' => $id]])->fetch();
if ($row[$field])
foreach ($row[$field] as $img) {
$f = CFile::GetFileArray($img);
if ($f)
$res[] = $f;
}
return $res;
}
public static function AddFile($name, $client_id, $file_id)
{
global $USER;
$el = new CIBlockElement;
$userId = $USER ? $USER->GetID() : null;
if ($client_id) {
$props =
[
1123 => $file_id,
1124 => $client_id,
];
$info = array(
"MODIFIED_BY" => $userId,
"IBLOCK_SECTION_ID" => false,
"IBLOCK_ID" => 19,
"NAME" => $name,
"ACTIVE" => "Y",
"PROPERTY_VALUES" => $props,
);
if ($ordId = $el->Add($info))
return ['id' => serialize($ordId), 'error' => ''];
} else if (Service::IsAdminEngineer()) {
$props = [1118 => $file_id];
$info = array(
"MODIFIED_BY" => $userId,
"IBLOCK_SECTION_ID" => false,
"IBLOCK_ID" => 18,
"NAME" => $name,
"ACTIVE" => "Y",
"PROPERTY_VALUES" => $props,
);
if ($ordId = $el->Add($info))
return ['id' => serialize($ordId), 'error' => ''];
}
return ['id' => 0, 'error' => $el->LAST_ERROR];
}
public static function GetFileCount($client_id)
{
return CIBlockElement::GetList(["SORT" => "ASC"], ["IBLOCK_ID" => 19, "ACTIVE" => "Y", "GLOBAL_ACTIVE" => "Y", 'PROPERTY_CLIENT' => $client_id], false, false)->SelectedRowsCount();
}
public static function AddPhoto($id, $file, $userType = 0) //0 - фото инженера, 1 - фото клиента, 2, 3 - скан отчета
{
$field = 'UF_PHOTOS';
if ($userType == 1)
$field = 'UF_CLIENT_PHOTOS';
if ($userType == 2 || $userType == 3)
$field = 'UF_REPORT_PHOTOS';
if ($userType == 4)
$field = 'UF_BILL_FILE';
$class = static::GetClass();
$row = $class::getList(['select' => [$field, 'UF_NODE_ID', 'UF_USER_ID'], 'filter' => ['ID' => $id]])->fetch();
$dat = [];
if ($row[$field])
foreach ($row[$field] as $p) {
$f = CFile::GetFileArray($p);
$f["old_id"] = $p;
$f['error'] = 1;
$dat[$field][] = $f;
}
$dat[$field][] = $file;
$result = $class::update($id, $dat);
$equip = Service::GetEquip($row['UF_NODE_ID']);
$dat = [];
if ($equip['PHOTOS']['VALUE'])
foreach ($equip['PHOTOS']['VALUE'] as $p) {
$f = CFile::GetFileArray($p);
$f["old_id"] = $p;
$f['error'] = 1;
$dat['PHOTOS'][] = $f;
}
$dat['PHOTOS'][] = $file;
CIBlockElement::SetPropertyValueCode($equip['ID'], "PHOTOS", array("VALUE" => $file));
$arSelect = array("ID", "NAME");
$arFilter = array("IBLOCK_ID" => 22, 'ID' => $row['UF_USER_ID'], "ACTIVE" => "Y");
$res = CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect);
if ($ob = $res->GetNextElement()) {
$arFields = $ob->GetFields();
CIBlockElement::SetPropertyValueCode($arFields['ID'], "PHOTOS", array("VALUE" => $file));
}
if ($result->isSuccess())
return $result->getId();
return 0;
}
public static function RemovePhoto($id, $photo_id, $userType = 0)
{
$field = 'UF_PHOTOS';
if ($userType == 1)
$field = 'UF_CLIENT_PHOTOS';
if ($userType == 2)
$field = 'UF_REPORT_PHOTOS';
if ($userType == 4)
$field = 'UF_BILL_FILE';
$class = static::GetClass();
$row = $class::getList(['select' => [$field, 'UF_NODE_ID'], 'filter' => ['ID' => $id]])->fetch();
$dat = [];
$dat[$field] = [];
if ($row[$field])
foreach ($row[$field] as $p) {
if ($p != $photo_id) {
$f = CFile::GetFileArray($p);
$f["old_id"] = $p;
$f['error'] = 1;
$dat[$field][] = $f;
}
}
$result = $class::update($id, $dat);
if ($result->isSuccess())
return $result->getId();
return 0;
}
public static function GetParent($record_id)
{
$class = static::GetClass();
$row = $class::getList(['select' => ['ID', 'UF_PARENT'], 'filter' => ['ID' => $record_id]])->fetch();
if ($row)
return $row['UF_PARENT'];
return null;
}
public static function GetChilds($parent_id, $num)
{
if ($num > 1000) //максимальная длина цепочки
return [];
$childs = [];
$class = static::GetClass();
$rows = $class::getList(['select' => ['*'], 'filter' => ['UF_PARENT' => $parent_id]]);
while ($row = $rows->fetch()) {
$p = static::GetRecordRow($row);
$p['childs'] = static::GetChilds($p['id'], $num + 1);
$childs[] = $p;
}
return $childs;
}
public static function GetLinks($record_id)
{
$root_id = $record_id;
$par_id = $root_id;
$i = 0;
while ($par_id && $i < 32) //максимальная вложенность
{
$root_id = $par_id;
$par_id = Register::GetParent($par_id);
++$i;
}
$root = Register::GetRecord($root_id);
if ($root)
$root['childs'] = Register::GetChilds($root_id, 0);
return $root;
}
public static function HasChilds($parent_id)
{
$class = static::GetClass();
$rows = $class::getList(['select' => ['*'], 'filter' => ['UF_PARENT' => $parent_id]]);
while ($row = $rows->fetch())
return 1;
return 0;
}
public static function GetNotViewCount()
{
global $USER;
$fil = [];
if (Service::IsClient())
$fil['UF_USER_ID'] = $USER->GetId();
$fil[] = ["LOGIC" => "OR", 'UF_IS_VIEW' => null, '!UF_IS_VIEW' => 1];
$class = static::GetClass();
$row = $class::getList(['select' => ['CNT'], 'filter' => $fil, 'runtime' => array(new \Bitrix\Main\Entity\ExpressionField('CNT', 'COUNT(*)'))])->fetch();
return $row ? $row['CNT'] : 0;
}
static public function SendEmail($id)
{
$res = [];
$p = Register::GetRecord($id, 1);
if (!$p)
return;
$prop = [];
$prop['CLIENT_EMAIL'] = null;
$prop['CLIENT_PHONE'] = null;
if (!$p['client_id']) {
$prop['CLIENT_NAME'] = $p['client_name'];
if (filter_var($p['contact'], FILTER_VALIDATE_EMAIL))
$prop['CLIENT_EMAIL'] = $p['contact'];
else {
$phone = preg_replace("/[^0-9]/", '', $p['contact']);
if (mb_strlen($phone) == 10)
$prop['CLIENT_PHONE'] = '7' . $phone;
else if (mb_strlen($phone) == 11) {
$phone = mb_substr($phone, 1);
$prop['CLIENT_PHONE'] = '7' . $phone;
}
echo $phone;
}
} else {
$prop['CLIENT_NAME'] = $p['client_fullname'];
$prop['CLIENT_EMAIL'] = $p['client_email'];
// echo '';
if ($p['sendsms'])
$prop['CLIENT_PHONE'] = $p['client_phone'];
}
$prop['ID'] = $id;
if ($p['move_trouble']) {
$prop['EMAIL_TYPE'] = "Аварийный выезд";
$prop['TITLE_CSS'] = "background: rgb( 255 , 153 , 0 );display: inline-block;";
} else {
$prop['EMAIL_TYPE'] = "Согласование сервисного обслуживания";
$prop['TITLE_CSS'] = "background: transparent";
}
$prop['VISIT_DATE'] = $p['datetext'];
$prop['ADDRESS'] = ((isset($p['object']['address']) && trim($p['object']['address'])) ? ' по адресу ' . $p['object']['address'] : '');
$prop['WORK_LIST'] = $p['comment'];
$prop['SERVICE_ENGINEER'] = '';
if ($p['engidata'] && $p['engidata']['fullname'])
$prop['SERVICE_ENGINEER'] = 'Исполнителем назначен ' . $p['engineer'] . ($p['engidata']['phone'] ? (', тел.: ' . $p['engidata']['phone']) : (', ' . $p['engidata']['email']));
if ($p['engidata'])
$prop['ENGINEER_EMAIL'] = $p['engidata']['email'];
if ($prop['CLIENT_EMAIL']) {
if ($p['client_id'])
$res = CEvent::SendImmediate('SERVICE_COORDINATION', 's1', $prop);
else {
$prop['PRICE'] = $p['price'] ? ($p['price'] . ' руб.') : '';
$prop['WORKS'] = '';
//$prop['WORKS'] = 'Запланированы работы: ';
$res = CEvent::SendImmediate('SERVICE_COORDINATION_FAST', 's1', $prop);
}
}
$orderText = '';
if ($p['move_trouble'])
$orderText = 'Аварийный выезд #';
else
$orderText = 'Заявка №';
$price = $p['price'] ? (' Стоимость ' . $p['price'] . ' руб.') : '';
$engi = '';
if ($p['engidata'] && $p['engidata']['fullname'])
$engi = ' Сервисный инженер ' . $p['engineer'] . ($p['engidata']['phone'] ? (', тел. ' . $p['engidata']['phone']) : '') . '.';
if (!$p['client_id']) {
$text = $orderText . $p['id'] . ".\nНа " . $p['date'] . "г. принят заказ на обслуживание." . $engi . $price . "\nТерритория тепла\n83522604410";
} else {
$text = $orderText . $p['id'] . ".\nНа " . $p['date'] . "г. запланировано обслуживание." .
"\nАдрес:" . $p['object']['address'];
}
$smsru = new SMSRU('6B510025-43BF-2DDF-1DB1-191EB995C01D'); // Авторизация
if ($prop['CLIENT_PHONE']) {
$data = new stdClass();
$data->to = $prop['CLIENT_PHONE']; // Номер получателя
$data->text = Register::translit($text); // Текст
$data->partner_id = "354903";
$pres = $smsru->send_one($data);
}
if ($p['move_trouble']) {
$phone = preg_replace("/[^0-9]/", '', $p['engidata']['phone']);
if (mb_strlen($phone) == 10)
$prop['ENGI_PHONE'] = '7' . $phone;
else if (mb_strlen($phone) == 11) {
$phone = mb_substr($phone, 1);
$prop['ENGI_PHONE'] = '7' . $phone;
}
$text = "Аварийный выезд #" . $p['id'];
$text .= "\nКлиент: " . $p['client_name'] . $p['object']['name'];
$text .= "\nАдрес:" . $p['address'];
$text .= "\nhttps://ttepla.com/service/register.php?record_id=" . $p['id'];
$data = new stdClass();
$data->to = $p['main_engi']['tel']; // Номер получателя
$data->text = Register::translit($text); // Текст
$data->partner_id = "354903";
$pres = $smsru->send_one($data);
$data = new stdClass();
$data->to = $prop['ENGI_PHONE']; // Номер получателя
$data->text = Register::translit($text); // Текст
$data->partner_id = "354903";
$pres = $smsru->send_one($data);
foreach ($p['dop_engineer'] as $de) {
$phone = Service::GetUserInfo($de)['phone'];
$data = new stdClass();
$data->to = $phone; // Номер получателя
$data->text = Register::translit($text); // Текст
$data->partner_id = "354903";
$pres = $smsru->send_one($data);
}
}
return $res;
}
static public function SendDelayNotify($id)
{
$res = [];
$p = Register::GetRecord($id);
if (!$p)
return;
$prop = [];
$prop['ID'] = $id;
$prop['CLIENT_EMAIL'] = null;
$prop['CLIENT_PHONE'] = null;
if (!$p['client_id']) {
if (filter_var($p['contact'], FILTER_VALIDATE_EMAIL)) {
$prop['CLIENT_EMAIL'] = $p['contact'];
} else {
$phone = preg_replace("/[^0-9]/", '', $p['contact']);
if (mb_strlen($phone) == 10)
$prop['CLIENT_PHONE'] = '7' . $phone;
else if (mb_strlen($phone) == 11) {
$phone = mb_substr($phone, 1);
$prop['CLIENT_PHONE'] = '7' . $phone;
}
}
} else {
$prop['CLIENT_EMAIL'] = $p['client_email'];
$prop['CLIENT_PHONE'] = $p['client_phone'];
}
$prop['ENGINEER_EMAIL'] = $p['engidata']['email'];
CEvent::SendImmediate('PERENOS_SROKA', 's1', $prop);
$delaySMStext1 = "Мы не можем выполнить обслуживание, приносим свои извинения. www.ttepla.com 604410";
$delaySMStext2 = "Мы не можем выполнить обслуживание, приносим свои извинения. www.ttepla.com 604410";
if ($prop['CLIENT_PHONE']) {
$smsru = new SMSRU('6B510025-43BF-2DDF-1DB1-191EB995C01D'); // Авторизация
$data = new stdClass();
$data->to = $prop['CLIENT_PHONE']; // Номер получателя
$data->text = $delaySMStext1; // Текст
$data->partner_id = "354903";
$pres = $smsru->send_one($data);
}
if ($p['engidata']['phone']) {
$smsru = new SMSRU('6B510025-43BF-2DDF-1DB1-191EB995C01D'); // Авторизация
$data = new stdClass();
$data->to = $p['engidata']['phone']; // Номер получателя
$data->text = $delaySMStext2; // Текст
$data->partner_id = "354903";
$pres = $smsru->send_one($data);
}
// return $res;
}
static public function SendReportEmail($id)
{
$res = [];
$p = Register::GetRecord($id);
if (!$p)
return;
$prop = [];
$prop['ID'] = $id;
$prop['CLIENT_EMAIL'] = null;
$prop['CLIENT_PHONE'] = null;
$dop_emails = '';
if (!$p['client_id']) {
$prop['CLIENT_NAME'] = $p['client_name'];
if (filter_var($p['contact'], FILTER_VALIDATE_EMAIL))
$prop['CLIENT_EMAIL'] = $p['contact'];
else {
$phone = preg_replace("/[^0-9]/", '', $p['contact']);
if (mb_strlen($phone) == 10)
$prop['CLIENT_PHONE'] = '7' . $phone;
else if (mb_strlen($phone) == 11) {
$phone = mb_substr($phone, 1);
$prop['CLIENT_PHONE'] = '7' . $phone;
}
}
foreach ($p['dop_emails'] as $de) {
$dop_emails .= $de . ',';
}
$prop['DOP_EMAILS'] = $dop_emails;
} else {
$prop['CLIENT_NAME'] = $p['client_fullname'];
$prop['CLIENT_EMAIL'] = $p['client_email'];
$prop['CLIENT_PHONE'] = $p['client_phone'];
foreach ($p['dop_emails'] as $de) {
$dop_emails .= $de . ',';
}
$prop['DOP_EMAILS'] = $dop_emails;
}
$prop['DATE'] = $p['datetext'] . 'г. были проведены работы в котельной по адресу ' . $p['address'] . '.';
$prop['MAIN_ENGI'] = 'Ответственный инженер ' . $p['main_engi']['fullname'] . ', тел:' . $p['main_engi']['tel'];
$prop['MAIN_ENGI_PHONE'] = $p['main_engi']['tel'];
if ($p['engidata'] && $p['engidata']['fullname'])
$prop['SERVICE_ENGINEER'] = 'Исполнитель ' . $p['engineer'] . ($p['engidata']['phone'] ? (', тел.: ' . $p['engidata']['phone']) : (', ' . $p['engidata']['email']));
if ($p['engidata']) {
$prop['ENGINEER_EMAIL'] = $p['engidata']['email'];
}
if ($prop["REASON"] != "") {
$prop["REASON"] .= "Причина вызова сервисного специалиста
" . $p['reason'] . "
";
}
$prop["COMMENT"] .= "Запланированные работы к выполнению
" . $p['comment'] . "
";
$prop["RECOM"] .= "Выполненные работы и рекомендации
" . $p['recom'] . "
";
$prop["REPAIR_PARTS"] .= "Заключение
" . $p['repair_parts'] . "
";
// if($p["employeer_attention"] == true && $status == 8){
// $employeeProps = [];
// $employeeProps['ID'] = $id;
// $employeeProps["EMPLOYEER_COMMENT"] = $p["employeer_comment"];
// $employeeProps["EMPLOYEER_EMAIL"] = $p["employeer_email"];
// if(!$p['client_id']){
// $employeeProps['CLIENT_NAME'] = $p['client_name'];
// }else{
// $employeeProps['CLIENT_NAME'] = $p['client_fullname'];
// }
// $SendEmployeerReport = CEvent::SendImmediate('SEND_EMPLOYEER_REPORT', 's1', $employeeProps);
// }
$prop['REASON_SUBJECT'] = $p['comment'];
$files = array_reverse(Register::GetPhotos($id));
$photos = [];
foreach ($files as $file) {
$ext = explode('.', basename($file['SRC']));
$ext = mb_strtolower($ext[count($ext) - 1]);
$file['ext'] = $ext;
if (in_array($ext, ['jpg', 'png', 'bmp', 'jpeg', 'gif'])) {
$photos[] = '
';
}
}
$prop['PHOTO_BLOCK'] = '' . implode('
', $photos) . '
';
if ($prop['CLIENT_EMAIL']) {
if (!$p['client_id'])
$res = CEvent::SendImmediate('SERVICE_REPORT_FAST', 's1', $prop);
else
$res = CEvent::SendImmediate('SERVICE_REPORT', 's1', $prop);
}
if ($prop['CLIENT_PHONE']) {
$text = "Заявка №" . $p['id'] . ".\nОтчет об обслуживании.\nСсылка на отчет: http://ttepla.com/service/act/report.pdf?id=" . $p['id'] . "\nТерритория тепла\n83522604410";
$smsru = new SMSRU('6B510025-43BF-2DDF-1DB1-191EB995C01D'); // Авторизация
$data = new stdClass();
$data->to = $prop['CLIENT_PHONE']; // Номер получателя
$data->text = Register::translit($text); // Текст
$data->partner_id = "354903";
$pres = $smsru->send_one($data);
}
return $res;
}
static public function SendEmployeerEmail($id)
{
$prop = [];
$p = Register::GetRecord($id);
if ($p && $p["employeer_attention"] == 1 && $p['status_id'] == 8) {
$prop = [];
$prop['ID'] = $id;
$prop["EMPLOYEER_COMMENT"] = $p["employeer_comment"];
// foreach($p['employeer_email'] as $keyMail => $valMail){
// $empMails .= $keyMail . " - " . $valMail . ",";
// }
// $prop["EMPLOYEER_EMAIL"] = substr($empMails, 0, -1);
$prop["EMPLOYEER_EMAIL"] = $p["employeer_email"];
if (!$p['client_id']) {
$prop['CLIENT_NAME'] = $p['client_name'];
} else {
$prop['CLIENT_NAME'] = $p['client_fullname'];
}
// AddMessage2Log($p["employeer_email"]);
CEvent::SendImmediate('SEND_EMPLOYEER_REPORT', 's1', $prop);
}
return $res;
}
static public function SendClientRecordEmail($id)
{
$prop = [];
$p = Register::GetRecord($id, true);
if ($p) {
$prop = [];
$prop['ID'] = $id;
$prop['CLIENT'] = $p['client_fullname'] . ' ' . ($p['client_phone'] ? $p['client_phone'] : '') . ' ' . ($p['client_email'] ? $p['client_email'] : '');
$prop['OBJECT'] = $p['object'] ? ($p['object']['name'] . ($p['object']['address'] ? (' (адрес: ' . $p['object']['address'] . ')') : '')) : '';
$prop['DATE'] = $p['date'];
$prop['COMMENT'] = $p['comment_client'];
$prop['ENGINEER_EMAIL'] = $p['main_engi'] ? $p['main_engi']['email'] : '';
if ($prop['ENGINEER_EMAIL'])
$res = CEvent::SendImmediate('CLIENT_RECORD', 's1', $prop);
}
return $res;
}
static public function ChangeCheck($id, $comment_main, $comment_client, $main_check, $client_check, $status)
{
$class = static::GetClass();
$data = [];
if ($main_check)
$data['UF_REMARKS_MAIN'] = 0;
if ($client_check)
$data['UF_REMARKS_CLIENT'] = 0;
if ($comment_main !== null)
$data['UF_COMMENT_MAIN'] = $comment_main;
if ($comment_client !== null)
$data['UF_COMMENT_CLIENT'] = $comment_client;
if ($status)
$data['UF_STATUS'] = $status;
$isMail = 0;
$isDelay = 0;
$isReport = 0;
$rec = Register::GetRecord($id);
if (!$rec['key'])
$data['UF_KEY'] = Register::generateRandomString(10) . '_' . dechex(time());
if ($rec && $rec['status_id'] != 4 && $status == 4)
$isMail = 1;
if ($rec && $rec['status_id'] != 19 && $status == 19)
$isDelay = 1;
if ($rec && $rec['status_id'] != 8 && $status == 8) //если завершен
$isReport = 1;
$result = $class::update($id, $data);
if ($result->isSuccess()) {
if (!Service::IsClient())
Register::SendEmployeerEmail($result->getId());
if ($isMail && !Service::IsClient())
Register::SendEmail($result->getId());
if ($isReport && !Service::IsClient())
Register::SendReportEmail($result->getId());
if ($isDelay && !Service::IsClient())
Register::SendDelayNotify($result->getId());
return $result->getId();
}
return 0;
}
public static function GetPhotoReport($record_id)
{
$res = Register::GetPhotos($record_id, 2);
$rec = Register::GetRecord($record_id);
$res = array_reverse($res);
$photos = '';
$docs = '';
$n = 0;
foreach ($res as $r) {
$ext = explode('.', basename($r['SRC']));
$ext = mb_strtolower($ext[count($ext) - 1]);
if (in_array($ext, ['jpg', 'png', 'bmp', 'jpeg', 'gif'])) {
$photos .= '';
++$n;
} else
$docs .= ('');
}
return '
' . $docs . '
';
}
public static function GetBillFiles($record_id)
{
$res = Register::GetPhotos($record_id, 4);
$rec = Register::GetRecord($record_id);
$res = array_reverse($res);
$photos = '';
$docs = '';
$n = 0;
foreach ($res as $r) {
$ext = explode('.', basename($r['SRC']));
$ext = mb_strtolower($ext[count($ext) - 1]);
$docs .= ('');
}
return '' . $docs . '
';
}
};