/*
This query will return a single running number as long as its in stock. 

To get all data comment out the lfdnr in the where statmen
*/
use AlplaPROD_test1

DECLARE @runningNumber nvarchar(max) = '[runningNr]' -- when saving in lst should be '[runningNr]'

select x.idartikelVarianten as av,
ArtikelVariantenAlias as alias,
x.Lfdnr as runningNumber,
round(sum(EinlagerungsMengeVPKSum),0) as totalPallets,
sum(EinlagerungsMengeSum) as totalPalletQTY, 
round(sum(VerfuegbareMengeVPKSum),0) as avaliblePallets,
sum(VerfuegbareMengeSum) as avaliablePalletQTY,
sum(case when c.Description LIKE '%COA%' then GesperrteMengeVPKSum else 0 end) as coaPallets,
sum(case when c.Description LIKE '%COA%' then GesperrteMengeSum else 0 end) as coaQTY, 
sum(case when c.Description NOT LIKE '%COA%' or x.IdMainDefect = -1 then GesperrteMengeVPKSum else 0 end) as heldPallets,
sum(case when c.Description NOT LIKE '%COA%' or x.IdMainDefect = -1 then GesperrteMengeSum else 0 end) as heldQTY
,IdProdPlanung as lot
,IdAdressen as addressID,
x.AdressBez as addressDescription
,x.IdLagerAbteilung as locationId
,x.lagerabteilungkurzbez as location
,lot.machine
,produktionsdatummin as productionDate
,'728'
    + RIGHT(CAST(YEAR(produktionsdatummin) AS varchar(4)), 1)
    + CAST(DATEDIFF(DAY, DATEFROMPARTS(YEAR(produktionsdatummin), 1, 1), produktionsdatummin) + 1 AS varchar(3))
    + CAST(lot.machine AS varchar(10))  as batch
,c.Description as blockingReason
,x.Barcode as barcode
--,*
from dbo.[V_LagerPositionenBarcodes] (nolock) x

left join
dbo.T_EtikettenGedruckt as l(nolock) on 
x.Lfdnr = l.Lfdnr AND l.Lfdnr > 1

left join

(SELECT *
  FROM [dbo].[T_BlockingDefects] where Active = 1) as c
  on x.IdMainDefect = c.IdBlockingDefect

/* 
get lot and machine info
*/
left join
(select location as machine,
runningnumber as lot
,planstart
,planend
from [test1_AlplaPROD2.0_Read].[productionScheduling].[ProductionLot] (nolock) x

left join
[test1_AlplaPROD2.0_Read].[masterData].[Machine] (nolock) m on
m.id = x.machineid) as lot on 
lot.lot = IdProdPlanung
/* 
The data below will be controlled by the user in excel by default everything will be passed over
 IdAdressen = 3
*/
where IdArtikelTyp = 1  
and x.IdWarenlager in (1) -- the pallet must be in ppoo 
and x.Lfdnr = @runningNumber -- comment this out when you want to get everything

group by x.idartikelVarianten, ArtikelVariantenAlias, c.Description, IdAdressen,
x.AdressBez , x.Lfdnr,
IdProdPlanung
,x.IdLagerAbteilung
,x.lagerabteilungkurzbez
,lot.machine
,produktionsdatummin
,x.Barcode

order by x.IdArtikelVarianten