2013年5月27日 星期一

標準 SAP 原則上 [評價] 是依據 [工廠] 層級



Purpose

The purpose of this page is to describe the main customizing settings for Account Determination.

Overview

For every goods movement created for a valuated material, the SAP system can create two types of documents:
a material document and an accounting document.

The SAP system follows the accounting principle that for every material movement, there is a corresponding document that provides details of that movement.
In addition, an accounting document is produced that describes the financial aspects of the goods movement.
The material document and accounting (FI) document creation depend on the movement type configuration.
Through the movement type configuration and based on the customizing settings defined for the account determination the SAP System can do automatic account postings.
To determine the customizing settings for Account Determination you should GO through the following customizing path: SPRO -> IMG -> Materials Management -> Valuation and Account Assignment -> Account Determination. 
  
Below sections describe the two ways to define the account determination: Account Determination Wizard and Account Determination without Wizard. 

Account Determination Wizard

It is a proposal from SAP System to define the account determination.
In this step, you can quickly configure the system to make automatic postings by answering the wizard's questions. The wizard undertakes the functions of the following steps:
1. Defining valuation control
2. Grouping valuation areas
3. Defining valuation classes
4. Defining account grouping for movement types
5. Purchase account management
6. Configuring automatic postings
You can continue to use these transactions either in conjunction with or instead of the wizard. 

Account Determination Without Wizard

In this step, you can manually define the settings for account determination in Inventory Management and Invoice Verification.
Account determination without the wizard enables you to make a more complex configuration than account determination with the wizard, but requires that you are already familiar with the principle of automatic account determination in the ERP System.
You can configure account determination with the wizard in the first instance, for example. Then, if the wizard does not meet your company's account determination requirements, you can work without it.
You have to work without the wizard if you use the material ledger (this is standard).
  • Define Valuation Control
It can be configured by the following customizing path:
SPRO -> IMG ->
Materials Management ->
Valuation and Account Assignment ->
Account Determination ->
Account Determination without Wizard->
Define Valuation Control
.
 It defines if the valuation areas will be grouped by activating the valuation grouping code. This makes the configuration of automatic postings much easier.
In the standard SAP R/3 System, the valuation grouping code is set to active as default setting.
Firstly, you should create the valuation grouping code.
It corresponds to the transaction OMWM.
OMWM - Valuation Control

  • Group together Valuation Areas
It can be configured by the following customizing path:
SPRO -> IMG ->
Materials Management ->
Valuation and Account Assignment ->
Account Determination ->
Account Determination without Wizard->
Group together Valuation Areas.
In this step, you assign valuation areas to a valuation grouping code.
Valuation area corresponds to the organization level in which the valuation will occur.
Or the valuation occurs at the plant level or it occurs at the company code level.
如果不同的 [評價區域]
對應相同的 [評價集合碼]
就會有相同規則產生 [會計科目]

The valuation grouping code makes it easier to set automatic account determination.
Within the chart of accounts, you assign the same valuation grouping code to the valuation areas you want to assign to the same account.

The chart of account is a list of accounts.
Within a chart of accounts, you can use the valuation grouping code:
  • to define individual account determination for certain valuation areas (company codes or plants)
Example:
[評價區域]
The valuation areas 0001 and 0002 are assigned to company codes which use the same chart of accounts.

For both valuation areas, however, you would like to define a different account determination.
You must assign different valuation grouping codes (for example, 0011 and 0022) to both valuation areas. 
  • to define common account determination for several valuation areas (company codes or plants)
Example:
Valuation areas 0003 and 0004 are assigned to company codes which use the same chart of accounts. Account assignment for both valuation areas should be similar.
You assign the same valuation grouping code (for example, 0033) to both valuation areas. Thus, you only have to define account assignment for both valuation areas once. 
Requirements:  
  • You must have activated the valuation grouping code in the step Define valuation control (OMWM). 
  • You must have defined the valuation level in corporate structure Customizing. The valuation level is defined in transaction OX14 where you should decide if the valuation will occur at the plant level or company code level. 
  • You must have assigned each plant to a company code in "Enterprise structure" into the Customizing. When assigning your plants, the valuation areas are defined automatically. To assign a plant to company code you should go to transaction OX18. 
OX14 - Define Valuation Level
Recommendation:
SAP recommends that you only use a valuation grouping code within a chart of accounts in order to prevent account determination from becoming confusing. 
Default settings
標準 SAP 原則上 [評價] 是依據 [工廠] 層級

(白話文 不同工廠有不同加權平均成本) 
In the standard SAP system, valuation is predefined at plant level.
All plants are grouped together via valuation grouping code 0001.         
Group together Valuation Areas corresponds to the transaction OMWD.  
OMWD - Account Determination for Valuation Areas

  • Define Valuation Classes
It can be configured by the following customizing path:
SPRO ->
IMG ->
Materials Management ->
Valuation and Account Assignment ->
Account Determination ->
Account Determination without Wizard->
Define Valuation Classes.
In this step, you define which valuation classes are allowed for a material type.
If an user creates a material, he/she must enter the material's valuation class in the accounting data (Accounting 1 and 2 views). The ERP system uses your default settings to check whether the valuation class is allowed for the material type.
 [評價分類] 是將對應同一 [會計科目] 的 [材料]  結合
The valuation class is a key to group materials with the same account determination. 
The valuation classes depend on the material type. 
 多個 [評價分類可對應一個  [材料型式
 一個 [評價分類] 可對應多個  [材料型式
Several valuation classes are generally allowed for one material type.
A valuation class can also be allowed for several material types.
The valuation class determines the G/L accounts which will be updated as result of the goods movement generated for the material.
The valuation class makes it possible to: 因此
同一 [材料型式] 對應不同 [會計科目
不同 [材料型式] 對應同一 [會計科目
  • Post the stock values of materials of the same material type to different G/L accounts
  • Post the stock values of materials of different material types to the same G/L account 
MM03 - Display - Acoount 1 view

The link between the valuation classes and the material types is set up via the account category reference.
The account category reference is a combination of valuation classes. Precisely one account category reference is assigned to a material type.
Requirements
  • You must have defined your material types.
  • You must have defined the chart of accounts.
  • You must have agreed with Financial Accounting which materials are assigned to which accounts.
Default settings
In the standard SAP R/3 System, an account category reference is created for each material type. The account category reference is, in turn, assigned to precisely one valuation class. This means that each material type has its own valuation class. 
OMSK – Account Category reference/valuation class
OMSK – Account category reference button

OMSK - Valuation Class Button

OMSK - Material Type/Account category reference

   
  • Define Account Grouping (account modifier) for Movement Types
Using this function, you can assign an account grouping to movement types. The account grouping is a finer subdivision of the transaction/event keys for the account determination.
The account grouping is provided for the following transactions keys:
  • GBB (offsetting entry for inventory posting)
  • PRD (price differences)
  • KON (consignment liabilities)
The account grouping in the standard system is only active for transaction key GBB (offsetting entry for inventory posting). 
OMWN - Define Account Grouping for Movement Types 
  • Purchase Account Management
It is used to attend legal requirement from specific countries (France, Italy, Finland, Belgium, Spain and Portugal). In this step, you will define a specific valuation and a separate accounting document for Purchase Order postings. 
  • Configure Automatic postings
In this step, you enter the system settings for Inventory Management and Invoice Verification transactions for automatic postings to G/L accounts.
You can then check your settings using a simulation function.
What are automatic postings?
Postings are made to G/L accounts automatically in the case of Invoice Verification and Inventory Management transactions relevant to Financial and Cost Accounting. 
Example:
Posting lines are created in the following accounts in the case of a goods issue for a cost center:
  • Stock account
  • Consumption account 
How does the system find the relevant accounts?
When entering the goods movement, the user does not have to enter a G/L account, since the ERP system automatically finds the accounts for each posting based on the following data: 
  • Chart of accounts of the company code
If the user enters a company code or a plant when entering a transaction, the ERP system determines the chart of accounts which is valid for the company code.
You must define the automatic account determination individually for each chart of accounts. 
  • Valuation grouping code of the valuation area
You must define the automatic account determination individually for every valuation grouping code within a chart of accounts. It applies to all valuation areas which are assigned to this valuation grouping code.
If the user enters a company code or a plant when entering a transaction, the system determines the valuation area and the valuation grouping code. 
  • Transaction/event key
You do not have to define these transaction keys, they are determined automatically from the transaction (invoice verification) or the movement type (inventory management). In this step, you can only insert the account number for each transaction key. 
  • Account grouping (modifier) (only for GBB, PRD and KOM)
Since the transaction key GBB is used for different transactions (for example, goods issue, scraping, physical inventory), which are assigned to different accounts (for example, consumption account, scrapping, expense/income from inventory differences), it is necessary to divide the posting transaction according to a further key: account grouping code. 
  • Valuation class of material or (in case of split valuation) the valuation type
The valuation class allows you to define automatic account determination that is dependent on the material.
You can achieve this by assigning different valuation classes to the materials and by assigning different G/L accounts to the transaction key for every valuation class. 
Default settings:
G/L account assignments for the charts of accounts INT and the valuation grouping code 0001 are SAP standard.  
OMWB - Configure Automatic Postings

OBYC - Maintain FI configuration 










How to test my account determination settings? 
You should go to transaction OMWB and click on ‘simulation’ button. Then, insert the affected material, the correspondent plant and the movement type. After that, click on ‘account assignments’ button and you will see the simulation’s result.
OMWB - Simulation






Important:      
Report DFKB1INT: run it in transaction SE38. It is used to shows us the possible values for the account determination customizing settings. If the customer changed something here, it is not standard anymore. 

2013年5月26日 星期日

勇敢的轉機 交換生的Blog

勇敢的轉機
交換生的Blog

最划算的約旦航空單程飛機票18000
http://toscany19.pixnet.net/blog/post/32230280

2012/05/31 記錄(推估2012/05/30開票)
昨天終於開票了!!!
2012.9.25約旦航空
  日  期     時 間  航 班                                     其  他  訊  息
------------ ------------------------------------------------- --------------------------------
國泰航空(CX-0565)                                飛行01小時45分  /直飛
 09月25日(二) 14:05 出發:台北(桃園)(TAIWAN TAOYUAN)                  航站1/經濟(S)/機位OK
                          15:50 抵達:香港(HONG KONG INTL AIRPORT)          航站1/波音777-300     /點心
------------ ------------------------------------------------- --------------------------------
約旦航空(RJ-0183)                                飛行12小時40分  /中間停1站
 09月25日(二) 21:35 出發:香港(HONG KONG INTL AIRPORT)                航站2/經濟(S)/機位OK
 09月26日(三) 05:15 抵達:安曼(AMMAN QUEEN ALIA INTL AIRPORT)   航站1/空中巴士A330-200/餐點
------------ ------------------------------------------------- --------------------------------
約旦航空(RJ-0125)                                飛行06小時30分  /中間停1站
 09月26日(三) 09:45 出發:安曼(AMMAN QUEEN ALIA INTL AIRPORT)   航站1/經濟(S)/機位OK
                         15:15 抵達:慕尼黑(MUNICH FRANZ J STRAUSS APT)    航站1/空中巴士A320-100/午餐
最划算的約旦航空單程飛機票18000

2013年5月1日 星期三

給要去德國奧地利的朋友預估金額

參考很厲害的海外服務
不及納髮所醫生替代役

http://cooltree.pixnet.net/blog/post/23429096

給要去德國奧地利的朋友預估金額
奧地利每天要 2000元=50歐元
就是每月需要 60,000元=1500歐元
就是每年需要 72萬元=1.8萬歐元
.......
另外 每月宿舍350 + 50歐元 * 12 = 4800歐元
另外 來回機票1000 + 500 歐元 * 2 = 3000歐元
......


30天開銷統計:
 
泰航機票:31200
YH卡:600
德國國鐵7天:6780
兌換歐元:33900+6003     (換得1010.00 EUR)
兌換美元:13662              (換得 414.00 USD)
簽證費用:1800+1440
特殊購買:240
總計:95625
回國剩餘:10250 (以1:41的匯率計算)
硬幣紙鈔收集:1035

出國總共開銷:85375   (含錢幣收集)


平均每日開銷:1698 (扣掉機票and簽證)
========================另外還有每日詳細記載的帳目==========================
歐元以(1:40)計算,捷克克朗以(1:1.5)計算
Whole tour in Europe (30 nights):56692.7 NTD
Daily Avg:1889.8 NTD


Regionally:

      Germany(1) (5 nights):218.02 EUR =  8720.8 NTD    Daily Avg:1744.2 NTD
Czech Republic (8 nights): 10224 CZK = 15336.0 NTD    Daily Avg:1917.0 NTD
             Austria (9 nights):432.86 EUR = 17314.4 NTD    Daily Avg:1923.8 NTD
     Germany(2) (8 nights):383.04 EUR = 15321.5 NTD    Daily Avg:1915.2 NTD
            Switzerland (0 nights):  0.00 CHF =     0.0 NTD    Daily Avg:      0.0 NTD

Separately:
 Charge of accommodation:               19375.2 NTD    Daily Avg: 645.8 NTD
   Fare of traffic (incl. ship & card):   15490.5 NTD    Daily Avg: 516.4 NTD
         Spending of food:                       9870.5 NTD    Daily Avg: 329.0 NTD

2012年11月12日 星期一

XXAPSP0058_PKG

PACKAGE BODY xxapsp0058_pkg
IS
/*************************************************************************************
     NAME:     XXAPSP0058_PKG.  GET_WHEREUSE
     PURPOSE:  1. XXAPSP0058 ON HANDS
     REVISIONS:
     Ver        Date        Author           Description
     ---------  ----------  ---------------  ------------------------------------
     1.0        2012/11/11  Albert           1. Created this Package.
*************************************************************************************/
   PROCEDURE main (
      errbuf    OUT   VARCHAR2,
      retcode   OUT   VARCHAR2,
      --    P_BU                    VARCHAR2 , --remove this paramenter form user request(once for all)
      --    P_EMS                   VARCHAR2 , --(same with above)
      --    P_PRODUCT_LINE          VARCHAR2 , --(same with above)
      p_oh            VARCHAR2,                                        --'Y/N'
      p_so            VARCHAR2,                                        --'Y/N'
      p_wip           VARCHAR2,                                        --'Y/N'
      p_po            VARCHAR2,                                        --'Y/N'
      p_mds           VARCHAR2                                         --'Y/N'
   )
   IS
      CURSOR c_so
      IS
         SELECT /*+PARALLEL */
                TRUNC(sn.promise_date+1,'DAY'),
                sn.inventory_item_id, mp.organization_id,
                a.segment1 AS inventory_item,
                   oh.order_number
                || '-'
                || ol.line_number
                || '.'
                || shipment_number AS order_number,
                (NVL (sn.ordered_quantity, 0) - NVL (sn.shipped_quantity, 0)
                ) AS quantity
               FROM oe_odr_lines_sn sn
     INNER JOIN oe_order_lines_all ol ON ol.line_id = sn.line_id
                                     AND ol.flow_status_code = 'AWAITING_SHIPPING'
                                     AND TRUNC (ol.schedule_ship_date) < TRUNC (SYSDATE, 'WW') --  + 6
     INNER JOIN oe_order_headers_all       oh ON ol.header_id = oh.header_id
     INNER JOIN mtl_secondary_inventories msi ON msi.organization_id = sn.organization_id
                                             AND msi.secondary_inventory_name = ol.subinventory
                                             AND msi.availability_type = 1
     INNER JOIN mtl_parameters       mp ON mp.organization_code  = msi.attribute10  --EMS
     INNER JOIN mtl_item_categories mic ON mic.inventory_item_id = sn.inventory_item_id
                                       AND mic.organization_id   = sn.organization_id
     INNER JOIN mtl_categories_b mc ON mc.category_id = mic.category_id
                                   AND mc.segment1 IN ('FG', 'SM')
------------------------------------------------
     INNER JOIN mtl_parameters          e  ON e.organization_id     = mp.organization_id  --sn.organization_id
                                        --AND e.attribute12         = 'Open'  -- this not a index key
                                        --AND e.attribute10         IN (2,5)  -- (same with above)
     INNER JOIN mtl_item_categories     b  ON b.organization_id     = mp.organization_id  --sn.organization_id
                                          AND b.inventory_item_id   = sn.inventory_item_id
                                          AND b.category_set_id     = 1
     INNER JOIN mtl_categories_b        c  ON c.category_id         = b.category_id
     INNER JOIN mtl_system_items_b      a  ON a.organization_id     =b.organization_id   --a.segment1 AS inventory_item
                                          AND a.inventory_item_id   =b.inventory_item_id
                                          AND a.wip_supply_type    <> 6 --
          WHERE NVL (sn.ordered_quantity, 0) - NVL (sn.shipped_quantity, 0) > 0;

-- MDS --
      CURSOR c_mds
      IS
         SELECT /*+PARALLEL */
                msd.inventory_item_id,
                msd.organization_id,
                a.segment1 AS inventory_item,
                msd.schedule_designator AS order_number,
                msd.schedule_quantity                      --schedule_quantity
           FROM mrp_schedule_dates msd
     INNER JOIN mtl_parameters mp ON mp.organization_id   = msd.organization_id
                            --   AND mp.ORGANIZATION_CODE = NVL(P_EMS,mp.ORGANIZATION_CODE )
                            --   AND mp.ATTRIBUTE13       = NVL(P_BU, mp.ATTRIBUTE13)
     INNER JOIN mtl_item_categories mic ON mic.inventory_item_id = msd.inventory_item_id
                                       AND mic.organization_id   = msd.organization_id
     INNER JOIN mtl_categories_b mc ON mc.category_id = mic.category_id
                                   AND mc.segment1 IN ('FG', 'SM')
                               --  AND mc.SEGMENT2 = NVL(P_PRODUCT_LINE, mc.SEGMENT
     ------------
     INNER JOIN mtl_parameters          e  ON e.organization_id     = mp.organization_id
     --msd.organization_id  --1,183,923
                                        --AND e.attribute12         = 'Open'
                                        --AND e.attribute10         IN (2,5)
     INNER JOIN mtl_item_categories     b  ON b.organization_id     = mp.organization_id
     --msd.organization_id
                                          AND b.inventory_item_id   = msd.inventory_item_id
                                          AND b.category_set_id     = 1
     INNER JOIN mtl_categories_b        c  ON c.category_id         = b.category_id
     INNER JOIN mtl_system_items_b      a  ON b.organization_id     = a.organization_id  --a.segment1 AS inventory_item,
                                          AND b.inventory_item_id   = a.inventory_item_id
                                          AND a.wip_supply_type    <> 6 --
     WHERE  msd.schedule_designator LIKE '%PMALLC';

      -- Work Order  Order Scrap --
      -- MSC_SUPPLIES  3 Work order
      -- MSC_DEMANDS  17 Work Order scrap
      CURSOR c_wo
      IS
            SELECT /*+PARALLEL */
                   we.wip_entity_name order_number, a.segment1 inventory_item,
                   mp.organization_id, wdj.primary_item_id inventory_item_id,
                   NVL  (wdj.net_quantity, 0) - NVL (wdj.quantity_completed, 0)  wip_qty,
                   --CEIL (wdj.net_quantity * NVL (msb.shrinkage_rate, 0))  wip_scrap_qty
                   LEAST(CEIL (NVL(wdj.net_quantity,0) * NVL (msb.shrinkage_rate, 0)),NVL (wdj.net_quantity, 0) - NVL (wdj.quantity_completed, 0) ) as wip_scrap_qty
              FROM wip_dscr_jobs_sn wip
        INNER JOIN wip_discrete_jobs wdj ON wdj.wip_entity_id = wip.wip_entity_id
                                        AND wdj.status_type IN (1, 3, 6)
        INNER JOIN wip_entities we ON we.wip_entity_id = wip.wip_entity_id
        INNER JOIN mtl_secondary_inventories msi ON msi.organization_id          = wdj.organization_id
                                                AND msi.secondary_inventory_name = wdj.completion_subinventory
                                                AND msi.availability_type        = 1
        INNER JOIN mtl_parameters             mp ON mp.organization_code = msi.attribute10
        INNER JOIN mtl_system_items_b        msb ON msb.organization_id  = mp.organization_id
                                                AND msb.inventory_item_id = wdj.primary_item_id
        INNER JOIN mtl_item_categories mic  ON mic.inventory_item_id = wdj.primary_item_id
                                           AND mic.organization_id = wdj.organization_id
        INNER JOIN mtl_categories_b mc  ON  mc.category_id = mic.category_id
                                       AND mc.segment1 IN ('FG', 'SM')

     INNER JOIN mtl_parameters          e  ON e.organization_id     = mp.organization_id
     INNER JOIN mtl_item_categories     b  ON b.organization_id     = mp.organization_id
                                          AND b.inventory_item_id   = wdj.primary_item_id
                                          AND b.category_set_id     = 1
     INNER JOIN mtl_categories_b        c  ON c.category_id         = b.category_id
     INNER JOIN mtl_system_items_b      a  ON b.organization_id     = a.organization_id --a.segment1 AS inventory_item,
                                          AND b.inventory_item_id   = a.inventory_item_id
                                          AND a.wip_supply_type    <> 6 --
             --AND NVL (wdj.start_quantity, 0) - NVL (wdj.quantity_completed, 0) > 0;
               AND NVL (wdj.net_quantity, 0) - NVL (wdj.quantity_completed, 0) > 0;
      -- Work Order Demand --Component --  [Wip ???[status ??1. 3. 6 ???????H} OK
      CURSOR c_wo_demand
      IS
         SELECT /*+PARALLEL */
                wwo.inventory_item_id,
                a.segment1  AS inventory_item,
                mp.organization_id,  -- wwo.ORGANIZATION_ID,
                we.wip_entity_name AS order_number,
                  NVL (wwo.required_quantity, 0)
                - NVL (wwo.quantity_issued, 0) AS wo_demand_qty
           FROM wip_wreq_oprs_sn wwo
     INNER JOIN wip_discrete_jobs wdj ON wdj.wip_entity_id=wwo.wip_entity_id
                                     AND wdj.status_type IN (1, 3, 6) --UNRELEASED, RELEASED, ON HOLD
     INNER JOIN wip_entities we ON we.wip_entity_id = wwo.wip_entity_id
     INNER JOIN mtl_secondary_inventories msi  ON msi.organization_id         =wdj.organization_id
                                              AND msi.secondary_inventory_name=wdj.completion_subinventory
                                              AND msi.availability_type = 1
     INNER JOIN mtl_parameters       mp ON mp.organization_code = msi.attribute10
     INNER JOIN mtl_item_categories mic ON mic.inventory_item_id = wwo.inventory_item_id
                                       AND mic.organization_id   = wwo.organization_id
     INNER JOIN mtl_categories_b     mc ON mc.category_id = mic.category_id
                                       AND mc.segment1 IN ('FG', 'SM')

     INNER JOIN mtl_parameters          e  ON e.organization_id     = mp.organization_id --wwo.organization_id
     INNER JOIN mtl_item_categories     b  ON b.organization_id     = mp.organization_id --wwo.organization_id
                                          AND b.inventory_item_id   = wwo.inventory_item_id
                                          AND b.category_set_id     = 1
     INNER JOIN mtl_categories_b        c  ON c.category_id         = b.category_id
     INNER JOIN mtl_system_items_b      a  ON b.organization_id     = a.organization_id --a.segment1 AS inventory_item,
                                          AND b.inventory_item_id   = a.inventory_item_id
                                          AND a.wip_supply_type    <> 6 --
          WHERE NVL (wwo.required_quantity, 0) - NVL (wwo.quantity_issued, 0) <> 0;

      -- MSC_SUPPLIES  1 Purchase order
      -- MSC_SUPPLIES  2 Purchase requisition
      -- MSC_SUPPLIES  8 PO in receiving
      CURSOR c_po
      IS
         SELECT /*+PARALLEL */
                   COALESCE (po.segment1,
                             ro.segment1,
                             so.shipment_num
                            )
                || '-'
                || COALESCE (pl.line_num, rl.line_num, sl.line_num)
                                                              AS order_number,
                CASE
                   WHEN po.segment1 IS NOT NULL
                      THEN 1
                   WHEN ro.segment1 IS NOT NULL
                      THEN 2
                   WHEN so.shipment_num IS NOT NULL
                      THEN 8
                   ELSE 0
                END AS order_type,
                sn.to_subinventory, msi.secondary_inventory_name,
                mp.organization_id, sn.item_id AS inventory_item_id,
                a.segment1  AS inventory_item, sn.supply_type_code, sn.quantity
            FROM mtl_supply_sn sn
 LEFT OUTER JOIN po_headers_all             po ON sn.po_header_id      =po.po_header_id
 LEFT OUTER JOIN po_lines_all               pl ON sn.po_line_id        =pl.po_line_id
 LEFT OUTER JOIN po_requisition_headers_all ro ON sn.req_header_id     =ro.requisition_header_id
 LEFT OUTER JOIN po_requisition_lines_all   rl ON sn.req_line_id       =rl.requisition_line_id
 LEFT OUTER JOIN rcv_shipment_headers       so ON sn.shipment_header_id=so.shipment_header_id
 LEFT OUTER JOIN rcv_shipment_lines         sl ON sn.shipment_line_id  =sl.shipment_line_id
      INNER JOIN mtl_secondary_inventories msi ON msi.organization_id=COALESCE (po.org_id, ro.org_id, so.organization_id)
                                              AND msi.secondary_inventory_name=sn.to_subinventory
                                              AND msi.availability_type = 1
      INNER JOIN mtl_parameters       mp  ON mp.organization_code  = msi.attribute10
      INNER JOIN mtl_item_categories mic  ON mic.inventory_item_id = sn.item_id
                                         AND mic.organization_id   = COALESCE (po.org_id, ro.org_id, so.organization_id)
      INNER JOIN mtl_categories_b     mc  ON mc.category_id = mic.category_id
                                         AND mc.segment1 IN ('FG', 'SM')

   INNER JOIN mtl_parameters          e  ON e.organization_id     =  mp.organization_id
       --COALESCE (po.org_id, ro.org_id, so.organization_id)
                                        --AND e.attribute12         = 'Open'
                                        --AND e.attribute10         IN (2,5)
     INNER JOIN mtl_item_categories     b  ON b.organization_id     = mp.organization_id
       --COALESCE (po.org_id, ro.org_id, so.organization_id)
                                          AND b.inventory_item_id   = sn.item_id
                                          AND b.category_set_id     = 1
     INNER JOIN mtl_categories_b        c  ON c.category_id         = b.category_id
     INNER JOIN mtl_system_items_b      a  ON b.organization_id     = a.organization_id    --a.segment1 AS inventory_item,
                                          AND b.inventory_item_id   = a.inventory_item_id
                                          AND a.wip_supply_type    <> 6 --

                                    --   AND MC.SEGMENT2 = NVL(P_PRODUCT_LINE, MC.SEGMENT2)
      INNER JOIN cux.xx_c_mcatp_rule_t zz  ON zz.inventory_item_id = sn.item_id
                                          AND zz.organization_id   = COALESCE (po.org_id, ro.org_id, so.organization_id)

      WHERE 1=1;

      --ON HwAND
      CURSOR c_onhand
      IS
         SELECT   /*+PARALLEL */
                  mp.attribute1        AS ems_group,
                  mp.organization_code AS ems,
                  miq.inventory_item_id,
                  mp.organization_id,
                  a.segment1                     AS inventory_item,
                  msi.secondary_inventory_name   AS subinventory_code,
                  SUM (miq.transaction_quantity) AS on_hand_quantity
             FROM mtl_oh_qtys_sn miq
       INNER JOIN mtl_secondary_inventories msi ON msi.organization_id         =miq.organization_id
                                               AND msi.secondary_inventory_name=miq.subinventory_code
                                               AND msi.availability_type = 1
       INNER JOIN mtl_parameters mp  ON mp.organization_code = msi.attribute10
                              --    AND mp.ORGANIZATION_CODE = NVL(P_EMS , mp.ORGANIZATION_CODE)
                              --    AND mp.ATTRIBUTE13       = NVL(P_BU  , mp.ATTRIBUTE13)
       INNER JOIN mtl_item_categories mic ON mic.inventory_item_id = miq.inventory_item_id
                                         AND mic.organization_id   = miq.organization_id
       INNER JOIN mtl_categories_b mc  ON mc.category_id = mic.category_id
                                      AND mc.segment1 IN ('FG', 'SM')
                                  --  AND MC.SEGMENT2 = NVL(P_PRODUCT_LINE, MC.SEGMENT2)
   INNER JOIN mtl_parameters          e  ON e.organization_id     = mp.organization_id  --1,183,923
                                        --AND e.attribute12         = 'Open'
                                        --AND e.attribute10         IN (2,5)
     INNER JOIN mtl_item_categories     b  ON b.organization_id     = mp.organization_id
                                          AND b.inventory_item_id   = miq.inventory_item_id
                                          AND b.category_set_id     = 1
     INNER JOIN mtl_categories_b        c  ON c.category_id         = b.category_id
     INNER JOIN mtl_system_items_b      a  ON b.organization_id     = a.organization_id   --a.segment1 AS inventory_item,
                                          AND b.inventory_item_id   = a.inventory_item_id
                                          AND a.wip_supply_type    <> 6 --
 WHERE 1 = 1
         GROUP BY msi.secondary_inventory_name,
                  mp.organization_id,
                  mp.attribute1,                                  -- EMS_GROUP
                  mp.organization_code,                                 -- EMS
                  miq.inventory_item_id,
                  a.segment1
         ORDER BY msi.secondary_inventory_name,
                  mp.organization_id,
                  mp.attribute1,
                  mp.organization_code,
                  miq.inventory_item_id,
                  a.segment1 ;

      v_user_id             NUMBER          := fnd_global.user_id;
      v_login_id            NUMBER          := fnd_global.conc_login_id;
      v_bu_id               NUMBER;
      v_assembly_item_id    NUMBER;
      v_cnt                 NUMBER;
      v_mod                 NUMBER          := 0;
      v_end_item_id         NUMBER;
      v_organization_id     NUMBER;
      v_component_item_id   NUMBER;
      v_counttable          NUMBER;
      v_char                VARCHAR2 (10);
      v_sql                 VARCHAR2 (2000);
      v_string              VARCHAR2 (2000);
      v_plan_id             NUMBER          := 0;
      v_instance_code       VARCHAR2 (10)   := 'EBS';
   BEGIN
/*
-- End of DDL Script for Table CUX.XX_APS_MCATP_DEMAND_PLAN
---------???M??Temp Table ---------------
MSC_SUPPLIES  3 Work order
MSC_DEMANDS 17 Work Order scrap

MSC_SUPPLIES 15 Nonstandard job by-product
MSC_SUPPLIES 7 Non-standard job
MSC_SUPPLIES 18 On Hand
MSC_SUPPLIES  3 Work order
MSC_SUPPLIES  5 Planned order
MSC_SUPPLIES 11 Intransit shipment
MSC_SUPPLIES  1 Purchase order
MSC_SUPPLIES  2 Purchase requisition
MSC_SUPPLIES  8 PO in receiving

MSC_DEMANDS 3 Work order demand
MSC_DEMANDS 30 Sales Orders
MSC_DEMANDS  1 Planned order demand
MSC_DEMANDS  2 Non-standard job demand
MSC_DEMANDS 16 Planned order scrap
MSC_DEMANDS 17 Work Order scrap
MSC_DEMANDS  8 Manual Demand
*/
   -- create_mcatp_rule;                       --(P_BU,P_EMS,P_PRODUCT_LINE);
      v_string := 'TRUNCATE TABLE CUX.XX_APS_PCATP_DETAIL_T';

      EXECUTE IMMEDIATE v_string;
      v_sql :=
         'DELETE CUX.XX_APS_PCATP_DETAIL WHERE SD_TYPE=:1 AND ORDER_TYPE=:2 ';
      IF UPPER (NVL (p_mds, 'N')) = 'Y'
      THEN
         EXECUTE IMMEDIATE v_sql USING 'D', 8; --MSC_DEMANDS  8 Manual Demand
      END IF;

      IF UPPER (NVL (p_oh, 'N')) = 'Y'
      THEN
         EXECUTE IMMEDIATE v_sql USING 'S', 18; --MSC_SUPPLIES 18 On Hand
      END IF;

      IF UPPER (NVL (p_so, 'N')) = 'Y'
      THEN
         EXECUTE IMMEDIATE v_sql USING 'D', 30; --MSC_DEMANDS 30 Sales Orders
      END IF;

      IF UPPER (NVL (p_wip, 'N')) = 'Y'
      THEN
         EXECUTE IMMEDIATE v_sql USING 'S', 3;  --MSC_SUPPLIES  3 Work order
         EXECUTE IMMEDIATE v_sql USING 'D', 3;  --MSC_DEMANDS  3 Work order demand
         EXECUTE IMMEDIATE v_sql USING 'D', 17; --MSC_DEMANDS 17 Work Order scrap
      END IF;

      IF UPPER (NVL (p_po, 'N')) = 'Y'
      THEN
         EXECUTE IMMEDIATE v_sql USING 'S', 1; --MSC_SUPPLIES  1 Purchase order
         EXECUTE IMMEDIATE v_sql USING 'S', 2; --MSC_SUPPLIES  2 Purchase requisition
         EXECUTE IMMEDIATE v_sql USING 'S', 8; --MSC_SUPPLIES  8 PO in receiving
         EXECUTE IMMEDIATE v_sql USING 'S', 0; --MSC_SUPPLIES  8 PO in receiving
      END IF;

-- MDS --
      DBMS_OUTPUT.put_line ('P_MDS--MSC_DEMANDS  8 Manual Demand');
      v_mod := 0;

      IF UPPER (NVL (p_mds, 'N')) = 'Y'
      THEN
         FOR r1 IN c_mds
         LOOP
            v_mod := v_mod + 1;
            DBMS_OUTPUT.put_line (   ' R1.INVENTORY_ITEM_ID='
                                  || r1.inventory_item_id
                                 );

            --V_END_ITEM_ID := GET_WHEREUSE(R1.INVENTORY_ITEM_ID);
            INSERT INTO cux.XX_APS_PCATP_DETAIL_T
                        (plan_id, sd_type, inventory_item_id,
                         item_number, end_item_id,
------------------------------ 5
                         organization_id, order_type, quantity,
                         creation_date, last_update_date,
------------------------------ 10
                                                         created_by,
                         last_updated_by, last_update_login, order_number,
                         plan_name,
------------------------------ 15
                                   instance_code, tune_seg_9m_code
                        )
                 VALUES (v_plan_id,                                 -- PLAN_ID
                                   'D',                             -- SD_TYPE
                                       r1.inventory_item_id,
                                                          -- INVENTORY_ITEM_ID
                         r1.inventory_item,                     -- ITEM_NUMBER
                                           v_end_item_id,       -- END_ITEM_ID
-------------------------------05
                         r1.organization_id, 8,                  -- ORDER_TYPE
                                               r1.schedule_quantity,
                                                                   -- QUANTITY
                         SYSDATE,                             -- CREATION_DATE
                                 SYSDATE,                  -- LAST_UPDATE_DATE
-------------------------------10
                                         v_user_id,              -- CREATED_BY
                         v_user_id,                         -- LAST_UPDATED_BY
                                   v_login_id,            -- LAST_UPDATE_LOGIN
                                              r1.order_number, -- ORDER_NUMBER
                         'PC-ATP',                                -- PLAN_NAME
-------------------------------15
                                  v_instance_code,            -- INSTANCE_CODE
                                                  NULL     -- TUNE_SEG_9M_CODE
                        );

            --   ?C?@?d??COMMIT?@??
            IF MOD (v_mod, 1000) = 0
            THEN
               COMMIT;
            END IF;
         END LOOP;
      END IF;

      IF UPPER (NVL (p_wip, 'N')) = 'Y'
      THEN
         --MSC_DEMANDS 3 Work order demand
         FOR r1 IN c_wo_demand
         LOOP
            v_mod := v_mod + 1;
            DBMS_OUTPUT.put_line (   ' R1.INVENTORY_ITEM_ID='
                                  || r1.inventory_item_id
                                 );

            --V_END_ITEM_ID := GET_WHEREUSE(R1.INVENTORY_ITEM_ID);
            INSERT INTO cux.XX_APS_PCATP_DETAIL_T
                        (plan_id, sd_type, inventory_item_id,
                         item_number, end_item_id,
------------------------------ 5
                         organization_id, order_type, quantity,
                         creation_date, last_update_date,
------------------------------ 10
                                                         created_by,
                         last_updated_by, last_update_login, order_number,
                         plan_name,
------------------------------ 15
                                   instance_code, tune_seg_9m_code
                        )
                 VALUES (v_plan_id,                                 -- PLAN_ID
                                   'D',                             -- SD_TYPE
                                       r1.inventory_item_id,
                                                          -- INVENTORY_ITEM_ID
                         r1.inventory_item,                     -- ITEM_NUMBER
                                           v_end_item_id,       -- END_ITEM_ID
-------------------------------05
                         r1.organization_id, 3,                  -- ORDER_TYPE
                                               r1.wo_demand_qty,   -- QUANTITY
                         SYSDATE,                             -- CREATION_DATE
                                 SYSDATE,                  -- LAST_UPDATE_DATE
-------------------------------10
                                         v_user_id,              -- CREATED_BY
                         v_user_id,                         -- LAST_UPDATED_BY
                                   v_login_id,            -- LAST_UPDATE_LOGIN
                                              r1.order_number, -- ORDER_NUMBER
                         'PC-ATP',                                -- PLAN_NAME
-------------------------------15
                                  v_instance_code,            -- INSTANCE_CODE
                                                  NULL     -- TUNE_SEG_9M_CODE
                        );

            --   ?C?@?d??COMMIT?@??
            IF MOD (v_mod, 1000) = 0
            THEN
               COMMIT;
            END IF;
         END LOOP;

         -- MSC_SUPPLIES  3 Work order
         -- MSC_DEMANDS  17 Work Order scrap
         FOR r1 IN c_wo
         LOOP
            v_mod := v_mod + 1;
            DBMS_OUTPUT.put_line (   ' R1.INVENTORY_ITEM_ID='
                                  || r1.inventory_item_id
                                 );

            --V_END_ITEM_ID := GET_WHEREUSE(R1.INVENTORY_ITEM_ID);

            -- MSC_SUPPLIES  3 Work order
            IF NVL (r1.wip_qty, 0) <> 0
            THEN
               INSERT INTO cux.XX_APS_PCATP_DETAIL_T
                           (plan_id, sd_type, inventory_item_id,
                            item_number, end_item_id,
------------------------------ 5
                            organization_id, order_type, quantity,
                            creation_date, last_update_date,
------------------------------ 10
                                                            created_by,
                            last_updated_by, last_update_login,
                            order_number, plan_name,
------------------------------ 15
                                                    instance_code,
                            tune_seg_9m_code
                           )
                    VALUES (v_plan_id,                              -- PLAN_ID
                                      'S',                          -- SD_TYPE
                                          r1.inventory_item_id,
                                                          -- INVENTORY_ITEM_ID
                            r1.inventory_item,                  -- ITEM_NUMBER
                                              v_end_item_id,    -- END_ITEM_ID
-------------------------------05
                            r1.organization_id, 3,               -- ORDER_TYPE
                                                  r1.wip_qty,
                                             -- QUANTITY       --WIP_SCRAP_QTY
                            SYSDATE,                          -- CREATION_DATE
                                    SYSDATE,               -- LAST_UPDATE_DATE
-------------------------------10
                                            v_user_id,           -- CREATED_BY
                            v_user_id,                      -- LAST_UPDATED_BY
                                      v_login_id,         -- LAST_UPDATE_LOGIN
                            r1.order_number,                   -- ORDER_NUMBER
                                            'PC-ATP',             -- PLAN_NAME
-------------------------------15
                                                     v_instance_code,
                                                              -- INSTANCE_CODE
                            NULL                           -- TUNE_SEG_9M_CODE
                           );
            END IF;

            -- MSC_DEMANDS  17 Work Order scrap
            IF NVL (r1.wip_scrap_qty, 0) <> 0
            THEN
               INSERT INTO cux.XX_APS_PCATP_DETAIL_T
                           (plan_id, sd_type, inventory_item_id,
                            item_number, end_item_id,
------------------------------ 5
                            organization_id, order_type, quantity,
                            creation_date, last_update_date,
------------------------------ 10
                                                            created_by,
                            last_updated_by, last_update_login,
                            order_number, plan_name,
------------------------------ 15
                                                    instance_code,
                            tune_seg_9m_code
                           )
                    VALUES (v_plan_id,                              -- PLAN_ID
                                      'D',                          -- SD_TYPE
                                          r1.inventory_item_id,
                                                          -- INVENTORY_ITEM_ID
                            r1.inventory_item,                  -- ITEM_NUMBER
                                              v_end_item_id,    -- END_ITEM_ID
-------------------------------05
                            r1.organization_id, 17,              -- ORDER_TYPE
                                                   r1.wip_scrap_qty,
                                             -- QUANTITY       --WIP_SCRAP_QTY
                            SYSDATE,                          -- CREATION_DATE
                                    SYSDATE,               -- LAST_UPDATE_DATE
-------------------------------10
                                            v_user_id,           -- CREATED_BY
                            v_user_id,                      -- LAST_UPDATED_BY
                                      v_login_id,         -- LAST_UPDATE_LOGIN
                            r1.order_number,                   -- ORDER_NUMBER
                                            'PC-ATP',             -- PLAN_NAME
-------------------------------15
                                                     v_instance_code,
                                                              -- INSTANCE_CODE
                            NULL                           -- TUNE_SEG_9M_CODE
                           );
            END IF;

            --   ?C?@?d??COMMIT?@??
            IF MOD (v_mod, 1000) = 0
            THEN
               COMMIT;
            END IF;
         END LOOP;
      END IF;

      IF UPPER (NVL (p_po, 'N')) = 'Y'
      THEN
         -- MSC_SUPPLIES  1 Purchase order
         -- MSC_SUPPLIES  2 Purchase requisition
         -- MSC_SUPPLIES  8 PO in receiving
         FOR r1 IN c_po
         LOOP
            v_mod := v_mod + 1;

            -- DBMS_OUTPUT.PUT_LINE('C_PO:: R1.INVENTORY_ITEM_ID='|| R1.INVENTORY_ITEM_ID);
            -- V_END_ITEM_ID := GET_WHEREUSE(R1.INVENTORY_ITEM_ID);
            INSERT INTO cux.XX_APS_PCATP_DETAIL_T
                        (plan_id, sd_type, inventory_item_id,
                         item_number, end_item_id,
------------------------------ 5
                         organization_id, order_type, quantity,
                         creation_date, last_update_date,
------------------------------ 10
                                                         created_by,
                         last_updated_by, last_update_login, order_number,
                         plan_name,
------------------------------ 15
                                   instance_code, tune_seg_9m_code
                        )
                 VALUES (v_plan_id,                                 -- PLAN_ID
                                   'S',                             -- SD_TYPE
                                       r1.inventory_item_id,
                                                          -- INVENTORY_ITEM_ID
                         r1.inventory_item,                     -- ITEM_NUMBER
                                           v_end_item_id,       -- END_ITEM_ID
-------------------------------05
                         r1.organization_id, r1.order_type,      -- ORDER_TYPE
                                                           r1.quantity,
                                                                   -- QUANTITY
                         SYSDATE,                             -- CREATION_DATE
                                 SYSDATE,                  -- LAST_UPDATE_DATE
-------------------------------10
                                         v_user_id,              -- CREATED_BY
                         v_user_id,                         -- LAST_UPDATED_BY
                                   v_login_id,            -- LAST_UPDATE_LOGIN
                                              r1.order_number, -- ORDER_NUMBER
                         'PC-ATP',                                -- PLAN_NAME
-------------------------------15
                                  v_instance_code,            -- INSTANCE_CODE
                                                  NULL     -- TUNE_SEG_9M_CODE
                        );

            --   ?C?@?d??COMMIT?@??
            IF MOD (v_mod, 1000) = 0
            THEN
               COMMIT;
            END IF;
         END LOOP;
      END IF;

      IF UPPER (NVL (p_so, 'N')) = 'Y'
      THEN
         -- MSC_DEMANDS 30 Sales Orders
         -- DBMS_OUTPUT.PUT_LINE('FOR R1 IN C10 LOOP');
         FOR r1 IN c_so
         LOOP
            v_mod := v_mod + 1;
            DBMS_OUTPUT.put_line (   ' R1.INVENTORY_ITEM_ID='
                                  || r1.inventory_item_id
                                 );

            INSERT INTO cux.XX_APS_PCATP_DETAIL_T
                        (plan_id, sd_type, inventory_item_id,
                         item_number, end_item_id,
------------------------------ 5
                         organization_id, order_type, quantity,
                         creation_date, last_update_date,
------------------------------ 10
                                                         created_by,
                         last_updated_by, last_update_login, order_number,
                         plan_name,
------------------------------ 15
                                   instance_code, tune_seg_9m_code
                        )
                 VALUES (v_plan_id,                                 -- PLAN_ID
                                   'D',                             -- SD_TYPE
                                       r1.inventory_item_id,
                                                          -- INVENTORY_ITEM_ID
                         r1.inventory_item,                     -- ITEM_NUMBER
                                           v_end_item_id,       -- END_ITEM_ID
-------------------------------05
                         r1.organization_id, 30,                 -- ORDER_TYPE
                                                r1.quantity,       -- QUANTITY
                         SYSDATE,                             -- CREATION_DATE
                                 SYSDATE,                  -- LAST_UPDATE_DATE
-------------------------------10
                                         v_user_id,              -- CREATED_BY
                         v_user_id,                         -- LAST_UPDATED_BY
                                   v_login_id,            -- LAST_UPDATE_LOGIN
                                              r1.order_number, -- ORDER_NUMBER
                         'PC-ATP',                                -- PLAN_NAME
-------------------------------15
                                  v_instance_code,            -- INSTANCE_CODE
                                                  NULL     -- TUNE_SEG_9M_CODE
                        );

            --   ?C?@?d??COMMIT?@??
            IF MOD (v_mod, 1000) = 0
            THEN
               COMMIT;
            END IF;
         END LOOP;
      END IF;

      IF UPPER (NVL (p_oh, 'N')) = 'Y'
      THEN
         -- MSC_SUPPLIES 18 On Hand
         FOR r1 IN c_onhand
         LOOP
            v_mod := v_mod + 1;
            DBMS_OUTPUT.put_line (   ' R1.INVENTORY_ITEM_ID='
                                  || r1.inventory_item_id
                                 );

            INSERT INTO cux.XX_APS_PCATP_DETAIL_T
                        (plan_id, sd_type, inventory_item_id,
                         item_number, end_item_id,
------------------------------ 5
                         organization_id, order_type, quantity,
                         creation_date, last_update_date,
------------------------------ 10
                                                         created_by,
                         last_updated_by, last_update_login, order_number,
                         plan_name,
------------------------------ 15
                                   instance_code, tune_seg_9m_code
                        )
                 VALUES (v_plan_id,                                 -- PLAN_ID
                                   'S',                             -- SD_TYPE
                                       r1.inventory_item_id,
                                                          -- INVENTORY_ITEM_ID
                         r1.inventory_item,                     -- ITEM_NUMBER
                                           v_end_item_id,       -- END_ITEM_ID
-------------------------------05
                         r1.organization_id, 18,                 -- ORDER_TYPE
                                                r1.on_hand_quantity,
                                                                   -- QUANTITY
                         SYSDATE,                             -- CREATION_DATE
                                 SYSDATE,                  -- LAST_UPDATE_DATE
-------------------------------10
                                         v_user_id,              -- CREATED_BY
                         v_user_id,                         -- LAST_UPDATED_BY
                                   v_login_id,            -- LAST_UPDATE_LOGIN
                                              NULL,            -- ORDER_NUMBER
                         'PC-ATP',                                -- PLAN_NAME
-------------------------------15
                                  v_instance_code,            -- INSTANCE_CODE
                                                  NULL     -- TUNE_SEG_9M_CODE
                        );

            --   ?C?@?d??COMMIT?@??
            IF MOD (v_mod, 1000) = 0
            THEN
               COMMIT;
            END IF;
         END LOOP;                                                 --CURSOR C1
      END IF;

      /*
      v_String :=''
      ||'CREATE TABLE CUX.XX_APS_PCATP_DETAIL_T AS '
      ||'SELECT INVENTORY_ITEM_ID,ORGANIZATION_ID, '
      ||'APPS.XXAPSP0057_PKG.GET_WHEREUSE(INVENTORY_ITEM_ID,ORGANIZATION_ID)AS END_ITEM_ID '
      ||'FROM (SELECT DISTINCT INVENTORY_ITEM_ID,ORGANIZATION_ID '
              ||'FROM CUX.XX_APS_PCATP_DETAIL_T) ';
      EXECUTE IMMEDIATE v_String;
      */
      v_string :=
            ''
         || 'INSERT INTO CUX.XX_APS_PCATP_DETAIL( '
         || 'plan_id               , '
         || 'sd_type               ,'
         || 'inventory_item_id     ,'
         || 'item_number           ,'
         || 'end_item_id           ,'
         || 'organization_id       ,'
         || 'order_type            ,'
         || 'quantity              ,'
         || 'creation_date         ,'
         || 'last_update_date      ,'
         || 'created_by            ,'
         || 'last_updated_by       ,'
         || 'last_update_login     ,'
         || 'order_number          ,'
         || 'plan_name             ,'
         || 'instance_code         ,'
         || 'tune_seg_9m_code      )'
         || 'SELECT '
         || 'a.plan_id             ,'
         || 'a.sd_type             ,'
         || 'a.inventory_item_id   ,'
         || 'a.item_number         ,'
         || 'b.END_ITEM_ID         ,'
         || 'a.organization_id     ,'
         || 'a.order_type          ,'
         || 'a.quantity            ,'
         || 'a.creation_date       ,'
         || 'a.last_update_date    ,'
         || 'a.created_by          ,'
         || 'a.last_updated_by     ,'
         || 'a.last_update_login   ,'
         || 'a.order_number        ,'
         || 'a.plan_name           ,'
         || 'a.instance_code       ,'
         || 'a.tune_seg_9m_code '
         || 'FROM CUX.XX_APS_PCATP_DETAIL_T a INNER JOIN '
         || '(SELECT INVENTORY_ITEM_ID,ORGANIZATION_ID, '
         || ' APPS.XXAPSP0057_PKG.GET_WHEREUSE(INVENTORY_ITEM_ID,ORGANIZATION_ID ) AS END_ITEM_ID '
         || 'FROM (SELECT DISTINCT INVENTORY_ITEM_ID,ORGANIZATION_ID FROM CUX.XX_APS_PCATP_DETAIL_T) '
         || ') b ON a.INVENTORY_ITEM_ID=b.INVENTORY_ITEM_ID '
         || 'AND a.ORGANIZATION_ID=b.ORGANIZATION_ID ';

      EXECUTE IMMEDIATE v_string;

      COMMIT;
--?n?????z?b?{????????
--?A?I?s?o?@?? procedure, ?p?U
      xxapsf0051_ebs_pkg.gen_pcatp_sum (v_plan_id);
--?o?? procedure?|?N?g?J?? Detail????,
--?????? Summary???? ( PC ATP Maintain  Form?????@???e ??, GSM?i???@??????)
      COMMIT;

      <>
      DBMS_OUTPUT.put_line ('....END....');
   END main;

   FUNCTION get_whereuse (p_component_item_id NUMBER, p_organization_id NUMBER)
      RETURN NUMBER
   IS
      v_return              NUMBER := 0;
      v_count               NUMBER := 0;

      CURSOR c4 (x_component_item_id NUMBER, x_organization_id NUMBER)
      IS
         --SELECT * FROM (
                 SELECT   bbo.assembly_item_id
                     -- , bic.component_item_id, bsc.substitute_component_id
                     FROM bom_structures_b bbo
               INNER JOIN bom_components_b bic ON bbo.common_bill_sequence_id = bic.bill_sequence_id
                     --   bom_substitute_components bsc
                    WHERE bic.component_item_id = x_component_item_id
                   -- AND bsc.component_sequence_id = bic.component_sequence_id
                   -- AND bsc.substitute_component_id = x_component_item_id
                      AND bbo.organization_id  = x_organization_id
                 ORDER BY bbo.assembly_item_id;
         --) WHERE ROWNUM = 1;

      CURSOR c4s (x_component_item_id NUMBER, x_organization_id NUMBER)
      IS
        -- SELECT * FROM (
                   SELECT bbo.assembly_item_id
                    --  , bic.component_item_id, bsc.substitute_component_id
                     FROM bom_structures_b bbo
               INNER JOIN bom_components_b bic ON bbo.common_bill_sequence_id = bic.bill_sequence_id
               INNER JOIN bom_substitute_components bsc ON bsc.component_sequence_id = bic.component_sequence_id
                    WHERE 1 = 1
                      AND bsc.substitute_component_id = x_component_item_id
                      AND bbo.organization_id = x_organization_id
                 ORDER BY bbo.assembly_item_id;
        --   ) WHERE ROWNUM = 1;

      v_component_item_id   NUMBER := 0;
      v_organization_id     NUMBER := 0;
      v_assembly_item_id    NUMBER := 0;
   BEGIN
      v_assembly_item_id := p_component_item_id;

      -- ?? cmponent ???X assembly
      FOR r4 IN c4 (p_component_item_id, p_organization_id)
      LOOP
         v_assembly_item_id := r4.assembly_item_id;

         SELECT COUNT (*)
           INTO v_count
           FROM bom_structures_b bbo
     INNER JOIN bom_components_b bic ON bbo.common_bill_sequence_id = bic.bill_sequence_id
          WHERE 1 = 1
            AND bic.component_item_id = v_assembly_item_id
            AND bbo.organization_id   = p_organization_id;

         IF v_count > 0
         THEN
            v_assembly_item_id := get_whereuse (v_assembly_item_id, p_organization_id);
         END IF;
         IF v_assembly_item_id <> p_component_item_id THEN
            GOTO substitute;
         END IF;
      END LOOP;
      <>
      IF v_assembly_item_id = p_component_item_id
      THEN                                                                   --
         FOR r4 IN c4s (p_component_item_id, p_organization_id)
         LOOP
            v_assembly_item_id := r4.assembly_item_id;

            SELECT COUNT (*)
              INTO v_count
              FROM bom_structures_b bbo
        INNER JOIN bom_components_b bic ON bbo.common_bill_sequence_id = bic.bill_sequence_id
             WHERE bic.component_item_id = v_assembly_item_id
               AND bbo.organization_id   = p_organization_id;

            IF v_count > 0
            THEN
               v_assembly_item_id := get_whereuse(v_assembly_item_id, p_organization_id);
            END IF;

          IF v_assembly_item_id <> p_component_item_id THEN
            GOTO end_substitute;
          END IF;

          END LOOP;
      END IF;
      <>
-- FND_FILE.PUT_LINE(FND_FILE.OUTPUT , 'LOOP-4: ' || 'Y' ) ;
      RETURN v_assembly_item_id;
   EXCEPTION
      WHEN OTHERS
      THEN
         RETURN v_assembly_item_id;
   END get_whereuse;
END XXAPSP0058_PKG;