Você está na página 1de 43

<?

php
/**
* Classe PmpController
*
* Contém as Funções para Cadastro e Processamento do Plano Mestre de Produção
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*/
class PmpController extends AppController {

public $name = 'Pmp';


public $uses = 'Pmp';

/**
* 07.11.2019 - Raphael: Itens Calculados pelo PMP
*
* @var array
*/
private $itens = array();

/**
* 07.11.2019 - Raphael: Erros encontrados durante o processamento
*
* @var array
*/
private $erros = array();

/**
* Indica se o PMP em Elaboração possui itens atrasados
*
* @var boolean
*/
private $atraso = false;

/**
* Habilitação para testes (apenas usar na base teste)
*
* @var boolean
*/
private $habTeste = false;

/**
* Relação de produtos encontrados em estoque
*
* @var array
*/
private $itensEstoque = array();

/**
* Informações do PMP Elaborado
*
* @var array
*/
private $infoPmp = array();

/** 22.02.2021 - Raphael: beforeRender


*
* Exibe um alerta quando encontrar erros antes de renderizar
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
public function beforeRender(){
parent::beforeRender();
if(!empty($this->erros)){
$listaErros = "<ul>";
foreach($this->erros as $erro){
$listaErros .= '<li style="list-style: circle;">'.$erro."</li>";
}
$listaErros .= "</ul>";
$this->Session->setFlash($listaErros,"flash_alert");
$this->erros = array();
return $this->Redirect(array('action'=>'index'));
}
}

/** 07.11.2019 - Raphael: index


*
* Relação dos Documentos PMP Cadastrados
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
public function index(){
//die("PMP EM MANUTENÇÃO, POR FAVOR AGUARDE");
DataLib::bdConnect();
if($this->request->is("post")){
$this->acoes_pmp($this->request->data['form']);
}
$filtros = array(
'cod' => array('campo'=>'Z80_CODPMP','operador'=>'='),
'sit' =>
array('campo'=>'Z80_STATUS','operador'=>'in','value'=>'1,2,3,7,A'),
'dti' =>
array('campo'=>'Z80_EMISSA','operador'=>'>=','class'=>'data','label'=>'Data Emissão
Inicial'),
'dtf' =>
array('campo'=>'Z80_EMISSA','operador'=>'<=','class'=>'data','label'=>'Data Emissão
Final'),
'prj' => array('campo'=>'Z81_PROJET','operador'=>'='),
'edt' => array('campo'=>'Z81_TAREFA','operador'=>'LIKE'),
'prd' => array('campo'=>'Z81_PRODUT','operador'=>'LIKE'),
);
$strQuery = $this->Pmp->sql002();
$strBind[":DEL"] = "*";
$ações = array(
'vis' =>
array('titulo'=>'Visualizar','url'=>array('action'=>'visualizar_pmp'),'icone'=>'fas
fa-eye','cmp'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT')),
'apr' =>
array('titulo'=>'Aprovar','url'=>array('action'=>'aprovar_pmp'),'icone'=>'fas fa-
calendar-
check','cmp'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT'),'confirm'=>'Confirma a
Aprovação do PMP?','acaMrk'=>true),
'lib' => array('titulo'=>'Liberar Geração de
Ops','url'=>array('action'=>'liberar_ops'),'icone'=>'fas fa-arrow-circle-
right','cmp'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT'),'confirm'=>'Confirma a
Liberação do PMP?','acaMrk'=>true),
'sac' => array('titulo'=>'Sacramentar
Ops','url'=>array('action'=>'sacramentar_ops'),'icone'=>'fas fa-check-
circle','cmp'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT','Z80_NUMOP'),'confirm'=
>'Confirma a Operação?','acaMrk'=>true),
'exc' => array('titulo'=>'Excluir
PMP','url'=>array('action'=>'excluir_pmp'),'icone'=>'fas fa-
ban','cmp'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT'),'confirm'=>'Confirma a
Exclusão do PMP?','acaMrk'=>true),
);
$subMenu = array(
array('desc'=>'Monitoramento', 'controller'=>'pmp',
'action'=>'monitoramento'),
array('desc'=>'APS', 'controller'=>'aps', 'action'=>'index'),
array('desc'=>'MRP Fabricados', 'controller'=>'pmp',
'action'=>'mrp_fabricados'),
array('desc'=>'Acomp.PMP Estoque', 'controller'=>'pmp',
'action'=>'relatorio_utilizacao_estoque_pmp')
);
$cols = array('Z80_FILIAL', 'Z80_CODPMP', 'Z80_SEQLOT', 'Z80_EMISSA',
'Z80_OBS', 'Z80_NUMOP', 'Z80_STATUS', 'Z80_DESUSR');
$this->montarTabPad("SA2",$strQuery,$strBind," ORDER BY
Z80_CODPMP,Z80_SEQLOT ",$filtros,$subMenu,$ações,null,
$cols,true,array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT','Z80_NUMOP'));
$helpTbPad = array(
'O <b>Plano Mestre de Produção (PMP)</b> é um documento que tem por
objetivo armazenar todas as informações referentes ao uso dos recursos para
fabricação.',
'Rotina <b>Monitoramento</b>: Mostra os Projetos pendentes de
análise;',
'Rotina <b>APS</b>: Visualização e Manutenção da Carga Fabrica;',
'Rotina <b>MRP Fabricados</b>: Geração do Documento PMP;',
'Rotina <b>Acompanhamento PMP Estoque</b>: Controle do PMP Estoque.
Trata-se dos itens identicados em estoque, não sendo necessária a produção.',
'O Documento PMP Gerado é cadastrado com o status "Elaboração", em
seguida o mesmo deve ser aprovado pelo PCP e então enviado para geração das OPs.',
);
$this->set('helpTbPad',$helpTbPad);
$this->monitoramentos();
}

/** 05.10.2021 - Raphael: monitoramentos


*
* Monitoramentos do PMP
* Quando encontradas divergências, é emitido um alerta para o usuário
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
private function monitoramentos(){
$tbody = null;
$strQuery = $this->Pmp->sql019();
$stid = DataLib::bdQueryExecBind($strQuery);
while($item = DataLib::bdQueryFetch($stid,true)){
$tbody .= '<tr>';
$tbody .= '<td style="text-align:center;">'.
$item['AFJ_PROJET'].'</td>';
$tbody .= '<td style="text-align:center;">'.
$item['AFJ_TAREFA'].'</td>';
$tbody .= '<td style="text-align:center;">'.
$item['AFJ_COD'].'</td>';
$tbody .= '<td style="text-align:left;">'.$item['B1_DESC'].'</td>';
$tbody .= '<td style="text-align:center;">'.
$item['AFJ_QEMP'].'</td>';
$tbody .= '<td style="text-align:center;">'.$item['OPS'].'</td>';
$tbody .= '</tr>';
}
if(!empty($tbody)){
$table = '<h3>Ordens de Produção com Quantidade Superior ao
Projeto:</h3>';
$table .= '<table class="tb-fixed">';
$table .= '<thead>';
$table .= '<th>Projeto</th>';
$table .= '<th>Tarefa</th>';
$table .= '<th>Produto</th>';
$table .= '<th>Descrição</th>';
$table .= '<th>Qtde.Projeto</th>';
$table .= '<th>Ops</th>';
$table .= '</thead>';
$table .= '<tbody>';
$table .= $tbody;
$table .= '</tbody>';
$table .= '</table>';
$this->Session-
>setFlash($table,"flash_alert",array("title"=>"Monitoramentos"));
}
}

/** 07.01.2020 - Raphael: acoes_pmp


*
* Ações para os Planos Selecionados
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param array $form Formulário Recebido pela Função index
* @return void
*/
public function acoes_pmp($form){
//echo '<pre>';print_r($form); die();
$itens = array();
foreach($form["itens"] as $item){
if($item["mrk"] == "1"){
$itens[] = explode(",",$item["cod"]);
}
}
//echo '<pre>';print_r($itens); die();
switch($form["acao"]){
case "apr":
foreach($itens as $itm){
$this->aprovar_pmp($itm[0],$itm[1],$itm[2]);
}
break;
case "lib":
foreach($itens as $itm){
$this->liberar_ops($itm[0],$itm[1],$itm[2]);
}
break;
case "sac":
foreach($itens as $itm){
$this->sacramentar_ops($itm[0],$itm[1],$itm[2],$itm[3]);
}
break;
case "exc":
foreach($itens as $itm){
$this->excluir_pmp($itm[0],$itm[1],$itm[2]);
}
break;
}
}

/** 07.01.2020 - Raphael: liberar_ops


*
* - Altera a Situação do Lote para "Aguardando Exportação"
* - Condição necessária para que o CONPCP51 inclua as ordens no Protheus
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @return void
*/
public function liberar_ops($filPmp,$codPmp,$seqPmp){
DataLib::bdConnect();

$dados = array(
'Z80_STATUS' => '2'
);
$where = array(
'Z80_FILIAL' => array('=',$filPmp),
'Z80_CODPMP' => array('=',$codPmp),
'Z80_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("UPDATE","Z80010",$dados,
$where,null,false,true,false);

$dadosZbj = array(
'ZBJ_STATUS' => 'F'
);
$whereZbj = array(
'ZBJ_FILIAL' => array('=',$filPmp),
'ZBJ_CODPMP' => array('=',$codPmp),
'ZBJ_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("UPDATE","ZBJ010",$dadosZbj,
$whereZbj,null,false,true,false);
$this->erros[] = "PMP $codPmp-$seqPmp Liberado. Aguarde o Email de
Confirmação da Geração de Ops.";

//HoldLib::enviar_email("000065","PMP $codPmp
Liberado",false,"Atenção!!!");
}

/** 07.01.2020 - Raphael: aprovar_pmp


*
* - Altera a Situação do Lote para "Aprovado"
* - A partir deste status, não é possivel alterar as datas do PMP
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @return void
*/
public function aprovar_pmp($filPmp,$codPmp,$seqPmp){
DataLib::bdConnect();
$ret = $this->hasBlockPrd($filPmp,$codPmp,$seqPmp);
if($ret["ret"]){
foreach($ret["prds"] as $prd){
$codPrd = $prd["B1_COD"];
$desPrd = $prd["B1_DESC"];
$this->erros[] = "PMP $codPmp-$seqPmp <b>NÃO APROVADO</b>. O
Produto '$codPrd-$desPrd' encontra-se bloqueado";
}
return;
}
$dados = array(
'Z80_STATUS' => 'A'
);
$where = array(
'Z80_FILIAL' => array('=',$filPmp),
'Z80_CODPMP' => array('=',$codPmp),
'Z80_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("UPDATE","Z80010",$dados,
$where,null,false,true,false);
$this->erros[] = "PMP $codPmp-$seqPmp Aprovado. Não é mais permitido editar
as datas de previsão deste plano.";
}

/** 13.09.2021 - Raphael: hasBlockPrd


*
* Verifica se existem produtos bloquados na estrutura do lote de PMP
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @return array
*/
private function hasBlockPrd($filPmp,$codPmp,$seqPmp){
$ret = array(
'ret' => false,
'prds' => array()
);
$strQuery = $this->Pmp->sql018();
$strBind = array(
':FILPMP' => $filPmp,
':Z80_CODPMP' => $codPmp,
':Z80_SEQLOT' => $seqPmp,
);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while($item = DataLib::bdQueryFetch($stid,true)){
$ret["ret"] = true;
$ret['prds'][] = $item;
}
return $ret;
}

/** 07.11.2019 - Raphael: visualizar_pmp


*
* Visualização do Plano Mestre de Produção Criado
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @return void
*/
public function visualizar_pmp($filPmp,$codPmp,$seqPmp){
$tmpFil = $this->empFil;
$this->empFil = $filPmp;
DataLib::bdConnect();
$tabs = array(
'Z80' => array('DESC'=>'Ordens de Produção Previstas -
PMP','REL'=>'*'),
'Z81' => array('DESC'=>'Projetos Relacionados','REL'=>'*'),
'ZBJ' => array('DESC'=>'Roteiros de Operações das Ops
Previstas','REL'=>'*'),
'ZBK' => array('DESC'=>'Empenhos das Ordens de Produção
Previstas','REL'=>'*'),
);
$setores = ProtheusLib::getOptions("SHB010","HB_COD","HB_NOME");
$cmps = array(

"Z80_FILIAL" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Filial do Sistema
"Z80_CODPMP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Codigo Plano
"Z80_EMISSA" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true,"MASK"=>"data"),//Data Emissao
"Z80_CODUSR" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Codigo Usuario Protheus
"Z80_DESUSR" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Nome Usuario
"Z80_TIPO" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Tipo de Plano
"Z80_OBS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Observacoes
"Z80_SEG" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Segmento
"Z80_CLVL" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Classe Valor
"Z80_NUMOP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Nº Lote Op Gerada
"Z80_STATUS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Situação Plano
"Z80_SEQLOT" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Sequência Abertura Lote
"Z80_FABRIC" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Fabrica
"Z80_GRPAFA" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Fabrica
"Z80_SEQUEN" => array(
"OBG"=>"N",
"ACAO"=>"MOSTRAR",
'LINK'=>array(
'title'=>'Visualizar Detalhes do Produto',
'href'=>'/pmp/visualizar_sequencia',

'campos'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT','Z80_ITEM','Z80_SEQUEN')
)
),//Sequencia

"Z80_PRODUT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo Produto


"Z80_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao Produto
"Z80_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z80_UM" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Unidade Medida
"Z80_DATPRI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Previsao Inicial
"Z80_DATPRF" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Previsao Final
"Z80_USO" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tipo de Uso
"Z80_SETOR" => array("OBG"=>"N","ACAO"=>"MOSTRAR","LABEL"=>"Setor
Inicial","OPTIONS"=>$setores),//Setor Vigente
"Z80_COR_OP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"color"),//Cor Op

"Z80_IDCJTO" => array(


"OBG"=>"N",
"ACAO"=>"MOSTRAR",
'LINK'=>array(
'title'=>'Visualizar Detalhes do Produto',
'href'=>'/pmp/visualizar_conjunto',

'campos'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT','Z80_IDCJTO')
)
),//

"Z81_PROJET" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Projeto


"Z81_DESCPJ" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao Projeto
"Z81_REVISA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Revisao
"Z81_PRIEMB" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Prioridade
Embarque

"Z81_SEQUEN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia


"Z81_TAREFA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_DESCAFA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_PRODUT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z81_PAI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z81_CTRPAI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","OPTIONS"=>$setores),//Quantidade

"ZBJ_SEQUEN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia


"ZBJ_ROTEIR" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Roteiro
"ZBJ_OPERAC" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Operacao
"ZBJ_RECURS" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Recurso
"ZBJ_DESCRE" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Recurso
"ZBJ_TEMPOM" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"hhmmii"),//Tempo Operacao
"ZBJ_TEMPOS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"hhmmii"),//Setup
"ZBJ_MAOOBR" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Mao de Obra
"ZBJ_DATAIN" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Data Inicio
"ZBJ_HORAIN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Hora Inicio
"ZBJ_DATAFI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Data Fim
"ZBJ_HORAFI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Hora Fim
"ZBJ_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao

"ZBK_SEQUEN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia


"ZBK_COD" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo do Produto
"ZBK_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo do Produto
"ZBK_LOCAL" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Armazem
"ZBK_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"ZBK_UM" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"ZBK_SEQCHI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia Filho
"ZBK_ITMCHI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Item Filho

);
$strQuery = $this->Pmp->sql009();
$strBind = array(
':Z80_CODPMP' => $codPmp,
':Z80_SEQLOT' => $seqPmp
);
//$this->print_b($strQuery, $strBind);
$this->setFrm($tabs,$cmps,$strQuery,$strBind,"V");
$subMenu = array(
array('desc'=>'Planos Cadastrados', 'controller'=>'pmp',
'action'=>'index'),
array('desc'=>'Novo Plano', 'controller'=>'pmp',
'action'=>'mrp_fabricados'),
array('desc'=>'Gerar PDF', 'controller'=>'genericos',
'action'=>'gerar_pdf',$codPmp,0,"L"),
);
$this->set('inputs',$this->inputs);
$this->set('subMenu',$subMenu);
$this->empFil = $tmpFil;
}

/** 07.11.2019 - Raphael: visualizar_conjunto


*
* Visualização do Plano Mestre de Produção Criado
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @param string $codCjto Código do Conjunto
* @return void
*/
public function visualizar_conjunto($filPmp,$codPmp,$seqPmp,$codCjto){
$tmpFil = $this->empFil;
$this->empFil = $filPmp;
DataLib::bdConnect();
$tabs = array(
'Z80' => array('DESC'=>'Ordens de Produção Previstas -
PMP','REL'=>'*'),
'Z81' => array('DESC'=>'Projetos Relacionados','REL'=>'*'),
'ZBJ' => array('DESC'=>'Roteiros de Operações das Ops
Previstas','REL'=>'*'),
'ZBK' => array('DESC'=>'Empenhos das Ordens de Produção
Previstas','REL'=>'*'),
);
$setores = ProtheusLib::getOptions("SHB010","HB_COD","HB_NOME");
$cmps = array(

"Z80_FILIAL" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Filial do Sistema
"Z80_CODPMP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Codigo Plano
"Z80_EMISSA" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true,"MASK"=>"data"),//Data Emissao
"Z80_CODUSR" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Codigo Usuario Protheus
"Z80_DESUSR" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Nome Usuario
"Z80_TIPO" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Tipo de Plano
"Z80_OBS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Observacoes
"Z80_SEG" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Segmento
"Z80_CLVL" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Classe Valor
"Z80_NUMOP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Nº Lote Op Gerada
"Z80_STATUS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Situação Plano
"Z80_SEQLOT" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Sequência Abertura Lote
"Z80_FABRIC" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Fabrica
"Z80_GRPAFA" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Fabrica

"Z80_SEQUEN" => array(


"OBG"=>"N",
"ACAO"=>"MOSTRAR",
'LINK'=>array(
'title'=>'Visualizar Detalhes do Produto',
'href'=>'/pmp/visualizar_sequencia',

'campos'=>array('Z80_FILIAL','Z80_CODPMP','Z80_SEQLOT','Z80_ITEM','Z80_SEQUEN')
)
),//Sequencia

"Z80_PRODUT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo Produto


"Z80_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao Produto
"Z80_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z80_UM" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Unidade Medida
"Z80_DATPRI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Previsao Inicial
"Z80_DATPRF" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Previsao Final
"Z80_USO" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tipo de Uso
"Z80_SETOR" => array("OBG"=>"N","ACAO"=>"MOSTRAR","LABEL"=>"Setor
Inicial","OPTIONS"=>$setores),//Setor Vigente
"Z80_COR_OP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"color"),//Cor Op

"Z80_SEMANA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Previsao Final

"Z81_PROJET" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Projeto


"Z81_DESCPJ" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao Projeto
"Z81_REVISA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Revisao
"Z81_PRIEMB" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Prioridade
Embarque

"Z81_SEQUEN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia


"Z81_TAREFA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_DESCAFA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_PRODUT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z81_PAI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z81_CTRPAI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","OPTIONS"=>$setores),//Quantidade

"ZBJ_SEQUEN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia


"ZBJ_ROTEIR" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Roteiro
"ZBJ_OPERAC" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Operacao
"ZBJ_RECURS" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Recurso
"ZBJ_DESCRE" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Recurso
"ZBJ_TEMPOM" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"hhmmii"),//Tempo Operacao
"ZBJ_TEMPOS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"hhmmii"),//Setup
"ZBJ_MAOOBR" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Mao de Obra
"ZBJ_DATAIN" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Data Inicio
"ZBJ_HORAIN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Hora Inicio
"ZBJ_DATAFI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Data Fim
"ZBJ_HORAFI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Hora Fim
"ZBJ_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao

"ZBK_SEQUEN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia


"ZBK_COD" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo do Produto
"ZBK_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo do Produto
"ZBK_LOCAL" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Armazem
"ZBK_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"ZBK_UM" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"ZBK_SEQCHI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia Filho
"ZBK_ITMCHI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Item Filho

);
$where = " AND Z80_IDCJTO = :Z80_IDCJTO ";
$strQuery = $this->Pmp->sql009($where);
$strBind = array(
':Z80_CODPMP' => $codPmp,
':Z80_SEQLOT' => $seqPmp,
':Z80_IDCJTO' => $codCjto
);
//$this->print_b($strQuery, $strBind);
$this->setFrm($tabs,$cmps,$strQuery,$strBind,"V");
$subMenu = array(
array('desc'=>'Planos Cadastrados', 'controller'=>'pmp',
'action'=>'index'),
array('desc'=>'Novo Plano', 'controller'=>'pmp',
'action'=>'mrp_fabricados'),
array('desc'=>'Gerar PDF', 'controller'=>'genericos',
'action'=>'gerar_pdf',$codPmp,0,"L"),
);
$this->set('inputs',$this->inputs);
$this->set('subMenu',$subMenu);
$this->empFil = $tmpFil;
$this->Render('/Elements/form');
}

/** 28.10.2021 - Raphael: visualizar_sequencia


*
* Visualiza os detalhes de uma sequência do documento PMP
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @param string $item Item do Lote
* @param string $sequen Sequência do Lote
* @return void
*/
public function visualizar_sequencia($filPmp = "", $codPmp = "", $seqPmp = "",
$item = "", $sequen = ""){
$tmpFil = $this->empFil;
$this->empFil = $filPmp;
DataLib::bdConnect();
$tabs = array(
'Z80' => array('DESC'=>'Ordem de Produção Prevista - PMP','REL'=>'u'),
'Z81' => array('DESC'=>'Projetos Relacionados','REL'=>'*'),
'ZBJ' => array('DESC'=>'Roteiro de Operações','REL'=>'*'),
'ZBK' => array('DESC'=>'Empenhos Necessários','REL'=>'*'),
);
$setores = ProtheusLib::getOptions("SHB010","HB_COD","HB_NOME");
$cmps = array(

"Z80_FILIAL" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Filial do Sistema
"Z80_CODPMP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Codigo Plano
"Z80_EMISSA" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true,"MASK"=>"data"),//Data Emissao
"Z80_DESUSR" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Nome Usuario

"Z80_TIPO" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Tipo de Plano
"Z80_OBS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Observacoes
"Z80_NUMOP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Nº Lote Op Gerada
"Z80_STATUS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Situação Plano
"Z80_SEQLOT" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Sequência Abertura Lote
"Z80_FABRIC" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Fabrica
"Z80_GRPAFA" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","CABECALHO"=>true),//Fabrica
"Z80_SEQUEN" => array("OBG"=>"N", "ACAO"=>"MOSTRAR"),

"Z80_PRODUT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo Produto


"Z80_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao Produto
"Z80_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z80_UM" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Unidade Medida

"Z80_DATPRI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Previsao Inicial
"Z80_DATPRF" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Previsao Final
"Z80_USO" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tipo de Uso
"Z80_SETOR" => array("OBG"=>"N","ACAO"=>"MOSTRAR","LABEL"=>"Setor
Inicial","OPTIONS"=>$setores),//Setor Vigente

"Z80_COR_OP" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"color"),//Cor Op

"Z81_PROJET" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Projeto


"Z81_DESCPJ" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao Projeto
"Z81_REVISA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Revisao
"Z81_PRIEMB" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Prioridade
Embarque
"Z81_TAREFA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_DESCAFA" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Tarefa
"Z81_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z81_PAI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"Z81_CTRPAI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","OPTIONS"=>$setores),//Quantidade

"ZBJ_OPERAC" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Operacao


"ZBJ_RECURS" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Recurso
"ZBJ_DESCRE" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Recurso
"ZBJ_TEMPOM" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"hhmmii"),//Tempo Operacao
"ZBJ_TEMPOS" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"hhmmii"),//Setup
"ZBJ_MAOOBR" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Mao de Obra
"ZBJ_DATAIN" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Data Inicio
"ZBJ_HORAIN" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Hora Inicio
"ZBJ_DATAFI" =>
array("OBG"=>"N","ACAO"=>"MOSTRAR","MASK"=>"data"),//Data Fim
"ZBJ_HORAFI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Hora Fim
"ZBJ_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Descricao

"ZBK_COD" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo do Produto


"ZBK_DESCRI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Codigo do Produto
"ZBK_LOCAL" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Armazem
"ZBK_QUANT" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"ZBK_UM" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Quantidade
"ZBK_SEQCHI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Sequencia Filho
"ZBK_ITMCHI" => array("OBG"=>"N","ACAO"=>"MOSTRAR"),//Item Filho
);
$where = " AND Z80_ITEM = :Z80_ITEM AND Z80_SEQUEN = :Z80_SEQUEN ";
$strQuery = $this->Pmp->sql009($where);
$strBind = array(
':Z80_CODPMP' => $codPmp,
':Z80_SEQLOT' => $seqPmp,
':Z80_ITEM' => $item,
':Z80_SEQUEN' => $sequen,
);
$this->setFrm($tabs,$cmps,$strQuery,$strBind,"V");
$subMenu = array(
array('desc'=>'Planos Cadastrados', 'controller'=>'pmp',
'action'=>'index'),
array('desc'=>'Novo Plano', 'controller'=>'pmp',
'action'=>'mrp_fabricados'),
array('desc'=>'Gerar PDF', 'controller'=>'genericos',
'action'=>'gerar_pdf',$codPmp,0,"L"),
);
$this->set('inputs',$this->inputs);
$this->set('subMenu',$subMenu);
$this->empFil = $tmpFil;
}

/** 07.11.2019 - Raphael: sacramentar_ops


*
* Alterar as Ordens de Produção Previstas para Firmes
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @param string $numOp Número do Lote Gerado
* @return void
*/
public function sacramentar_ops($filPmp,$codPmp,$seqPmp,$numOp){
//Atualiza a Situação do Lote para "Firme"
DataLib::bdConnect();
$dados = array(
'C2_TPOP' => 'F'
);
$where = array(
'C2_FILIAL' => array('=',$filPmp),
'C2_NUM' => array('=',$numOp),
);
DataLib::montarComandoBind("UPDATE","SC2010",$dados,
$where,null,false,true,false);
//Atualiza o Status do PMP
$dados = array(
'Z80_STATUS' => '6'
);
$where = array(
'Z80_FILIAL' => array('=',$filPmp),
'Z80_CODPMP' => array('=',$codPmp),
'Z80_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("UPDATE","Z80010",$dados,
$where,null,false,true,false);
$this->erros[] = "Lote $numOp Sacramentado!";
}

/** 08.11.2019 - Raphael: excluir_pmp


*
* Exclui um documento de PMP Criado
* Esta função não exclui as Ordens de Produção geradas na SC2
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $filPmp Filial do Sistema
* @param string $codPmp Código do PMP
* @param string $seqPmp Sequência de Lote
* @return void
*/
public function excluir_pmp($filPmp,$codPmp,$seqPmp){
DataLib::bdConnect();

//Ordens de Produção Aglutinadas (Z80)


$where = array(
'Z80_FILIAL' => array('=',$filPmp),
'Z80_CODPMP' => array('=',$codPmp),
'Z80_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("DELETE","Z80010",null,
$where,null,true,true,false);

//Relacionamentos com Projetos (Z81)


$where = array(
'Z81_FILIAL' => array('=',$filPmp),
'Z81_CODPMP' => array('=',$codPmp),
'Z81_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("DELETE","Z81010",null,
$where,null,true,true,false);

//Relacionamentos com Projetos (ZBJ)


$dados = array(
'D_E_L_E_T_' => '*',
'ZBJ_ALTORI' => 'D'
);
$where = array(
'ZBJ_FILIAL' => array('=',$filPmp),
'ZBJ_CODPMP' => array('=',$codPmp),
'ZBJ_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("UPDATE","ZBJ010",$dados,
$where,null,true,true,false);

//Relacionamentos com Projetos (ZBK)


$where = array(
'ZBK_FILIAL' => array('=',$filPmp),
'ZBK_CODPMP' => array('=',$codPmp),
'ZBK_SEQLOT' => array('=',$seqPmp),
);
DataLib::montarComandoBind("DELETE","ZBK010",null,
$where,null,true,true,false);

$this->erros[] = "PMP $codPmp-$seqPmp Excluído";


$msg = HoldLib::$styleEmail;
$msg .= '<p>'.HoldLib::getSaudacao().'</p>';
$msg .= '<p>O Lote de PMP '.$codPmp.'/'.$seqPmp.' foi Cancelado.</p>';
$msg .= '<p>Data Emissão: '.date("d/m/Y H:i").'</p>';
$msg .= '<p>Usuário Emissor: '.$this->UserAuth->getUserName().'</p>';

$assunto = "[PMP][$codPmp][$seqPmp] Plano Mestre de Produção -


Cancelamento";
HoldLib::enviar_email("000010",$msg,true,$assunto);
}

/**********************************
Elaboração do Documento PMP
**********************************/

/** 23.10.2019 - Raphael: mrp_fabricados


*
* MRP para Abertura de Ordens de Produção
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
public function mrp_fabricados(){
$this->trocar_filial("0101");//Sempre estar conectado na matriz para gerar
o PMP
set_time_limit(0);
DataLib::bdConnect();
ProtheusLib::getUserCodProtheus();
$options = $this->getOptions();
$filtros = $this->getFiltros();
//ProtheusLib::consultaCalculoAndamento(" AND Z40_SITUA IN ('1','2') ");
//ProtheusLib::hasPmpElab();
if($this->request->is("post")){
$form = $this->request->data['gerar'];
$this->aglutinar($form);
$this->redirect(array('action'=>'index'));
} elseif(!empty($this->request->params['pass']) || !empty($this->request-
>query)){
$tratamento = HoldLib::parametros_filtros($filtros);
$con = $tratamento["con"];
//echo '<pre>'; print_r($con); die();
$filtros = $tratamento["filtro"];
$this->getOpsPrevistas($con);
if(!empty($this->itens)){
$keyDados = uniqid();
Cache::write($keyDados,$this->itens,'relatorios');
$this->set('itens',$this->itens);
$this->set('keyDados',$keyDados);
$codPmp =
ProtheusLib::getNextCod("Z80_CODPMP","Z80010","SUBSTR(Z80_CODPMP,1,2) =
'".date("y")."'",6);
$codPmp = $codPmp == "000001" ? date("y").'0001' : $codPmp;
$obsPmp = "";
if(isset($con["sem"]) && $con["sem"] != 't' && strlen($con["sem"])
== 6){
$obsPmp = "PLANEJAMENTO SEMANA ".substr($con["sem"],4,2);
}
$this->set('codPmp',$codPmp);
$this->set('obsPmp',$obsPmp);
} else {
echo $this->Session->setFlash("Não há dados para
Exibição","default",array("class"=>"msg-erro"));
}
}

$this->set('options',$options);
$this->set('filtros',$filtros);
}

/** 23.10.2019 - Raphael: getOptions


*
* Monta as Opções dos Filtros da Função "mrp_fabricados"
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
private function getOptions(){
$options['uso'] = array('1'=>'Cons.','2'=>'Exp.');
$options['opt'] = array(
'1' => 'Ocultar Produtos Kanban',
'2' => 'Mostrar Apenas Itens com Necessidade de Produção',
'3' => 'Mostrar Apenas Produtos sem Roteiro de Operações',
'4' => 'Considerar Itens em Estoque 51/31',
'5' => 'Mostrar Apenas Itens não Calculados'
);
$options['sit'] = array(
'0' => array('help'=>'[0] OP QUANTIDADE EXCENDENTE',
'leg'=> 'Qtde.Exc.' , 'style' => 'background-color:#000000;color:#fff;'),
'1' => array('help'=>'[1] SEPARADO 100%',
'leg'=> 'Sep.100%' , 'style' => 'background-color:#000000;color:#fff;'),
'2' => array('help'=>'[2] PMP ESTOQUE NÃO SEPARADO',
'leg'=> 'PMP Pend.' , 'style' => 'background-color:#000000;color:#fff;'),
'3' => array('help'=>'[3] EM PRODUÇÃO',
'leg'=> 'Em Produção' , 'style' => 'background-color:#0099FF;color:#fff;'),
'4' => array('help'=>'[4] EM PRODUÇÃO',
'leg'=> 'Em Produção' , 'style' => 'background-color:#0099FF;color:#fff;'),
'5' => array('help'=>'[5] PRODUÇÃO ENCERRADA',
'leg'=> 'Prod.Encer.' , 'style' => 'background-color:#000000;color:#fff;'),
'6' => array('help'=>'[6] NEC.PRODUÇÃO PARCIAL',
'leg'=> 'Gerar OP.' , 'style' => 'background-color:#339933;color:#fff;'),
'7' => array('help'=>'[7] PROD.ENCERRADA + PMP ESTOQUE NÃO SEPARADO',
'leg'=> 'Ag.Separ..' , 'style' => 'background-color:#000000;color:#fff;'),
'8' => array('help'=>'[8] PRODUZIDO PARCIAL',
'leg'=> 'Prod.Parcial' , 'style' => 'background-color:#000000;color:#fff;'),
'9' => array('help'=>'[9] SEPARADO PARCIAL',
'leg'=> 'Sep.Parcial' , 'style' => 'background-color:#000000;color:#fff;'),
'10' => array('help'=>'[10] PRODUZIR',
'leg'=> 'Gerar OP' , 'style' => 'background-color:#339933;color:#fff;'),
'11' => array('help'=>'[11] EM PRODUÇÃO',
'leg'=> 'Em Produção' , 'style' => 'background-color:#0099FF;color:#fff;'),
'12' => array('help'=>'[12] PRODUZIR',
'leg'=> 'Gerar OP' , 'style' => 'background-color:#339933;color:#fff;'),
'X' => array('help'=>'[X] NÃO CALCULADO',
'leg'=> 'N/C' , 'style' => 'background-color:#000000;color:#fff;'),
'ES' => array('help'=>'[ES] USA ESTOQUE',
'leg'=> 'Estoque' , 'style' => 'background-color:#FF9900;color:#fff;'),
'NE' => array('help'=>'[NE] SITUAÇÃO NÃO DEFINIDA',
'leg'=> 'N/E' , 'style' => 'background-color:#000000;color:#fff;'),
);
return $options;
}

/** 23.10.2019 - Raphael: getFiltros


*
* Monta as Filtros da Função "mrp_fabricados"
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
private function getFiltros(){
$options = $this->getOptions();
$filtros = array(
'0'=> array(
'descri' => 'FILTROS',
'show' => true,
'filtros' => array(
'prj' =>
array('label'=>'Projeto','type'=>'text','maxlength'=>10,'search'=>'projeto','destin
o'=>'filtrosPrj'),
'fas' => array('label'=>'Fase
Obra','type'=>'text','maxlength'=>2),
'edt' =>
array('label'=>'EDT','type'=>'text','maxlength'=>2),
'prc' => array('label'=>'Código Produto
Expedido','type'=>'text','maxlength'=>18),
'prd' => array('label'=>'Descrição Produto
Expedido','type'=>'text','maxlength'=>60),
'sem' => array('label'=>'Semana','type'=>'text','class'=>'mes-
ano','value'=>'t'),
'opt' =>
array('label'=>'Opções','type'=>'select','multiple'=>'checkbox','options'=>$options
['opt'],'value'=>'1,2,4')
)
)
);
return $filtros;
}

/** 23.10.2019 - Raphael: getOpsPrevistas


*
* Consulta Sql das Ordens de Produção Previstas
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param array $con Vetor com os Filtros Aplicados
* @return void
*/
private function getOpsPrevistas($con){
$opcSel = explode(",",$con["opt"]);
$usaEstoque = in_array("4",$opcSel) ? true : false;
$alerta = 'Informações do Documento em Elaboração:<hr>';
$ret = $this->montarConsultaSql($con);
$strQuery = $ret[0];
$strBind = $ret[1];
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while ($item = DataLib::bdQueryFetch($stid, true)) {
$key = $item["PROJETO"].$item["EDT"].$item["CODAFJ"]; //Chave do
Conjunto
//Verifica se o item encontra-se atrasado
if($item["Z41_DTFIM"] > $item["PREVISAO"]){
$this->atraso = true;
$item["ATRASADO"] = true;
} else {
$item["ATRASADO"] = false;
}
//Quando for necessário debugar o projeto desconsiderando ops abertas
if($this->habTeste && $_SERVER['SERVER_ADDR'] == '192.168.0.211'){
$item["QTD_PRODUZIR"] = $item["QUANT_AFJ"];
}
//Definição das variaveis
$item["KANBAN"] = empty($item["KANBAN"]) ? '1' : $item["KANBAN"];
//Item controlado?
$item["CODPAI"] = $item["PAI"];
$item["PAI"] = $item["PROJETO"].$item["EDT"].$item["PAI"];
$item["COD"] = $item["PROJETO"].$item["EDT"].$item["FILHO"];
$item["QTD_PRO"] = $item["QTD_PRODUZIR"];
$item["QTD_EST"] = 0;
$item["QTDES"][$item["MSFIL"]] = array("11"=>$item["QTD_PRODUZIR"]);
$keyFilho = $item["PROJETO"] . $item["EDT"] . $item["CODAFJ"] .
$item["CODPAI"] . $item["NIVEL"] . $item["FILHO"] . $item["ITEM"];
$this->itens[$key][$keyFilho] = $item;
//Quando Existir Estoque, salva a quantidade do Armazem no Vetor para
ser usado no próximo foreach
if($item["QTD_SOBRA"] > 0 && !isset($this->itensEstoque[$item["FILHO"]]
[$item["B2_FILIAL"]][$item["B2_LOCAL"]])){
$this->itensEstoque[$item["FILHO"]][$item["B2_FILIAL"]]
[$item["B2_LOCAL"]] = $item["QTD_SOBRA"];
}
}
if(!empty($this->itens)){
$this->tratamentoElaboracao($usaEstoque); //Tratamento dos itens
encontrados
//Construção da Mensagem de retorno para o usuário
foreach($this->infoPmp as $in){
$alerta .= "Destino: <b>".$in["descri"]."</b><br>";
$alerta .= "Qtde.Ops: ".$in["qtde_ops"]." - Peso Total:
".HoldLib::numberFormat($in["peso_ops_exp"])." kg.<br>";
$alerta .= "Qtde.PMP Estoque: ".$in["qtde_est"]." - Peso Total:
".HoldLib::numberFormat($in["peso_est_exp"])." kg.";
if(!$this->atraso){
$alerta .= '<br><span style="background-color: red;color:
white;padding: 5px;">O Simulador identificou itens onde a data de finalização da
produção não atende a data de entrega do Projeto. Verifique os itens
destacados.</span><br>';
}
$alerta .= "<hr>";
}
$this->set('atraso', $this->atraso);
} else {
$alerta = "Nenhum item encontrado.<br><br>Verifique os filtros
aplicados e tente novamente.";
}
$this->Session->setFlash($alerta, "flash_alert",array("title"=>"Plano
Mestre de Produção"));
}
/** 10.11.2021 - Raphael: tratamentoElaboracao
*
* ### Tratamento do MRP Fabricados
* - Verifica itens não calculados
* - Verifica peças em estoque
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param boolean $usaEstoque
* @return void
*/
private function tratamentoElaboracao($usaEstoque = false){
//Varre as Estruturas ,caso um dos item do conjunto não for calculado, todo
o conjunto é bloqueado
if(!$this->habTeste){
foreach($this->itens as $key => $produtos){
$produzir = true;
foreach($produtos as $cod => $info){
if(empty($info["Z41_ID"])){ //Se não Encontrar o ID do Cálculo
do Simulador
$this->itens[$key][$cod]["RESULTADO"] = "X";
$produzir = false;
}
}
if(!$produzir){
foreach($produtos as $cod => $info){
$this->itens[$key][$cod]["RESULTADO"] = "X";
}
}
}
}
//Varre todos os CONJUNTOS encontrados
foreach($this->itens as $key => $produtos){
//Varre todos os produtos do conjunto encontrado
//Nesta etapa os produtos não são aglutinados
foreach($produtos as $num => $info){
$filOrd = $info["MSFIL"]; //Filial onde o equipamento é produzido
$cod = $info["FILHO"]; //Código do Produto
if($info["RESULTADO"] == "X"){ //Itens não calculados tem suas
quantidades zeradas
$this->itens[$key][$num]["QTD_PRO"] = 0;
$this->itens[$key][$num]["QTD_EST"] = 0;
continue;
}
//Montagem do resumo final do calculo
if(!isset($this->infoPmp[$filOrd])){
$this->infoPmp[$filOrd] = array(
'descri' => null,
'qtde_ops' => null,
'peso_ops_exp' => null,
'qtde_est' => null,
'peso_est_exp' => null,
);
$this->infoPmp[$filOrd]["descri"] = $filOrd == "0102" ?
"Fabrica 02 (Filial Citvel)" : "Fabrica 01 (Matriz)";
}
//Verifica se o material possui saldo em estoque
if(isset($this->itensEstoque[$cod][$filOrd]) && $usaEstoque ===
true){
$this->infoPmp[$filOrd]["qtde_est"]++;
$this->infoPmp[$filOrd]["peso_est_exp"] += $info["USO"] ==
"2" ? $info["PESO"] : 0;
$qtdPro = $this->itens[$key][$num]["QTD_PRO"];
foreach($this->itensEstoque[$cod] as $filEst => $armazens){
foreach($armazens as $arm => $qtdArm){
$qtdEst = $this->itensEstoque[$cod][$filEst][$arm];
if($qtdPro > 0 && $qtdEst > 0){
if($this->itens[$key][$num]["QTD_PMP_ESTOQUE"] > 0)
{
$qtdPro = $qtdPro - $this->itens[$key][$num]
["QTD_PMP_ESTOQUE"];
}
if($qtdPro > 0){
if($qtdEst >= $qtdPro){
$usaEst = $qtdPro;
$qtdPro = 0;
$this->itens[$key][$num]["QTDES"][$filOrd]
["11"] = 0;
$this->itens[$key][$num]["QTDES"][$filEst]
[$arm] = $usaEst;
} elseif($qtdEst < $info["QTD_PRO"]){
$usaEst = $qtdEst;
$qtdPro = $qtdPro-$qtdEst;
$this->itens[$key][$num]["QTDES"][$filOrd]
["11"] = $qtdPro;
$this->itens[$key][$num]["QTDES"][$filEst]
[$arm] = $usaEst;
}
if($usaEst > 0){
$this->itens[$key][$num]["RESULTADO"] =
"ES";
$this->itens[$key][$num]["QTD_PMP_ESTOQUE"]
+= $usaEst;
$this->itens[$key][$num]["QTD_EST"] +=
$usaEst;
$this->itens[$key][$num]["QTD_PRO"] -=
$usaEst;
$this->itensEstoque[$cod][$filEst][$arm] =
$qtdEst - $usaEst;
}
}
$this->ajustar_quantidade_filhos($key,$this-
>itens[$key][$num]["COD"],$qtdPro,$arm,$filEst);
}
}
}
} elseif($this->itens[$key][$num]["QTD_PRO"] > 0) {
$this->itens[$key][$num]["QTDES"][$filOrd]["11"] = $this-
>itens[$key][$num]["QTD_PRO"];
}
if($this->itens[$key][$num]["QTD_PRO"] > 0) {
$this->infoPmp[$filOrd]["qtde_ops"]++;
$this->infoPmp[$filOrd]["peso_ops_exp"] += $info["USO"] ==
"2" ? $info["PESO"] : 0;
$this->itens[$key][$num]["RESULTADO"] = "12";
}
}
}
}

/** 27.10.2021 - Raphael: montarConsultaSql


*
* Retorna o SQL utilizado na função "getOpsPrevistas"
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param array $con
* @return void
*/
private function montarConsultaSql($con = array()){
$strBind = array(
':DEL' => '*',
':B2_LOCAL' => '51',
':B2_LOCAL2' => '31',
);

$wherePrj = null;
$whereAll = " WHERE 1=1 ";

if($con["sem"] != 't'){ //Projeto


$strBind[":SEMANA"] = $con["sem"];
$wherePrj .= " AND
TO_CHAR(TO_DATE(TRIM(AF9_FINISH),'YYYYMMDD'),'YYYYIW') = :SEMANA ";
}

if($con["prj"] != 't'){ //Projeto


$strBind[":PROJETO"] = $con["prj"];
$wherePrj .= " AND AF8_PROJET = :PROJETO ";
} else {
$wherePrj .= " AND AF8_FASE = '02' ";
}
if($con["fas"] != 't'){ //Fase
$strBind[":FASE"] = $con["fas"];
$wherePrj .= " AND AFC_X_FASE = :FASE ";
}
if($con["edt"] != 't'){ //EDT
$strBind[":EDT"] = $con["edt"];
$wherePrj .= " AND AFC_EDT = :EDT ";
} else {
$wherePrj .= " AND AF9_DTATUF = ' ' ";
}
if($con["prc"] != 't'){ //Código do Produto Expedido
$strBind[":AFJ_COD"] = $con["prc"];
$wherePrj .= " AND AFJ_COD = :AFJ_COD ";
}
if($con["prd"] != 't'){ //Descrição do Produto Expedido
$strBind[":DESCAFJ"] = '%'.$con["prd"].'%';
$wherePrj .= " AND SB1.B1_DESC LIKE :DESCAFJ ";
}

$opcSel = explode(",",$con["opt"]);

if(in_array("1",$opcSel)){
$wherePrj .= " AND SB1.B1_X_ESTOQ != '2' ";
$whereAll .= " AND KANBAN != '2' ";
}
if(in_array("2",$opcSel)){
$whereAll .= " AND QTD_PRODUZIR > 0 ";
}
if(in_array("3",$opcSel)){
$whereAll .= " AND G2_PRODUTO IS NULL ";
}
if(in_array("5",$opcSel)){
$whereAll .= " AND Z41_ID IS NULL ";
}

$equi0102 = ProtheusLib::getZx6("000038",true);

$strQuery = $this->Pmp->sql003($wherePrj,$whereAll,$equi0102);
$ret = array($strQuery,$strBind);
return $ret;
}

/** 08.11.2019 - Raphael: ajustar_quantidade_filhos


*
* Ajusta a quantidade das Ops Filhas no caso de produção parcial da op pai
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $key Chave do Item
* @param string $pai Item Pai
* @param string $qtd Quantidade
* @param string $arm Armazém
* @return void
*/
private function ajustar_quantidade_filhos($key,$pai,$qtd,$arm,$filEst){
foreach($this->itens[$key] as $num => $info){
$codPai = $this->itens[$key][$num]["COD"];
if($info["PAI"] == $pai && $info["PAI"] != $info["COD"]){
$newPrd = $info["QTD_UN"] * $qtd;
$this->itens[$key][$num]["RESULTADO"] = "ES";
$this->itens[$key][$num]["QTD_PRO"] = $newPrd;
$this->itens[$key][$num]["QTD_EST"] = 0;
$this->itens[$key][$num]["QTDES"][$filEst]["11"] = $newPrd;
$this->ajustar_quantidade_filhos($key,$codPai,$newPrd,$arm,
$filEst);
}
}
}

/** 23.10.2019 - Raphael: aglutinar


*
* Aglutina os itens antes de salvar no BD
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param array $form Formulário Recebido da View mrp_fabricados
* @return void
*/
private function aglutinar($form){
set_time_limit(0); //Remove o tempo limite do PMP
ProtheusLib::hasPmpElab(); //Verifica se existe outro PMP em elaboração
$keyDados = $form["keyDados"]; //Chave do Cache gravado
$pmp = Cache::read($keyDados,'relatorios'); //Cache do Calculo
$numeroOp = array(); //Guarda o número da op prevista para determinada
chave de produto
$itens = array(); //Controle da quantidade de itens de cada lote (para os
casos onde o lote ultrapassa 999 ops)
$sequencias = array(); //Controle das sequências de cada lote
$descLote = array(); //Informações do Lote Previsto
$lotes = array(); //Lotes Previstos
$preview = array(); //Estrutura dos Lotes Previstos (Apenas para
Conferência durante o DEBUG)
$seqLot = 0; //Controle da numeração de cada lote do PMP
//Varre todos os conjuntos encontrados
foreach($pmp as $estrutura){
//Varre todos os produtos encontrados em cada conjuntos
foreach($estrutura as $item){
//Ignora itens não calculados pelo simulador de produção (falta de
roteiro SG2)
if($item["RESULTADO"] == "X"){
continue;
}
//Separação dos Lotes por Equipamento e Prioridade
if($form["slt"] == "1"){
$grp = substr($item["GRUPO"],0,2);
$pri = !empty($item["AFJ_X_PRIO"]) ? $item["AFJ_X_PRIO"] :
"001";
if($form["agl"] == "2") { //Aglutina os itens do mesmo
projeto,código do produto e tipo de uso
$pri = $item["PROJETO"].'-'.$pri;
}
} elseif($form["slt"] == "2") {
$grp = 'unico';
$pri = 'unico';
}
//Aglutinador
foreach($item["QTDES"] as $fil => $armazens){
foreach($armazens as $arm => $qtd){
$tp = $arm == "11" ? "1" : "2"; //Tipo de Lote =>
1=Produzir,2=Material em Estoque
//Chave do Lote
if($tp == "2"){
$lote = $fil."-".$tp;
} else {
$lote = $fil."-".$tp."-".$grp."-".$pri;
}
if($qtd > 0){
if($form["agl"] == "1"){ //Aglutina os itens do mesmo
produto e tipo de uso
$key = $item["FILHO"].'-'.$item["USO"];
} elseif($form["agl"] == "2") { //Aglutina os itens do
mesmo projeto,código do produto e tipo de uso
$key = $item["PROJETO"].$item["FILHO"].'-'.
$item["USO"];
}
//06.08.2021 - Raphael: Não aglutina as Ops que possuem
motores/redutores/motoredutores
if($item["QTDE_MOTOR"] > 0 && $item["USO"] == "2"){
$key = $item["PROJETO"].$item["EDT"].
$item["FILHO"].'-'.$item["USO"];
} else {
$key = !empty($item["CODPAI"]) && $tp == "2" &&
$item["USO"] == "1" ? $item["CODPAI"].'-'.$key : $key;
}
//Definição dos futuros lotes
if(!isset($sequencias[$lote])){
$seqLot++;
$descLote[$lote]["ARMAZEM"] = $arm;
$descLote[$lote]["FILIAL"] = $fil;
$descLote[$lote]["DESC"] = $lote;
$descLote[$lote]["TIPO"] = $tp;
$descLote[$lote]["SEQUENCIA"] =
str_pad($seqLot,2,'0',STR_PAD_LEFT);
$sequencias[$lote] = 0;
$itens[$lote] = 1;
}
//Define o item e sequência de cada produto em cada
lote
if(!isset($lotes[$lote][$key])){
$sequencias[$lote]++;
if($sequencias[$lote] > 999){
$itens[$lote]++;
$sequencias[$lote] = 1;
}
$item["ITEM_OP"] =
str_pad($itens[$lote],2,'0',STR_PAD_LEFT);
$item["SEQUEN_OP"] =
str_pad($sequencias[$lote],3,'0',STR_PAD_LEFT);
$item["NUMERO_OP"] = $item["ITEM_OP"].
$item["SEQUEN_OP"];
$numeroOp[$item["COD"]] = $item["NUMERO_OP"];
$item["QUANT"] = $qtd;
$lotes[$lote][$key] = $item;
$preview[$lote][$key] = $item["NUMERO_OP"];
} else {
if($lotes[$lote][$key]['AFJ_X_PRIO'] >
$item["AFJ_X_PRIO"]){
$lotes[$lote][$key]['AFJ_X_PRIO'] =
$item["AFJ_X_PRIO"];
}
$lotes[$lote][$key]['QUANT'] += $qtd;
$lotes[$lote][$key]['QTDES'][$fil][$arm] += $qtd;
}
$numeroOp[$item["COD"]] = $lotes[$lote][$key]
["NUMERO_OP"];
$lotes[$lote][$key]['QTDES_DET'][] = $qtd;
$lotes[$lote][$key]['PAIS'][] = $item["PAI"];
$lotes[$lote][$key]['projetos'][] = $item;
}
}
}
}
}
if(empty($lotes)){
$this->Session->setFlash("Nenhum Documento foi Gerado. Verifique se
todos os itens estão liberados para produção.","default",array("class"=>"msg-
erro"));
return;
}
$codPla = $form["cod"];
if(!empty($lotes)){
$this->gerar_plano_mestre_producao($form,$lotes,$numeroOp,$descLote);
$this->notificar_utilizacao_estoque($codPla);
$this->Session->setFlash("Plano Mestre <b>$codPla</b> Cadastrado. PMP
aguardando Aprovação.","default",array("class"=>"msg-sucesso"));
} else {
$this->Session->setFlash("Plano Mestre <b>não Cadastrado</b>. Não foram
encontradas Ações para Cadastro","default",array("class"=>"msg-alerta"));
}
}

/** 23.10.2019 - Raphael: gerar_plano_mestre_producao


*
* Cadastra o Plano Mestre de Produção
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param array $form Cabeçalho do Cadastro do Lote
* @param array $exp Itens do Cadastro
* @return void
*/
private function gerar_plano_mestre_producao($form,$lotes,$numeroOp,$descLote){
$codPla = $form["cod"];
$emissa = date("Ymd");
$codUsrPrt = ProtheusLib::getUserCodProtheus();
foreach($descLote as $l => $infoLote){
$produtos = $lotes[$l];
$filial = $infoLote["FILIAL"];
$tipo = $infoLote["TIPO"];
$seqLote = $infoLote["SEQUENCIA"];
$arm = $infoLote["ARMAZEM"];
$status = $tipo == "2" ? "5" : "1";
foreach($produtos as $infPrd){
//Ordens de Produção Previstas
$insZ80 = array(
'Z80_FILIAL' => $filial,
'Z80_CODPMP' => $codPla,
'Z80_EMISSA' => $emissa,
'Z80_CODUSR' => $codUsrPrt,
'Z80_TIPO' => $tipo,
'Z80_ITEM' => $infPrd["ITEM_OP"],
'Z80_SEQUEN' => $infPrd["SEQUEN_OP"],
'Z80_PRODUT' => $infPrd["FILHO"],
'Z80_QUANT' => $infPrd["QTDES"][$filial][$arm],
'Z80_QTDORI' => $infPrd["QTDES"][$filial][$arm],
'Z80_NIVEL' => empty($infPrd["NIVEL"]) ? '00' :
str_pad($infPrd["NIVEL"],2,'0',STR_PAD_LEFT),
'Z80_USO' => $infPrd["USO"],
'Z80_LOCAL' => $arm,
'Z80_OBS' => strtoupper($form["obs"]),
'Z80_SEG' => '0001',
'Z80_CLVL' => '10010',
'Z80_FABRIC' => substr($filial,2,2),
'Z80_STATUS' => $status,
'Z80_PRIEMB' => $infPrd["AFJ_X_PRIO"],
'Z80_CODPAI' => $infPrd["CODPAI"],
'Z80_IDAGRP' => $infPrd["Z41_ID"],
'Z80_SITSEP' => 'P',
'Z80_SEQLOT' => $seqLote,
'Z80_GRPAFA' => $infPrd["GRUPO"],
'Z80_IDCJTO' => $infPrd["CONJUNTO"],
'Z80_ROTEIR' => '01',
);
DataLib::montarComandoBind("INSERT","Z80010",
$insZ80,null,null,false,true,false,true);
//Relacionamento das Ordens de Produção Previstas
foreach($infPrd["projetos"] as $prj){
$insZ81 = array(
'Z81_FILIAL' => $filial,
'Z81_CODPMP' => $codPla,
'Z81_TIPO' => $tipo,
'Z81_ITEM' => $infPrd["ITEM_OP"],
'Z81_SEQUEN' => $infPrd["SEQUEN_OP"],
'Z81_PROJET' => $prj["PROJETO"],
'Z81_REVISA' => $prj["REVISA"],
'Z81_TAREFA' => $prj["TARPRD"],
'Z81_QUANT' => $prj["QTDES"][$filial][$arm],
'Z81_QTDORI' => $prj["QTDES"][$filial][$arm],
'Z81_PRODUT' => $infPrd["FILHO"],
'Z81_USO' => $infPrd["USO"],
'Z81_PRIEMB' => $prj["AFJ_X_PRIO"],
'Z81_CODPAI' => $prj["CODPAI"],
'Z81_LOCAL' => $arm,
'Z81_SEQLOT' => $seqLote,
'Z81_SITSEP' => 'P',
'Z81_PAI' => isset($numeroOp[$prj["PAI"]]) ?
$numeroOp[$prj["PAI"]] : " ",
);
DataLib::montarComandoBind("INSERT","Z81010",
$insZ81,null,null,false,true,false,true);
}
}
}
//Após o cadastro das ops e projetos, inicia-se o cadastro das operações e
empenhos e ajuste dos lotes
$this->cadastroOperacoes($codPla);
$this->setDataFim($codPla);
$this->updateSetorPai($codPla);
$this->setCorPmp($codPla);
$this->cadastroEmpenhos($codPla);
}

/** 12.05.2021 - Raphael: cadastroOperacoes


*
* Cadastra as Operações da Ordem de Produção
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $codPmp Código do PMP
* @return void
*/
private function cadastroOperacoes($codPmp){
$strQuery = $this->Pmp->sql010();
$strBind = array(":Z80_CODPMP"=>$codPmp);
//$this->print_b($strQuery, $strBind);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while($item = DataLib::bdQueryFetch($stid,true)){
$dados = array(
"ZBJ_FILIAL" => $item["ZBJ_FILIAL"],// [C][4] Filial do Sistema
"ZBJ_CODPMP" => $item["ZBJ_CODPMP"],// [C][6] PMP
"ZBJ_SEQUEN" => $item["ZBJ_SEQUEN"],// [C][2] Sequencia
"ZBJ_ITEM" => $item["ZBJ_ITEM"],// [C][3] Item
"ZBJ_SEQLOT" => $item["ZBJ_SEQLOT"],// [C][2] Seq.PMP
"ZBJ_ROTEIR" => $item["ZBJ_ROTEIR"],// [C][2] Roteiro
"ZBJ_OPERAC" => $item["ZBJ_OPERAC"],// [C][2] Operacao
"ZBJ_RECURS" => $item["ZBJ_RECURS"],// [C][6] Recurso
"ZBJ_FERRAM" => $item["ZBJ_FERRAM"],// [C][6] Ferramenta
"ZBJ_CTRAB" => $item["ZBJ_CTRAB"],// [C][6] Centro de Trabalho
"ZBJ_TEMPOM" => round($item["ZBJ_TEMPOM"],10),// [N][11] Tempo
Operacao
"ZBJ_TEMPOS" => round($item["ZBJ_TEMPOS"],10),// [N][11] Setup
"ZBJ_MAOOBR" => $item["ZBJ_MAOOBR"],// [N][2] Mao de Obra
"ZBJ_DATAIN" => $item["ZBJ_DATAIN"],// [D][8] Data Inicio
"ZBJ_HORAIN" => $item["ZBJ_HORAIN"],// [C][8] Hora Inicio
"ZBJ_DATAFI" => $item["ZBJ_DATAFI"],// [D][8] Data Fim
"ZBJ_HORAFI" => $item["ZBJ_HORAFI"],// [C][8] Hora Fim
"ZBJ_DESCRI" => $item["ZBJ_DESCRI"],// [C][20] Descricao
"ZBJ_QUANT" => $item["ZBJ_QUANT"],// [C][20] Descricao
"ZBJ_DTIORI" => $item["ZBJ_DATAIN"],// [D][8] Data Inicio Orignal
"ZBJ_DTFORI" => $item["ZBJ_DATAFI"],// [D][8] Data Fim Orignal
"ZBJ_STATUS" => "1",// [D][8] Status
"ZBJ_IDCJTO" => $item["ZBJ_IDCJTO"],// [D][8] Status
"ZBJ_NVCJTO" => $item["ZBJ_NVCJTO"],// [D][8] Status
"ZBJ_ALTORI" => 'O',// [D][8] Inf.Original
"ZBJ_USRALT" => $this->UserAuth->getUserName(),// [D][8] Usuario
"ZBJ_SEMALO" => $item["ZBJ_SEMALO"],// [D][8] Status
);
DataLib::montarComandoBind("INSERT","ZBJ010",
$dados,null,null,false,true,false);
}
}

/** 12.05.2021 - Raphael: setDataFim


*
* Define a Data de Inicio, Fim e Setor Inicial da OP
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $codPmp Código do PMP
* @return void
*/
private function setDataFim($codPmp){
$strQuery = $this->Pmp->sql012();
$strBind = array(":ZBJ_CODPMP"=>$codPmp);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while($item = DataLib::bdQueryFetch($stid,true)){
$dados = array(
"Z80_DATPRI" => $item["ZBJ_DATAIN"], //Data de Inicio
"Z80_DATPRF" => $item["ZBJ_DATAFI"], //Data de Finalização
"Z80_DTIORI" => $item["ZBJ_DATAIN"], //Data de Inicio Original
"Z80_DTFORI" => $item["ZBJ_DATAFI"], //Data de Finalização Original
"Z80_SETOR" => $item["ZBJ_CTRAB"],
"Z80_SEMALO" => $item["ZBJ_SEMALO"],
);
$where = array(
"Z80_FILIAL" => array("=",$item["ZBJ_FILIAL"]),
"Z80_CODPMP" => array("=",$item["ZBJ_CODPMP"]),
"Z80_SEQLOT" => array("=",$item["ZBJ_SEQLOT"]),
"Z80_ITEM" => array("=",$item["ZBJ_ITEM"]),
"Z80_SEQUEN" => array("=",$item["ZBJ_SEQUEN"]),
);
DataLib::montarComandoBind("UPDATE","Z80010",$dados,
$where,null,false,true,false);
}
}

/** 28.10.2021 - Raphael: updateSetorPai


*
* - Atualiza o campo do setor de destino da op consumida (Z81_CTRPAI)
* - O campo será replicado na tabela Z59 durante o processamento das Ordens de
Produção (CONPCP51)
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $codPmp Código do PMP
* @return void
*/
private function updateSetorPai($codPmp = ""){
$strQuery = $this->Pmp->sql020();
$strBind = array(":Z81_CODPMP"=>$codPmp);
DataLib::bdQueryExecBind($strQuery,$strBind);
}

/** 12.05.2021 - Raphael: setCorPmp


*
* Define a Cor da Ordem de produção
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $codPmp Código do PMP
* @return void
*/
private function setCorPmp($codPmp){
$strQuery = $this->Pmp->sql013();
$strBind = array(":Z80_CODPMP"=>$codPmp);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while($item = DataLib::bdQueryFetch($stid,true)){
$dados = array(
"Z80_COR_OP" => "#".$item["COR"]
);
$where = array(
"R_E_C_N_O_" => array("=",$item["Z80REC"])
);
DataLib::montarComandoBind("UPDATE","Z80010",$dados,
$where,null,false,true,false);
}
}

/** 12.05.2021 - Raphael: cadastroEmpenhos


*
* Cadastra os Empenhos que serão usados pelas Ordens de Produção (SD4)
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $codPmp Código do PMP
* @return void
*/
private function cadastroEmpenhos($codPmp){
//Retorna a relação dos itens consumidos
$cons = $this->getPmpConsumido($codPmp);

$strQuery = $this->Pmp->sql011();
$strBind = array(":Z80_CODPMP"=>$codPmp);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while($item = DataLib::bdQueryFetch($stid,true)){
$dados = array(
"ZBK_FILIAL" => $item["ZBK_FILIAL"],// [C][4] Filial do Sistema
"ZBK_CODPMP" => $item["ZBK_CODPMP"],// [C][6] PMP
"ZBK_SEQUEN" => $item["ZBK_SEQUEN"],// [C][2] Sequencia
"ZBK_ITEM" => $item["ZBK_ITEM"],// [C][3] Item
"ZBK_SEQLOT" => $item["ZBK_SEQLOT"],// [C][2] Seq.PMP
"ZBK_COD" => $item["ZBK_COD"],// [C][18] Codigo do Produto
"ZBK_LOCAL" => $item["ZBK_LOCAL"],// [C][4] Armazem
"ZBK_QUANT" => $item["ZBK_QUANT"],// [N][12] Quantidade
);
if(isset($cons[$item["ZBK_SEQLOT"]][$item["ZBK_COD"]])){
foreach($cons[$item["ZBK_SEQLOT"]][$item["ZBK_COD"]] as $arm =>
$infArm){
if($infArm["QTDE"] >= $item["ZBK_QUANT"]){
$dados["ZBK_LOCAL"] = $arm;
$dados["ZBK_ITMCHI"] = $infArm["ITEM"];
$dados["ZBK_SEQCHI"] = $infArm["SEQUEN"];
break;
}
}
}
DataLib::montarComandoBind("INSERT","ZBK010",
$dados,null,null,false,true,false);
}
}

/** 14.05.2021 - Raphael: getPmpConsumido


*
* Retorna a relação de itens consumidos do PMP
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $codPmp Código do PMP
* @return array
*/
private function getPmpConsumido($codPmp){
$strQuery = $this->Pmp->sql016();
$strBind = array(":Z80_CODPMP"=>$codPmp);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
$itens = array();
while($item = DataLib::bdQueryFetch($stid,true)){
$itens[$item["Z80_SEQLOT"]][$item["Z80_PRODUT"]][$item["Z80_LOCAL"]]
['SEQUEN'] = $item["Z80_SEQUEN"];
$itens[$item["Z80_SEQLOT"]][$item["Z80_PRODUT"]][$item["Z80_LOCAL"]]
['ITEM'] = $item["Z80_ITEM"];
$itens[$item["Z80_SEQLOT"]][$item["Z80_PRODUT"]][$item["Z80_LOCAL"]]
['QTDE'] = $item["Z80_QUANT"];
}
return $itens;
}

/** 23.10.2019 - Raphael: notificar_utilizacao_estoque


*
* Notifica os Usuários Sobre a Utilização do Estoque
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $codPla Código do Plano
* @return void
*/
private function notificar_utilizacao_estoque($codPla){
DataLib::bdConnect();
$strQuery = $this->Pmp->sql004();
$strBind = array(
':DEL' => '*',
':Z80_CODPMP' => $codPla,
':Z80_TIPO' => '2',
);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while($item = DataLib::bdQueryFetch($stid,true)){
$itens[$item["Z81_FILIAL"]][$item["Z81_LOCAL"]][] = $item;
}
$uso = array('1'=>'Consumido','2'=>'Expedido');
if(!empty($itens)){
$table = null;
foreach($itens as $fil => $armazens){
$table .= '<h1>FABRICA '.substr($fil,2,2).'</h1>';
foreach($armazens as $arm => $produtos){
$table .= '<h2>Armazém: '.$arm.'</h2>';
$table .= '<table>';
$table .= '<thead>';
$table .= '<tr></tr>';
$table .= '<th>Item</th>';
$table .= '<th>Projeto</th>';
$table .= '<th>Cliente</th>';
$table .= '<th>EDT</th>';
$table .= '<th>Código</th>';
$table .= '<th>Descrição</th>';
$table .= '<th>Qtde.Estoque</th>';
$table .= '<th>Tipo de Uso</th>';
$table .= '</tr>';
$table .= '</thead>';
$table .= '<tbody>';
$n = 1;
foreach($produtos as $item){
$table .= '<tr>';
$table .= '<td style="text-align:center;">'.
$n.'</td>';
$table .= '<td style="text-align:center;">'.
$item["Z81_PROJET"].'</td>';
$table .= '<td style="text-align:left;">'.
$item["AF8_DESCRI"].'</td>';
$table .= '<td style="text-
align:center;">'.substr($item["Z81_TAREFA"],0,2).'</td>';
$table .= '<td style="text-align:center;">'.
$item["Z81_PRODUT"].'</td>';
$table .= '<td style="text-align:left;">'.
$item["B1_DESC"].'</td>';
$table .= '<td style="text-align:center;">'.
$item["Z81_QUANT"].'</td>';
$table .= '<td style="text-align:center;'.
($item["Z81_USO"] == '2' ? 'font-weight:bold;' : '').'">'.
$uso[$item["Z81_USO"]].'</td>';
$table .= '</tr>';
$n++;
}
$table .= '</tbody>';
$table .= '</table>';
}
$table .= '<hr>';
}
$msg = HoldLib::$styleEmail;
$msg .= '<p>'.HoldLib::getSaudacao().'</p>';
$msg .= '<p>A Rotina "Plano Mestre de Produção" encontrou produtos
disponíveis em Estoque.</p>';
$msg .= $table;
$msg .= '<p>Procedimentos para confirmar a Utilização do Estoque:</p>';
$msg .= '<p><b>Itens Expedidos</b>: Providenciar Criação das Etiquetas
e Volumes das Peças.</p>';
$msg .= '<p><b>Itens Consumidos</b>: Utilizar a Rotina de Preparação
para Controle.</p>';
$msg .= '<p>Caso encontre divergências, entre em contato com o
Departamento de PCP.</p>';
$msg .= '<p>Data Emissão: '.date("d/m/Y H:i").'</p>';
$msg .= '<p>Usuário Emissor: '.$this->UserAuth->getUserName().'</p>';
$assunto = "[PMP][$codPla] Plano Mestre de Produção - Itens em
Estoque";
HoldLib::enviar_email("000010",$msg,true,$assunto);
}
}

/**********************************
Análise da Utilização do Estoque no PMP
**********************************/

/** 21.11.2019 - Raphael: relatorio_utilizacao_estoque_pmp


*
* Relatório para Gestão dos Itens Cadastrados como Estoque no PMP
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
public function relatorio_utilizacao_estoque_pmp(){
DataLib::bdConnect();
$options['uso'] = array('1'=>'Consumido','2'=>'Expedido');
$options['sit'] = ProtheusLib::getCboxZx3("Z81_SITSEP");
$options['rep'] = array('1'=>'Tabela','2'=>'Imagens');
$options["arm"] = array("31"=>"Armazém 31","51"=>"Armazém 51");
$optAcab['#'] = '- Selecione -';
$optAcab += ProtheusLib::getCboxZx3("Z81_ENTREG");
//echo '<pre>'; print_r($optAcab); die();
$tpRel = 'Escolha se deseja exibir apenas uma <b>tabela normal</b> de
listagem de itens, ou um painel com as <b>imagens</b> das peças.';
$filtros = array(
'0'=> array(
'descri' => 'FILTROS',
'show' => true,
'filtros' => array(
'pmp' => array('label'=>'Código
PMP','type'=>'text','maxlength'=>'6'),
'dat' => array('label'=>'Data Criação
PMP','type'=>'text','class'=>'data'),
'prj' =>
array('label'=>'Projeto','type'=>'text','maxlength'=>'10'),
'fas' =>
array('label'=>'Fase','type'=>'text','maxlength'=>'2'),
'edt' => array('label'=>'EDT','type'=>'text','maxlength'=>'2'),
'prd' => array('label'=>'Código
Produto','type'=>'text','maxlength'=>'18'),
'uso' => array('label'=>'Tipo de
Uso','type'=>'select','options'=>$options['uso'],'multiple'=>'checkbox','value'=>'1
,2'),
'arm' =>
array('label'=>'Armazéns','type'=>'select','options'=>$options['arm'],'multiple'=>'
checkbox','value'=>'31,51'),
'sit' => array('label'=>'Situação
Separação','type'=>'select','multiple'=>'checkbox','options'=>$options['sit'],'valu
e'=>'P'),
'dti' => array('label'=>'Data Previsão
de','type'=>'text','class'=>'data'),
'dtf' => array('label'=>'Data Previsão
até','type'=>'text','class'=>'data'),
'rep' => array('label'=>'Tipo de
Relatório','type'=>'select','value'=>'1','options'=>$options['rep'],'titulo_ajuda'=
>'Tipo de Relatório','ajuda'=>$tpRel),
'dsp' => array('label'=>'Data
Separação','type'=>'text','class'=>'data'),
)
)
);

if(!empty($this->request->params['pass']) || !empty($this->request->query))
{
$tratamento = HoldLib::parametros_filtros($filtros);
$con = $tratamento["con"];
//echo '<pre>'; print_r($con); die;
$filtros = $tratamento["filtro"];
$itens = $this->con_relatorio_utilizacao_estoque_pmp($con);
//echo '<pre>'; print_r($itens); die;
if(!empty($itens)){
$this->set('itens',$itens);
$this->set('con',$con);
$this->set('options',$options);
} else {
echo $this->Session->setFlash("Não há dados para
exibição!","default",array("class"=>"msg-erro"));
}
}
$this->set('filtros',$filtros);
$this->set('optAcab',$optAcab);

/** 21.11.2019 - Raphael: con_relatorio_utilizacao_estoque_pmp


*
* Tratamento Consulta SQL - relatorio_utilizacao_estoque_pmp
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param array $con Vetor com os Filtros Aplicados
* @return void
*/
private function con_relatorio_utilizacao_estoque_pmp($con){
//echo '<pre>'; print_r($con); die;
$strBind = array(
':DEL' => '*',
':Z80_TIPO' => '2',
':AF8_CLIENT' => '76533629'
);
$where = null;
if($con["pmp"] != 't'){
$where .= " AND Z80_CODPMP = :Z80_CODPMP ";
$strBind[":Z80_CODPMP"] = $con["pmp"];
}
if($con["dat"] != 't'){
$where .= " AND Z80_EMISSA = :Z80_EMISSA ";
$strBind[":Z80_EMISSA"] = $con["dat"];
}
if($con["prj"] != 't'){
$where .= " AND Z81_PROJET = :Z81_PROJET ";
$strBind[":Z81_PROJET"] = $con["prj"];
}
if($con["fas"] != 't'){
$where .= " AND AFC_X_FASE = :AFC_X_FASE ";
$strBind[":AFC_X_FASE"] = $con["fas"];
}
if($con["edt"] != 't'){
$where .= " AND AFC_EDT = :AFC_EDT ";
$strBind[":AFC_EDT"] = $con["edt"];
}
if($con["prd"] != 't'){
$where .= " AND Z80_PRODUT = :Z80_PRODUT ";
$strBind[":Z80_PRODUT"] = $con["prd"];
}
if($con["uso"] != 't'){
$info = HoldLib::createVetorBind($con["uso"],'Z81_USO');
$where .= $info['where'];
$strBind += $info['val'];
}
if($con["arm"] != 't'){
$info = HoldLib::createVetorBind($con["arm"],'Z80_LOCAL');
$where .= $info['where'];
$strBind += $info['val'];
}
if($con["sit"] != 't'){
$info = HoldLib::createVetorBind($con["sit"]," CASE WHEN Z81_USO = '1'
THEN Z80_SITSEP ELSE Z81_SITSEP END ","IN","SITSEP");
$where .= $info['where'];
$strBind += $info['val'];
}
if($con["dti"] != 't'){
$where .= " AND CASE WHEN Z81_USO = '1' THEN C2_DATPRF ELSE AF9_FINISH
END >= :DTI ";
$strBind[":DTI"] = $con["dti"];
}
if($con["dtf"] != 't'){
$where .= " AND CASE WHEN Z81_USO = '1' THEN C2_DATPRF ELSE AF9_FINISH
END <= :DTF ";
$strBind[":DTF"] = $con["dtf"];
}
if($con["dsp"] != 't'){
$where .= " AND CASE WHEN Z81_USO = '1' THEN SUBSTR(Z80_DATSEP,1,8)
ELSE SUBSTR(Z81_DATSEP,1,8) END = :DATA_SEPARACAO ";
$strBind[":DATA_SEPARACAO"] = $con["dsp"];
}
$strQuery = $this->Pmp->sql006($where);
//$this->print_b($strQuery,$strBind);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
$itens = array();
$coresSitSep = array( 'P' => '#ccc', 'C' => 'green', 'N' => 'red', 'Z' =>
'blue','E'=>'orange' );
while($item = DataLib::bdQueryFetch($stid,true)){
//echo '<pre>'; print_r($item['Z81_ENTREGA']); die;

$item["RECNO"] = $item["Z80_USO"] == "1" ? $item["RECZ80"] :


$item["RECZ81"];
$item["QUANT"] = $item["Z80_USO"] == "1" ? $item["Z80_QUANT"] :
$item["Z81_QUANT"];
$item["QTDORI"] = $item["Z80_USO"] == "1" ? $item["Z80_QTDORI"] :
$item["Z81_QTDORI"];
$item["USRSEP"] = $item["Z80_USO"] == "1" ? $item["Z80_USRSEP"] :
$item["Z81_USRSEP"];
$item["DATSEP"] = $item["Z80_USO"] == "1" ? $item["Z80_DATSEP"] :
$item["Z81_DATSEP"];
$item["TABELA"] = $item["Z80_USO"] == "1" ? "Z80" : "Z81";
$item["SITSEP"] = $item["Z80_USO"] == "1" ? $item["Z80_SITSEP"] :
$item["Z81_SITSEP"];
$item["ENTREGA"] = $item["Z80_USO"] == "1" ? $item["Z80_ENTREG"] :
$item["Z81_ENTREG"];
$keyPrj = $item["Z81_PROJET"].$item["AFC_EDT"];

$item["PREVISAO"] = !empty($item["C2_DATPRF"]) ? $item["C2_DATPRF"] :


$item["AF9_FINISH"];
$path = HoldLib::filesPath() . "imagens_ops" . DS .
$item['Z80_PRODUT'].".png";
if (file_exists($path)) {
$item['LINK_IMG'] = true;
} else {
$item['LINK_IMG'] = false;
}
$item['COR'] = $coresSitSep[$item["SITSEP"]];
$itens[$item["Z80_USO"]][$item["Z80_LOCAL"]][$item["RECNO"]]["DADOS"] =
$item;
$itens[$item["Z80_USO"]][$item["Z80_LOCAL"]][$item["RECNO"]]
["PROJETOS"][$keyPrj] = $item;
}
//echo '<pre>'; print_r($itens); die;
return $itens;
}

/** 27.03.2020 - Raphael: conferencia_manual_pmp_estoque


*
* Conferência dos Itens do PMP Estoque
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
public function conferencia_manual_pmp_estoque(){
$this->autoRender = false;
$this->layout = 'ajax';
if($this->request->is("post")){
DataLib::bdConnect();
$post = $this->request->data;
//echo '<pre>';print_r($post);die;

if($post["acab"] == "S"){

$dados = array(
'Z81_ENTREG'=>$post["situa"]
);
$where = array(
'R_E_C_N_O_'=>array("=",$post["recno"])
);
DataLib::montarComandoBind("UPDATE","Z81010",$dados,
$where,null,false,true,false);
echo json_encode(array("result" => "ok"));

} else {

$tab = $post["tabela"];
$arm = $post["arm"];
$cod = $post["cod"];

if($post["situa"] == "N"){
$post["qtde"] = 0;
}

$infEst = $this->getEstPmp($cod,$arm);
$qtdArm = $infEst["B2_QATU"] - $infEst["Z60_QTDENT"];
if($qtdArm < $post["qtde"] && $post["situa"] != "N"){
$msg = "Não existe saldo suficiente para transferir o material
do Armazém <b>$arm</b> para o Armazém <b>11</b>:<br><br>";

$msg .= "- Quantidade Necessária:<b> ".


$post["qtde"]."</b><br>";
$msg .= "- Saldo Armazém $arm:<b> ".
$infEst["B2_QATU"]."</b><br>";
$msg .= "- Quantidade Aguardando Transferência:<b> ".
$infEst["Z60_QTDENT"]."</b><br>";
$msg .= "- Quantidade Total Disponível:<b> ".
$qtdArm."</b><br><br>";

$msg .= "<b>Será necessário ajustar o saldo do estoque antes de


continuar.</b><br>";
echo json_encode(array("result" => "ERRO01","msg"=>$msg));
return;
} else if($qtdArm >= $post["qtde"] && $post["situa"] != "N" &&
$post["qtde"] > 0){
$numReq = ProtheusLib::getNextCod("Z60_NUMREQ","Z60010","
Z60_FILIAL = '".ProtheusLib::xFilial("Z60")."' ");
$insZ60 = array(
"Z60_FILIAL" => ProtheusLib::xFilial("Z60"),
"Z60_NUMREQ" => $numReq,
"Z60_ITEM" => "0001",
"Z60_PRODUT" => $cod,
"Z60_QTDSOL" => $post["qtde"],
"Z60_QTDENT" => $post["qtde"],
"Z60_FILORI" => ProtheusLib::xFilial("Z60"),
"Z60_LOCORI" => $arm,
"Z60_FILDES" => ProtheusLib::xFilial("Z60"),
"Z60_LOCDES" => "11",
"Z60_TIPO" => "1",
"Z60_OBS" => "Transferência Saldo PMP - Tabela Atualizada:
$tab Recno: ".$post["recno"],
"Z60_DATPRF" => date("Ymd"),
"Z60_USRINC" => $this->UserAuth->getUserName(),
"Z60_DATINC" => date("YmdHis"),
"Z60_USRCON" => $this->UserAuth->getUserName(),
"Z60_DATCON" => date("YmdHis"),
"Z60_ORIGEM" => "8",
"Z60_ESTORN" => "N",
);

$sqlZ60 = DataLib::montaInsert("Z60010",
$insZ60,"Z60_QTDSOL,Z60_QTDENT",true,true,null,"Z60_OBS");
DataLib::bdQueryExecute($sqlZ60);

$strQuery = "UPDATE ".$tab."010 SET ".$tab."_SITSEP = :SITSEP,".


$tab."_USRSEP = :USRSEP,".$tab."_DATSEP = :DATSEP,".$tab."_QUANT = :QUANT WHERE
R_E_C_N_O_ = :RECNO";

$strBind = array(
":SITSEP" => $post["situa"],
":USRSEP" => $post["user"],
":QUANT" => $post["qtde"],
":DATSEP" => date("YmdHis"),
":RECNO" => $post["recno"],
);
//$this->print_b($strQuery,$strBind);
DataLib::bdQueryExecBind($strQuery,$strBind);
echo json_encode(array("result" => "ok"));
}

}
}

/** 22.02.2021 - Raphael: getEstPmp


*
* Retorna o Saldo do Estoque do produto
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $cod Código do Produto
* @param string $arm Local de Armazenagem
* @return void
*/
private function getEstPmp($cod,$arm){
$strQuery = $this->Pmp->sql007();
$strBind = array(
':DEL' => '*',
':B2_COD' => $cod,
':B2_LOCAL' => $arm,
);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
$info = DataLib::bdQueryFetch($stid,true);
return $info;
}

/**********************************
Schedule
**********************************/

/** 01.02.2021 - Raphael: notificacao_expiracao_pmp


*
* Monitoramento de PMP Estoque Pendente
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
public function notificacao_expiracao_pmp(){
//27.10.2021 - Raphael: Desabilitado - Solicitação PCP (016459)
return;
DataLib::bdConnect();
$trs["PE"] = $trs["EX"] = $trs["SE"] = null;
//Itens não procurados ou expirados
$dtLim = date("Ymd",strtotime("-15 days")); //Data Máxima de Emissão de
Itens que podem aguardar a separação do estoque, os emitidos anterior a esta data
serão cancelados
$where = " AND CASE WHEN Z81_USO = '1' THEN Z80_SITSEP ELSE Z81_SITSEP END
IN ('P') ";
$strQuery = $this->Pmp->sql001($where);
$strBind = array(':DEL'=>'*');
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
$n = 1;
while ($item = DataLib::bdQueryFetch($stid,true)) {
$situa = "PE";
if($item["Z80_EMISSA"] < $dtLim){
$situa = "EX";
$dados = array(
'Z81_SITSEP'=>'E'
);
$where = array(
'R_E_C_N_O_'=>array('=',$item["Z81REC"])
);
DataLib::montarComandoBind("UPDATE","Z81010",$dados,
$where,null,false,true,false);
}
$tr = '<tr>';
$tr .= '<td style="text-align:center;">'.$n.'</td>';//'<th></th>';
$tr .= '<td style="text-
align:center;">'.HoldLib::dateFormat($item["Z80_EMISSA"]).'</td>';//'<th>Emissão
PMP</th>';
$tr .= '<td style="text-align:center;">'.
$item["AF8_PROJET"].'</td>';//'<th>Projeto</th>';
$tr .= '<td style="text-align:left;">'.
$item["AF8_X_NRED"].'</td>';//'<th>Cliente</th>';
$tr .= '<td style="text-align:center;">'.
$item["AFC_EDT"].'</td>';//'<th>EDT</th>';
$tr .= '<td style="text-align:center;">'.
$item["B1_COD"].'</td>';//'<th>Produto</th>';
$tr .= '<td style="text-align:left;">'.
$item["B1_DESC"].'</td>';//'<th>Descrição</th>';
$tr .= '<td style="text-
align:right;">'.HoldLib::numberFormat($item["Z81_QUANT"]).'</td>';//'<th>Quantidade
</th>';
$tr .= '<td style="text-align:center;">'.
$item["B1_UM"].'</td>';//'<th>UM</th>';
$tr .= '<td style="text-align:center;">'.
$item["Z81_LOCAL"].'</td>';//'<th>Armazém</th>';
$tr .= '<td style="text-align:center;">'.($item["Z81_USO"] == '2' ?
'Expedido' : 'Consumido').'</td>';//'<th>Tipo de Uso</th>';
$tr .= '<td style="text-align:center;"></td>';//'<th>Armazém</th>';
$tr .= '</tr>';
$trs[$situa] .= $tr;
$n++;
}

//Itens Encontrados
$where = " AND CASE WHEN Z81_USO = '1' THEN Z80_SITSEP ELSE Z81_SITSEP END
NOT IN ('P','E') AND Z81_DATSEP >= '".date("YmdHis",strtotime("-4 days"))."' AND
Z81_QUANT > 0 ";
$strQuery = $this->Pmp->sql001($where);
$strBind = array(':DEL'=>'*');
$sitSep = ProtheusLib::getCboxZx3("Z81_SITSEP");
//echo '<pre>'; print_r($sitSep); die;
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
$n = 1;
while ($item = DataLib::bdQueryFetch($stid,true)) {
//echo '<pre>'; print_r($item); die;
$tr = '<tr>';
$tr .= '<td style="text-align:center;">'.$n.'</td>';//'<th></th>';
$tr .= '<td style="text-
align:center;">'.HoldLib::dateFormat($item["Z80_EMISSA"]).'</td>';//'<th>Emissão
PMP</th>';
$tr .= '<td style="text-align:center;">'.
$item["AF8_PROJET"].'</td>';//'<th>Projeto</th>';
$tr .= '<td style="text-align:left;">'.
$item["AF8_X_NRED"].'</td>';//'<th>Cliente</th>';
$tr .= '<td style="text-align:center;">'.
$item["AFC_EDT"].'</td>';//'<th>EDT</th>';
$tr .= '<td style="text-align:center;">'.
$item["B1_COD"].'</td>';//'<th>Produto</th>';
$tr .= '<td style="text-align:left;">'.
$item["B1_DESC"].'</td>';//'<th>Descrição</th>';
$tr .= '<td style="text-
align:right;">'.HoldLib::numberFormat($item["Z81_QUANT"]).'</td>';//'<th>Quantidade
</th>';
$tr .= '<td style="text-align:center;">'.
$item["B1_UM"].'</td>';//'<th>UM</th>';
$tr .= '<td style="text-align:center;">'.
$item["Z81_LOCAL"].'</td>';//'<th>Armazém</th>';
$tr .= '<td style="text-align:center;">'.($item["Z81_USO"] == '2' ?
'Expedido' : 'Consumido').'</td>';//'<th>Tipo de Uso</th>';
$tr .= '<td style="text-align:center;">'.
$sitSep[$item["Z81_SITSEP"]].'</td>';//'<th>Armazém</th>';
$tr .= '</tr>';
$trs['SE'] .= $tr;
$n++;
}

$msg = HoldLib::$styleEmail;
$msg .= HoldLib::getSaudacao(true);
if(!is_null($trs["EX"])){
$msg .= '<hr><p>PMP Estoque Expirado. Data de Emissão superior à 15
dias.</p>';
$msg .= $this->construcao_tabela($trs["EX"]);
}
if(!is_null($trs["PE"])){
$msg .= '<hr><p>Pendências de Separação do PMP Estoque.</p>';
$msg .= $this->construcao_tabela($trs["PE"]);
$msg .= '<p>Itens onde o documento do PMP foi emitido ha mais de 15
dias são automaticamente cancelados.</p>';
}
if(!is_null($trs["SE"])){
$msg .= '<hr><p>Retorno Conferência</p>';
$msg .= $this->construcao_tabela($trs["SE"]);
$msg .= '<p>Itens onde o documento do PMP foi emitido ha mais de 15
dias são automaticamente cancelados.</p>';
}

HoldLib::enviar_email("000010",$msg,false,"[PMP] Monitoramento");

/** 01.02.2021 - Raphael: construcao_tabela


*
* Monitoramento de PMP Estoque Pendente - Contrução da tabela do Email
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $tr Vetor das Linhas da Tabela
* @return void
*/
private function construcao_tabela($tr){
$msg = '<table>';
$msg .= '<thead>';
$msg .= '<tr>';
$msg .= '<th></th>';
$msg .= '<th>Emissão PMP</th>';
$msg .= '<th>Projeto</th>';
$msg .= '<th>Cliente</th>';
$msg .= '<th>EDT</th>';
$msg .= '<th>Produto</th>';
$msg .= '<th>Descrição</th>';
$msg .= '<th>Quantidade</th>';
$msg .= '<th>UM</th>';
$msg .= '<th>Armazém</th>';
$msg .= '<th>Tipo de Uso</th>';
$msg .= '<th>Situação</th>';
$msg .= '</tr>';
$msg .= '</thead>';
$msg .= '<tbody>';
$msg .= $tr;
$msg .= '</tbody>';
$msg .= '</table>';
return $msg;
}

/** 14.05.2021 - Raphael: monitoramento


*
* Monitoramento dos Projetos com pendência de geração de Ops
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
* @return void
*/
public function monitoramento(){
$this->layout = "default_v2";
DataLib::bdConnect();
$options = array(
'1' => 'Exibir Apenas Tarefas com Pendência de PMP'
);
$filtros = array(
'prv' => array('label'=>'Data Previsão Máxima Produção
PMS','type'=>'text','value'=>date("d/m/Y",strtotime("+9 weeks")),'class'=>'data'),
'opt' =>
array('label'=>'Opções','type'=>'select','multiple'=>'checkbox','options'=>$options
,'value'=>'1'),
);
$this->getMonitoramento($filtros);
$this->set('filtros',$filtros);
}

/** 14.05.2021 - Raphael: getMonitoramento


*
* Processa o monitoramento do PMP
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param array $filtros Filtros Aplicados
* @return void
*/
private function getMonitoramento($filtros){
$itens = array();
$tratamento = HoldLib::parametros_filtros($filtros);
$filtros = $tratamento["filtro"];
$con = $tratamento["con"];
$optSel = explode(",",$con["opt"]);
$where1 = $where2 = null;
$strBind = array(':DEL' => '*');
if(isset($con["prv"]) && $con["prv"] != 't'){
$where1 = " AND AF9_FINISH <= :AF9_FINISH ";
$strBind[":AF9_FINISH"] = $con["prv"];
}
if(in_array("1",$optSel)){
$where2 = " AND PESO_TOTAL > PESO_FIM ";
}
$equi0102 = ProtheusLib::getZx6("000038",true);
$strQuery = $this->Pmp->sql014($where1,$where2,$equi0102);
//$this->print_b($strQuery, $strBind);
$stid = DataLib::bdQueryExecBind($strQuery,$strBind);
while($item = DataLib::bdQueryFetch($stid,true)){
$keyFas = $item["AF8_PROJET"]."-".$item["AFC_X_FASE"];
if($item["AF8_PROJET"] == "202000187" && $item["AFC_EDT"] == "33"){
//echo '<pre>'; print_r($item); die;
}
$itens[$item["SEMANA"]][$keyFas]["INFO"] = $item;
$itens[$item["SEMANA"]][$keyFas]["TAREFAS"][$item["AFC_EDT"]] = $item;
}
$strQuery = $this->Pmp->sql015();
$stid = DataLib::bdQueryExecBind($strQuery);
while($item = DataLib::bdQueryFetch($stid,true)){
$perEng[$item["AF9_PROJET"]][$item["AF9_EDTPAI"]] = $item["PERC"];
}
$this->set('itens',$itens);
$this->set('perEng',$perEng);
}

/** 26.07.2021 - Raphael: excluir_lote


*
* Exclui um lote do sistema que ainda esteja como C2_TP = 'P' (Previsto)
*
* @author Raphael Lacerda <mailto:raphael.lacerda@consilos.com.br>
*
* @param string $numOp Número do Lote
* @return void
*/
public function excluir_lote($filial = "",$numOp = ""){
if(empty($filial)){
die("Informe a filial...");
}
if(empty($numOp)){
die("Informe o lote...");
}
$this->trocar_filial($filial);
DataLib::bdConnect();

$wheSc2 = array("C2_NUM" => array("=",$numOp));


$wheAfm = array("AFM_NUMOP" => array("=",$numOp));
$wheZ59 = array("Z59_NUMOP" => array("=",$numOp));
$wheSD4 = array("SUBSTR(D4_OP,1,6)" => array("=",$numOp,"ORDEM"));
$wheSHY = array("SUBSTR(HY_OP,1,6)" => array("=",$numOp,"ORDEM"));

$infoOp = DataLib::montarComandoBind("SELECT","SC2010",null,
$wheSc2,null,true,true);
$infoOp = reset($infoOp);
$infoOp = HoldLib::removeEspacos($infoOp);
if(!empty($infoOp["C2_X_PMP"])){
$wheZ80 = array(
"Z80_CODPMP" => array("=",$infoOp["C2_X_PMP"]),
"Z80_SEQLOT" => array("=",$infoOp["C2_X_PMPS"])
);
$dados = array("Z80_STATUS"=>"1");
DataLib::montarComandoBind("UPDATE","Z80010",$dados,
$wheZ80,null,true,true);
$wheZbj = array(
"ZBJ_CODPMP" => array("=",$infoOp["C2_X_PMP"]),
"ZBJ_SEQLOT" => array("=",$infoOp["C2_X_PMPS"])
);
$dados = array("ZBJ_STATUS"=>"1");
DataLib::montarComandoBind("UPDATE","ZBJ010",$dados,
$wheZbj,null,true,true);
}

DataLib::montarComandoBind("DELETE","SC2010",null,$wheSc2,null,true,true);
DataLib::montarComandoBind("DELETE","AFM010",null,$wheAfm,null,true,true);
DataLib::montarComandoBind("DELETE","Z59010",null,$wheZ59,null,true,true);
DataLib::montarComandoBind("DELETE","SD4010",null,$wheSD4,null,true,true);
DataLib::montarComandoBind("DELETE","SHY010",null,$wheSHY,null,true,true);
$sql["SC2"] = DataLib::montarComandoBind("COUNT","SC2010",null,
$wheSc2,null,true,true);
$sql["AFM"] = DataLib::montarComandoBind("COUNT","AFM010",null,
$wheAfm,null,true,true);
$sql["Z59"] = DataLib::montarComandoBind("COUNT","Z59010",null,
$wheZ59,null,true,true);
$sql["SD4"] = DataLib::montarComandoBind("COUNT","SD4010",null,
$wheSD4,null,true,true);
$sql["SHY"] = DataLib::montarComandoBind("COUNT","SHY010",null,
$wheSHY,null,true,true);

echo '<pre>';print_r($sql);die;
}

Você também pode gostar