Example usage for org.hibernate Criteria createCriteria

List of usage examples for org.hibernate Criteria createCriteria

Introduction

In this page you can find the example usage for org.hibernate Criteria createCriteria.

Prototype

public Criteria createCriteria(String associationPath, String alias) throws HibernateException;

Source Link

Document

Create a new Criteria, "rooted" at the associated entity, assigning the given alias.

Usage

From source file:br.com.empresabordados.dao.CidadeDao.java

public List<Cidade> listarObjetosCriterios() {
    try {/*from www .ja  v  a  2  s  .  co  m*/
        sessao = (Session) HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = sessao.createCriteria(Cidade.class);
        criteria.createCriteria("estado", "e");

        criteria.add(Restrictions.eq("e.sigla", "SC"));
        //criteria.add(Restrictions.eq("situacao", Situacao.Ativo));
        //criteria.addOrder(Order.asc("t.nome"));
        //criteria.addOrder(Order.asc("nomeGuerra"));

        return criteria.list();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        sessao.close();
    }
}

From source file:Clases.CobroHelper.java

public List<Cobro> findByClienteInitAll(String CICliente) {
    List<Cobro> list = null;
    try {/* www. ja v a 2s. c o m*/
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria cri = session.createCriteria(Cobro.class);
        cri.createCriteria("cliente", "c");
        cri.add(Restrictions.eq("c.CI", CICliente));
        list = cri.list();
        for (Cobro cobro : list) {
            Hibernate.initialize(cobro.getCliente());
            Hibernate.initialize(cobro.getCobroActividad());
            List<CobroActividad> listActCob = cobro.getCobroActividad();
            for (CobroActividad actCob : listActCob) {
                Hibernate.initialize(actCob.getActividad());
            }
        }
    } catch (Exception e) {
        throw e;
    } finally {
        session.close();
    }
    return list;
}

From source file:cn.lhfei.fu.orm.persistence.impl.HomeworkBaseDAOImpl.java

License:Apache License

@Override
public SearchAndCountModel<HomeworkBase> getPageAndCount(HomeworkBaseModel homeworkModel) {
    SearchAndCountModel<HomeworkBase> resultModel = new SearchAndCountModel<HomeworkBase>();
    List<HomeworkBase> list = new ArrayList<HomeworkBase>();

    //String sql = "From HomeworkBase as hb left join hb.archives with hb.className = :className ";
    Session session = null;/*from  w ww. jav a2  s . c  o  m*/
    int total;

    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException e) {
        session = getSessionFactory().openSession();
    }

    Criteria criteria = session.createCriteria(HomeworkBase.class, "homeworkBase");

    for (SimpleExpression exp : homeworkModel.wrapperFilter()) {
        criteria.add(exp);
    }

    //criteria.setFetchMode("homeworkBase.archives", FetchMode.JOIN);

    criteria.createCriteria("homeworkBase.archives", JoinType.LEFT_OUTER_JOIN);
    //      criteria.createAlias("homeworkBase.archives", "archives");

    total = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();

    criteria.setProjection(null);

    list = criteria.setFirstResult(homeworkModel.getFirst()).setMaxResults(homeworkModel.getPageSize())
            .setCacheable(true).list();

    resultModel.setTotal(total);
    resultModel.setRows(list);

    return resultModel;
}

From source file:com.abssh.util.GenericDao.java

License:Apache License

/**
 * ?Criteriabulletin.channel.valid,bulletin.channel
 * /*  w ww. ja  va 2  s .c o  m*/
 * @return
 */
private Criteria findParentCriteria(Criteria root, String propertyName, Map<String, Criteria> criteriaMap) {
    if (propertyName.indexOf(DEF_SEPARATOR) > 0) {
        String parentName = propertyName.substring(0, propertyName.lastIndexOf(DEF_SEPARATOR));
        Criteria t = criteriaMap.get(parentName);
        if (t == null) {
            Criteria p = findParentCriteria(root, parentName, criteriaMap);
            String[] tmp = StringUtils.split(parentName, DEF_SEPARATOR);
            Criteria c = p.createCriteria(tmp[tmp.length - 1], CriteriaSpecification.LEFT_JOIN);
            criteriaMap.put(parentName, c);
            return c;
        } else {
            return t;
        }
    } else {
        return root;
    }
}

From source file:com.evolveum.midpoint.repo.sql.OrgStructTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test/* w  ww  .  j av  a  2 s .c  om*/
public void test002modifyOrgStructAddRef() throws Exception {
    LOGGER.info("===[ modifyOrgStruct ]===");
    OperationResult opResult = new OperationResult("===[ modifyOrgStruct ]===");
    // test modification of org ref in another org type..

    ObjectModificationType modification = PrismTestUtil.parseAtomicValue(new File(MODIFY_ORG_ADD_REF_FILENAME),
            ObjectModificationType.COMPLEX_TYPE);
    ObjectDelta<OrgType> delta = DeltaConvertor.createObjectDelta(modification, OrgType.class, prismContext);

    Session session = getFactory().openSession();
    session.beginTransaction();

    Criteria criteria = session.createCriteria(ROrgClosure.class).createCriteria("descendant", "desc")
            .setFetchMode("descendant", FetchMode.JOIN)
            .add(Restrictions.eq("desc.oid", MODIFY_ORG_ADD_REF_OID));

    List<ROrgClosure> orgClosure = criteria.list();

    LOGGER.info("before modify");
    for (ROrgClosure c : orgClosure) {
        LOGGER.info("{}\t{}\t{}",
                new Object[] { c.getAncestor().getOid(), c.getDescendant().getOid(), c.getDepth() });
    }
    AssertJUnit.assertEquals(3, orgClosure.size());
    session.getTransaction().commit();

    repositoryService.modifyObject(OrgType.class, MODIFY_ORG_ADD_REF_OID, delta.getModifications(), opResult);

    session.clear();
    session.beginTransaction();
    criteria = session.createCriteria(ROrgClosure.class).createCriteria("descendant", "desc")
            .setFetchMode("descendant", FetchMode.JOIN)
            .add(Restrictions.eq("desc.oid", MODIFY_ORG_ADD_REF_OID));

    orgClosure = criteria.list();

    LOGGER.info("after modify");
    for (ROrgClosure c : orgClosure) {
        LOGGER.info("{}\t{}\t{}",
                new Object[] { c.getAncestor().getOid(), c.getDescendant().getOid(), c.getDepth() });
    }
    AssertJUnit.assertEquals(4, orgClosure.size());

    List<String> ancestors = new ArrayList<String>();
    ancestors.add(MODIFY_ORG_ADD_REF_OID);
    ancestors.add(ORG_F003_OID);
    ancestors.add(ORG_F001_OID);
    ancestors.add(ORG_F002_OID);

    for (String ancestorOid : ancestors) {
        criteria = session.createCriteria(ROrgClosure.class);
        criteria.createCriteria("ancestor", "anc").setFetchMode("ancestor", FetchMode.JOIN)
                .add(Restrictions.eq("anc.oid", ancestorOid));
        criteria.createCriteria("descendant", "desc").setFetchMode("descendant", FetchMode.JOIN)
                .add(Restrictions.eq("desc.oid", MODIFY_ORG_ADD_REF_OID));

        orgClosure = criteria.list();

        LOGGER.info("=> A: {}, D: {}, depth: {}",
                new Object[] { orgClosure.get(0).getAncestor().toJAXB(prismContext, null),
                        orgClosure.get(0).getDescendant().toJAXB(prismContext, null),
                        orgClosure.get(0).getDepth() });

        AssertJUnit.assertEquals(1, orgClosure.size());
        AssertJUnit.assertEquals(ancestorOid, orgClosure.get(0).getAncestor().getOid());
        AssertJUnit.assertEquals(MODIFY_ORG_ADD_REF_OID, orgClosure.get(0).getDescendant().getOid());
        int depth = -1;
        if (ancestorOid.equals(MODIFY_ORG_ADD_REF_OID)) {
            depth = 0;
        } else if (ancestorOid.equals(ORG_F001_OID)) {
            depth = 2;
        } else if (ancestorOid.equals(ORG_F003_OID)) {
            depth = 1;
        } else if (ancestorOid.equals(ORG_F002_OID)) {
            depth = 1;
        }
        AssertJUnit.assertEquals(depth, orgClosure.get(0).getDepth());

    }
    session.getTransaction().commit();
    session.close();
}

From source file:com.evolveum.midpoint.repo.sql.OrgStructTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test//from  ww w .  j  a  v  a2s. c  o  m
public void test002modifyOrgStructAddRefIncorrect() throws Exception {
    LOGGER.info("===[ modifyOrgStruct ]===");
    OperationResult opResult = new OperationResult("===[ modifyOrgStructIncorrect ]===");
    // test modification of org ref in another org type..

    ObjectModificationType modification = PrismTestUtil.parseAtomicValue(
            new File(MODIFY_ORG_INCORRECT_ADD_REF_FILENAME), ObjectModificationType.COMPLEX_TYPE);
    ObjectDelta<OrgType> delta = DeltaConvertor.createObjectDelta(modification, OrgType.class, prismContext);

    repositoryService.modifyObject(OrgType.class, MODIFY_ORG_INCORRECT_ADD_REF_OID, delta.getModifications(),
            opResult);

    Session session = getFactory().openSession();
    session.beginTransaction();

    Criteria criteria = session.createCriteria(ROrgClosure.class).createCriteria("descendant", "desc")
            .setFetchMode("descendant", FetchMode.JOIN)
            .add(Restrictions.eq("desc.oid", MODIFY_ORG_INCORRECT_ADD_REF_OID));

    List<ROrgClosure> orgClosure = criteria.list();

    LOGGER.info("after modify incorrect - closure");
    for (ROrgClosure c : orgClosure) {
        LOGGER.info("{}\t{}\t{}",
                new Object[] { c.getAncestor().getOid(), c.getDescendant().getOid(), c.getDepth() });
    }
    AssertJUnit.assertEquals(5, orgClosure.size());

    List<String> ancestors = new ArrayList<String>();
    ancestors.add(MODIFY_ORG_INCORRECT_ADD_REF_OID);
    ancestors.add(ORG_F001_OID);
    ancestors.add(ORG_F002_OID);

    for (String ancestorOid : ancestors) {
        criteria = session.createCriteria(ROrgClosure.class);
        criteria.createCriteria("ancestor", "anc").setFetchMode("ancestor", FetchMode.JOIN)
                .add(Restrictions.eq("anc.oid", ancestorOid));
        criteria.createCriteria("descendant", "desc").setFetchMode("descendant", FetchMode.JOIN)
                .add(Restrictions.eq("desc.oid", MODIFY_ORG_INCORRECT_ADD_REF_OID));

        orgClosure = criteria.list();

        AssertJUnit.assertEquals(1, orgClosure.size());

        AssertJUnit.assertEquals(ancestorOid, orgClosure.get(0).getAncestor().getOid());
        AssertJUnit.assertEquals(MODIFY_ORG_INCORRECT_ADD_REF_OID, orgClosure.get(0).getDescendant().getOid());

        int depth = -1;
        if (ancestorOid.equals(MODIFY_ORG_INCORRECT_ADD_REF_OID)) {
            depth = 0;
        } else if (ancestorOid.equals(ORG_F001_OID)) {
            depth = 2;
        } else if (ancestorOid.equals(ORG_F002_OID)) {
            depth = 1;
        }
        AssertJUnit.assertEquals(depth, orgClosure.get(0).getDepth());
    }

    criteria = session.createCriteria(ROrgIncorrect.class)
            .add(Restrictions.eq("descendantOid", MODIFY_ORG_INCORRECT_ADD_REF_OID));

    List<ROrgIncorrect> orgIncorrect = criteria.list();

    LOGGER.info("after modify incorrect - incorrect");
    for (ROrgIncorrect c : orgIncorrect) {
        LOGGER.info("{}\t{}\t{}", new Object[] { c.getAncestorOid(), c.getDescendantOid() });
    }
    AssertJUnit.assertEquals(1, orgIncorrect.size());
    AssertJUnit.assertEquals(MODIFY_ORG_INCORRECT_ADD_REF_OID, orgIncorrect.get(0).getDescendantOid());
    AssertJUnit.assertEquals(ORG_F012_OID, orgIncorrect.get(0).getAncestorOid());

    session.getTransaction().commit();
    session.close();
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void asdf() throws Exception {
    Session session = open();//  ww  w.  j  a v  a2s  . c o  m
    try {
        Criteria main = session.createCriteria(RUser.class, "u");
        Criteria a = main.createCriteria("assignments", "a");
        a.add(Restrictions.eq("a.assignmentOwner", RAssignmentOwner.FOCUS));
        Criteria e = a.createCriteria("a.extension");

        Criteria s = e.createCriteria("strings", "s");

        Conjunction c2 = Restrictions.conjunction();
        c2.add(Restrictions.eq("s.extensionType", RAssignmentExtensionType.EXTENSION));
        c2.add(Restrictions.eq("s.name", new QName("http://midpoint.evolveum.com/blabla", "foo")));
        c2.add(Restrictions.eq("s.value", "uid=jbond,ou=People,dc=example,dc=com"));

        Conjunction c1 = Restrictions.conjunction();
        c1.add(Restrictions.eq("a.targetRef.targetOid", "1234"));
        c1.add(Restrictions.eq("a.targetRef.type", RObjectType.ORG));

        main.add(Restrictions.and(c1, c2));

        main.setProjection(Projections.property("u.fullObject"));

        String expected = HibernateToSqlTranslator.toSql(main);
        LOGGER.info(">>> >>> {}", expected);
    } finally {
        close(session);
    }
}

From source file:com.floreantpos.model.dao.SalesSummaryDAO.java

License:Open Source License

public List<SalesAnalysisData> findSalesAnalysis(Date start, Date end, UserType userType, Terminal terminal) {
    Session session = null;/*w  w  w  . ja v  a2s .com*/

    try {
        ArrayList<SalesAnalysisData> list = new ArrayList<SalesAnalysisData>();

        session = getSession();

        Criteria criteria = session.createCriteria(Shift.class);
        List<Shift> shifts = criteria.list();

        criteria = session.createCriteria(MenuCategory.class);
        List<MenuCategory> categories = criteria.list();
        MenuCategory miscCategory = new MenuCategory();
        miscCategory.setName(Messages.getString("SalesSummaryDAO.0")); //$NON-NLS-1$
        categories.add(miscCategory);

        //find food sales
        criteria = session.createCriteria(TicketItem.class, "item"); //$NON-NLS-1$
        criteria.createCriteria("ticket", "t"); //$NON-NLS-1$ //$NON-NLS-2$
        criteria.createCriteria("t.owner", "u"); //$NON-NLS-1$ //$NON-NLS-2$
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.sum(TicketItem.PROP_ITEM_COUNT));
        projectionList.add(Projections.sum(TicketItem.PROP_SUBTOTAL_AMOUNT));
        projectionList.add(Projections.sum(TicketItem.PROP_DISCOUNT_AMOUNT));
        criteria.setProjection(projectionList);
        criteria.add(Restrictions.eq("item." + TicketItem.PROP_BEVERAGE, Boolean.FALSE)); //$NON-NLS-1$
        criteria.add(Restrictions.ge("t." + Ticket.PROP_ACTIVE_DATE, start)); //$NON-NLS-1$
        criteria.add(Restrictions.le("t." + Ticket.PROP_ACTIVE_DATE, end)); //$NON-NLS-1$

        if (userType != null) {
            criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
        }
        if (terminal != null) {
            criteria.add(Restrictions.eq("t." + Ticket.PROP_TERMINAL, terminal)); //$NON-NLS-1$
        }
        List datas = criteria.list();
        if (datas.size() > 0) {
            Object[] objects = (Object[]) datas.get(0);

            SalesAnalysisData data = new SalesAnalysisData();
            data.setShiftName(""); //$NON-NLS-1$
            data.setCategoryName(Messages.getString("SalesSummaryDAO.1")); //$NON-NLS-1$

            if (objects.length > 0 && objects[0] != null)
                data.setCount(((Number) objects[0]).intValue());

            if (objects.length > 1 && objects[1] != null)
                data.setGross(((Number) objects[1]).doubleValue());

            if (objects.length > 2 && objects[2] != null)
                data.setDiscount(((Number) objects[2]).doubleValue());

            data.calculate();
            list.add(data);
        }

        //find non food sales
        criteria = session.createCriteria(TicketItem.class, "item"); //$NON-NLS-1$
        criteria.createCriteria("ticket", "t"); //$NON-NLS-1$ //$NON-NLS-2$
        criteria.createCriteria("t.owner", "u"); //$NON-NLS-1$ //$NON-NLS-2$
        projectionList = Projections.projectionList();
        projectionList.add(Projections.sum(TicketItem.PROP_ITEM_COUNT));
        projectionList.add(Projections.sum(TicketItem.PROP_SUBTOTAL_AMOUNT));
        projectionList.add(Projections.sum(TicketItem.PROP_DISCOUNT_AMOUNT));
        criteria.setProjection(projectionList);
        criteria.add(Restrictions.eq("item." + TicketItem.PROP_BEVERAGE, Boolean.TRUE)); //$NON-NLS-1$
        criteria.add(Restrictions.ge("t." + Ticket.PROP_ACTIVE_DATE, start)); //$NON-NLS-1$
        criteria.add(Restrictions.le("t." + Ticket.PROP_ACTIVE_DATE, end)); //$NON-NLS-1$

        if (userType != null) {
            criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
        }
        if (terminal != null) {
            criteria.add(Restrictions.eq("t." + Ticket.PROP_TERMINAL, terminal)); //$NON-NLS-1$
        }
        datas = criteria.list();
        if (datas.size() > 0) {
            Object[] objects = (Object[]) datas.get(0);

            SalesAnalysisData data = new SalesAnalysisData();
            data.setShiftName(""); //$NON-NLS-1$
            data.setCategoryName(Messages.getString("SalesSummaryDAO.2")); //$NON-NLS-1$

            if (objects.length > 0 && objects[0] != null)
                data.setCount(((Number) objects[0]).intValue());

            if (objects.length > 1 && objects[1] != null)
                data.setGross(((Number) objects[1]).doubleValue());

            if (objects.length > 2 && objects[2] != null)
                data.setDiscount(((Number) objects[2]).doubleValue());

            data.calculate();
            list.add(data);
        }

        //find shift wise salse
        for (Shift shift : shifts) {

            for (MenuCategory category : categories) {

                criteria = session.createCriteria(TicketItem.class, "item"); //$NON-NLS-1$
                criteria.createCriteria("ticket", "t"); //$NON-NLS-1$ //$NON-NLS-2$
                criteria.createCriteria("t.owner", "u"); //$NON-NLS-1$ //$NON-NLS-2$
                projectionList = Projections.projectionList();
                projectionList.add(Projections.sum(TicketItem.PROP_ITEM_COUNT));
                projectionList.add(Projections.sum(TicketItem.PROP_SUBTOTAL_AMOUNT));
                projectionList.add(Projections.sum(TicketItem.PROP_DISCOUNT_AMOUNT));
                criteria.setProjection(projectionList);
                criteria.add(Restrictions.eq("item." + TicketItem.PROP_CATEGORY_NAME, category.getName())); //$NON-NLS-1$
                criteria.add(Restrictions.eq("t." + Ticket.PROP_SHIFT, shift)); //$NON-NLS-1$
                criteria.add(Restrictions.ge("t." + Ticket.PROP_ACTIVE_DATE, start)); //$NON-NLS-1$
                criteria.add(Restrictions.le("t." + Ticket.PROP_ACTIVE_DATE, end)); //$NON-NLS-1$

                if (userType != null) {
                    criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
                }
                if (terminal != null) {
                    criteria.add(Restrictions.eq("t." + Ticket.PROP_TERMINAL, terminal)); //$NON-NLS-1$
                }
                datas = criteria.list();
                if (datas.size() > 0) {
                    Object[] objects = (Object[]) datas.get(0);

                    SalesAnalysisData data = new SalesAnalysisData();
                    data.setShiftName(shift.getName());
                    data.setCategoryName(category.getName());

                    if (objects.length > 0 && objects[0] != null)
                        data.setCount(((Number) objects[0]).intValue());

                    if (objects.length > 1 && objects[1] != null)
                        data.setGross(((Number) objects[1]).doubleValue());

                    if (objects.length > 2 && objects[2] != null)
                        data.setDiscount(((Number) objects[2]).doubleValue());

                    data.calculate();
                    list.add(data);
                }
            }
        }

        //find all sales
        for (MenuCategory category : categories) {

            criteria = session.createCriteria(TicketItem.class, "item"); //$NON-NLS-1$
            criteria.createCriteria("ticket", "t"); //$NON-NLS-1$ //$NON-NLS-2$
            criteria.createCriteria("t.owner", "u"); //$NON-NLS-1$ //$NON-NLS-2$
            projectionList = Projections.projectionList();
            projectionList.add(Projections.sum(TicketItem.PROP_ITEM_COUNT));
            projectionList.add(Projections.sum(TicketItem.PROP_SUBTOTAL_AMOUNT));
            projectionList.add(Projections.sum(TicketItem.PROP_DISCOUNT_AMOUNT));
            criteria.setProjection(projectionList);
            criteria.add(Restrictions.eq("item." + TicketItem.PROP_CATEGORY_NAME, category.getName())); //$NON-NLS-1$
            criteria.add(Restrictions.ge("t." + Ticket.PROP_ACTIVE_DATE, start)); //$NON-NLS-1$
            criteria.add(Restrictions.le("t." + Ticket.PROP_ACTIVE_DATE, end)); //$NON-NLS-1$

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }
            if (terminal != null) {
                criteria.add(Restrictions.eq("t." + Ticket.PROP_TERMINAL, terminal)); //$NON-NLS-1$
            }
            datas = criteria.list();
            if (datas.size() > 0) {
                Object[] objects = (Object[]) datas.get(0);

                SalesAnalysisData data = new SalesAnalysisData();
                data.setShiftName("ALL DAY"); //$NON-NLS-1$
                data.setCategoryName(category.getName());

                if (objects.length > 0 && objects[0] != null)
                    data.setCount(((Number) objects[0]).intValue());

                if (objects.length > 1 && objects[1] != null)
                    data.setGross(((Number) objects[1]).doubleValue());

                if (objects.length > 2 && objects[2] != null)
                    data.setDiscount(((Number) objects[2]).doubleValue());

                data.calculate();
                list.add(data);
            }
        }
        return list;
    } finally {
        if (session != null) {
            closeSession(session);
        }
    }
}

From source file:com.floreantpos.model.dao.SalesSummaryDAO.java

License:Open Source License

public SalesStatistics findKeyStatistics(Date start, Date end, UserType userType, Terminal terminal) {
    Session session = null;/*from w  w w  . j a  va2  s  .  co  m*/

    try {
        SalesStatistics salesSummary = new SalesStatistics();

        session = getSession();

        //retrieve restaurant information and set it to sales summary
        Restaurant restaurant = (Restaurant) get(Restaurant.class, new Integer(1), session);
        if (restaurant != null) {
            salesSummary
                    .setCapacity(restaurant.getCapacity() != null ? restaurant.getCapacity().intValue() : 0);
            salesSummary.setTables(restaurant.getTables() != null ? restaurant.getTables().intValue() : 0);
        }

        {
            //find gross sale, discount and tax. this excludes void tickets
            //net sale = gross_sale - discount
            Criteria criteria = session.createCriteria(Ticket.class, "ticket"); //$NON-NLS-1$
            criteria.createCriteria(Ticket.PROP_OWNER, "u"); //$NON-NLS-1$

            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.rowCount());
            projectionList.add(Projections.sum(Ticket.PROP_SUBTOTAL_AMOUNT));
            projectionList.add(Projections.sum(Ticket.PROP_DISCOUNT_AMOUNT));
            projectionList.add(Projections.sum(Ticket.PROP_TAX_AMOUNT));
            criteria.setProjection(projectionList);
            criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, start));
            criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, end));

            //do not take into account void tickets
            criteria.add(Restrictions.eq(Ticket.PROP_VOIDED, Boolean.FALSE));
            criteria.add(Restrictions.eq(Ticket.PROP_REFUNDED, Boolean.FALSE));

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }

            if (terminal != null) {
                criteria.add(Restrictions.eq(Ticket.PROP_TERMINAL, terminal));
            }
            List list = criteria.list();
            if (list.size() > 0) {
                Object[] objects = (Object[]) list.get(0);

                if (objects.length > 1 && objects[1] != null) {
                    salesSummary.setGrossSale(((Number) objects[1]).doubleValue());
                }
                if (objects.length > 2 && objects[2] != null) {
                    salesSummary.setDiscount(((Number) objects[2]).intValue());
                }
                if (objects.length > 3 && objects[3] != null) {
                    salesSummary.setTax(((Number) objects[3]).intValue());
                }
            }
        }

        {
            //determine number of guests within the specified time. this includes void tickets, 
            Criteria criteria = session.createCriteria(Ticket.class, "ticket"); //$NON-NLS-1$
            criteria.createCriteria(Ticket.PROP_OWNER, "u"); //$NON-NLS-1$

            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.rowCount());
            projectionList.add(Projections.sum(Ticket.PROP_NUMBER_OF_GUESTS));
            criteria.setProjection(projectionList);
            criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, start));
            criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, end));

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }

            if (terminal != null) {
                criteria.add(Restrictions.eq(Ticket.PROP_TERMINAL, terminal));
            }
            List list = criteria.list();
            if (list.size() > 0) {
                Object[] objects = (Object[]) list.get(0);
                salesSummary.setCheckCount(((Number) objects[0]).intValue());

                if (objects.length > 1 && objects[1] != null) {
                    salesSummary.setGuestCount(((Number) objects[1]).intValue());
                }
            }
        }

        {
            //find number of open tickets and its total amount
            Criteria criteria = session.createCriteria(Ticket.class, "ticket"); //$NON-NLS-1$
            criteria.createCriteria(Ticket.PROP_OWNER, "u"); //$NON-NLS-1$

            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.rowCount());
            projectionList.add(Projections.sum(Ticket.PROP_TOTAL_AMOUNT));
            criteria.setProjection(projectionList);
            criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, start));
            criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, end));
            criteria.add(Restrictions.eq(Ticket.PROP_CLOSED, Boolean.FALSE));

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }
            if (terminal != null) {
                criteria.add(Restrictions.eq(Ticket.PROP_TERMINAL, terminal));
            }
            List list = criteria.list();
            if (list.size() > 0) {
                Object[] objects = (Object[]) list.get(0);
                salesSummary.setOpenChecks(((Number) objects[0]).intValue());

                if (objects.length > 1 && objects[1] != null) {
                    salesSummary.setOpenAmount(((Number) objects[1]).doubleValue());
                }
            }
        }

        {
            //find number of void tickets and its total amount
            Criteria criteria = session.createCriteria(Ticket.class, "ticket"); //$NON-NLS-1$
            criteria.createCriteria(Ticket.PROP_OWNER, "u"); //$NON-NLS-1$
            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.rowCount());
            projectionList.add(Projections.sum(Ticket.PROP_TOTAL_AMOUNT));
            criteria.setProjection(projectionList);
            criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, start));
            criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, end));
            criteria.add(Restrictions.eq(Ticket.PROP_CLOSED, Boolean.TRUE));
            criteria.add(Restrictions.eq(Ticket.PROP_VOIDED, Boolean.TRUE));

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }
            if (terminal != null) {
                criteria.add(Restrictions.eq(Ticket.PROP_TERMINAL, terminal));
            }
            List list = criteria.list();
            if (list.size() > 0) {
                Object[] objects = (Object[]) list.get(0);
                salesSummary.setVoidChecks(((Number) objects[0]).intValue());

                if (objects.length > 1 && objects[1] != null) {
                    salesSummary.setVoidAmount(((Number) objects[1]).doubleValue());
                }
            }
        }

        {
            //find non taxable sales
            Criteria criteria = session.createCriteria(Ticket.class, "ticket"); //$NON-NLS-1$
            criteria.createCriteria(Ticket.PROP_OWNER, "u"); //$NON-NLS-1$
            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.rowCount());
            projectionList.add(Projections.sum(Ticket.PROP_TOTAL_AMOUNT));
            criteria.setProjection(projectionList);
            criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, start));
            criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, end));
            criteria.add(Restrictions.eq(Ticket.PROP_VOIDED, Boolean.FALSE));
            criteria.add(Restrictions.eq(Ticket.PROP_REFUNDED, Boolean.FALSE));
            criteria.add(Restrictions.eq(Ticket.PROP_TAX_EXEMPT, Boolean.TRUE));

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }
            if (terminal != null) {
                criteria.add(Restrictions.eq(Ticket.PROP_TERMINAL, terminal));
            }
            List list = criteria.list();
            if (list.size() > 0) {
                Object[] objects = (Object[]) list.get(0);
                salesSummary.setNtaxChecks(((Number) objects[0]).intValue());

                if (objects.length > 1 && objects[1] != null) {
                    salesSummary.setNtaxAmount(((Number) objects[1]).doubleValue());
                }
            }
        }
        {
            //find reopen statistics
            Criteria criteria = session.createCriteria(Ticket.class, "ticket"); //$NON-NLS-1$
            criteria.createCriteria(Ticket.PROP_OWNER, "u"); //$NON-NLS-1$
            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.rowCount());
            projectionList.add(Projections.sum(Ticket.PROP_TOTAL_AMOUNT));
            criteria.setProjection(projectionList);
            criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, start));
            criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, end));
            criteria.add(Restrictions.eq(Ticket.PROP_RE_OPENED, Boolean.TRUE));

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }
            if (terminal != null) {
                criteria.add(Restrictions.eq(Ticket.PROP_TERMINAL, terminal));
            }
            List list = criteria.list();
            if (list.size() > 0) {
                Object[] objects = (Object[]) list.get(0);
                salesSummary.setRopnChecks(((Number) objects[0]).intValue());

                if (objects.length > 1 && objects[1] != null) {
                    salesSummary.setRopnAmount(((Number) objects[1]).doubleValue());
                }
            }
        }

        {
            //calculate totalLaborHours in the specified period
            Criteria criteria = session.createCriteria(AttendenceHistory.class, "history"); //$NON-NLS-1$
            criteria.createCriteria(AttendenceHistory.PROP_USER, "u"); //$NON-NLS-1$
            criteria.add(Restrictions.ge(AttendenceHistory.PROP_CLOCK_IN_TIME, start));
            criteria.add(Restrictions.le(AttendenceHistory.PROP_CLOCK_IN_TIME, end));

            if (userType != null) {
                criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
            }
            if (terminal != null) {
                criteria.add(Restrictions.eq(AttendenceHistory.PROP_TERMINAL, terminal));
            }
            List list = criteria.list();

            double laborHours = 0;
            double laborCost = 0;
            for (Object object : list) {
                AttendenceHistory attendenceHistory = (AttendenceHistory) object;
                double laborHourInMillisecond = 0;
                if (!attendenceHistory.isClockedOut() || attendenceHistory.getClockOutTime() == null) {
                    Shift attendenceShift = attendenceHistory.getShift();
                    laborHourInMillisecond = Math
                            .abs(end.getTime() - attendenceHistory.getClockInTime().getTime());
                    if (laborHourInMillisecond > attendenceShift.getShiftLength()) {
                        laborHourInMillisecond = attendenceShift.getShiftLength();
                    }
                } else {
                    laborHourInMillisecond = Math.abs(attendenceHistory.getClockInTime().getTime()
                            - attendenceHistory.getClockInTime().getTime());
                }
                double hour = (laborHourInMillisecond * (2.77777778 * Math.pow(10, -7)));
                laborHours += hour;
                laborCost += hour * (attendenceHistory.getUser().getCostPerHour() == null ? 0
                        : attendenceHistory.getUser().getCostPerHour());
            }
            salesSummary.setLaborHour(laborHours);
            salesSummary.setLaborCost(laborCost);
        }

        {
            //find summary by shift
            Criteria criteria = session.createCriteria(Shift.class);
            List shifts = criteria.list();
            for (Object object : shifts) {
                Shift shift = (Shift) object;

                List<OrderType> values = Application.getInstance().getOrderTypes(); //change enum
                for (OrderType ticketType : values) {
                    findRecordByProfitCenter(start, end, userType, terminal, session, salesSummary, shift,
                            ticketType);
                }

            }
        }

        salesSummary.calculateOthers();
        return salesSummary;
    } finally {
        if (session != null) {
            closeSession(session);
        }
    }
}

From source file:com.floreantpos.model.dao.SalesSummaryDAO.java

License:Open Source License

private void findRecordByProfitCenter(Date start, Date end, UserType userType, Terminal terminal,
        Session session, SalesStatistics salesSummary, Shift shift, OrderType ticketType) {
    Criteria criteria;
    criteria = session.createCriteria(Ticket.class, "ticket"); //$NON-NLS-1$
    criteria.createCriteria(Ticket.PROP_OWNER, "u"); //$NON-NLS-1$
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.rowCount());
    projectionList.add(Projections.sum(Ticket.PROP_NUMBER_OF_GUESTS));
    projectionList.add(Projections.sum(Ticket.PROP_SUBTOTAL_AMOUNT));
    criteria.setProjection(projectionList);
    criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, start));
    criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, end));
    criteria.add(Restrictions.eq(Ticket.PROP_SHIFT, shift));
    criteria.add(Restrictions.eq(Ticket.PROP_TICKET_TYPE, ticketType.name()));

    if (userType != null) {
        criteria.add(Restrictions.eq("u." + User.PROP_TYPE, userType)); //$NON-NLS-1$
    }//  ww  w  .  j av  a 2  s  .c o m
    if (terminal != null) {
        criteria.add(Restrictions.eq(Ticket.PROP_TERMINAL, terminal));
    }
    List list = criteria.list();
    if (list.size() > 0) {
        ShiftwiseSalesTableData data = new ShiftwiseSalesTableData();
        data.setProfitCenter(ticketType.toString());
        Object[] objects = (Object[]) list.get(0);

        data.setShiftName(shift.getName());
        data.setCheckCount(((Number) objects[0]).intValue());

        if (objects.length > 1 && objects[1] != null) {
            data.setGuestCount(((Number) objects[1]).intValue());
        }
        if (objects.length > 2 && objects[2] != null) {
            data.setTotalSales(((Number) objects[2]).doubleValue());
        }
        data.setPercentage(data.getTotalSales() * 100 / salesSummary.getGrossSale());
        data.calculateOthers();
        salesSummary.addSalesTableData(data);
    }
}