-- 仮受注データ削除

CREATE OR REPLACE FUNCTION f_upd_preorder(
    IN _ordermember integer
    )  RETURNS integer
    AS
$$
DECLARE
    _rec RECORD;
    _s varchar(4000);
BEGIN

    -- ordermemberがNOT NULLの場合は、ordermemberを見て処理を行う
    IF _ordermember IS NOT NULL THEN
        -- 仮受注
        _s := 'SELECT * FROM t_order_title WHERE ordermember = ' || _ordermember || ' AND preorderflg = TRUE;';
        FOR _rec IN EXECUTE _s LOOP

            -- 受注見出し
            UPDATE t_order_title set delflg = TRUE WHERE orderno = _rec.orderno;
            -- 受注明細
            UPDATE t_order_detail set delflg = TRUE WHERE orderno = _rec.orderno;
            -- 入金
            UPDATE t_deposit set delflg = TRUE WHERE orderno = _rec.orderno;
            -- 出荷
            UPDATE t_forward_detail set delflg = TRUE WHERE orderno = _rec.orderno;
            -- DL受注
            UPDATE t_dl_order set delflg = TRUE WHERE orderno = _rec.orderno;

        END LOOP;

    ELSE
    -- ordermemberがNULLの場合は、adddateを見て処理を行う
        -- 仮受注
        _s := 'SELECT * FROM t_order_title WHERE preorderflg = TRUE AND adddate <= CURRENT_TIMESTAMP + \'-1 hours\';';
        FOR _rec IN EXECUTE _s LOOP

            -- 受注見出し
            UPDATE t_order_title set delflg = TRUE WHERE orderno = _rec.orderno;
            -- 受注明細
            UPDATE t_order_detail set delflg = TRUE WHERE orderno = _rec.orderno;
            -- 入金
            UPDATE t_deposit set delflg = TRUE WHERE orderno = _rec.orderno;
            -- 出荷
            UPDATE t_forward_detail set delflg = TRUE WHERE orderno = _rec.orderno;
            -- DL受注
            UPDATE t_dl_order set delflg = TRUE WHERE orderno = _rec.orderno;
            --RAISE NOTICE 'orderno : % ', _rec.orderno;

        END LOOP;

    END IF;
    RETURN 1;
END;
$$
LANGUAGE 'plpgsql' VOLATILE;

