mx.edu.ittepic.AEEcommerce.ejbs.OperationCommerce.java Source code

Java tutorial

Introduction

Here is the source code for mx.edu.ittepic.AEEcommerce.ejbs.OperationCommerce.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.edu.ittepic.AEEcommerce.ejbs;

import javax.ejb.Stateless;
import javax.persistence.Query;
import com.google.gson.GsonBuilder;
import com.google.gson.Gson;
import java.nio.file.Paths;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.LockTimeoutException;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.PessimisticLockException;
import javax.persistence.QueryTimeoutException;
import javax.persistence.TransactionRequiredException;
import javax.servlet.http.Part;
import mx.edu.ittepic.AEEcommerce.entities.Category;
import mx.edu.ittepic.AEEcommerce.entities.Product;
import mx.edu.ittepic.AEEcommerce.util.Message;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.EntityExistsException;
import mx.edu.ittepic.AEEcommerce.entities.Carrito;
import mx.edu.ittepic.AEEcommerce.entities.Company;
import mx.edu.ittepic.AEEcommerce.entities.Role;
import mx.edu.ittepic.AEEcommerce.entities.Sale;
import mx.edu.ittepic.AEEcommerce.entities.Salesline;
import mx.edu.ittepic.AEEcommerce.entities.Users;
import org.apache.commons.codec.digest.DigestUtils;

@Stateless
public class OperationCommerce {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext
    EntityManager entity; //ya tiene las conexiones con las entidades.
    List<Role> listRoles;
    List<Company> listCompany;
    List<Users> listUsers;
    List<Category> listCateg;
    List<Carrito> listCarrito;
    List<Sale> listVenta;
    List<Salesline> listVentaDetalle;

    public String newVentaDetalle(String productid, String purchprice, String quantity, String saleid,
            String saleprice) {

        Message m = new Message();
        listVentaDetalle = null;
        Query q = null;
        Salesline p = new Salesline();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        Sale us = entity.find(Sale.class, Integer.parseInt(saleid));
        Product pr = entity.find(Product.class, Integer.parseInt(productid));
        if (us == null || pr == null) {
            m.setCode(404);
            m.setMsg("No se encontro el usuario o el producto");
            m.setDetail(":(");
        } else {
            p.setProductid(pr);
            p.setPurchprice(Double.parseDouble(purchprice));
            p.setQuantity(Integer.parseInt(quantity));
            p.setSaleid(us);
            p.setSaleprice(Double.parseDouble(saleprice));
            entity.persist(p);
            entity.flush();

            m.setCode(200);
            m.setMsg("Todo bien compa");
            m.setDetail("OK, El id de la venta es: " + p.getSaleid().toString());
        }
        return gson.toJson(m);
    }

    public String getVenta(String date, String userid) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Date dat = null;
        String d;
        try {
            dat = formatter.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Message m = new Message();
        listVenta = null;
        Query q = null;
        String msg = "";
        Sale p = new Sale();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        q = entity.createNativeQuery("Select * From sale where date ='" + date + "' and userid=" + userid);
        listVenta = q.getResultList();

        msg = gson.toJson(listVenta);
        m.setCode(200);
        m.setMsg(msg);
        m.setDetail("Ok");

        return gson.toJson(m);
    }

    public String newVenta(String amount, String userid) {
        Date fecha = new Date();
        Message msg = new Message();
        listVenta = null;
        Query q = null;
        Sale p = new Sale();
        Users u = new Users();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        q = entity.createNamedQuery("Users.findByApikey").setParameter("apikey", userid);
        u = (Users) q.getSingleResult();
        if (u == null) {
            msg.setCode(404);
            msg.setMsg("No se encontro el usuario");
            msg.setDetail(":(");
        } else {
            p.setAmount(Double.parseDouble(amount));
            p.setDate(fecha);
            p.setUserid(u);

            entity.persist(p);
            entity.flush();

            decrementar(userid);

            msg.setCode(200);
            msg.setMsg("Todo bien compa");
            msg.setDetail(p.getSaleid().toString());

        }
        return gson.toJson(msg);
    }

    public String getCarrito(String idcarrito) {
        Carrito c = new Carrito();
        Message m = new Message();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        Query q = entity.createNamedQuery("Carrito.findByIdcarrito").setParameter("idcarrito", idcarrito);
        listCarrito = q.getResultList();
        msg = gson.toJson(listCarrito);
        m.setCode(200);
        m.setMsg(msg);
        m.setDetail("OK");
        return gson.toJson(m);
    }

    public String newCarrito(String productid, String sesion, String productname, String cantidad, String precio,
            String preciomay) {
        Message m = new Message();
        listCarrito = null;
        Query q = null;
        Carrito p = new Carrito();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        q = entity.createNamedQuery("Carrito.findBySesion").setParameter("idcarrito", sesion)
                .setParameter("productid", Integer.parseInt(productid));
        //Query q = entity.createNativeQuery("SELECT c FROM Carrito c WHERE idcarrito =" + Integer.parseInt(sesion) + " and c.productid=" + Integer.parseInt(productid));
        listCarrito = q.getResultList();
        if (listCarrito.size() == 0) {
            p.setIdcarrito(sesion);
            p.setProdname(productname);
            p.setCantidad(Integer.parseInt(cantidad));
            p.setProductid(Integer.parseInt(productid));
            p.setSalepricemay(Double.parseDouble(preciomay));
            p.setSalepricemin(Double.parseDouble(precio));

            entity.persist(p);
            entity.flush();

            m.setCode(200);
            m.setMsg("Todo bien compa");
            m.setDetail("OK, El id es:" + p.getProductid().toString());

        } else {
            int can = listCarrito.get(0).getCantidad();
            can++;
            q = entity.createNamedQuery("Carrito.EditarCarritoCantidad").setParameter("cantidad", can)
                    .setParameter("idcarrito", sesion).setParameter("productid", Integer.parseInt(productid));
            q.executeUpdate();
            entity.clear();

            m.setCode(200);
            m.setMsg("Todo bien compa");
            m.setDetail("Se actualizo correctamente");

        }
        return gson.toJson(m);
    }

    public String deleteCarrito(String productid) {
        Message m = new Message();
        listCarrito = null;
        Query q = null;
        Carrito p = new Carrito();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        q = entity.createNamedQuery("Carrito.findByIdcarrito").setParameter("idcarrito", productid);
        listCarrito = q.getResultList();

        if (listCarrito == null) {
            m.setCode(404);
            m.setMsg("No se encontro");
            m.setDetail(":(");
        } else {
            for (Carrito c : listCarrito) {
                entity.remove(c);
            }

            m.setCode(200);
            m.setMsg("Todo bien");
            m.setDetail("OK");
        }
        return gson.toJson(m);
    }

    public String updateCarrito(String productid, String sesion, String cantidad) {
        Message m = new Message();
        Carrito p = new Carrito();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        entity.createNativeQuery("UPDATE Carrito SET cantidad=" + (Integer.parseInt(cantidad) + 1)
                + " WHERE idcarrito = " + sesion + " and productid =" + Integer.parseInt(productid));
        entity.flush();

        m.setCode(200);
        m.setMsg("Todo bien");
        m.setDetail("OK");

        return gson.toJson(m);
    }

    public String getRoles() {

        Message m = new Message();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json

        Query q = entity.createNamedQuery("Role.findAll");
        listRoles = q.getResultList();

        //Este codigo es para convertir list de objetos en json
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        msg = gson.toJson(listRoles);

        m.setCode(200);
        m.setMsg(msg);
        m.setDetail("OK");
        return gson.toJson(m);

    }

    public String updateRole(String roleid, String name) {
        Message m = new Message();
        /*CREACION DEL OBJETO ROL*/
        Role r = new Role();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        /*try {
        r.setRoleid(Integer.parseInt(roleid));
        r.setRolename(name);
        //Actualiza BD//
        entity.refresh(entity.merge(r));
        //el merge tiene una caracteristica especial, se puede crear algo que se llame native query,persist guarda un nuevo registro, el merge
        si el id del role ya existe lo actualiza y si no existe crea uno nuevo.
         //
        m.setCode(200);
        m.setMsg("El rol se actualizo correctamente");
        m.setDetail("OK");
        } catch (NumberFormatException e) {
        m.setCode(406);
        m.setMsg("Error de tipo de dato '" + roleid + "'");
        m.setDetail(e.toString());
        }*/

        //La linea siguiente, es una forma de hacer update
        //Query q = entity.createNativeQuery("UPDATE role SET rolename='"+name+"' WHERE roleid="+roleid);
        //La linea siguiente, es otra forma de hacer update
        //Query q = entity.createNamedQuery("Role.updateRole").setParameter("name", name).setParameter("id", Integer.parseInt(roleid));
        //Esta es otra forma de hacer un update, esta es la forma recomendada
        r = entity.find(Role.class, Integer.parseInt(roleid));
        if (r == null) {
            m.setCode(404);
            m.setMsg("No se encontro");
            m.setDetail(":(");
        } else {
            r.setRolename(name);
            entity.merge(r);
            m.setCode(200);
            m.setMsg("Todo bien");
            m.setDetail("OK");
        }

        //Cuando sea un update, se pone la siguiente linea para ejecutar el query        
        /*if (q.executeUpdate() == 1) {
        m.setCode(200);
        m.setMsg("Todo bien");
        m.setDetail("OK");
        } else {
        m.setCode(404);
        m.setMsg("No se encontro");
        m.setDetail(":(");
        }*/
        //Lo que restaria es manejar todas las excepciones//
        return gson.toJson(m);

    }

    public String CreateRole(String name) {
        Message m = new Message();
        /*CREACION DEL OBJETO ROL*/
        Role r = new Role();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            r.setRolename(name);
            /*Actualiza BD*/
            entity.persist(r);
            entity.flush();
            /*el merge tiene una caracteristica especial, se puede crear algo que se llame native query,persist guarda un nuevo registro, el merge
            si el id del role ya existe lo actualiza y si no existe crea uno nuevo.
             */
            m.setCode(200);
            m.setMsg("El rol se creo correctamente");
            m.setDetail(r.getRoleid().toString());
        } catch (Exception e) {
            m.setCode(406);
            m.setMsg("Error de tipo de dato '" + name + "'");
            m.setDetail(e.toString());
        }
        return gson.toJson(m);
    }

    public String getRole(String roleid) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        Role role;
        /*
            
        Query q = entity.createNamedQuery("Role.findByRoleid").setParameter(roleid, Integer.parseInt(roleid));
        role = (Role) q.getSingleResult();
        role.setUsersList(null);
            
        m.setCode(200);
        m.setMsg(gson.toJson(role));
        m.setDetail("OK");*/

        Query q = entity.createNativeQuery("Select roleid, rolename From role Where roleid=" + roleid, Role.class);
        role = (Role) q.getSingleResult();

        return gson.toJson(m);
    }

    public String deleteRole(String roleid) {
        Message m = new Message();
        Role r = new Role();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        Query q = entity.createNamedQuery("Role.findByRoleid").setParameter("roleid", Integer.parseInt(roleid));
        r = (Role) q.getSingleResult();
        if (r == null) {
            m.setCode(404);
            m.setMsg("No se encontro");
            m.setDetail(":(");
        } else {
            entity.remove(r);
            m.setCode(200);
            m.setMsg("Todo bien");
            m.setDetail("OK");
        }
        return gson.toJson(m);

    }

    public String getUser(String user, String contra) {

        Message m = new Message();
        Users u = new Users();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Query q = entity.createNamedQuery("Users.findByUsername").setParameter("username", user);
            listUsers = q.getResultList();

            if (u == null) {

            } else if (listUsers.get(0).getPassword().equals(contra)) {
                msg = gson.toJson(u);
                m.setCode(200);
                m.setMsg(msg);
                m.setDetail("OK");
            } else {
                m.setCode(406);
                m.setMsg("No tiene permiso");
                m.setDetail(":(");
            }
        } catch (NoResultException e) {
            m.setCode(406);
            m.setMsg("No tiene permiso");
            m.setDetail(":(");
        }
        return gson.toJson(m);
    }

    /*TODO LO NUEVO QUE HICE*/
    /*CRUD DE COMPANY*/
    public String newCompany(String CompanyName, String neighborhood, String zipcode, String city, String country,
            String state, String region, String street, String streetnumber, String phone, String rfc,
            String logo) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Company p = new Company();

            p.setCompanyname(CompanyName);
            p.setNeighborhood(neighborhood);
            p.setZipcode(zipcode);
            p.setCity(city);
            p.setCountry(country);
            p.setState(state);
            p.setRegion(region);
            p.setStreet(street);
            p.setStreetnumber(streetnumber);
            p.setPhone(phone);
            p.setRfc(rfc);
            p.setLogo(logo);

            entity.persist(p);
            entity.flush();

            m.setCode(200);
            m.setMsg("Todo bien compa");
            m.setDetail("OK, El id es:" + p.getCompanyid().toString());
            return gson.toJson(m);
        } catch (EntityExistsException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        } catch (IllegalArgumentException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        } catch (PersistenceException exx) {
            m.setCode(404);
            m.setMsg(exx.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        }
    }

    public String updateCompany(String companyid, String companyname, String city, String country, String neigh,
            String zipcode, String state, String region, String street, String streetnumber, String phone,
            String rfc, String logo) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Company r = new Company();
            r = entity.find(Company.class, Integer.parseInt(companyid));
            if (r == null) {
                m.setCode(404);
                m.setMsg("No se encontro");
                m.setDetail(":(");
            } else {
                r.setCompanyname(companyname);
                r.setCity(city);
                r.setCountry(country);
                r.setNeighborhood(neigh);
                r.setZipcode(zipcode);
                r.setState(state);
                r.setRegion(region);
                r.setStreet(street);
                r.setStreetnumber(streetnumber);
                r.setPhone(phone);
                r.setRfc(rfc);
                r.setLogo(logo);
                entity.merge(r);
                m.setCode(200);
                m.setMsg("Todo bien");
                m.setDetail("OK");
            }
            return gson.toJson(m);
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("Error");
            return gson.toJson(m);
        } catch (TransactionRequiredException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("Error");
            return gson.toJson(m);
        }

    }

    public String deleteCompany(String CompanyId) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Company r = new Company();
            Query q = entity.createNamedQuery("Company.findByCompanyid").setParameter("companyid",
                    Integer.parseInt(CompanyId));
            r = (Company) q.getSingleResult();
            if (r == null) {
                m.setCode(404);
                m.setMsg("No se encontro");
                m.setDetail(":(");
            } else {
                entity.remove(r);
                m.setCode(200);
                m.setMsg("Todo bien");
                m.setDetail("OK");
            }
            return gson.toJson(m);

        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (NoResultException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (IllegalStateException exx) {
            m.setCode(404);
            m.setMsg(exx.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (TransactionRequiredException exxx) {
            m.setCode(404);
            m.setMsg(exxx.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        }
    }

    public String getCompanyAll() {

        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            Query q = entity.createNamedQuery("Company.findAll");
            listCompany = q.getResultList();
            //Este codigo es para convertir list de objetos en json
            for (Company p : listCompany) {
            }
            msg = gson.toJson(listCompany);
            if (listCompany.isEmpty()) {
                m.setCode(404);
                m.setMsg(msg);
                m.setDetail("ERROR");
            } else {
                msg = gson.toJson(listCompany);
                m.setCode(200);
                m.setMsg(msg);
                m.setDetail("OK");
            }
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("OK");

        }
        return gson.toJson(m);
    }

    public String getCompanyID(String companyid) {
        Company p = new Company();
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            //Query q= entity.createNativeQuery("Select * From product Where productid="+productid,Product.class);
            Query q = entity.createNamedQuery("Company.findByCompanyid").setParameter("companyid",
                    Integer.parseInt(companyid));
            p = (Company) q.getSingleResult();
            msg = gson.toJson(p);
            m.setCode(200);
            m.setMsg(msg);
            m.setDetail("OK");
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("error");

        }
        return gson.toJson(m);
    }

    public String getCompanyName(String companyname) {
        Company p = new Company();
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            Query q = entity.createNamedQuery("Company.findByCompanyname").setParameter("companyname", companyname);

            listCompany = q.getResultList();
            if (listCompany.isEmpty()) {
                m.setCode(404);
                m.setMsg("No se encontro con esta compaia");
                m.setDetail("ERROR");
            } else {
                msg = gson.toJson(listCompany);
                m.setCode(200);
                m.setMsg(msg);
                m.setDetail("OK");
            }
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("ERROR");

        }
        return gson.toJson(m);
    }

    /* ----------------------------------------------- */
    //CRUD DE USERS
    public String newUser(String username, String password, String phone, String neigborhood, String zipcode,
            String city, String country, String state, String region, String street, String email,
            String streetnumber, Part file, String cellphone, String companyid, String roleid, String gender) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Users p = new Users();

            p.setUsername(username);
            p.setPassword(password);
            p.setPhone(phone);
            p.setNeigborhood(neigborhood);
            p.setZipcode(zipcode);
            p.setCity(city);
            p.setCountry(country);
            p.setState(state);
            p.setRegion(region);
            p.setStreet(street);
            p.setEmail(email);
            p.setStreetnumber(streetnumber);

            p.setCellphone(cellphone);
            Company companyid_ = entity.find(Company.class, Integer.parseInt(companyid));
            Role roleid_ = entity.find(Role.class, Integer.parseInt(roleid));
            if (companyid_ == null) {
                m.setCode(404);
                m.setMsg("Error" + 404);
                m.setDetail("ERROR");
                return gson.toJson(m);
            } else {
                p.setCompanyid(companyid_);
            }
            if (roleid_ == null) {
                m.setCode(404);
                m.setMsg("Error" + 404);
                m.setDetail("ERROR");
                return gson.toJson(m);
            } else {
                p.setRoleid(roleid_);
            }

            p.setGender(gender.charAt(0));
            p.setApikey("");
            entity.persist(p);
            entity.flush();
            p.setApikey(DigestUtils.md5Hex(p.getUserid().toString()));
            entity.merge(p);

            PreExamenProduct insertImg = new PreExamenProduct();
            p.setPhoto(insertImg.copyIMG(file, p.getUserid(), "Usuario"));

            m.setCode(200);
            m.setMsg("Todo bien compa");
            m.setDetail("OK, El id es:" + p.getUserid().toString());
            return gson.toJson(m);
        } catch (EntityExistsException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        } catch (IllegalArgumentException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        } catch (PersistenceException exx) {
            m.setCode(404);
            m.setMsg(exx.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        }
    }

    public String updateUsers(String userid, String username, String password, String phone, String neigborhood,
            String zipcode, String city, String country, String state, String region, String street, String email,
            String streetnumber, Part file, String cellphone, String companyid, String roleid, String gender) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Users r = new Users();
            r = entity.find(Users.class, Integer.parseInt(userid));
            if (r == null) {
                m.setCode(404);
                m.setMsg("No se encontro");
                m.setDetail(":(");
            } else {
                r.setUsername(username);
                r.setPassword(password);
                r.setPhone(phone);
                r.setNeigborhood(neigborhood);
                r.setZipcode(zipcode);
                r.setCity(city);
                r.setCountry(country);
                r.setState(state);
                r.setRegion(region);
                r.setStreet(street);
                r.setEmail(email);
                r.setStreetnumber(streetnumber);

                r.setCellphone(cellphone);
                Company companyid_ = entity.find(Company.class, Integer.parseInt(companyid));
                Role roleid_ = entity.find(Role.class, Integer.parseInt(roleid));
                r.setCompanyid(companyid_);
                r.setRoleid(roleid_);
                r.setGender(gender.charAt(0));

                String nomArch = Paths.get(file.getSubmittedFileName()).getFileName().toString();
                if (!nomArch.equals("")) {
                    PreExamenProduct updateU = new PreExamenProduct();
                    r.setPhoto(updateU.updateImagenU(file, r.getUserid()));
                } else {

                }
                entity.merge(r);

                m.setCode(200);
                m.setMsg("Todo bien");
                m.setDetail("OK");
            }
            return gson.toJson(m);
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("Error");
            return gson.toJson(m);
        } catch (TransactionRequiredException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("Error");
            return gson.toJson(m);
        }

    }

    public String deleteUsers(String userid) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Users r = new Users();
            Query q = entity.createNamedQuery("Users.findByUserid").setParameter("userid",
                    Integer.parseInt(userid));
            r = (Users) q.getSingleResult();
            if (r == null) {
                m.setCode(404);
                m.setMsg("No se encontro");
                m.setDetail(":(");
            } else {
                entity.remove(r);
                m.setCode(200);
                m.setMsg("Todo bien");
                m.setDetail("OK");
            }
            return gson.toJson(m);

        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (NoResultException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (IllegalStateException exx) {
            m.setCode(404);
            m.setMsg(exx.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (TransactionRequiredException exxx) {
            m.setCode(404);
            m.setMsg(exxx.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        }
    }

    public Object getUsersAll() {

        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            Query q = entity.createNamedQuery("Users.findAll");
            listUsers = q.getResultList();
            //Este codigo es para convertir list de objetos en json
            /*for (int i = 0; i < listUsers.size(); i++) {
            listUsers.get(i).setSaleList(null);
            }*/
            //msg = gson.toJson(listUsers);
            if (listUsers.isEmpty()) {
                m.setCode(404);
                m.setMsg("No se encontro company");
                m.setDetail("ERROR");
            } else {
                //msg = gson.toJson(listUsers);
                m.setCode(200);
                m.setMsg(msg);
                m.setDetail("OK");
            }
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("OK");

        }
        return listUsers;
    }

    public String getUsers() {

        List<Users> users;
        Message msg = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Query q = entity.createNamedQuery("Users.findAll");

            users = q.getResultList();
            msg.setCode(200);
            msg.setMsg(gson.toJson(users));
            msg.setDetail("OK");
        } catch (IllegalArgumentException e) {
            msg.setCode(422);
            msg.setMsg("Error de entidad, el usuario no es una entidad.");
            msg.setDetail(e.toString());
        } catch (IllegalStateException e) {
            msg.setCode(422);
            msg.setMsg("Error de entidad, el usuario no es una entidad o ha sido removido.");
            msg.setDetail(e.toString());
        } catch (QueryTimeoutException e) {
            msg.setCode(509);
            msg.setMsg("La operacin tardo demasiado, por favor vuelve a intentarlo.");
            msg.setDetail(e.toString());
        } catch (TransactionRequiredException e) {
            msg.setCode(509);
            msg.setMsg("La operacin tardo demasiado, por favor vuelve a intentarlo.");
            msg.setDetail(e.toString());
        } catch (PessimisticLockException e) {
            msg.setCode(400);
            msg.setMsg("Error, operacin bloqueada (Pesimistic), no se realizo la transaccin.");
            msg.setDetail(e.toString());
        } catch (LockTimeoutException e) {
            msg.setCode(400);
            msg.setMsg("Error, operacin bloqueada (Lock), no se realizo la transaccin.");
            msg.setDetail(e.toString());
        } catch (PersistenceException e) {
            msg.setCode(400);
            msg.setMsg("Error, operacin bloqueada (Persistence), no se realizo la transaccin.");
            msg.setDetail(e.toString());
        }
        return gson.toJson(msg);
    }

    public String getUsersID(String userid) {
        Users p = new Users();
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            //Query q= entity.createNativeQuery("Select * From product Where productid="+productid,Product.class);
            Query q = entity.createNamedQuery("Users.findByUserid").setParameter("userid",
                    Integer.parseInt(userid));
            p = (Users) q.getSingleResult();
            msg = gson.toJson(p);
            m.setCode(200);
            m.setMsg(msg);
            m.setDetail("OK");
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("error");

        } catch (PersistenceException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("error");

        }

        return gson.toJson(m);
    }

    public String getUsersName(String username) {
        Users p = new Users();
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            Query q = entity.createNamedQuery("Users.findByUsername").setParameter("username", username);

            listUsers = q.getResultList();
            if (listUsers.isEmpty()) {
                m.setCode(404);
                m.setMsg("No se encontro con esta usuario");
                m.setDetail("ERROR");
            } else {
                msg = gson.toJson(listUsers);
                m.setCode(200);
                m.setMsg(msg);
                m.setDetail("OK");
            }
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("ERROR");

        }
        return gson.toJson(m);
    }

    public String getUserApikey(String apikey) {
        Users u = new Users();
        List<Users> listUsers;

        Query q = null;
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = "";

        q = entity.createNamedQuery("Users.findByApikey").setParameter("apikey", apikey);

        u = (Users) q.getSingleResult();

        if (q == null) {
            m.setCode(404);
            m.setMsg("No se encontro usuario");
            m.setDetail("OK");
        } else {
            msg = gson.toJson(u);
            m.setCode(200);
            m.setMsg(msg);
            m.setDetail("OK");
        }
        return gson.toJson(m);
    }

    /* ----------------------------------------------- */
    //CRUD DE CATEGORY
    public String newCategory(String categoryname) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Category p = new Category();

            p.setCategoryname(categoryname);
            entity.persist(p);
            entity.flush();
            m.setCode(200);
            m.setMsg("Todo bien compa");
            m.setDetail("OK, El id es:" + p.getCategoryid().toString());
            return gson.toJson(m);
        } catch (EntityExistsException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        } catch (IllegalArgumentException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        } catch (PersistenceException exx) {
            m.setCode(404);
            m.setMsg(exx.getMessage());
            m.setDetail("ERROR");
            return gson.toJson(m);
        }
    }

    public String updateCategory(String categoryid, String categoryname) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Category r = new Category();
            r = entity.find(Category.class, Integer.parseInt(categoryid));
            if (r == null) {
                m.setCode(404);
                m.setMsg("No se encontro");
                m.setDetail(":(");
            } else {
                r.setCategoryname(categoryname);
                entity.merge(r);
                m.setCode(200);
                m.setMsg("Todo bien");
                m.setDetail("OK");
            }
            return gson.toJson(m);
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("Error");
            return gson.toJson(m);
        } catch (TransactionRequiredException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("Error");
            return gson.toJson(m);
        }

    }

    public String deleteCategory(String categoryid) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        try {
            Category r = new Category();
            Query q = entity.createNamedQuery("Category.findByCategoryid").setParameter("categoryid",
                    Integer.parseInt(categoryid));
            r = (Category) q.getSingleResult();
            if (r == null) {
                m.setCode(404);
                m.setMsg("No se encontro");
                m.setDetail(":(");
            } else {
                entity.remove(r);
                m.setCode(200);
                m.setMsg("Todo bien");
                m.setDetail("OK");
            }
            return gson.toJson(m);

        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (NoResultException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (IllegalStateException exx) {
            m.setCode(404);
            m.setMsg(exx.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        } catch (TransactionRequiredException exxx) {
            m.setCode(404);
            m.setMsg(exxx.getMessage());
            m.setDetail("error");
            return gson.toJson(m);
        }
    }

    public String getCategoryAll() {
        List<Category> listCateg;
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            Query q = entity.createNamedQuery("Category.findAll");
            listCateg = q.getResultList();
            //Este codigo es para convertir list de objetos en json

            msg = gson.toJson(listCateg);
            if (listCateg.isEmpty()) {
                m.setCode(404);
                m.setMsg(msg);
                m.setDetail("ERROR");
            } else {
                msg = gson.toJson(listCateg);
                m.setCode(200);
                m.setMsg(msg);
                m.setDetail("OK");
            }
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("OK");

        }
        return gson.toJson(m);
    }

    public String getCategoryID(String Categoryid) {
        Category p = new Category();
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            //Query q= entity.createNativeQuery("Select * From product Where productid="+productid,Product.class);
            Query q = entity.createNamedQuery("Category.findByCategoryid").setParameter("categoryid",
                    Integer.parseInt(Categoryid));
            p = (Category) q.getSingleResult();
            msg = gson.toJson(p);
            m.setCode(200);
            m.setMsg(msg);
            m.setDetail("OK");
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("error");

        } catch (PersistenceException ex) {
            m.setCode(404);
            m.setMsg(ex.getMessage());
            m.setDetail("error");

        }

        return gson.toJson(m);
    }

    public String getCategoryName(String categoryname) {
        Category p = new Category();
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String msg = ""; //LA lista de roles que vienen de la base de datos convertido en json
        try {
            Query q = entity.createNamedQuery("Category.findByCategoryname").setParameter("categoryname",
                    categoryname);

            listCateg = q.getResultList();
            if (listCateg.isEmpty()) {
                m.setCode(404);
                m.setMsg("No se encontro con esta usuario");
                m.setDetail("ERROR");
            } else {
                msg = gson.toJson(listCateg);
                m.setCode(200);
                m.setMsg(msg);
                m.setDetail("OK");
            }
        } catch (IllegalArgumentException e) {
            m.setCode(404);
            m.setMsg(e.getMessage());
            m.setDetail("ERROR");

        }
        return gson.toJson(m);
    }

    public String validarProductos(String api) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        List<Carrito> car;
        Query q = entity.createNamedQuery("Carrito.findByIdcarrito").setParameter("idcarrito", api);
        car = q.getResultList();

        if (car.size() != 0) {
            String mensaje = "No hay existencia en almacen de los siguientes productos: ";
            for (Carrito carrito : car) {
                Query q1 = entity.createNamedQuery("Product.findByProductid").setParameter("productid",
                        carrito.getProductid());
                Product product = (Product) q1.getSingleResult();

                if (carrito.getCantidad() > product.getStock()) {
                    mensaje += product.getProductname() + "\n";
                } else {
                    mensaje = "";
                }
            }
            if (mensaje.equals("")) {
                m.setCode(200);
                m.setMsg("Si hay stock");
                m.setDetail("OK");
            } else {
                m.setCode(404);
                m.setMsg(mensaje);
                m.setDetail("OK");
            }
        }
        return gson.toJson(m);
    }

    public void decrementar(String apikey) {
        Message m = new Message();
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        List<Carrito> car;
        Query q = entity.createNamedQuery("Carrito.findByIdcarrito").setParameter("idcarrito", apikey);
        car = q.getResultList();

        int res = 0;
        for (Carrito carrito : car) {
            Query q1 = entity.createNamedQuery("Product.findByProductid").setParameter("productid",
                    carrito.getProductid());
            Product product = (Product) q1.getSingleResult();

            res = product.getStock() - carrito.getCantidad();
            product.setStock(res);

            entity.merge(product);
            entity.flush();

        }
    }
}