| Server IP : 54.94.228.101 / Your IP : 172.28.1.13 Web Server : Apache System : Linux ip-172-28-29-189 6.5.0-1014-aws #14~22.04.1-Ubuntu SMP Thu Feb 15 15:27:06 UTC 2024 x86_64 User : www-data ( 33) PHP Version : 7.2.34-43+ubuntu22.04.1+deb.sury.org+1 Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals, MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/html/vinumday2_0/app/Modules/Cotacao/Controllers/Admin/ |
Upload File : |
<?php
namespace App\Modules\Cotacao\Controllers\Admin;
use Illuminate\Http\Request;
use Mail;
use Exception;
use App\Http\Requests;
use App\Http\Controllers\BaseController;
use App\Modules\Cotacao\Models\Cotacao;
use App\Modules\CotacaoValor\Models\CotacaoValor;
use App\Modules\Empresa\Models\Empresa;
use App\Modules\PedidoEntrega\Models\PedidoEntrega;
use App\Modules\PedidoEntregaStatus\Models\PedidoEntregaStatus;
use App\Modules\Transportadora\Models\Transportadora;
use App\Modules\TransportadoraTabela\Models\TransportadoraTabela;
use App\Services\GeralService;
use App\Services\ErpService;
use DB;
use Excel;
use Illuminate\Support\Facades\Log;
class AdminCotacaoController extends BaseController
{
private $modulo;
private $fields;
private $fks;
private $lastInsertId;
public function __construct(){
parent::__construct();
$this->middleware('auth');
$this->modulo = \App\Gerador::where('nome', 'Cotacao')->with('campos', 'fks')->first();
$this->fields = $this->modulo->campos;
$this->fks = $this->modulo->fks;
$this->cotacao_m = new Cotacao();
}
public function index(){
$query = $this->cotacao_m->select('cotacao.*');
$data['fields_listagem'] = array();
foreach ($this->fields as $field) {
if($field->listagem){
$data['fields_listagem'][] = $field;
}
}
foreach ($this->fks as $fk) {
if($fk->listagem){
if($fk->campoRelacionado->translatable){
$table = $fk->moduloRelacionado->nome_tabela.'_descricao';
$on = $fk->moduloRelacionado->nome_tabela.'_descricao.'.$fk->moduloRelacionado->nome_tabela.'_id';
}else{
$table = $fk->moduloRelacionado->nome_tabela;
$on = $fk->moduloRelacionado->nome_tabela.'.id';
}
$query->leftJoin($table, 'cotacao.'.$fk->nome, '=', $on);
$query->addSelect($table.'.'.$fk->campoRelacionado->nome.' as fk'.$fk->id);
$data['fields_listagem'][] = $fk;
}
}
$data['cotacoes'] = $query->groupBy('cotacao.id')->get();
usort($data['fields_listagem'], function($a, $b) {
return $a->ordem - $b->ordem;
});
return view('Cotacao::admin/cotacao',$data);
}
public function cotacaoFechar($id){
$PedidoEntrega = PedidoEntrega::find($id);
$Empresa = $PedidoEntrega->empresa;
$Transportadora = $PedidoEntrega->cotacaoValor->transportadora;
$notafiscal = new \stdClass();
$notafiscal->notafiscal = new \stdClass();
$notafiscal->notafiscal->id = $PedidoEntrega->id_nota_fiscal_erp;
$notafiscal->notafiscal->volumes = $PedidoEntrega->quantidade_volumes_nota_erp;
$notafiscal->notafiscal->formaEnvio = 'T';
$notafiscal->notafiscal->transportadora = trim($Transportadora->nome_erp);
Log::info("ErpService::atualizarDespachoNotaFiscal => empresa: {$Empresa->nome} / notafiscal: {$PedidoEntrega->nota_fiscal_erp}: ". json_encode($notafiscal));
$response = ErpService::atualizarDespachoNotaFiscal($notafiscal, $Empresa);
Log::info("ErpService::atualizarDespachoNotaFiscal => notafiscal: {$PedidoEntrega->nota_fiscal_erp} response: ". json_encode($response));
//Validação Erros
if($response->retorno->status_processamento != 3){
$json = array(
'status' => false,
'message' => "Código Erro: {$response->retorno->codigo_erro} / Erros: " . json_encode($response->retorno->erros)
);
return response()->json($json);
}
$Cotacao = $PedidoEntrega->cotacao;
$Cotacao->status = 'F';
$Cotacao->save();
//Atualiza Transportadora Pedido Entrega e Nota Fiscal
$sql = "UPDATE pedido_entrega SET id_transportadora = {$Transportadora->id} WHERE id = {$PedidoEntrega->id}";
DB::update($sql);
$json = array(
'status' => true,
'message' => "Cotação Fechada com Sucesso!"
);
return response()->json($json);
}
public function exportarExcel(Request $request){
$post = $request->input();
$data['pedidos'] = GeralService::buscarPedidosCotacao($post, FALSE, TRUE);
foreach($data['pedidos'] as $pedido){
$peso_caixa = GeralService::calculaPesoCaixa($pedido->adega->quantidade_produtos, $pedido->quantidade_volumes_nota_erp);
$peso_nota_fiscal_erp = GeralService::calculaPesoProdutosAdega($pedido);
$pedido->peso_final_nf = number_format($peso_nota_fiscal_erp + $peso_caixa, 2, '.', ',');
}
Excel::create('Pedidos '.date('d-m-Y'), function($excel) use ($data) {
$excel->sheet('PEDIDOS', function($sheet) use ($data){
$sheet->loadView('Cotacao::admin/excel', $data);
});
})->download('xls');
}
public function cotacaoPedido($id){
$PedidoEntrega = PedidoEntrega::find($id);
$PedidoEntrega = GeralService::obterNotaFiscalPedido($PedidoEntrega);
if(is_array($PedidoEntrega) && isset($PedidoEntrega['status'])){
return $PedidoEntrega;
}
$data = [];
$data['pedido_entrega'] = $PedidoEntrega;
$data['transportadoras'] = Transportadora::where('ativo', 1)->orderBy('ordem_cotacao','asc')->get();
$peso_caixa = GeralService::calculaPesoCaixa($PedidoEntrega->adega->quantidade_produtos, $PedidoEntrega->quantidade_volumes_nota_erp);
$peso_nota_fiscal_erp = GeralService::calculaPesoProdutosAdega($PedidoEntrega);
$peso_nota_fiscal_erp = $peso_nota_fiscal_erp + $peso_caixa;
$peso_nota_fiscal_erp = number_format($peso_nota_fiscal_erp, 2, '.', ',');
//BUSCA VALORES TABELA TRANSPORTADORAS
$tabelas = [];
foreach ($data['transportadoras'] as $transportadora) {
$valorTabela = 0;
$pesoTabela = 0;
$valorOriginal = 0;
$kiloAdicional = 0;
$valorAdicional = 0;
$Tabela = TransportadoraTabela::where('transportadora_id', $transportadora->id)->where('estado_id', $PedidoEntrega->endereco->estado_id)->where('peso', '>=', $peso_nota_fiscal_erp)->first();
//Se não encontrou busca maior peso cadastrado
if(!$Tabela){
$Tabela = TransportadoraTabela::where('transportadora_id', $transportadora->id)->where('estado_id', $PedidoEntrega->endereco->estado_id)->where('peso', '<=', $peso_nota_fiscal_erp)->orderBy('peso', 'desc')->first();
}
if($Tabela){
$kiloAdicional = 0;
$valorAdicional = 0;
$valorTabela = $Tabela->valor;
$pesoTabela = $Tabela->peso;
$valorOriginal = $valorTabela;
//Calcula Kg Adicional
if($peso_nota_fiscal_erp > $Tabela->peso){
$kiloAdicional = $peso_nota_fiscal_erp - $Tabela->peso;
$kiloAdicional = ceil($kiloAdicional);
$TabelaKiloAdicional = TransportadoraTabela::where('transportadora_id', $transportadora->id)->where('estado_id', $PedidoEntrega->endereco->estado_id)->where('peso', 0)->first();
if($TabelaKiloAdicional){
$valorAdicional = $TabelaKiloAdicional->valor * $kiloAdicional;
$valorTabela = $valorTabela + $valorAdicional;
$valorTabela = number_format($valorTabela, 2, '.', ',');
}
}
}
//Cálculo Percentual Adicional Transportadora
if($valorTabela > 0 && $transportadora->adicional_valor != 0):
$valorTabela = $valorTabela + (($PedidoEntrega->valor_nota_erp * $transportadora->adicional_valor) / 100);
$valorTabela = number_format($valorTabela, 2, '.', ',');
endif;
$tabelas[$transportadora->id] = [
'valor' => $valorTabela,
'valor_original' => $valorOriginal,
'peso' => $pesoTabela,
'peso_adicional' => $kiloAdicional,
'valor_adicional' => $valorAdicional,
];
}
$data['tabelas'] = $tabelas;
$data['peso_nota_fiscal_erp'] = $peso_nota_fiscal_erp;
$data['peso_caixa'] = $peso_caixa;
$html = view('Cotacao::admin/_pedido', $data)->render();
$json = array(
'status' => true,
'message' => "Operação realizada com sucesso!",
'html' => $html
);
return response()->json($json);
}
public function saveCotacaoPedido(Request $request){
$post = $request->input();
$PedidoEntrega = PedidoEntrega::find($post['pedido_entrega_id']);
$PedidoEntrega->id_cotacao_valor = NULL;
$PedidoEntrega->save();
if($PedidoEntrega->cotacao){
$Cotacao = $PedidoEntrega->cotacao;
}else{
$Cotacao = new Cotacao;
$Cotacao->status = 'A';
$Cotacao->pedido_entrega_id = $PedidoEntrega->id;
$Cotacao->save();
}
//Limpa Cotações
DB::table('cotacao_valor')->where('cotacao_id', $Cotacao->id)->delete();
$key_cotacao_valor = false;
$menor_cotacao = 0;
$valores = [];
foreach ($post['transportadora'] as $key => $transportadora_id) {
$valorCotacao = [
'cotacao_id' => $Cotacao->id,
'transportadora_id' => $transportadora_id,
'peso' => $post['peso'][$key],
'valor' => $post['valor'][$key],
'ordem_cotacao' => $post['ordem'][$key]
];
$valores[] = $valorCotacao;
if(!empty($post['melhor_cotacao']) && $post['ordem'][$key] == $post['melhor_cotacao']){
$key_cotacao_valor = $key;
}elseif(empty($post['melhor_cotacao']) && ($post['valor'][$key] < $menor_cotacao && $post['valor'][$key] > 0 || ($menor_cotacao == 0 && $post['valor'][$key] > 0))){
$menor_cotacao = $post['valor'][$key];
$key_cotacao_valor = $key;
}
}
CotacaoValor::insert($valores);
$CotacaoValor = false;
if($key_cotacao_valor || $key_cotacao_valor == '0'){
$CotacaoValor = CotacaoValor::where('cotacao_id', $Cotacao->id)->where('transportadora_id', $post['transportadora'][$key_cotacao_valor])->first();
}
if($CotacaoValor){
$PedidoEntrega->id_cotacao_valor = $CotacaoValor->id;
$PedidoEntrega->save();
}
$json = array(
'status' => true,
'message' => "Cotação Salva com Sucesso!",
'pedido' => $PedidoEntrega->id,
'transportadora' => ($PedidoEntrega->cotacaoValor ? $PedidoEntrega->cotacaoValor->transportadora->nome : '') . ' ' . ($PedidoEntrega->cotacaoValor ? '(' . number_format($PedidoEntrega->cotacaoValor->valor, 2, ',', '.') . ')' : '')
);
return response()->json($json);
}
public function cotacaoFrete(Request $request){
$post = $request->input();
$data = [];
if(empty($post)){
$data['pedidos'] = [];
}else{
$data = $post;
$data['pedidos'] = GeralService::buscarPedidosCotacao($post, 50);
}
$data['empresas'] = Empresa::all();
$data['statusPedidos'] = PedidoEntregaStatus::all();
$data['transportadoras'] = Transportadora::where('ativo', 1)->orderBy('ordem_cotacao', 'asc')->get();
return view('Cotacao::admin/frete',$data);
}
public function add(){
$data = array();
$data['modulo'] = $this->modulo;
$data['fields'] = [];
foreach ($this->fields as $field) {
$data['fields'][] = $field;
}
foreach ($this->fks as $fk) {
$data['fields'][] = $fk;
}
usort($data['fields'], function($a, $b) {
return $a->ordem - $b->ordem;
});
foreach ($this->fks as $fk) {
$classPath = '\App\Modules\\'.$fk->moduloRelacionado->nome.'\Models\\'.$fk->moduloRelacionado->nome;
$data['array_'.$fk->nome] = $classPath::get();
}
$data['nextId'] = $this->cotacao_m->getNextAutoIncrement();
return view('Cotacao::admin/form-cotacao', $data);
}
public function edit($slug){
$id = Cotacao::where('slug', $slug)->value('id');
$data['modulo'] = $this->modulo;
$data['fields'] = [];
foreach ($this->fields as $field) {
$data['fields'][] = $field;
}
foreach ($this->fks as $fk) {
$data['fields'][] = $fk;
}
usort($data['fields'], function($a, $b) {
return $a->ordem - $b->ordem;
});
foreach ($this->fks as $fk) {
$classPath = '\App\Modules\\'.$fk->moduloRelacionado->nome.'\Models\\'.$fk->moduloRelacionado->nome;
$data['array_'.$fk->nome] = $classPath::get();
}
$data['cotacao'] = $this->cotacao_m->find($id);
if($this->modulo->galeria){
$data['cotacao']->imagens = $this->cotacao_m->getImagens($id);
}
return view('Cotacao::admin/form-cotacao',$data);
}
public function save(Request $request){
$post = $request->input();
$post['meta_keywords'] = (isset($post['meta_keywords'])) ? implode(',',$post['meta_keywords']) : null;
foreach ($this->fields as $field) {
$arrayFields[] = $field->nome;
}
foreach ($this->fks as $fk) {
$arrayFields[] = $fk->nome;
}
if($this->modulo->imagem){
$arrayFields[] = 'thumbnail_principal';
}
if($request->input('id')){
$id_cotacao = $this->cotacao_m->editar($arrayFields, $post, $request->input('id'));
}else{
$id_cotacao = $this->cotacao_m->criar($arrayFields, $post);
}
\Session::flash('type', 'success');
\Session::flash('message', "Alteracoes salvas com sucesso!");
return redirect('admin/cotacao');
}
public function upload_image(Request $request) {
if($request->hasFile('file')) {
//upload an image to the /img/tmp directory and return the filepath.
$file = $request->file('file');
$tmpFilePath = '/uploads/cotacao/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
$path = $tmpFilePath . $tmpFileName;
return response()->json(array('path'=> $path, 'file_name'=>$tmpFileName), 200);
} else {
return response()->json(false, 200);
}
}
public function upload_galeria($id, Request $request) {
if($request->hasFile('file')) {
//upload an image to the /img/tmp directory and return the filepath.
$file = $request->file('file');
$tmpFilePath = '/uploads/cotacao/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
$path = $tmpFilePath . $tmpFileName;
$this->cotacao_m->criar_imagem(array('id_cotacao' => $id, 'thumbnail_principal' => $tmpFileName));
return response()->json(array('path'=> $path, 'file_name'=>$tmpFileName), 200);
} else {
return response()->json(false, 200);
}
}
public function crop_image(Request $request) {
$img = \Image::make('uploads/cotacao/'.$request->input('file_name'));
$dataCrop = json_decode($request->input('data_crop'));
if($img->crop(intval($dataCrop->width), intval($dataCrop->height), intval($dataCrop->x), intval($dataCrop->y))->save('uploads/cotacao/thumb_'.$request->input('file_name'))){
@unlink('uploads/cotacao/'.$request->input('file_name'));
echo json_encode(array(
'status' => true,
'path' => '/uploads/cotacao/thumb_'.$request->input('file_name'),
'file_name' => 'thumb_'.$request->input('file_name'),
));
}else{
echo json_encode(array(
'status' => false,
'message' => 'Não foi possível alterar a imagem.'
));
}
}
public function delete($slug){
$id = Cotacao::where('slug', $slug)->value('id');
$this->cotacao_m->deletar($id);
\Session::flash('type', 'success');
\Session::flash('message', "Registro removido com sucesso!");
return redirect('admin/cotacao');
}
public function delete_imagem($id){
try{
$imagem = $this->cotacao_m->getImagem($id);
$this->cotacao_m->deletar_imagem($id);
unlink('uploads/cotacao/'.$imagem->thumbnail_principal);
return response()->json(array('status' => true, 'message' => 'Registro removido com sucesso!'));
}catch(Exception $e){
return response()->json(array('status' => false, 'message' => $e->getMessage()));
}
}
private function slugify($string)
{
return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
}
}