<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.style24.batch.biz.dao.TsbDeliveryDao">
	
	<!-- 총알배송 권역정보 등록  -->
	<insert id="mergeDailyDeliveryZone" parameterType="Delivery" >
		/*TsbDelivery.mergeDailyDeliveryZone*/
		
			INSERT INTO TB_DAILY_DELIVERY_ZONE
			(
				  ZIP_NO
				, PND_BRAN
				, PND_BRAN_NM
				, CITY_DO
				, GU_GUN
				, DONG_YUP_MEUN
				, DELIVERYCLASSCD
				, ISUSE
                , DATELASTUPDATE
			)
			VALUES
			(
			 	  #{zipNo}
				, #{pndBran}
				, #{pndBranNm}
				, #{cityDo}
				, #{guGun}
				, #{dongYupMeun}
				, #{deliveryclasscd}
				, #{isuse}
                , NOW()
			)
			ON 
			DUPLICATE KEY
			UPDATE
			  PND_BRAN	            = #{pndBran}
			, PND_BRAN_NM	        = #{pndBranNm}
			, CITY_DO	            = #{cityDo}
			, GU_GUN	            = #{guGun}
			, DONG_YUP_MEUN	        = #{dongYupMeun}
			, DELIVERYCLASSCD	    = #{deliveryclasscd}
			, ISUSE	                = #{isuse}
            , DATELASTUPDATE        = NOW()
	</insert>
	
	<!-- 총알배송 권역정보 삭제  -->
	<delete id="deleteDailyDeliveryZone" parameterType="Delivery" >
		DELETE FROM TB_DAILY_DELIVERY_ZONE 
	</delete>	
	
	<!-- 회수예외 등록 마스터   -->
	<insert id="insertTbOrderRecallException" parameterType="Delivery" >
		/*TsbDelivery.insertTbOrderRecallException*/
		INSERT INTO TB_ORDER_RECALL_EXCEPTION 
		(
			  RECALL_EXCEPTION_NO
			, DELIVERY_ORDER_NO
			, ORDER_NO
			, CUSTOMER_NAME
			, STATUS_CD
			, LOGISTICS_NAME
			, INVOICE_NO
			, RECALL_STAT
			, WMS_SEND_YN
			, CHARGE_TYPE
			, CHARGE_AMOUNT
			, USER_ID_CREATED
			, USER_NAME_CREATED
			, DATE_CREATED
			, USER_ID_MODIFIED
			, USER_NAME_MODIFIED
			, DATE_LAST_MODIFIED
			, REG_NO
			, REG_DT
			, COD_FEE
			, PAY_GB
			, ORDER_EXCEPTION_NO
		)
		VALUES
		(
			  #{recallexceptionno}
			, #{deliveryorderno}
			, #{orderno}
			, #{customername}
			, #{statuscd}
			, #{logisticsname}
			, #{invoiceno}
			, 'P'
			, 'N'
			, #{chargetype}
			, #{chargeamount}
			, #{useridcreated}
			, #{usernamecreated}
			, #{datecreated}
			, #{useridmodified}
			, #{usernamemodified}
			, #{datelastmodified}
			, #{regNo}
			, NOW()
			, #{codFee}
			, #{payGb}
			, #{orderexceptionno}
		)
		ON DUPLICATE KEY UPDATE INVOICE_NO = #{invoiceno}, LOGISTICS_NAME = #{logisticsname}, CHARGE_TYPE = #{chargetype}, CHARGE_AMOUNT = #{chargeamount}
			
	</insert>

	<!-- 회수예외 등록 디테일   -->
	<insert id="insertTbOrderRecallExceptionItem" parameterType="Delivery" >
		/*TsbDelivery.insertTbOrderRecallExceptionItem*/
		INSERT INTO tb_order_recall_exception_item 
		(
			  RECALL_EXCEPTION_ITEM_NO
			, RECALL_EXCEPTION_NO
			, DELIVERY_ORDER_ITEM_NO
			, ORDER_DTL_NO
			, PRODUCT_NO
			, PRODUCT_CODE
			, PRODUCT_NAME
			, SKU_CODE
			, SKU_VALUE
			, EXCEPTION_QTY
			, REASON_CD
			, QTY
			, REASON_CODE
			, REG_NO
			, REG_DT
		)
		VALUES
		(
			  #{recallexceptionitemno}
			, #{recallexceptionno}
			, #{deliveryorderitemno}
			, CASE WHEN #{orderdtlno} IS NULL THEN (SELECT D.ORD_DTL_NO FROM TB_ORDER_DETAIL_ITEM D WHERE D.ORD_NO = #{orderno} AND D.OPT_CD = #{skucode} ) ELSE #{orderdtlno} END
			, #{productno}
			, #{productcode}
			, #{productname}
			, #{skucode}
			, #{skuvalue}
			, #{exceptionqty}
			, #{reasoncd}
			, #{qty}
			, #{reasoncode}
			, #{regNo}
			, NOW()
		)
		ON DUPLICATE KEY UPDATE REASON_CD = #{reasoncd}, REASON_CODE = #{reasoncode}, EXCEPTION_QTY = #{exceptionqty}
	</insert>
	
	<!-- 회수예외 등록 메모   -->
	<insert id="insertTbOrderRecallExceptionMemo" parameterType="Delivery" >
		/*TsbDelivery.insertTbOrderRecallExceptionMemo*/
		INSERT INTO TB_ORDER_RECALL_EXCEPTION_MEMO
		(
			  RECALL_EXCEPTION_MEMO_NO
			, RECALL_EXCEPTION_NO
			, MEMO_TYPE
			, ADMIN_MEMO
			, USER_ID_CREATED
			, USER_NAME_CREATED
			, DATE_CREATED
			, REG_NO
			, REG_DT
		)
		VALUES
		(
			  #{recallexceptionmemono}
			, #{recallexceptionno}
			, #{memotype}
			, #{adminmemo}
			, #{useridcreated}
			, #{usernamecreated}
			, #{datecreated}
			, #{regNo}
			, NOW()
		)
		ON DUPLICATE KEY UPDATE ADMIN_MEMO = #{adminmemo}
	</insert>	

	<!-- 회수예외처리결과 조회 -->	
	<select id="getWithdrawExcRsltList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getWithdrawExcRsltList*/
		SELECT RECALL_EXCEPTION_NO AS RECALLEXCEPTIONNO
			 , CS_ADD_FEE
			 , CS_MEMO AS CSMENO
		  FROM TB_ORDER_RECALL_EXCEPTION
		 WHERE RECALL_STAT = 'S'
		   AND WMS_SEND_YN = 'N'
	</select>
	
	<!-- 회수예외 등록 메모   -->
	<update id="updateTbOrderRecallException" parameterType="Delivery" >
		/*TsbDelivery.updateTbOrderRecallException*/
		UPDATE TB_ORDER_RECALL_EXCEPTION SET
			  WMS_SEND_YN = 'Y'
			, WMS_SEND_DT = NOW()
		 WHERE RECALL_STAT ='S'
		   AND WMS_SEND_YN = 'N'
		   AND RECALL_EXCEPTION_NO = #{recallexceptionno}
	</update>
	
	
	<!-- 출고예외 등록 마스터   -->
	<insert id="insertTbOrderDeliveryException" parameterType="Delivery" keyProperty="deliveryExceptionSq" >
		/*TsbDelivery.insertTbOrderDeliveryException*/
		INSERT INTO TB_ORDER_DELIVERY_EXCEPTION
		(
			  DELIVERY_EXCEPTION_SQ
			, IF_DELIVERY_EXCEPTION_NO
			, IF_DELIVERY_ORDER_NO
			, ORD_NO
			, DELIVERY_TYPE_CD
			, IF_STATUS_CD
			, PRODUCT_SUMMARY
			, ADMIN_MEMO
			, USER_ID_CREATED
			, USER_NAME_CREATED
			, DATE_CREATED
			, COMPLTED_YN
			, REG_NO
			, REG_DT
			, UPD_NO
			, UPD_DT
		)
		VALUES
		(
			  #{deliveryExceptionSq}
			, #{deliveryexceptionno}
			, #{deliveryorderno}
			, #{orderno}
			, 'WMS'
			, #{statuscd}
			, ''
			, #{adminmemo}
			, #{useridcreated}
			, #{usernamecreated}
			, #{datecreated} 
			, 'N'
			, #{regNo}
			, NOW()
			, #{regNo}
			, NOW()
		)ON DUPLICATE KEY UPDATE ADMIN_MEMO = #{adminmemo}
		
	</insert>
	
	<!-- 출고예외 등록 디테일   -->
	<insert id="insertTbOrderDeliveryExceptionItem" parameterType="Delivery" keyProperty="deliveryExceptionItemSq">
		/*TsbDelivery.insertTbOrderDeliveryExceptionItem*/
			INSERT INTO TB_ORDER_DELIVERY_EXCEPTION_ITEM
			(
				  DELIVERY_EXCEPTION_ITEM_SQ
				, DELIVERY_EXCEPTION_SQ
				, IF_DELIVERY_EXCEPTION_ITEM_NO
				, IF_DELIVERY_EXCEPTION_NO
				, EXCEPTION_QTY
				, REASON_CD
				, ORD_NO
				, ORD_DTL_NO
				, GIFT_YN
				, PRODUCT_NO
				, PRODUCT_CODE
				, SKU_CODE
				, REG_NO
				, REG_DT
				, UPD_NO
				, UPD_DT
			)
			VALUES
			(
				  #{deliveryExceptionItemSq} 
				, (SELECT DELIVERY_EXCEPTION_SQ FROM TB_ORDER_DELIVERY_EXCEPTION WHERE  IF_DELIVERY_EXCEPTION_NO = #{deliveryexceptionno} )
				, #{deliveryexceptionitemno} 
				, #{deliveryexceptionno} 
				, #{exceptionqty} 
				, #{reasoncd}
				, #{orderno}
				, CASE WHEN #{orderdtlno} IS NULL THEN (SELECT D.ORD_DTL_NO FROM TB_ORDER_DETAIL_ITEM D WHERE D.ORD_NO = #{orderno} AND D.OPT_CD = #{skucode} ) ELSE #{orderdtlno} END 
				, #{giftyn}
				, #{productno}
				, #{productcode}
				, #{skucode}
				, #{regNo}
				, NOW()
				, #{regNo}
				, NOW()			
			)ON DUPLICATE KEY UPDATE REASON_CD = #{reasoncd}
	</insert>	
	
	<!-- 주문상세상태 변경   -->
	<update id="updateTbOrderDtlStat" parameterType="Delivery" >
		/*TsbDelivery.updateTbOrderDtlStat*/
		UPDATE tb_order_detail SET
			  ORD_DTL_STAT = #{ordDtlStat} 
			<if test='invoiceSendYn != null and invoiceSendYn != ""'>
			, INVOICE_SEND_YN = #{invoiceSendYn} 
			, DELV_STDT       = NOW()
			</if>
			, UPD_NO       = #{updNo}
			, UPD_DT       = NOW()
		WHERE ORD_DTL_NO = #{orderdtlno}
		  AND ORD_NO     = #{orderno}
		  AND ORD_DTL_STAT IN ('G013_30','G013_35','G013_40')
	</update>
	
	<!-- 주문정보 조회 -->	
	<select id="getOrderInfoList" resultType="Delivery">
		/*TsbDelivery.getOrderInfoList*/
		SELECT 
			  B.ORD_NO
			, B.ORD_DTL_NO
			, C.ITEM_CD 
			, C.OPT_CD 
			, C.OPT_CD1 
			, C.OPT_CD2 
			, D.ORD_CHG_SQ 
			, D.CHG_ORD_DTL_NO
			, B.ORD_EXCH_GB     -- 주문교환구분(O:주문,E:교환)
			, B.SELL_STORE_CD
			, E.CHG_GB          -- 변경구분 
			, E.WD_GB           -- 회수구분 (W:회수요청, D:직접배송)
			, A.CUST_NO 
			, E.WD_BF_SEND_YN
		  FROM TB_ORDER A
		  JOIN TB_ORDER_DETAIL B        ON A.ORD_NO     = B.ORD_NO
		  JOIN TB_ORDER_DETAIL_ITEM C   ON B.ORD_NO     = C.ORD_NO AND B.ORD_DTL_NO = C.ORD_DTL_NO 
		  JOIN TB_ORDER_CHANGE_DETAIL D ON B.ORD_DTL_NO = D.ORD_DTL_NO 
		  JOIN TB_ORDER_CHANGE        E ON D.ORD_CHG_SQ = E.ORD_CHG_SQ 
		 WHERE A.ORD_NO       = #{orderno}
		   AND B.ORD_DTL_NO   = #{ordDtlNo}
		   AND C.OPT_CD       = #{skucode}
		   AND C.PRODUCT_NO   = #{productno}
		   AND C.PRODUCT_CODE = #{productcode}
		   AND E.ORD_CHG_SQ   = #{ordChgSq} 
		   AND D.DEL_YN       = 'N'
		   AND D.CHG_STAT IN ('G685_30','G685_31','G685_33','G685_40') -- 회수요청 상품검수중
	</select>

	<!-- 주문정보 조회 -->	
	<select id="getOrderInfoList2" resultType="Delivery">
		/*TsbDelivery.getOrderInfoList2*/
		SELECT 
			  B.ORD_NO
			, B.ORD_DTL_NO
			, D.ORD_CHG_SQ 
			, D.CHG_ORD_DTL_NO
			, B.ORD_EXCH_GB     -- 주문교환구분(O:주문,E:교환)
			, B.SELL_STORE_CD
			, E.CHG_GB          -- 변경구분 
			, E.WD_GB           -- 회수구분 (W:회수요청, D:직접배송)
			, A.CUST_NO 
			, E.WD_BF_SEND_YN
		  FROM TB_ORDER A
		  JOIN TB_ORDER_DETAIL B        ON A.ORD_NO     = B.ORD_NO
		  JOIN TB_ORDER_CHANGE_DETAIL D ON B.ORD_DTL_NO = D.ORD_DTL_NO 
		  JOIN TB_ORDER_CHANGE        E ON D.ORD_CHG_SQ = E.ORD_CHG_SQ 
		 WHERE A.ORD_NO       = #{orderno}
		   AND B.ORD_DTL_NO   = #{ordDtlNo}
		   AND E.ORD_CHG_SQ   = #{ordChgSq} 
		   AND D.DEL_YN       = 'N'
		   AND D.CHG_STAT IN ('G685_30','G685_31','G685_33','G685_40') -- 회수요청 상품검수중
	</select>
	
	<!-- 회수결과 등록  -->
	<update id="insertTbWithdraw" parameterType="Delivery" >
		/*TsbDelivery.insertTbWithdraw*/
		INSERT INTO  TB_WITHDRAW
		(
			  WD_INVOICE_NO		
			, ORD_CHG_SQ		
			, SENDER_NM			
			, SENDER_PHNNO		
			, SENDER_TELNO		
			, SENDER_POST_NO	
			, SENDER_BASE_ADDR	
			, SENDER_DTL_ADDR	
			, SHIP_COMP_CD		
			, WD_REQ_REASON		
			, ENCLOSE_FEE		
			, COD_FEE
			, WD_MEMO			
			, ARRIVAL_DT		
			, CS_MEMO			
			, CS_OB_YN			
			, SMS_SEND_YN		
			, REG_NO			
			, REG_DT			
			, UPD_NO			
			, UPD_DT			
		)
		SELECT
		      OC.WD_INVOICE_NO
		    , OC.ORD_CHG_SQ 
		    , OC.CHGER_NM
		    , OC.CHGER_PHNNO
			, OC.CHGER_TELNO
			, OC.CHGER_ZIPCODE 
			, OC.CHGER_BASE_ADDR
			, OC.CHGER_DTL_ADDR
		    , (SELECT MAX(C.SHIP_COMP_CD) FROM TB_SHIP_COMPANY C WHERE C.WMS_SHIP_COMP_CD = #{logisticscode} )	-- 택배사 코드  
		    , OC.CHG_REASON			-- 회수요청사유
		    , IFNULL(#{enclosefee},0)  -- 동봉비 
		    , IFNULL(#{codFee},0)
		    , #{wmsmemo}            -- 물류메모 
		    , IFNULL(#{datecompleted}, NOW())  -- 도착일시
		    , #{csmemo}                        -- C/S메모 
		    , CASE WHEN #{csmemo} IS NULL THEN 'N' ELSE 'Y' END  -- C/S 아웃바운드여부 
			, 'N'                   -- SMS 발송여부 
		    , #{regNo}              -- 등록자NO 
		    , NOW()                 -- 등록일시
		    , #{regNo}              -- 수정자NO
		    , NOW()                 -- 수정일시 
		FROM TB_ORDER_CHANGE OC
		WHERE OC.ORD_CHG_SQ = #{ordChgSq}
		  AND NOT EXISTS (
				SELECT 1
				  FROM TB_WITHDRAW A
				 WHERE A.WD_INVOICE_NO = OC.WD_INVOICE_NO
				   AND A.ORD_CHG_SQ    = OC.ORD_CHG_SQ 
			)
	</update>
   
	<!-- 회수상세결과 등록   -->
	<update id="insertTbWithdrawDetail" parameterType="Delivery" >
		/*TsbDelivery.insertTbWithdrawDetail*/
		INSERT INTO TB_WITHDRAW_DETAIL 
		(
			  WD_INVOICE_NO	
			, ORD_CHG_SQ	
			, GOODS_CD		
			, OPT_CD1		
			, OPT_CD2		
			, ORD_DTL_NO	
			, WD_QTY		
			, RTN_LOC_CD	
			, SELL_STORE_CD	
			, REG_NO		
			, REG_DT		
			, UPD_NO		
			, UPD_DT		
		)
		VALUES
		(
			  #{recallinvoiceno} 	
			, #{ordChgSq}	
			, #{itemCd}		
			, #{optCd1} 		
			, #{optCd2} 		
			, #{ordDtlNo}	
			, #{recallqty}		
			, #{rtnLocCd}	
			, #{sellStoreCd} 	
			, #{regNo}		
			, NOW()	
			, #{regNo}		
			, NOW()	
		)
	
	</update>
	   
	<!-- 주문변경 회수완료    -->
	<update id="updateTbOrderChange" parameterType="Delivery" >
		/*TsbDelivery.updateTbOrderChange*/
		UPDATE TB_ORDER_CHANGE SET
			  WD_INVOICE_NO      = #{recallinvoiceno}
			, WD_INVOICE_SEND_YN = #{wdInvoiceSendYn}
			, SHIP_COMP_CD       = (SELECT MAX(C.SHIP_COMP_CD) FROM TB_SHIP_COMPANY C WHERE C.WMS_SHIP_COMP_CD = #{logisticscode} )
			, WD_EDDT            = #{datecompleted}
			, UPD_NO             = #{regNo}
			, UPD_DT             = NOW()
		WHERE ORD_CHG_SQ = #{ordChgSq}
	</update>	
	
	<!-- 주문변경상세 회수완료    -->
	<update id="updateTbOrderChangeDetail" parameterType="Delivery" >
		/*TsbDelivery.updateTbOrderChangeDetail*/
		UPDATE TB_ORDER_CHANGE_DETAIL SET			  
			  WH_MEMO            = #{wmsmemo}
			<if test='chgGb == "G680_40"'>
			, COMPLETE_DT        = NOW()
			</if>
			, CHG_STAT           = #{chgStat} 
			, UPD_NO             = #{regNo}
			, UPD_DT             = NOW()
		WHERE ORD_CHG_SQ  = #{ordChgSq}
		  AND ORD_DTL_NO  = #{orderdtlno}
		  AND DEL_YN      = 'N'
	</update>
	
	<!-- 주문상세상태 변경   -->
	<update id="updateWdOrderDtlStat" parameterType="Delivery" >
		/*TsbDelivery.updateWdOrderDtlStat*/
		UPDATE tb_order_detail SET
			  ORD_DTL_STAT = #{ordDtlStat} 
			, UPD_NO       = #{regNo}
			, UPD_DT       = NOW()
		WHERE ORD_DTL_NO = #{orderdtlno}
		  AND ORD_NO     = #{orderno}
	</update>
		
	<!-- 교환대기 상태값변경    -->
	<update id="updateOrderExch" parameterType="Delivery" >
		/*TsbDelivery.updateOrderExch*/
		UPDATE TB_ORDER_DETAIL SET
			  ORD_DTL_STAT = #{ordDtlStat}
			, UPD_NO       = #{regNo}
			, UPD_DT       = NOW()		
		WHERE ORD_DTL_NO = #{chgOrdDtlNo}
		AND ORD_DTL_STAT IN ('G013_25')
			
	</update>

	<!--  주문상세송장 등록   -->
	<insert id="insertTbOrdDtlInvoice" parameterType="Delivery"  keyProperty="ordInvoiceSq">
		/*TsbDelivery.insertTbOrdDtlInvoice*/
		INSERT INTO TB_ORDER_DETAIL_INVOICE 
		(
			  ORD_NO					 -- 주문번호		
			, ORD_DTL_NO				 -- 주문상세번호	
			, INVOICE_NO				 -- 송장번호	
			, ADD_INVOICE_YN			 -- 추가송장여부	
			, DEL_YN					 -- 삭제여부		
			, REG_NO					 -- 등록자NO		
			, REG_DT					 -- 등록일시		
			, UPD_NO					 -- 수정자NO		
			, UPD_DT					 -- 수정일시		
		)
		VALUES
		(
			  #{orderno}
			, IFNULL(#{orderdtlno},0)
			, #{invoiceno}
			, #{addinvoiceyn}
			, 'N'
			, #{regNo}
			, NOW()
			, #{regNo}
			, NOW()
		)
			
	</insert>
	
	<!-- 주문상세번호 조회 -->	
	<select id="getOrdDtlno" resultType="Delivery">
		/*TsbDelivery.getOrdDtlno*/
		SELECT ORD_DTL_NO 
		  FROM TB_ORDER_DETAIL_ITEM A 
		  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO AND A.ORD_DTL_NO = B.ORD_DTL_NO 
		 WHERE ORD_NO     = #{orderno}
		   AND PRODUCT_NO = #{productno}
		   AND OPT_CD     = #{skucode}
		   AND B.ORD_DTL_STAT NOT IN ('G013_50','G013_55','G013_60','G013_70','G013_97','G013_98','G013_99')
	</select>
		
	<!-- 주문상세 상태값변경    -->
	<update id="updateOrdDtlStat" parameterType="Delivery" >
		/*TsbDelivery.updateOrdDtlStat*/
		UPDATE TB_ORDER_DETAIL SET
			  ORD_DTL_STAT    = CASE WHEN ORD_DTL_STAT = 'G013_50' THEN ORD_DTL_STAT ELSE  #{ordDtlStat} END -- G013_40	배송준비중
			, INVOICE_NO      = #{invoiceno}
			, SHIP_COMP_CD    = (SELECT MAX(C.SHIP_COMP_CD) FROM TB_SHIP_COMPANY C WHERE WMS_SHIP_COMP_CD = #{logisticsno})
			, UPD_NO          = #{regNo}
			, UPD_DT          = NOW()
		WHERE ORD_NO     = #{orderno}
		<if test='orderdtlno != null and orderdtlno != ""'>
		  AND ORD_DTL_NO = #{orderdtlno}
		</if>
		  AND ORD_DTL_STAT NOT IN ('G013_40','G013_55','G013_60','G013_70','G013_97','G013_98','G013_99') 
			
	</update>
		
	<!-- 매장상품재고 삭제     -->
	<delete id="deleteShopStock" parameterType="Delivery" >
		/*TsbDelivery.deleteShopStock*/
		DELETE FROM TB_SHOP_GOODS_STOCK 
	</delete>
		
	<!-- 매장상품재고 삭제     -->
	<insert id="insertShopStock" parameterType="Delivery" >
		/*TsbDelivery.insertShopStock*/
		INSERT INTO TB_SHOP_GOODS_STOCK 
		(
			  SUPPLY_COMP_CD
			, CD_SHOP
			, CD_STYLE
			, CD_COLOR
			, CD_SIZE
			, QT_STOCK
			, REG_NO
			, REG_DT
		)
		VALUES
		(
			  #{supplyCompCd}
			, #{cdShop}
			, #{cdStyle}
			, #{cdColor}
			, replace(#{cdSize},'.0','')
			, #{qtStock}
			, #{regNo}
			, NOW()
		)
	</insert>		

	<!-- 출고대상 주문번호 조회  -->	
	<select id="getOrderNoList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getOrderNoList*/
	<![CDATA[	
	  SELECT DISTINCT ORD_NO, ORD_EXCH_GB, PG_GB
		FROM (
			SELECT A.ORD_NO, B.ORD_EXCH_GB, (SELECT MAX(PG_GB) FROM TB_PAYMENT WHERE ORD_NO= A.ORD_NO AND PAY_GB ='O') AS PG_GB /* 주문 상품 */
			     , CASE WHEN (SELECT COUNT(*) FROM TB_ORD_FREEGIFT ODF WHERE ODF.ORD_NO = A.ORD_NO) > 0 THEN 'Y' ELSE 'N' END AS GIFT_YN 
			  FROM TB_ORDER        A
			  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO 
			  JOIN TB_GOODS        C ON B.GOODS_CD = C.GOODS_CD 
			 WHERE C.SELF_GOODS_YN = 'Y'       -- 자사 
			   AND B.ORD_DTL_STAT  = 'G013_20' -- 결제완료 
			   AND B.ORD_EXCH_GB   = 'O'       -- 주문
			   AND 1 >= FN_GET_BIZDAYS(DATE_FORMAT(A.ORD_DT, '%Y%m%d') , DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY ), '%Y%m%d')) -- 영업일 기준 -1일   
			   AND NOT EXISTS (SELECT '1' FROM TB_GOODS_RES_SELL WHERE GOODS_CD = B.GOODS_CD AND USE_YN ='Y') 
			   AND 'Y' = CASE WHEN B.GIFT_PACK_YN ='Y' AND B.GIFT_ADDR_INP_YN = 'N' THEN 'N' ELSE 'Y' END 
			   AND A.ORD_DT <= DATE_ADD(NOW(), INTERVAL -30 SECOND) -- 30초 DELAY
			   AND NOT EXISTS (
			                SELECT 1
			                  FROM TB_DELIVERY_ASSIGN
			                 WHERE ORD_NO      = B.ORD_NO
			                   AND ORD_DTL_NO  = B.ORD_DTL_NO
			                   AND DELV_LOC_CD = 'ST0001'
			                   AND DELV_AR_GB  = 'N'
			              )

			 GROUP BY A.ORD_NO, B.ORD_EXCH_GB
			
			UNION ALL /* 교환  상품 */
			
			SELECT A.ORD_NO, B.ORD_EXCH_GB, (SELECT MAX(PG_GB) FROM TB_PAYMENT WHERE ORD_NO= A.ORD_NO AND PAY_GB ='O') AS PG_GB
			    , 'N' AS GIFT_YN
			  FROM TB_ORDER        A
			  JOIN TB_ORDER_DETAIL B        ON A.ORD_NO = B.ORD_NO 
			  JOIN TB_GOODS        C        ON B.GOODS_CD = C.GOODS_CD 
			  JOIN TB_ORDER_CHANGE_DETAIL D ON B.ORD_DTL_NO = D.CHG_ORD_DTL_NO 
			  JOIN TB_ORDER_CHANGE        E ON D.ORD_CHG_SQ = E.ORD_CHG_SQ 
			 WHERE C.SELF_GOODS_YN = 'Y'       -- 자사 
			   AND B.ORD_DTL_STAT  = 'G013_20' -- 결제완료 
			   AND B.ORD_EXCH_GB   = 'E'       -- 교환 
			   AND D.CHG_STAT      IN ('G685_20','G685_30','G685_31', 'G685_40')
			   AND 1 >= FN_GET_BIZDAYS(DATE_FORMAT(CASE WHEN E.WD_BF_SEND_YN = 'Y' THEN B.REG_DT ELSE D.COMPLETE_DT END, '%Y%m%d') , DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY ), '%Y%m%d'))
			   AND CASE WHEN E.WD_BF_SEND_YN = 'Y' THEN B.REG_DT ELSE D.COMPLETE_DT END <= DATE_ADD(NOW(), INTERVAL -30 SECOND)
			   AND NOT EXISTS (SELECT 1 FROM TB_EXCHANGE_DELV_FAIL WHERE ORD_NO = A.ORD_NO AND ORD_DTL_NO= D.CHG_ORD_DTL_NO AND ORD_CHG_SQ = D.ORD_CHG_SQ AND DELV_CNCL_YN ='N')
			   AND NOT EXISTS (
			                SELECT 1
			                  FROM TB_DELIVERY_ASSIGN
			                 WHERE ORD_NO      = B.ORD_NO
			                   AND ORD_DTL_NO  = B.ORD_DTL_NO
			                   AND DELV_LOC_CD = 'ST0001'
			                   AND DELV_AR_GB  = 'N'
			              )
			 GROUP BY A.ORD_NO, B.ORD_EXCH_GB

			UNION ALL  /* 예약상품 */
			   
			SELECT A.ORD_NO, B.ORD_EXCH_GB, (SELECT MAX(PG_GB) FROM TB_PAYMENT WHERE ORD_NO= A.ORD_NO AND PAY_GB ='O') AS PG_GB  -- 예약상품    
			     , CASE WHEN (SELECT COUNT(*) FROM TB_ORD_FREEGIFT ODF WHERE ODF.ORD_NO = A.ORD_NO) > 0 THEN 'Y' ELSE 'N' END AS GIFT_YN 
			  FROM TB_ORDER          A
			  JOIN TB_ORDER_DETAIL   B ON A.ORD_NO = B.ORD_NO 
			  JOIN TB_GOODS          C ON B.GOODS_CD = C.GOODS_CD 
			  JOIN TB_GOODS_RES_SELL D ON B.GOODS_CD = D.GOODS_CD  
			 WHERE C.SELF_GOODS_YN = 'Y'       -- 자사 
			   AND B.ORD_DTL_STAT  = 'G013_20' -- 결제완료 
			   AND D.DELV_RES_DT  <= NOW()
			   AND B.ORD_EXCH_GB   = 'O'       -- 주문 
			   AND 1 >= FN_GET_BIZDAYS(DATE_FORMAT(CASE WHEN  A.ORD_DT < D.DELV_RES_DT THEN D.DELV_RES_DT ELSE A.ORD_DT END, '%Y%m%d') , DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY ), '%Y%m%d'))
			   AND 'Y' = CASE WHEN B.GIFT_PACK_YN ='Y' AND B.GIFT_ADDR_INP_YN = 'N' THEN 'N' ELSE 'Y' END 
			   AND NOT EXISTS (
			                SELECT 1
			                  FROM TB_DELIVERY_ASSIGN
			                 WHERE ORD_NO      = B.ORD_NO
			                   AND ORD_DTL_NO  = B.ORD_DTL_NO
			                   AND DELV_LOC_CD = 'ST0001'
			                   AND DELV_AR_GB  = 'N'
			              )
			   AND (SELECT COUNT(*) FROM TB_GOODS_RES_SELL WHERE DELV_RES_DT > NOW() AND GOODS_CD = B.GOODS_CD) = 0
			 GROUP BY A.ORD_NO, B.ORD_EXCH_GB

			
		) A
		WHERE 'Y' = CASE WHEN PG_GB = 'NAVER_ORDER' AND DATE_FORMAT(NOW(),'%H%i%S') > '140000' THEN 'N' ELSE 'Y' END   --  오픈시점 주석풀기  네이버 주문형은 14시까지 
		ORDER BY ORD_NO
		LIMIT 0, 400
		]]>
	</select>
			
	<!-- 출고대상 주문상세번호 조회  -->	
	<select id="getOrderDtlNoList" resultType="Delivery" >
		/*TsbDelivery.getOrderDtlNoList*/
		SELECT 
				  A.ORD_NO 
				, B.ORD_DTL_NO 
				, B.GOODS_TYPE 
				, B.ORD_QTY - B.CNCL_RTN_QTY AS ORD_QTY
				, B.ORD_EXCH_GB 
		  FROM TB_ORDER A
		  JOIN TB_ORDER_DETAIL B ON A.ORD_NO   = B.ORD_NO 
		  JOIN TB_GOODS C        ON B.GOODS_CD = C.GOODS_CD 
		 WHERE A.ORD_NO = #{ordNo}
		   AND B.ORD_DTL_STAT = 'G013_20' -- 결제완료건 
		   AND C.SELF_GOODS_YN = 'Y'       -- 자사 
		 ORDER BY B.ORD_DTL_NO		
	</select>
		
		
	<!-- 출고대상 주문상세아이템 조회  -->	
	<select id="getOrderDtlItemList" resultType="Delivery">
		/*TsbDelivery.getOrderDtlItemList*/
		SELECT 
			  A.ORD_NO 
			, B.ORD_DTL_NO 
			, B.GOODS_CD 
			, C.ITEM_CD 
			, C.OPT_CD 
			, C.OPT_CD1 
			, C.OPT_CD2 
		    , (B.ORD_QTY - B.CNCL_RTN_QTY) * C.ITEM_QTY  AS ORD_QTY
		    , (B.ORD_QTY - B.CNCL_RTN_QTY)               AS ORD_DTL_QTY
		    , C.ITEM_QTY                                 AS ITEM_QTY
		    , B.GOODS_TYPE 
		    , C.PRODUCT_NO 
    		, B.FORMAL_GB  
    		, B.SUPPLY_COMP_CD 
    		, D.BRAND_CD
		  FROM TB_ORDER             A
		  JOIN TB_ORDER_DETAIL      B ON A.ORD_NO = B.ORD_NO 
		  JOIN TB_ORDER_DETAIL_ITEM C ON B.ORD_NO = C.ORD_NO AND B.ORD_DTL_NO = C.ORD_DTL_NO 
		  JOIN TB_GOODS             D ON B.GOODS_CD = D.GOODS_CD 
		 WHERE B.ORD_DTL_NO = #{ordDtlNo}
		 
	</select>
		
	<!-- 출고처 및 상품 제외 조회  -->	
	<select id="getDeliveryAssignBanGoods" resultType="int">
		/*TsbDelivery.getDeliveryAssignBanGoods*/
		<![CDATA[
		SELECT SUM(CNT) AS CNT 
		  FROM (
				 SELECT COUNT(*) CNT 
				   FROM TB_DELIVERY_ASSIGN
				  WHERE ORD_NO      = #{ordNo}
				    AND ORD_DTL_NO  = #{ordDtlNo}
				    AND DELV_LOC_CD = #{delvLocCd}
				    AND DELV_AR_GB  = 'N'  -- 출고수락  거부 
				UNION ALL 
				SELECT COUNT(*) CNT 
				  FROM TB_DELIVERY_BAN_GOODS
				 WHERE DELV_LOC_CD    = #{delvLocCd}
				   AND GOODS_CD       = #{optCd}
				   AND OPT_CD1        = #{optCd1}
				   AND OPT_CD2        = #{optCd2}
				   AND DELV_BAN_STDT <= NOW()
				   AND DELV_BAN_EDDT >= NOW()
				   AND DEL_YN         = 'N'
			   ) A
		 ]]>
	</select>		
		
	<!-- 출고처지정 등록    -->
	<insert id="insertTbDeliveryAssign" parameterType="Delivery" keyProperty="delvAssignSq" >
		/*TsbDelivery.insertTbDeliveryAssign*/
		INSERT INTO TB_DELIVERY_ASSIGN
		(
			  ORD_NO	 		--	주문번호
			, ORD_DTL_NO	 	--	주문상세번호
			, DELV_LOC_CD	    --	출고처코드
			, ASSIGN_QTY	    --	지정수량
			, DELV_AR_GB	    --	출고수락거부구분(P:대기, Y:수락, N:거부)
			, REG_NO	 	    --	등록자NO
			, REG_DT	 	    --	등록일시
			, UPD_NO	 	    --	수정자NO
			, UPD_DT	 	    --	수정일시
		)
		VALUES
		(
			  #{ordNo}	 		--	주문번호
			, #{ordDtlNo}	 	--	주문상세번호
			, #{delvLocCd}	    --	출고처코드
			, #{locQty}	        --	지정수량
			, #{delvArGb}	    --	출고수락거부구분(P:대기, Y:수락, N:거부)
			, #{regNo}	 	    --	등록자NO
			, NOW()	 		    --	등록일시
			, #{regNo}	 	    --	수정자NO
			, NOW()	            --	수정일시
		)		
	</insert>
   
	<!-- 출고처지정HST 등록    -->
	<insert id="insertTbDeliveryAssignHst" parameterType="Delivery" keyProperty="delvAssignHstSq"  >
		/*TsbDelivery.insertTbDeliveryAssignHst*/
		INSERT INTO TB_DELIVERY_ASSIGN_HST
		(
			  DELV_ASSIGN_SQ  --  출고지정일련번호
			, ORD_NO	 	  --  주문번호
			, ORD_DTL_NO	  --  주문상세번호
			, DELV_LOC_CD	  --  출고처코드
			, ASSIGN_QTY	  --  지정수량
			, DELV_AR_GB	  --  출고수락거부구분(P:대기, Y:수락, N:거부)
			, REG_NO	 	  --  등록자NO
			, REG_DT	 	  --  등록일시
			, UPD_NO	 	  --  수정자NO
			, UPD_DT	 	  --  수정일시
			, HST_REG_DT      --  이력등록일시
		)
		VALUES
		(
			  #{delvAssignSq}	--	출고지정일련번호
			, #{ordNo}	 		--	주문번호
			, #{ordDtlNo}	 	--	주문상세번호
			, #{delvLocCd}	    --	출고처코드
			, #{locQty}	        --	지정수량
			, #{delvArGb}	    --	출고수락거부구분(P:대기, Y:수락, N:거부)
			, #{regNo}	 	    --	등록자NO
			, NOW()	 		    --	등록일시
			, #{regNo}	 	    --	수정자NO
			, NOW()	            --	수정일시
			, NOW()	            --	수정일시
		)
	</insert>
		
	<!-- 주문상세 출고처지정   -->
	<update id="updateTbOrderDtlAssign" parameterType="Delivery" >
		/*TsbDelivery.updateTbOrderDtlAssign*/
		UPDATE TB_ORDER_DETAIL SET
			  ORD_DTL_STAT     = #{ordDtlStat}
			, DELV_LOC_CD      = #{delvLocCd}
			, DELV_ASSIGN_DT   = NOW()
			, DELV_ASSIGN_STAT = #{delvAssignStat} 
			, UPD_NO           = #{regNo}
			, UPD_DT           = NOW()
		WHERE ORD_DTL_NO   = #{ordDtlNo}
		  AND ORD_NO       = #{ordNo}
		  AND ORD_DTL_STAT = 'G013_20'
	</update>
	

			
	<!-- 출고처 직송매장 체크   -->	
	<select id="getDeliveryAssignBanGoodsShop" resultType="Delivery">
		/*TsbDelivery.getDeliveryAssignBanGoodsShop*/
		<![CDATA[
			SELECT 
				  'PRC' AS USE_GB
				, A.DELV_LOC_CD 
				, A.DELV_ASSIGN_ORD
				, #{locQty} AS LOC_QTY
				, #{ordDtlNo} AS ORD_DTL_NO
				, #{optCd}    AS OPT_CD
				, #{optCd1}   AS OPT_CD1
				, #{optCd2}   AS OPT_CD2
				, #{goodsType} AS GOODS_TYPE
			  FROM TB_DELIVERY_LOC A
			  JOIN TB_STOCK_SYNC_BASE B ON A.DELV_LOC_CD = B.DELV_LOC_CD 
			 WHERE A.USE_YN          = 'Y'
			   AND B.DELV_SYNC_YN    = 'Y'
			   AND B.BRAND_CD        = #{brandCd}
			   AND B.FORMAL_GB       = #{formalGb}
			   AND A.SUPPLY_COMP_CD  = #{supplyCompCd}
			   AND A.DELV_LOC_CD     = #{delvLocCd}
			   AND NOT EXISTS (
			                SELECT 1
			                  FROM TB_DELIVERY_ASSIGN
			                 WHERE ORD_NO      = #{ordNo}
			                   AND ORD_DTL_NO  = #{ordDtlNo}
			                   AND DELV_LOC_CD = A.DELV_LOC_CD
			                   AND DELV_AR_GB  = 'N'
			              )
			   AND NOT EXISTS (
			                    SELECT 1
			                      FROM TB_DELIVERY_BAN_GOODS
			                     WHERE DELV_LOC_CD    = A.DELV_LOC_CD
								   AND GOODS_CD       = #{optCd}
								   AND OPT_CD1        = #{optCd1}
								   AND OPT_CD2        = #{optCd2}
			                       AND DELV_BAN_STDT <= NOW()
			                       AND DELV_BAN_EDDT >= NOW()
			                       AND DEL_YN         = 'N'
			                  ) 
		 ]]>
	</select>	
			
	<!-- 출고처지정 임시 테이블 삭제    -->
	<delete id="deleteTbDeliveryLocTmp" parameterType="Delivery"  >
		/*TsbDelivery.deleteTbDeliveryLocTmp*/
		DELETE FROM TB_DELIVERY_LOC_TMP WHERE USE_GB ='PRC'
	</delete>		
	
	<!-- 출고처지정 임시 테이블 등록   -->
	<insert id="insertTbDeliveryLocTmp" parameterType="Delivery"  >
		/*TsbDelivery.insertTbDeliveryLocTmp*/
		INSERT INTO TB_DELIVERY_LOC_TMP
		(
			  USE_GB
			, DELV_LOC_CD
			, DELV_ASSIGN_ORD
			, LOC_QTY
			, GOODS_LOC_CNT
			, ORD_DTL_NO_LIST
		)
		VALUES
		(
			  #{useGb}
			, #{delvLocCd}
			, #{delvAssignOrd}
			, #{locQty}
			, 1
			, #{ordDtlNo}
		) ON DUPLICATE KEY
		UPDATE 
			GOODS_LOC_CNT = GOODS_LOC_CNT+1
		  , ORD_DTL_NO_LIST = CONCAT(ORD_DTL_NO_LIST,',',#{ordDtlNo})
		  , LOC_QTY = CASE WHEN  LOC_QTY > #{locQty} THEN  #{locQty} ELSE LOC_QTY END 
				
	</insert>		
	
	<!-- 출고처 지정 임시테이블 조회    -->	
	<select id="getDeliveryLocTmp" resultType="Delivery">
		/*TsbDelivery.getDeliveryLocTmp*/
		SELECT A.*
		  FROM(
				SELECT 
					  DELV_LOC_CD
					, ORD_DTL_NO_LIST
					, LOC_QTY
					, GOODS_LOC_CNT
					, RANK() OVER( ORDER BY GOODS_LOC_CNT DESC, DELV_ASSIGN_ORD, LOC_QTY DESC, DELV_LOC_CD) AS RNK
				  FROM TB_DELIVERY_LOC_TMP
				 WHERE USE_GB        = 'PRC' 
				   AND GOODS_LOC_CNT = #{goodsLocCnt}
		  ) A WHERE RNK = 1
	</select>
	
	<!-- 출고처지정 임시 테이블 등록   -->
	<insert id="insertTbDeliveryLocSetTmp" parameterType="Delivery"  >
		/*TsbDelivery.insertTbDeliveryLocSetTmp*/
		INSERT INTO TB_DELIVERY_LOC_TMP
		(
			  USE_GB
			, DELV_LOC_CD
			, DELV_ASSIGN_ORD
			, LOC_QTY
			, GOODS_LOC_CNT
			, GOODS_LOC_SET_CNT
		)
		VALUES
		(
			  #{useGb}
			, #{delvLocCd}
			, #{delvAssignOrd}
			, #{locQty}
			, 0
			, 1
		) ON DUPLICATE KEY
		UPDATE 
			GOODS_LOC_SET_CNT = A.GOODS_LOC_SET_CNT+1
		  ,	LOC_QTY = CASE WHEN LOC_QTY > #{locQty} THEN #{locQty} ELSE LOC_QTY END 
	</insert>			
		
	<!-- 출고처 지정 임시테이블 세트상품갯수 max값 조회      -->	
	<select id="getDeliveryLocTmpGoodsSetMaxCnt" resultType="int">
		/*TsbDelivery.getDeliveryLocTmpGoodsSetMaxCnt*/
		SELECT CASE WHEN MAX(GOODS_LOC_SET_CNT) IS NULL THEN 0 ELSE MAX(GOODS_LOC_SET_CNT)  END  AS CNT 
		  FROM TB_DELIVERY_LOC_TMP
		 WHERE USE_GB = 'PRC'
	</select>		
	
	<!-- 출고처지정 임시 테이블 수정   -->
	<update id="updateTbDeliveryLocSetTmp" parameterType="Delivery"  >
		/*TsbDelivery.updateTbDeliveryLocSetTmp*/
		UPDATE TB_DELIVERY_LOC_TMP SET
		      GOODS_LOC_CNT = GOODS_LOC_CNT + 1
		    , ORD_DTL_NO_LIST =  CASE WHEN ORD_DTL_NO_LIST IS NULL THEN #{ordDtlNo} ELSE CONCAT(ORD_DTL_NO_LIST,',',#{ordDtlNo}) END
		WHERE USE_GB = 'PRC' AND GOODS_LOC_SET_CNT = #{goodsLocSetCnt}		
	</update>	
	
	<!-- 출고처지정 임시 테이블 세트상품갯수 초기화   -->
	<update id="updateTbDeliveryLocSetTmpInit" parameterType="Delivery"  >
		/*TsbDelivery.updateTbDeliveryLocSetTmpInit*/
		UPDATE TB_DELIVERY_LOC_TMP SET
			GOODS_LOC_SET_CNT = 0
		WHERE USE_GB = 'PRC'		
	</update>	
			
	<!-- WMS 출고요청 대상 주문번호 조회      -->	
	<select id="getWmsDeliveryOrdNoList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getWmsDeliveryOrdNoList*/
		SELECT 
		  	   A.ORD_NO 
		  FROM TB_ORDER A
		  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO 
		  JOIN TB_DELIVERY_LOC C ON B.DELV_LOC_CD = C.DELV_LOC_CD AND B.SUPPLY_COMP_CD = C.SUPPLY_COMP_CD 
		  JOIN TB_GOODS        D ON B.GOODS_CD = D.GOODS_CD 
		 WHERE B.ORD_DTL_STAT  = 'G013_35' -- 출고처지정 
		   AND C.DELV_LOC_CLSF = 'G024_10' -- 물류창고
		   AND D.SELF_GOODS_YN = 'Y' -- 자사상품
		 GROUP BY A.ORD_NO
	
	</select>	
	
	<!-- WMS 출고요청 대상 조회      -->	
	<select id="getWmsDeliveryList" resultType="Delivery">
		/*TsbDelivery.getWmsDeliveryList*/
		SELECT 
			  A.ORD_NO                            AS OrderNo
			, 'WMS'                               AS  DeliveryTypeCd
			, '정상'                               AS  IssueTypeCd
			, '10'                                AS StatusCd -- 배송지시
			, D.CUST_ID                           AS LoginId
			, A.ORD_NM                            AS CustomerName
			, A.ORD_DT                            AS DateOrdered
			, FN_GET_CODE_NM('G110',D.CUST_GRADE) AS  Grade 
			, E.RECIP_NM                          AS Receiver
			, E.RECIP_TELNO                       AS ReceiverTelNum
			, E.RECIP_PHNNO                       AS ReceiverCellNum
			, E.RECIP_ZIPCODE                     AS DeliveryPostalCode
			, E.RECIP_BASE_ADDR                   AS DeliveryAddr1
			, E.RECIP_DTL_ADDR                    AS DeliveryAddr2
			, CASE WHEN B.SHOT_DELV_YN ='Y' THEN '14' ELSE '05' END                               AS LogisticsNo
			, CASE WHEN B.SHOT_DELV_YN ='Y' THEN '디디로직스'  ELSE 'CJ 대한통운' END                  AS LogisticsName
			, E.DELV_MEMO                         AS DeliveryMemo
			, CASE WHEN (SELECT COUNT(*) -1 FROM TB_ORDER_DETAIL WHERE ORD_NO = A.ORD_NO) > 0 THEN CONCAT(F.GOODS_NM,' 외  ', (SELECT COUNT(*) -1 FROM TB_ORDER_DETAIL WHERE ORD_NO = A.ORD_NO) , '건') ELSE F.GOODS_NM END   AS ProductSummary
			,  0                                  AS IsCancel
			,  0                                  AS IsChangeAddress
			,  0                                  AS IsReOrder
			, CASE WHEN A.MALL_GB = 'G011_20' THEN B.EXTMALL_ID ELSE 'APISHOP_0054' END                  AS OrderPath -- 주문경로 (확인필요!)
			, CASE WHEN B.SHOT_DELV_YN ='Y' THEN '20' ELSE '10' END                                 	 AS DeliveryClassCd 
			, CASE WHEN B.ORD_EXCH_GB ='O'  THEN '10' ELSE '20' END                                 	 AS ShippingTypeCd
			, B.GIFT_PACK_YN                      AS IsBeautyDelivery
			, ''                                                                                         AS DeliveryAddrNew  -- 도로명 주소 (확인필요!)
			, (SELECT PROVIDER_NO FROM TB_SUPPLY_COMPANY BB WHERE BB.SUPPLY_COMP_CD = B.SUPPLY_COMP_CD ) AS ProviderNo
			, C.PRODUCT_NO                        AS ProductNo
			, C.PRODUCT_CODE                      AS ProductCode
			, (SELECT CC.GOODS_NM FROM TB_GOODS CC WHERE CC.GOODS_CD = C.ITEM_CD) AS ProductName    -- 상품명 
			, CASE WHEN B.GOODS_TYPE = 'G056_S' THEN '세트' ELSE '일반' END 		  AS ProductTypeCd  -- 상품타입
			, C.OPT_CD                            AS SKUCode       
			, CONCAT(C.OPT_CD1,'/',C.OPT_CD2)     AS SKUValue
			, B.CURR_PRICE + B.OPT_ADD_PRICE      AS UnitPrice
			, (B.ORD_QTY -B.CNCL_RTN_QTY) * C.ITEM_QTY  AS Qty
			, 'WMS'                               AS StockMgmtTypeCd
			, 'N'                                 AS GiftYn  -- 사은품여부 
			, CASE WHEN B.GOODS_TYPE = 'G056_S' THEN B.GOODS_CD ELSE '' END  AS SetProductCode -- 세트상품코드 
			, CASE WHEN B.GOODS_TYPE = 'G056_S' THEN 'Y' ELSE 'N' END        AS SetProductYn   -- 세트상품여부 
			, CASE WHEN B.GOODS_TYPE = 'G056_S' THEN F.GOODS_NM ELSE '' END  AS SetproductName -- 세트상품명 
			, B.ORD_DTL_NO                        AS OrderDtlNo
			, 0                                   AS Cqty
			, CASE WHEN B.GOODS_TYPE = 'G056_S' THEN (B.ORD_QTY -B.CNCL_RTN_QTY) ELSE 0 END  AS SetQty        -- 세트상품 수량
			, CASE WHEN B.GOODS_TYPE = 'G056_S' THEN C.ITEM_QTY ELSE 0 END                   AS SetItemQty    -- 세트 구성수량
			, (SELECT MAX(CASE WHEN PG_GB ='NAVER_ORDER' THEN 'NAVER' ELSE 'KCP' END)   FROM TB_PAYMENT WHERE ORD_NO= A.ORD_NO AND PAY_GB ='O'  ) AS PAY_GB 
		  FROM TB_ORDER              A 
		  JOIN TB_ORDER_DETAIL       B ON A.ORD_NO = B.ORD_NO 
		  JOIN TB_ORDER_DETAIL_ITEM  C ON B.ORD_NO = C.ORD_NO AND B.ORD_DTL_NO = C.ORD_DTL_NO 
		  LEFT JOIN TB_CUSTOMER      D ON A.CUST_NO = D.CUST_NO 
		  JOIN TB_DELIVERY_ADDR      E ON B.DELV_ADDR_SQ = E.DELV_ADDR_SQ 
		  JOIN TB_GOODS              F ON B.GOODS_CD = F.GOODS_CD 
		  JOIN TB_DELIVERY_LOC       G ON B.DELV_LOC_CD = G.DELV_LOC_CD AND B.SUPPLY_COMP_CD = G.SUPPLY_COMP_CD
		 WHERE A.ORD_NO        = #{ordNo} 
		   AND B.ORD_DTL_STAT  = 'G013_35' -- 출고처지정
		   AND G.DELV_LOC_CLSF = 'G024_10' -- 물류창고
		  ORDER BY B.ORD_DTL_NO 
		   
	</select>			
	
	<!-- WMS 출고요청 대상 조회      -->	
	<select id="getWmsDeliveryGiftList" resultType="Delivery">
		/*TsbDelivery.getWmsDeliveryGiftList*/
		SELECT 
				  A.ORD_NO    AS OrderNo
				, '' AS  DeliveryTypeCd
				, '' AS  IssueTypeCd
				, '10' AS StatusCd -- 배송지시
				, '' AS LoginId
				, '' AS CustomerName
				, '' AS DateOrdered
				, '' AS  Grade 
				, '' AS Receiver
				, '' AS ReceiverTelNum
				, '' AS ReceiverCellNum
				, '' AS DeliveryPostalCode
				, '' AS DeliveryAddr1
				, '' AS DeliveryAddr2
				, '' AS LogisticsNo
				, '' AS LogisticsName
				, '' AS DeliveryMemo
				, '' AS ProductSummary
				,  0 AS IsCancel
				,  0 AS IsChangeAddress
				,  0 AS IsReOrder
				, '' AS OrderPath -- 주문경로 (확인필요!)
				, '' AS DeliveryClassCd 
				, '' AS ShippingTypeCd   -- 출고구분 10 일반, 20 교환
				, '' AS IsBeautyDelivery
				, '' AS DeliveryAddrNew  -- 도로명 주소 
				, '' AS ProviderNo
				, C.PRODUCT_NO                        AS ProductNo
				, C.PRODUCT_CODE                      AS ProductCode
				, (SELECT G.GOODS_NM FROM TB_FREE_GOODS G WHERE G.PRODUCT_NO = C.PRODUCT_NO AND G.PRODUCT_CODE = C.PRODUCT_CODE) AS ProductName    -- 상품명 
				, '사은품'     AS ProductTypeCd  	-- 상품타입
				, ' '         AS SKUCode       
				, ''         AS SKUValue
				, 0          AS UnitPrice
				, C.ITEM_QTY AS Qty
				, 'WMS'      AS StockMgmtTypeCd
				, 'Y'        AS GiftYn  -- 사은품여부 
				, ''         AS SetProductCode -- 세트상품코드 
				, 'N'        AS SetProductYn   -- 세트상품여부 
				, ''         AS SetproductName -- 세트상품명 
				, NULL       AS OrderDtlNo
				, 0          AS Cqty
				, 0          AS SetQty        -- 세트상품 수량
				, 0          AS SetItemQty    -- 세트 구성수량
		  FROM TB_ORD_FREEGIFT     A
		  JOIN TB_ORD_FREEGIFT_VAL C ON A.ORD_FREEGIFT_SQ = C.ORD_FREEGIFT_SQ
		  JOIN TB_ORDER            O ON A.ORD_NO = O.ORD_NO 
		  WHERE A.ORD_NO = #{ordNo} 
	</select>

	<!-- WMS 회수요청 대상 조회      -->	
	<select id="getWithdrawRequestList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getWithdrawRequestList*/
	SELECT * FROM (
		SELECT
			  A.ORD_CHG_SQ                                          AS OrderExceptionNo -- 주문변경번호 
			, CASE WHEN A.CHG_GB ='G680_30' THEN '10' ELSE '20' END AS RecallTypeCd
			, A.CHGER_NM                                            AS Receiver
			, A.CHGER_TELNO                                         AS ReceiverTelNum
			, A.CHGER_PHNNO                                         AS ReceiverCellNum
			, A.CHGER_ZIPCODE                                       AS DeliveryPostalCode
			, A.CHGER_BASE_ADDR                                     AS DeliveryAddr1
			, A.CHGER_DTL_ADDR                                      AS DeliveryAddr2
			, G.ORD_NO                                              AS OrderNo
			, G.ORD_NM                                              AS CustomerName
			, (SELECT CC.CUST_ID FROM TB_CUSTOMER CC WHERE CC.CUST_NO = G.CUST_NO) AS LoginId
			, CASE WHEN (SELECT COUNT(*) FROM TB_USER U WHERE U.USER_NO = A.REG_NO ) > 0 THEN CONCAT('[C/S]-반품 /',FN_GET_CODE_NM('G688', A.CHG_REASON),'/',A.CHG_MEMO,'/',(SELECT R.USER_NM FROM TB_USER R WHERE R.USER_NO = A.REG_NO )) ELSE CONCAT('[고객]-반품 /',FN_GET_CODE_NM('G688', A.CHG_REASON),'/',A.CHG_MEMO) END   AS CSMemo
			, A.UPD_DT                                              AS DateCSMemoUpdated
			, 0                                                     AS IsDeleted
			, ''                                                    AS DeliveryAddrNew 
			, CASE WHEN A.WD_TARGET_YN  = 'N' THEN 'N' WHEN A.WD_GB ='W'  THEN 'Y' ELSE 'N' END          AS RecallRequestYn
			, '0'                                                   AS IfStat
			, D.PRODUCT_NO                                          AS ProductNo
			, D.PRODUCT_CODE                                        AS ProductCode
			, E.GOODS_NM                                            AS ProductName
			, D.OPT_CD                                              AS SKUCode
			, CONCAT(D.OPT_CD1,'/',D.OPT_CD2)                       AS SKUValue
			, B.CHG_QTY * D.ITEM_QTY                                AS RecallQty
			, '입고대기'                                         	    AS StatusCd
			, (SELECT SS.SHIP_COMP_NM FROM TB_SHIP_COMPANY SS WHERE SS.SHIP_COMP_CD = A.SHIP_COMP_CD  ) AS LogisticsName
			, A.SHIP_COMP_CD                                        AS LogisticsCode
			, A.WD_INVOICE_NO                                       AS RecallInvoiceNo
			, C.ORD_DTL_NO                                          AS OrderDtlNo
			, C.INVOICE_NO                                          AS InvoiceNo
			, A.CHGER_RTN_MEMO                                      AS chgerRtnMemo
			, A.WD_GB
			, A.WD_TARGET_YN
			, (SELECT MAX(CASE WHEN PG_GB ='NAVER_ORDER' THEN 'NAVER' ELSE 'KCP' END)   FROM TB_PAYMENT WHERE ORD_NO= G.ORD_NO AND PAY_GB ='O'  ) AS PAY_GB 
		  FROM TB_ORDER_CHANGE        A 
		  JOIN TB_ORDER_CHANGE_DETAIL B ON A.ORD_CHG_SQ = B.ORD_CHG_SQ 
		  JOIN TB_ORDER_DETAIL        C ON B.ORD_DTL_NO = C.ORD_DTL_NO 
		  JOIN TB_ORDER_DETAIL_ITEM   D ON C.ORD_DTL_NO = D.ORD_DTL_NO 
		  JOIN TB_GOODS               E ON C.GOODS_CD   = E.GOODS_CD
		  JOIN TB_ORDER               G ON C.ORD_NO     = G.ORD_NO 
		 WHERE A.CHG_GB         = 'G680_30' -- 반품요청
		   AND B.CHG_STAT       = 'G685_50' -- 반품접수
		   AND B.DEL_YN         = 'N' 
		   AND E.SELF_GOODS_YN  = 'Y' -- 자사상품 
		   AND E.RETURNABLE_YN  = 'Y' -- 반품가능여부 
		   AND G.MALL_GB        = 'G011_10' -- 자사몰
		   AND a.REG_DT  >= DATE_ADD(STR_TO_DATE(REPLACE( '2021-08-31','-','')+ 1, '%Y%m%d%H%i%s'), INTERVAL 0 DAY)

		
		UNION ALL 
		
		SELECT 
			  A.ORD_CHG_SQ                                          AS OrderExceptionNo -- 주문변경번호 
			, CASE WHEN A.CHG_GB ='G680_30' THEN '10' ELSE '20' END AS RecallTypeCd
			, A.CHGER_NM                                            AS Receiver
			, A.CHGER_TELNO                                         AS ReceiverTelNum
			, A.CHGER_PHNNO                                         AS ReceiverCellNum
			, A.CHGER_ZIPCODE                                       AS DeliveryPostalCode
			, A.CHGER_BASE_ADDR                                     AS DeliveryAddr1
			, A.CHGER_DTL_ADDR                                      AS DeliveryAddr2
			, G.ORD_NO                                              AS OrderNo
			, G.ORD_NM                                              AS CustomerName
			, (SELECT CC.CUST_ID FROM TB_CUSTOMER CC WHERE CC.CUST_NO = G.CUST_NO) AS LoginId
			, CASE WHEN (SELECT COUNT(*) FROM TB_USER U WHERE U.USER_NO = A.REG_NO ) > 0 THEN CONCAT('[C/S]-교환 /',FN_GET_CODE_NM('G689', A.CHG_REASON),'/',A.CHG_MEMO,'/',(SELECT R.USER_NM FROM TB_USER R WHERE R.USER_NO = A.REG_NO )) ELSE CONCAT('[고객]-교환 /',FN_GET_CODE_NM('G689', A.CHG_REASON),'/',A.CHG_MEMO) END   AS CSMemo
			, A.UPD_DT                                              AS DateCSMemoUpdated
			, 0                                                     AS IsDeleted
			, ''                                                    AS DeliveryAddrNew 
			, CASE WHEN A.WD_TARGET_YN  = 'N' THEN 'N' WHEN A.WD_GB ='W'  THEN 'Y' ELSE 'N' END          AS RecallRequestYn
			, '0'                                                   AS IfStat
			, D.PRODUCT_NO                                          AS ProductNo
			, D.PRODUCT_CODE                                        AS ProductCode
			, E.GOODS_NM                                            AS ProductName
			, D.OPT_CD                                              AS SKUCode
			, CONCAT(D.OPT_CD1,'/',D.OPT_CD2)                       AS SKUValue
			, B.CHG_QTY * D.ITEM_QTY                                AS RecallQty
			, '입고대기'                                         	    AS StatusCd
			, (SELECT SS.SHIP_COMP_NM FROM TB_SHIP_COMPANY SS WHERE SS.SHIP_COMP_CD = A.SHIP_COMP_CD  ) AS LogisticsName
			, A.SHIP_COMP_CD                                        AS LogisticsCode
			, A.WD_INVOICE_NO                                       AS RecallInvoiceNo
			, C.ORD_DTL_NO                                          AS OrderDtlNo
			, C.INVOICE_NO                                          AS InvoiceNo
			, A.CHGER_RTN_MEMO                                      AS chgerRtnMemo
			, A.WD_GB
			, A.WD_TARGET_YN
			, (SELECT MAX(CASE WHEN PG_GB ='NAVER_ORDER' THEN 'NAVER' ELSE 'KCP' END)   FROM TB_PAYMENT WHERE ORD_NO= G.ORD_NO AND PAY_GB ='O'  ) AS PAY_GB 
		  FROM TB_ORDER_CHANGE        A 
		  JOIN TB_ORDER_CHANGE_DETAIL B ON A.ORD_CHG_SQ = B.ORD_CHG_SQ 
		  JOIN TB_ORDER_DETAIL        C ON B.ORD_DTL_NO = C.ORD_DTL_NO 
		  JOIN TB_ORDER_DETAIL_ITEM   D ON C.ORD_DTL_NO = D.ORD_DTL_NO 
		  JOIN TB_GOODS               E ON C.GOODS_CD   = E.GOODS_CD
		  JOIN TB_ORDER               G ON C.ORD_NO     = G.ORD_NO 
		 WHERE A.CHG_GB         = 'G680_40' -- 교환요청
		   AND B.CHG_STAT       = 'G685_20' -- 교환접수 
		   AND B.DEL_YN         = 'N'
		   AND E.SELF_GOODS_YN  = 'Y' -- 자사상품
		   AND E.CHANGEABLE_YN  = 'Y' -- 교환가능여부
		   AND G.MALL_GB        = 'G011_10' -- 자사몰 
		   AND a.REG_DT  >= DATE_ADD(STR_TO_DATE(REPLACE( '2021-08-31','-','')+ 1, '%Y%m%d%H%i%s'), INTERVAL 0 DAY) 

		
		UNION ALL 
		
		SELECT 
			  A.ORD_CHG_SQ                                          AS OrderExceptionNo -- 주문변경번호 
			, CASE WHEN A.CHG_GB ='G680_30' THEN '10' ELSE '20' END AS RecallTypeCd
			, A.CHGER_NM                                            AS Receiver
			, A.CHGER_TELNO                                         AS ReceiverTelNum
			, A.CHGER_PHNNO                                         AS ReceiverCellNum
			, A.CHGER_ZIPCODE                                       AS DeliveryPostalCode
			, A.CHGER_BASE_ADDR                                     AS DeliveryAddr1
			, A.CHGER_DTL_ADDR                                      AS DeliveryAddr2
			, G.ORD_NO                                              AS OrderNo
			, G.ORD_NM                                              AS CustomerName
			, (SELECT CC.CUST_ID FROM TB_CUSTOMER CC WHERE CC.CUST_NO = G.CUST_NO) AS LoginId
			, CASE WHEN (SELECT COUNT(*) FROM TB_USER U WHERE U.USER_NO = A.REG_NO ) > 0 THEN CONCAT('[C/S]-반품 /',FN_GET_CODE_NM('G688', A.CHG_REASON),'/',A.CHG_MEMO,'/',(SELECT R.USER_NM FROM TB_USER R WHERE R.USER_NO = A.REG_NO )) ELSE CONCAT('[고객]-반품 /',FN_GET_CODE_NM('G688', A.CHG_REASON),'/',A.CHG_MEMO) END   AS CSMemo
			, A.UPD_DT                                              AS DateCSMemoUpdated
			, 0                                                     AS IsDeleted
			, ''                                                    AS DeliveryAddrNew 
			, CASE WHEN F.DWDP_YN = 'Y'       THEN 'N'
			       WHEN A.WD_TARGET_YN  = 'N' THEN 'N' 
			       WHEN A.WD_GB ='W'          THEN 'Y' ELSE 'N' END AS RecallRequestYn
			, '0'                                                   AS IfStat
			, D.PRODUCT_NO                                          AS ProductNo
			, D.PRODUCT_CODE                                        AS ProductCode
			, E.GOODS_NM                                            AS ProductName
			, D.OPT_CD                                              AS SKUCode
			, CONCAT(D.OPT_CD1,'/',D.OPT_CD2)                       AS SKUValue
			, B.CHG_QTY * D.ITEM_QTY                                AS RecallQty
			, '입고대기'                                         	    AS StatusCd
			, (SELECT SS.SHIP_COMP_NM FROM TB_SHIP_COMPANY SS WHERE SS.SHIP_COMP_CD = A.SHIP_COMP_CD  ) AS LogisticsName
			, A.SHIP_COMP_CD                                        AS LogisticsCode
			, A.WD_INVOICE_NO                                       AS RecallInvoiceNo
			, C.ORD_DTL_NO                                          AS OrderDtlNo
			, C.INVOICE_NO                                          AS InvoiceNo
			, A.CHGER_RTN_MEMO                                      AS chgerRtnMemo
			, A.WD_GB
			, A.WD_TARGET_YN
			, (SELECT MAX(CASE WHEN PG_GB ='NAVER_ORDER' THEN 'NAVER' ELSE 'KCP' END)   FROM TB_PAYMENT WHERE ORD_NO= G.ORD_NO AND PAY_GB ='O'  ) AS PAY_GB 
		  FROM TB_ORDER_CHANGE        A 
		  JOIN TB_ORDER_CHANGE_DETAIL B ON A.ORD_CHG_SQ = B.ORD_CHG_SQ 
		  JOIN TB_ORDER_DETAIL        C ON B.ORD_DTL_NO = C.ORD_DTL_NO 
		  JOIN TB_ORDER_DETAIL_ITEM   D ON C.ORD_DTL_NO = D.ORD_DTL_NO 
		  JOIN TB_GOODS               E ON C.GOODS_CD   = E.GOODS_CD
		  JOIN TB_EXTMALL             F ON C.VENDOR_ID  = F.VENDOR_ID AND C.EXTMALL_ID = F.EXTMALL_ID 
		  JOIN TB_ORDER               G ON C.ORD_NO     = G.ORD_NO 
		 WHERE A.CHG_GB         = 'G680_30' -- 반품요청
		   AND B.CHG_STAT       = 'G685_50' -- 반품접수 
		   AND B.DEL_YN         = 'N'
		   AND F.DWDP_YN        = 'N' -- N:자사몰에서 회수 
		   AND E.SELF_GOODS_YN  = 'Y' -- 자사상품 
		   AND E.RETURNABLE_YN  = 'Y' -- 반품가능여부 
		   AND G.MALL_GB        = 'G011_20' -- 제휴몰 
		   AND a.REG_DT  >= DATE_ADD(STR_TO_DATE(REPLACE( '2021-08-31','-','')+ 1, '%Y%m%d%H%i%s'), INTERVAL 0 DAY) 

		
		UNION ALL 
		
		SELECT 
			  A.ORD_CHG_SQ                                          AS OrderExceptionNo -- 주문변경번호 
			, CASE WHEN A.CHG_GB ='G680_30' THEN '10' ELSE '20' END AS RecallTypeCd
			, A.CHGER_NM                                            AS Receiver
			, A.CHGER_TELNO                                         AS ReceiverTelNum
			, A.CHGER_PHNNO                                         AS ReceiverCellNum
			, A.CHGER_ZIPCODE                                       AS DeliveryPostalCode
			, A.CHGER_BASE_ADDR                                     AS DeliveryAddr1
			, A.CHGER_DTL_ADDR                                      AS DeliveryAddr2
			, G.ORD_NO                                              AS OrderNo
			, G.ORD_NM                                              AS CustomerName
			, (SELECT CC.CUST_ID FROM TB_CUSTOMER CC WHERE CC.CUST_NO = G.CUST_NO) AS LoginId
			, CASE WHEN (SELECT COUNT(*) FROM TB_USER U WHERE U.USER_NO = A.REG_NO ) > 0 THEN CONCAT('[C/S]-교환 /',FN_GET_CODE_NM('G689', A.CHG_REASON),'/',A.CHG_MEMO,'/',(SELECT R.USER_NM FROM TB_USER R WHERE R.USER_NO = A.REG_NO )) ELSE CONCAT('[고객]-교환 /',FN_GET_CODE_NM('G689', A.CHG_REASON),'/',A.CHG_MEMO) END   AS CSMemo
			, A.UPD_DT                                              AS DateCSMemoUpdated
			, 0                                                     AS IsDeleted
			, ''                                                    AS DeliveryAddrNew 
			, CASE WHEN F.DWDP_YN = 'Y'       THEN 'N'
			       WHEN A.WD_TARGET_YN  = 'N' THEN 'N' 
			       WHEN A.WD_GB ='W'          THEN 'Y' ELSE 'N' END AS RecallRequestYn
			, '0'                                                   AS IfStat
			, D.PRODUCT_NO                                          AS ProductNo
			, D.PRODUCT_CODE                                        AS ProductCode
			, E.GOODS_NM                                            AS ProductName
			, D.OPT_CD                                              AS SKUCode
			, CONCAT(D.OPT_CD1,'/',D.OPT_CD2)                       AS SKUValue
			, B.CHG_QTY * D.ITEM_QTY                                AS RecallQty
			, '입고대기'                                         	    AS StatusCd
			, (SELECT SS.SHIP_COMP_NM FROM TB_SHIP_COMPANY SS WHERE SS.SHIP_COMP_CD = A.SHIP_COMP_CD  ) AS LogisticsName
			, A.SHIP_COMP_CD                                        AS LogisticsCode
			, A.WD_INVOICE_NO                                       AS RecallInvoiceNo			
			, C.ORD_DTL_NO                                          AS OrderDtlNo
			, C.INVOICE_NO                                          AS InvoiceNo
			, A.CHGER_RTN_MEMO                                      AS chgerRtnMemo
			, A.WD_GB
			, A.WD_TARGET_YN
			, (SELECT MAX(CASE WHEN PG_GB ='NAVER_ORDER' THEN 'NAVER' ELSE 'KCP' END)   FROM TB_PAYMENT WHERE ORD_NO= G.ORD_NO AND PAY_GB ='O'  ) AS PAY_GB 
		  FROM TB_ORDER_CHANGE        A 
		  JOIN TB_ORDER_CHANGE_DETAIL B ON A.ORD_CHG_SQ = B.ORD_CHG_SQ 
		  JOIN TB_ORDER_DETAIL        C ON B.ORD_DTL_NO = C.ORD_DTL_NO 
		  JOIN TB_ORDER_DETAIL_ITEM   D ON C.ORD_DTL_NO = D.ORD_DTL_NO 
		  JOIN TB_GOODS               E ON C.GOODS_CD   = E.GOODS_CD
		  JOIN TB_EXTMALL             F ON C.VENDOR_ID  = F.VENDOR_ID AND C.EXTMALL_ID = F.EXTMALL_ID 
		  JOIN TB_ORDER               G ON C.ORD_NO     = G.ORD_NO 
		 WHERE A.CHG_GB         = 'G680_40' -- 교환요청
		   AND B.CHG_STAT       = 'G685_20' -- 교환요청
		   AND B.DEL_YN         = 'N'
		   AND F.DWDP_YN        = 'N' -- N:자사몰에서 회수 
		   AND E.SELF_GOODS_YN  = 'Y' -- 자사상품
		   AND E.CHANGEABLE_YN  = 'Y' -- 교환가능여부
		   AND G.MALL_GB        = 'G011_20' -- 제휴몰 		
		   AND a.REG_DT  >= DATE_ADD(STR_TO_DATE(REPLACE( '2021-08-31','-','')+ 1, '%Y%m%d%H%i%s'), INTERVAL 0 DAY) 

		) A ORDER BY OrderExceptionNo
	</select>	
		
	<!-- 주문변경상세 상태값 변경   -->
	<update id="updateTbOrderChaneDetailStat" parameterType="Delivery"  >
		/*TsbDelivery.updateTbOrderChaneDetailStat*/
		UPDATE TB_ORDER_CHANGE_DETAIL SET
			  CHG_STAT = #{chgStat}
			, UPD_NO   = #{updNo}
			, UPD_DT   = NOW()
		WHERE ORD_CHG_SQ = #{orderexceptionno}
		  AND ORD_DTL_NO = #{orderdtlno}
		  AND CHG_STAT IN ('G685_20','G685_50')
	</update>			
		
  		
	<!-- 주문변경상세  반운송장번호 업데이트   -->
	<update id="updateTbOrderChaneInvoc" parameterType="Delivery"  >
		/*TsbDelivery.updateTbOrderChaneInvoc*/
		UPDATE TB_ORDER_CHANGE SET
			  WD_STDT        = #{deliveryDt}
			, WD_INVOICE_NO  = #{recallinvoiceno}
			, WD_INVOICE_SEND_YN = 'Y'
			, SHIP_COMP_CD   = #{shipCompCd}
			, UPD_NO         = #{updNo}
			, UPD_DT         = NOW()
		WHERE ORD_CHG_SQ = #{ordChgSq}	
	</update>
  		
	<!-- 주문변경회수상태 업데이트   -->
	<update id="updateTbOrderChangeStat" parameterType="Delivery"  >
		/*TsbDelivery.updateTbOrderChangeStat*/
		UPDATE TB_ORDER_CHANGE SET 
			  WD_SHIP_STATE   = #{crgSt}
			, WD_REASON_CD    = #{noCldvRsnCd} 
			<if test='crgSt == "91"'>
			, WD_EDDT         = #{deliveryDt}
			</if>
			, WD_STATE_DT     = NOW()
			, UPD_NO          = #{updNo}
			, UPD_DT          = NOW()
		WHERE ORD_CHG_SQ = #{ordChgSq}
	</update>	
  		
	<!-- 주문변경상태 업데이트   -->
	<update id="updateTbOrderChangeDtlStat" parameterType="Delivery"  >
		/*TsbDelivery.updateTbOrderChangeDtlStat*/
		UPDATE TB_ORDER_CHANGE_DETAIL SET
			  CHG_STAT = #{chgStat}
			, UPD_NO   = #{updNo}
			, UPD_DT   = NOW()
		WHERE ORD_CHG_SQ = #{ordChgSq}
		  AND CHG_STAT  = 'G685_30'
		  AND DEL_YN    = 'N'
	</update>	
  		
	<!-- 주문변경 주문상세번호 조회        -->	
	<select id="getOrdChgDtlNoList" resultType="Delivery">
		/*TsbDelivery.getOrdChgDtlNoList*/
		SELECT ORD_CHG_SQ
		     , ORD_DTL_NO 
		  FROM TB_ORDER_CHANGE_DETAIL 
		 WHERE ORD_CHG_SQ = #{ordChgSq} 
		   AND CHG_STAT   = 'G685_30' 
		   AND DEL_YN     = 'N'
	</select>
	
	
	<!-- 배송추적 대상 조회             -->	
	<select id="getDelvTrackingList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getDelvTrackingList*/
		
		SELECT * 
		  FROM (
			SELECT 'O' AS GB
			     , A.INVOICE_NO AS INVOICENO
			     , (SELECT SWT_SHIP_COMP_CD FROM TB_SHIP_COMPANY C WHERE C.SHIP_COMP_CD = A.SHIP_COMP_CD) AS SWT_SHIP_COMP_CD
			     , A.SHIP_COMP_CD
			     , NULL AS ORD_CHG_SQ 
			  FROM TB_ORDER_DETAIL A 
			 WHERE A.INVOICE_NO IS NOT NULL 
			   AND A.INVOICE_NO != ''
			   AND A.ORD_DTL_STAT  = 'G013_50'--  배송중
			   AND NOT EXISTS (SELECT 1 FROM TB_ORDER_DETAIL_INVOICE B WHERE A.ORD_NO = B.ORD_NO AND A.ORD_DTL_NO = B.ORD_DTL_NO AND A.INVOICE_NO = B.INVOICE_NO AND B.SWT_TRC_SEND_YN ='Y')
			 GROUP BY A.INVOICE_NO, A.SHIP_COMP_CD   
			   
			UNION ALL 
			 
			SELECT 'W' AS GB
			     , A.WD_INVOICE_NO
			     , (SELECT SWT_SHIP_COMP_CD FROM TB_SHIP_COMPANY C WHERE C.SHIP_COMP_CD = A.SHIP_COMP_CD) AS SWT_SHIP_COMP_CD
			     , A.SHIP_COMP_CD
			     , A.ORD_CHG_SQ 
			  FROM TB_ORDER_CHANGE A
			  JOIN TB_ORDER_CHANGE_DETAIL B ON A.ORD_CHG_SQ = B.ORD_CHG_SQ AND B.DEL_YN ='N'
			 WHERE A.WD_INVOICE_NO IS NOT NULL 
			   AND A.WD_INVOICE_NO != ''
			   AND A.CHG_GB IN('G680_30','G680_40')   -- 반품요청 교환요청
			   AND A.SWT_TRC_SEND_YN = 'N'
			   AND A.WD_GB           = 'W'
			   AND B.CHG_STAT IN('G685_30') --  회수요청
			   AND A.REG_DT >= DATE_ADD(STR_TO_DATE(REPLACE( '2021-09-01','-','')+ 1, '%Y%m%d%H%i%s'), INTERVAL 0 DAY) 
			 GROUP BY A.WD_INVOICE_NO, A.SHIP_COMP_CD, A.ORD_CHG_SQ 
		 ) A WHERE SWT_SHIP_COMP_CD IS NOT NULL AND SWT_SHIP_COMP_CD != ''
	</select>
	
	
	<!-- 주문 배송추적요청 완료   -->
	<update id="updateSwtOrdInvcSendYn" parameterType="Delivery"  >
		/*TsbDelivery.updateSwtOrdInvcSendYn*/
		UPDATE TB_ORDER_DETAIL_INVOICE A SET
			  SWT_TRC_SEND_YN = 'Y'
			, UPD_NO          = #{updNo}
			, UPD_DT          = NOW()
		WHERE EXISTS (SELECT 1 FROM TB_ORDER_DETAIL B 
		                      WHERE B.ORD_NO = A.ORD_NO AND B.ORD_DTL_NO = A.ORD_DTL_NO AND B.INVOICE_NO = A.INVOICE_NO 
		                        AND B.INVOICE_NO   = #{invoiceno}
		                        AND B.SHIP_COMP_CD = #{shipCompCd} )
	</update>		
	
	<!-- 회수 배송추적요청 완료   -->
	<update id="updateSwtWdInvcSendYn" parameterType="Delivery"  >
		/*TsbDelivery.updateSwtWdInvcSendYn*/
		UPDATE TB_ORDER_CHANGE SET
			  SWT_TRC_SEND_YN = 'Y'
			, UPD_NO          = #{updNo}
			, UPD_DT          = NOW() 
		WHERE ORD_CHG_SQ = #{ordChgSq}
	</update>		
	
	<!-- 품절 사은품 재고 업데이트    -->
	<update id="updateTbFreegiftValSoldout" parameterType="Delivery" >
		/*TsbDelivery.updateTbFreegiftValSoldout*/
		UPDATE TB_FREEGIFT_VAL SET 
			  LEFT_QTY = 0
			, UPD_NO   = #{updNo}
			, UPD_DT   = NOW()
		WHERE PRODUCT_NO = #{productno}

	</update>	
	
	<!-- 품절대상 주문 목록 조회(일반,예약)         -->	
	<select id="getSoldoutOrderNoList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getSoldoutOrderNoList*/
		<![CDATA[
		SELECT ORD_NO
		  FROM (
			SELECT A.ORD_NO 
			  FROM TB_ORDER A 
			  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO 
			  JOIN TB_GOODS        C ON B.GOODS_CD = C.GOODS_CD 
			 WHERE B.ORD_DTL_STAT  = 'G013_20' -- 결재완료 
			   AND C.SELF_GOODS_YN = 'Y'       -- 자사 상품
			   AND B.ORD_EXCH_GB = 'O'
			   AND 2 <= FN_GET_BIZDAYS(DATE_FORMAT(A.ORD_DT, '%Y%m%d') , DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY ), '%Y%m%d'))
			   AND A.ORD_DT >= DATE_ADD(DATE_FORMAT('20210831160000','%Y%m%d%H%i%S') , INTERVAL 0 DAY)   -- 오픈 시점 날짜 세팅 후 주석풀기
	
			UNION ALL  
			 
			SELECT A.ORD_NO 
			  FROM TB_ORDER A 
			  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO 
			  JOIN TB_GOODS        C ON B.GOODS_CD = C.GOODS_CD 
			  JOIN TB_GOODS_RES_SELL D ON B.GOODS_CD = D.GOODS_CD 
			 WHERE B.ORD_DTL_STAT  = 'G013_20' -- 결재완료 
			   AND C.SELF_GOODS_YN = 'Y'       -- 자사 상품
			   AND D.USE_YN        = 'Y'
			   AND B.ORD_EXCH_GB = 'O'
			   AND D.DELV_RES_DT  < NOW()
			   AND 2 <= FN_GET_BIZDAYS(DATE_FORMAT(CASE WHEN  A.ORD_DT < D.DELV_RES_DT THEN D.DELV_RES_DT ELSE A.ORD_DT END, '%Y%m%d') , DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY ), '%Y%m%d'))
			   AND CASE WHEN  A.ORD_DT < D.DELV_RES_DT THEN D.DELV_RES_DT ELSE A.ORD_DT END  >= DATE_ADD(DATE_FORMAT('20210831160000','%Y%m%d%H%i%S') , INTERVAL 0 DAY)   -- 오픈 시점 날짜 세팅 후 주석풀기 
		) A 
		GROUP BY A.ORD_NO
		ORDER BY ORD_NO
		]]>
	</select>	
	
	<!-- 품절대상 주문상세 목록 조회(일반,예약)         -->	
	<select id="getSoldoutOrderDtlNoList" resultType="Delivery">
		/*TsbDelivery.getSoldoutOrderDtlNoList*/
		<![CDATA[
		SELECT 
				  A.ORD_NO 
				, B.ORD_DTL_NO 
				, A.CUST_NO 
				, A.ORD_NM 
				, A.ORD_PHNNO
				, D.PAY_GB 
				, D.PAY_MEANS
				, E.BANK_CD 
				, E.ACCOUNT_NM 
				, E.ACCOUNT_NO 
				, B.ORD_QTY - B.CNCL_RTN_QTY AS SALE_QTY
		  FROM TB_ORDER A
		  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO 
		  JOIN TB_GOODS        C ON B.GOODS_CD = C.GOODS_CD 
		  JOIN TB_PAYMENT      D ON A.ORD_NO = D.ORD_NO AND D.PAY_STAT = 'G016_30'
		  LEFT OUTER JOIN TB_CUST_ACCOUNT E ON A.CUST_NO = E.CUST_NO AND E.DEL_YN = 'N'	AND E.CUST_NO NOT IN(0)
		 WHERE A.ORD_NO = #{ordNo}
		   AND C.SELF_GOODS_YN = 'Y'      -- 자사상품
		   AND B.ORD_DTL_STAT = 'G013_20' -- 결제완료건 
		   AND NOT EXISTS (SELECT '1' FROM TB_GOODS_RES_SELL WHERE GOODS_CD = B.GOODS_CD AND USE_YN ='Y' AND DELV_RES_DT > DATE_ADD(DATE_FORMAT(CONCAT(STR_TO_DATE(NOW(), '%Y-%m-%d'),' 10:00:00'),'%Y%m%d%H%i%S') , INTERVAL -1 DAY)) -- 예약상품건 제외   
		   AND NOT EXISTS (SELECT 1 FROM TB_EXCHANGE_DELV_FAIL WHERE ORD_NO = B.ORD_NO AND ORD_DTL_NO= B.ORD_DTL_NO) 
		 ORDER BY B.ORD_DTL_NO	
		 ]]>
	</select>	
		
	
	<!-- 품절대상 출고예외 주문 목록 조회         -->	
	<select id="getSoldoutOrderExcNoList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getSoldoutOrderExcNoList*/
		<![CDATA[
		SELECT A.ORD_NO 
		  FROM TB_ORDER_DELIVERY_EXCEPTION A 
		  JOIN TB_ORDER_DELIVERY_EXCEPTION_ITEM B ON A.DELIVERY_EXCEPTION_SQ = B.DELIVERY_EXCEPTION_SQ 
		 WHERE A.COMPLTED_YN = 'N'
		   AND B.GIFT_YN     = 'N'
		   AND A.REG_DT >= DATE_ADD(DATE_FORMAT('20210901','%Y%m%d%H%i%S') , INTERVAL 0 DAY)
		 GROUP BY A.ORD_NO 
		 ]]>
	</select>
	
	<!-- 품절대상 출고예외 주문상세 목록 조회         -->
	<select id="getSoldoutOrderExcDtlNoList" resultType="Delivery">
		/*TsbDelivery.getSoldoutOrderExcDtlNoList*/
		SELECT 
			  A.ORD_NO 
			, B.ORD_DTL_NO
			, C.CUST_NO 
			, C.ORD_NM 
			, C.ORD_PHNNO
			, D.PG_GB 
			, D.PAY_MEANS 
			, E.BANK_CD
			, E.ACCOUNT_NM 
			, E.ACCOUNT_NO 
			, B.EXCEPTION_QTY AS SALE_QTY 
		  FROM TB_ORDER_DELIVERY_EXCEPTION A 
		  JOIN TB_ORDER_DELIVERY_EXCEPTION_ITEM B ON A.DELIVERY_EXCEPTION_SQ = B.DELIVERY_EXCEPTION_SQ 
		  JOIN TB_ORDER                         C ON A.ORD_NO = C.ORD_NO 
		  JOIN TB_PAYMENT                       D ON A.ORD_NO = D.ORD_NO   AND D.PAY_STAT = 'G016_30'
		  LEFT OUTER JOIN TB_CUST_ACCOUNT       E ON C.CUST_NO = E.CUST_NO AND E.DEL_YN = 'N' AND E.CUST_NO NOT IN(0)	
		  WHERE A.COMPLTED_YN = 'N'
		   AND B.GIFT_YN      = 'N'
		   AND A.ORD_NO       = #{ordNo}
		   AND NOT EXISTS (SELECT 1 FROM TB_EXCHANGE_DELV_FAIL WHERE ORD_NO = A.ORD_NO AND ORD_DTL_NO= B.ORD_DTL_NO) 
		  GROUP BY A.ORD_NO, B.ORD_DTL_NO, C.CUST_NO, C.ORD_NM, D.PG_GB, D.PAY_MEANS, E.BANK_CD, E.ACCOUNT_NM, E.ACCOUNT_NO, B.EXCEPTION_QTY 
	</select>	
	
	<!-- 품절대상 회수예외 주문 목록 조회         -->	
	<select id="getSoldoutOrderRecallNoList" resultType="Delivery" timeout="600">
		/*TsbDelivery.getSoldoutOrderRecallNoList*/
		SELECT A.ORDER_NO AS ORD_NO
		  FROM TB_ORDER_RECALL_EXCEPTION A 
		  JOIN TB_ORDER_RECALL_EXCEPTION_ITEM B ON A.RECALL_EXCEPTION_NO = B.RECALL_EXCEPTION_NO 
		 WHERE B.REASON_CODE IN ('08','10')
		   AND A.RECALL_STAT ='P'
		   AND NOT EXISTS (SELECT 1 FROM TB_EXCHANGE_DELV_FAIL WHERE ORD_NO = A.ORDER_NO AND ORD_DTL_NO= B.ORDER_DTL_NO) 
		 GROUP BY A.ORDER_NO 
	</select>
		
	<!-- 품절대상 회수예외 주문상세 목록 조회         -->
	<select id="getSoldoutOrderRecallDtlNoList" resultType="Delivery">
		/*TsbDelivery.getSoldoutOrderRecallDtlNoList*/
		SELECT 
			  A.ORDER_NO     AS ORD_NO
			, B.ORDER_DTL_NO AS ORD_DTL_NO 
			, C.CUST_NO 
			, C.ORD_NM 
			, C.ORD_PHNNO
			, D.PG_GB 
			, D.PAY_MEANS 
			, E.BANK_CD
			, E.ACCOUNT_NM 
			, E.ACCOUNT_NO 
			, B.EXCEPTION_QTY AS SALE_QTY 
		  FROM TB_ORDER_RECALL_EXCEPTION A 
		  JOIN TB_ORDER_RECALL_EXCEPTION_ITEM B ON A.RECALL_EXCEPTION_NO = B.RECALL_EXCEPTION_NO 
		  JOIN TB_ORDER                         C ON A.ORDER_NO = C.ORD_NO 
		  JOIN TB_ORDER_DETAIL                 OD ON A.ORDER_NO = OD.ORD_NO AND B.ORDER_DTL_NO = OD.ORD_DTL_NO AND OD.ORD_DTL_STAT NOT IN('G013_99')
		  JOIN TB_PAYMENT                       D ON A.ORDER_NO = D.ORD_NO   AND D.PAY_STAT = 'G016_30'
		  LEFT OUTER JOIN TB_CUST_ACCOUNT       E ON C.CUST_NO = E.CUST_NO   AND E.DEL_YN = 'N' AND E.CUST_NO NOT IN(0)
		 WHERE B.REASON_CODE IN ('08','10')
		   AND A.RECALL_STAT ='P'
		   AND NOT EXISTS (SELECT 1 FROM TB_EXCHANGE_DELV_FAIL WHERE ORD_NO = A.ORDER_NO AND ORD_DTL_NO= B.ORDER_DTL_NO) 
		   AND A.ORDER_NO = #{ordNo}
	</select>
	
	<!-- 출고예외 처리 완료    -->
	<update id="updateTbOrderDeliveryException" parameterType="Delivery" >
		/*TsbDelivery.updateTbOrderDeliveryException*/
		UPDATE TB_ORDER_DELIVERY_EXCEPTION SET 
			  COMPLTED_YN = 'Y'
			, UPD_NO      = #{updNo}
			, UPD_DT      =  NOW()
		WHERE COMPLTED_YN = 'N'
		  AND ORD_NO      = #{ordNo}
	</update>	
	
	<!-- 회수예외 처리 완료    -->
	<update id="updateTbRecallException" parameterType="Delivery" >
		/*TsbDelivery.updateTbRecallException*/
		UPDATE TB_ORDER_RECALL_EXCEPTION SET
			  RECALL_STAT    = 'S'
			, RECALL_STAT_DT = NOW()
		WHERE RECALL_STAT ='P'
		  AND ORDER_NO = #{ordNo}
	</update>	
		
	<!-- 교환상품 출고예외등록    -->
	<insert id="insertTbExchangeDelvFail" parameterType="Delivery" keyProperty="exchangeDelvFailSq" >
		/*TsbDelivery.insertTbExchangeDelvFail*/
		INSERT INTO TB_EXCHANGE_DELV_FAIL
		(
			  EXCHANGE_DELV_FAIL_SQ
			, ORD_NO	 			--	주문번호
			, ORD_DTL_NO	 		--	주문상세번호
			, ORD_CHG_SQ	 		--	변경요청번호
			, ORD_QTY	 			--	주문수량(출고가능수량)
			, CNCL_RTN_QTY	 		--	취소수량(미출고수량)
			, DELV_FAIL_REASON		--	출고실패사유
			, DEL_YN
			, REG_NO	 			--	등록자 NO
			, REG_DT	 			--	등록일
			, UPD_NO	 			--	수정자 NO
			, UPD_DT	 			--	수정일
		
		)
		VALUES
		(
			  #{exchangeDelvFailSq}	
			, #{ordNo} 	 			--	주문번호
			, #{ordDtlNo}	 		--	주문상세번호
			, (SELECT MAX(C.ORD_CHG_SQ) FROM TB_ORDER_CHANGE_DETAIL C WHERE C.CHG_ORD_DTL_NO = #{ordDtlNo})	--	변경요청번호
			, #{ordQty}	 			--	주문수량(출고가능수량)
			, #{cnclRtnQty}	 		--	취소수량(미출고수량)
			, '재고부족'				--	출고실패사유
			, 'N' 
			, #{regNo}	 			--	등록자 NO
			, NOW()	 				--	등록일
			, #{regNo}	 			--	수정자 NO
			, NOW()	 				--	수정일
		)		
	</insert>
	
	<!-- 자동 품절처리    -->
	<update id="updateSoldOut" parameterType="Delivery" >
		/*TsbDelivery.updateSoldOut*/
		 UPDATE TB_ORDER_DETAIL SET
			   SOLDOUT_YN     = 'Y'
			 , SOLDOUT_MEMO   = #{soldoutMemo}
			 , SOLDOUT_REG_NO = #{updNo}
			 , SOLDOUT_REG_DT = NOW()
			 , UPD_NO         = #{updNo}
			 , UPD_DT         = NOW()
		 WHERE ORD_NO     = #{ordNo} 
		   AND ORD_DTL_NO = #{ordDtlNo}
	</update>	
		
	<!-- 주문변경정보 조회          -->
	<select id="getOrderChangeDetailInfo" resultType="OrderChange">
		/*TsbDelivery.getOrderChangeDetailInfo*/
		SELECT OC.ORD_CHG_SQ
		     , OD.ORD_NO
		     , OCD.ORD_DTL_NO
		     , OCD.CHG_QTY
		     , O.CUST_NO
		     , O.ORD_NM
		     , O.ORD_PHNNO
		     , OC.CHG_GB
		     , OC.CHG_REASON
		     , CASE WHEN OC.CHG_GB = 'G680_20' THEN FN_GET_CODE_NM('G686', OC.CHG_REASON)
		            WHEN OC.CHG_GB = 'G680_30' THEN FN_GET_CODE_NM('G688', OC.CHG_REASON)
		            WHEN OC.CHG_GB = 'G680_40' THEN FN_GET_CODE_NM('G689', OC.CHG_REASON)
		            ELSE '결제전취소'
		        END                                       AS CHG_REASON_NM
		  FROM TB_ORDER_CHANGE OC
		 INNER JOIN TB_ORDER_CHANGE_DETAIL OCD ON OC.ORD_CHG_SQ = OCD.ORD_CHG_SQ
		 INNER JOIN TB_ORDER_DETAIL OD         ON OCD.ORD_DTL_NO = OD.ORD_DTL_NO
		 INNER JOIN TB_ORDER O                 ON OD.ORD_NO = O.ORD_NO
		 WHERE OC.ORD_CHG_SQ =  #{ordChgSq}
	</select>		
	
	<!-- 주문상세단품 SQ 조회          -->
	<select id="getOrdDtlItemSq" resultType="Delivery">
		/*TsbDelivery.getOrdDtlItemSq*/
		SELECT  ORD_DTL_ITEM_SQ
		  FROM TB_ORDER_DETAIL_ITEM 
		WHERE ORD_DTL_NO = #{orderdtlno}
		  AND PRODUCT_NO = #{productno}
		  AND OPT_CD     = #{skucode}
	</select>	
	
	<!-- 교환 출고예외 조회        -->
	<select id="getChgDelvExcList" resultType="Delivery">
		/*TsbDelivery.getChgDelvExcList*/
			SELECT 
				  ORD_NO
				, ORD_DTL_NO
				, MAX(ORD_QTY) AS ORD_QTY
				, MAX(CNCL_RTN_QTY) AS CNCL_RTN_QTY
			FROM (
						SELECT 
							  A.ORD_NO 
							, B.ORD_DTL_NO 
							, C.ORD_QTY - C.CNCL_RTN_QTY AS ORD_QTY
							, B.EXCEPTION_QTY   -- AS CNCL_RTN_QTY
							, (C.ORD_QTY - C.CNCL_RTN_QTY) - TRUNCATE((((C.ORD_QTY - C.CNCL_RTN_QTY) * D.ITEM_QTY) -  B.EXCEPTION_QTY) / D.ITEM_QTY,1)   AS CNCL_RTN_QTY
						  FROM TB_ORDER_DELIVERY_EXCEPTION      A
						  JOIN TB_ORDER_DELIVERY_EXCEPTION_ITEM B ON A.DELIVERY_EXCEPTION_SQ = B.DELIVERY_EXCEPTION_SQ 
						  JOIN TB_ORDER_DETAIL                  C ON A.ORD_NO = C.ORD_NO AND B.ORD_DTL_NO = C.ORD_DTL_NO 
						  JOIN TB_ORDER_DETAIL_ITEM             D ON C.ORD_DTL_NO =  D.ORD_DTL_NO AND B.SKU_CODE = D.OPT_CD 
						 WHERE   A.ORD_NO = #{orderno}
						   AND B.GIFT_YN = 'N'
						   AND C.ORD_EXCH_GB = 'E'
			) A 
			GROUP BY ORD_NO, ORD_DTL_NO 
	</select>			
	
	<!-- 교환 회수예외 조회        -->
	<select id="getChgRecallExcList" resultType="Delivery">
		/*TsbDelivery.getChgRecallExcList*/
			SELECT 
			  C.ORD_NO 
			, C.ORD_DTL_NO 
			, C.ORD_QTY - C.CNCL_RTN_QTY  AS ORD_QTY
			, B.EXCEPTION_QTY AS CNCL_RTN_QTY 
		  FROM TB_ORDER_RECALL_EXCEPTION A 
		  JOIN TB_ORDER_RECALL_EXCEPTION_ITEM B ON A.RECALL_EXCEPTION_NO = B.RECALL_EXCEPTION_NO 
		  JOIN TB_ORDER_DETAIL                C ON A.ORDER_NO = C.ORD_NO AND B.ORDER_DTL_NO = C.ORD_DTL_NO 
		 WHERE A.ORDER_NO  = #{orderno}
		   AND B.REASON_CODE IN ('08','10')
		   AND C.ORD_EXCH_GB = 'E'
	</select>		

	<!-- 주문변경정보  조회 -->	
	<select id="getOrdchgSqInfo" resultType="Delivery">
		/*TsbDelivery.getOrdchgSqInfo*/
		SELECT CHG_GB
		     , WD_GB 
		     , WD_BF_SEND_YN 
		  FROM TB_ORDER_CHANGE
		 WHERE ORD_CHG_SQ   = #{ordChgSq}
	</select>
	
	<!-- 주문상세번호 조회 -->	
	<select id="getOrdDtlno2" resultType="Delivery">
		/*TsbDelivery.getOrdDtlno2*/
		SELECT DISTINCT ORD_DTL_NO 
		  FROM TB_ORDER_DETAIL_ITEM A 
		  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO AND A.ORD_DTL_NO = B.ORD_DTL_NO 
		 WHERE ORD_NO     = #{orderno}
		   AND PRODUCT_NO = #{productno}
		   AND OPT_CD     = #{skucode}
		   AND B.ORD_DTL_STAT IN ('G013_50','G013_55','G013_60','G013_70')
	</select>
	
	<!-- 배송출발 알림문구 조회  -->	
	<select id="getDeliveryStart" resultType="Delivery">
		/*TsbDelivery.getDeliveryStart*/
		SELECT
			  A.ORD_NO 
			, A.CUST_NO
			, A.ORD_PHNNO 
			, A.ORD_NM 
			, (SELECT GOODS_NM FROM TB_GOODS WHERE GOODS_CD= MAX(B.GOODS_CD))  AS GOODS_NM
			, COUNT(B.GOODS_CD) -1 AS GOODS_CNT
		  FROM TB_ORDER A
		  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO 
		 WHERE A.ORD_NO = #{orderno}
		   AND B.ORD_DTL_STAT ='G013_50'
		   AND NOT EXISTS (SELECT C.ORDER_DTL_NO FROM TB_ORDER_RECALL_EXCEPTION_ITEM C WHERE C.ORDER_DTL_NO = B.ORD_DTL_NO AND C.REASON_CODE IN('09','11') AND C.EXCEPTION_QTY = (B.ORD_QTY - B.CNCL_RTN_QTY))
		 GROUP BY A.ORD_NO, A.CUST_NO, A.ORD_PHNNO, A.ORD_NM  
	</select>	
	
	<!-- 회수시작 알림문구 조회  -->	
	<select id="getWithdrawStart" resultType="Delivery">
		/*TsbDelivery.getWithdrawStart*/
		SELECT
			  D.ORD_NO 
			, D.CUST_NO 
			, A.CHGER_PHNNO AS ORD_PHNNO
			, A.CHGER_NM    AS ORD_NM
			, CONCAT(A.CHGER_BASE_ADDR ,' ',A.CHGER_DTL_ADDR)                  AS CHGER_BASE_ADDR 
			, (SELECT GOODS_NM FROM TB_GOODS WHERE GOODS_CD= MAX(C.GOODS_CD))  AS GOODS_NM
			, COUNT(C.GOODS_CD) -1                                             AS GOODS_CNT
		  FROM TB_ORDER_CHANGE A
		  JOIN TB_ORDER_CHANGE_DETAIL B ON A.ORD_CHG_SQ = B.ORD_CHG_SQ 
		  JOIN TB_ORDER_DETAIL C        ON B.ORD_DTL_NO = C.ORD_DTL_NO 
		  JOIN TB_ORDER        D        ON C.ORD_NO     = D.ORD_NO 
		 WHERE A.ORD_CHG_SQ = #{orderexceptionno}
		   AND B.DEL_YN ='N'
		 GROUP BY D.ORD_NO, D.CUST_NO, A.CHGER_PHNNO, A.CHGER_NM, A.CHGER_BASE_ADDR, A.CHGER_DTL_ADDR 
	</select>	
		
	<!-- 주문상세번호 조회 -->	
	<select id="getOrderDtlno" resultType="Delivery">
		/*TsbDelivery.getOrderDtlno*/
		SELECT DISTINCT ORD_DTL_NO 
		  FROM TB_ORDER_DETAIL_ITEM A 
		  JOIN TB_ORDER_DETAIL B ON A.ORD_NO = B.ORD_NO AND A.ORD_DTL_NO = B.ORD_DTL_NO 
		 WHERE ORD_NO     = #{orderno}
		   AND PRODUCT_NO = #{productno}
		   AND OPT_CD     = #{skucode}

	</select>
	
</mapper>