com.nec.harvest.controller.KoguchiController.java Source code

Java tutorial

Introduction

Here is the source code for com.nec.harvest.controller.KoguchiController.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.controller;

import java.lang.reflect.Field;
import java.net.URI;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import com.nec.core.exception.ObjectNotFoundException;
import com.nec.core.exception.TooManyObjectsException;
import com.nec.harvest.bean.mapping.PettyCashBean;
import com.nec.harvest.bean.mapping.json.JSONBean;
import com.nec.harvest.constant.Constants;
import com.nec.harvest.constant.MsgConstants;
import com.nec.harvest.exception.ServiceException;
import com.nec.harvest.helper.MessageHelper;
import com.nec.harvest.menu.group.DailyReportingProGroup;
import com.nec.harvest.model.Organization;
import com.nec.harvest.model.PettyCash;
import com.nec.harvest.model.SmallCategory;
import com.nec.harvest.model.Tighten;
import com.nec.harvest.service.OrganizationService;
import com.nec.harvest.service.PettyCashService;
import com.nec.harvest.service.SmallCategoryService;
import com.nec.harvest.service.TightenService;
import com.nec.harvest.stereotype.SessionAttribute;
import com.nec.harvest.util.DateFormatUtil;
import com.nec.harvest.util.DateFormatUtil.DateFormat;
import com.nec.harvest.util.DateUtil;

/**
 * All about koguchi path implementation
 * 
 * @author huonghv
 *
 */
@Controller
@RequestMapping(Constants.KOGUCHI_PATH)
public class KoguchiController extends DailyReportingProGroup implements AbstractRenderer, TitleRenderer {

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

    private static final String PETTY_CASH_LIST = "lstPettyCashes";
    private static final String SMALL_CATEGORY_LIST = "lstSmallCategories";
    private static final String DEFAULT_SETTING_AMOUNT = "defaultSettingAmount";

    private final PettyCashService pettyCashService;

    private final SmallCategoryService smallCategoryService;

    private final OrganizationService organizationService;

    private final TightenService tightenService;

    @Inject
    public KoguchiController(PettyCashService pettyCashService, SmallCategoryService smallCategoryService,
            OrganizationService organizationService, TightenService tightenService) {
        this.pettyCashService = pettyCashService;
        this.smallCategoryService = smallCategoryService;
        this.organizationService = organizationService;
        this.tightenService = tightenService;
    }

    /** {@inheritDoc} */
    @Override
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
            @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
        logger.info("Load koguchi page");

        //
        String businessDate = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);

        // Build a link to redirect
        UriComponents uriComponent = UriComponentsBuilder
                .fromUriString(Constants.KOGUCHI_PATH + "/{orgCode}/{monthly}").build();
        URI uri = uriComponent.expand(proGNo, userOrgCode, businessDate).encode().toUri();
        return "redirect:" + uri.toString();
    }

    /**
     * Load koguchi page with parameters organization code and current date
     * 
     * @param orgCode
     *            Organization code on request path
     * @param monthly
     *            Current business day on request path
     * @param model
     *            Model to update and return to view
     * @param businessDay
     *            Business day on session
     * @param orgCodeFromSession
     *            Organization code on session
     * @return Logic page view
     */
    @RequestMapping(value = "/{orgCode}/{monthly}", method = RequestMethod.GET)
    public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
            @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo,
            @PathVariable String orgCode, @PathVariable @DateTimeFormat(pattern = "yyyyMM") Date monthly,
            final Model model) {
        logger.info("Koguchi page view rendering...");

        //
        model.addAttribute(PRINTABLE, true);
        model.addAttribute(PROCESSING_MONTH, monthly);

        try {
            // Get petty cash data
            List<PettyCash> pettyCashes = pettyCashService.findByOrgCodeAndBusinessDay(userOrgCode, monthly);
            model.addAttribute(PETTY_CASH_LIST, pettyCashes);
            if (pettyCashes == null || pettyCashes.size() == 0) {
                model.addAttribute(ERROR, false);
                model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.CM_QRY_M01));
            }
        } catch (IllegalArgumentException ex) {
            logger.warn(ex.getMessage());
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

            // ???????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, getSystemError());
            return getViewName();
        }

        try {

            // Check next and previous month is available            
            Date previousMonth = DateUtil.monthsToSubtract(businessDay, 12);
            Date nextMonth = DateUtil.monthsToSubtract(businessDay, 1);
            if (monthly.compareTo(previousMonth) > 0) {
                model.addAttribute(PREVIOUS_MONTH, DateUtil.monthsToSubtract(monthly, 1));
            }

            if (monthly.compareTo(nextMonth) <= 0) {
                model.addAttribute(NEXT_MONTH, DateUtil.monthsToAdd(monthly, 1));
            }

        } catch (IllegalArgumentException ex) {
            logger.warn(ex.getMessage());
        }

        try {
            // Get small category data
            List<SmallCategory> smallCategories = smallCategoryService.findAll();
            model.addAttribute(SMALL_CATEGORY_LIST, smallCategories);
        } catch (IllegalArgumentException ex) {
            logger.warn(ex.getMessage());
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

            // ???????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, getSystemError());
            return getViewName();
        }

        try {
            // Get default total amount
            Organization orgObj = organizationService.findByOrgCode(orgCode);
            if (logger.isDebugEnabled()) {
                logger.debug("Organization: {}", orgObj.toString());
            }

            logger.info("Total amount of all montly: {}", orgObj.getAmountOfToltal());
            String amount = getTotalAmountOfMonth(monthly, orgObj);

            logger.info("Total amount of processing monthly: {}", amount);
            model.addAttribute(DEFAULT_SETTING_AMOUNT, amount);
        } catch (IllegalArgumentException ex) {
            logger.warn(ex.getMessage());
        } catch (ServiceException | TooManyObjectsException ex) {
            logger.error(ex.getMessage(), ex);

            // ???????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, getSystemError());
            return getViewName();
        }

        // Check and set editable page
        pageEditable(monthly, businessDay, model);

        logger.info("Koguchi page view rendered!");
        return getViewName();
    }

    /**
     * Handle submission from client To create new, update or delete petty
     * cashes list
     * 
     * @param orgCode
     *            The organization code
     * @param monthly
     *            Current business day
     * @param request
     *            The server request
     * @param businessDay
     *            The business day get from session
     * @param userOrgCode
     *            The organization code from session
     * @param pettyCashBeans
     *            The beans submit from client
     * @return
     */
    @RequestMapping(value = "/save/{orgCode}/{monthly}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody JSONBean saveKoguchiData(@SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay,
            @SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode, @PathVariable String proGNo,
            @PathVariable String orgCode, @PathVariable @DateTimeFormat(pattern = "yyyyMM") Date monthly,
            @RequestBody final List<PettyCashBean> pettyCashBeans) {
        // LOG
        logger.info("Handling submit from client...");

        JSONBean jsonBean = new JSONBean(false, 1, MessageHelper.get(MsgConstants.CM_UPD_M03));
        /* To security, check organization code from session and path variable */
        if (!userOrgCode.equalsIgnoreCase(orgCode)) {
            logger.error("Organization code get from session is different with one from path variable");

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

        String strMonthly = "";
        try {
            strMonthly = DateFormatUtil.format(monthly, DateFormat.DATE_WITHOUT_DAY);
        } catch (IllegalArgumentException | NullPointerException ex) {
            logger.warn("Casting date to string error");
        }

        try {
            jsonBean = pettyCashService.handleDataChange(strMonthly, pettyCashBeans);

            // Successfully handled process
            logger.info("Submit from client was handled successful!");
        } catch (ServiceException ex) {
            logger.error("???????????", ex);

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

        return jsonBean;
    }

    /**
     * Get total amount of month
     * 
     * @param businessDay
     *       The date to determine month
     * @param orgObj
     *       Organization object that contain amount of month
     * @return
     *       The amount of month in string type
     */
    private String getTotalAmountOfMonth(Date businessDay, Organization orgObj) {
        if (businessDay == null || orgObj == null) {
            return null;
        }

        try {
            String fieldToFind = "koguchi";
            int month = DateUtil.getMonth(businessDay);

            if (month != DateUtil.INVALID) {
                fieldToFind += String.valueOf(month).trim();
                Field field = orgObj.getClass().getDeclaredField(fieldToFind);
                field.setAccessible(true);
                Object smallAmountDefault = field.get(orgObj);
                if (smallAmountDefault == null) {
                    return "";
                }
                return String.valueOf(smallAmountDefault);
            }

        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            logger.warn("Cannot get total amount of month ");
            return "";
        }

        return "";
    }

    /**
     * To set editable page
     * 
     * @param currentDate
     *          Current date
     * @param businessDay
     *          The business day
     * @param model
     *          Page model to update attribute EDITABLE
     */
    private void pageEditable(Date currentDate, Date businessDay, final Model model) {
        Date getSudo = null;
        try {
            Tighten tighten = tightenService.findByClassifyAndMonth("1");
            getSudo = DateFormatUtil.parse(tighten.getGetSudo(), DateFormat.DATE_WITHOUT_DAY);

            //
            model.addAttribute(EDITABLE, currentDate.after(getSudo));
        } catch (ObjectNotFoundException ex) {
            getSudo = DateUtil.monthsToSubtract(businessDay, 3);

            // 
            model.addAttribute(EDITABLE, currentDate.after(getSudo));
        } catch (IllegalArgumentException | NullPointerException | ParseException ex) {
            logger.warn(ex.getMessage());

            // 
            model.addAttribute(EDITABLE, Boolean.FALSE);
        }
    }

    @Override
    public String getViewName() {
        return "koguchi/koguchi";
    }

    @Override
    public String getTitleName() {
        return "???";
    }
}