
    
-- This shows where each lot currently stands across the full chain
SELECT
    pp.name                     AS supplier,
    pur.number                  AS purchase_contract,
    pur.state                   AS contract_state,
    si.number                   AS shipment,
    si.state                    AS shipment_state,
    pur.invoice_state           AS invoice_state,
    COUNT(l.id)                 AS lots,
    SUM(l.lot_qt)               AS quantity
FROM lot_lot            l
LEFT JOIN stock_shipment_in  si  ON si.id  = l.lot_shipment_in
LEFT JOIN purchase_line      pl  ON pl.id  = l.line
LEFT JOIN purchase_purchase  pur ON pur.id = pl.purchase
LEFT JOIN party_party        pp  ON pp.id  = pur.party
GROUP BY pp.name, pur.number, pur.state, si.number, si.state, pur.invoice_state
ORDER BY pp.name, pur.number;

-- This shows the details of each lot that is still in draft shipment, to see where they are in the chain and what is missing
SELECT
    pp.name                     AS supplier,
    prod.name                   AS product,
    pur.number                  AS purchase_contract,
    si.number                   AS shipment_number,
    tv.vessel_name              AS vessel,
    si.planned_date,
    si.eta,
    si.etd,
    si.cargo_mode,
    si.transport_type,
    si.bl_number,
    l.id                        AS lot_id,
    pl.quantity                 AS contracted_qty,
    u.name                      AS unit,
    pl.unit_price,
    cur.code                    AS currency,
    pl.price_type,
    l.lot_pur_inv_state,
    l.lot_sale_inv_state
FROM lot_lot             l
JOIN stock_shipment_in   si   ON si.id   = l.lot_shipment_in
JOIN purchase_line       pl   ON pl.id   = l.line
JOIN purchase_purchase   pur  ON pur.id  = pl.purchase
JOIN party_party         pp   ON pp.id   = pur.party
JOIN product_product     prd  ON prd.id  = l.lot_product
JOIN product_template    prod ON prod.id = prd.template
JOIN currency_currency   cur  ON cur.id  = pur.currency
LEFT JOIN product_uom    u    ON u.id    = pl.unit
LEFT JOIN trade_vessel   tv   ON tv.id   = si.vessel
WHERE si.state = 'draft'
ORDER BY si.planned_date, pp.name, si.number, l.id;

-- This shows all the contracts that are fixed price
SELECT
    'Purchase'              AS side,
    pur.number              AS contract,
    pur.state               AS contract_state,
    pp.name                 AS counterparty,
    prod.name               AS product,
    pl.from_del,
    pl.to_del,
    pl.quantity             AS contracted_qty,
    u.name                  AS unit,
    pl.unit_price           AS fixed_price,
    cur.code                AS currency
FROM purchase_line      pl
JOIN purchase_purchase  pur  ON pur.id  = pl.purchase
JOIN party_party        pp   ON pp.id   = pur.party
JOIN product_product    prd  ON prd.id  = pl.product
JOIN product_template   prod ON prod.id = prd.template
JOIN currency_currency  cur  ON cur.id  = pur.currency
LEFT JOIN product_uom   u    ON u.id    = pl.unit
WHERE pl.type = 'line' AND pl.price_type = 'priced'

UNION ALL

SELECT
    'Sale'                  AS side,
    s.number,
    s.state,
    pp.name,
    prod.name,
    sl.from_del,
    sl.to_del,
    sl.quantity,
    u.name,
    sl.unit_price,
    cur.code
FROM sale_line          sl
JOIN sale_sale          s    ON s.id    = sl.sale
JOIN party_party        pp   ON pp.id   = s.party
JOIN product_product    prd  ON prd.id  = sl.product
JOIN product_template   prod ON prod.id = prd.template
JOIN currency_currency  cur  ON cur.id  = s.currency
LEFT JOIN product_uom   u    ON u.id    = sl.unit
WHERE sl.type = 'line' AND sl.price_type = 'priced'
ORDER BY side, contract;



WITH

-- Last fixation state per purchase line
pur_fix AS (
    SELECT DISTINCT ON (line)
        line,
        fixed_qt,
        fixed_qt_price,
        unfixed_qt,
        unfixed_qt_price        AS unfixed_price
    FROM pricing_pricing
    WHERE line IS NOT NULL
    ORDER BY line, last DESC NULLS LAST, pricing_date DESC
),

-- Last fixation state per sale line  ← mirrors pur_fix exactly
sale_fix AS (
    SELECT DISTINCT ON (sale_line)
        sale_line,
        fixed_qt,
        fixed_qt_price,
        unfixed_qt,
        unfixed_qt_price        AS unfixed_price
    FROM pricing_pricing
    WHERE sale_line IS NOT NULL
    ORDER BY sale_line, last DESC NULLS LAST, pricing_date DESC
),

-- Most recent market price per price index
last_mkt AS (
    SELECT DISTINCT ON (price)
        price                   AS price_index_id,
        price_date              AS last_market_date,
        price_value             AS last_market_price
    FROM price_price_value
    ORDER BY price, price_date DESC
),

-- Next scheduled fixing date per purchase line
pur_next_fix AS (
    SELECT DISTINCT ON (line)
        line,
        estimated_date          AS next_fixing_date,
        trigger                 AS fixing_trigger
    FROM pricing_estimated
    WHERE line IS NOT NULL
      AND estimated_date >= CURRENT_DATE
    ORDER BY line, estimated_date ASC
),

-- Next scheduled fixing date per sale line
sale_next_fix AS (
    SELECT DISTINCT ON (sale_line)
        sale_line,
        estimated_date          AS next_fixing_date,
        trigger                 AS fixing_trigger
    FROM pricing_estimated
    WHERE sale_line IS NOT NULL
      AND estimated_date >= CURRENT_DATE
    ORDER BY sale_line, estimated_date ASC
)

SELECT
    'Purchase'                                      AS side,
    pur.number                                      AS contract,
    pur.state                                       AS contract_state,
    pp.name                                         AS counterparty,
    prod.name                                       AS product,
    pl.from_del,
    pl.to_del,
    pl.quantity                                     AS contracted_qty,
    u.name                                          AS unit,
    cur.symbol                                      AS currency,
    pi2.price_desc                                  AS price_index,
    nf.fixing_trigger,
    nf.next_fixing_date,
    COALESCE(pf.fixed_qt,        0)                 AS fixed_qty,
    COALESCE(pf.fixed_qt_price,  0)                 AS avg_fixed_price,
    pl.quantity - COALESCE(pf.fixed_qt, 0)          AS unfixed_qty,
    COALESCE(lm.last_market_price, pf.unfixed_price) AS unfixed_market_price,
    lm.last_market_date,
    lm.last_market_price

FROM purchase_line      pl
JOIN purchase_purchase  pur  ON pur.id           = pl.purchase
JOIN party_party        pp   ON pp.id            = pur.party
JOIN product_product    prd  ON prd.id           = pl.product
JOIN product_template   prod ON prod.id          = prd.template
JOIN currency_currency  cur  ON cur.id           = pur.currency
LEFT JOIN product_uom   u    ON u.id             = pl.unit
LEFT JOIN pricing_component pc   ON pc.line      = pl.id
LEFT JOIN price_price       pi2  ON pi2.id       = pc.price_index
LEFT JOIN last_mkt          lm   ON lm.price_index_id = pc.price_index
LEFT JOIN pur_fix           pf   ON pf.line      = pl.id
LEFT JOIN pur_next_fix      nf   ON nf.line      = pl.id
WHERE pl.type = 'line' AND pl.price_type = 'basis'

UNION ALL

SELECT
    'Sale'                                          AS side,
    s.number,
    s.state,
    pp.name,
    prod.name,
    sl.from_del,
    sl.to_del,
    sl.quantity,
    u.name,
    cur.symbol,
    pi2.price_desc,
    nf.fixing_trigger,
    nf.next_fixing_date,
    COALESCE(sf.fixed_qt,        0)                 AS fixed_qty,
    COALESCE(sf.fixed_qt_price,  0)                 AS avg_fixed_price,
    sl.quantity - COALESCE(sf.fixed_qt, 0)          AS unfixed_qty,
    COALESCE(lm.last_market_price, sf.unfixed_price) AS unfixed_market_price,
    lm.last_market_date,
    lm.last_market_price

FROM sale_line          sl
JOIN sale_sale          s    ON s.id             = sl.sale
JOIN party_party        pp   ON pp.id            = s.party
JOIN product_product    prd  ON prd.id           = sl.product
JOIN product_template   prod ON prod.id          = prd.template
JOIN currency_currency  cur  ON cur.id           = s.currency
LEFT JOIN product_uom   u    ON u.id             = sl.unit
LEFT JOIN pricing_component pc   ON pc.sale_line = sl.id
LEFT JOIN price_price       pi2  ON pi2.id       = pc.price_index
LEFT JOIN last_mkt          lm   ON lm.price_index_id = pc.price_index
LEFT JOIN sale_fix          sf   ON sf.sale_line = sl.id
LEFT JOIN sale_next_fix     nf   ON nf.sale_line = sl.id
WHERE sl.type = 'line' AND sl.price_type = 'basis'

ORDER BY side, contract;



-- MtM strategy, component details, and last valuation per contract (purchase and sale)
-- Columns:
--   strategy_name / scenario_name / valuation_date  → MtM setup header
--   component_*  → from pricing_component linked via strategy (MtM strategy-level components)
--   pricing_*    → from pricing_component linked via line/sale_line (contract fixation setup)
--   vv_*         → latest snapshot from valuation_valuation (price = contract price, amount = contract value)
--   vvl_*        → current state from valuation_valuation_line (same structure, always most recent)
WITH

-- Latest valuation_valuation row per purchase line (physical price row only)
last_vv_pur AS (
    SELECT DISTINCT ON (line)
        line,
        date        AS vv_date,
        price       AS vv_price,
        quantity    AS vv_quantity,
        amount      AS vv_amount,
        base_amount AS vv_base_amount,
        rate        AS vv_rate
    FROM valuation_valuation
    WHERE line IS NOT NULL
      AND type = 'pur. priced'
      AND reference = 'Purchase/Physic'
    ORDER BY line, date DESC
),

-- Latest valuation_valuation row per sale line
last_vv_sale AS (
    SELECT DISTINCT ON (sale_line)
        sale_line,
        date        AS vv_date,
        price       AS vv_price,
        quantity    AS vv_quantity,
        amount      AS vv_amount,
        base_amount AS vv_base_amount,
        rate        AS vv_rate
    FROM valuation_valuation
    WHERE sale_line IS NOT NULL
      AND type = 'sale priced'
      AND reference = 'Sale/Physic'
    ORDER BY sale_line, date DESC
),

-- valuation_valuation_line per purchase line (current state)
last_vvl_pur AS (
    SELECT DISTINCT ON (line)
        line,
        date        AS vvl_date,
        price       AS vvl_price,
        quantity    AS vvl_quantity,
        amount      AS vvl_amount,
        base_amount AS vvl_base_amount,
        rate        AS vvl_rate
    FROM valuation_valuation_line
    WHERE line IS NOT NULL
      AND type = 'pur. priced'
      AND reference = 'Purchase/Physic'
    ORDER BY line, date DESC
),

-- valuation_valuation_line per sale line (current state)
last_vvl_sale AS (
    SELECT DISTINCT ON (sale_line)
        sale_line,
        date        AS vvl_date,
        price       AS vvl_price,
        quantity    AS vvl_quantity,
        amount      AS vvl_amount,
        base_amount AS vvl_base_amount,
        rate        AS vvl_rate
    FROM valuation_valuation_line
    WHERE sale_line IS NOT NULL
      AND type = 'sale priced'
      AND reference = 'Sale/Physic'
    ORDER BY sale_line, date DESC
)

SELECT
    'Purchase'                              AS side,
    pur.number                              AS contract,
    pur.state                               AS contract_state,
    pp.name                                 AS counterparty,
    prod.name                               AS product,
    pl.from_del,
    pl.to_del,
    pl.quantity                             AS contracted_qty,
    u.name                                  AS unit,
    -- Strategy
    ms.name                                 AS strategy_name,
    ms_cur.symbol                           AS strategy_currency,
    -- Scenario
    msc.name                                AS scenario_name,
    msc.valuation_date,
    msc.use_last_price,
    cal.name                                AS scenario_calendar,
    -- MtM component (pricing_component linked via strategy)
    pc_mtm.price_source_type                AS component_price_source,
    pc_mtm.ratio                            AS component_ratio_pct,
    ft.name                                 AS component_fix_type,
    pi2.price_desc                          AS component_curve,
    pc_mtm_cal.name                         AS component_calendar,
    pc_mtm.auto                             AS component_auto,
    pc_mtm.fallback                         AS component_fallback,
    -- Pricing component (fixation setup — independent of MtM, already populated)
    pc_idx.price_desc                       AS pricing_curve,
    pc_ft.name                              AS pricing_fix_type,
    pc.price_source_type                    AS pricing_source_type,
    pc.ratio                                AS pricing_ratio_pct,
    pc_cal.name                             AS pricing_calendar,
    -- Last valuation snapshot (valuation_valuation — most recent run)
    vv.vv_date                              AS last_valuation_date,
    vv.vv_price                             AS last_valuation_price,
    vv.vv_quantity                          AS last_valuation_qty,
    vv.vv_amount                            AS last_valuation_amount,
    vv.vv_base_amount                       AS last_valuation_base_amount,
    vv.vv_rate                              AS last_valuation_rate,
    -- Current valuation state (valuation_valuation_line — always latest)
    vvl.vvl_date                            AS current_valuation_date,
    vvl.vvl_price                           AS current_valuation_price,
    vvl.vvl_quantity                        AS current_valuation_qty,
    vvl.vvl_amount                          AS current_valuation_amount,
    vvl.vvl_base_amount                     AS current_valuation_base_amount,
    vvl.vvl_rate                            AS current_valuation_rate
FROM purchase_strategy      ps
JOIN purchase_line          pl      ON pl.id        = ps.line
JOIN purchase_purchase      pur     ON pur.id       = pl.purchase
JOIN party_party            pp      ON pp.id        = pur.party
JOIN product_product        prd     ON prd.id       = pl.product
JOIN product_template       prod    ON prod.id      = prd.template
LEFT JOIN product_uom       u       ON u.id         = pl.unit
JOIN mtm_strategy           ms      ON ms.id        = ps.strategy
JOIN mtm_scenario           msc     ON msc.id       = ms.scenario
LEFT JOIN currency_currency ms_cur  ON ms_cur.id    = ms.currency
LEFT JOIN price_calendar    cal     ON cal.id       = msc.calendar
LEFT JOIN pricing_component pc_mtm      ON pc_mtm.strategy   = ms.id
LEFT JOIN price_fixtype     ft          ON ft.id             = pc_mtm.fix_type
LEFT JOIN price_price       pi2         ON pi2.id            = pc_mtm.price_index
LEFT JOIN price_calendar    pc_mtm_cal  ON pc_mtm_cal.id     = pc_mtm.calendar
LEFT JOIN pricing_component pc          ON pc.line           = pl.id
LEFT JOIN price_price       pc_idx  ON pc_idx.id    = pc.price_index
LEFT JOIN price_fixtype     pc_ft   ON pc_ft.id     = pc.fix_type
LEFT JOIN price_calendar    pc_cal  ON pc_cal.id    = pc.calendar
LEFT JOIN last_vv_pur       vv      ON vv.line      = pl.id
LEFT JOIN last_vvl_pur      vvl     ON vvl.line     = pl.id

UNION ALL

SELECT
    'Sale'                                  AS side,
    s.number,
    s.state,
    pp.name,
    prod.name,
    sl.from_del,
    sl.to_del,
    sl.quantity,
    u.name,
    ms.name,
    ms_cur.symbol,
    msc.name,
    msc.valuation_date,
    msc.use_last_price,
    cal.name,
    pc_mtm.price_source_type,
    pc_mtm.ratio,
    ft.name,
    pi2.price_desc,
    pc_mtm_cal.name,
    pc_mtm.auto,
    pc_mtm.fallback,
    pc_idx.price_desc,
    pc_ft.name,
    pc.price_source_type,
    pc.ratio,
    pc_cal.name,
    vv.vv_date,
    vv.vv_price,
    vv.vv_quantity,
    vv.vv_amount,
    vv.vv_base_amount,
    vv.vv_rate,
    vvl.vvl_date,
    vvl.vvl_price,
    vvl.vvl_quantity,
    vvl.vvl_amount,
    vvl.vvl_base_amount,
    vvl.vvl_rate
FROM sale_strategy          ss
JOIN sale_line              sl      ON sl.id          = ss.sale_line
JOIN sale_sale              s       ON s.id           = sl.sale
JOIN party_party            pp      ON pp.id          = s.party
JOIN product_product        prd     ON prd.id         = sl.product
JOIN product_template       prod    ON prod.id        = prd.template
LEFT JOIN product_uom       u       ON u.id           = sl.unit
JOIN mtm_strategy           ms      ON ms.id          = ss.strategy
JOIN mtm_scenario           msc     ON msc.id         = ms.scenario
LEFT JOIN currency_currency ms_cur  ON ms_cur.id      = ms.currency
LEFT JOIN price_calendar    cal     ON cal.id         = msc.calendar
LEFT JOIN pricing_component pc_mtm      ON pc_mtm.strategy   = ms.id
LEFT JOIN price_fixtype     ft          ON ft.id             = pc_mtm.fix_type
LEFT JOIN price_price       pi2         ON pi2.id            = pc_mtm.price_index
LEFT JOIN price_calendar    pc_mtm_cal  ON pc_mtm_cal.id     = pc_mtm.calendar
LEFT JOIN pricing_component pc          ON pc.sale_line      = sl.id
LEFT JOIN price_price       pc_idx  ON pc_idx.id      = pc.price_index
LEFT JOIN price_fixtype     pc_ft   ON pc_ft.id       = pc.fix_type
LEFT JOIN price_calendar    pc_cal  ON pc_cal.id      = pc.calendar
LEFT JOIN last_vv_sale      vv      ON vv.sale_line   = sl.id
LEFT JOIN last_vvl_sale     vvl     ON vvl.sale_line  = sl.id

ORDER BY side, contract;