WITH 
cols AS (
    SELECT 
        "Renamed" shipcust
        ,"ReRep" dsm
        -- "Ship-To Group" shipcust
        -- ,"Default Rep" dsm
        ,"FY26"::numeric lbs
    FROM  
        rlarp.lbs_upload
    WHERE
        "FY26"::numeric <> 0
        AND "Renamed" <> '(blank)'
)
,no_customermaster AS (
    SELECT 
        l.*
    FROM 
        cols l
        LEFT OUTER JOIN rlarp.cust c ON 
            c.dba = l.shipcust
            AND c.default_rep = l.dsm
    WHERE 
        c.dba IS NULL
)
,last_season AS (
    SELECT 
        l.shipcust
        ,l.dsm
        ,l.lbs
        ,max(oseas) max_oseas
    FROM 
        cols l
        LEFT OUTER JOIN rlarp.osm_stack o ON
            l.shipcust = o.ship_dba
            AND l.dsm = o.dsm
    WHERE 
        qty <> 0 
        AND sales_usd <> 0
        AND fs_line = '41010'
        AND oseas <= 2025
        AND version = 'Actual'
    GROUP BY 
        l.shipcust
        ,l.dsm
        ,l.lbs
)
,all_with_last_season AS (
    select 
        l.*
        ,s.max_oseas
    from 
        cols l
        LEFT OUTER JOIN last_season s ON 
            s.shipcust = l.shipcust
            AND s.dsm = l.dsm
)
select 
    c.*
    ,o.bill_cust
    ,o.ship_cust
    ,o.part
    ,o.promo
    ,o.programd
    ,o.qty
    ,o.odate
    ,o.sdate
from 
    all_with_last_season c
    left outer join rlarp.osm_stack o ON 
        c.shipcust = o.ship_dba
        AND c.dsm = o.dsm
        AND c.max_oseas = o.oseas
WHERE 
    version = 'Actual'
    AND fs_line = '41010'
    AND qty <> 0
    AND sales_usd <> 0
