com.nec.harvest.service.impl.PettyCashServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.nec.harvest.service.impl.PettyCashServiceImpl.java

Source

/*
 * Copyright(C) 2014
 * NEC Corporation All rights reserved.
 * 
 * No permission to use, copy, modify and distribute this software
 * and its documentation for any purpose is granted.
 * This software is provided under applicable license agreement only.
 */
package com.nec.harvest.service.impl;

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.GenericJDBCException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nec.core.exception.ObjectNotFoundException;
import com.nec.crud.hibernate.HibernateSessionManager;
import com.nec.harvest.bean.mapping.PettyCashBean;
import com.nec.harvest.bean.mapping.json.JSONBean;
import com.nec.harvest.constant.MsgConstants;
import com.nec.harvest.constant.SqlConstants;
import com.nec.harvest.constant.TblConstants;
import com.nec.harvest.exception.ServiceException;
import com.nec.harvest.helper.MessageHelper;
import com.nec.harvest.helper.ProductHelper;
import com.nec.harvest.model.PettyCash;
import com.nec.harvest.model.User;
import com.nec.harvest.repository.PettyCashRepository;
import com.nec.harvest.service.PettyCashService;
import com.nec.harvest.service.SerialNumberService;
import com.nec.harvest.userdetails.AuthenticatedUserDetails;
import com.nec.harvest.util.DateFormatUtil;
import com.nec.harvest.util.DateFormatUtil.DateFormat;

/**
 * {@link PettyCashService}
 * 
 * @author huonghv
 *
 */
public class PettyCashServiceImpl implements PettyCashService {

    private static final Logger logger = LoggerFactory.getLogger(PettyCashServiceImpl.class);

    private static final int DELETE_STATE = 1;
    private static final int UPDATE_STATE = 3;
    private static final int CREATE_NEW_STATE = 4;

    private PettyCashRepository pettyCashRepository;

    private SerialNumberService serialNumberService;

    public PettyCashServiceImpl(PettyCashRepository pettyCashRepository, SerialNumberService serialNumberService) {
        this.pettyCashRepository = pettyCashRepository;
        this.serialNumberService = serialNumberService;
    }

    /** {@inheritDoc} */
    @Override
    public List<PettyCash> findByOrgCodeAndBusinessDay(String orgCode, Date getSudo) throws ServiceException {
        String strBusinessDay = DateFormatUtil.format(getSudo, DateFormat.DATE_WITHOUT_DAY);

        // 
        return findByOrgCodeAndBusinessDay(orgCode, strBusinessDay);
    }

    /** {@inheritDoc} */
    @Override
    public List<PettyCash> findByOrgCodeAndBusinessDay(String orgCode, String getSudo) throws ServiceException {
        if (StringUtils.isEmpty(orgCode)) {
            throw new IllegalArgumentException("Organization must not be null or empty");
        }
        if (StringUtils.isEmpty(getSudo)) {
            throw new IllegalArgumentException("Business day must not be null or empty");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        List<PettyCash> pettyCashes = new ArrayList<PettyCash>();
        try {
            tx = session.beginTransaction();
            Query query = pettyCashRepository
                    .getNamedQuery(session, SqlConstants.SQL_FIND_PETTY_CASH_BY_ORG_CODE_AND_BUSINESS_DAY)
                    .setString("strCode", orgCode).setString("getSudo", getSudo)
                    .setResultTransformer(Transformers.aliasToBean(PettyCash.class));

            pettyCashes = pettyCashRepository.findByQuery(query);
            tx.commit();
        } catch (HibernateException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException(
                    "Hibernate runtime exception occur when get petty cashes with organization code..." + orgCode
                            + " and business day " + getSudo,
                    ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return pettyCashes;
    }

    /** {@inheritDoc} */
    @Override
    public List<PettyCash> findCurrentUpdateNo(String... recordIds) throws ServiceException {
        if (ArrayUtils.isEmpty(recordIds)) {
            throw new IllegalArgumentException("The list of petty cash's Id must not be null or empty");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        List<PettyCash> pettyCashes = new ArrayList<PettyCash>();
        try {
            tx = session.beginTransaction();
            Query query = pettyCashRepository
                    .getNamedQuery(session, SqlConstants.SQL_FIND_PETTY_CASH_PRESENT_UPDATE_NO)
                    .setParameterList("recordIDs", recordIds)
                    .setResultTransformer(Transformers.aliasToBean(PettyCash.class));
            pettyCashes = pettyCashRepository.findByQuery(query);
            tx.commit();
        } catch (HibernateException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception occur when get petty cash update number", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return pettyCashes;
    }

    /** {@inheritDoc} */
    @Override
    public boolean deleteByRecordIds(String... recordIds) throws ServiceException {
        if (ArrayUtils.isEmpty(recordIds)) {
            throw new IllegalArgumentException("The list of petty cash's Id must not be null or empty");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        boolean isDeleted = false;
        try {
            StringBuilder sql = new StringBuilder();
            sql.append(" DELETE FROM " + TblConstants.TBL_PETTY_CASH);
            sql.append(" WHERE RecID in (:recordIDs) ");

            tx = session.beginTransaction();
            Query query = pettyCashRepository.getSQLQuery(session, sql.toString()).setParameterList("recordIDs",
                    recordIds);

            int deletedRecords = query.executeUpdate();
            isDeleted = deletedRecords == recordIds.length;
            tx.commit();
        } catch (Exception ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception occur when delete a list of petty cashes", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return isDeleted;
    }

    /** {@inheritDoc} */
    @Override
    public boolean updatePettyCashes(PettyCash... pettyCashes) throws ServiceException {
        if (ArrayUtils.isEmpty(pettyCashes)) {
            throw new IllegalArgumentException("The list of petty cash must not be null or empty");
        }

        User user = AuthenticatedUserDetails.getUserPrincipal();
        if (user == null) {
            logger.info("You must login to use this function");
            // 
            return false;
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        boolean isUpdated = false;
        try {
            StringBuilder sql = new StringBuilder();
            sql.append(" UPDATE " + TblConstants.TBL_PETTY_CASH);
            sql.append(" SET SrDate=:srDate, CtgCode=:ctgCode, Naiyo=:naiyo, Kingaku=:kingaku, Shito=:shito, ");
            sql.append(
                    " UpdNo=:updNo, DelKbn=:delKbn, TanCode=:tanCode, APInf2=:apInf2, StfCodeU=:stfCodeU, PrdNoU=:prdNoU ");
            sql.append(" WHERE RecID=:recId ");

            // 
            tx = session.beginTransaction();
            Query query = pettyCashRepository.getSQLQuery(session, sql.toString());
            for (int i = 0; i < pettyCashes.length; i++) {
                PettyCash pettyCash = pettyCashes[i];
                // Trying to build a query
                query.setDate("srDate", pettyCash.getSrDate())
                        .setString("ctgCode", pettyCash.getCategory().getCtgCode())
                        .setString("naiyo", pettyCash.getNaiyo()).setDouble("kingaku", pettyCash.getKingaku())
                        .setString("shito", pettyCash.getShito())
                        .setInteger("updNo", (pettyCash.getUpdNo() == null ? 1 : pettyCash.getUpdNo()))
                        .setString("delKbn", pettyCash.getDelKbn()).setString("tanCode", user.getUsrCode())
                        .setString("apInf2", user.getUsrCode()).setString("stfCodeU", user.getUsrCode())
                        .setString("prdNoU", pettyCash.getPrdNoU()).setString("recId", pettyCash.getRecID())
                        .executeUpdate();
            }

            isUpdated = true;
            tx.commit();
        } catch (Exception ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception occur when update a list of petty cashes", ex);
        }
        return isUpdated;
    }

    /** {@inheritDoc} */
    @Override
    public boolean checkAvailable(String orgCode, Date getSudo) throws ServiceException {
        if (StringUtils.isEmpty(orgCode) || getSudo == null) {
            throw new IllegalArgumentException(
                    "To check month's data available, The input parameter organization code or business day must not be empty.");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        boolean isAvailable = false;
        try {
            tx = session.beginTransaction();
            StringBuilder sql = new StringBuilder();
            sql.append(" SELECT count(recID) ");
            sql.append(" FROM AT009 ");
            sql.append(" WHERE strCode=:strCode AND getSudo=:getSudo AND delKbn=2");

            // 
            String strBusinessDay = DateFormatUtil.format(getSudo, DateFormat.DATE_WITHOUT_DAY);
            Query query = pettyCashRepository.getSQLQuery(session, sql.toString()).setString("strCode", orgCode)
                    .setString("getSudo", strBusinessDay);

            BigInteger count = (BigInteger) query.uniqueResult();
            isAvailable = (count.floatValue() > 0);
            tx.commit();
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception when check data available", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return isAvailable;
    }

    /** {@inheritDoc} */
    @Override
    public List<PettyCash> findUpdateNoById(String... recIDs) throws ServiceException {
        if (ArrayUtils.isEmpty(recIDs)) {
            throw new IllegalArgumentException("To get petty cash update number, its record id must not be empty");
        }
        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        List<PettyCash> pettyCashes = new ArrayList<PettyCash>();
        try {
            tx = session.beginTransaction();
            Query query = pettyCashRepository
                    .getSQLQuery(session, " SELECT UpdNo FROM AT009 WHERE RecID in (:recIDs) AND DelKbn=2 ")
                    .setParameterList("recIDs", recIDs);

            pettyCashes = pettyCashRepository.findByQuery(query);
            tx.commit();
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception when get update no of petty cash list ", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return pettyCashes;
    }

    /** {@inheritDoc} */
    @Override
    public synchronized void insertPettyCash(String monthly, String sequenceNo, PettyCashBean pettyCashBean)
            throws ServiceException {
        if (StringUtils.isEmpty(monthly)) {
            throw new IllegalArgumentException("The monthly must not be null or empty");
        }

        if (StringUtils.isEmpty(sequenceNo)) {
            throw new IllegalArgumentException("The sequence number must not be null or empty");
        }

        if (pettyCashBean == null) {
            throw new IllegalArgumentException("Petty cash must not be null or empty");
        }

        User user = AuthenticatedUserDetails.getUserPrincipal();
        if (user == null) {
            logger.info("You must login to use this function");
            // 
            throw new IllegalStateException("You don't have a permission to use this");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        try {

            StringBuilder sql = new StringBuilder();
            // Trying to build a query
            sql.append(" INSERT INTO " + TblConstants.TBL_PETTY_CASH).append(
                    " (RecID, SrDate, CtgCode, Naiyo, Kingaku, Shito, UpdNo, DelKbn, TanCode, APInf1, StfCodeC, PrdNoU, GetSudo, StrCode, RecCkbn, PrdNoC, TimeC, TimeU) ")
                    .append("values(:recID, :srDate, :ctgCode, :naiyo, :kingaku, :shito, :updNo, :delKbn, :tanCode, :aPInf1, :stfCodeC, :prdNoU, :getSudo, :strCode, :recCkbn, :prdNoC, now(), now()) ");

            tx = session.beginTransaction();
            Query query = pettyCashRepository.getSQLQuery(session, sql.toString());
            query.setString("recID", sequenceNo).setDate("srDate", pettyCashBean.getDate())
                    .setString("ctgCode",
                            (StringUtils.isEmpty(pettyCashBean.getItem()) ? null : pettyCashBean.getItem()))
                    .setString("naiyo", pettyCashBean.getContent()).setDouble("kingaku", pettyCashBean.getAmount())
                    .setString("shito", pettyCashBean.getRemark()).setInteger("updNo", 1).setString("delKbn", "2")
                    .setString("tanCode", user.getUsrCode()).setString("aPInf1", user.getUsrCode())
                    .setString("stfCodeC", user.getUsrCode());

            try {
                String productVersion = ProductHelper.getProductInfor().getVersion();

                // Update the product's version
                query.setString("prdNoU", productVersion);
                query.setString("prdNoC", productVersion);
            } catch (IOException ex) {
                logger.warn(ex.getMessage(), ex);
            }

            query.setString("getSudo", monthly);
            query.setString("strCode", user.getOrganization().getStrCode());
            query.setString("recCkbn", "1");
            query.executeUpdate();

            // 
            tx.commit();
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("An error occurred when trying to create a new one petty cash", ex);
        } finally {
            tx = null;
            HibernateSessionManager.closeSession(session);
        }
    }

    /** {@inheritDoc} */
    @Override
    public void updatePettyCash(PettyCashBean pettyCashBean) throws ServiceException {
        if (pettyCashBean == null) {
            throw new IllegalArgumentException("Petty cash must not be null or empty");
        }

        User user = AuthenticatedUserDetails.getUserPrincipal();
        if (user == null) {
            logger.info("You must login to use this function");
            // 
            throw new IllegalArgumentException("You don't have a permission to use this");
        }

        float currentUpdNo = findUpdateNoById(pettyCashBean.getId());

        // ?\r\n\r\n?????????????
        // \r\n??????????
        if (currentUpdNo > pettyCashBean.getUpdNo()) {
            throw new IllegalArgumentException(
                    "?\r\n\r\n?????????????"
                            + "\r\n??????????");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();

            // 
            StringBuilder sql = new StringBuilder();
            sql.append(" UPDATE " + TblConstants.TBL_PETTY_CASH);
            sql.append(" SET SrDate=:srDate, CtgCode=:ctgCode, Naiyo=:naiyo, Kingaku=:kingaku, Shito=:shito, ");
            sql.append(
                    " UpdNo=:updNo, TanCode=:tanCode, APInf2=:apInf2, StfCodeU=:stfCodeU, PrdNoU=:prdNoU, RecCkbn=1, TimeU=now()");
            sql.append(" WHERE RecID=:recId ");

            // 
            Query query = pettyCashRepository.getSQLQuery(session, sql.toString());

            query.setDate("srDate", pettyCashBean.getDate());
            query.setString("ctgCode", pettyCashBean.getItem());
            query.setString("naiyo", pettyCashBean.getContent());
            query.setDouble("kingaku", pettyCashBean.getAmount());
            query.setString("shito", pettyCashBean.getRemark());
            query.setFloat("updNo", currentUpdNo + 1);
            query.setString("tanCode", user.getUsrCode());
            query.setString("apInf2", user.getUsrCode());
            query.setString("stfCodeU", user.getUsrCode());

            try {
                query.setString("prdNoU", ProductHelper.getProductInfor().getVersion());
            } catch (IOException ex) {
                logger.warn(ex.getMessage(), ex);
            }

            query.setString("recId", pettyCashBean.getId());
            query.executeUpdate();
            tx.commit();
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception occur when update a list of petty cashes", ex);
        } finally {
            tx = null;
            HibernateSessionManager.closeSession(session);
        }
    }

    /** {@inheritDoc} */
    @Override
    public float findUpdateNoById(String recId) throws ServiceException {
        if (StringUtils.isEmpty(recId)) {
            throw new IllegalArgumentException("To get petty cash update number, its record id must not be empty");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        float recordsNo = 0;
        try {
            tx = session.beginTransaction();
            Query query = pettyCashRepository.getSQLQuery(session,
                    " SELECT UpdNo FROM AT009 WHERE RecID=:recID AND DelKbn=2 ");
            query.setString("recID", recId);
            Object obj = query.uniqueResult();
            if (obj == null) {
                throw new ObjectNotFoundException("Can not find update number of record with id " + recId);
            }
            recordsNo = (Float.parseFloat(obj.toString()));
            tx.commit();
        } catch (HibernateException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception when get update no of petty cash", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return recordsNo;
    }

    /** {@inheritDoc} */
    @Override
    public void deleteById(String recId) throws ServiceException {
        if (StringUtils.isEmpty(recId)) {
            throw new IllegalArgumentException("To delete a petty cash record, its id must not be empty!");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            StringBuilder sql = new StringBuilder();
            sql.append(" DELETE FROM " + TblConstants.TBL_PETTY_CASH);
            sql.append(" WHERE RecID=:recID ");

            Query query = pettyCashRepository.getSQLQuery(session, sql.toString()).setString("recID", recId);
            query.executeUpdate();
            tx.commit();
        } catch (Exception ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("Hibernate runtime exception occur when delete a petty cash", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
    }

    /** {@inheritDoc} */
    @Override
    public JSONBean handleDataChange(String monthly, List<PettyCashBean> pettyCashBeans) {
        if (pettyCashBeans == null) {
            return new JSONBean(Boolean.FALSE, -1, MessageHelper.get(MsgConstants.CM_UPD_M03));
        }

        User user = AuthenticatedUserDetails.getUserPrincipal();
        if (user == null) {
            logger.info("You must login to use this function");
            // 
            throw new IllegalStateException("You don't have a permission to use this");
        }

        try {
            for (int i = 0; i < pettyCashBeans.size(); i++) {
                PettyCashBean pettyCash = pettyCashBeans.get(i);

                // Handle by actual state of petty cash
                switch (pettyCash.getState()) {
                case DELETE_STATE: {
                    deleteById(pettyCash.getId());
                    break;
                }
                case UPDATE_STATE: {
                    updatePettyCash(pettyCash);
                    break;
                }
                case CREATE_NEW_STATE: {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Waiting seconds... we are trying to create a new one petty cash {}",
                                pettyCash.getId());
                    }

                    // * Create new or update sequence BEGIN
                    String maximumSeqNo = null;

                    try {
                        final String REC_CODE = "AT009.RecID";
                        maximumSeqNo = serialNumberService.generateUUIDByRecID(REC_CODE);
                    } catch (ServiceException ex) {
                        logger.error(ex.getMessage(), ex);

                        // 
                        return new JSONBean(Boolean.FALSE, -1, MessageHelper.getSystemError());
                    }

                    if (StringUtils.isEmpty(maximumSeqNo)) {
                        logger.warn("Could not generate a sequence number at this time");

                        //
                        return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M03));
                    }

                    // Creating a new one petty cash
                    insertPettyCash(monthly, maximumSeqNo, pettyCash);

                    // 
                    logger.info("Successfully created a new one petty cash");
                    break;
                }
                default: {
                    break;
                }
                }
            }

            return new JSONBean(Boolean.TRUE, 1, MessageHelper.get(MsgConstants.CM_UPD_M02));
        } catch (IllegalArgumentException | IllegalStateException ex) {
            logger.error(ex.getMessage(), ex);

            return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M01));
        } catch (ObjectNotFoundException ex) {
            logger.error(ex.getMessage(), ex);

            return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M03));
        } catch (HibernateException ex) {
            logger.error(ex.getMessage(), ex);

            return new JSONBean(Boolean.FALSE, -1, MessageHelper.getSystemError());
        }
    }
}