/**
 * Copyright (c) 2003-2006 System Integrator Corporation.
 *                 All Rights Reserved.
 */
package jp.co.sint.servlet.mallmgr;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jp.co.sint.basic.SILogin;
import jp.co.sint.basic.SIMailTemp;
import jp.co.sint.basic.SIReserveOrder;
import jp.co.sint.basic.SIStockHistory;
import jp.co.sint.basic.SITax;
import jp.co.sint.beans.mallmgr.UIStockHistory;
import jp.co.sint.beans.mallmgr.UIStockControl;
import jp.co.sint.beans.mallmgr.UIStockDecide;
import jp.co.sint.config.SIConfig;
import jp.co.sint.config.SICSVConf;
import jp.co.sint.config.SIDBMultiConf;
import jp.co.sint.config.SIFlagConf;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDateType;
import jp.co.sint.database.SIDeleteRec;
import jp.co.sint.database.SIDuplicateKeyException;
import jp.co.sint.database.SIInsertRec;
import jp.co.sint.database.SIModifyRec;
import jp.co.sint.database.SISpcType;
import jp.co.sint.mail.SISendMail;
import jp.co.sint.servlet.SIServlet;
import jp.co.sint.tools.SICheckUtil;
import jp.co.sint.tools.SICSVWrite;
import jp.co.sint.tools.SICustomError;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIDateTime;
import jp.co.sint.tools.SIErrorFactory;
import jp.co.sint.tools.SIFatalException;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIBGUtil;
import jp.co.sint.tools.SIUtil;
import jp.co.sint.tools.SIFlagUtil;

import org.apache.log4j.Category;
import jp.co.sint.tools.SIURLParameter;

public class SIRegStockControlSrv extends SIServlet {
  // ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);
  
  /**
   * <b>doUpdate</b> HTTP リクエストの処理
   * 
   * @param request リクエスト
   * @param response
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void doUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    SILogin manLogin = SIHTMLUtil.getLogin(request);
    if (!manLogin.isLogin()) {
      forwardKey(request, response, "webshop.jsp.manager.login");
      return;
    }
    
    HttpSession session = request.getSession(true);// セッションの取得
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();// DBへのコネクションの作成
    SIURLParameter urlParam = new SIURLParameter(request);
    
    try {
      String actionName = this.getActionName(urlParam);// 画面からのアクション
      String editMode = this.getEditMode(urlParam);// DBへの編集モード
      Connection lConnection = databaseConnection.getConnection();
      
      UIStockControl stockControl = new UIStockControl();
      UIStockHistory stockHistory = new UIStockHistory();
      
      if (this.getServletPath(request).equals("/mallmgr/RegStockControlSrv")) {//入出庫管理・入出庫履歴
        if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) {// 一覧と検索などの画面（入庫管理）
          // データの取得とデータのチェック
          stockControl = new UIStockControl(request, urlParam);
          stockControl.validateStoreList(request);
          session.setAttribute(SIConfig.SISESSION_MAN_STORE_CONTROL_NAME, stockControl);
          forwardKey(request, response, "webshop.jsp.manager.store.control");
        } else if (SIConfig.SIACTION_LIST2.equalsIgnoreCase(actionName)) {// 一覧と検索などの画面（出庫管理）
          // データの取得とデータのチェック
          stockControl = new UIStockControl(request, urlParam);
          stockControl.validateShipList(request);
          session.setAttribute(SIConfig.SISESSION_MAN_SHIP_CONTROL_NAME, stockControl);
          forwardKey(request, response, "webshop.jsp.manager.ship.control");
        } else if (SIConfig.SIACTION_DETAIL.equalsIgnoreCase(actionName)) {// 入庫履歴画面
          // データの取得とデータのチェック
          stockHistory = new UIStockHistory(request, urlParam);
          if (stockHistory.validateIndividual(request, lConnection)) {
            session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.history");
          } else {
            forwardKey(request, response, "webshop.jsp.manager.store.control");
          }
        } else if (SIConfig.SIACTION_DETAIL2.equalsIgnoreCase(actionName)) {// 出庫履歴画面
          // データの取得とデータのチェック
          stockHistory = new UIStockHistory(request, urlParam);
          if (stockHistory.validateIndividual(request, lConnection)) {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.history");
          } else {
            forwardKey(request, response, "webshop.jsp.manager.ship.control");
          }
        } else if (SIConfig.SIACTION_BACK.equalsIgnoreCase(actionName)) {// 入庫履歴へ戻る
          if (SIConfig.SIEDIT_MODE_LIST.equals(editMode)) forwardKey(request, response, "webshop.jsp.manager.cmdty.edit");
          else forwardKey(request, response, "webshop.jsp.manager.store.control");
        } else if (SIConfig.SIACTION_BACK2.equalsIgnoreCase(actionName)) {// 出庫履歴へ戻る
          forwardKey(request, response, "webshop.jsp.manager.ship.control");
        } else if (SIConfig.SIACTION_MOVE.equalsIgnoreCase(actionName)) {// 在庫移動
          stockHistory.initMove(request, urlParam);
          if (stockHistory.validateMove(request, lConnection)) {
            try {
              moveStock(lConnection, stockHistory);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.history");
          }
        } else if (SIConfig.SIACTION_PREVIEW2.equalsIgnoreCase(actionName)) {// 仕入まとめて入庫（表示）
          stockHistory = new UIStockHistory(request, urlParam);
          session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
          forwardKey(request, response, "webshop.jsp.manager.store.distribute");
        } else if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)) {// 仕入まとめて入庫（確定）
          stockHistory.initStoreFull(request, urlParam);
          if (stockHistory.validateStoreFull(request, lConnection)) {
            try {
              storeFull(lConnection, stockHistory);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.store.distribute");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.store.distribute");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.distribute");
          }
        } else if (SIConfig.SIACTION_PREVIEW.equalsIgnoreCase(actionName)) {// 在庫まとめて移動（表示）
          stockHistory = new UIStockHistory(request, urlParam);
          session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
          forwardKey(request, response, "webshop.jsp.manager.ship.move");
        } else if (SIConfig.SIACTION_MOVE2.equalsIgnoreCase(actionName)) {// 在庫まとめて移動（確定）
          stockHistory.initMoveFull(request, urlParam);
          if (stockHistory.validateMoveFull(request, lConnection)) {
            try {
              moveStockFull(lConnection, stockHistory);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.ship.move");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.ship.move");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.move");
          }
        } else if (SIConfig.SIACTION_REFRESH.equalsIgnoreCase(actionName)) {
          stockHistory = new UIStockHistory(request, urlParam);
          session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
          forwardKey(request, response, "webshop.jsp.manager.ship.history");
        } else if (SIConfig.SIACTION_RESERVE.equalsIgnoreCase(actionName)) {// 予約割当
          boolean mailflg = stockHistory.initReserve(request, urlParam);
          if (stockHistory.validateReserve(request, lConnection)) {
            try {
              String fromMail = SIDBUtil.getFirstData(databaseConnection.getConnection(), "SELECT email FROM chargetbl WHERE chargecode=" + SIDBUtil.SQL2Str(manLogin.getUserCode()));
              assignReserve(lConnection, stockHistory, fromMail);
              if (mailflg) {
                if (sendShipmentMail(request, lConnection, stockHistory.getReserveCode())) {
                  request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert.mail"));
                } else {
                  request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert.mail2"));
                }
              } else {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              }
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.history");
          }
        } else if (SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)) {// 入庫取消
          stockHistory.initDelete(request, urlParam);
          if (stockHistory.validateDelete(request, lConnection, true)) {
            try {
              deleteStore(lConnection, stockHistory, manLogin.getUserCode());
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.delete"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.history");
          }
        } else if (SIConfig.SIACTION_DELETE2.equalsIgnoreCase(actionName)) {// 出庫取消
          stockHistory.initDelete(request, urlParam);
          if (stockHistory.validateDelete(request, lConnection, false)) {
            try {
              deleteShip(lConnection, stockHistory, manLogin.getUserCode());
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.delete"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.history");
          }
        } else if (SIConfig.SIACTION_APPROVAL.equalsIgnoreCase(actionName)) {// 入庫承認
          stockHistory.initApproveStore(request, urlParam);
          if (stockHistory.validateApprove(request, lConnection, true)) {
            try {
              approveStore(lConnection, stockHistory);
              int result = sendApproveMail(request, lConnection, stockHistory, true, manLogin);
              if (result == 1) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail"));
              } else if (result == 3){
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail3"));
              } else {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail2"));
              }
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.history");
          }
        } else if (SIConfig.SIACTION_APPROVAL2.equalsIgnoreCase(actionName)) {// 出庫承認
          stockHistory.initApproveShip(request, urlParam);
          if (stockHistory.validateApprove(request, lConnection, false)) {
            try {
              approveShip(lConnection, stockHistory);
              int result = sendApproveMail(request, lConnection, stockHistory, false, manLogin);
              if (result == 1) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail"));
              } else if (result == 3) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail3"));
              } else {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail2"));
              }
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.history");
          }
        } else if (SIConfig.SIACTION_REJECTION.equalsIgnoreCase(actionName)) {// 入庫却下
          stockHistory.initApproveStore(request, urlParam);
          if (stockHistory.validateRejection(request, lConnection, true)) {
            try {
              rejectStore(request, lConnection, stockHistory, manLogin.getUserCode());
              int result = sendRejectMail(request, lConnection, stockHistory, true, manLogin);
              if (result == 1) {// メール送信成功
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail"));
              } else if (result == 3) {// メール送信しない
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail3"));
              } else {// メール送信失敗
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail2"));
              }
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.history");
          }
        } else if (SIConfig.SIACTION_REJECTION2.equalsIgnoreCase(actionName)) {// 出庫却下
          stockHistory.initApproveShip(request, urlParam);
          if (stockHistory.validateRejection(request, lConnection, false)) {
            try {
              rejectShip(lConnection, stockHistory);
              int result = sendRejectMail(request, lConnection, stockHistory, false, manLogin);
              if (result == 1) {// メール送信成功
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail"));
              } else if (result == 3){// メール送信しない
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail3"));
              } else {// メール送信失敗
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail2"));
              }
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.history");
          }
        } else if (SIConfig.SIACTION_CORRECTION.equalsIgnoreCase(actionName)) {// 入庫訂正
          stockHistory.initCorrectStore(request, urlParam);
          if (stockHistory.validateCorrection(request, lConnection, true)) {
            try {
              storeCorrection(lConnection, stockHistory);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.correction"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.history");
          }
        } else if (SIConfig.SIACTION_CORRECTION2.equalsIgnoreCase(actionName)) {// 出庫訂正
          stockHistory.initCorrectShip(request, urlParam);
          if (stockHistory.validateCorrection(request, lConnection, false)) {
            try {
              if (stockHistory.isMultiShippment(lConnection)) {
                String[] numList = stockHistory.getOtherShippmentNumber(lConnection);
                shipCorrection(lConnection, stockHistory);
                if (numList != null && numList.length > 0){
                  for (int i=0;i<numList.length;i++) {
                    stockHistory.setCorrectNo(numList[i]);
                    if (stockHistory.validateCorrection(request, lConnection, false)) shipCorrection(lConnection, stockHistory, true);
                  }
                }
              }else{
                shipCorrection(lConnection, stockHistory);
              }
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.correction"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.history");
          }
        } else if (SIConfig.SIACTION_ADD.equalsIgnoreCase(actionName)) {// 新規入庫作成
          stockHistory.initNewStore(request, urlParam);
          if (stockHistory.validateNewStore(request, lConnection)) {
            try {
              // 買取・訂正・その他・評価替えは承認不要
              if (stockHistory.getType().equals("1") || stockHistory.getType().equals("4") || stockHistory.getType().equals("6") || stockHistory.getType().equals("10")) {
                createNewStore(lConnection, stockHistory);
              } else {
                createNewStore2(lConnection, stockHistory);
              }
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.store.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_STORE_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.store.history");
          }
        } else if (SIConfig.SIACTION_ADD2.equalsIgnoreCase(actionName)) {// 新規出庫作成
          stockHistory.initNewShip(request, urlParam);
          if (stockHistory.validateNewShip(request, lConnection)) {
            try {
              // 訂正・その他・評価替えは承認不要
              if (stockHistory.getType().equals("4") || stockHistory.getType().equals("6") || stockHistory.getType().equals("10")) {
                createNewShip2(lConnection, stockHistory);
              } else {
                createNewShip(lConnection, stockHistory);
              }
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {
                lConnection.commit();
              } catch (SQLException sqle) {}
              stockHistory = new UIStockHistory(request, urlParam);
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            } catch (SIDBAccessException e) {
              try {
                lConnection.rollback();
              } catch (SQLException sqle) {}
              session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.ship.history");
            }
          } else {
            session.setAttribute(SIConfig.SISESSION_MAN_SHIP_HISTORY_NAME, stockHistory);
            forwardKey(request, response, "webshop.jsp.manager.ship.history");
          }
        }
      }else if (this.getServletPath(request).equals("/mallmgr/RegDecideAllSrv")) {//一括決裁画面
        if (SIUtil.isNull(actionName)) {
          forwardKey(request, response, "webshop.jsp.manager.decide.all");
        }
        if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) {// 新規出庫作成
          UIStockDecide lStockDecide = new UIStockDecide();
          lStockDecide.init(request, urlParam);
          lStockDecide.validate(request);
          session.setAttribute(SIConfig.SISESSION_MAN_DECIDE_ALL_NAME, lStockDecide);
          forwardKey(request, response, "webshop.jsp.manager.decide.all");
        } else if (SIConfig.SIACTION_APPROVAL.equalsIgnoreCase(actionName)) {// 入庫承認
          stockHistory.setCmdtyCode((String)urlParam.getParam("cmdtyCode"));
          stockHistory.setIndividualCode((String)urlParam.getParam("individualCode"));
          stockHistory.initApproveStore(request, urlParam);
          if (stockHistory.validateApprove(request, lConnection, true)) {
            try {
              approveStore(lConnection, stockHistory);
              int result = sendApproveMail(request, lConnection, stockHistory, true, manLogin);
              if (result == 1) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail"));
              } else if (result == 3){
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail3"));
              } else {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail2"));
              }
              try {lConnection.commit();} catch (SQLException sqle) {}
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            } catch (SIDBAccessException e) {
              try {lConnection.rollback();} catch (SQLException sqle) {}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.decide.all");
          }
        } else if (SIConfig.SIACTION_APPROVAL2.equalsIgnoreCase(actionName)) {// 出庫承認
          stockHistory.setCmdtyCode((String)urlParam.getParam("cmdtyCode"));
          stockHistory.setIndividualCode((String)urlParam.getParam("individualCode"));
          stockHistory.initApproveShip(request, urlParam);
          if (stockHistory.validateApprove(request, lConnection, false)) {
            try {
              approveShip(lConnection, stockHistory);
              int result = sendApproveMail(request, lConnection, stockHistory, false, manLogin);
              if (result == 1) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail"));
              } else if (result == 3) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail3"));
              } else {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.approve.mail2"));
              }
              try {lConnection.commit();} catch (SQLException sqle) {}
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            } catch (SIDBAccessException e) {
              try {lConnection.rollback();} catch (SQLException sqle) {}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.decide.all");
          }
        } else if (SIConfig.SIACTION_REJECTION.equalsIgnoreCase(actionName)) {// 入庫却下
          stockHistory.setCmdtyCode((String)urlParam.getParam("cmdtyCode"));
          stockHistory.setIndividualCode((String)urlParam.getParam("individualCode"));
          stockHistory.initApproveStore(request, urlParam);
          if (stockHistory.validateRejection(request, lConnection, true)) {
            try {
              rejectStore(request, lConnection, stockHistory, manLogin.getUserCode());
              int result = sendRejectMail(request, lConnection, stockHistory, true, manLogin);
              if (result == 1) {// メール送信成功
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail"));
              } else if (result == 3) {// メール送信しない
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail3"));
              } else {// メール送信失敗
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail2"));
              }
              try {lConnection.commit();} catch (SQLException sqle) {}
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            } catch (SIDBAccessException e) {
              try {lConnection.rollback();} catch (SQLException sqle) {}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.decide.all");
          }
        } else if (SIConfig.SIACTION_REJECTION2.equalsIgnoreCase(actionName)) {// 出庫却下
          stockHistory.setCmdtyCode((String)urlParam.getParam("cmdtyCode"));
          stockHistory.setIndividualCode((String)urlParam.getParam("individualCode"));
          stockHistory.initApproveShip(request, urlParam);
          if (stockHistory.validateRejection(request, lConnection, false)) {
            try {
              rejectShip(lConnection, stockHistory);
              int result = sendRejectMail(request, lConnection, stockHistory, false, manLogin);
              if (result == 1) {// メール送信成功
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail"));
              } else if (result == 3){// メール送信しない
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail3"));
              } else {// メール送信失敗
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.reject.mail2"));
              }
              try {lConnection.commit();} catch (SQLException sqle) {}
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            } catch (SIDBAccessException e) {
              try {lConnection.rollback();} catch (SQLException sqle) {}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.decide.all");
          }
        } else if (SIConfig.SIACTION_REGIST.equalsIgnoreCase(actionName)) {// 一括承認
          boolean errorMailFlg = false;
          UIStockDecide lStockDecide=(UIStockDecide)session.getAttribute(SIConfig.SISESSION_MAN_DECIDE_ALL_NAME);
          if (lStockDecide==null)lStockDecide=new UIStockDecide();
          lStockDecide.initDecideAll(request,true);
          if (lStockDecide.validateDecideAll(request)) {
            try {
              Iterator itemIte = lStockDecide.getItemData().iterator();
              while (itemIte.hasNext()) {
                stockHistory = (UIStockHistory)itemIte.next();
                if (lStockDecide.isStore())approveStore(lConnection, stockHistory);
                else approveShip(lConnection, stockHistory);
                int result = sendApproveMail(request, lConnection, stockHistory, lStockDecide.isStore(), manLogin);
                if (result==2) errorMailFlg = true;
              }
              if (errorMailFlg) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.freeword","一括承認しましたが一部のメール送信に失敗しました"));
              }else{
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.freeword","一括承認しました"));
              }
              try {lConnection.commit();} catch (SQLException sqle) {}
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            } catch (SIDBAccessException e) {
              try {lConnection.rollback();} catch (SQLException sqle) {}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.decide.all");
          }
        } else if (SIConfig.SIACTION_CANCEL.equalsIgnoreCase(actionName)) {// 一括却下
          boolean errorMailFlg = false;
          UIStockDecide lStockDecide=(UIStockDecide)session.getAttribute(SIConfig.SISESSION_MAN_DECIDE_ALL_NAME);
          if (lStockDecide==null)lStockDecide=new UIStockDecide();
          lStockDecide.initDecideAll(request,false);
          if (lStockDecide.validateDecideAll(request)) {
            try {
              Iterator itemIte = lStockDecide.getItemData().iterator();
              while (itemIte.hasNext()) {
                stockHistory = (UIStockHistory)itemIte.next();
                if (lStockDecide.isStore()) rejectStore(request, lConnection, stockHistory, manLogin.getUserCode());
                else rejectShip(lConnection, stockHistory);
                int result = sendRejectMail(request, lConnection, stockHistory, lStockDecide.isStore(), manLogin);
                if (result==2) errorMailFlg = true;
              }
              if (errorMailFlg) {
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.freeword","一括却下しましたが一部のメール送信に失敗しました"));
              }else{
                request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.freeword","一括却下しました"));
              }
              try {lConnection.commit();} catch (SQLException sqle) {}
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            } catch (SIDBAccessException e) {
              try {lConnection.rollback();} catch (SQLException sqle) {}
              SICustomErrors errors = new SICustomErrors();
              errors.addError(new SICustomError("database.execute.error"));
              request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK, errors);
              forwardKey(request, response, "webshop.jsp.manager.decide.all");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.decide.all");
          }
        } else if (SIConfig.SIACTION_CSV.equalsIgnoreCase(actionName)) {//CSV出力
          // 取得するCSVデータの取得
          UIStockDecide lStockDecide=(UIStockDecide)session.getAttribute(SIConfig.SISESSION_MAN_DECIDE_ALL_NAME);
          if (lStockDecide==null)lStockDecide=new UIStockDecide();
          this.produceCSVFile(response, databaseConnection.getConnection(), lStockDecide);
          if (!response.isCommitted()) {
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("database.query.notexist", "CSVデータ"));
            forwardKey(request, response, "webshop.jsp.manager.decide.all");
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new ServletException();
    } finally {
      databaseConnection.close();
    }
  }
  
  /**
   * <b>deleteStore</b> 入庫取消データを作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @param delUser 削除するユーザ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void deleteStore(Connection lConnection, UIStockHistory stockHistory, String delUser) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    // 在庫数量マイナス
    SISpcType lSpc1 = new SISpcType("amount-" + stockHistory.getNewAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getNewBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      String taxRate = SITax.getTaxRate(lConnection);
      String targetRate = SIDBUtil.getFirstData(lConnection, "SELECT tax(initdatetime) FROM storehistorytbl WHERE individualcode="+SIDBUtil.SQL2Str(stockHistory.getIndividualCode()) +" AND storenumber=" + stockHistory.getDeleteNo());
      if (!taxRate.equals(targetRate)) {
        String pp = SIUtil.div_LD(stockHistory.getPurchasePrice(), SIUtil.add_DL(SIUtil.div_DL(targetRate, "100"), "1"));
        stockHistory.setPurchasePrice(String.valueOf(Math.ceil(Math.floor(Double.parseDouble(pp) * Double.parseDouble(SIUtil.add_DL(SIUtil.div_DL(taxRate, "100"), "1")) * 10000) / 10000)));
        String pe = SIUtil.div_LD(stockHistory.getProcessingExpence(), SIUtil.add_DL(SIUtil.div_DL(targetRate, "100"), "1"));
        stockHistory.setProcessingExpence(String.valueOf(Math.ceil(Math.floor(Double.parseDouble(pe) * Double.parseDouble(SIUtil.add_DL(SIUtil.div_DL(taxRate, "100"), "1")) * 10000) / 10000)));
      }
      String storeNo = stockHistory.getNewStoreNumber(lConnection);
      
      // 入庫履歴（削除用差分データ）
      SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("storenumber", storeNo);
      lRec2.add("storebranch", stockHistory.getNewBranch());
      lRec2.add("storecharge", delUser);
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", stockHistory.getPurchasePrice());
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("storetype", stockHistory.getType());
      lRec2.add("comment", "入庫" + stockHistory.getDeleteNo() + "取消");
      lRec2.add("delflg", "3");
      lRec2.add("initdatetime", lDateTime.getFullDate());
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      // 入庫履歴（削除済みデータ）
      SISpcType lSpc = new SISpcType("comment||'（取消）'");
      SIModifyRec lRec3 = new SIModifyRec("storehistorytbl");
      lRec3.addCondition("cmdtycode", stockHistory.getCmdtyCode());
      lRec3.addCondition("individualcode", stockHistory.getIndividualCode());
      lRec3.addCondition("storenumber", stockHistory.getDeleteNo());
      lRec3.add("comment", lSpc);
      lRec3.add("delflg", "2");
      
      lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      lRec3.execute(lConnection);
      
      if (!stockHistory.getProcessingExpence().equals("0")) {// 加工価格が0円でないとき
      
        // 加工データの削除
        SIDeleteRec lRec4 = new SIDeleteRec("processtbl");
        lRec4.addCondition("cmdtycode", stockHistory.getCmdtyCode());
        lRec4.addCondition("individualcode", stockHistory.getIndividualCode());
        lRec4.addCondition("storenumber", stockHistory.getDeleteNo());
        
        lRec4.execute(lConnection);
      }
      
      // 原価再計算
      //SIBGUtil.costCalculationSub(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getPurchasePrice(), stockHistory.getProcessingExpence(), stockHistory.getNewAmount(), true);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  public synchronized static void deleteStoreHacchu(Connection lConnection, UIStockHistory stockHistory, boolean amountFlg) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    // 在庫数量マイナス
    SISpcType lSpc1 = new SISpcType("amount-" + stockHistory.getNewAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getNewBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      String storeNo = stockHistory.getNewStoreNumber(lConnection);
      
      // 入庫履歴（削除用差分データ）
      SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("storenumber", storeNo);
      lRec2.add("storebranch", stockHistory.getNewBranch());
      lRec2.add("storecharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", stockHistory.getPurchasePrice());
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("storetype", "0");
      lRec2.add("comment", "入庫" + stockHistory.getDeleteNo() + "取消");
      lRec2.add("delflg", "3");
      lRec2.add("initdatetime", stockHistory.getInitDateTime());
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      // 入庫履歴（削除済みデータ）
      SISpcType lSpc = new SISpcType("comment||'（取消）'");
      SIModifyRec lRec3 = new SIModifyRec("storehistorytbl");
      lRec3.addCondition("cmdtycode", stockHistory.getCmdtyCode());
      lRec3.addCondition("individualcode", stockHistory.getIndividualCode());
      lRec3.addCondition("storenumber", stockHistory.getDeleteNo());
      lRec3.add("comment", lSpc);
      lRec3.add("delflg", "2");
      
      if (amountFlg) lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      lRec3.execute(lConnection);
      
      if (amountFlg) {
        if (!stockHistory.getProcessingExpence().equals("0")) {// 加工価格が0円でないとき
          // 加工データの削除
          SIDeleteRec lRec4 = new SIDeleteRec("processtbl");
          lRec4.addCondition("cmdtycode", stockHistory.getCmdtyCode());
          lRec4.addCondition("individualcode", stockHistory.getIndividualCode());
          lRec4.addCondition("storenumber", stockHistory.getDeleteNo());
          lRec4.execute(lConnection);
        }
        
        // 原価再計算
        //SIBGUtil.costCalculationSub(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getPurchasePrice(), stockHistory.getProcessingExpence(), stockHistory.getNewAmount(), true);
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>deleteShip</b> 出庫取消データを作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @param delUser 削除するユーザ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void deleteShip(Connection lConnection, UIStockHistory stockHistory, String delUser) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    // 在庫数量プラス
    SISpcType lSpc1 = new SISpcType("amount+" + stockHistory.getNewAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getNewBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      String taxRate = SITax.getTaxRate(lConnection);
      String targetRate = SIDBUtil.getFirstData(lConnection, "SELECT tax(initdatetime) FROM shiphistorytbl WHERE individualcode="+SIDBUtil.SQL2Str(stockHistory.getIndividualCode()) +" AND shipnumber=" + stockHistory.getDeleteNo());
      if (!taxRate.equals(targetRate)) {
        String pp = SIUtil.div_LD(stockHistory.getPurchasePrice(), SIUtil.add_DL(SIUtil.div_DL(targetRate, "100"), "1"));
        stockHistory.setPurchasePrice(String.valueOf(Math.ceil(Math.floor(Double.parseDouble(pp) * Double.parseDouble(SIUtil.add_DL(SIUtil.div_DL(taxRate, "100"), "1")) * 10000)) / 10000));
        String pe = SIUtil.div_LD(stockHistory.getProcessingExpence(), SIUtil.add_DL(SIUtil.div_DL(targetRate, "100"), "1"));
        stockHistory.setProcessingExpence(String.valueOf(Math.ceil(Math.floor(Double.parseDouble(pe) * Double.parseDouble(SIUtil.add_DL(SIUtil.div_DL(taxRate, "100"), "1")) * 10000)) / 10000));
      }
      String shipNo = stockHistory.getNewShipNumber(lConnection);
      
      // 出庫履歴（削除用差分データ）
      SIInsertRec lRec2 = new SIInsertRec("shiphistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("shipnumber", shipNo);
      lRec2.add("shipbranch", stockHistory.getNewBranch());
      lRec2.add("shipcharge", delUser);
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", stockHistory.getPurchasePrice());
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("shiptype", stockHistory.getType());
      lRec2.add("comment", "出庫" + stockHistory.getDeleteNo() + "取消");
      lRec2.add("delflg", "3");
      lRec2.add("initdatetime", lDateTime.getFullDate());
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      // 出庫履歴（削除済みデータ）
      SISpcType lSpc = new SISpcType("comment||'（取消）'");
      SIModifyRec lRec3 = new SIModifyRec("shiphistorytbl");
      lRec3.addCondition("cmdtycode", stockHistory.getCmdtyCode());
      lRec3.addCondition("individualcode", stockHistory.getIndividualCode());
      lRec3.addCondition("shipnumber", stockHistory.getDeleteNo());
      lRec3.add("comment", lSpc);
      lRec3.add("delflg", "2");
      
      lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      lRec3.execute(lConnection);
      
      // 原価再計算
      //SIBGUtil.costCalculationAdd(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getPurchasePrice(), stockHistory.getProcessingExpence(), stockHistory.getNewAmount(), true);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  public synchronized static void deleteShipHacchu(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    try {
      String shipNo = stockHistory.getNewShipNumber(lConnection);
      
      // 出庫履歴（削除用差分データ）
      SIInsertRec lRec2 = new SIInsertRec("shiphistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("shipnumber", shipNo);
      lRec2.add("shipbranch", stockHistory.getNewBranch());
      lRec2.add("shipcharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", stockHistory.getPurchasePrice());
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("shiptype", "0");
      lRec2.add("comment", "出庫" + stockHistory.getDeleteNo() + "取消");
      lRec2.add("delflg", "3");
      lRec2.add("initdatetime", stockHistory.getInitDateTime());
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      // 出庫履歴（削除済みデータ）
      SISpcType lSpc = new SISpcType("comment||'（取消）'");
      SIModifyRec lRec3 = new SIModifyRec("shiphistorytbl");
      lRec3.addCondition("cmdtycode", stockHistory.getCmdtyCode());
      lRec3.addCondition("individualcode", stockHistory.getIndividualCode());
      lRec3.addCondition("shipnumber", stockHistory.getDeleteNo());
      lRec3.add("comment", lSpc);
      lRec3.add("delflg", "2");
      
      lRec2.execute(lConnection);
      lRec3.execute(lConnection);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>approveStore</b> 未承認入庫データを承認します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void approveStore(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    String purchaseprice = "0";
    String processingexpence = "0";
    SIStockHistory lStock = new SIStockHistory();
    lStock = stockHistory.getHistoryData(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getNumber(), true);
    
    if (lStock.getType().equals("2") || lStock.getType().equals("7") || lStock.getType().equals("9")) {// 加工・修理・代替品は入力値を取得
      purchaseprice = SIUtil.multi(stockHistory.getPurchasePrice(), lStock.getAmount());// 入力値は単価なので総額へ変換
      processingexpence = stockHistory.getProcessingExpence();
    } else {// それ以外は登録値取得
      purchaseprice = lStock.getPurchasePrice();
      processingexpence = lStock.getProcessingExpence();
    }
    
    // 在庫数量プラス
    SISpcType lSpc1 = new SISpcType("amount+" + lStock.getAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", lStock.getBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    // 入庫承認
    SIModifyRec lRec2 = new SIModifyRec("storehistorytbl");
    lRec2.addCondition("cmdtycode", stockHistory.getCmdtyCode());
    lRec2.addCondition("individualcode", stockHistory.getIndividualCode());
    lRec2.addCondition("storenumber", stockHistory.getNumber());
    lRec2.addCondition("delflg","0");
    lRec2.add("purchaseprice", purchaseprice);
    lRec2.add("processingexpence", processingexpence);
    if (!"13".equals(lStock.getType())){
      lRec2.add("ordercode", "");
    }
    lRec2.add("initdatetime", lDateTime.getFullDate());
    lRec2.add("calcdatetime", lDateTime.getFullDateTime());
    if (lStock.getType().equals("2") || lStock.getType().equals("3") || lStock.getType().equals("7") || lStock.getType().equals("9")) lRec2.add("delflg", "4");
    else lRec2.add("delflg", "1");
    
    StringBuffer checkString = new StringBuffer();
    checkString.append("SELECT * FROM storehistorytbl ");
    checkString.append("WHERE cmdtycode = ").append(SIDBUtil.SQL2Str(stockHistory.getCmdtyCode()," "));
    checkString.append("AND individualcode = ").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()," "));
    checkString.append("AND storenumber = ").append(SIDBUtil.SQL2Str(stockHistory.getNumber()," "));
    checkString.append("AND delflg = '0'");
    
    try {
      if (!SIDBUtil.hasData(lConnection, checkString.toString())) {
        throw new SIDBAccessException();
      }
      // コード替＋初回入庫のみ予定原価更新
      StringBuffer checkStr = new StringBuffer();
      checkStr.append("SELECT s.individualcode ");
      checkStr.append("FROM storestocktbl s,individualtbl i ");
      checkStr.append("WHERE i.individualcode=s.individualcode ");
      checkStr.append("AND i.purchaseprice+i.processingexpence=0 ");
      checkStr.append("AND i.individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()," "));
      checkStr.append("GROUP BY s.individualcode ");
      checkStr.append("HAVING sum(s.amount)=0");
      
      if("12".equals(lStock.getType())&&SIDBUtil.hasData(lConnection, checkStr.toString())) {
        String purchaseUnit = "0";
        String processUnit = "0";
        try{purchaseUnit = SIUtil.div(purchaseprice, stockHistory.getNewAmount());}catch(Exception e){purchaseUnit = "0";}
        try{processUnit = SIUtil.div(processingexpence, stockHistory.getNewAmount());}catch(Exception e){processUnit = "0";}
        SIModifyRec lRec4 = new SIModifyRec("individualtbl");
        lRec4.addCondition("cmdtycode", stockHistory.getCmdtyCode());
        lRec4.addCondition("individualcode", stockHistory.getIndividualCode());
        lRec4.add("purchaseprice", purchaseUnit);
        lRec4.add("processingexpence", processUnit);
        lRec4.execute(lConnection);
      }
      lRec2.execute(lConnection);
      lRec1.execute(lConnection);
      
      if (!processingexpence.equals("0")) {// 加工価格が0円でないとき
        String processNo = "";
        String processSql = "SELECT MAX(processnumber) FROM processtbl WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"
            + stockHistory.getIndividualCode() + "'";
        if (SIUtil.isNotNull(SIDBUtil.getFirstData(lConnection, processSql))) processNo = SIUtil.add(SIDBUtil.getFirstData(lConnection, processSql), "1");
        else processNo = "1";
        
        // 加工データ
        SIInsertRec lRec3 = new SIInsertRec("processtbl");
        lRec3.add("cmdtycode", stockHistory.getCmdtyCode());
        lRec3.add("individualcode", stockHistory.getIndividualCode());
        lRec3.add("processnumber", processNo);
        lRec3.add("storenumber", stockHistory.getNumber());
        lRec3.add("processprice", processingexpence);
        lRec3.add("branchcode", "");
        lRec3.add("chargecode", "");
        lRec3.add("makername", "");
        lRec3.add("paymentmethod", "");
        lRec3.add("remarks", "入庫番号" + stockHistory.getNumber() + "番、入庫数" + lStock.getAmount() + "台で加工総額" + processingexpence + "円。");
        lRec3.add("initdatetime", lDateTime.getFullDate());
        
        lRec3.execute(lConnection);
      }
      if (lStock.getType().equals("3")){//移動の時は出庫承認する
        SIModifyRec lRec4 = new SIModifyRec("shiphistorytbl");
        lRec4.addCondition("cmdtycode", stockHistory.getCmdtyCode());
        lRec4.addCondition("individualcode", stockHistory.getIndividualCode());
        lRec4.addCondition("shipnumber", lStock.getOrderCode());
        lRec4.add("initdatetime", lDateTime.getFullDate());
        lRec4.add("calcdatetime", lDateTime.getFullDateTime());
        lRec4.add("delflg", "4");
        lRec4.execute(lConnection);
      }else{
        //原価再計算
        //SIBGUtil.costCalculationAdd(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), purchaseprice, processingexpence, lStock.getAmount(), true);
        
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>rejectStore</b> 未承認入庫データを却下します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void rejectStore(HttpServletRequest request, Connection lConnection, UIStockHistory stockHistory, String delUser) throws SIDBAccessException {
    SIStockHistory lStock = new SIStockHistory();
    SIDateTime lDateTime = new SIDateTime();
    lStock = stockHistory.getHistoryData(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getNumber(), true);
    
    // 保証戻り入庫の場合は却下ではなく承認＋取消を行う
    if (lStock.getType().equals("13")) {
      SIModifyRec lRec1 = new SIModifyRec("storehistorytbl");
      lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());
      lRec1.addCondition("individualcode", stockHistory.getIndividualCode());
      lRec1.addCondition("storenumber", stockHistory.getNumber());
      lRec1.add("delflg", "2");
      lRec1.add("initdatetime", lDateTime.getFullDate());
      lRec1.add("calcdatetime", lDateTime.getFullDateTime());
      
      // 出庫履歴（削除用差分データ）
      SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("storenumber", stockHistory.getNewStoreNumber(lConnection));
      lRec2.add("storebranch", lStock.getBranch());
      lRec2.add("storecharge", lStock.getCharge());
      lRec2.add("amount", lStock.getAmount());
      lRec2.add("purchaseprice", lStock.getPurchasePrice());
      lRec2.add("processingexpence", lStock.getProcessingExpence());
      lRec2.add("storetype", "13");
      lRec2.add("comment", "入庫" + stockHistory.getNumber() + "取消（保証戻り却下）");
      lRec2.add("delflg", "3");
      lRec2.add("initdatetime", lDateTime.getFullDate());
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      try {
        lRec1.execute(lConnection);
        lRec2.execute(lConnection);
      }catch(Exception e){
        e.printStackTrace();
        throw new SIDBAccessException();
      }
    }else{//保証戻り入庫以外の場合は通常の却下を行う
      // 入庫却下
      SIModifyRec lRec1 = new SIModifyRec("storehistorytbl");
      lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());
      lRec1.addCondition("individualcode", stockHistory.getIndividualCode());
      lRec1.addCondition("storenumber", stockHistory.getNumber());
      lRec1.add("purchaseprice", lStock.getPurchasePrice());
      lRec1.add("processingexpence", lStock.getProcessingExpence());
      lRec1.add("ordercode", "");
      lRec1.add("delflg", "5");
      if (SIUtil.isNull(lStock.getComment())) lRec1.add("comment", "（却下されました）");
      else lRec1.add("comment", lStock.getComment() + "（却下されました）");
      
      try {
        lRec1.execute(lConnection);
        
        // 加工・修理・代替品の場合は出庫を取り消す
        if (lStock.getType().equals("2") || lStock.getType().equals("7") || lStock.getType().equals("9")) {
          UIStockHistory delStock = new UIStockHistory();
          delStock.setDeleteNo(lStock.getOrderCode());
          delStock.setCmdtyCode(stockHistory.getCmdtyCode());
          delStock.setIndividualCode(stockHistory.getIndividualCode());
          
          SIModifyRec lRec2 = new SIModifyRec("shiphistorytbl");
          lRec2.addCondition("cmdtycode", stockHistory.getCmdtyCode());
          lRec2.addCondition("individualcode", stockHistory.getIndividualCode());
          lRec2.addCondition("shipnumber", lStock.getOrderCode());
          lRec2.add("delflg", "1");
          lRec2.execute(lConnection);// 削除禁止のフラグを解除する
          
          delStock.validateDelete(request, lConnection, false);
          deleteShip(lConnection, delStock, delUser);
        }else if(lStock.getType().equals("3")){// 移動の場合は却下する
          UIStockHistory delStock = new UIStockHistory();
          delStock.setNumber(lStock.getOrderCode());
          delStock.setCmdtyCode(stockHistory.getCmdtyCode());
          delStock.setIndividualCode(stockHistory.getIndividualCode());
          rejectShip(lConnection, delStock);
        }
      } catch (Exception e) {
        e.printStackTrace();
        throw new SIDBAccessException();
      }
    }
  }
  
  /**
   * <b>approveShip</b> 未承認出庫データを承認します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void approveShip(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    String purchaseprice = "0";
    String processingexpence = "0";
    SIStockHistory lStock = new SIStockHistory();
    SIDateTime lDateTime = new SIDateTime();
    lStock = stockHistory.getHistoryData(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getNumber(), false);
    
    // 原価現在値（予定原価）取得
    if (lStock.getType().equals("12")) {
      String amountorg = "0";
      String pporg = "0";
      String peorg = "0";
      String amountnow = "0";
      String ppnow = "0";
      String penow = "0";
      
      StringBuffer amountStr = new StringBuffer();
      amountStr.append("SELECT CASE substring(i.season,5,2) WHEN '01' THEN sum(s.amount1) WHEN '02' THEN sum(s.amount2) ");
      amountStr.append("WHEN '03' THEN sum(s.amount3) WHEN '04' THEN sum(s.amount4) WHEN '05' THEN sum(s.amount5) ");
      amountStr.append("WHEN '06' THEN sum(s.amount6) WHEN '07' THEN sum(s.amount7) WHEN '08' THEN sum(s.amount8) ");
      amountStr.append("WHEN '09' THEN sum(s.amount9) WHEN '10' THEN sum(s.amount10) WHEN '11' THEN sum(s.amount11) ");
      amountStr.append("ELSE sum(s.amount12) END AS amount ");
      amountStr.append("FROM stockrecordtbl s,(SELECT max(season) AS season FROM inventorytbl) i ");
      amountStr.append("WHERE s.stockyear=substring(i.season,1,4) AND s.individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode(), " "));
      amountStr.append("GROUP BY i.season");
      amountorg = SIDBUtil.getFirstData(lConnection, amountStr.toString());
      
      StringBuffer pp = new StringBuffer();
      pp.append("SELECT purchaseprice FROM costhistorytbl ");
      pp.append("WHERE season=(SELECT max(season) FROM inventorytbl) AND individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
      pporg = SIUtil.multi(amountorg, SIDBUtil.getFirstData(lConnection, pp.toString()));
      
      StringBuffer pe = new StringBuffer();
      pe.append("SELECT processingexpence FROM costhistorytbl ");
      pe.append("WHERE season=(SELECT max(season) FROM inventorytbl) AND individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
      peorg = SIUtil.multi(amountorg, SIDBUtil.getFirstData(lConnection, pe.toString()));
      
      StringBuffer sumlist = new StringBuffer();
      sumlist.append("SELECT coalesce(sum(list.amount),0) AS amount, ");
      sumlist.append("coalesce(sum(list.purchaseprice),0) AS purchaseprice, ");
      sumlist.append("coalesce(sum(list.processingexpence),0) AS processingexpence ");
      sumlist.append("FROM ");
      sumlist.append("(SELECT CASE delflg WHEN 3 THEN -1 ELSE 1 END * amount AS amount, ");
      sumlist.append("CASE delflg WHEN 3 THEN -1 ELSE 1 END * purchaseprice AS purchaseprice, ");
      sumlist.append("CASE delflg WHEN 3 THEN -1 ELSE 1 END * processingexpence AS processingexpence ");
      sumlist.append("FROM storehistorytbl ");
      sumlist.append("WHERE initdatetime>=(SELECT (substring(max(season),1,4)||'-'||substring(max(season),5,2)||'-01')::date + '1 month'::interval FROM inventorytbl) ");
      sumlist.append("AND initdatetime<=current_date AND individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()," "));
      sumlist.append("AND storetype IN ('0','1','2','4','5','6','8','10','11','12','13') AND delflg IN ('1','2','3','4') ");
      sumlist.append("UNION ALL ");
      sumlist.append("SELECT CASE delflg WHEN 3 THEN 1 ELSE -1 END * amount AS amount, ");
      sumlist.append("CASE delflg WHEN 3 THEN 1 ELSE -1 END * purchaseprice AS purchaseprice, ");
      sumlist.append("CASE delflg WHEN 3 THEN 1 ELSE -1 END * processingexpence AS processingexpence ");
      sumlist.append("FROM shiphistorytbl ");
      sumlist.append("WHERE initdatetime>=(SELECT (substring(max(season),1,4)||'-'||substring(max(season),5,2)||'-01')::date + '1 month'::interval FROM inventorytbl) ");
      sumlist.append("AND initdatetime<=current_date AND individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()," "));
      sumlist.append("AND shiptype IN ('2','5','6','10','11','12') AND delflg IN ('1','2','3','4') ");
      sumlist.append("UNION ALL ");
      sumlist.append("SELECT -1 * amount AS amount, ");
      sumlist.append("-1 * purchaseprice AS purchaseprice, ");
      sumlist.append("-1 * processingexpence AS processingexpence ");
      sumlist.append("FROM shiphistorytbl s,ordertbl o ");
      sumlist.append("WHERE s.initdatetime>=(SELECT (substring(max(season),1,4)||'-'||substring(max(season),5,2)||'-01')::date + '1 month'::interval FROM inventorytbl) ");
      sumlist.append("AND o.updatedatetime>=(SELECT (substring(max(season),1,4)||'-'||substring(max(season),5,2)||'-01')::date + '1 month'::interval FROM inventorytbl) ");
      sumlist.append("AND s.initdatetime<=current_date AND o.updatedatetime<=current_date ");
      sumlist.append("AND s.individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()," "));
      sumlist.append("AND s.shiptype=0 AND o.status='2' AND o.enabledflg='1' AND delflg IN ('1','4') AND s.ordercode=o.ordercode) list");
      
      Statement lStatement = null;
      ResultSet lResultSet = null;
      try {
        lStatement = lConnection.createStatement();
        lResultSet = lStatement.executeQuery(sumlist.toString());
        
        if (lResultSet.next()) {
          amountnow = lResultSet.getString("amount");
          ppnow = lResultSet.getString("purchaseprice");
          penow = lResultSet.getString("processingexpence");
        }
      }catch(Exception e){
        throw new SIDBAccessException();
      }finally{
        SIDBUtil.close(lResultSet, lStatement);
      }
      try{purchaseprice = SIUtil.multi(SIUtil.div(SIUtil.add(pporg, ppnow), SIUtil.add(amountorg, amountnow)), lStock.getAmount());}
      catch(SIFatalException e){purchaseprice="0";}
      try{processingexpence = SIUtil.multi(SIUtil.div(SIUtil.add(peorg, penow), SIUtil.add(amountorg, amountnow)), lStock.getAmount());}
      catch(SIFatalException e){processingexpence="0";}
    } else if (!"5".equals(stockHistory.getType())&&!"11".equals(stockHistory.getType())) {
      StringBuffer pp = new StringBuffer();
      StringBuffer pe = new StringBuffer();
      pp.append("SELECT purchaseprice FROM individualtbl WHERE individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
      pe.append("SELECT processingexpence FROM individualtbl WHERE individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
      purchaseprice = SIUtil.multi(SIDBUtil.getFirstData(lConnection, pp.toString()), lStock.getAmount());
      processingexpence = SIUtil.multi(SIDBUtil.getFirstData(lConnection, pe.toString()), lStock.getAmount());
    }
    
    // 出庫承認
    SIModifyRec lRec1 = new SIModifyRec("shiphistorytbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());
    lRec1.addCondition("shipnumber", stockHistory.getNumber());
    if (!"5".equals(stockHistory.getType())&&!"11".equals(stockHistory.getType())) {
      lRec1.add("purchaseprice", purchaseprice);
      lRec1.add("processingexpence", processingexpence);
    }
    lRec1.add("calcdatetime", lDateTime.getFullDateTime());
    if (lStock.getType().equals("2") || lStock.getType().equals("7") || lStock.getType().equals("9")) lRec1.add("delflg", "4");
    else lRec1.add("delflg", "1");
    
    try {
      lRec1.execute(lConnection);
      
      // 加工・修理・代替品・保証対応の場合には未承認入庫を作成する
      if (lStock.getType().equals("2") || lStock.getType().equals("7") || lStock.getType().equals("9") || lStock.getType().equals("13")) {
        
        String storeNo = stockHistory.getNewStoreNumber(lConnection);
        lDateTime = new SIDateTime();
        String comment = "";
        String branch = "";
        
        SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
        lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
        lRec2.add("individualcode", stockHistory.getIndividualCode());
        lRec2.add("storenumber", storeNo);
        if (lStock.getType().equals("13") && SIUtil.isNotNull(lStock.getCharge())) {
          branch = SIDBUtil.getFirstData(lConnection, "SELECT belongingbranchcode FROM chargetbl WHERE chargecode="+SIDBUtil.SQL2Str(lStock.getCharge()));
        } else {
          branch = lStock.getBranch();
        }
        lRec2.add("storebranch", branch);
        lRec2.add("storecharge", lStock.getCharge());
        lRec2.add("amount", lStock.getAmount());
        lRec2.add("purchaseprice", purchaseprice);
        lRec2.add("processingexpence", processingexpence);
        lRec2.add("storetype", lStock.getType());
        if (lStock.getType().equals("2")) comment = "加工入庫：";
        if (lStock.getType().equals("7")) comment = "修理入庫：";
        if (lStock.getType().equals("9")) comment = "代替品入庫：";
        if (lStock.getType().equals("13")) comment = "保証戻り入庫：";
        lRec2.add("comment", comment + "出庫番号" + stockHistory.getNumber());
        if (lStock.getType().equals("13")) lRec2.add("ordercode", lStock.getOrderCode());
        else lRec2.add("ordercode", stockHistory.getNumber());
        lRec2.add("delflg", "0");
        lRec2.add("initdatetime", lDateTime.getFullDate());
        
        lRec2.execute(lConnection);
      }
      
      // 原価再計算しない
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>rejectShip</b> 未承認出庫データを却下します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void rejectShip(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    String purchaseprice = "0";
    String processingexpence = "0";
    SIStockHistory lStock = new SIStockHistory();
    lStock = stockHistory.getHistoryData(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getNumber(), false);
    
    // 原価現在値取得
    if (!"3".equals(lStock.getType())){
      purchaseprice = SIDBUtil.getFirstData(lConnection, "SELECT purchaseprice FROM individualtbl WHERE  individualcode="+SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
      processingexpence = SIDBUtil.getFirstData(lConnection, "SELECT processingexpence FROM individualtbl WHERE individualcode="+SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
      purchaseprice = SIUtil.multi(purchaseprice, lStock.getAmount());
      processingexpence = SIUtil.multi(processingexpence, lStock.getAmount());
    }
    // 在庫数量プラス
    SISpcType lSpc1 = new SISpcType("amount+" + lStock.getAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", lStock.getBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    // 出庫却下
    SIModifyRec lRec2 = new SIModifyRec("shiphistorytbl");
    lRec2.addCondition("cmdtycode", stockHistory.getCmdtyCode());
    lRec2.addCondition("individualcode", stockHistory.getIndividualCode());
    lRec2.addCondition("shipnumber", stockHistory.getNumber());
    lRec2.add("purchaseprice", purchaseprice);
    lRec2.add("processingexpence", processingexpence);
    lRec2.add("ordercode", "");
    lRec2.add("delflg", "5");
    if(!"18".equals(lStock.getType())) {
      if (SIUtil.isNull(lStock.getComment())) lRec2.add("comment", "（却下されました）");
      else lRec2.add("comment", lStock.getComment() + "（却下されました）");
    }
    
    try {
      lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>moveStock</b> 移動データを作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void moveStock(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    // 移動出庫
    SISpcType lSpc1 = new SISpcType("amount-" + stockHistory.getMoveAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getMoveBranchFrom());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      String shipNo = stockHistory.getNewShipNumber(lConnection);
      String storeNo = stockHistory.getNewStoreNumber(lConnection);
      String branchFrom = SIDBUtil.getFirstData(lConnection, "SELECT branchname FROM branchtbl WHERE branchcode='" + stockHistory.getMoveBranchFrom() + "'");
      String branchTo = SIDBUtil.getFirstData(lConnection, "SELECT branchname FROM branchtbl WHERE branchcode='" + stockHistory.getMoveBranchTo() + "'");
      
      // 出庫履歴
      SIInsertRec lRec3 = new SIInsertRec("shiphistorytbl");
      lRec3.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec3.add("individualcode", stockHistory.getIndividualCode());
      lRec3.add("shipnumber", shipNo);
      lRec3.add("shipbranch", stockHistory.getMoveBranchFrom());
      lRec3.add("shipcharge", stockHistory.getMoveCharge());
      lRec3.add("amount", stockHistory.getMoveAmount());
      lRec3.add("purchaseprice", "0");
      lRec3.add("processingexpence", "0");
      lRec3.add("shiptype", "3");
      lRec3.add("comment", branchTo + "へ出庫");
      lRec3.add("ordercode", "");
      lRec3.add("delflg", "0");
      lRec3.add("initdatetime", lDateTime.getFullDate());
      lRec3.add("calcdatetime", lDateTime.getFullDateTime());
      
      // 入庫履歴
      SIInsertRec lRec4 = new SIInsertRec("storehistorytbl");
      lRec4.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec4.add("individualcode", stockHistory.getIndividualCode());
      lRec4.add("storenumber", storeNo);
      lRec4.add("storebranch", stockHistory.getMoveBranchTo());
      lRec4.add("storecharge", stockHistory.getMoveCharge());
      lRec4.add("amount", stockHistory.getMoveAmount());
      lRec4.add("purchaseprice", "0");
      lRec4.add("processingexpence", "0");
      lRec4.add("storetype", "3");
      lRec4.add("comment", branchFrom + "から入庫");
      lRec4.add("ordercode", shipNo);
      lRec4.add("delflg", "0");
      lRec4.add("initdatetime", lDateTime.getFullDate());
      
      lRec1.execute(lConnection);
      // lRec2.execute(lConnection);
      lRec3.execute(lConnection);
      lRec4.execute(lConnection);
      
    } catch (SIDuplicateKeyException e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>moveStockFull</b> 移動データを複数個作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void moveStockFull(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    // 移動出庫
    SISpcType lSpc1 = new SISpcType("amount-" + stockHistory.getMoveAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getMoveBranchFrom());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      lRec1.execute(lConnection);
    } catch (SIDuplicateKeyException e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
    
    for (int i = 0; i < stockHistory.getMoveBranchToList().length; i++) {
      if (!stockHistory.getMoveAmountList()[i].equals("0")) {
        try {
          String shipNo = stockHistory.getNewShipNumber(lConnection);
          String storeNo = stockHistory.getNewStoreNumber(lConnection);
          String branchFrom = SIDBUtil.getFirstData(lConnection, "SELECT branchname FROM branchtbl WHERE branchcode='" + stockHistory.getMoveBranchFrom() + "'");
          String branchTo = SIDBUtil.getFirstData(lConnection, "SELECT branchname FROM branchtbl WHERE branchcode='" + stockHistory.getMoveBranchToList()[i] + "'");
          
          // 出庫履歴
          SIInsertRec lRec3 = new SIInsertRec("shiphistorytbl");
          lRec3.add("cmdtycode", stockHistory.getCmdtyCode());
          lRec3.add("individualcode", stockHistory.getIndividualCode());
          lRec3.add("shipnumber", shipNo);
          lRec3.add("shipbranch", stockHistory.getMoveBranchFrom());
          lRec3.add("shipcharge", stockHistory.getMoveCharge());
          lRec3.add("amount", stockHistory.getMoveAmountList()[i]);
          lRec3.add("purchaseprice", "0");
          lRec3.add("processingexpence", "0");
          lRec3.add("shiptype", "3");
          lRec3.add("comment", branchTo + "へ出庫");
          lRec3.add("ordercode", "");
          lRec3.add("delflg", "0");
          lRec3.add("initdatetime", lDateTime.getFullDate());
          lRec3.add("calcdatetime", lDateTime.getFullDateTime());
          lDateTime.addSecond(1);
          
          // 入庫履歴
          SIInsertRec lRec4 = new SIInsertRec("storehistorytbl");
          lRec4.add("cmdtycode", stockHistory.getCmdtyCode());
          lRec4.add("individualcode", stockHistory.getIndividualCode());
          lRec4.add("storenumber", storeNo);
          lRec4.add("storebranch", stockHistory.getMoveBranchToList()[i]);
          lRec4.add("storecharge", stockHistory.getMoveCharge());
          lRec4.add("amount", stockHistory.getMoveAmountList()[i]);
          lRec4.add("purchaseprice", "0");
          lRec4.add("processingexpence", "0");
          lRec4.add("storetype", "3");
          lRec4.add("comment", branchFrom + "から入庫");
          lRec4.add("ordercode", shipNo);
          lRec4.add("delflg", "0");
          lRec4.add("initdatetime", lDateTime.getFullDate());
          
          lRec3.execute(lConnection);
          lRec4.execute(lConnection);
        } catch (SIDuplicateKeyException e) {
          e.printStackTrace();
          throw new SIDBAccessException();
        }
      }
    }
  }
  
  /**
   * <b>storeFull</b> 未承認入庫データを複数個作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void storeFull(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    for (int i = 0; i < stockHistory.getStoreBranchList().length; i++) {
      if (!stockHistory.getStoreAmountList()[i].equals("0")) {
        try {
          String storeNo = stockHistory.getNewStoreNumber(lConnection);
          String purchaseprice = SIUtil.multi(stockHistory.getPurchasePrice(), stockHistory.getStoreAmountList()[i]);
          String processingexpence = SIUtil.multi(SIUtil.div(stockHistory.getProcessingExpence(), stockHistory.getNewAmount()), stockHistory.getStoreAmountList()[i]);
          
          // 入庫履歴
          SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
          lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
          lRec2.add("individualcode", stockHistory.getIndividualCode());
          lRec2.add("storenumber", storeNo);
          lRec2.add("storebranch", stockHistory.getStoreBranchList()[i]);
          lRec2.add("storecharge", stockHistory.getNewCharge());
          lRec2.add("amount", stockHistory.getStoreAmountList()[i]);
          lRec2.add("purchaseprice", purchaseprice);
          lRec2.add("processingexpence", processingexpence);
          lRec2.add("storetype", "0");
          lRec2.add("comment", stockHistory.getComment()+" [合計数："+stockHistory.getNewAmount()+"]");
          lRec2.add("delflg", "0");
          lRec2.add("initdatetime", lDateTime.getFullDate());
          
          lRec2.execute(lConnection);
          
        } catch (SIDuplicateKeyException e) {
          e.printStackTrace();
          throw new SIDBAccessException();
        } catch (SIFatalException e) {
          e.printStackTrace();
          throw new SIDBAccessException();
        }
      }
    }
  }
  
  /**
   * <b>createNewStore</b> 新規入庫データ（承認済）を作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void createNewStore(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    createNewStore(lConnection,stockHistory,false);
  }
  public synchronized static void createNewStore(Connection lConnection, UIStockHistory stockHistory,boolean isKeep) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    StringBuffer lSqlBuf = new StringBuffer();
    lSqlBuf.append("SELECT * FROM storestocktbl WHERE cmdtycode=").append(SIDBUtil.SQL2Str(stockHistory.getCmdtyCode(), " "));
    lSqlBuf.append("AND individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode(), " "));
    lSqlBuf.append("AND branchcode=").append(SIDBUtil.SQL2Str(stockHistory.getNewBranch(), " "));
    lSqlBuf.append("FOR UPDATE");
    
    // 在庫数量プラス
    SISpcType lSpc1 = new SISpcType("amount+" + stockHistory.getNewAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getNewBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      String storeNo = stockHistory.getNewStoreNumber(lConnection);
      String purchaseprice = SIUtil.multi(stockHistory.getPurchasePrice(), stockHistory.getNewAmount());
      
      // 入庫履歴
      SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("storenumber", storeNo);
      lRec2.add("storebranch", stockHistory.getNewBranch());
      lRec2.add("storecharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", purchaseprice);
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("storetype", stockHistory.getType());
      if ("1".equals(stockHistory.getType())) {
        lRec2.add("comment", "[" + stockHistory.getPaymentType() + "]" + stockHistory.getComment());
      } else {
        lRec2.add("comment", stockHistory.getComment());
      }
      lRec2.add("delflg", "1");
      lRec2.add("initdatetime", lDateTime.getFullDate());
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      StringBuffer checkStr = new StringBuffer();
      checkStr.append("SELECT s.individualcode ");
      checkStr.append("FROM storestocktbl s,individualtbl i ");
      checkStr.append("WHERE i.individualcode=s.individualcode ");
      checkStr.append("AND i.purchaseprice+i.processingexpence=0 ");
      checkStr.append("AND i.individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()," "));
      checkStr.append("GROUP BY s.individualcode ");
      checkStr.append("HAVING sum(s.amount)=0");
      
      if("1".equals(stockHistory.getType())&&SIDBUtil.hasData(lConnection, checkStr.toString())) {
        String processingexpence = "0";
        try{processingexpence = SIUtil.div(stockHistory.getProcessingExpence(), stockHistory.getNewAmount());}catch(Exception e){processingexpence = "0";}
        SIModifyRec lRec4 = new SIModifyRec("individualtbl");
        lRec4.addCondition("cmdtycode", stockHistory.getCmdtyCode());
        lRec4.addCondition("individualcode", stockHistory.getIndividualCode());
        lRec4.add("purchaseprice", stockHistory.getPurchasePrice());
        lRec4.add("processingexpence", processingexpence);
        lRec4.execute(lConnection);
      }
      
      if(!isKeep){
        SIDBUtil.hasData(lConnection, lSqlBuf.toString());// レコードロック
        lRec1.execute(lConnection);
      }
      lRec2.execute(lConnection);
      
      if (!stockHistory.getProcessingExpence().equals("0")) {// 加工価格が0円でないとき
        String processNo = "";
        String processSql = "SELECT MAX(processnumber) FROM processtbl WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"
            + stockHistory.getIndividualCode() + "'";
        if (SIUtil.isNotNull(SIDBUtil.getFirstData(lConnection, processSql))) processNo = SIUtil.add(SIDBUtil.getFirstData(lConnection, processSql), "1");
        else processNo = "1";
        
        // 加工データ
        SIInsertRec lRec3 = new SIInsertRec("processtbl");
        lRec3.add("cmdtycode", stockHistory.getCmdtyCode());
        lRec3.add("individualcode", stockHistory.getIndividualCode());
        lRec3.add("processnumber", processNo);
        lRec3.add("storenumber", storeNo);
        lRec3.add("processprice", stockHistory.getProcessingExpence());
        lRec3.add("branchcode", "");
        lRec3.add("chargecode", "");
        lRec3.add("makername", "");
        lRec3.add("paymentmethod", "");
        lRec3.add("remarks", "入庫番号" + storeNo + "番、入庫数" + stockHistory.getNewAmount() + "台で加工総額" + stockHistory.getProcessingExpence() + "円。");
        lRec3.add("initdatetime", lDateTime.getFullDate());
        
        lRec3.execute(lConnection);
      }
      
      // 原価再計算
      //SIBGUtil.costCalculationAdd(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), purchaseprice, stockHistory.getProcessingExpence(), stockHistory.getNewAmount(), true);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>createNewStore2</b> 新規入庫データ（未承認）を作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void createNewStore2(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    try {
      String storeNo = stockHistory.getNewStoreNumber(lConnection);
      String purchaseprice = SIUtil.multi(stockHistory.getPurchasePrice(), stockHistory.getNewAmount());
      
      // 入庫履歴
      SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("storenumber", storeNo);
      lRec2.add("storebranch", stockHistory.getNewBranch());
      lRec2.add("storecharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", purchaseprice);
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("storetype", stockHistory.getType());
      lRec2.add("comment", stockHistory.getComment());
      if ("13".equals(stockHistory.getType())){
        lRec2.add("ordercode", stockHistory.getOrderCode());
      }
      lRec2.add("delflg", "0");
      lRec2.add("initdatetime", lDateTime.getFullDate());
      
      lRec2.execute(lConnection);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  public synchronized static String createNewStoreHacchu(Connection lConnection, UIStockHistory stockHistory,String orderCode,String shippmentDate,boolean amountFlg) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    String storeNo = "";
    
    StringBuffer lSqlBuf = new StringBuffer();
    lSqlBuf.append("SELECT * FROM storestocktbl WHERE cmdtycode=").append(SIDBUtil.SQL2Str(stockHistory.getCmdtyCode(), " "));
    lSqlBuf.append("AND individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode(), " "));
    lSqlBuf.append("AND branchcode=").append(SIDBUtil.SQL2Str(stockHistory.getNewBranch(), " "));
    lSqlBuf.append("FOR UPDATE");
    
    // 在庫数量プラス
    SISpcType lSpc1 = new SISpcType("amount+" + stockHistory.getNewAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getNewBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      storeNo = stockHistory.getNewStoreNumber(lConnection);
      
      // 入庫履歴
      SIInsertRec lRec2 = new SIInsertRec("storehistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("storenumber", storeNo);
      lRec2.add("storebranch", stockHistory.getNewBranch());
      lRec2.add("storecharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", stockHistory.getPurchasePrice());
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("storetype", "0");
      lRec2.add("comment", stockHistory.getComment());
      lRec2.add("ordercode", orderCode);
      lRec2.add("delflg", "1");
      lRec2.add("initdatetime", new SIDateType(shippmentDate));
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      StringBuffer checkStr = new StringBuffer();
      checkStr.append("SELECT s.individualcode ");
      checkStr.append("FROM storestocktbl s,individualtbl i ");
      checkStr.append("WHERE i.individualcode=s.individualcode ");
      checkStr.append("AND i.purchaseprice+i.processingexpence=0 ");
      checkStr.append("AND i.individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode()," "));
      checkStr.append("GROUP BY s.individualcode ");
      checkStr.append("HAVING sum(s.amount)=0");
      
      if (amountFlg&&SIDBUtil.hasData(lConnection, checkStr.toString())) {
        String purchaseprice = "0";
        try{purchaseprice = SIUtil.div(stockHistory.getPurchasePrice(), stockHistory.getNewAmount());}catch(Exception e){purchaseprice = "0";}
        String processingexpence = "0";
        try{processingexpence = SIUtil.div(stockHistory.getProcessingExpence(), stockHistory.getNewAmount());}catch(Exception e){processingexpence = "0";}
        SIModifyRec lRec4 = new SIModifyRec("individualtbl");
        lRec4.addCondition("cmdtycode", stockHistory.getCmdtyCode());
        lRec4.addCondition("individualcode", stockHistory.getIndividualCode());
        lRec4.add("purchaseprice", purchaseprice);
        lRec4.add("processingexpence", processingexpence);
        lRec4.execute(lConnection);
      }
      
      if (amountFlg) {//店舗在庫品の場合、在庫加算
        SIDBUtil.hasData(lConnection, lSqlBuf.toString());// レコードロック
        lRec1.execute(lConnection);
      }
      lRec2.execute(lConnection);
      
      if (!stockHistory.getProcessingExpence().equals("0")&&amountFlg) {// 店舗在庫品で加工価格が0円でないとき
        String processNo = "";
        String processSql = "SELECT MAX(processnumber) FROM processtbl WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"
            + stockHistory.getIndividualCode() + "'";
        if (SIUtil.isNotNull(SIDBUtil.getFirstData(lConnection, processSql))) processNo = SIUtil.add(SIDBUtil.getFirstData(lConnection, processSql), "1");
        else processNo = "1";
        
        // 加工データ
        SIInsertRec lRec3 = new SIInsertRec("processtbl");
        lRec3.add("cmdtycode", stockHistory.getCmdtyCode());
        lRec3.add("individualcode", stockHistory.getIndividualCode());
        lRec3.add("processnumber", processNo);
        lRec3.add("storenumber", storeNo);
        lRec3.add("processprice", stockHistory.getProcessingExpence());
        lRec3.add("branchcode", "");
        lRec3.add("chargecode", "");
        lRec3.add("makername", "");
        lRec3.add("paymentmethod", "");
        lRec3.add("remarks", "入庫番号" + storeNo + "番、入庫数" + stockHistory.getNewAmount() + "台で加工総額" + stockHistory.getProcessingExpence() + "円。");
        lRec3.add("initdatetime", lDateTime.getFullDate());
        
        lRec3.execute(lConnection);
      }
      
      //if (amountFlg) {//店舗在庫品の場合、原価再計算
      //  SIBGUtil.costCalculationAdd(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getPurchasePrice(), stockHistory.getProcessingExpence(), stockHistory.getNewAmount(), true);
      //}
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
    return storeNo;
  }
  
  /**
   * <b>createNewShip</b> 新規出庫データ（未承認）を作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void createNewShip(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    
    // 在庫数量マイナス
    SISpcType lSpc1 = new SISpcType("amount-" + stockHistory.getNewAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getNewBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    try {
      String shipNo = stockHistory.getNewShipNumber(lConnection);
      String purchasePrice = "0";
      String processingExpence = "0";
      if ("11".equals(stockHistory.getType()) || "5".equals(stockHistory.getType())) {
        purchasePrice = SIDBUtil.getFirstData(lConnection, "SELECT purchaseprice FROM individualtbl WHERE individualcode="+SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
        processingExpence = SIDBUtil.getFirstData(lConnection, "SELECT processingexpence FROM individualtbl WHERE individualcode="+SIDBUtil.SQL2Str(stockHistory.getIndividualCode()));
      }
      // 出庫履歴（未承認）
      SIInsertRec lRec2 = new SIInsertRec("shiphistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("shipnumber", shipNo);
      lRec2.add("shipbranch", stockHistory.getNewBranch());
      lRec2.add("shipcharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", purchasePrice);
      if ("13".equals(stockHistory.getType())||"16".equals(stockHistory.getType())){
        lRec2.add("ordercode", stockHistory.getOrderCode());
      }
      lRec2.add("processingexpence", processingExpence);
      lRec2.add("shiptype", stockHistory.getType());
      if ("18".equals(stockHistory.getType())) {
        lRec2.add("comment", "[" + stockHistory.getPaymentType() + "]" + stockHistory.getComment());
      } else {
      lRec2.add("comment", stockHistory.getComment());
      }
      lRec2.add("delflg", "0");
      lRec2.add("initdatetime", lDateTime.getFullDate());
      
      lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  public synchronized static String createNewShipHacchu(Connection lConnection, UIStockHistory stockHistory,String orderCode,String shippmentDate) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    String shipNo = "";
    
    try {
      stockHistory.setCmdtyCode(SIDBUtil.getFirstData(lConnection, "SELECT cmdtycode FROM individualtbl WHERE individualcode="+SIDBUtil.SQL2Str(stockHistory.getIndividualCode())));
      shipNo = stockHistory.getNewShipNumber(lConnection);
      
      // 出庫履歴
      SIInsertRec lRec2 = new SIInsertRec("shiphistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("shipnumber", shipNo);
      lRec2.add("ordercode", orderCode);
      lRec2.add("shipbranch", stockHistory.getNewBranch());
      lRec2.add("shipcharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", stockHistory.getPurchasePrice());
      lRec2.add("processingexpence", stockHistory.getProcessingExpence());
      lRec2.add("shiptype", "0");
      lRec2.add("comment", stockHistory.getComment());
      lRec2.add("delflg", "1");
      lRec2.add("initdatetime", new SIDateType(shippmentDate));
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      lRec2.execute(lConnection);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
    return shipNo;
  }
  /**
   * <b>createNewShip2</b> 新規出庫データ（承認済）を作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public synchronized static void createNewShip2(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    String purchaseprice = "0";
    String processingexpence = "0";
    // 原価の現在値を取得
    purchaseprice = SIDBUtil.getFirstData(lConnection, "SELECT purchaseprice FROM individualtbl WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"
        + stockHistory.getIndividualCode() + "'");
    processingexpence = SIDBUtil.getFirstData(lConnection, "SELECT processingexpence FROM individualtbl WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"
        + stockHistory.getIndividualCode() + "'");
    purchaseprice = SIUtil.multi(purchaseprice, stockHistory.getNewAmount());
    processingexpence = SIUtil.multi(processingexpence, stockHistory.getNewAmount());
    
    try {
      // 在庫数量マイナス
      SISpcType lSpc1 = new SISpcType("amount-" + stockHistory.getNewAmount());
      SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
      lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
      lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
      lRec1.addCondition("branchcode", stockHistory.getNewBranch());// 支店コード
      lRec1.add("amount", lSpc1);
      
      String shipNo = stockHistory.getNewShipNumber(lConnection);
      
      // 出庫履歴（承認済）
      SIInsertRec lRec2 = new SIInsertRec("shiphistorytbl");
      lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
      lRec2.add("individualcode", stockHistory.getIndividualCode());
      lRec2.add("shipnumber", shipNo);
      lRec2.add("shipbranch", stockHistory.getNewBranch());
      lRec2.add("shipcharge", stockHistory.getNewCharge());
      lRec2.add("amount", stockHistory.getNewAmount());
      lRec2.add("purchaseprice", purchaseprice);
      lRec2.add("processingexpence", processingexpence);
      lRec2.add("shiptype", stockHistory.getType());
      lRec2.add("comment", stockHistory.getComment());
      lRec2.add("delflg", "1");
      lRec2.add("initdatetime", lDateTime.getFullDate());
      lRec2.add("calcdatetime", lDateTime.getFullDateTime());
      
      lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>assignReserve</b> 割当未済予約データに在庫を割り当てます。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void assignReserve(Connection lConnection, UIStockHistory stockHistory, String fromMail) throws SIDBAccessException {
    
    // 在庫数量マイナス
    SISpcType lSpc1 = new SISpcType("amount-" + stockHistory.getReserveAmount());
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("branchcode", stockHistory.getReserveBranch());// 支店コード
    lRec1.add("amount", lSpc1);
    
    // 予約割当
    SIModifyRec lRec2 = new SIModifyRec("reserveordertbl");
    lRec2.addCondition("reservecode", stockHistory.getReserveCode());// 予約コード
    lRec2.add("reservebranch", stockHistory.getReserveBranch());
    lRec2.add("assignamount", stockHistory.getReserveAmount());
    lRec2.add("reserveflg", "1");
    
    try {
      
      lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      SIBGUtil.sendReserveMail(lConnection, stockHistory.getReserveCode(), fromMail);
      
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>storeCorrection</b> 誤った入庫データを訂正します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void storeCorrection(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    SIStockHistory lStock = new SIStockHistory();
    lStock = stockHistory.getHistoryData(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getCorrectNo(), true);
    String storeNo = stockHistory.getNewStoreNumber(lConnection);
    String correctPurchasePrice = SIUtil.multi(stockHistory.getCorrectPurchasePrice(), stockHistory.getCorrectAmount());
    
    SIModifyRec lRec1 = new SIModifyRec("storestocktbl");
    boolean amountModFlg = false;
    
    // 在庫数量増減
    if (!stockHistory.isNoStock() && !stockHistory.getCorrectAmount().equals(lStock.getAmount())) {
      SISpcType lSpc1 = null;
      if (SICheckUtil.isGreater(stockHistory.getCorrectAmount(), lStock.getAmount())) {
        lSpc1 = new SISpcType("amount+" + SIUtil.sub(stockHistory.getCorrectAmount(), lStock.getAmount()));
      } else {
        lSpc1 = new SISpcType("amount-" + SIUtil.sub(lStock.getAmount(), stockHistory.getCorrectAmount()));
      }
      
      lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
      lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
      lRec1.addCondition("branchcode", lStock.getBranch());// 支店コード
      lRec1.add("amount", lSpc1);
      amountModFlg = true;
    }
    
    // 既存データの訂正
    SIModifyRec lRec2 = new SIModifyRec("storehistorytbl");
    lRec2.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec2.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec2.addCondition("storenumber", stockHistory.getCorrectNo());// 入庫番号
    if (SIUtil.isNull(lStock.getComment())) lRec2.add("comment", "（訂正されました）");
    else lRec2.add("comment", lStock.getComment() + "（訂正されました）");
    lRec2.add("delflg", "2");
    
    // 訂正用データ作成
    SIInsertRec lRec3 = new SIInsertRec("storehistorytbl");
    lRec3.add("cmdtycode", stockHistory.getCmdtyCode());
    lRec3.add("individualcode", stockHistory.getIndividualCode());
    lRec3.add("storenumber", storeNo);
    lRec3.add("storebranch", lStock.getBranch());
    lRec3.add("storecharge", lStock.getCharge());
    lRec3.add("amount", lStock.getAmount());
    lRec3.add("purchaseprice", lStock.getPurchasePrice());
    lRec3.add("processingexpence", lStock.getProcessingExpence());
    lRec3.add("storetype", lStock.getType());
    lRec3.add("ordercode", lStock.getOrderCode());
    lRec3.add("comment", "入庫" + stockHistory.getCorrectNo() + "訂正");
    lRec3.add("delflg", "3");
    lRec3.add("initdatetime", lDateTime.getFullDate());
    lRec3.add("calcdatetime", lDateTime.getFullDateTime());
    
    lDateTime.addSecond(1);// １秒加算
    
    // 訂正済データ作成
    SIInsertRec lRec4 = new SIInsertRec("storehistorytbl");
    lRec4.add("cmdtycode", stockHistory.getCmdtyCode());
    lRec4.add("individualcode", stockHistory.getIndividualCode());
    lRec4.add("storenumber", SIUtil.add(storeNo, "1"));
    lRec4.add("storebranch", lStock.getBranch());
    lRec4.add("storecharge", lStock.getCharge());
    lRec4.add("amount", stockHistory.getCorrectAmount());
    lRec4.add("purchaseprice", correctPurchasePrice);
    lRec4.add("processingexpence", lStock.getProcessingExpence());
    lRec4.add("ordercode", lStock.getOrderCode());
    lRec4.add("storetype", lStock.getType());
    lRec4.add("comment", "訂正済データ");
    lRec4.add("delflg", lStock.getDelFlg());
    lRec4.add("initdatetime", lDateTime.getFullDate());
    lRec4.add("calcdatetime", lDateTime.getFullDateTime());
    
    try {
      
      //String purchase = SIDBUtil.getFirstData(lConnection, "SELECT purchaseprice FROM individualtbl WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"+ stockHistory.getIndividualCode() + "'");
      //String amountBefor = SIDBUtil.getFirstData(lConnection, "SELECT total FROM realstocktotalvw WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"+ stockHistory.getIndividualCode() + "'");
      
      if (amountModFlg) lRec1.execute(lConnection);
      
      //String amountAfter = SIDBUtil.getFirstData(lConnection, "SELECT total FROM realstocktotalvw WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"+ stockHistory.getIndividualCode() + "'");
      
      lRec2.execute(lConnection);
      lRec3.execute(lConnection);
      lRec4.execute(lConnection);
      
      // 原価再計算
      /*
      if (!stockHistory.isNoStock()) {
        String totalP = SIUtil.div(SIUtil.sub(SIUtil.add(SIUtil.multi(purchase, amountBefor), correctPurchasePrice), lStock.getPurchasePrice()), amountAfter);
        
        SIModifyRec lRec5 = new SIModifyRec("individualtbl");
        lRec5.addCondition("cmdtycode", stockHistory.getCmdtyCode());
        lRec5.addCondition("individualcode", stockHistory.getIndividualCode());
        lRec5.add("purchaseprice", totalP);
        lRec5.execute(lConnection);
      }
      */
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>shipCorrection</b> 誤った出庫データを訂正します。
   * 
   * @param lConnection DBへのコネクション
   * @param stockHistory 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void shipCorrection(Connection lConnection, UIStockHistory stockHistory) throws SIDBAccessException {
    shipCorrection(lConnection,stockHistory,false);
  }
  
  public static void shipCorrection(Connection lConnection, UIStockHistory stockHistory,boolean noOrderFlg) throws SIDBAccessException {
    SIDateTime lDateTime = new SIDateTime();
    SIStockHistory lStock = new SIStockHistory();
    lStock = stockHistory.getHistoryData(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode(), stockHistory.getCorrectNo(), false);
    String shipNo = stockHistory.getNewShipNumber(lConnection);
    String correctPurchasePrice = SIUtil.multi(stockHistory.getCorrectPurchasePrice(), lStock.getAmount());
    
    // 既存データの訂正
    SIModifyRec lRec1 = new SIModifyRec("shiphistorytbl");
    lRec1.addCondition("cmdtycode", stockHistory.getCmdtyCode());// 親コード
    lRec1.addCondition("individualcode", stockHistory.getIndividualCode());// 個別コード
    lRec1.addCondition("shipnumber", stockHistory.getCorrectNo());// 出庫番号
    lRec1.add("comment", lStock.getComment() + "（訂正されました）");
    lRec1.add("delflg", "2");
    
    // 訂正用データ作成
    SIInsertRec lRec2 = new SIInsertRec("shiphistorytbl");
    lRec2.add("cmdtycode", stockHistory.getCmdtyCode());
    lRec2.add("individualcode", stockHistory.getIndividualCode());
    lRec2.add("shipnumber", shipNo);
    lRec2.add("shipbranch", lStock.getBranch());
    lRec2.add("shipcharge", lStock.getCharge());
    lRec2.add("amount", lStock.getAmount());
    lRec2.add("purchaseprice", lStock.getPurchasePrice());
    lRec2.add("processingexpence", lStock.getProcessingExpence());
    lRec2.add("shiptype", lStock.getType());
    lRec2.add("ordercode", lStock.getOrderCode());
    lRec2.add("comment", "出庫" + stockHistory.getCorrectNo() + "訂正");
    lRec2.add("delflg", "3");
    lRec2.add("initdatetime", lDateTime.getFullDate());
    lRec2.add("calcdatetime", lDateTime.getFullDateTime());
    
    lDateTime.addSecond(1);// １秒加算
    
    // 訂正済データ作成
    SIInsertRec lRec3 = new SIInsertRec("shiphistorytbl");
    lRec3.add("cmdtycode", stockHistory.getCmdtyCode());
    lRec3.add("individualcode", stockHistory.getIndividualCode());
    lRec3.add("shipnumber", SIUtil.add(shipNo, "1"));
    lRec3.add("shipbranch", lStock.getBranch());
    lRec3.add("shipcharge", lStock.getCharge());
    lRec3.add("amount", lStock.getAmount());
    lRec3.add("purchaseprice", correctPurchasePrice);
    lRec3.add("processingexpence", lStock.getProcessingExpence());
    lRec3.add("shiptype", lStock.getType());
    lRec3.add("ordercode", lStock.getOrderCode());
    lRec3.add("comment", "訂正済データ");
    lRec3.add("delflg", lStock.getDelFlg());
    lRec3.add("initdatetime", lDateTime.getFullDate());
    lRec3.add("calcdatetime", lDateTime.getFullDateTime());
    
    String count = SIDBUtil.getFirstData(lConnection, "SELECT count(*) FROM orderdetailcosttbl WHERE ordercode='" + lStock.getOrderCode() + "' AND cmdtycode='"
        + stockHistory.getCmdtyCode() + "' AND individualcode='" + stockHistory.getIndividualCode() + "'");
    
    String purchasePriceOld = "0";
    try {
      purchasePriceOld = SIUtil.div(lStock.getPurchasePrice(), lStock.getAmount());
    } catch (SIFatalException e) {
      purchasePriceOld = "0";
    }
    
    // 受注訂正データ作成
    SIInsertRec lRec4 = new SIInsertRec("orderdetailcosttbl");
    lRec4.add("ordercode", lStock.getOrderCode());
    lRec4.add("cmdtycode", stockHistory.getCmdtyCode());
    lRec4.add("individualcode", stockHistory.getIndividualCode());
    lRec4.add("correctcount", SIUtil.add(count, "1"));
    lRec4.add("purchasepriceold", purchasePriceOld);
    lRec4.add("purchasepricenew", stockHistory.getCorrectPurchasePrice());
    lRec4.add("initdatetime", lDateTime.getFullDateTime());
    
    try {
      
      lRec1.execute(lConnection);
      lRec2.execute(lConnection);
      lRec3.execute(lConnection);
      if (SIUtil.isNotNull(lStock.getOrderCode()) && !lStock.getOrderCode().equals("0") && !noOrderFlg) {// 受注番号:0は棚卸差異登録用なので除外
        lRec4.execute(lConnection);
      }
      // 原価再計算
      /*
      if (!stockHistory.isNoStock()) {
        String purchase = SIDBUtil.getFirstData(lConnection, "SELECT purchaseprice FROM individualtbl WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"
            + stockHistory.getIndividualCode() + "'");
        String amountAll = SIDBUtil.getFirstData(lConnection, "SELECT total FROM realstocktotalvw WHERE cmdtycode='" + stockHistory.getCmdtyCode() + "' AND individualcode='"
            + stockHistory.getIndividualCode() + "'");
        String totalP = "0";
        if (!"0".equals(amountAll)) totalP = SIUtil.div(SIUtil.sub(SIUtil.add(SIUtil.multi(purchase, amountAll), lStock.getPurchasePrice()), correctPurchasePrice), amountAll);
        SIModifyRec lRec5 = new SIModifyRec("individualtbl");
        lRec5.addCondition("cmdtycode", stockHistory.getCmdtyCode());
        lRec5.addCondition("individualcode", stockHistory.getIndividualCode());
        lRec5.add("purchaseprice", totalP);
        lRec5.execute(lConnection);
      }
      */
    } catch (Exception e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
  }
  
  /**
   * <b>sendShipmentMail</b> 出荷メールを送信します。
   * 
   * @param lRequest
   * @param lConnection DBへのコネクション
   * @param lListCond 対象のデータレコード
   * @return なし
   * @throws SIDBAccessException
   */
  private boolean sendShipmentMail(HttpServletRequest lRequest, Connection lConnection, String lReserveCode) throws SIDBAccessException {
    boolean lResult = true;
    boolean lMailResult = true;
    SIReserveOrder lReserveOrder = new SIReserveOrder();
    SIModifyRec lRec = new SIModifyRec();
    String lNow = (new SIDateTime()).getFullDateTime();
    SISendMail lSendMail = new SISendMail();
    SIMailTemp lMailTemp = new SIMailTemp("0", SIConfig.SIMAIL_TEMPLATE_RESERVE_ARRIVE);
    
    try {
      lMailTemp.reset(lConnection);
    } catch (SIDBAccessException e1) {
      lResult = false;
      e1.printStackTrace();
    }
    Collection lMailList = new ArrayList();
    
    try {
      if (SIUtil.isNotNull(lReserveCode)) {
        log.debug("sendShipmentMail:lReserveCode=" + lReserveCode);
        lReserveOrder = new SIReserveOrder(lReserveCode);
        if (lReserveOrder.reset(lConnection) && (lReserveOrder.getReserveFlg().equals("0") || lReserveOrder.getReserveFlg().equals("1"))) {
          lRec = new SIModifyRec("ReserveOrderTbl");
          lRec.addCondition("ReserveCode", lReserveCode);
          lRec.add("ShipMailDateTime", lNow);
          lRec.execute(lConnection);
          
          lMailList.add(lReserveOrder.getCurrentEmails());
          
          lSendMail = new SISendMail(lReserveOrder.getCurrentEmails() , lMailTemp);
          
          lSendMail.appendContent1("\n予約日時:" + lReserveOrder.getReserveDateTime());
          lSendMail.appendContent1("\n予約番号:" + lReserveOrder.getReserveCode());
          lSendMail.appendContent1("\n\nご予約商品");
          lSendMail.appendContent1("\n===============");
          lSendMail.appendContent1("\n商品コード:" + lReserveOrder.getIndividualCode());
          lSendMail.appendContent1("\n商品名:" + lReserveOrder.getCmdtyName());
          lSendMail.appendContent1("\n予約数：" + lReserveOrder.getAmount());
          lSendMail.appendContent1("\n==============\n");
          try {
            lMailResult = lSendMail.execute();
          } catch (SIFatalException e) {
            lMailResult = false;
            e.printStackTrace();
          }
          if (lMailResult) {
            try {
              lConnection.commit();
            } catch (SQLException e2) {}
          } else {
            try {
              lConnection.rollback();
            } catch (SQLException e2) {}
          }
          lResult = lMailResult && lMailResult;
        } else {
          log.warn("not find lReserveCode=" + lReserveCode);
          lResult = false;
        }
      }
    } catch (SIDuplicateKeyException e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    }
    return lResult;
  }
  
  /**
   * <b>sendApproveMail</b> 承認メールを送信します。
   * 
   * @param lRequest
   * @param lConnection DBへのコネクション
   * @param lListCond 対象のデータレコード
   * @return なし
   * @throws SIDBAccessException
   */
  private int sendApproveMail(HttpServletRequest lRequest, Connection lConnection, UIStockHistory stockHistory, boolean storeFlg, SILogin manLogin) throws SIDBAccessException {
    return sendMail(lRequest, lConnection, stockHistory, storeFlg, true, manLogin);
  }
  
  /**
   * <b>sendRejectMail</b> 却下メールを送信します。
   * 
   * @param lRequest
   * @param lConnection DBへのコネクション
   * @param lListCond 対象のデータレコード
   * @return なし
   * @throws SIDBAccessException
   */
  private int sendRejectMail(HttpServletRequest lRequest, Connection lConnection, UIStockHistory stockHistory, boolean storeFlg, SILogin manLogin) throws SIDBAccessException {
    return sendMail(lRequest, lConnection, stockHistory, storeFlg, false, manLogin);
  }
  
  /**
   * <b>sendMail</b> メールを送信します。
   * 
   * @param lRequest
   * @param lConnection DBへのコネクション
   * @param lListCond 対象のデータレコード
   * @return なし
   * @throws SIDBAccessException
   */
  private int sendMail(HttpServletRequest lRequest, Connection lConnection, UIStockHistory stockHistory, boolean storeFlg, boolean appFlg, SILogin manLogin)
      throws SIDBAccessException {
    int lResult = 1;
    int lMailResult = 1;
    SISendMail lSendMail = new SISendMail();
    SIMailTemp lMailTemp = new SIMailTemp();
    
    Statement lStatement = null;
    ResultSet lResultSet = null;
    
    if (appFlg) lMailTemp = new SIMailTemp("0", SIConfig.SIMAIL_TEMPLATE_APPROVAL);
    else lMailTemp = new SIMailTemp("0", SIConfig.SIMAIL_TEMPLATE_REJECTION);
    
    String branchMail = "";
    String chargeName = "";
    StringBuffer branchBuf = new StringBuffer();
    StringBuffer conditionBuf = new StringBuffer();
    
    try {
      lMailTemp.reset(lConnection);
    } catch (SIDBAccessException e1) {
      lResult = 2;
      e1.printStackTrace();
    }
    
    if (storeFlg) {
      branchBuf.append("SELECT b.email,c.chargename FROM storehistorytbl AS a LEFT JOIN chargetbl AS c ON a.storecharge = c.chargecode ,branchtbl AS b ");
      branchBuf.append("WHERE a.storebranch=b.branchcode AND b.publicflg=1 AND ");
      conditionBuf.append("a.individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode(), " "));
      conditionBuf.append("AND a.cmdtycode=").append(SIDBUtil.SQL2Str(stockHistory.getCmdtyCode(), " AND a.storenumber=")).append(SIDBUtil.SQL2Str(stockHistory.getNumber(), " "));
    } else {
      branchBuf.append("SELECT b.email,c.chargename FROM shiphistorytbl a LEFT JOIN chargetbl AS c ON a.shipcharge = c.chargecode ,branchtbl AS b ");
      branchBuf.append("WHERE a.shipbranch=b.branchcode AND b.publicflg=1 AND ");
      conditionBuf.append("a.individualcode=").append(SIDBUtil.SQL2Str(stockHistory.getIndividualCode(), " "));
      conditionBuf.append("AND a.cmdtycode=").append(SIDBUtil.SQL2Str(stockHistory.getCmdtyCode(), " AND a.shipnumber=")).append(SIDBUtil.SQL2Str(stockHistory.getNumber(), " "));
    }
    branchBuf.append(conditionBuf);
    
    try {
      lStatement = lConnection.createStatement();
      lResultSet = lStatement.executeQuery(branchBuf.toString());
      if (lResultSet.next()) {
        branchMail = lResultSet.getString(1);
        chargeName = lResultSet.getString(2);
      }
      
      if (SIUtil.isNotNull(branchMail)) {
        
        lSendMail = new SISendMail(new String[] { branchMail }, lMailTemp);
        
        lSendMail.appendContent1("\n担当者:" + chargeName);
        lSendMail.appendContent1("\n決裁者:" + manLogin.getUserName());
        
        lSendMail.appendContent1("\n\n在庫コード:" + stockHistory.getIndividualCode());
        lSendMail.appendContent1("\n商品名:" + SIBGUtil.getCmdtyFullName(lConnection, stockHistory.getCmdtyCode(), stockHistory.getIndividualCode()));
        if (storeFlg) {
          lSendMail.appendContent1("\n入庫番号:" + stockHistory.getNumber());
          lSendMail.appendContent1("\n入庫区分:"
              + SIFlagUtil.getFlagName(SIFlagConf.SIFLAG_STORE_TYPE_FLG_INX, SIDBUtil.getFirstData(lConnection, "SELECT a.storetype FROM storehistorytbl a WHERE "
                  + conditionBuf.toString())));
        } else {
          lSendMail.appendContent1("\n出庫番号:" + stockHistory.getNumber());
          lSendMail.appendContent1("\n出庫区分:"
              + SIFlagUtil.getFlagName(SIFlagConf.SIFLAG_SHIP_TYPE_FLG_INX, SIDBUtil.getFirstData(lConnection, "SELECT a.shiptype FROM shiphistorytbl a WHERE "
                  + conditionBuf.toString())));
        }
        
        lSendMail.appendContent1("\n");
        try {
          if(lSendMail.execute()) lMailResult = 1;
          else lMailResult = 2;
        } catch (SIFatalException e) {
          lMailResult = 2;
          e.printStackTrace();
        }
        /*
        if (lMailResult == 1) {
          try {lConnection.commit();} catch (SQLException e2) {}
        } else {
          try {lConnection.rollback();} catch (SQLException e2) {}
        }
        */
        lResult = lMailResult;
      } else {
        lResult = 3;//メールアドレスなしの支店 or 公開フラグなしの支店
      }
    } catch (SIDBAccessException e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    } catch (SQLException e) {
      e.printStackTrace();
      throw new SIDBAccessException();
    } finally {
      SIDBUtil.close(lStatement, lResultSet);
    }
    return lResult;
  }
  
  /**
   * <b>produceCSVFile</b> CSVファイルを作成します。
   * 
   * @param response クライアントまでのresponse
   * @param lConnection DBへのコネクション
   * @param lListCond CSVファイルに出力するデータセット
   * @return なし
   * @throws なし
   */
  private void produceCSVFile(HttpServletResponse response, Connection lConnection, UIStockDecide lListCond) {
    // CSVファイル名の作成
    String lCsvFileName = SICSVConf.getCsvFileName(SICSVConf.SICSV_UNAPPROVAL_DATA_LIST_INX);
    SICSVWrite lCsv = new SICSVWrite(lCsvFileName);
    
    // SQL文の作成
    StringBuffer lSqlBuf = new StringBuffer();
    // 基本のSQL
    if (lListCond.isStore()) {
      lSqlBuf.append("SELECT s.cmdtycode,s.individualcode,c.cmdtyname,s.initdatetime,br.branchname,ch.chargename,s.amount ");
      lSqlBuf.append(",CASE WHEN s.amount<=1 THEN s.purchaseprice ELSE trunc(s.purchaseprice/s.amount) END AS purchaseprice,s.processingexpence ");
      lSqlBuf.append(",s.storebranch AS branchcode,s.storetype AS type,s.comment,s.storenumber AS number ");
      lSqlBuf.append("FROM storehistorytbl s,branchtbl br,chargetbl ch,cmdtymtbl c ");
      lSqlBuf.append("WHERE s.cmdtycode=c.cmdtycode AND s.storebranch=br.branchcode AND s.storecharge=ch.chargecode ");
      lSqlBuf.append("AND s.delflg=0 AND s.storetype IN ('3','11','12','13') ").append(lListCond.getConditionSQL());
      lSqlBuf.append("ORDER BY s.individualcode,s.storenumber DESC");
    } else {
      lSqlBuf.append("SELECT s.cmdtycode,s.individualcode,c.cmdtyname,s.initdatetime,br.branchname,ch.chargename,s.amount ");
      lSqlBuf.append(",CASE WHEN s.amount<=1 THEN s.purchaseprice ELSE trunc(s.purchaseprice/s.amount) END AS purchaseprice,s.processingexpence ");
      lSqlBuf.append(",s.shipbranch AS branchcode,s.shiptype AS type,s.comment,s.shipnumber AS number ");
      lSqlBuf.append("FROM shiphistorytbl s,branchtbl br,chargetbl ch,cmdtymtbl c ");
      lSqlBuf.append("WHERE s.cmdtycode=c.cmdtycode AND s.shipbranch=br.branchcode AND s.shipcharge=ch.chargecode ");
      lSqlBuf.append("AND s.delflg=0 AND s.shiptype IN ('1','3','8','11','12','13','14','15','16','18') ").append(lListCond.getConditionSQL());
      lSqlBuf.append("ORDER BY s.individualcode,s.shipnumber DESC");
    }
    
    // SQL文の設定
    lCsv.setSqlStatement(lSqlBuf.toString());
    // タイトルの設定
    lCsv.setCsvTitleAndField(SICSVConf.getTitleAndFieldName(SICSVConf.SICSV_UNAPPROVAL_DATA_LIST_INX));
    if (SIDBMultiConf.SIDB_CURRENT_INX == SIDBMultiConf.SIDB_POSTGRESQL_INX) {} else {
      lCsv.setFieldType(SICSVConf.getFieldType(SICSVConf.SICSV_UNAPPROVAL_DATA_LIST_INX));
    }
    // CSVファイルの出力
    lCsv.execute(lConnection, response);
  }
  
  public void destroy() {}
}
