





/*ApiCrmDocumentsView*/
CREATE VIEW [dbo].[ApiBarcodesView]
AS


SELECT [Kod] Barcode,
case when(ZapisType ='Towary') then 4 else case when(ZapisType ='DokHandlowe') then 0 else 0 end  end Type, [Zapis] objectId,'' UM, 1 State
from [dbo].[KodyKreskowe]
where ZapisType = 'Towary'


UNION
select  SUBSTRING(NumerPelny,1,2)+RIGHT('000'+CAST(Definicja AS VARCHAR(3)),3) +RIGHT('000000'+CAST(ID AS VARCHAR(6)),6)  Barcode,  

10 Type, ID  objectId, '' UM, 1 State from dbo.DokHandlowe where Definicja = 82



-- 
/*
UNION
select Name Barcode, 11 Type, ErpId  objectId,'' UM, 0 State from [dbo].[ApiStockLocationsViewNN]
*/
--select *  from [dbo].[KodyKreskowe] where ZapisType = 'DokHandlowe'
UNION ALL
sELECT     UPPER(f.Data) AS Barcode, 6 Type, prac.ID objectId,'' UM, 1 State
FROM         dbo.Pracownicy AS prac INNER JOIN
                      dbo.Features AS f ON f.ParentType = 'Pracownicy' AND f.Name = 'Pestka' AND f.Parent = prac.ID

-- usuwamy stąd inaczej będą szukane te kody
--UNION ALL select Barcode, 42 type, Id [objectId], UM, RepositoryId State from dbo.ApiWmsStocks where ISNULL(Barcode,'')<>''


/*
UNION

select  RIGHT(1000000 + p.ID , 6) Barcode,10 as Type,p.ID objectId, '' UM, 0 State 

from dbo.Zasoby  z JOIN dbo.DokHandlowe d ON z.PartiaDokument = d.Id
JOIN dbo.PozycjeDokHan p ON p.Dokument = d.ID and p.Ident = z.PartiaPozycjaIdent
JOIN  dbo.OkresyMag o  ON o.ID = z.Okres and o.Zamkniety = 0
where Kierunek =1 and  PartiaTyp =1 and z.Magazyn =1 
--and z.Towar = 16246

*/
UNION ALL
SELECT  [Barcode]
      ,[type]
      ,[objectId]
      ,[UM]
      ,[State]
  FROM [dbo].[ApiBarcodes]
  where State=0


  UNION ALL
select [Kod] Barcode, 12 Type, ID objectId,'' UM, 1 State  from dbo.Lokalizacje where ISNULL(Kontrahent,0)=0

GO


