Ir para conteúdo
Fórum Script Brasil
  • 0

Orçamento em PHP, usando classes


Frank K Hosaka

Pergunta

O seguinte código coloca todos os arquivos no diretório raiz, as definições e a conexão foram colocadas no arquivo Controle, e foi utilizado o prefixo v para todos os arquivos que contém os formulários em HTML.


arquivo /Astudy/Controle.php
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
    rel="stylesheet">
<div style=height:20px></div>
<?php
date_default_timezone_set('America/Sao_Paulo');

defined('HOST') || define('HOST', 'localhost');
defined('DBNAME') || define('DBNAME', 'teste');
defined('USER') || define('USER','root');
defined('PASSWORD') || define('PASSWORD','');

spl_autoload_register(
    function ($classe) 
    {
        $arquivo =  $classe . '.php';
        if (file_exists($arquivo)) 
        {
            require_once $arquivo;
            return;
        }   
    throw new Exception("Erro ao carregar a classe '{$classe}'. Arquivo não encontrado.$arquivo");
    }
);

function dec($value) 
{
    if($value==null) 
    {
        return null;
    }
    return number_format($value,2,',','.');
}

function deca($num) 
{   
    $value=str_replace(".","",$num); 
    return str_replace(",",".",$value);
}

function fmt($date) 
{ 
    return date('d/m/y',strtotime($date));
}

function pvenda($custo,$margem) 
{
    $calculo=intval($custo*(1+$margem/100)*100)/100;
    $fracao=$calculo-intval($calculo);
    if ($fracao < 0.09) 
    {
        $pvenda=intval($calculo);
    } else {
        if ($fracao <= 0.59) 
        {
            $pvenda=intval($calculo)+0.5;
        } else {
            $pvenda=intval($calculo)+1;
        }
    }		
    return dec($pvenda);  
}




function view($arquivo, $array = null)
{
    if (!is_null($array))
    {
        foreach ($array as $var => $value)
        {
            ${$var} = $value;
        }
    }
    ob_start();
    include $arquivo . ".php";
    ob_flush();
}

class Controle
{
    private static $pdo;

    public static function instancia()
    {
        if(!self::$pdo)
        {
            self::$pdo=new PDO("mysql:host=".HOST.";dbname=".DBNAME,USER,PASSWORD);
        }
        return self::$pdo;
    }

    function select($sql)
    {
        $stmt=$this->instancia()->query("select $sql");
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    function insert($sql)
    {
        return $this->instancia()->query("insert into $sql");
    }

    function delete($sql)
    {
        return $this->instancia()->query("delete $sql");
    }

    function update($sql)
    {
        return $this->instancia()->query("update $sql");
    }
        
}

arquivo /Astudy/ControleOrcamento.php
<?php
class ControleOrcamento extends Controle
{
	public function alteraQt()
	{
		$qt=$_POST['alteraQt'];
		$id=$_POST['id'];
		$ped=$_POST['ped'];
		$unitario=$_POST['unitario'];
		$subtotal=$qt*$unitario;
		$this->update("tbhistped set qt=$qt, subtotal=$subtotal where id=$id");
		$total=$this->select("sum(subtotal) as total from tbhistped where ped=$ped")[0]->total;
		$this->update("tbpedido set total=$total where ped=$ped");
		return $this->inicio($ped);
	}

	public function excluir($id)
	{
		$pedido=$_GET['pedido'];
		$this->delete("from tbhistped where id=$id");
		$total=$this->select("sum(subtotal) as total from tbhistped where ped=$pedido")[0]->total;
		$this->update("tbpedido set total=$total where ped=$pedido");
		return $this->inicio($pedido);

	}

	public function historico($hist = null)
	{
		$where="";
        if($hist) 
		{
            $ped=$_GET['referencia']+$hist;
            $where="where ped <= $ped";
        }
		$pedidos=$this->select("* from tbpedido $where order by ped desc limit 15");
		return view('vHistorico',['pedidos'=>$pedidos]);
	}

	public function incluirProduto($codprod)
	{
		$pedido=$_GET['pedido'];
		return $this->inicio($pedido,$codprod);
	}

	public function incluirQt()
	{
		$qt=deca($_POST['qt']);
		$ped=$_POST['ped'];
		$codprod=$_POST['codprod'];
		$unitario=str_replace(",",".",$_POST['venda']);
		$un=$_POST['un'];
		$subtotal=$qt*$unitario;
		$this->insert("tbhistped (ped,codprod,un,unitario,subtotal,qt)
			values ($ped,$codprod,'$un',$unitario,$subtotal,$qt)");
		$total=$this->select("sum(subtotal) as total from tbhistped where ped=$ped")[0]->total;
		$this->update("tbpedido set total=$total where ped=$ped");
		return $this->inicio($ped);
	}

	public function inicio($pedido = null, $codprod = null)
	{
		if($pedido)
		{
			$pedido=$this->select("* from tbpedido where ped=$pedido")[0];
		} else {
			$ultimo=$this->select("max(ped) as ultimo from tbpedido")[0]->ultimo;
			$pedido=$this->select("* from tbpedido where ped=$ultimo")[0];
		}
		if($codprod)
		{
			$vr['codprod']=$codprod;
			$produto=$this->select("* from tbprod where codprod=$codprod")[0];
			$vr['prod']=$produto->prod;
			$vr['venda']=$produto->venda;
			$vr['un']=$produto->un;
		} else {
			$vr['codprod']=null;
			$vr['prod']=null;
			$vr['venda']=null;
			$vr['un']=null;
		}
		$vr['ped']=$pedido->ped;
		$vr['diaped'] = $pedido->dia;
		$vr['total'] = $pedido->total;
		$vr=json_decode(json_encode($vr));
		$histped=$this->select("* from tbhistped 
			join tbprod on tbprod.codprod = tbhistped.codprod
			where ped=$vr->ped");
		return view('vOrcamento',['vr'=>$vr,'histped'=>$histped]);
	}

	public function novoPedido()
	{
		$pedido=$this->select("* from tbpedido order by ped desc")[0];
        $ped=$pedido->ped;
        $total=$pedido->total;
        if($total!==null)
			{
				$ped++;
				$dia=date('Y-m-d');
				$this->insert("tbpedido (ped,dia) values ($ped,'$dia')");
			}
        return $this->inicio($ped);
	}

	public function produto()
	{
		$pedido=$_POST['pedido'];
		$produtos=$this->select("* from tbprod order by prod limit 15");
		return view('vProduto',['produtos'=>$produtos,'pedido'=>$pedido]);
	}
}

arquivo /Astudy/ControleProduto.php
<?php
class ControleProduto extends Controle
{   

    public function procurarProduto()
    {
        $procura=$_POST['procura'];
        $pedido=$_POST['pedido'];
        $criterio=str_replace(" ","%",$procura);
        $produtos=$this->select("* from tbprod where prod like '%$criterio%' order by prod");
        return view('vProduto',['produtos'=>$produtos,'pedido'=>$pedido]);
    }

    public function selecionado($codprod)
    {
        $pedido=$_GET['pedido'];
        return header("location:?ControleOrcamento.incluirProduto.$codprod&pedido=$pedido");
    }
}


arquivo /Astudy/index.php
<?php
require('Controle.php');
$rota='ControleOrcamento_inicio';
if($_GET)
{
    if(strpos(key($_GET),"_")==0)
    {
        exit;
    }
    $rota=isset($_GET) ? key($_GET) : $rota;
}
$segmentos=explode('_',$rota);
$nomeControle=$segmentos[0] ?? 'ControleOrcamento';
$metodo=$segmentos[1] ?? 'inicio';
$parametro=$segmentos[2] ?? null;
$controle=new $nomeControle();
$controle->$metodo($parametro);


arquivo /Astudy/mysql.txt
CREATE TABLE `tbhistped` (
  `ped` int DEFAULT NULL,
  `codprod` int DEFAULT NULL,
  `un` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `unitario` float DEFAULT NULL,
  `subtotal` float DEFAULT NULL,
  `id` int NOT NULL AUTO_INCREMENT,
  `qt` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13063 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

CREATE TABLE `tbpedido` (
  `ped` int NOT NULL AUTO_INCREMENT,
  `total` float DEFAULT NULL,
  `dia` date DEFAULT NULL,
  `codp` mediumint DEFAULT NULL,
  `horavenda` datetime DEFAULT NULL,
  `vendido` date DEFAULT NULL,
  `dinheiro` float DEFAULT NULL,
  `troco` float DEFAULT NULL,
  `cartao` tinyint DEFAULT NULL,
  `pix` tinyint DEFAULT NULL,
  `bling` int DEFAULT NULL,
  PRIMARY KEY (`ped`)
) ENGINE=InnoDB AUTO_INCREMENT=5825 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

CREATE TABLE `tbprod` (
  `codprod` mediumint NOT NULL AUTO_INCREMENT,
  `un` varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT 'un',
  `prod` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `custo` decimal(13,2) DEFAULT NULL,
  `marg` decimal(5,2) DEFAULT NULL,
  `codbar` varchar(29) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `loc` varchar(14) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '""',
  `emb` float DEFAULT NULL,
  `cf` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `codforn` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `estoque` float DEFAULT NULL,
  `origem` int NOT NULL DEFAULT '0',
  `vazio` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `venda` decimal(13,2) DEFAULT NULL,
  PRIMARY KEY (`codprod`)
) ENGINE=InnoDB AUTO_INCREMENT=2288 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci


arquivo /Astudy/vHistorico.php
<?php $referencia = $pedidos[0]->ped; ?>
<table class='table table-striped table-sm w-25 m-auto'>
<th style=width:20px>Dia
<th style=width:40px>
    <div style="display:flex;width:30px;margin-right:15px">
    <a href="?ControleOrcamento.historico.-14&referencia=<?=$referencia?>"><</a>&nbsp;
    <a href="?ControleOrcamento.inicio">Ped</a>&nbsp;
    <a href="?ControleOrcamento.historico.14&referencia=<?=$referencia?>" >></a>
    </div>
<th class=text-end>Total
<?php foreach($pedidos as $ped) : ?>
    <tr><td><?=date('d/m/y',strtotime($ped->dia))?>
    <td class=text-end><a href=?ControleOrcamento.inicio.<?=$ped->ped?>><?=$ped->ped?></a>
    <td class=text-end><?=dec($ped->total)?>
<?php endforeach; ?>


arquivo /Astudy/vOrcamento.php
<table class='table table-striped table-sm w-50 m-auto pt-3'>
<tr class="fw-semibold align-middle" style=height:40px>
    <td>Produto  <a href=?ControleOrcamento.historico>Historico</a>
	<a href="?ControleOrcamento.novoPedido">Novo</a>
    <spam class=text-danger>Pedido <?=$vr->ped?> de <?=fmt($vr->diaped)?></spam>
	
    <td class=text-end>Qt<td>Un<td>Preço<td class=text-end>Total
    <?php foreach($histped as $item): ?>
    <tr>
	<td><?=$item->prod?>
	<td class=text-end>
		<form class='m-0' action=?ControleOrcamento.alteraQt method=post>
		<?php if($item->qt==intval($item->qt)): ?>
			<input name=alteraQt value='<?=$item->qt?>' onchange=submit() size=1 
				style=text-align:right;border:none;background:transparent>
		<?php else: ?>
			<input name=alteraqQt value='<?=dec($item->qt)?>' onchange=submit() size=1 
			style=text-align:right;border:none;background:transparent>
		<?php endif; ?>
		<input type=hidden name=id value=<?=$item->id?>>
		<input type=hidden name=ped value=<?=$item->ped?>>
		<input type=hidden name=unitario value=<?=$item->unitario?>>
		</form>
	<td><a href=?ControleOrcamento.excluir.<?=$item->id?>&pedido=<?=$item->ped?>><?=$item->un?></a>
	<td class=text-end><?=dec($item->unitario)?>
	<td class=text-end><?=dec($item->subtotal)?>
<?php endforeach; ?>
<tr >
<?php if($vr->prod==""):?>
	<td>
	<form action=?ControleOrcamento.produto method=post class=m-0>
	<input type=submit value="Selecione um produto" autofocus>
    <input type=hidden name=pedido value=<?=$vr->ped?>>
	</form>
<?php else: ?>
	<td><?=$vr->prod?>
<?php endif; ?>
<?php if(isset($_GET['pedido'])): ?>
	<td class=text-end>
	<form action=?ControleOrcamento.incluirQt method=post class=m-0>
	<input id=qt name=qt onchange=submit() size=1 placeholder=qt autofocus>
	<input type=hidden name=ped value="<?=$vr->ped?>">
	<input type=hidden name=codprod value="<?=$vr->codprod?>">
	<input type=hidden name=venda value="<?=$vr->venda?>">
	<input type=hidden name=un value="<?=$vr->un?>">
	</form>
	<td><?=$vr->un?><td class=text-end><?=$vr->venda?><td>
<?php else: ?>
	<td><td><td><td>
<?php endif; ?>
<tr class=fw-semibold><td><td><td><td>Total<td class=text-end><?=dec($vr->total)?>
</table>>

arquivo /Astudy/vProduto.php
<table class='table table-striped table-sm w-50 m-auto'>
<tr><td><td>
    <form action="?ControleProduto.procurarProduto" method=post class=m-0>
    <input name=procura size=40 onchange=submit() autofocus>
    <input type=hidden name=pedido value=<?=$pedido?>>
    </form>
    <td>
<tr class=fw-semibold><td>Cód<td>Descrição dos Produtos<td>Venda
<?php foreach($produtos as $prod): ?>
<tr><td class=text-end>
    <a href='?ControleProduto.selecionado.<?=$prod->codprod?>&pedido=<?=$pedido?>'>
    <?=$prod->codprod?></a>
    <td><?=$prod->prod?>
    <td class=text-end><?=pvenda($prod->custo,$prod->marg)?>
<?php endforeach; ?>

 

Captura de tela 2024-05-19 153732.png

Editado por Frank K Hosaka
Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...