• No se han encontrado resultados

CAPÍTULO 3: DESCRIPCIÓN DE PROGRAMAS

3.4 Descripción detalle de programas

3.4.7 Informe de ganancia

Nombre lógico: formInRangoVenta Nombre Físico: formInRangoVenta.java

Objetivo: Mostrar un informe de los ingresos y egresos del establecimiento.

Descripción: Presenta dos campos para seleccionar un rango de fecha a examinar, permite filtrar según el turno y, dos listas que muestran los datos por pantalla.

Diagrama de bloques:

Diagrama. 3-9 – Diagrama de bloque informe ganancias

Reglas de proceso: Luego de seleccionar la opción Productos/Productos en la barra de menú de la pantalla Login, el sistema desplegará el formulario formInRangoVenta (ver figura 3-7). Al seleccionar en el combo box la opción “Mes Actual” (ver figura 3-7) se tomarán los datos que estén en el rango de fecha desde el primero del mes hasta la fecha en la que se consulta. Si se selecciona la opción “Rango de fechas”, se desplegarán botones que permitirán seleccionar un rango de fechas desde un calendario que se mostrará en pantalla (ver figura 3-7); pero al seleccionar la fecha específica se validará que el rango final de fecha sea mayor.

Una vez validadas las fechas, se realizarán las consultas deseadas, para llenar el listado de ingresos (ver figura 3-7) se consultará a la tabla “detalle_pedido”, obteniendo de esta forma todos los productos que fueron vendidos en el rango de fecha seleccionado. Para llenar el listado de egresos (ver figura 3-7), se consulta a la tabla “detalle_registro_compra”, obteniendo así, todos los insumos adquiridos en el rango de fecha.

Al oprimir el botón “Total Neto” se obtiene el total neto adquirido en cada listado (ver figura 3-7). Finalmente al presionar “Ganancia” (ver figura 3-7) se calculará la diferencia entre el total neto de ingresos y el de ingresos, obteniendo un valor positivo en caso de haber ganancia o negativo en caso de pérdida.

Pantalla:

CONCLUSIONES

El desarrollo del presente Sistema de Información dejó diversas apreciaciones en las distintas etapas que lo componen, las cuales se procede a mencionar a continuación.

En la etapa de análisis se logró concluir que es la etapa más compleja de la construcción de un sistema, pues toca enfrentar los requerimientos del cliente, y se debe revisar constantemente lo que se necesita, ya que generalmente no es conciso en sus requerimientos, además de que las ideas de optimización no siempre coincidirán con la perspectiva del cliente.

En la etapa de diseño se pudo concluir que la concepción de la Base de Datos es un proceso sumamente crítico en el desarrollo, puesto que siempre está susceptible a cambios provocados por nuevos requerimientos y modificación por parte del cliente, o bien por la aparición de nuevas tablas durante el proceso de normalización.

En la etapa de construcción de las interfaces de usuario, se logró concluir que si bien lo más difícil fue lograr una interfaz atractiva y cómoda para el cliente, es una etapa relativamente más fácil que las anteriores. No obstante, en situaciones donde se requieren nuevos aspectos a ser implementados, implica volver a etapas anteriores, por lo que se requiere reevaluar el proyecto desde análisis, tomando bastante tiempo y generalmente viene con una mayor carga de trabajo.

Tras la finalización de este trabajo se concluye que se pudo cumplir con los objetivos señalados con anterioridad. Los resultados del sistema propuesto cumplen con los objetivos señalados con anterioridad y las expectativas tanto nuestras como las del cliente. También cabe señalar que todo el proceso de desarrollo es arduo y bastante complejo y, para desarrollarlo de la mejor manera es vital la comunicación con el cliente y un profundo análisis de todos los requerimientos solicitados. Toda la construcción de este sistema implicó adquirir conocimientos importantes para nuestra formación como profesionales del área de informática.

Como futura proyección del sistema se visualiza agregar un mayor detalle de datos en la generación de informes, además de permitir que éstos puedan ser exportados en formato Excel. Como segunda proyección se planea implementar la impresión de boletas junto con su detalle correspondiente. Evolucionar el funcionamiento de la base de datos migrándola a un servidor en red local, otorgando el acceso de los distintos dispositivos conectados a la misma red. Ésto permite, además, poder implementar una aplicación que posibilite a los garzones tomar pedidos desde dispositivos móviles (Tablets), eliminando asi el uso de papel para registrar los productos pedidos.

BIBLIOGRAFÍA https://www.mysql.com/about/ https://es.wikipedia.org/wiki/Entorno_de_desarrollo_integrado https://netbeans.org/features/index.html https://mariadb.org/ http://www.w3api.com/wiki/Java:String.equals()

Anexos Anexo 1 *formMenu.java import java.awt.Color; import java.awt.FlowLayout; import java.awt.Toolkit; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.table.DefaultTableModel; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Calendar; import javax.swing.JButton; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JToggleButton;

public class formMenu extends javax.swing.JFrame implements KeyListener, ActionListener, ItemListener{

private List<JButton> botonesMesas; private Integer indice ;

private Statement sentencia; /*puedo ocupar sentencias de control sql*/

private Connection conexion; /*objeto que permite conectar mi base datos con programa*/ /* private String nomBD="bussandwicheria";

private String usuario="root";

private String password="informatica"; */ private String msj;

private int cantidad_mesas; private int limite_llevar; private int contLlevarN; public formMenu() { initComponents(); limite_llevar = 20; contLlevarN = 0;

botonesMesas = new ArrayList<>(); indice = 0 ;

conectar();

this.setLocationRelativeTo(null); setIcon();

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd"); LocalDate localDate = LocalDate.now();

txtFecha.setText(dtf.format(localDate)); GetTurno();

cantidad_mesas = contarMesas(); mostrarMesasN();

mostrarLlevarN();

this.getContentPane().setBackground(Color.orange); }

public formMenu(String text, String text0) {

throw new UnsupportedOperationException("Not supported yet."); }

public void conectar() { try{

Class.forName("com.mysql.jdbc.Driver");

String url ="jdbc:mysql://localhost:3306/"+this.nomBD;

this.conexion=(Connection)DriverManager.getConnection(url,this.usuario,this.password); this.sentencia=(Statement)this.conexion.createStatement(); } catch(Exception e){ } }

public void insertar(String sql){ try{ sentencia.executeUpdate(sql); msj="Datos guardados"; } catch(SQLException e){ System.out.print(e.getMessage()); msj="no ingreso"; } }

private void setIcon() {

setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/imagen/icono.png" )));

}

public int GetPedidoNuevo(){ String query="";

ResultSet existe; int num=0; int numped = 0; try {

sentencia = (Statement) conexion.createStatement();

query = "SELECT * FROM pedido where fecha_venta = '" + txtFecha.getText() + "'"; existe = sentencia.executeQuery(query);

if (existe.next() == false) { numped = 1; } else {

try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT * FROM pedido where fecha_venta = '" + txtFecha.getText() + "'") ;

while (lista.next()) { num = (lista.getInt("numero_pedido")); numped = num + 1; } }catch (SQLException e) { } } } catch (SQLException e) { } return numped; }

public String GetEstadoPedido(int pedido){ String state = "";

String query = ""; ResultSet existe;

String valFecha = txtFecha.getText(); try {

sentencia = (Statement) conexion.createStatement();

query = "SELECT * from pedido where numero_pedido = " + pedido + " and fecha_venta = '" + valFecha + "'"; existe = sentencia.executeQuery(query); if (existe.next() == false){ state = "N"; } else { try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT estado_pedido FROM pedido where numero_pedido = " + pedido + " and fecha_venta = '" + valFecha + "'"); while (lista.next()) { state = (lista.getString("estado_pedido")); } } catch (SQLException e) { state = "N"; } } } catch (SQLException e) { state = "N"; } return state; }

public int ConsultarEstadoMesa(int codmesa){ boolean ocupada = false;

int cod_ped = 0;

String estado = ""; try{

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT estado FROM mesas where numero_mesa = " + codmesa);

while (lista.next()) { estado = (lista.getString("estado")); if (estado.equals("L")){ ocupada = false; }else{ ocupada = true; } } }catch (SQLException e) { } if (ocupada == false){ cod_ped = GetPedidoNuevo(); }else{ try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT numero_pedido FROM mesas where numero_mesa = " + codmesa);

int cont = 0; while (lista.next()) { cod_ped = (lista.getInt("numero_pedido")); } }catch (SQLException e) { } } return cod_ped; }

public int consultar_estado_llevar(int v_idllevar){ int estado = 0;

try{

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT estado_llevar FROM llevar where id_llevar = " + v_idllevar); while (lista.next()) { estado = (lista.getInt("estado_llevar")); } }catch (SQLException e) { } return estado; }

public int consultar_pedido_llevar(int v_idllevar){ boolean ocupada = false;

int cod_ped = 0; int estado = 0; try{

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT estado_llevar FROM llevar where id_llevar = " + v_idllevar);

while (lista.next()) {

estado = (lista.getInt("estado_llevar")); if (estado ==(0)){

ocupada = false; }else{ ocupada = true; } } }catch (SQLException e) { } if (ocupada == false){ cod_ped = GetPedidoNuevo(); }else{ try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT numero_ped FROM llevar where id_llevar = " + v_idllevar); int cont = 0; while (lista.next()) { cod_ped = (lista.getInt("numero_ped")); } }catch (SQLException e) { } } return cod_ped; }

public String GetTurno(){

Calendar calendario = Calendar.getInstance(); String watashinoturn = "";

int hora, minutos;

hora =calendario.get(Calendar.HOUR_OF_DAY); minutos = calendario.get(Calendar.MINUTE); if (hora < 17){ watashinoturn = "D"; }else{ watashinoturn = "V"; } return watashinoturn; }

public int contarMesas(){ int cant_mesa = 12; try{

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT * FROM mesas"); cant_mesa = 0;

while (lista.next()) { cant_mesa = cant_mesa + 1;

System.out.println("cant mesa" + cant_mesa); } }catch (SQLException e) { e.printStackTrace(); } return cant_mesa; }

public void modificarJscrollMesasLayout(){

}

public void mostrarMesas() { Integer contMesas = 0 ; Integer sumarX = 0 ; Integer sumarY = 0 ; Integer cantASumarX = 85; Integer cantASumarY = 50;

while (contMesas < cantidad_mesas){ JButton auxNomBtn =new JButton("1");

auxNomBtn .setText(String.valueOf("Mesa " + (contMesas + 1)));

auxNomBtn .reshape(20 + sumarX,120 + sumarY,80,40);// x,y,ancho,largo auxNomBtn.addActionListener(this);

auxNomBtn.setActionCommand(String.valueOf(contMesas)); auxNomBtn .setName(String.valueOf(contMesas));

if ( ((contMesas+1) % 4 == 0)) { sumarY = sumarY + cantASumarY; sumarX = sumarX - cantASumarX*4; }

contMesas = 1 + contMesas ; sumarX = sumarX + cantASumarX; }

}

public void mostrarLlevarN(){

while ( contLlevarN < limite_llevar){

JButton auxNomBtn =new JButton("Llevar " + (contLlevarN+1) ); panelLlevar.add(auxNomBtn); panelLlevar.updateUI(); auxNomBtn.addActionListener(this); auxNomBtn.setActionCommand("L"+String.valueOf(contLlevarN )); auxNomBtn.setName("L"+String.valueOf(contLlevarN)); contLlevarN = contLlevarN + 1; } }

public void mostrarMesasN(){ Integer contN = 0;

while (contN < cantidad_mesas){

JButton auxNomBtn =new JButton("Mesa " + (contN+1) ); panelMesas.add(auxNomBtn); panelMesas.updateUI(); auxNomBtn.addActionListener(this); auxNomBtn.setActionCommand("M"+String.valueOf(contN )); auxNomBtn.setName("M"+String.valueOf(contN )); contN = contN + 1; } }

int num_pedido = ConsultarEstadoMesa(auxNumBotonMesa); String turno_act = GetTurno();

String stat = GetEstadoPedido(num_pedido);

formPedido pedi = new formPedido(txtFecha.getText(), auxNumBotonMesa, num_pedido, "S", stat, turno_act);

System.out.println("menu, estado: " + stat); pedi.setVisible(true);

}

public void ingresarAFormLlevar(Integer auxNumBotonLlevar ){ int num_pedido = consultar_pedido_llevar(1);

String turno_act = GetTurno();

String stat = GetEstadoPedido(num_pedido);

formPedido pedi = new formPedido(txtFecha.getText(), num_pedido, "L", stat, turno_act, auxNumBotonLlevar);

pedi.setVisible(true);

}

public void actionPerformed(ActionEvent e) { Integer contAbstracto =0;

while (contAbstracto < cantidad_mesas){

if(e.getActionCommand().equals("M"+(String.valueOf(contAbstracto)))){ ingresarAFormMesas(contAbstracto); } if(e.getActionCommand().equals("L"+(String.valueOf(contAbstracto)))){ ingresarAFormLlevar(contAbstracto); } contAbstracto = contAbstracto + 1 ; } } ///////////////////////// Botones ////////////// @SuppressWarnings("unchecked") private void initComponents() {

scrollPane1 = new java.awt.ScrollPane(); jLabel1 = new javax.swing.JLabel();

jSeparator1 = new javax.swing.JSeparator(); jLabel2 = new javax.swing.JLabel();

jSeparator2 = new javax.swing.JSeparator(); btnRegresar = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jButton11 = new javax.swing.JButton(); jSeparator3 = new javax.swing.JSeparator(); txtFecha = new javax.swing.JTextField();

scrollPanelMesas = new javax.swing.JScrollPane(); panelMesas = new javax.swing.JPanel();

scrollPaneLlevar = new javax.swing.JScrollPane(); panelLlevar = new javax.swing.JPanel();

btnAumentoLlevar = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Layout de Mesas");

jLabel1.setText("Mesas"); jLabel2.setText("Pedidos"); btnRegresar.setText("Atrás");

btnRegresar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegresarActionPerformed(evt);

} });

jLabel3.setText("Fecha");

jLabel4.setText("\"EL PRIVILEGIO DEL SABOR\""); jButton11.setText("Ingresar Merma");

jButton11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton11ActionPerformed(evt); } }); txtFecha.setEditable(false); panelMesas.setLayout(new java.awt.GridLayout(0, 4)); scrollPanelMesas.setViewportView(panelMesas); panelLlevar.setLayout(new java.awt.GridLayout(0, 4)); scrollPaneLlevar.setViewportView(panelLlevar); btnAumentoLlevar.setText("Aumentar Llevar"); btnAumentoLlevar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) {

btnAumentoLlevarActionPerformed(evt); }

});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(scrollPanelMesas) .addComponent(scrollPaneLlevar) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(jLabel3) .addGap(4, 4, 4) .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(222, 222, 222) .addComponent(btnRegresar)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(130, 130, 130) .addComponent(jLabel4)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabel1) .addGap(10, 10, 10) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabel2) .addGap(10, 10, 10) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 1, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(btnAumentoLlevar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton11))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(jLabel3)) .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRegresar)) .addGap(6, 6, 6) .addComponent(jLabel4) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(scrollPanelMesas, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)

.addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(scrollPaneLlevar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton11) .addComponent(btnAumentoLlevar)) .addContainerGap()) ); pack(); }

private void btnRegresarActionPerformed(java.awt.event.ActionEvent evt) { this.setVisible(false);

this.dispose(); }

private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) { formMerma merm = new formMerma();

merm.setVisible(true); }

private void btnAumentoLlevarActionPerformed(java.awt.event.ActionEvent evt) { limite_llevar = limite_llevar + 20;

mostrarLlevarN(); }

public static void main(String args[]) { try {

for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } }

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(formMenu.class.getName()).log(java.util.logging.Level.SEV ERE, null, ex);

java.util.logging.Logger.getLogger(formMenu.class.getName()).log(java.util.logging.Level.SEV ERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(formMenu.class.getName()).log(java.util.logging.Level.SEV ERE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(formMenu.class.getName()).log(java.util.logging.Level.SEV ERE, null, ex);

}

java.awt.EventQueue.invokeLater(new Runnable() { public void run() {

new formMenu().setVisible(true); }

}); }

private javax.swing.JButton btnAumentoLlevar; private javax.swing.JButton btnRegresar; private javax.swing.JButton jButton11; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4;

private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JPanel panelLlevar; private javax.swing.JPanel panelMesas; private java.awt.ScrollPane scrollPane1;

private javax.swing.JScrollPane scrollPaneLlevar; private javax.swing.JScrollPane scrollPanelMesas; private javax.swing.JTextField txtFecha;

public void keyTyped(KeyEvent e) {

throw new UnsupportedOperationException("Not supported yet."); }

public void keyPressed(KeyEvent e) {

throw new UnsupportedOperationException("Not supported yet."); }

public void keyReleased(KeyEvent e) {

throw new UnsupportedOperationException("Not supported yet."); }

public void itemStateChanged(ItemEvent e) {

throw new UnsupportedOperationException("Not supported yet."); } } Anexo 2 *formPedido.java import java.awt.Color; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent;

import java.sql.Connection; import java.sql.Statement; import java.sql.SQLException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import javax.swing.JOptionPane; import javax.swing.table.*; import java.util.logging.*; import javax.swing.RowFilter;

public class formPedido extends javax.swing.JFrame { private Statement sentencia;

private Statement sentencia2; private Connection conexion;

private String nomBD = "bussandwicheria"; private String usuario = "root";

private String password = "informatica"; private String msj;

private TableRowSorter trsFiltro; private int SelectDetalle = -1; private int swStockInsuficiente = 0; private int id_llevar = 0;

private boolean pedido_type = true; private String mesa;

public formPedido() { initComponents(); conectar();

this.setLocationRelativeTo(null);

DefaultTableModel modelo = (DefaultTableModel) tblproductos.getModel(); DefaultTableModel modeloI = (DefaultTableModel) tbldetalle.getModel(); }

public formPedido(String fecha, int numMesa, int numPedido, String tipPedi, String stat, String turn) {

initComponents(); conectar();

this.setLocationRelativeTo(null); llenarTablaP();

String states = "stat " + stat; lblMesa.setVisible(true); txtMesa.setVisible(true); txtMesa.setText(String.valueOf(numMesa+1)); mesa = String.valueOf(numMesa); pedido_type = true; if (stat.equals("N")) {

RegistrarPedido(fecha, numPedido, tipPedi, turn); OcuparMesa(numMesa);

RegistrarDetalleMesa(numMesa, numPedido, fecha); }

if (stat.equals("A") || stat.equals("P")) { LlenarDetalle(numPedido, fecha); }

btnVuelto.setEnabled(false); txtVuelto.setEnabled(false); txtNum.setText(Integer.toString(numPedido)); txtTurno.setText(turn); txtFecha.setText(fecha); System.out.println(tipPedi); this.getContentPane().setBackground(Color.orange); setIcon(); }

public formPedido(String fecha, int numPedido, String tipPedi, String stat, String turn, int idLLevar) { initComponents(); conectar(); lblMesa.setVisible(false); txtMesa.setVisible(false); txtMesa.setText(""); id_llevar = idLLevar; pedido_type = false; this.setLocationRelativeTo(null); llenarTablaP(); if (stat.equals("N")) { registrarPedido_llevar(idLLevar, numPedido); RegistrarPedido(fecha, numPedido, tipPedi, turn); registrarEstado_llevar(idLLevar); } if (stat.equals("A") || stat.equals("P")) { LlenarDetalle(numPedido, fecha); } btnVuelto.setEnabled(false); txtVuelto.setEnabled(false); txtNum.setText(Integer.toString(numPedido)); txtTurno.setText(turn); txtFecha.setText(fecha); System.out.println(tipPedi);

System.out.println("pedido llevar, stat" + stat); this.getContentPane().setBackground(Color.orange); setIcon();

}

public Integer comprobarExistencia(String auxCodProd ){ Integer existex = (-1);

Integer nuevaCantidad = 0 ;

int largo = tbldetalle.getRowCount(); for (int i = 0; i < largo; i++) {

Object codp = tbldetalle.getValueAt(i, 0); String auxCodP = codp.toString();

if (txtcod.getText().equals(auxCodP)){ existex = i ; } } return existex ; }

String sql = "UPDATE llevar set num_ped = " + v_numped + " WHERE id_llevar= " + v_numLLevar;

insertar(sql); }

public void registrarEstado_llevar(int v_numLLevar){

String sql = "UPDATE llevar set estado_llevar = 1 WHERE id_llevar=" + v_numLLevar; insertar(sql);

}

public void RegistrarPedido(String valFecha, int valNumPedido, String valtipPedi, String turn) {

String sql = "INSERT INTO pedido VALUES (" + valNumPedido + ",'" + valFecha + "'," + 0 + ",'" + turn + "','" + valtipPedi + "','" + "" + "'," + 0 + ",'" + "A" + "')";

insertar(sql); }

public void RegistrarDetalleMesa(int varNumMesa, int varNumPedido, String varFecha) { String sql = "UPDATE mesas set numero_pedido = " + varNumPedido + " where numero_mesa = " + varNumMesa + "";

System.out.println(sql); insertar(sql);

}

public void LlenarDetalle(int valNumePedido, String valFecha) { int auxCodP = 0;

int auxCant = 0; int auxPre = 0; String auxEst = ""; try {

System.out.println("llenar tabala detalle");

sentencia = (Statement) conexion.createStatement();

String query = "SELECT * FROM detalle_pedido where numero_pedido = " + valNumePedido + " and fecha_venta = '" + valFecha + "'";

ResultSet lista = sentencia.executeQuery(query); int cont = 0; while (lista.next()) { auxCodP = (lista.getInt("cod_producto")); auxCant = (lista.getInt("cantidad")); auxPre = (lista.getInt("precio")); auxEst = (lista.getString("estado")); String auxNom = ""; try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista1 = sentencia.executeQuery("SELECT * FROM producto where cod_producto =" + auxCodP);

while (lista1.next()) {

auxNom = (lista1.getString("nombre_producto")); }

} catch (SQLException e) { msj = "no se pudo seleccionar"; }

DefaultTableModel modeloDetalle = (DefaultTableModel) tbldetalle.getModel(); modeloDetalle.addRow(new Object[]{auxCodP, auxNom, auxPre, auxCant, auxEst}); cont = cont + 1;

}

} catch (SQLException e) { msj = "no se pudo seleccionar"; }

}

public void conectar() { try {

Class.forName("com.mysql.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/" + this.nomBD;

this.conexion = (Connection) DriverManager.getConnection(url, this.usuario, this.password);

this.sentencia = (Statement) this.conexion.createStatement(); } catch (Exception e) {

msj = "error al conectar"; }

}

public void insertar(String sql) { try { sentencia.executeUpdate(sql); msj = "Datos guardados"; } catch (SQLException e) { System.out.print(e.getMessage()); msj = "no ingreso"; } }

private void setIcon() {

setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/imagen/icono.png" )));

}

public void llenarTablaP() { String auxCod = ""; String auxNom = ""; String auxPre = ""; String auxStock = ""; try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT * FROM producto"); int cont = 0;

while (lista.next()) {

auxCod = (lista.getString("cod_producto")); //System.out.println(auxCod); auxNom = (lista.getString("nombre_producto")); // System.out.println(auxNom); auxPre = (lista.getString("precio")); // System.out.println(auxPre); auxStock = calcularStockVirtual(auxCod);

DefaultTableModel modelo = (DefaultTableModel) tblproductos.getModel(); modelo.addRow(new Object[]{auxCod, auxNom, auxPre,auxStock});

cont = cont + 1; }

} catch (SQLException e) { msj = "no se pudo seleccionar"; }

}

public void limpiarTablaP() { try {

DefaultTableModel modelo = (DefaultTableModel) tblproductos.getModel(); int filas = tblproductos.getRowCount();

for (int i = 0; filas > i; i++) { modelo.removeRow(0); }

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error al limpiar la tabla."); }

}

public void llenarTablaDP(){ String auxCod = ""; String auxCant = ""; String auxPre = ""; String auxState = ""; String auxNom = "";

String auxFec = txtFecha.getText(); String auxNum = txtNum.getText(); int auxiNum = Integer.parseInt(auxNum); try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT * FROM detalle_pedido where fecha_venta = '" + auxFec + "' and numero_pedido = " + auxiNum + "");

int cont = 0; while (lista.next()) { auxCod = (lista.getString("cod_producto")); auxCant = (lista.getString("cantidad")); auxPre = (lista.getString("precio")); auxState = (lista.getString("precio"));

DefaultTableModel modelo = (DefaultTableModel) tbldetalle.getModel(); modelo.addRow(new Object[]{auxCod, auxCant, auxPre,auxState}); cont = cont + 1;

}

} catch (SQLException e) { msj = "no se pudo seleccionar"; }

}

public void limpiarTablaDP(){ try {

DefaultTableModel modelo = (DefaultTableModel) tbldetalle.getModel(); int filas = tbldetalle.getRowCount();

for (int i = 0; filas > i; i++) { modelo.removeRow(0); }

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error al limpiar la tabla."); }

}

public void CalcularTotal() { int total = 0;

int largo = tbldetalle.getRowCount(); System.out.println("el largo es: " + largo); for (int i = 0; i < largo; i++) {

Object valor = tbldetalle.getValueAt(i, 3); int auxValor = Integer.parseInt(valor.toString()); total = total + auxValor;

} }

public void OcuparMesa(int valMesa) {

String sql = "UPDATE mesas set estado='O' WHERE numero_mesa=" + valMesa; insertar(sql);

}

public void limpiarCampos() { txtcod.setText("");

txtnom.setText(""); txtprec.setText(""); spinCant.setValue(1); }

public String calcularStockVirtual(String paramCodProd) { String returnStockVirtual = "000";

String auxCodInsumox = "111"; String auxCodProd = paramCodProd; float valorMinimo = 0; float auxCantDetalle = 0; Integer auxCantIns = 0; float auxStockVirtual = 0; float auxStockInsumo = 0; Integer swValorMin = 1; try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT * FROM detalle_producto where cod_producto ='" + auxCodProd + "'");

int cont = 0;

while (lista.next()) {

auxCodInsumox = (lista.getString("cod_insumo"));

auxCantDetalle = Float.parseFloat((lista.getString("cantidad"))); sentencia2 = (Statement) conexion.createStatement();

ResultSet lista2 = sentencia2.executeQuery("SELECT * FROM insumos where cod_insumo ='" + auxCodInsumox + "'");

while (lista2.next()) {

auxStockInsumo = Float.parseFloat((lista2.getString("stock_actual"))); }

auxStockVirtual = auxStockInsumo / auxCantDetalle; if (swValorMin == 1) { valorMinimo = auxStockVirtual; swValorMin = 2; } if (swValorMin == 2) { if (auxStockVirtual < valorMinimo) { valorMinimo = auxStockVirtual; } }

}

} catch (SQLException e) { msj = "no se pudo seleccionar"; }

int retorno = (int)valorMinimo ;

returnStockVirtual = Integer.toString(retorno); return returnStockVirtual;

}

public void ActualizarStockAuto(int v_codProd, int v_cant, int v_tipoAct) { String auxCodIns = "";

float auxCant = 0; try {

System.out.println("actualizar stock");

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT * FROM detalle_producto WHERE cod_producto= " + v_codProd + "");

int cont = 0;

while (lista.next()) {

auxCodIns = lista.getString("cod_insumo");

auxCant = (Float.parseFloat(lista.getString("cantidad"))) * v_cant; if (v_tipoAct == 1) {

descontarAumentarInsumo(auxCodIns, v_tipoAct, auxCant); }

if (v_tipoAct == 2) {

descontarAumentarInsumo(auxCodIns, v_tipoAct, auxCant); }

}

} catch (SQLException e) { msj = "no se pudo seleccionar"; }

}

public void descontarAumentarInsumo(String paramCodIns, Integer accion, float cantidad) { int switchNoNegativo = 0;

String auxCodIns = paramCodIns; float auxMontoBD = 0;

float auxMontoForm = cantidad; float auxMontoNuevo = 0; String query = "";

String auxTipoAjuste = "X"; String auxObs = "Nada"; try {

sentencia = (Statement) conexion.createStatement();

ResultSet lista = sentencia.executeQuery("SELECT * FROM insumos where cod_insumo ='" + auxCodIns + "'"); int cont = 0; while (lista.next()) { auxMontoBD = Float.parseFloat((lista.getString("stock_actual"))); if (accion == 1) {

auxMontoNuevo = auxMontoBD + auxMontoForm; }

auxMontoNuevo = auxMontoBD - auxMontoForm;

System.out.println(auxMontoNuevo + "=" + auxMontoBD + "-" + auxMontoForm); }

if (auxMontoNuevo < 0) { switchNoNegativo = 1; swStockInsuficiente = 1;

JOptionPane.showMessageDialog(null, "Error! Cantidad de insumos solicitados NO disponible", "ERROR", JOptionPane.INFORMATION_MESSAGE);

}

cont = cont + 1; }

} catch (SQLException e) { msj = "no se pudo seleccionar"; }

if (switchNoNegativo == 0) { ResultSet existe;

try {

query = "SELECT * FROM insumos where cod_insumo ='" + auxCodIns + "'"; existe = sentencia.executeQuery(query);

if (existe.next() == true) {

String sql = "UPDATE insumos SET stock_actual='" + auxMontoNuevo + "'WHERE cod_insumo ='" + auxCodIns + "'";

try {

sentencia.executeUpdate(sql); } catch (SQLException e) { msj = "no ingreso";

JOptionPane.showMessageDialog(null, "Datos no actualizados", "Error", JOptionPane.INFORMATION_MESSAGE);

}

msj = "Modificado"; } else {

msj = "Insumo seleccionado no existe";

JOptionPane.showMessageDialog(null, msj, "INFORMACION", JOptionPane.INFORMATION_MESSAGE);

}

} catch (SQLException e) {

msj = "No existe persona, no se puede modificar"; }

} }

@SuppressWarnings("unchecked") private void initComponents() {

buttonGroup2 = new javax.swing.ButtonGroup(); jScrollPane1 = new javax.swing.JScrollPane(); tblproductos = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); tbldetalle = new javax.swing.JTable();

btnAgregar = new javax.swing.JButton(); txtcod = new javax.swing.JTextField(); txtnom = new javax.swing.JTextField();

rbtnEfectivo = new javax.swing.JRadioButton(); rbtnTarjeta = new javax.swing.JRadioButton(); rbtnCredito = new javax.swing.JRadioButton(); spinCant = new javax.swing.JSpinner();

txtTotal = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtPago = new javax.swing.JTextField(); btnVuelto = new javax.swing.JButton();

Documento similar