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

Java tutorial

Introduction

Here is the source code for com.nec.harvest.controller.IdoController.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.net.URI;
import java.text.ParseException;
import java.util.Collections;
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.MoveTransferBean;
import com.nec.harvest.bean.mapping.json.JSONBean;
import com.nec.harvest.bean.mapping.json.JSONMoveTransfer;
import com.nec.harvest.constant.Constants;
import com.nec.harvest.constant.MsgConstants;
import com.nec.harvest.exception.ServiceException;
import com.nec.harvest.helper.BusinessDayHelper;
import com.nec.harvest.helper.MessageHelper;
import com.nec.harvest.menu.group.DailyReportingProGroup;
import com.nec.harvest.model.Account;
import com.nec.harvest.model.Organization;
import com.nec.harvest.model.Tighten;
import com.nec.harvest.service.AccountService;
import com.nec.harvest.service.MoveTransferService;
import com.nec.harvest.service.OrganizationService;
import com.nec.harvest.service.TightenService;
import com.nec.harvest.stereotype.MaskFormat;
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;

@Controller
@RequestMapping(Constants.IDO_PATH)
public class IdoController extends DailyReportingProGroup implements AbstractRenderer, TitleRenderer {

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

    private static final String MOVE_TRANSFERES = "moveTransferBeans";
    private static final String ORGNIZATIONS = "organizations";
    private static final String ITEMS = "items";

    private final MoveTransferService moveTransferService;

    private final OrganizationService organizationService;

    private final TightenService tightenService;

    private final AccountService accountService;

    @Inject
    public IdoController(MoveTransferService moveTransferService, OrganizationService organizationService,
            TightenService tightenService, AccountService accountService) {
        this.moveTransferService = moveTransferService;
        this.organizationService = organizationService;
        this.tightenService = tightenService;
        this.accountService = accountService;
    }

    /**
     * Default mapping without path variables for IDO screen
     * 
     * @param userOrgCode
     * @param businessDay
     * @param proGNo
     * @param request
     * @param response
     * @param model
     * @return String redirect Uri
     */
    @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) {
        if (logger.isDebugEnabled()) {
            logger.debug("Redering ido report without parameters...");
        }

        // Automatically build a redirect link
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(Constants.IDO_PATH + "/{orgCode}/{month}")
                .build();
        String businessMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);
        URI uri = uriComponents.expand(proGNo, userOrgCode, businessMonth).encode().toUri();
        return "redirect:" + uri.toString();
    }

    /**
     * This function will be mapped with URL {@link /ido/ organizationCode}
     * /{businessDay}}, it can be used to render the IDO screen with a month for
     * a orgnization. Will be displayed a message when have a exception or an
     * error occurred
     * 
     * @param orgCodeStored
     * @param businessDay
     * @param orgCode
     * @param monthly
     * @param model
     * @return String redirect Uri
     */
    @RequestMapping("/{orgCode:[a-z0-9]+}/{monthly:[\\d]+}")
    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) {
        if (logger.isDebugEnabled()) {
            logger.debug("Redering ido page...");
        }

        logger.info("Trying to generate the ido template for monthly {} and organization code {}", monthly,
                orgCode);

        //
        model.addAttribute(PROCESSING_MONTH, monthly);

        try {
            List<MoveTransferBean> moveTransferes = moveTransferService.findByOrgCodeAndMonthly(orgCode,
                    DateFormatUtil.format(monthly, DateFormat.DATE_WITHOUT_DAY));
            model.addAttribute(MOVE_TRANSFERES, moveTransferes);
        } catch (IllegalArgumentException ex) {
            logger.warn(ex.getMessage());
        } catch (ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.CM_QRY_M01));
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

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

        // The following source code will be detected the end-user can be changed
        // the sales data or not. If the data already pushed into Tighten table 
        // so that means end-user can not modify the data. Otherwise that is TRUE
        Tighten tighten = null;
        Date monthsToSubtract;

        try {
            tighten = tightenService.findByClassifyAndMonth("1"); // NOTE: fixed value is 1
            // The final month year of tighten
            String getSudoOfTighten = tighten.getGetSudo();

            try {
                Date monthlyOfTighten = DateFormatUtil.parse(getSudoOfTighten, DateFormat.DATE_WITHOUT_DAY);
                model.addAttribute(EDITABLE, monthly.after(monthlyOfTighten));
            } catch (NullPointerException | ParseException ex) {
                logger.warn(ex.getMessage(), ex);

                // The default is can't be edited
                model.addAttribute(EDITABLE, Boolean.FALSE);
            }
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            monthsToSubtract = DateUtil.monthsToSubtract(businessDay, 3);
            model.addAttribute(EDITABLE, monthly.after(monthsToSubtract));
        } catch (TooManyObjectsException ex) {
            logger.warn(ex.getMessage(), ex);

            // The default is can be edited
            model.addAttribute(EDITABLE, Boolean.TRUE);
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

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

        // 13 months to subtract based on current month (processing month)
        monthsToSubtract = DateUtil.monthsToSubtract(businessDay, 12);

        // ???????????
        String previousMonthly = null;
        if (monthly.after(monthsToSubtract)) {
            previousMonthly = BusinessDayHelper.getPreviousMonthly(monthly, DateFormat.DATE_WITHOUT_DAY);
        }

        // ??????????
        String nextMontly = BusinessDayHelper.getNextMonthly(monthly, DateFormat.DATE_WITHOUT_DAY);
        Date tempNextMontly = null;
        try {
            tempNextMontly = DateFormatUtil.parse(nextMontly, DateFormat.DATE_WITHOUT_DAY);
        } catch (NullPointerException | IllegalArgumentException | ParseException ex) {
            logger.warn(ex.getMessage(), ex);
        }

        if (tempNextMontly == null || tempNextMontly.after(businessDay)) {
            nextMontly = null;
        }

        model.addAttribute(PREVIOUS_MONTH, previousMonthly);
        model.addAttribute(NEXT_MONTH, nextMontly);

        // Get list Organization for select box
        List<Organization> organizations;

        try {
            organizations = organizationService.findByKaisoBango(Constants.DEFAULT_KAISOBANGO);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // 
            organizations = Collections.emptyList();
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

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

        // 
        model.addAttribute(ORGNIZATIONS, organizations);

        // Get list Item for select box
        List<Account> accounts;

        try {
            accounts = accountService.findByIdoKbn(Constants.DEFAULT_KBN);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            accounts = Collections.emptyList();
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

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

        model.addAttribute(ITEMS, accounts);

        // 
        logger.info("Successfully rendered the ido view for organization {}", userOrgCode);
        return getViewName();
    }

    /**
     * This function will be mapped with URL {@link /ido/save/ organizationCode}
     * /{businessDay}}, it can be used to save sales data changed. Will be
     * displayed a message when have a exception or an error occurred.
     * 
     * @param orgCode
     * @param monthly
     * @param params
     * @param model
     * @return JSonBean
     */
    @RequestMapping(value = "/save/{orgCode:[a-z0-9]+}/{monthly:[\\d]+}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody JSONBean saveIdoData(@PathVariable String proGNo, @PathVariable String orgCode,
            @PathVariable @MaskFormat("######") String monthly,
            @RequestBody final List<JSONMoveTransfer> jSONMoveTransferes, final Model model) {
        if (logger.isDebugEnabled()) {
            logger.debug("Saving sales data on month: " + monthly + " of organizetion code: " + orgCode);
        }
        try {
            return moveTransferService.handleMoveTransferes(monthly, jSONMoveTransferes);
        } catch (IllegalArgumentException | IllegalStateException | ServiceException ex) {
            logger.warn(ex.getMessage());
            return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M03));
        }
    }

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

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

}