<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Menu;
use App\Entity\LogHistoryRequest;
use App\Entity\User;
use App\Entity\UserToken;
use App\Entity\Notification;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Service\AppApiService;
use App\Entity\AppPersonalAccount;
use App\Entity\MediaObject;
use App\Entity\AppCounterReading;
use App\Entity\DataReception;
use App\Entity\Accounts;
use App\Entity\ServiceOrderHistory;
use Symfony\Component\HttpKernel\KernelInterface;
class NotificationController extends AbstractController
{
public $datetime;
public $entityManager;
public $passwordEncoder;
public $appApiService;
private $kernel;
public function __construct( ?\DateTimeInterface $datetime, EntityManagerInterface $entityManager, AppApiService $appApiService, KernelInterface $kernel ){
$this->datetime = $datetime;
$this->entityManager = $entityManager;
$this->appApiService = $appApiService;
$this->kernel = $kernel;
}
public function valid($requestFilds, $requiredFilds){
$errors = '';
foreach($requiredFilds as $f){
if(!isset($requestFilds[$f]))
$errors .= " $f";
}
return $errors;
}
public function logHistory($id, $method, $data){
if(!$id){
$LogHistoryRequest = new LogHistoryRequest();
$LogHistoryRequest->setMethod($method);
$LogHistoryRequest->setRequest($data);
$LogHistoryRequest->setDate(new \DateTime());
$LogHistoryRequest->setStatus('start');
$this->entityManager->persist($LogHistoryRequest);
$this->entityManager->flush();
return $LogHistoryRequest->getId();
}else{
$LogHistoryRequest = $this->entityManager->getRepository(LogHistoryRequest::class)->findOneBy(['id' => $id]);
if($LogHistoryRequest){
$LogHistoryRequest->setStatus('finish');
$LogHistoryRequest->setResponseAnswer($data);
$this->entityManager->persist($LogHistoryRequest);
$this->entityManager->flush();
}
return true;
}
}
private function customAuth($request){
$validUser = 'loe';
$validPassword = 'GE2666Mh4maRa79iMs5igRPD';
$login = $request->server->get('PHP_AUTH_USER');
$password = $request->server->get('PHP_AUTH_PW');
if ($login !== $validUser || $password !== $validPassword) {
return false;
}
return true;
}
#[Route('/api/create-notfication', name: 'create_notfication', methods: ['POST'])]
public function create_notfication(Request $request)
{
if (!$this->customAuth($request)) {
return new JsonResponse(['message' => 'Unauthorized'], 401, [
'WWW-Authenticate' => 'Basic realm="API Access"',
]);
}
$data = json_decode($request->getContent(), true);
// $logId = $this->logHistory(false, 'createPersonalAccount', $data);
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "\n\n\n" . print_r($data, true) . "\n", FILE_APPEND);
$valid = $this->valid( $data, ['user', 'title', 'body'] );
if( empty($valid) ){
$find = $this->entityManager->getRepository(User::class)->findOneBy(['id' => $data['user']]);
if($find){
$notification = new Notification();
$notification->setUsers($find);
$notification->setTitle( $data['title']);
$notification->setBody( $data['body']);
if(!empty($data['type']))
$notification->setType( $data['type']);
else
$notification->setType('text');
$notification->setDateEntered( new \DateTime() );
$notification->setStatus('new');
$this->entityManager->persist($notification);
$this->entityManager->flush();
$rez = ['rez' => true, 'id' => $notification->getId()];
// }else{
// $rez = ['registered' => false, $res];
// }
}else{
$rez = ['rez' => false, 'error' => "Користувача не знайдено"];
}
}else{
$rez = ['rez' => false, 'error' => "Не задано поля: $valid"];
}
$response = new JsonResponse();
$response->setData($rez);
return $response;
}
public function sendCurl ($data){
/**
* admin
* w2mWOf5Q0hX8UX6H9h37hZk6RzBtnIBMqEfU173VKIsOmPzgEp
*/
$json = json_encode(
[
'token' => $data['token'],
'data' => [
'title' => $data['title'],
'body' => $data['body'],
'type_text' => $data['type'],
'text' => $data['body'],
// 'text' => "",
// 'image' => ''
],
'apns' => [
'payload' => [
'aps' => [
'content-available' => 1
]
]
],
'topic' => '',
'condition' => ''
]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://dev-firebase-proxy.inneti.net/api/message/notify');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "admin:w2mWOf5Q0hX8UX6H9h37hZk6RzBtnIBMqEfU173VKIsOmPzgEp");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
$json
);
$answer = curl_exec($ch);
curl_close($ch);
return $answer;
}
#[Route('/api/send-notfication', name: 'send_notfication', methods: ['GET'])]
public function send_notfication(Request $request)
{
$send = 0;
$err = 0;
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "************************" . date('H:i:s') . "\n", FILE_APPEND);
$notifications = $this->entityManager->getRepository(Notification::class)->findBy(['status' => 'new']);
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "1111111" . date('H:i:s') . "\n", FILE_APPEND);
if($notifications){
foreach($notifications as $notification){
$send = 0;
$user = $notification->getUsers();
// $tokensArr = [];
if($user){
$tokens = $user->getUserTokens();
if(!empty($tokens) AND count($tokens) > 0){
}else{
$device_id = $user->getDeviceId();
$tokens = $this->entityManager->getRepository(UserToken::class)->findBy(['device_id' => $device_id, 'active' => true]);
}
foreach($tokens as $token){
if(!$token->isActive())
continue;
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "st - " . date('H:i:s') . "\n", FILE_APPEND);
$resultJson = $this->sendCurl([
'token' => $token->getTokenFcm(),
'title' => $notification->getTitle(),
'body' => $notification->getBody(),
'type' => $notification->getType(),
]);
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', $resultJson . "\n", FILE_APPEND);
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', " - " . date('H:i:s') . "\n", FILE_APPEND);
$notification->setDateSend( new \DateTime() );
$result = json_decode($resultJson, true);
if(!empty( $result['res'] )){
$send = 1;
$notification->setStatus('send');
$send++;
}elseif(!empty( $result['err'] )){
$send = 2;
$token->setActive(false);
$notification->setStatus('error');
$notification->setError($notification->getError() . "\n" . date('Y-m-d H:i:s') . $token->getTokenFcm() . "\n" . $resultJson);
$err++;
}else{
$send = 3;
$token->setActive(false);
$notification->setStatus('error');
$notification->setError($notification->getError() . "\n" . date('Y-m-d H:i:s') . $token->getTokenFcm() . "\n" . $resultJson);
$err++;
}
$this->entityManager->persist($token);
$this->entityManager->persist($notification);
$this->entityManager->flush();
}
}
/** Якщо ключа нема */
if($send == 0){
$notification->setStatus('not_token');
$notification->setError($notification->getError() . "\n" . date('Y-m-d H:i:s') . " Ключ не знайдено \n");
$this->entityManager->persist($notification);
$this->entityManager->flush();
}
// echo '222';
// die('1111');
}
// $this->entityManager->persist($notification);
// $this->entityManager->flush();
// $rez = ['rez' => true, 'id' => $notification->getId()];
// }else{
// $rez = ['registered' => false, $res];
// }
}else{
$rez = ['rez' => false, 'error' => "Незнайдено нових сповіщень!"];
}
$response = new JsonResponse();
$response->setData(['send' => $send, 'err' => $err]);
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "***********END*************" . date('H:i:s') . "\n", FILE_APPEND);
return $response;
}
#[Route('/api/create-notfication-actions', name: 'create_notfication_account', methods: ['POST'])]
public function create_notfication_account(Request $request)
{
if (!$this->customAuth($request)) {
return new JsonResponse(['message' => 'Unauthorized'], 401, [
'WWW-Authenticate' => 'Basic realm="API Access"',
]);
}
// { "sender": "loe", "msg-type": "from-ns", "msg-data": { "priority": 0, "ns_msg_id": 123, "title": "шапка повідомлення", "receivers": { "account1": "текст повідомлення", "account2": "текст повідомлення", "account3": "текст повідомлення" } } }
// $arr = [
// 'sender' => 'loe', // від кого прийшло (ЛОЕ, вооканал і т.д.)
// 'msg-type' => 'from-ns', // будуть інші типи з іншими наборами даних
// 'msg-data' => [
// 'priority' => 0, // пріоритет (ціле додатнє число типу tinyint)
// 'ns_msg_id' => 123, // моя ідешка (тип int)
// 'title' => 'шапка повідомлення',
// 'receivers' => [ // для даного типу повідомлення це масив, де ключ - номер особового рахунку, значення - текст повідомлення
// 'account1' => 'текст повідомлення',
// 'account2' => 'текст повідомлення',
// 'account3' => 'текст повідомлення'
// // ...
// ],
// ],
// ];
// echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// die;
$data = json_decode($request->getContent(), true);
// if(isset($data['msg-type']) AND $data['msg-type'] == 'number-phone')
// file_put_contents('/var/www/symfony_docker/public/media/notification-sms.log', date('Y-m-d H:i:s') . ' ' . $request->getContent() . "\n", FILE_APPEND);
// echo '<pre>';
// print_r($data);
// die;
// $logId = $this->logHistory(false, 'createPersonalAccount', $data);
// file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "\n\n\n" . print_r($data, true) . "\n", FILE_APPEND);
$send = [];
$err = '';
$valid = $this->valid( $data, ['sender', 'msg-data'] );
if( empty($valid) ){
$title = $data['msg-data']['title'];
if(isset($data['msg-data']['receivers']) AND count($data['msg-data']['receivers']) > 0){
if($data['msg-type'] == 'from-ns'){
$i = 0;
foreach($data['msg-data']['receivers'] as $number => $receivers){
$AccountUser = [];
/** Шукаю Всі особові за номером */
$findAccounts = $this->entityManager->getRepository(AppPersonalAccount::class)->findBy(['number' => $number]);
if($findAccounts){
foreach($findAccounts as $account){
$user_id = $account->getOwner()->getId();
if(!isset( $AccountUser[ $user_id] ))
$AccountUser[$user_id] = [];
/** Перевірка якщо в користувача додано декілька однакових особових */
if(!isset( $AccountUser[$user_id][ $number ] )){
$AccountUser[$user_id][ $number ] = true;
$notification = new Notification();
$notification->setUsers($account->getOwner());
$notification->setTitle( $title );
$notification->setBody($receivers);
if(!empty($data['msg-data']['type']))
$notification->setType( $data['msg-data']['type']);
else
$notification->setType('text');
$notification->setDateEntered( new \DateTime() );
$notification->setStatus('new');
if(!empty($data['msg-data']['priority']))
$notification->setPriority($data['msg-data']['priority']);
if(!empty($data['msg-data']['ns_msg_id']))
$notification->setNsMsgId($data['msg-data']['ns_msg_id']);
$this->entityManager->persist($notification);
// $this->entityManager->flush();
if(!isset($send[$number]))
$send[$number] = 1;
else
++$send[$number];
$i++;
}
if($i == 100){
$this->entityManager->flush();
$i = 0;
}
}
}
}
}elseif($data['msg-type'] == 'number-phone'){
$i = 0;
foreach($data['msg-data']['receivers'] as $number => $receivers){
$find = $this->entityManager->getRepository(User::class)->findOneBy(['phone' => $number]);
if($find){
$notification = new Notification();
$notification->setUsers($find);
$notification->setTitle( $title);
$notification->setBody( $receivers );
if(!empty($data['msg-data']['type']))
$notification->setType( $data['msg-data']['type']);
else
$notification->setType('text');
$notification->setDateEntered( new \DateTime() );
$notification->setStatus('new');
if(!empty($data['msg-data']['priority']))
$notification->setPriority($data['msg-data']['priority']);
if(!empty($data['msg-data']['ns_msg_id']))
$notification->setNsMsgId($data['msg-data']['ns_msg_id']);
$this->entityManager->persist($notification);
$i++;
}
if($i == 100){
$this->entityManager->flush();
$i = 0;
}
}
}
$this->entityManager->flush();
}
$rez = ['rez' => true, 'send' => $send , 'error' => ""];
}else{
$rez = ['rez' => false, 'error' => "Не задано поля: $valid"];
}
$response = new JsonResponse();
$response->setData($rez);
return $response;
}
#[Route('/api/create-data-reception', name: 'create_notfication_data_reception', methods: ['POST'])]
public function create_notfication_data_reception(Request $request)
{
if (!$this->customAuth($request)) {
return new JsonResponse(['message' => 'Unauthorized'], 401, [
'WWW-Authenticate' => 'Basic realm="API Access"',
]);
}
$data = json_decode($request->getContent(), true);
// $logId = $this->logHistory(false, 'createPersonalAccount', $data);
// file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "\n\n\n" . print_r($data, true) . "\n", FILE_APPEND);
$valid = $this->valid( $data, ['method', 'data'] );
if( empty($valid) ){
$DataReception = new DataReception();
$DataReception->setType( $data['method']);
$DataReception->setData( $data['data']);
$DataReception->setDateEntered( new \DateTime() );
$DataReception->setStatus('new');
$this->entityManager->persist($DataReception);
$this->entityManager->flush();
$rez = ['rez' => true, 'id' => $DataReception->getId()];
}else{
$rez = ['rez' => false, 'error' => "Не задано поля: $valid"];
}
$response = new JsonResponse();
$response->setData($rez);
return $response;
}
public function updateStatus($inf){
$query = $this->entityManager->createQuery(
'UPDATE App\Entity\Accounts d
SET d.statusPlanning = :new_status
WHERE d.eic IN (:ids)'
);
$query->setParameter('new_status', 'planned');
$query->setParameter('ids', $inf); // Масив ID
$query->execute();
}
#[Route('/cron-get-planned', name: 'cron_get_pllanned', methods: ['GET'])]
public function cron_get_pllanned(Request $request)
{
$query = $this->entityManager->createQuery(
'UPDATE App\Entity\Accounts d SET d.statusPlanning = :new_status'
);
$query->setParameter('new_status', 'not_pllaned');
// $query->setParameter('old_status', 'new');
// echo '<pre>';
$query->execute();
$this->entityManager->clear();
$DataReception = $this->entityManager->getRepository(DataReception::class)->findBy(['status' => 'new']);
$eic = [];
foreach($DataReception as $data){
$infos = json_decode($data->getData(), true);
foreach($infos as $acc_id => $inf){
array_push($eic, $inf);
if(count($eic) == 500){
$this->updateStatus($eic);
$eic = [];
}
}
if(count($eic) > 0)
$this->updateStatus($eic);
$this->entityManager->clear();
$data->setStatus('complate');
$this->entityManager->persist($data);
$this->entityManager->flush();
// print_r($infos);
}
echo count($DataReception); die;
}
#[Route('/api/get-account-all-data', name: 'get_account_all_data', methods: ['GET'])]
public function get_account_all_data(Request $request)
{
// echo '<pre>';
$AppPersonalAccount = $this->entityManager->getRepository(AppPersonalAccount::class)->findBy(['active' => true]);
foreach($AppPersonalAccount as $account){
// if(!empty( $account->getEic() ))
// continue;
$data = [
'account' => $account->getNumber()
];
$res = json_decode( $this->appApiService->account_all_data($data) , true );
if(isset($res['rez']) AND $res['rez'] == 1){
file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', print_r($res, true) . "\n", FILE_APPEND);
// $account->setEic($res['data'][0]['eic_kod']);
$this->entityManager->persist($account);
$this->entityManager->flush();
$accounts = $this->entityManager->getRepository(Accounts::class)->findOneBy(['number' => $account->getNumber()]);
if(!$accounts){
$accounts = new Accounts();
$accounts->setNumber($account->getNumber());
$accounts->setEic($account->getEic());
// $accounts->setEicParent($res_data['eic_kod_place']);
$this->entityManager->persist($accounts);
$this->entityManager->flush();
}
$account->setAccounts($accounts);
$this->entityManager->persist($account);
$this->entityManager->flush();
}
// print_r($res); die;
}
echo count( $AppPersonalAccount ); die;
echo 1; die;
}
/** Додавання id crm LOE */
#[Route('/api/update-service-id', name: 'update_service_id', methods: ['POST'])]
public function update_service_id(Request $request)
{
if (!$this->customAuth($request)) {
return new JsonResponse(['message' => 'Unauthorized'], 401, [
'WWW-Authenticate' => 'Basic realm="API Access"',
]);
}
$data = json_decode($request->getContent(), true);
// $logId = $this->logHistory(false, 'createPersonalAccount', $data);
// file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log', "\n\n\n" . print_r($data, true) . "\n", FILE_APPEND);
$valid = $this->valid( $data, ['id', 'id_crm'] );
if( empty($valid) ){
$ServiceOrderHistory = $this->entityManager->getRepository(ServiceOrderHistory::class)->findOneBy(['id' => $data['id']]);
if($ServiceOrderHistory){
$ServiceOrderHistory->setIdCrm( $data['id_crm']);
if(!empty( $data['status'] ))
$ServiceOrderHistory->setStatus( $data['status'] );
else
$ServiceOrderHistory->setStatus( 'in_process' );
if(!empty( $data['description'] ))
$ServiceOrderHistory->setDescription( $data['description'] );
$ServiceOrderHistory->setDateModified( new \DateTime() );
// $ServiceOrderHistory->setStatus('new');
$this->entityManager->persist($ServiceOrderHistory);
$this->entityManager->flush();
}
$rez = ['rez' => true, 'id' => $ServiceOrderHistory->getId()];
}else{
$rez = ['rez' => false, 'error' => "Не задано поля: $valid"];
}
$response = new JsonResponse();
$response->setData($rez);
return $response;
}
/** Додавання id crm LOE */
#[Route('/api/get-service-id', name: 'get_service_id', methods: ['GET'])]
public function get_service_id(Request $request)
{
if (!$this->customAuth($request)) {
return new JsonResponse(['message' => 'Unauthorized'], 401, [
'WWW-Authenticate' => 'Basic realm="API Access"',
]);
}
$arr = [];
$ServiceOrderHistory = $this->entityManager->getRepository(ServiceOrderHistory::class)->findBy(['status' => 'in_process']);
foreach($ServiceOrderHistory as $service){
$arr[] = [
'id' => $service->getId(),
'id_crm' => $service->getIdCrm(),
];
}
$rez = ['rez' => true, 'data' => $arr];
$response = new JsonResponse();
$response->setData($rez);
return $response;
}
/** Історія заявок з сторонніх систем */
#[Route('/api/create-order-history', name: 'create_order_history', methods: ['POST'])]
public function create_order_history(Request $request)
{
if (!$this->customAuth($request)) {
return new JsonResponse(['message' => 'Unauthorized'], 401, [
'WWW-Authenticate' => 'Basic realm="API Access"',
]);
}
$data = json_decode($request->getContent(), true);
$valid = $this->valid( $data, ['phone', 'account', 'service_code', 'status', 'id_crm' , 'pdf'] );
if( empty($valid) ){
$find = $this->entityManager->getRepository(User::class)->findOneBy(['phone' => $data['phone']]);
if($find){
$arr = [];
$orderNames = [
9 => "Встановлення зонного лічильника",
10 => "Лічильник не працює",
21 => "Неправильний показ",
32 => "Зміна власника",
35 => "Підключення електроустановок замовника після виконання ТУ",
63 => "Звернення щодо підозри на крадіжку",
79 => "Заміна автоматичного вимикача, який опломбований ОСР",
85 => "Відсутність пломб на засобі обліку",
86 => "Закриття особового рахунку",
];
foreach($find->getAppPersonalAccounts() as $acc){
if($acc->getNumber() == $data['account'])
$account = $acc;
}
if($account){
$ServiceOrderHistory = new ServiceOrderHistory();
$ServiceOrderHistory->setName($orderNames[$data['service_code']]);
// $ServiceOrderHistory->setRequest($data);
$ServiceOrderHistory->setDateEntered( new \DateTime() );
$ServiceOrderHistory->setType($data['service_code']);
$ServiceOrderHistory->setStatus('new');
$ServiceOrderHistory->setPersonalAccount($account);
if(!empty( $data['id_crm'] ))
$ServiceOrderHistory->setIdCrm( $data['id_crm']);
if(!empty( $data['status'] ))
$ServiceOrderHistory->setStatus( $data['status'] );
else
$ServiceOrderHistory->setStatus( 'in_process' );
if(!empty( $data['description'] ))
$ServiceOrderHistory->setDescription( $data['description'] );
$ServiceOrderHistory->setPersonalAccount($account);
$this->entityManager->persist($ServiceOrderHistory);
$this->entityManager->flush();
$data["id"] = $ServiceOrderHistory->getId();
$rez = ['rez' => true, 'data' => $arr];
}
}else{
$rez = ['rezult' => false, 'error' => "Користувача не знайдено!"];
}
}else{
$rez = ['rez' => false, 'error' => "Не задано поля: $valid"];
}
$response = new JsonResponse();
$response->setData($rez);
return $response;
}
}