Advertisement
henikseptiana15

f_get_product_balance_stock_exclude_reserved

May 27th, 2021
1,223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. CREATE OR REPLACE FUNCTION f_get_product_balance_stock_exclude_reserved(bigint, bigint, bigint)
  2.   RETURNS numeric AS
  3. $BODY$
  4. DECLARE
  5.     pTenantId       alias for $1;
  6.     pProductId      alias for $2;
  7.     pOuId           alias for $3;
  8.  
  9.     vResult         numeric;
  10.    
  11. BEGIN
  12.  
  13.     vResult := 0;
  14.  
  15.     IF EXISTS (SELECT 1
  16.                 FROM in_product_balance_stock A
  17.                     INNER JOIN m_warehouse_ou B ON A.warehouse_id = B.warehouse_id
  18.                 WHERE A.tenant_id = pTenantId AND
  19.                     A.product_id = pProductId AND
  20.                     B.ou_id = pOuId AND
  21.                     A.product_status =  'GOOD') THEN
  22.            
  23.         WITH data_product_balance_stock AS(
  24.             SELECT SUM(A.qty) AS qty_product_balance_stock, A.product_id, B.ou_id, A.tenant_id, A.product_status
  25.             FROM in_product_balance_stock A
  26.             INNER JOIN m_warehouse_ou B ON A.warehouse_id = B.warehouse_id
  27.             WHERE A.tenant_id = pTenantId
  28.                 AND A.product_id = pProductId
  29.                 AND B.ou_id = pOuId
  30.                 AND A.product_status = 'GOOD'
  31.             GROUP BY A.product_id, B.ou_id, A.tenant_id, A.product_status
  32.            
  33.         ), data_product_balance_stock_reserved AS(
  34.             SELECT SUM(A.qty) AS qty_product_balance_stock_reserved, A.product_id, A.ou_id, A.tenant_id, A.product_status
  35.             FROM in_product_balance_stock_reserved A
  36.             WHERE A.tenant_id = pTenantId
  37.                 AND A.product_id = pProductId
  38.                 AND A.ou_id = pOuId
  39.                 AND A.product_status = 'GOOD'
  40.             GROUP BY A.product_id, A.ou_id, A.tenant_id, A.product_status
  41.         )
  42.        
  43.         SELECT (SUM(A.qty_product_balance_stock) - SUM(COALESCE(B.qty_product_balance_stock_reserved, 0))) AS stock_product INTO vResult
  44.         FROM data_product_balance_stock A
  45.             LEFT OUTER JOIN data_product_balance_stock_reserved B
  46.                 ON A.product_id = B.product_id AND A.tenant_id = B.tenant_id AND A.product_status = B.product_status
  47.         WHERE A.tenant_id = pTenantId
  48.             AND A.product_id = pProductId
  49.             AND A.ou_id = pOuId
  50.             AND A.product_status = 'GOOD';
  51.        
  52.     END IF;
  53.    
  54.     return vResult;
  55. END;
  56. $BODY$
  57.   LANGUAGE plpgsql VOLATILE
  58.   COST 100;
  59.   /
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement