Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 84.65 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Controllers\Prevenda\ViabilidadeComercial;
  4.  
  5. use \Util\Prevendas\PrevendasConfig;
  6. use \Util\Prevendas\CurlPrevendas;
  7. use \Util\Prevendas\SVAParamParser;
  8. use \Util\Param;
  9. use \Util\Util;
  10.  
  11. class DetalharController extends \Controllers\Comercial\Viabilidade\DetalharBase implements \Util\BaseController {
  12.  
  13. const FEATURE_ATRIBUTE_CAPILARES = 88;
  14.  
  15. const LPU_TIPO_PADRAO = 'P';
  16.  
  17. public function __construct(){
  18. $this->nivel = $_SESSION['permissoes'][117];
  19. if (!$this->nivel && !$_SESSION['permissoes'][109]) {
  20. throw new \Exception('Sem permissão', 403);
  21. }
  22. }
  23.  
  24. public function index(){
  25.  
  26. parent::index();
  27. $config = PrevendasConfig::getConfig();
  28. $objServicoFinanceiro = $this->getArrayParams('servicoFinanceiro');
  29. $viable = $this->getArrayParams("objViable");
  30.  
  31. // Caso tenha espaço exclusivo para Datacenter, será um Colocation
  32. //e a informação deve ir para view
  33.  
  34. $this->setArrayParams('espacoDatacenter', $viable->getEspacoDatacenter());
  35.  
  36. $interfacesValidar = array(1, 2);
  37. if (in_array($objServicoFinanceiro->getServApelido(), $config['servicos']) && (in_array($viable->getInterfaceReal(), $interfacesValidar))) {
  38. $this->setArrayParams('urlPrevendasApiConsultaGrupo', $config['ajaxEndpoinst']['consultaGrupos']);
  39. $this->setArrayParams('isSegregatedViable', true);
  40. $grupos = $this->getGrupoSva($objServicoFinanceiro, $this->getArrayParams('objViable'));
  41. $this->setArrayParams('gruposSva', $grupos);
  42. } else {
  43. $this->setArrayParams('isSegregatedViable', 0);
  44. }
  45.  
  46. $interfaces = \Util\Param::paramMovi('interfaces');
  47. $this->setArrayParams('meios', array_map(function($value, $label)use($viable){
  48. return array(
  49. 'label' => $label,
  50. 'value' => $value,
  51. 'attr' => $viable->getInterface()==$value?'selected':''
  52. );
  53. }, array_keys($interfaces), array_values($interfaces)));
  54.  
  55. $interfacesReal = \Util\Param::paramMovi('interfacesReal');
  56. $arrayCarregaInterfaces = \Util\Param::paramMovi('relacionamentoInterfaces');
  57. $this->setArrayParams('interfaces', array_filter(array_map(function($value, $label)use($viable,$arrayCarregaInterfaces){
  58. if(!in_array($value, $arrayCarregaInterfaces[$viable->getInterface()])){
  59. return false;
  60. }
  61. return array(
  62. 'label' => $label,
  63. 'value' => $value,
  64. 'attr' => $viable->getInterfaceReal()==$value?'selected':''
  65. );
  66. }, array_keys($interfacesReal), array_values($interfacesReal))));
  67.  
  68. $tiposRedes = \Util\Param::paramMovi('tiposRede');
  69. $this->setArrayParams('tiposRede', array_map(function($value, $label)use($viable){
  70. return array(
  71. 'label' => $label,
  72. 'value' => $value,
  73. 'attr' => $viable->getNetworkType()==$value?'selected':''
  74. );
  75. }, array_keys($tiposRedes), array_values($tiposRedes)));
  76.  
  77. $this->setArrayParams('totalFO', (float) $viable->getTotalFO());
  78.  
  79. $entityComercial = $this->getArrayParams('entityComercial');
  80. $arrayProdutos = $entityComercial->getRepository('\Comercial\Entity\Requirement')->findAll();
  81. $produtos = array_filter(array_map ( function (\Comercial\Entity\Requirement $objRequirement) {
  82. $lumaid = $objRequirement->getLumaId();
  83. if (!$lumaid) {
  84. return NULL;
  85. }
  86. $name = str_pad($lumaid, 4, '0', STR_PAD_LEFT).' - '.utf8_decode($objRequirement->getName());
  87. return array (
  88. 'value' => $lumaid,
  89. 'label' => $name,
  90. 'attr' => utf8_decode ( "data-sigla='{$objRequirement->getUnit()}'" )
  91. );
  92. }, $arrayProdutos));
  93. $this->setArrayParams('produtos', $produtos);
  94.  
  95. $template = $this->getArrayParams( 'objTemplate' )->setTemplate ( '/inc/skeleton/base.html.twig' );
  96. $template->routing = true;
  97. return $template->show();
  98. }
  99.  
  100. /**
  101. * Carrega uma lista de LPUs de acordo com o serviço
  102. */
  103. public function vincular(){
  104. $this->setArrayParams("modelTemplate", '/prevenda/viabilidadeComercial/vincularLPU.html.twig');
  105. $entityPresale = $this->getArrayParams ( 'entityPresale' );
  106. $entityComercial = $this->getArrayParams ( 'entityComercial' );
  107. $objViable = $entityComercial->getRepository('\Comercial\Entity\Viable')->find($_REQUEST['viabilidade']);
  108. $objService = $objViable->getChance()->getIdProduct();
  109. $objService = $entityPresale->getRepository('\Presale\Entity\Service')->findOneByServCodigoid($objService->getServicoContrato());
  110. /*$arrayLpus = $entityPresale->getRepository('\Presale\Entity\Lpu')->findBy ( array (
  111. 'active' => true,
  112. 'service' => $objService,
  113. 'onlineSales' => null
  114. ), array (
  115. 'id' => 'ASC'
  116. ) );*/
  117.  
  118. $arrayLpus = $entityPresale->getRepository('\Presale\Entity\Lpu')->getLpus($objService->getId());
  119. $this->setArrayParams("params", array('lpus'=> array_map(function(\Presale\Entity\Lpu $objLpu){
  120. return array(
  121. 'label' => utf8_decode($objLpu->getName()),
  122. 'value' => $objLpu->getId()
  123. );
  124. }, $arrayLpus)));
  125. $this->getArrayParams('objTemplate')->show('ViabilidadeComercial', 'Ajax');
  126. }
  127.  
  128. /**
  129. * Carrega tela para cadastrar nova lpu
  130. */
  131. public function adicionar() {
  132. try{
  133. $entityComercial = $this->getArrayParams('entityComercial');
  134. $entityPresale = $this->getArrayParams('entityPresale');
  135. $entityFinanceiro = $this->getArrayParams('entityFinanceiro');
  136.  
  137. if(!isset($_REQUEST['viabilidade']) || !$_REQUEST['viabilidade']){
  138. throw new \Exception('Viabilidade não encontrada.');
  139. }
  140. $objViable = $entityComercial->getRepository('\Comercial\Entity\Viable')->find($_REQUEST['viabilidade']);
  141. if(!$objViable instanceof \Comercial\Entity\Viable){
  142. throw new \Exception('Viabilidade inválida.');
  143. }
  144.  
  145. // Tipo de rede pode já ter sido definido pela equipe de engenharia ou na tela-mãe da adição da LPU
  146. $tipoRede = $objViable->getNetworkType();
  147. $requestTipoRede = (!empty($_REQUEST['tipoRede'])) ? $_REQUEST['tipoRede'] : '';
  148. $tipoRede = (empty($tipoRede)) ? $requestTipoRede : $tipoRede;
  149.  
  150. $objChance = $objViable->getChance();
  151. $objService = $entityPresale->getRepository('Presale\Entity\Service')->findOneBy(
  152. array('servCodigoid'=>$objChance->getIdProduct()->getServicoContrato())
  153. );
  154.  
  155. $caracteristicas = array();
  156. foreach ($objViable->getFeatures() as $objViableFeature){
  157. // Deve deixar precificar apenas a feature dos capilares para o produto FIBRA APAGADA
  158. if ($objService->getName() == "FIBRA APAGADA" && $objViableFeature->getFeatureattributeId() != self::FEATURE_ATRIBUTE_CAPILARES) {
  159. continue;
  160. }
  161. $objFeatureAttribute = $entityPresale->getRepository('Presale\Entity\FeatureAttribute')->find(
  162. $objViableFeature->getFeatureAttributeId()?:0
  163. );
  164. if(!$objFeatureAttribute instanceof \Presale\Entity\FeatureAttribute){
  165. throw new \Exception('Característica inválida.');
  166. }
  167. $objFeature = $objFeatureAttribute->getFeature();
  168. $nome = utf8_decode($objFeatureAttribute->getName());
  169. if (is_numeric($nome)) {
  170. $objAtrivalo = $entityFinanceiro->getRepository('Financeiro\Entity\Atributovalor')->find($nome);
  171. if($objAtrivalo instanceof \Financeiro\Entity\Atributovalor){
  172. $nome = $objAtrivalo->getAtrivaloValor();
  173. }
  174. }
  175. $caracteristicas[utf8_decode($objFeature->getName())]['atributos'][] = array('label'=>$nome?:utf8_decode($objFeature->getName()),'value'=>$objFeatureAttribute->getId());
  176. $caracteristicas[utf8_decode($objFeature->getName())]['label']= utf8_decode($objFeature->getName());
  177. }
  178. // Características obrigatórias
  179. $arrayFeatureMandatory = array_filter(array_map(function($obj){
  180. if($obj->getMandatory()){
  181. return $obj;
  182. }
  183. return false;
  184. },$objService->getFeatures()->toArray()));
  185. foreach ($arrayFeatureMandatory as $objFeatureMandatory){
  186. // Retorna os marcados como default
  187. $arrayFeatureAttribute = array_filter(array_map(function($obj){
  188. if($obj->getDefaultSelected()){
  189. return $obj;
  190. }
  191. return false;
  192. },$objFeatureMandatory->getAttributes()->toArray()));
  193.  
  194. foreach ($arrayFeatureAttribute as $objFeatureAttribute){
  195. if(!in_array(utf8_decode($objFeatureMandatory->getName()),$caracteristicas)){
  196. $nome = utf8_decode($objFeatureAttribute->getName());
  197. if (is_numeric($nome)) {
  198. $objAtrivalo = $entityFinanceiro->getRepository('Financeiro\Entity\Atributovalor')->find($nome);
  199. if($objAtrivalo instanceof \Financeiro\Entity\Atributovalor){
  200. $nome = $objAtrivalo->getAtrivaloValor();
  201. }
  202. }
  203. $caracteristicas[utf8_decode($objFeatureMandatory->getName())]['atributos'][] = array('label'=>$nome?:utf8_decode($objFeatureMandatory->getName()),'value'=>$objFeatureAttribute->getId());
  204. $caracteristicas[utf8_decode($objFeatureMandatory->getName())]['label']= utf8_decode($objFeatureMandatory->getName());
  205. }
  206. }
  207. }
  208. $params['caracteristicas'] = $caracteristicas;
  209.  
  210.  
  211. if($objViable->getRequestContractDeadline()){
  212. $params['tempo'] = $objViable->getRequestContractDeadline();
  213. $params['unidadeTempo'] = $objViable->getRequestContractDeadlineUnit();
  214. }
  215.  
  216. // Verifica se é um serviço sem velocidade
  217. $servicoSemVelocidade = false;
  218. if(in_array($objService->getid(),\Util\Param::$arrayServicosSemVelocidadePresale)) {
  219. $servicoSemVelocidade = true;
  220. }
  221. // Se for colocation permite definir quantidade
  222. $params["semVelocidade"] = $servicoSemVelocidade;
  223. if(strtolower($objService->getName()) == "colocation") {
  224. $params["quantidade"] = true;
  225. }
  226.  
  227. $params["tipoRede"] = (empty($tipoRede)) ? '' : $tipoRede;
  228.  
  229. $this->setArrayParams("modelTemplate", '/prevenda/viabilidadeComercial/adicionarLPU.html.twig');
  230. $this->setArrayParams("params", $params);
  231. $this->getArrayParams('objTemplate')->show('ViabilidadeComercial', 'Ajax');
  232. }
  233. catch(\Exception $ex){
  234. print_r($ex->getMessage());
  235. }
  236. }
  237.  
  238. public function anexo(){
  239. try {
  240. $entityComercial = $this->getArrayParams ( 'entityComercial' );
  241. $objViableApproval = $entityComercial->getRepository ( '\Comercial\Entity\ViableApproval' )->find ( $_REQUEST['doc']?:0 );
  242. if(!$objViableApproval instanceof \Comercial\Entity\ViableApproval){
  243. throw new \Exception ( 'Documento inválido', 0xb00b5 );
  244. }
  245. $pathBroken = explode('/', $objViableApproval->getAttachment());
  246. $filename = $pathBroken[count($pathBroken)-1];
  247. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // some day in the past
  248. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  249. header("Content-type: application/x-download");
  250. header("Content-Disposition: attachment; filename={$filename}");
  251. header("Content-Transfer-Encoding: binary");
  252. return readfile($objViableApproval->getAttachment());
  253. } catch ( \Exception $ex ) {
  254. throw new \Exception ( $ex->getMessage (), $ex->getCode () );
  255. }
  256. }
  257.  
  258. /** Rejeita uma solicitação de viabilidade
  259. */
  260. public function rejeitar() {
  261. $entityComercial = $this->getArrayParams('entityComercial');
  262. $entityStech = $this->getArrayParams('entityStech');
  263. $entityLuma = $this->getArrayParams('entityLuma');
  264. try {
  265. // Validação
  266. $objValidate = new \Util\Validate ();
  267. $objValidate->set('viabilidade', 'viabilidade')->is_parameter();
  268. $objValidate->set('Motivo', 'motivo')->is_parameter();
  269. \Util\Util::getErrors($objValidate);
  270. $objValidate->set('viabilidade', $_REQUEST['viabilidade'])->is_required()->is_integer();
  271. $objValidate->set('Motivo', $_REQUEST['motivo'])->is_required();
  272. \Util\Util::getErrors($objValidate);
  273.  
  274. // Inicia transação e busca viabilidade
  275. $entityComercial->beginTransaction();
  276. $objViable = $entityComercial->getRepository('\Comercial\Entity\Viable')->find($_REQUEST['viabilidade']);
  277. if(!in_array($objViable->getViableStatus()->getId(), array(3,9))){
  278. throw new \Exception('Status inválido');
  279. }
  280. // Atualiza para inviável
  281. $objViable->setViable(false);
  282.  
  283. // Rejeita a viabilidade e notifica o EV
  284. if($_REQUEST['tipo-rejeicao'] == "erroInviavel") { // Já tem aprovação da engenharia
  285. $inviavelComercial = $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(5);
  286. $objViableApproval = $entityComercial->getRepository('\Comercial\Entity\ViableApproval')->findOneBy(array(
  287. 'viable' => $objViable,
  288. 'prevViableStatus' => 3,
  289. ));
  290. if(!$objViableApproval instanceof \Comercial\Entity\ViableApproval){
  291. $objViableApproval = new \Comercial\Entity\ViableApproval();
  292. $objViableApproval->setViable($objViable);
  293. $objViableApproval->setDateRecord(new \DateTime());
  294. $objViableApproval->setPrevViableStatus(
  295. $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(9)
  296. );
  297. $objViableApproval->setDeadlineApproval(new \DateTime());
  298. }
  299. // Atualiza os dados de aprovação
  300. $objViableApproval->setAuthor($_SESSION['id_user']);
  301. $objViableApproval->setDateApproval(new \DateTime());
  302. $objViableApproval->setObs($_REQUEST['motivo']);
  303. $objViable->setViableStatus($inviavelComercial);
  304. $entityComercial->persist($objViableApproval);
  305.  
  306. } else if($_REQUEST['tipo-rejeicao'] == "erroCadastro") { // Ainda não foi aprovado por ninguém
  307.  
  308. $erroCadastro = $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(10);
  309. if(!($erroCadastro instanceof \Comercial\Entity\ViableStatus)) {
  310. throw new \Exception("Status não encontrado para erro de cadastro");
  311. }
  312. $objViableApproval = new \Comercial\Entity\ViableApproval();
  313. $objViableApproval->setAuthor($_SESSION["user_id"]);
  314. $objViableApproval->setApproved(false);
  315. $objViableApproval->setObs($_REQUEST["motivo"]);
  316. $objViableApproval->setViable($objViable);
  317. $objViableApproval->setDateApproval(new \DateTime());
  318. $objViableApproval->setDateRecord(new \DateTime());
  319. $objViableApproval->setDeadlineApproval(new \DateTime());
  320. $objViableApproval->setPrevViableStatus(
  321. $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(9)
  322. );
  323. $objViable->setViableStatus($erroCadastro);
  324. $entityComercial->persist($objViableApproval);
  325. }
  326.  
  327. $entityComercial->flush();
  328. $entityComercial->commit();
  329.  
  330. if($this->notificar($objViableApproval)){
  331. $retorno = array("msg"=> "Rejeitado com Sucesso!", "error" => false);
  332. } else {
  333. $retorno = array("msg"=> utf8_encode("Viabilidade Rejeitado com sucesso, mas notificação não enviada."), "error" => false);
  334. }
  335.  
  336. // se foi uma viabilidade gerada pelo Vendas Online, enviar email de atualização de status
  337. $tags = $objViable->getChance()->getTags()->first();
  338. if (is_object($tags) && $tags->getName() == 'gerada_web') {
  339. $objProspect = $entityComercial->getRepository('\Comercial\Entity\Prospect')->findOneBy(array(
  340. 'id' => $objViable->getChance()->getIdProspect(),
  341. )
  342. );
  343.  
  344. $objCadUsers = $entityStech->getRepository('\Sistech\Entity\CadUsers')->find($objProspect->getIdCliente());
  345.  
  346. $arrayEmail = $objCadUsers->getCadUsersEmail()->toArray();
  347.  
  348. $objEmail = array_map(function($obj){
  349. if($obj->getPrincipal()) return $obj->getEmail();
  350. else return '';
  351. },$arrayEmail);
  352. $email = (count($objEmail)?implode('/',array_filter($objEmail)):$objCustomers->getEmail());
  353.  
  354. $objTipo = $entityLuma->getRepository("Luma\Entity\Tipo")->find(54);
  355.  
  356. // Adiciona email de confirmação a tabela de envios
  357. $objEmail = new \Luma\Entity\Email();
  358. $objEmail->setEmailAnexo(NULL);
  359. $objEmail->setEmailAssunto('Vogel Telecom - Status de solicitação de viabilidade atualizado!');
  360. $objEmail->setEmailBcc(NULL);
  361. $objEmail->setEmailCc(NULL);
  362. $objEmail->setEmailCorpo('O status da solicitação de sua viabilidade foi atualizado. Verificar em: https://at.vogeltelecom.com/vendas/');
  363. $objEmail->setEmailDataenvio(new \DateTime());
  364. $objEmail->setEmailDatainc(new \DateTime());
  365. $objEmail->setEmailDe('sistemas@vogeltelecom.com');
  366. $objEmail->setEmailIdoperacao(0);
  367. $objEmail->setEmailPagina('');
  368. $objEmail->setEmailPara($email);
  369. $objEmail->setEmailPrioridade(5);
  370. $objEmail->setEmailTipooperacao('insert');
  371. $objEmail->setTipoCodigoid($objTipo);
  372. $entityLuma->persist($objEmail);
  373. $entityLuma->flush();
  374. }
  375.  
  376. } catch (\Exception $e) {
  377. $entityComercial->rollback();
  378. $retorno = array("msg"=> nl2br(utf8_encode($e->getMessage())), "error" => true);
  379. }
  380. return JSON_encode($retorno);
  381. }
  382.  
  383. private function getUploadedName(\Comercial\Entity\ViableApproval $objViableAproval) {
  384. // Undefined | Multiple Files | $_FILES Corruption Attack
  385. // If this request falls under any of them, treat it invalid.
  386. if (! isset ( $_FILES ['anexo-produtos'] ['error'] ) || is_array ( $_FILES ['anexo-produtos'] ['error'] )) {
  387. return '';
  388. }
  389. switch ($_FILES ['anexo-produtos'] ['error']) {
  390. case UPLOAD_ERR_OK :
  391. break;
  392. case UPLOAD_ERR_NO_FILE :
  393. return false;
  394. case UPLOAD_ERR_INI_SIZE :
  395. case UPLOAD_ERR_FORM_SIZE :
  396. throw new \RuntimeException ( 'Exceeded filesize limit.' );
  397. default :
  398. throw new \RuntimeException ( 'Unknown errors.' );
  399. }
  400. // You should also check filesize here.
  401. if ($_FILES['anexo-produtos']['size'] > 5*1024*1024) {
  402. throw new \RuntimeException('Exceeded filesize limit.');
  403. }
  404.  
  405. // DO NOT TRUST $_FILES['anexo']['mime'] VALUE !!
  406. // Check MIME Type by yourself.
  407. $exts = explode('.', $_FILES ['anexo-produtos'] ['name']);
  408. $ext = $exts[count($exts)-1];
  409. if (!in_array($ext, array('doc', 'docx', 'odt', 'xls', 'xlsx', 'ods', 'pdf', 'zip'))) {
  410. throw new \RuntimeException ( 'Formato inválido do arquivo. Formatos aceitos: doc, docx, odt, xls, xlsx, ods, pdf, zip.' );
  411. }
  412. // You should name it uniquely.
  413. // DO NOT USE $_FILES['anexo']['name'] WITHOUT ANY VALIDATION !!
  414. // On this example, obtain safe unique name from its binary data.
  415. if(!is_dir( '/mnt/dados/ movi/viabilidade/')){
  416. mkdir('/mnt/dados/movi/viabilidade/', 0775, true);
  417. }
  418. $savedName = sprintf ( '/mnt/dados/movi/viabilidade/%s.%s', str_pad($objViableAproval->getId(), 8, '0', STR_PAD_LEFT).'_'.sha1_file ( $_FILES ['anexo-produtos'] ['tmp_name'] ), $ext );
  419. if (! move_uploaded_file ( $_FILES ['anexo-produtos'] ['tmp_name'], $savedName )) {
  420. throw new \RuntimeException ( 'Failed to move uploaded file.' );
  421. }
  422. return $savedName;
  423. }
  424.  
  425. /**
  426. * Associa uma LPU para a viabilidade
  427. */
  428. public function vincularLpu() {
  429.  
  430. $entityComercial = $this->getArrayParams('entityComercial');
  431. $entityPresale = $this->getArrayParams('entityPresale');
  432. $entityStech = $this->getArrayParams('entityStech');
  433. $entityLuma = $this->getArrayParams('entityLuma');
  434.  
  435. try {
  436.  
  437. $entityComercial->beginTransaction();
  438. $entityStech->beginTransaction();
  439. if($this->nivel & 2 != 2){
  440. throw new \Exception('Sem permissão para esta ação.', 403);
  441. }
  442. $objValidate = new \Util\Validate ();
  443. $objValidate->set('viabilidade', 'viabilidade')->is_parameter();
  444. $objValidate->set('Observações', 'obs')->is_parameter()->is_required();
  445. $objValidate->set('Prazo Mínimo de Ativação', 'prazoAtivacaoMinimo')->is_parameter()->is_integer();
  446. $objValidate->set('Lpu', 'lpu')->is_parameter();
  447. \Util\Util::getErrors($objValidate);
  448. $objValidate->set('viabilidade', $_REQUEST['viabilidade'])->is_required();
  449. $objValidate->set('Lpu', $_REQUEST['lpu'])->is_integer()->is_required();
  450. \Util\Util::getErrors($objValidate);
  451.  
  452. $objViable = $entityComercial->getRepository('\Comercial\Entity\Viable')->find($_REQUEST['viabilidade']);
  453. if(!$objViable instanceof \Comercial\Entity\Viable){
  454. throw new \Exception('Id Viabilidade inválido');
  455. }
  456. if(!in_array($objViable->getViableStatus()->getId(),array(3,9))){
  457. throw new \Exception('Status inválido');
  458. }
  459.  
  460. $tipoRede = $objViable->getNetworkType();
  461. if(empty($tipoRede)){
  462. if(empty($_REQUEST['tipoRede'])){
  463. throw new \Exception('Selecione um tipo de rede.');
  464. }
  465. $objViable->setNetworkType($_REQUEST['tipoRede']);
  466. $entityComercial->persist($objViable);
  467. }
  468.  
  469. $idServico = $objViable->getChance()->getIdProduct()->getId();
  470. if( !in_array($idServico,\Util\Param::$arrayServicosSemMeioAcesso)) {
  471. $objValidate->set('interface', $_REQUEST['interface'])->is_required();
  472. $objValidate->set('Total FO', $_REQUEST['totalFO'])->is_required()->is_integer();
  473. }
  474.  
  475. if(isset($_REQUEST['produto']) || isset($_REQUEST['quantidade']) || isset($_REQUEST['finalidade']) || isset($_REQUEST['valor'])){
  476. $produtos = $_REQUEST['produto'];
  477. $finalidades = $_REQUEST['finalidade'];
  478. $objValidate->set('Produtos', $produtos)->is_required()->is_arr();
  479. $quantidades = $_REQUEST['quantidade'];
  480. $objValidate->set('Quantidades de Produto', $quantidades)->is_required()->is_arr();
  481. $valores = $_REQUEST['valor'];
  482. $objValidate->set('Valores de Produto', $valores)->is_required()->is_arr();
  483. if (count($produtos) !== count($quantidades)) {
  484. throw new \Exception('Há produto ou quantidade não preenchida.');
  485. }
  486. } else {
  487. $produtos = $quantidades = array();
  488. }
  489.  
  490. $objViableApproval = $entityComercial->getRepository('\Comercial\Entity\ViableApproval')->findOneBy(array(
  491. 'viable' => $objViable,
  492. 'prevViableStatus' => 3,
  493. ));
  494. if(!$objViableApproval instanceof \Comercial\Entity\ViableApproval){
  495. $objViableApproval = new \Comercial\Entity\ViableApproval();
  496. $objViableApproval->setDateRecord(new \DateTime());
  497. $objViableApproval->setDeadlineApproval(new \DateTime());
  498. // $entityComercial->persist($objViableApproval);
  499.  
  500. $oldViableStatus = $objViable->getViableStatus();
  501. $objViableApproval->setPrevViableStatus($oldViableStatus);
  502. $objViableApproval->setViable($objViable);
  503. }
  504. $objViableApproval->setMinAtivationDays($_REQUEST['prazoAtivacao']?:NULL);
  505. $objViableApproval->setAuthor($_SESSION['id_user']);
  506. $objViableApproval->setDateApproval(new \DateTime());
  507. $objViableApproval->setObs($_REQUEST['obs']);
  508. $objViableApproval->setAttachment($this->getUploadedName($objViableApproval));
  509. $entityComercial->persist($objViableApproval);
  510.  
  511. // Se for par (colocation) na ponta B grava uma aprovação igual a da Ponta A
  512. if(!is_null($objViable->getPair())) {
  513. $objViableApprovalPontaB = new \Comercial\Entity\ViableApproval();
  514. $objViableApprovalPontaB->setDateRecord(new \DateTime());
  515. $objViableApprovalPontaB->setDeadlineApproval(new \DateTime());
  516. $objViableApprovalPontaB->setPrevViableStatus($objViable->getViableStatus());
  517. $objViableApprovalPontaB->setViable($objViable->getPair());
  518. $objViableApprovalPontaB->setMinAtivationDays($objViableApproval->getMinAtivationDays());
  519. $objViableApprovalPontaB->setDateApproval($objViableApproval->getDateApproval());
  520. $objViableApprovalPontaB->setAuthor($objViableApproval->getAuthor());
  521. $objViableApprovalPontaB->setObs($objViableApproval->getObs());
  522. $entityComercial->persist($objViableApprovalPontaB);
  523. }
  524.  
  525. $newViableStatus = $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(6);
  526. $objViable->setViableStatus($newViableStatus);
  527. $objViable->setViable(true);
  528. $objViable->setShadowLpuId($_REQUEST['lpu']);
  529.  
  530. // $arrayObjLpuPoints = $entityPresale->getRepository('\Presale\Entity\LpuPoint')->findByLpu($_REQUEST['lpu']);
  531. // if(!count($arrayObjLpuPoints)){
  532. // throw new \Exception('A Lpu selecionada não possui pontos cadastrados');
  533. // }
  534. // foreach ($arrayObjLpuPoints as $objLpuPoint){
  535. // $objViablePoint = new \Comercial\Entity\ViablePoint();
  536. // $objViablePoint->setPointId($objLpuPoint->getPointId());
  537. // $objViablePoint->setViable($objViable);
  538. // $entityComercial->persist($objViablePoint);
  539. // }
  540. //
  541.  
  542. $this->validaGrupoProdutoViabilidade($objViable, $_POST);
  543.  
  544. $entityComercial->flush();
  545.  
  546. if($objViable->getChance()->getIdProduct()->getName() != "FIBRA APAGADA"){
  547. // Verifica se houve alteração da engenharia no meio de acesso
  548. if ($_REQUEST['meio'] != $objViable->getInterface() || $_REQUEST['interface'] != $objViable->getInterfaceReal()) {
  549. $newViableStatus = $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(4);
  550. $objViableOld= $objViable;
  551. $objViableOld->setViableStatus($newViableStatus);
  552. $objViableOld->setActive(false);
  553. $objViable = new \Comercial\Entity\Viable();
  554. $objViable->setPreviousViable($objViableOld);
  555. $objViableOld->setNextViable($objViable);
  556. $objViable->setActive(true);
  557. $objViable->setAuthor($objViableOld->getAuthor());
  558. $objViable->setCep($objViableOld->getCep());
  559. $objViable->setChance($objViableOld->getChance());
  560. $objViable->setCity($objViableOld->getCity());
  561. $objViable->setComplement($objViableOld->getComplement());
  562. $objViable->setContCodigoid($objViableOld->getContCodigoid());
  563. $objViable->setDateRecord($objViableOld->getDateRecord());
  564. $objViable->setDistrict($objViableOld->getDistrict());
  565. $objViable->setHash($objViableOld->getHash());
  566. $objViable->setInterface($_REQUEST['meio']);
  567. $objViable->setInterfaceReal($_REQUEST['interface']);
  568. $objViable->setLat($objViableOld->getLat());
  569. $objViable->setLon($objViableOld->getLon());
  570. $objViable->setNumber($objViableOld->getNumber());
  571. $objViable->setPriceZone($objViableOld->getPriceZone());
  572. $objViable->setSpeed($objViableOld->getSpeed());
  573. $objViable->setSpeedType($objViableOld->getSpeedType());
  574. $objViable->setSteet($objViableOld->getSteet());
  575. $objViable->setUf($objViableOld->getUf());
  576. $objViable->setViable(false);
  577. foreach ($objViableOld->getFeatures() as $objViableFeatureOld){
  578. $objViableFeature = new \Comercial\Entity\ViableFeature();
  579. $objViableFeature->setFeatureattributeId($objViableFeatureOld->getFeatureattributeId());
  580. $objViableFeature->setViable($objViable);
  581. $entityComercial->persist($objViableFeature);
  582. $objViable->addViableFeature($objViableFeature);
  583. }
  584. $entityComercial->persist($objViable);
  585. }
  586.  
  587. $objService = $entityPresale->getRepository('\Presale\Entity\Service')->findOneByServCodigoid(
  588. $objViable->getChance()->getIdProduct()->getServicoContrato()
  589. );
  590. if (!$objService instanceof \Presale\Entity\Service) {
  591. throw new \Exceptio('Tipo de serviço não encontrado.');
  592. }
  593.  
  594. if ($objService->getId() == self::SERVICO_IP_ISP && $objViable->getDeliveryPlace() == 'caixa') {
  595. $objValidate->set('LAT', $_REQUEST['lat'])->is_required()->is_num();
  596. $objValidate->set('LON', $_REQUEST['lon'])->is_required()->is_num();
  597. \Util\Util::getErrors($objValidate);
  598.  
  599. $objViable->setLat($_REQUEST['lat']);
  600. $objViable->setLon($_REQUEST['lon']);
  601. }
  602. }
  603.  
  604. if ($_REQUEST['totalFO'] != $objViable->getTotalFO()) {
  605. $objViable->setTotalFO($_REQUEST['totalFO']);
  606. }
  607.  
  608. if(isset($_REQUEST['coordenadas'])){
  609. $objViable->setCoords($_REQUEST['coordenadas']);
  610. if($objViable->getPair()){
  611. $objViable->getPair()->setCoords($_REQUEST['coordenadas']);
  612. }
  613. }
  614.  
  615. if (isset($_REQUEST['distancia']) || isset($_REQUEST['siglaDistancia'])) {
  616. $distancia = $_REQUEST['distancia']?:0;
  617. $siglaDistancia = $_REQUEST['siglaDistancia']?:'';
  618. if($distancia || $siglaDistancia){
  619. $objValidate->set('Distancia', $distancia)->is_required()->is_num()->min_value(0);
  620. $objValidate->set('Distancia', $siglaDistancia)->is_required()->contains(array('km', 'm'));
  621. $objViable->setFiberDistance($distancia);
  622. $objViable->setFiberUnit($siglaDistancia);
  623. if($objViable->getPair()){
  624. $objViable->getPair()->setFiberDistance($distancia);
  625. $objViable->getPair()->setFiberUnit($siglaDistancia);
  626. }
  627. }
  628. }
  629. $entityComercial->persist($objViable);
  630.  
  631. // Trata os casos em que a equipe de pré-vendas exclui algum produto que foi adicionado pela equipe de engenharia
  632. $arrayObjViableRequirements = $entityComercial->getRepository('\Comercial\Entity\ViableRequirement')->findBy(array('viable' => $objViable));
  633. $arrayIdViableRequirementsForDelete = array();
  634. foreach ($arrayObjViableRequirements as $objViableRequirementExistente) {
  635. $arrayIdViableRequirementsForDelete[] = $objViableRequirementExistente->getId();
  636. }
  637.  
  638. // Produtos para viabilidade (grupos e produto avulso)
  639. $count = count($produtos);
  640. for ($i = 0; $i < $count; ++$i){
  641. if (!empty($_REQUEST['idViableRequirement'][$i])) {
  642. //Edição de um produto anteriormente adicionado pela equipe de Engenharia
  643. $objViableRequirement = $entityComercial->getRepository('\Comercial\Entity\ViableRequirement')->find($_REQUEST['idViableRequirement'][$i]);
  644.  
  645. // Como este ViableRequirement foi mantido pela equipe de engenharia, remove da lista de exclusões
  646. if (($chave = array_search($_REQUEST['idViableRequirement'][$i], $arrayIdViableRequirementsForDelete)) !== false) {
  647. unset($arrayIdViableRequirementsForDelete[$chave]);
  648. }
  649. } else {
  650. // Novo
  651. $objViableRequirement = new \Comercial\Entity\ViableRequirement();
  652. }
  653. $lumaid = $produtos[$i];
  654. $objGrupo = NULL;
  655. $isGrupo = $lumaid[0]=='G';
  656. if(is_numeric($lumaid) || $isGrupo){
  657. if($isGrupo) {
  658. $grip = substr($lumaid, 1);
  659. $objGroupItem = $entityComercial->getRepository('\Comercial\Entity\GroupItem')->find($grip);
  660. if(!$objGroupItem instanceof \Comercial\Entity\GroupItem){
  661. throw new \Exception('Item de Grupo inválido.');
  662. }
  663. $lumaid = $objGroupItem->getProductLuma();
  664. $objGrupo = $objGroupItem->getGroup();
  665. }
  666. $objRequirement = $entityComercial->getRepository('\Comercial\Entity\Requirement')->findOneByLumaId($lumaid);
  667. if(!$objRequirement instanceof \Comercial\Entity\Requirement){
  668. $objProduct = $entityLuma->getRepository('\Luma\Entity\Produto')->find($lumaid);
  669. if(!$objProduct instanceof \Luma\Entity\Produto){
  670. throw new \Exception('Id produto inválido.');
  671. }
  672. $objRequirement = new \Comercial\Entity\Requirement();
  673. $objRequirement->setLumaId($lumaid);
  674. $objRequirement->setName(utf8_encode($objProduct->getProdNome()));
  675. $objRequirement->setUnit(utf8_encode($objProduct->getMediCodigoid()->getMediSigla()));
  676. $entityComercial->persist($objRequirement);
  677. }
  678. } elseif($lumaid[0]=='S') {
  679. $reqid = substr($lumaid, 1);
  680. $objRequirement = $entityComercial->getRepository('\Comercial\Entity\Requirement')->find($reqid);
  681. if(!$objRequirement instanceof \Comercial\Entity\Requirement){
  682. throw new \Exception('Id produto/serviço inválido.');
  683. }
  684. } else {
  685. throw new \Exception('Código inválido.');
  686. }
  687. $objValidate->set('Produto No '.($i+1), $objRequirement)->is_instance_of('\Comercial\Entity\Requirement');
  688. $quantidade = str_replace(array('.', ','), array('', '.'), $quantidades[$i]);
  689. $objValidate->set('Quantidade Produto No '.($i+1), $quantidade)->is_num()->min_value(0);
  690. $objViableRequirement->setQuantity($quantidade);
  691. $objViableRequirement->setRequirement($objRequirement);
  692. $objViableRequirement->setViable($objViable);
  693. $finalidade = empty($finalidades[$i]) ? 0 : $finalidades[$i];
  694. $objViableRequirement->setGoal($finalidade);
  695. $objViableRequirement->setGroup($objGrupo);
  696. $price = str_replace(array('.', ','), array('', '.'), $valores[$i]);
  697. $objViableRequirement->setPrice(number_format($price*$quantidade, 2, ',', ''));
  698. $entityComercial->persist($objViableRequirement);
  699. }
  700.  
  701. // Deleta do banco os produtos que foram removidos da viabilidade pela equipe de pré-vendas
  702. foreach ($arrayIdViableRequirementsForDelete as $idViableRequirement) {
  703. $objViableRequirementDelete = $entityComercial->getRepository('\Comercial\Entity\ViableRequirement')->find($idViableRequirement);
  704. $entityComercial->remove($objViableRequirementDelete);
  705. }
  706.  
  707. \Util\Util::getErrors($objValidate);
  708.  
  709. $entityComercial->flush();
  710. $entityComercial->commit();
  711.  
  712. // Tentará salvar apenas os serviços de terceiros adicionados pela equipe de pré-vendas. O que veio da Engenharia não sofrerá alterações
  713. $quantidades = array();
  714. $thirdService = array();
  715. for ($i = 0; $i <= count($_POST["servico"]); $i++) {
  716. if (isset($_POST["editavel"][$i]) && $_POST["editavel"][$i] == 'true') {
  717. $quantidades[] = $_POST["quantidadeServico"][$i];
  718. $thirdService[] = $_POST["servico"][$i];
  719. }
  720. }
  721.  
  722. $custos = array(
  723. "viable" => $_POST["viabilidade"],
  724. "quantity" => $quantidades,
  725. "thirdService" => $thirdService
  726. );
  727.  
  728. $cookie = '';
  729. $cookieName = \Util::getConfigSSO();
  730. if(is_array($_COOKIE)) {
  731. foreach($_COOKIE as $key => $value) {
  732. if($key == $cookieName['cookie_name']){
  733. $cookie = $key . '=' . $value . '; ';
  734. }
  735. }
  736. }
  737.  
  738. $curl = curl_init();
  739.  
  740. // USAR PARA DESENVOLVIMENTO SE USA DOCKER
  741. // curl_setopt($curl, CURLOPT_URL, "http://".$_SERVER['SERVER_ADDR']."/vogel/web/engenharia/terceiros/listarCustoServicos");
  742.  
  743. curl_setopt($curl, CURLOPT_URL, "http://".$_SERVER['HTTP_HOST']."/vogel/web/engenharia/terceiros/adicionar/salvarCustos");
  744. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  745. curl_setopt($curl, CURLOPT_POST, true);
  746. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($custos));
  747. curl_setopt($curl, CURLOPT_COOKIE, $cookie);
  748. $response = curl_exec($curl);
  749. curl_close($curl);
  750. $retorno = json_decode($response);
  751.  
  752. if($this->notificar($objViableApproval, true)){
  753. $retorno = array("msg"=> "Vinculado com Sucesso!", "error" => false);
  754. } else {
  755. $retorno = array("msg"=> utf8_encode("Viabilidade vinculada com sucesso, mas notificação não enviada."), "error" => false);
  756. }
  757.  
  758. $tags = $objViable->getChance()->getTags()->first();
  759.  
  760. // se foi uma viabilidade gerada pelo Vendas Online, enviar email de atualização de status
  761. if (is_object($tags) && $tags->getName() == 'gerada_web') {
  762. $objProspect = $entityComercial->getRepository('\Comercial\Entity\Prospect')->findOneBy(array(
  763. 'id' => $objViable->getChance()->getIdProspect(),
  764. )
  765. );
  766. $objCadUsers = $entityStech->getRepository('\Sistech\Entity\CadUsers')->find($objProspect->getIdCliente());
  767. $arrayEmail = $objCadUsers->getCadUsersEmail()->toArray();
  768. $objEmail = array_map(function($obj){
  769. if($obj->getPrincipal()) return $obj->getEmail();
  770. else return '';
  771. },$arrayEmail);
  772. $email = (count($objEmail)?implode('/',array_filter($objEmail)):$objCustomers->getEmail());
  773.  
  774. $objTipo = $entityLuma->getRepository("Luma\Entity\Tipo")->find(54);
  775.  
  776. // Adiciona email de confirmação a tabela de envios
  777. $objEmail = new \Luma\Entity\Email();
  778. $objEmail->setEmailAnexo(NULL);
  779. $objEmail->setEmailAssunto('Vogel Telecom - Status de solicitação de viabilidade atualizado!');
  780. $objEmail->setEmailBcc(NULL);
  781. $objEmail->setEmailCc(NULL);
  782. $objEmail->setEmailCorpo('O status da solicitação de sua viabilidade foi atualizado. Verificar em: https://at.vogeltelecom.com/vendas/');
  783. $objEmail->setEmailDataenvio(new \DateTime());
  784. $objEmail->setEmailDatainc(new \DateTime());
  785. $objEmail->setEmailDe('sistemas@vogeltelecom.com');
  786. $objEmail->setEmailIdoperacao(0);
  787. $objEmail->setEmailPagina('');
  788. $objEmail->setEmailPara($email);
  789. $objEmail->setEmailPrioridade(5);
  790. $objEmail->setEmailTipooperacao('insert');
  791. $objEmail->setTipoCodigoid($objTipo);
  792. $entityLuma->persist($objEmail);
  793. $entityLuma->flush();
  794. }
  795.  
  796. } catch (\Exception $e) {
  797. $entityComercial->rollback();
  798. $retorno = array("msg"=> nl2br(utf8_encode($e->getMessage())), "error" => true);
  799. }
  800. return JSON_encode($retorno);
  801. }
  802.  
  803. public function salvarLpu() {
  804.  
  805. try {
  806. // Permissão
  807. if($this->nivel & 2 != 2){
  808. throw new \Exception('Sem permissão para esta ação.', 403);
  809. }
  810. // Entidades
  811. $entityComercial = $this->getArrayParams('entityComercial');
  812. $entityPresale = $this->getArrayParams('entityPresale');
  813. $entityFinanceiro = $this->getArrayParams('entityFinanceiro');
  814. $entityStech = $this->getArrayParams('entityStech');
  815. $entityLuma = $this->getArrayParams('entityLuma');
  816. // Validador
  817. $objValidate = new \Util\Validate ();
  818. $objValidate->set('viabilidade', 'viabilidade')->is_parameter();
  819. $objValidate->set('Tempo', 'tempo')->is_parameter();
  820. $objValidate->set('Tempo', 'unidadeTempo')->is_parameter();
  821. $objValidate->set('SLA', 'porcentSla')->is_parameter();
  822. $objValidate->set('Observações', 'obs')->is_parameter()->is_required();
  823. $objValidate->set('Prazo Mínimo de Ativação', 'prazoAtivacao')->is_parameter()->is_integer();
  824.  
  825. // Valida viabilidade e aprovação
  826. $objViable = $entityComercial->getRepository('\Comercial\Entity\Viable')->find($_REQUEST['viabilidade']);
  827. if(!$objViable instanceof \Comercial\Entity\Viable || !in_array($objViable->getViableStatus()->getId(),array(3,9))){
  828. throw new \Exception('Foram encontratos problemas na viabilidade');
  829. }
  830.  
  831. $idServico = $objViable->getChance()->getIdProduct()->getId();
  832. if( !in_array($idServico,\Util\Param::$arrayServicosSemMeioAcesso)) {
  833. $objValidate->set('interface', $_REQUEST['interface'])->is_required();
  834. $objValidate->set('Total FO', $_REQUEST['totalFO'])->is_required()->is_integer();
  835. }
  836.  
  837. if(isset($_REQUEST['produto']) || isset($_REQUEST['quantidade']) || isset($_REQUEST['finalidade']) || isset($_REQUEST['valor'])){
  838. $produtos = $_REQUEST['produto'];
  839. $finalidades = $_REQUEST['finalidade'];
  840. $objValidate->set('Produtos', $produtos)->is_required()->is_arr();
  841. $quantidades = $_REQUEST['quantidade'];
  842. $objValidate->set('Quantidades de Produto', $quantidades)->is_required()->is_arr();
  843. $valores = $_REQUEST['valor'];
  844. $objValidate->set('Valores de Produto', $valores)->is_required()->is_arr();
  845. if (count($produtos) !== count($quantidades)) {
  846. throw new \Exception('Há produto ou quantidade não preenchida.');
  847. }
  848. } else {
  849. $produtos = $quantidades = array();
  850. }
  851.  
  852. $objViableApprovalTec = $entityComercial->getRepository('\Comercial\Entity\ViableApproval')->findOneBy(array(
  853. 'viable' => $objViable,
  854. 'prevViableStatus' => 2
  855. ));
  856. if($objViableApprovalTec instanceof \Comercial\Entity\ViableApproval && $objViableApprovalTec->getMinAtivationDays()){
  857. if(!isset($_REQUEST['prazoAtivacao']) || !$_REQUEST['prazoAtivacao']){
  858. throw new \Exception('O prazo de Ativação é obrigatório.');
  859. }
  860. elseif($_REQUEST['prazoAtivacao'] < $objViableApprovalTec->getMinAtivationDays()){
  861. throw new \Exception('O prazo de ativação não pode ser menor que '.$objViableApprovalTec->getMinAtivationDays().' dias, sugerido pela engenharia.');
  862. }
  863. }
  864.  
  865. // Serviço
  866. $idServiceComercial = $objViable->getChance()->getIdProduct()->getServicoContrato();
  867. $objService = $entityPresale->getRepository('Presale\Entity\Service')->findOneBy(array('servCodigoid'=>$idServiceComercial));
  868. // Deadline de contrato
  869. $contractDeadline = $_REQUEST['tempo'];
  870. $objValidate->set('Tempo', $contractDeadline)->is_required()->is_integer()->min_value(0);
  871. $unidadeDeadline = $_REQUEST['unidadeTempo'];
  872. $objValidate->set('Unidade Tempo', $unidadeDeadline)->is_required()->is_integer()->contains(array(1, 2));
  873. \Util\Util::getErrors($objValidate);
  874.  
  875. // Valida informações de velocidade de acordo com o plano
  876. if(!in_array($objService->getId(),\Util\Param::$arrayServicosSemVelocidadePresale)) {
  877. $objValidate->set('Velocidade', 'velocidade')->is_parameter();
  878. $objValidate->set('Tipo Velocidade', 'tipovelocidade')->is_parameter();
  879. $velocidades = $_REQUEST['velocidade'];
  880. $objValidate->set('Velocidades do Produto', $velocidades)->is_required()->is_arr();
  881. $tipovelocidades = $_REQUEST['tipovelocidade'];
  882. $objValidate->set('Tipos Velocidade do Produto', $tipovelocidades)->is_required()->is_arr();
  883. $objValidate->set('Valor Ativação', 'ativacao')->is_parameter();
  884. $objValidate->set('Valor Mensalidade', 'mensalidade')->is_parameter();
  885. $objValidate->set('Valor Mínimo', 'valorMinimo')->is_parameter();
  886. \Util\Util::getErrors($objValidate);
  887. $objValidate->set('viabilidade', $_REQUEST['viabilidade'])->is_required();
  888. $objValidate->set('Valor MÃínimo', 'valorMinimo')->is_required();
  889. $ativacoes = $_REQUEST['ativacao'];
  890. $objValidate->set('Valores Ativação do Produto', $ativacoes)->is_required()->is_arr();
  891. $mensalidades = $_REQUEST['mensalidade'];
  892. $objValidate->set('Mensalidades do Produto', $mensalidades)->is_required()->is_arr();
  893. if (count($velocidades) !== count($tipovelocidades) ||
  894. count($velocidades) !== count($ativacoes) ||
  895. count($velocidades) !== count($mensalidades)
  896. ) {
  897. throw new \Exception('Há velocidade(s) não preenchida(s).');
  898. }
  899. }
  900.  
  901. // Anexo BP (Business Planning)
  902. if(!isset($_FILES["anexoBP"]) || $_FILES["anexoBP"]["error"] != 0) {
  903. throw new \Exception("Selecione um arquivo .xls ou .xlsx");
  904. }
  905. $extensoesPermitidas = array("xls","xlsx");
  906. $extensao = end(explode(".",$_FILES["anexoBP"]["name"]));
  907. if(!in_array($extensao,$extensoesPermitidas)) {
  908. throw new \Exception("Extensão não permitida: ".$extensao);
  909. }
  910. $dir = "/mnt/dados/movi/viabilidade/".$_REQUEST['viabilidade'];
  911. if(!is_dir($dir)) {
  912. mkdir($dir, 0775);
  913. }
  914. if (!is_dir($dir . "/anexoBP")) {
  915. mkdir($dir . "/anexoBP", 0775);
  916. }
  917. if(!move_uploaded_file($_FILES["anexoBP"]["tmp_name"], $dir . "/anexoBP/".$_FILES["anexoBP"]["name"])){
  918. throw new \Exception("Erro ao enviar arquivo");
  919. }
  920.  
  921. // Características adicionadas para a LPU
  922. $caracteristicas = (isset($_REQUEST['caracteristicas'])?$_REQUEST['caracteristicas']:array());
  923. $ativacaoCaracteristicas = (isset($_REQUEST['ativacaoCaracteristicas'])?$_REQUEST['ativacaoCaracteristicas']:array());
  924. $mensalidadeCaracteristicas = (isset($_REQUEST['mensalidadeCaracteristicas'])?$_REQUEST['mensalidadeCaracteristicas']:array());
  925. $quantidadecaracteristicas = (isset($_REQUEST['quantidadeCaracteristicas'])?$_REQUEST['quantidadeCaracteristicas']:array());
  926. // Atributos obrigatorios foram preenchidos
  927. $arrayFeatureMandatory = array_filter(array_map(function($obj){
  928. if($obj->getMandatory()){
  929. return $obj;
  930. }
  931. return false;
  932. },$objService->getFeatures()->toArray()));
  933.  
  934. foreach ($arrayFeatureMandatory as $objFeatureMandatory){
  935. $arrayFeatureAttribute = array_filter(array_map(function($obj){
  936. if($obj->getDefaultSelected()){
  937. return $obj;
  938. }
  939. return false;
  940. },$objFeatureMandatory->getAttributes()->toArray()));
  941.  
  942. foreach ($arrayFeatureAttribute as $objFeatureAttribute){
  943. if(!in_array($objFeatureAttribute->getId(),$caracteristicas)){
  944. $nome = utf8_decode($objFeatureAttribute->getName());
  945. if (is_numeric($nome)) {
  946. $objAtrivalo = $entityFinanceiro->getRepository('Financeiro\Entity\Atributovalor')->find($nome);
  947. if($objAtrivalo instanceof \Financeiro\Entity\Atributovalor){
  948. $nome = $objAtrivalo->getAtrivaloValor();
  949. }
  950. }
  951. $objValidate->set(($nome?:utf8_decode($objFeatureMandatory->getName())), NULL)->is_required();
  952. }
  953. }
  954. }
  955.  
  956. \Util\Util::getErrors($objValidate);
  957.  
  958. // verifica se todos os atributos solicitados, na abertura da viabilidade, foram preenchidos
  959. if(count($objViable->getFeatures())){
  960. foreach ($objViable->getFeatures() as $objViableFeature){
  961. $objFeatureAttribute = $entityPresale->getRepository('Presale\Entity\FeatureAttribute')->find(
  962. $objViableFeature->getFeatureAttributeId()?:0
  963. );
  964. if(!$objFeatureAttribute instanceof \Presale\Entity\FeatureAttribute){
  965. throw new \Exception('Serviço adicional inválido.');
  966. }
  967. $objFeature = $objFeatureAttribute->getFeature();
  968. if(!in_array($objFeatureAttribute->getId(),$caracteristicas)){
  969. // Deve deixar obrigatório apenas a feature dos capilares para o produto FIBRA APAGADA
  970. if ($objService->getName() == "FIBRA APAGADA" && $objFeatureAttribute->getId() != self::FEATURE_ATRIBUTE_CAPILARES) {
  971. continue;
  972. }
  973. $nome = utf8_decode($objFeatureAttribute->getName());
  974. if (is_numeric($nome)) {
  975. $objAtrivalo = $entityFinanceiro->getRepository('Financeiro\Entity\Atributovalor')->find($nome);
  976. if($objAtrivalo instanceof \Financeiro\Entity\Atributovalor){
  977. $nome = $objAtrivalo->getAtrivaloValor();
  978. }
  979. }
  980. $objValidate->set(($nome?:utf8_decode($objFeature->getName())), NULL)->is_required();
  981. }
  982. }
  983. }
  984. // foreach (array_count_values($caracteristicas) as $key=>$val){
  985. // $objFeatureAttribute = $entityPresale->getRepository('Presale\Entity\FeatureAttribute')->find($key);
  986. // if(!$objFeatureAttribute instanceof \Presale\Entity\FeatureAttribute){
  987. // throw new \Exception('Serviço adicional inválido.');
  988. // }
  989. // $objFeature = $objFeatureAttribute->getFeature();
  990. // $nome = utf8_decode($objFeatureAttribute->getName());
  991. // if (is_numeric($nome)) {
  992. // $objAtrivalo = $entityFinanceiro->getRepository('Financeiro\Entity\Atributovalor')->find($nome);
  993. // if($objAtrivalo instanceof \Financeiro\Entity\Atributovalor){
  994. // $nome = $objAtrivalo->getAtrivaloValor();
  995. // }
  996. // }
  997. // $objValidate->set(($nome?:utf8_decode($objFeature->getName())), $val)->max_value(2);
  998. // }
  999. // \Util\Util::getErrors($objValidate);
  1000.  
  1001. $objViableApproval = $entityComercial->getRepository('\Comercial\Entity\ViableApproval')->findOneBy(array(
  1002. 'viable' => $objViable,
  1003. 'prevViableStatus' => 3,
  1004. ));
  1005.  
  1006. $entityComercial->beginTransaction();
  1007. if(!$objViableApproval instanceof \Comercial\Entity\ViableApproval){
  1008. $objViableApproval = new \Comercial\Entity\ViableApproval();
  1009. $objViableApproval->setDateRecord(new \DateTime());
  1010. $objViableApproval->setDeadlineApproval(new \DateTime());
  1011. $entityComercial->persist($objViableApproval);
  1012. $oldViableStatus = $objViable->getViableStatus();
  1013. $objViableApproval->setPrevViableStatus($oldViableStatus);
  1014. $objViableApproval->setViable($objViable);
  1015. }
  1016. $objViableApproval->setAuthor($_SESSION['id_user']);
  1017. $objViableApproval->setDateApproval(new \DateTime());
  1018. $objViableApproval->setAttachment($this->getUploadedName($objViableApproval));
  1019. $objViableApproval->setObs($_REQUEST['obs']);
  1020. $objViableApproval->setMinAtivationDays($_REQUEST['prazoAtivacao']?:NULL);
  1021.  
  1022. $tipoRede = $objViable->getNetworkType();
  1023. if(empty($tipoRede)){
  1024. if(empty($_REQUEST['tipoRede'])){
  1025. throw new \Exception('Selecione um tipo de rede.');
  1026. }
  1027. $objViable->setNetworkType($_REQUEST['tipoRede']);
  1028. $entityComercial->persist($objViable);
  1029. }
  1030.  
  1031. // Se for par (colocation) na ponta B grava uma aprovação igual a da Ponta A
  1032. if(!is_null($objViable->getPair())) {
  1033. $objViableApprovalPontaB = new \Comercial\Entity\ViableApproval();
  1034. $objViableApprovalPontaB->setDateRecord(new \DateTime());
  1035. $objViableApprovalPontaB->setDeadlineApproval(new \DateTime());
  1036. $objViableApprovalPontaB->setPrevViableStatus($objViable->getViableStatus());
  1037. $objViableApprovalPontaB->setViable($objViable->getPair());
  1038. $objViableApprovalPontaB->setMinAtivationDays($objViableApproval->getMinAtivationDays());
  1039. $objViableApprovalPontaB->setDateApproval($objViableApproval->getDateApproval());
  1040. $objViableApprovalPontaB->setAuthor($objViableApproval->getAuthor());
  1041. $objViableApprovalPontaB->setObs($objViableApproval->getObs());
  1042. $entityComercial->persist($objViableApprovalPontaB);
  1043. }
  1044.  
  1045. if($objViable->getChance()->getIdProduct()->getName() != "FIBRA APAGADA"){
  1046. // Verifica se houve alteração da engenharia no meio de acesso
  1047. if ($_REQUEST['meio'] != $objViable->getInterface() || $_REQUEST['interface'] != $objViable->getInterfaceReal()) {
  1048. $newViableStatus = $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(4);
  1049. $objViableOld= $objViable;
  1050. $objViableOld->setViableStatus($newViableStatus);
  1051. $objViableOld->setActive(false);
  1052. $objViable = new \Comercial\Entity\Viable();
  1053. $objViable->setPreviousViable($objViableOld);
  1054. $objViableOld->setNextViable($objViable);
  1055. $objViable->setActive(true);
  1056. $objViable->setAuthor($objViableOld->getAuthor());
  1057. $objViable->setCep($objViableOld->getCep());
  1058. $objViable->setChance($objViableOld->getChance());
  1059. $objViable->setCity($objViableOld->getCity());
  1060. $objViable->setComplement($objViableOld->getComplement());
  1061. $objViable->setContCodigoid($objViableOld->getContCodigoid());
  1062. $objViable->setDateRecord($objViableOld->getDateRecord());
  1063. $objViable->setDistrict($objViableOld->getDistrict());
  1064. $objViable->setHash($objViableOld->getHash());
  1065. $objViable->setInterface($_REQUEST['meio']);
  1066. $objViable->setInterfaceReal($_REQUEST['interface']);
  1067. $objViable->setLat($objViableOld->getLat());
  1068. $objViable->setLon($objViableOld->getLon());
  1069. $objViable->setNumber($objViableOld->getNumber());
  1070. $objViable->setPriceZone($objViableOld->getPriceZone());
  1071. $objViable->setSpeed($objViableOld->getSpeed());
  1072. $objViable->setSpeedType($objViableOld->getSpeedType());
  1073. $objViable->setSteet($objViableOld->getSteet());
  1074. $objViable->setUf($objViableOld->getUf());
  1075. $objViable->setViable(false);
  1076. foreach ($objViableOld->getFeatures() as $objViableFeatureOld){
  1077. $objViableFeature = new \Comercial\Entity\ViableFeature();
  1078. $objViableFeature->setFeatureattributeId($objViableFeatureOld->getFeatureattributeId());
  1079. $objViableFeature->setViable($objViable);
  1080. $entityComercial->persist($objViableFeature);
  1081. $objViable->addViableFeature($objViableFeature);
  1082. }
  1083. $entityComercial->persist($objViable);
  1084. }
  1085.  
  1086. $objService = $entityPresale->getRepository('\Presale\Entity\Service')->findOneByServCodigoid(
  1087. $objViable->getChance()->getIdProduct()->getServicoContrato()
  1088. );
  1089. if (!$objService instanceof \Presale\Entity\Service) {
  1090. throw new \Exceptio('Tipo de serviço não encontrado.');
  1091. }
  1092.  
  1093. if ($objService->getId() == self::SERVICO_IP_ISP && $objViable->getViable() === false && $objViable->getDeliveryPlace() == 'caixa') {
  1094. $objValidate->set('LAT', $_REQUEST['lat'])->is_required()->is_num();
  1095. $objValidate->set('LON', $_REQUEST['lon'])->is_required()->is_num();
  1096. \Util\Util::getErrors($objValidate);
  1097.  
  1098. $objViable->setLat($_REQUEST['lat']);
  1099. $objViable->setLon($_REQUEST['lon']);
  1100. }
  1101. }
  1102.  
  1103. if ($_REQUEST['totalFO'] != $objViable->getTotalFO()) {
  1104. $objViable->setTotalFO((int) $_REQUEST['totalFO']);
  1105. }
  1106.  
  1107. if(isset($_REQUEST['coordenadas'])){
  1108. $objViable->setCoords($_REQUEST['coordenadas']);
  1109. if($objViable->getPair()){
  1110. $objViable->getPair()->setCoords($_REQUEST['coordenadas']);
  1111. }
  1112. }
  1113.  
  1114. if (isset($_REQUEST['distancia']) || isset($_REQUEST['siglaDistancia'])) {
  1115. $distancia = $_REQUEST['distancia']?:0;
  1116. $siglaDistancia = $_REQUEST['siglaDistancia']?:'';
  1117. if($distancia || $siglaDistancia){
  1118. $objValidate->set('Distancia', $distancia)->is_required()->is_num()->min_value(0);
  1119. $objValidate->set('Distancia', $siglaDistancia)->is_required()->contains(array('km', 'm'));
  1120. $objViable->setFiberDistance($distancia);
  1121. $objViable->setFiberUnit($siglaDistancia);
  1122. if($objViable->getPair()){
  1123. $objViable->getPair()->setFiberDistance($distancia);
  1124. $objViable->getPair()->setFiberUnit($siglaDistancia);
  1125. }
  1126. }
  1127. }
  1128.  
  1129. $newViableStatus = $entityComercial->getRepository('\Comercial\Entity\ViableStatus')->find(6);
  1130. $objViable->setViableStatus($newViableStatus);
  1131. if($objViable->getPair()){
  1132. $objViable->getPair()->setViableStatus($newViableStatus);
  1133. }
  1134. $objViable->setViable(true);
  1135. if($objViable->getPair()) {
  1136. $objViable->getPair()->setViable(true);
  1137. }
  1138.  
  1139. if(isset($_REQUEST['prazoAtivacao'])){
  1140. $objViable->setDaysDeadline($_REQUEST['prazoAtivacao']);
  1141. if($objViable->getPair()) {
  1142. $objViable->getPair()->setDaysDeadline($_REQUEST['prazoAtivacao']);
  1143. }
  1144. }
  1145. $entityComercial->flush();
  1146.  
  1147. $objLpu = new \Presale\Entity\Lpu();
  1148. $objLpu->setActive(false);
  1149. $objLpu->setAuthor($_SESSION['id_user']);
  1150. $objLpu->setDateRecord(new \DateTime());
  1151. $objLpu->setDateValid(new \DateTime());
  1152. $objLpu->setDistance(0);
  1153. $objLpu->setMinContractDeadline($contractDeadline);
  1154. $objLpu->setMinContractUnit($unidadeDeadline);
  1155. $objLpu->setType(self::LPU_TIPO_PADRAO);
  1156. $objLpu->setName('AutoLpuApproval_'.str_pad($objViableApproval->getId(), 8, '0', STR_PAD_LEFT));
  1157. $valorMinimo = floatval(str_replace(',', '.', str_replace('.', '',$_POST["valorMinimo"])));
  1158. $objLpu->setMinimumPrice($valorMinimo);
  1159. $sla = str_replace(array('.', ','), array('', '.'), $_REQUEST['porcentSla']);
  1160. $objLpu->setSla(+$sla);
  1161. $entityPresale->beginTransaction();
  1162. $entityPresale->persist($objLpu);
  1163. $entityPresale->flush();
  1164. $objViable->setShadowLpuId($objLpu->getId());
  1165. if($objViable->getPair()) {
  1166. $objViable->getPair()->setShadowLpuId($objLpu->getId());
  1167. }
  1168.  
  1169. $entityComercial->persist($objViable);
  1170.  
  1171. $objMoviService = $objViable->getChance()->getIdProduct();
  1172. $objPresaleService = $entityPresale->getRepository('\Presale\Entity\Service')->findOneByServCodigoid($objMoviService->getServicoContrato());
  1173. if(!$objPresaleService instanceof \Presale\Entity\Service){
  1174. throw new \Exception('Serviço não cadastrado');
  1175. }
  1176. $objLpu->setService($objPresaleService);
  1177.  
  1178. if(!in_array($objService->getId(),\Util\Param::$arrayServicosSemVelocidadePresale)) {
  1179. $count = count($velocidades);
  1180. for ($i =0; $i < $count; ++$i){
  1181. $ativacao = str_replace(array('.', ','), array('', '.'), $ativacoes[$i]);
  1182. $mensalidade = str_replace(array('.', ','), array('', '.'), $mensalidades[$i]);
  1183. $velocidade = str_replace(array('.', ','), array('', '.'), $velocidades[$i]);
  1184. $tipovelocidade = str_replace(array('.', ','), array('', '.'), $tipovelocidades[$i]);
  1185. $objValidate->set('Ativação da velocidade '.($i+1), $ativacao)->is_integer();
  1186. $objValidate->set('Mensalidade da velocidade '.($i+1), $mensalidade)->is_integer();
  1187. if($objService->getServCodigoid()==17){ // Fibra apagada
  1188. $velocidade = 0;
  1189. $tipovelocidade = 2;
  1190. }else{
  1191. $objValidate->set('Velocidade '.($i+1), $velocidade)->is_integer()->min_value(0);
  1192. $objValidate->set('Tipo de Velocidade '.($i+1), $tipovelocidade)->is_integer()->min_value(0);
  1193. }
  1194. $objLpuVelocidade = new \Presale\Entity\Speed();
  1195. $objLpuVelocidade->setActivationFare($ativacao);
  1196. $objLpuVelocidade->setLpu($objLpu);
  1197. $objLpuVelocidade->setMonthlyCost($mensalidade);
  1198. $objLpuVelocidade->setSpeed($velocidade);
  1199. $objVelocidadeTipo = $entityPresale->getRepository('\Presale\Entity\SpeedType')->find($tipovelocidade);
  1200. $objValidate->set('Tipo de Velocidade '.($i+1), $objVelocidadeTipo)->is_instance_of('\Presale\Entity\SpeedType');
  1201. $objLpuVelocidade->setSpeedType($objVelocidadeTipo);
  1202. $entityPresale->persist($objLpuVelocidade);
  1203. }
  1204. }
  1205.  
  1206. foreach ($caracteristicas as $key=>$features){
  1207. $objFeatureAttribute = $entityPresale->getRepository('Presale\Entity\FeatureAttribute')->find($features);
  1208. if(!$objFeatureAttribute instanceof \Presale\Entity\FeatureAttribute){
  1209. throw new \Exception('Atributo da LPU inválido.');
  1210. }
  1211. $ativacaoCaracteristicas[$key] = (float)str_replace(',','.',str_replace('.','',$ativacaoCaracteristicas[$key]));
  1212. $mensalidadeCaracteristicas[$key] = (float)str_replace(',','.',str_replace('.','',$mensalidadeCaracteristicas[$key]));
  1213. $objLpuFeature = new \Presale\Entity\LpuFeature();
  1214. $objLpuFeature->setActivationFare($ativacaoCaracteristicas[$key]);
  1215. $objLpuFeature->setMonthlyCost($mensalidadeCaracteristicas[$key]);
  1216. $objLpuFeature->setDateRecord(new \DateTime());
  1217. $objLpuFeature->setLpu($objLpu);
  1218. $objLpuFeature->setDateValid($objLpu->getDateValid());
  1219. $objLpuFeature->setFeatureAttribute($objFeatureAttribute);
  1220. $objLpuFeature->setQuantity($quantidadecaracteristicas[$key]);
  1221. $entityPresale->persist($objLpuFeature);
  1222. }
  1223.  
  1224. $this->validaGrupoProdutoViabilidade($objViable, $_POST);
  1225.  
  1226. // Trata os casos em que a equipe de pré-vendas exclui algum produto que foi adicionado pela equipe de engenharia
  1227. $arrayObjViableRequirements = $entityComercial->getRepository('\Comercial\Entity\ViableRequirement')->findBy(array('viable' => $objViable));
  1228. $arrayIdViableRequirementsForDelete = array();
  1229. foreach ($arrayObjViableRequirements as $objViableRequirementExistente) {
  1230. $arrayIdViableRequirementsForDelete[] = $objViableRequirementExistente->getId();
  1231. }
  1232.  
  1233. // Produtos para viabilidade (grupos e produto avulso)
  1234. $count = count($produtos);
  1235. for ($i = 0; $i < $count; ++$i){
  1236. if (!empty($_REQUEST['idViableRequirement'][$i])) {
  1237. //Edição de um produto anteriormente adicionado pela equipe de Engenharia
  1238. $objViableRequirement = $entityComercial->getRepository('\Comercial\Entity\ViableRequirement')->find($_REQUEST['idViableRequirement'][$i]);
  1239.  
  1240. // Como este ViableRequirement foi mantido pela equipe de engenharia, remove da lista de exclusões
  1241. if (($chave = array_search($_REQUEST['idViableRequirement'][$i], $arrayIdViableRequirementsForDelete)) !== false) {
  1242. unset($arrayIdViableRequirementsForDelete[$chave]);
  1243. }
  1244. } else {
  1245. // Novo
  1246. $objViableRequirement = new \Comercial\Entity\ViableRequirement();
  1247. }
  1248. $lumaid = $produtos[$i];
  1249. $objGrupo = NULL;
  1250. $isGrupo = $lumaid[0]=='G';
  1251. if(is_numeric($lumaid) || $isGrupo){
  1252. if($isGrupo) {
  1253. $grip = substr($lumaid, 1);
  1254. $objGroupItem = $entityComercial->getRepository('\Comercial\Entity\GroupItem')->find($grip);
  1255. if(!$objGroupItem instanceof \Comercial\Entity\GroupItem){
  1256. throw new \Exception('Item de Grupo inválido.');
  1257. }
  1258. $lumaid = $objGroupItem->getProductLuma();
  1259. $objGrupo = $objGroupItem->getGroup();
  1260. }
  1261. $objRequirement = $entityComercial->getRepository('\Comercial\Entity\Requirement')->findOneByLumaId($lumaid);
  1262. if(!$objRequirement instanceof \Comercial\Entity\Requirement){
  1263. $objProduct = $entityLuma->getRepository('\Luma\Entity\Produto')->find($lumaid);
  1264. if(!$objProduct instanceof \Luma\Entity\Produto){
  1265. throw new \Exception('Id produto inválido.');
  1266. }
  1267. $objRequirement = new \Comercial\Entity\Requirement();
  1268. $objRequirement->setLumaId($lumaid);
  1269. $objRequirement->setName(utf8_encode($objProduct->getProdNome()));
  1270. $objRequirement->setUnit(utf8_encode($objProduct->getMediCodigoid()->getMediSigla()));
  1271. $entityComercial->persist($objRequirement);
  1272. }
  1273. } elseif($lumaid[0]=='S') {
  1274. $reqid = substr($lumaid, 1);
  1275. $objRequirement = $entityComercial->getRepository('\Comercial\Entity\Requirement')->find($reqid);
  1276. if(!$objRequirement instanceof \Comercial\Entity\Requirement){
  1277. throw new \Exception('Id produto/serviço inválido.');
  1278. }
  1279. } else {
  1280. throw new \Exception('Código inválido.');
  1281. }
  1282. $objValidate->set('Produto No '.($i+1), $objRequirement)->is_instance_of('\Comercial\Entity\Requirement');
  1283. $quantidade = str_replace(array('.', ','), array('', '.'), $quantidades[$i]);
  1284. $objValidate->set('Quantidade Produto No '.($i+1), $quantidade)->is_num()->min_value(0);
  1285. $objViableRequirement->setQuantity($quantidade);
  1286. $objViableRequirement->setRequirement($objRequirement);
  1287. $objViableRequirement->setViable($objViable);
  1288. $finalidade = empty($finalidades[$i]) ? 0 : $finalidades[$i];
  1289. $objViableRequirement->setGoal($finalidade);
  1290. $objViableRequirement->setGroup($objGrupo);
  1291. $price = str_replace(array('.', ','), array('', '.'), $valores[$i]);
  1292. $objViableRequirement->setPrice(number_format($price*$quantidade, 2, ',', ''));
  1293. $entityComercial->persist($objViableRequirement);
  1294. }
  1295.  
  1296. // Deleta do banco os produtos que foram removidos da viabilidade pela equipe de pré-vendas
  1297. foreach ($arrayIdViableRequirementsForDelete as $idViableRequirement) {
  1298. $objViableRequirementDelete = $entityComercial->getRepository('\Comercial\Entity\ViableRequirement')->find($idViableRequirement);
  1299. $entityComercial->remove($objViableRequirementDelete);
  1300. }
  1301.  
  1302. \Util\Util::getErrors($objValidate);
  1303.  
  1304. $entityComercial->flush();
  1305. $entityPresale->flush();
  1306. $entityComercial->commit();
  1307. $entityPresale->commit();
  1308.  
  1309. // Tentará salvar apenas os serviços de terceiros adicionados pela equipe de pré-vendas. O que veio da Engenharia não sofrerá alterações
  1310. $quantidades = array();
  1311. $thirdService = array();
  1312. for ($i = 0; $i <= count($_POST["servico"]); $i++) {
  1313. if (isset($_POST["editavel"][$i]) && $_POST["editavel"][$i] == 'true') {
  1314. $quantidades[] = $_POST["quantidadeServico"][$i];
  1315. $thirdService[] = $_POST["servico"][$i];
  1316. }
  1317. }
  1318.  
  1319. $custos = array(
  1320. "viable" => $_POST["viabilidade"],
  1321. "quantity" => $quantidades,
  1322. "thirdService" => $thirdService
  1323. );
  1324.  
  1325. $cookie = '';
  1326. $cookieName = \Util::getConfigSSO();
  1327. if(is_array($_COOKIE)) {
  1328. foreach($_COOKIE as $key => $value) {
  1329. if($key == $cookieName['cookie_name']){
  1330. $cookie = $key . '=' . $value . '; ';
  1331. }
  1332. }
  1333. }
  1334.  
  1335. $curl = curl_init();
  1336.  
  1337. // USAR PARA DESENVOLVIMENTO SE USA DOCKER
  1338. // curl_setopt($curl, CURLOPT_URL, "http://".$_SERVER['SERVER_ADDR']."/vogel/web/engenharia/terceiros/listarCustoServicos");
  1339.  
  1340. curl_setopt($curl, CURLOPT_URL, "http://".$_SERVER['HTTP_HOST']."/vogel/web/engenharia/terceiros/adicionar/salvarCustos");
  1341. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1342. curl_setopt($curl, CURLOPT_POST, true);
  1343. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($custos));
  1344. curl_setopt($curl, CURLOPT_COOKIE, $cookie);
  1345. $response = curl_exec($curl);
  1346. curl_close($curl);
  1347. $retorno = json_decode($response);
  1348.  
  1349. if($this->notificar($objViableApproval, true)){
  1350. $retorno = array("msg"=> "Sucesso!", "error" => false);
  1351. } else {
  1352. $retorno = array("msg"=> utf8_encode("Viabilidade alterada com sucesso, mas notificação não enviada."), "error" => false);
  1353. }
  1354.  
  1355. $tags = $objViable->getChance()->getTags()->first();
  1356. // se foi uma viabilidade gerada pelo Vendas Online, enviar email de atualiza��o de status
  1357. if (is_object($tags) && $tags->getName() == 'gerada_web') {
  1358. $objProspect = $entityComercial->getRepository('\Comercial\Entity\Prospect')->findOneBy(array(
  1359. 'id' => $objViable->getChance()->getIdProspect(),
  1360. )
  1361. );
  1362. $objCadUsers = $entityStech->getRepository('\Sistech\Entity\CadUsers')->find($objProspect->getIdCliente());
  1363. $arrayEmail = $objCadUsers->getCadUsersEmail()->toArray();
  1364. $objEmail = array_map(function($obj){
  1365. if($obj->getPrincipal()) return $obj->getEmail();
  1366. else return '';
  1367. },$arrayEmail);
  1368. $email = (count($objEmail)?implode('/',array_filter($objEmail)):$objCustomers->getEmail());
  1369.  
  1370. $objTipo = $entityLuma->getRepository("Luma\Entity\Tipo")->find(54);
  1371.  
  1372. // Adiciona email de confirma��o a tabela de envios
  1373. $objEmail = new \Luma\Entity\Email();
  1374. $objEmail->setEmailAnexo(NULL);
  1375. $objEmail->setEmailAssunto('Vogel Telecom - Status de solicitação de viabilidade atualizado!');
  1376. $objEmail->setEmailBcc(NULL);
  1377. $objEmail->setEmailCc(NULL);
  1378. $objEmail->setEmailCorpo('O status da solicitação de sua viabilidade foi atualizado. Verificar em: https://at.vogeltelecom.com/vendas/');
  1379. $objEmail->setEmailDataenvio(new \DateTime());
  1380. $objEmail->setEmailDatainc(new \DateTime());
  1381. $objEmail->setEmailDe('sistemas@vogeltelecom.com');
  1382. $objEmail->setEmailIdoperacao(0);
  1383. $objEmail->setEmailPagina('');
  1384. $objEmail->setEmailPara($email);
  1385. $objEmail->setEmailPrioridade(5);
  1386. $objEmail->setEmailTipooperacao('insert');
  1387. $objEmail->setTipoCodigoid($objTipo);
  1388. $entityLuma->persist($objEmail);
  1389. $entityLuma->flush();
  1390. }
  1391.  
  1392. } catch (\Exception $e) {
  1393.  
  1394. //$entityPresale->rollback();
  1395. //$entityComercial->rollback();
  1396. $retorno = array("msg"=> utf8_encode($e->getMessage()), "error" => true);
  1397. }
  1398. return json_encode($retorno);
  1399. }
  1400.  
  1401. private function notificar(\Comercial\Entity\ViableApproval $objViableApproval) {
  1402. try {
  1403. $entityLuma = $this->getArrayParams('entityLuma');
  1404. $entityStech = $this->getArrayParams('entityStech');
  1405. $entityRh = $this->getArrayParams('entityRh');
  1406. if(trim($objViableApproval->getObs())){
  1407. $motivo = "O motivo alegado foi: \"{$objViableApproval->getObs()}\".";
  1408. } else {
  1409. $motivo = '';
  1410. }
  1411. $objViable = $objViableApproval->getViable();
  1412. if($objViable->getViable()){
  1413. $resposta = "<span style='font-family: Dax-Bold !important; color:#669933;'>Aprovada</span>";
  1414. $tipo = 'Aprova��o';
  1415. }else {
  1416. $resposta = "<span style='font-family: Dax-Bold !important; color:#8C0D0B;'>Reprovada</span>";
  1417. $tipo = 'Rejei��o';
  1418. }
  1419. $lon = number_format($objViable->getLon(), 8);
  1420. $lat = number_format($objViable->getLat(), 8);
  1421. $cidade = $entityStech->getRepository('\Sistech\Entity\AdmCidades')->find($objViable->getCity())->getNome();
  1422. $street = utf8_decode($objViable->getSteet());
  1423. $viabilidade = "({$lat}, {$lon}) {$street}, {$objViable->getNumber()}, {$cidade}, {$objViable->getUf()}";
  1424. $assunto = "Resposta solicitação viabilidade {$viabilidade}";
  1425. $objAutusuario = $entityStech->getRepository('\Sistech\Entity\AutUsuarios')->findOneBy(array(
  1426. 'id' => $objViable->getAuthor(),
  1427. 'ativo' => true,
  1428. ));
  1429. if(!$objAutusuario instanceof \Sistech\Entity\AutUsuarios){
  1430. return false;
  1431. }
  1432.  
  1433. $objRhColaborador = $entityRh->getRepository("Rh\Entity\RhColaborador")->findOneBy(array('idAltUsuarioSistech' => $objAutusuario->getId()));
  1434. if($objRhColaborador instanceof \Rh\Entity\RhColaborador){
  1435. $arrayCadUsersEmail = $entityStech->getRepository("Sistech\Entity\CadUsersEmail")->findBy(array('cadUsers' => $objRhColaborador->getIdCadUserSistech()));
  1436. $objCadUserEmail = array_map(function (\Sistech\Entity\CadUsersEmail $objEmail){
  1437. if(preg_match("/vogeltelecom/", $objEmail->getEmail())){
  1438. return $objEmail->getEmail();
  1439. }
  1440. }, $arrayCadUsersEmail);
  1441.  
  1442. if($objCadUserEmail[0] instanceof \Sistech\Entity\CadUsersEmail){
  1443. $destinatario = $objCadUserEmail[0]->getEmail();
  1444. }else {
  1445. $destinatario = $arrayCadUsersEmail[0]->getEmail();
  1446. }
  1447. }
  1448.  
  1449. $criacao = $objViable->getDateRecord()->format('d/m/Y H:i');
  1450. $objChance = $objViable->getChance();
  1451. $objProspect = $objChance->getIdProspect();
  1452. $cliente = utf8_decode($objProspect->getClientName());
  1453. $objCadUsers = $entityStech->getRepository('\Sistech\Entity\CadUsers')->find($objProspect->getIdCliente());
  1454. if(!$objCadUsers instanceof \Sistech\Entity\CadUsers){
  1455. return false;
  1456. }
  1457. $cnpj = \Util\Util::formataCpfCnpj($objCadUsers->getCnpj()?:$objCadUsers->getCpf());
  1458. $chanceId = $objChance->getId();
  1459. $viabilidadeId = $objViable->getId();
  1460. $html = "A sua solicitação de viabilidade <a href='http://sistech.vogeltelecom.com/movi/proposta/listar/{$chanceId}#{$viabilidadeId}'>\"{$viabilidade}\"</a> para o prospect \"$cliente\" ({$cnpj})".
  1461. ", solicitada em {$criacao}, foi {$resposta}. $motivo";
  1462. \Util\Util::enviarEmail($entityLuma, $assunto, $html, 'sistemas@stech.net.br', $destinatario, '/prevenda/viabilidadeComercial/detalhar/', $objViableApproval->getId(), $tipo, 1);
  1463. return true;
  1464. } catch (Exception $e) {
  1465. return false;
  1466. }
  1467. }
  1468.  
  1469. public function downloadAnexo(){
  1470. try {
  1471. $diretorioAnexo = "/mnt/dados/movi/viabilidade/anexoprevenda/".$_REQUEST["id"];
  1472. $handler = scandir($diretorioAnexo);
  1473. foreach ($handler as $arquivo) {
  1474. if(in_array($arquivo,array(".",".."))){
  1475. continue;
  1476. }
  1477. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // some day in the past
  1478. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  1479. header("Content-type: application/x-download");
  1480. header("Content-Disposition: attachment; filename={$arquivo}");
  1481. return readfile($diretorioAnexo."/".$arquivo);
  1482. break;
  1483. }
  1484. } catch ( \Exception $ex ) {
  1485. throw new \Exception ( $ex->getMessage (), $ex->getCode () );
  1486. }
  1487. }
  1488.  
  1489. private function validaGrupoProdutoViabilidade(\Comercial\Entity\Viable $objViable, $postRequest)
  1490. {
  1491. $entityFinanceiro = $this->getArrayParams('entityFinanceiro');
  1492. $objService = $objViable->getChance()->getIdProduct();
  1493. $objServicoFinanceiro = $entityFinanceiro->getRepository('Financeiro\Entity\Servico')
  1494. ->find($objService->getServicoContrato());
  1495. $config = PrevendasConfig::getConfig();
  1496. $interfacesValidar = array(1, 2);
  1497. if (in_array($objServicoFinanceiro->getServApelido(), $config['servicos']) && (in_array($objViable->getInterfaceReal(), $interfacesValidar))) {
  1498. if ( isset($postRequest['id_grupo_sva']) && ((int)$postRequest['id_grupo_sva'])) {
  1499. // Valida e salva o grupo de produto
  1500. $curlPrevendas = new CurlPrevendas();
  1501. $result = $curlPrevendas->getGrupoProduto($_POST['id_grupo_sva']);
  1502. if ($result['status'] != 200) {
  1503. throw new \Exception('não foi possí­vel encontrar o Grupo de Produtos selecionado no sistema de prevendas.');
  1504. }
  1505. $objViable->setIdGroupSva($result['data']['id']);
  1506. }
  1507. }
  1508. }
  1509.  
  1510. private function getGrupoSva($servico, $viable)
  1511. {
  1512. $speed = $viable->getSpeed();
  1513. $entityPresale = $this->getArrayParams ( 'entityPresale' );
  1514. $speedType = $entityPresale->getRepository('\Presale\Entity\SpeedType')->find($viable->getSpeedType());
  1515. $params = array(
  1516. "interface" => utf8_encode(SVAParamParser::parseInterface($viable->getInterfaceReal())),
  1517. "meio_acesso" => utf8_encode(SVAParamParser::TRANSMISSAO_OPTICO),
  1518. "estado" => $viable->getUf(),
  1519. "velocidade" => SVAParamParser::parseVelocidade($speed, $speedType->getMultiplier()),
  1520. "servico" => $servico->getServApelido()
  1521. );
  1522. $curlPrevendas = new CurlPrevendas();
  1523. $data = $curlPrevendas->getGrupoSva($params);
  1524. if ($data['status'] == 200) {
  1525. return $data['data'];
  1526. } else {
  1527. return null;
  1528. }
  1529. }
  1530.  
  1531. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement