/* primo update x gestioen reale magazzini */

-- creo tab Celle

set xact_abort on
go

begin transaction
go

create table Celle(
  IdxCella     int          not null identity constraint PK_Celle primary key,
  CodCS        nchar(2)     not null,
  CodCella     nvarchar(50) not null,
  IdxTipoCella int,
  Descrizione  nvarchar(50),
  Attiva       bit,
  IdxBlocco    int          not null constraint DF_Celle_IdxBlocco default (0),
  X            int          not null,
  Y            int          not null,
  Z            int          not null
)
go

exec sp_addextendedproperty 'MS_Description', N'indica se sia attiva, se non lo fosse è impedito caricamento nella stessa', 'SCHEMA', 'dbo', 'TABLE', 'Celle', 'COLUMN', 'Attiva'
go

exec sp_addextendedproperty 'MS_Description', 'posizione X (colonna)', 'SCHEMA', 'dbo', 'TABLE', 'Celle', 'COLUMN', 'X'
go

exec sp_addextendedproperty 'MS_Description', 'posizione Y (livello/ripiano)', 'SCHEMA', 'dbo', 'TABLE', 'Celle', 'COLUMN', 'Y'
go

exec sp_addextendedproperty 'MS_Description', 'posizione Z (profondita)', 'SCHEMA', 'dbo', 'TABLE', 'Celle', 'COLUMN', 'Z'
go

commit
go


-- update tab AnagMag

set xact_abort on
go

begin transaction
go

alter table AnagMag add
  CodCS nchar(2) not null ,
  DescMag nvarchar(50)
go

alter table AnagMag drop
  column DescrMag,
  constraint PK_AnagMag 
go

alter table AnagMag add
  constraint PK_AnagMag primary key(CodMag,CodCS)
go

set ANSI_NULLS on
go

create VIEW v_selMag
AS
SELECT        TOP (100) PERCENT CodMag AS value, DescMag AS label, CodCS AS conditio
FROM            dbo.AnagMag
ORDER BY label
go


commit
go



-- blocchi

set xact_abort on
go

begin transaction
go

create table Blocchi(
  IdxBlocco  int          not null identity constraint PK_Blocchi primary key,
  CodMag     nvarchar(50),
  CodCS      nchar(2),
  CodBlocco  nvarchar(3),
  DescBlocco nvarchar(50),
  NumX       int,
  NumY       int,
  NumZ       int
)
go

alter table Blocchi add
  constraint FK_Blocchi_AnagMag foreign key(CodMag,CodCS) references AnagMag(CodMag,CodCS) on update cascade
go

exec sp_addextendedproperty 'MS_Description', 'numero elementi X (colonne)', 'SCHEMA', 'dbo', 'TABLE', 'Blocchi', 'COLUMN', 'NumX'
go

exec sp_addextendedproperty 'MS_Description', 'numero elementi Y (livelli/ripiani)', 'SCHEMA', 'dbo', 'TABLE', 'Blocchi', 'COLUMN', 'NumY'
go

exec sp_addextendedproperty 'MS_Description', 'numero elementi Z (profondita)', 'SCHEMA', 'dbo', 'TABLE', 'Blocchi', 'COLUMN', 'NumZ'
go

commit
go



-- logUpdate

create table LogUpdateDb(
  Versione int      not null constraint PK_LogUpdateDb primary key,
  Data     datetime
)
go


-- permessi
set xact_abort on
go

begin transaction
go

create table Permessi(
  COD_PERMESSO varchar(50)  not null constraint PK_Permessi primary key,
  URL          varchar(250) not null,
  GRUPPO       int,
  NUMERO       int,
  NOME         varchar(50),
  DESCRIZIONE  varchar(50)
)
go

create table Permessi2Funzione(
  COD_PERMESSO varchar(50)  not null,
  COD_FUNZIONE nvarchar(31) not null,
  READWRITE    char(1),

  constraint PK_Permessi2Funzione primary key(COD_PERMESSO,COD_FUNZIONE)
)
go

alter table Permessi2Funzione add
  constraint FK_Permessi2Funzione_Permessi foreign key(COD_PERMESSO) references Permessi(COD_PERMESSO) on update cascade
go

commit
go



-- tipocella
set xact_abort on
go

begin transaction
go

create table TipoCella(
  IdxTipoCella int          not null identity constraint PK_TipoCella primary key,
  CodMag       nvarchar(50) not null,
  CodCS        nchar(2)     not null,
  Quantita     int          not null,
  Capienza     int          not null,
  Max_X        float,
  Max_Y        float,
  Max_Z        float,
  Max_Kg       float
)
go

alter table TipoCella add
  constraint FK_TipoCella_AnagMag foreign key(CodMag,CodCS) references AnagMag(CodMag,CodCS) on update cascade
go

commit
go


-- posizione
set xact_abort on
go

begin transaction
go

create table PosizioneUdcCorrente(
  UDC      nvarchar(50) not null,
  IdxCella int          not null,
  CodCS    nchar(2)     not null,
  DataRif  datetime,

  constraint PK_PosizioneUdcCorrente primary key(UDC,IdxCella)
)
go

alter table PosizioneUdcCorrente add
  constraint FK_PosizioneUdcCorrente_ElencoCartellini foreign key(UDC) references ElencoCartellini(UDC) on update cascade,
  constraint FK_PosizioneUdcCorrente_Celle foreign key(IdxCella) references Celle(IdxCella) on update cascade
go

create table PosizioneUdcStorico(
  UDC        nvarchar(50) not null,
  IdxCella   int          not null,
  CodCS      nchar(2)     not null,
  DataInizio datetime     not null,
  DataFine   datetime,

  constraint PK_PosizioneUdcStorico_1 primary key(UDC,IdxCella)
)
go

alter table PosizioneUdcStorico add
  constraint FK_PosizioneUdcStorico_ElencoCartellini foreign key(UDC) references ElencoCartellini(UDC) on update cascade
go

commit
go


-- viste
set xact_abort on
go

begin transaction
go

set ANSI_NULLS on
go

create VIEW v_selBlocco
AS
SELECT        IdxBlocco AS value, CodBlocco + ' - ' + DescBlocco + ' (' + CAST(NumX AS varchar) + 'x' + CAST(NumY AS varchar) + 'x' + CAST(NumZ AS varchar) + ')' AS label, 
                         CodCS, CodMag
FROM            dbo.Blocchi
go


create VIEW v_selTipoCella
AS
SELECT        IdxTipoCella AS value, 'n°' + CAST(Capienza AS varchar) + ' - ' + CAST(Max_Kg AS varchar) + 'kg (' + CAST(Max_X AS varchar) + 'x' + CAST(Max_Y AS varchar) 
                         + 'x' + CAST(Max_Z AS varchar) + ')' AS label, CodMag, CodCS
FROM            dbo.TipoCella
go


create VIEW v_UdcDetail
AS
SELECT        dbo.ElencoCartellini.UDC, dbo.ElencoCartellini.RagSociale, dbo.ElencoCartellini.Particolare, dbo.ElencoCartellini.DescParticolare, 
                         dbo.ElencoCartellini.DisegnoGrezzo, dbo.ElencoCartellini.Esponente, dbo.ElencoCartellini.DescImpianto, dbo.ElencoCartellini.DataFus, 
                         dbo.ElencoCartellini.TurnoFus, dbo.ElencoCartellini.CodImballo, dbo.ElencoCartellini.Qta, dbo.AnagStatiProdotto.DescStato, dbo.ElencoCartellini.ModDate, 
                         ISNULL(dbo.Blocchi.CodMag, N'') AS CodMag, ISNULL(dbo.Blocchi.CodBlocco, N'') AS CodBlocco, ISNULL(dbo.Celle.CodCella, N'') AS CodCella, ISNULL(dbo.Celle.X, 
                         0) AS X, ISNULL(dbo.Celle.Y, 0) AS Y, ISNULL(dbo.Celle.Z, 0) AS Z
FROM            dbo.AnagStatiProdotto RIGHT OUTER JOIN
                         dbo.ElencoCartellini ON dbo.AnagStatiProdotto.CodStato = dbo.ElencoCartellini.CodStato AND 
                         dbo.AnagStatiProdotto.CodStato = dbo.ElencoCartellini.CodStato LEFT OUTER JOIN
                         dbo.Celle INNER JOIN
                         dbo.PosizioneUdcCorrente ON dbo.Celle.IdxCella = dbo.PosizioneUdcCorrente.IdxCella AND dbo.Celle.IdxCella = dbo.PosizioneUdcCorrente.IdxCella AND 
                         dbo.Celle.IdxCella = dbo.PosizioneUdcCorrente.IdxCella INNER JOIN
                         dbo.Blocchi ON dbo.Celle.IdxBlocco = dbo.Blocchi.IdxBlocco INNER JOIN
                         dbo.AnagMag ON dbo.Blocchi.CodMag = dbo.AnagMag.CodMag AND dbo.Blocchi.CodCS = dbo.AnagMag.CodCS AND 
                         dbo.Blocchi.CodMag = dbo.AnagMag.CodMag AND dbo.Blocchi.CodCS = dbo.AnagMag.CodCS AND dbo.Blocchi.CodMag = dbo.AnagMag.CodMag AND 
                         dbo.Blocchi.CodCS = dbo.AnagMag.CodCS ON dbo.ElencoCartellini.UDC = dbo.PosizioneUdcCorrente.UDC
go

commit
go



set xact_abort on
go

begin transaction
go

exec sp_addextendedproperty 'MS_DiagramPane1', '[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "Blocchi"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 229
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
         Width = 2295
         Width = 1500
         Width = 3210
         Width = 4410
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', 'SCHEMA', 'dbo', 'VIEW', 'v_selBlocco'
go

exec sp_addextendedproperty 'MS_DiagramPaneCount', 1, 'SCHEMA', 'dbo', 'VIEW', 'v_selBlocco'
go

exec sp_addextendedproperty 'MS_DiagramPane1', '[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "AnagMag"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 118
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', 'SCHEMA', 'dbo', 'VIEW', 'v_selMag'
go

exec sp_addextendedproperty 'MS_DiagramPaneCount', 1, 'SCHEMA', 'dbo', 'VIEW', 'v_selMag'
go

exec sp_addextendedproperty 'MS_DiagramPane1', '[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "TipoCella"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 237
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', 'SCHEMA', 'dbo', 'VIEW', 'v_selTipoCella'
go

exec sp_addextendedproperty 'MS_DiagramPaneCount', 1, 'SCHEMA', 'dbo', 'VIEW', 'v_selTipoCella'
go

exec sp_addextendedproperty 'MS_DiagramPane1', '[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "AnagStatiProdotto"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 101
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "ElencoCartellini"
            Begin Extent = 
               Top = 6
               Left = 246
               Bottom = 135
               Right = 416
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "Celle"
            Begin Extent = 
               Top = 6
               Left = 454
               Bottom = 135
               Right = 624
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "PosizioneUdcCorrente"
            Begin Extent = 
               Top = 6
               Left = 662
               Bottom = 135
               Right = 832
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "Blocchi"
            Begin Extent = 
               Top = 6
               Left = 870
               Bottom = 135
               Right = 1040
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "AnagMag"
            Begin Extent = 
               Top = 6
               Left = 1078
               Bottom = 118
               Right = 1248
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
  ', 'SCHEMA', 'dbo', 'VIEW', 'v_UdcDetail'
go

exec sp_addextendedproperty 'MS_DiagramPane2', '       Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', 'SCHEMA', 'dbo', 'VIEW', 'v_UdcDetail'
go

exec sp_addextendedproperty 'MS_DiagramPaneCount', 2, 'SCHEMA', 'dbo', 'VIEW', 'v_UdcDetail'
go

commit
go


-- stored!

set xact_abort on
go

begin transaction
go

set ANSI_NULLS on
go

/***************************************
* STORED stp_BlocchiGetByCodMag
*
* ottiene l'elenco dei blocchi di magazzino dal codice Company/Sito + codice magazzino richiesti
*
* Steamware, S.E.L.
* mod: 2010.05.17
*
****************************************/
create PROCEDURE stp_BlocchiGetByCodMag
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50)
)
AS

	SELECT	* 
	FROM	Blocchi
	WHERE	CodCS = @CodCS
	AND		CodMag = @CodMag

RETURN
go

/***************************************
* STORED stp_BlocchiGetByIdx
*
* ottiene l'elenco dei blocchi di magazzino dall'Idx richiesto
*
* Steamware, S.E.L.
* mod: 2010.05.18
*
****************************************/
create PROCEDURE stp_BlocchiGetByIdx
(
	@IdxBlocco INT
)
AS

	SELECT	* 
	FROM	Blocchi
	WHERE	IdxBlocco = @IdxBlocco

RETURN
go

/***************************************
* STORED stp_celleMagGetByCodMagCS
*
* ottiene l'elenco delle celle dato codice dei magazzini e Company/Sito richiesti
*
* Steamware, S.E.L.
* mod: 2010.05.12
*
****************************************/
create PROCEDURE stp_cellaGetByCodMag
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50)
)
AS

	SELECT		Celle.*
	FROM		Blocchi INNER JOIN
	            Celle ON Blocchi.IdxBlocco = Celle.IdxBlocco
	WHERE       (Blocchi.CodCS = @CodCS) AND (Blocchi.CodMag = @CodMag)

RETURN
go

/***************************************
* STORED stp_cellaGetByIdxBlocco
*
* ottiene l'elenco delle celle dato codice del blocco di appartenenza
*
* Steamware, S.E.L.
* mod: 2010.05.17
*
****************************************/
create PROCEDURE stp_cellaGetByIdxBlocco
(
	@IdxBlocco INT
)
AS

	SELECT	*
	FROM    Celle 
	WHERE   IdxBlocco = @IdxBlocco
RETURN
go

/***************************************
* STORED stp_cellaGetByTipoCella
*
* ottiene l'elenco delle celle dato codice del tipo cella
*
* Steamware, S.E.L.
* mod: 2010.05.17
*
****************************************/
create PROCEDURE stp_cellaGetByTipoCella
(
	@IdxTipoCella INT
)
AS

	SELECT	*
	FROM    Celle 
	WHERE   IdxTipoCella = @IdxTipoCella
RETURN
go

/***************************************
* STORED stp_celleCreaMancantiBlocco
*
* crea il numero di celle richeiste e le assegna al blocco con valori default
*
* Steamware, S.E.L.
* mod: 2010.05.18
*
****************************************/
create PROCEDURE stp_celleCreaMancantiBlocco
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50),
	@IdxBlocco INT
)
AS

---------------------------------------------------------------------
-- setup iniziale valori XYZ del blocco
---------------------------------------------------------------------
DECLARE	@CodBlocco VARCHAR(3);
SET		@CodBlocco = (SELECT CodBlocco FROM Blocchi WHERE IdxBlocco = @IdxBlocco)
DECLARE @NumX INT;
DECLARE @NumY INT;
DECLARE @NumZ INT;
SET		@NumX = (SELECT NumX FROM Blocchi WHERE IdxBlocco = @IdxBlocco) ;
SET		@NumY = (SELECT NumY FROM Blocchi WHERE IdxBlocco = @IdxBlocco) ;
SET		@NumZ = (SELECT NumZ FROM Blocchi WHERE IdxBlocco = @IdxBlocco) ; 

DECLARE @Index INT ;
DECLARE @IdxTipoCella INT;


---------------------------------------------------------------------
-- creazione temp table x numeri delle dimensioni XYZ del blocco
---------------------------------------------------------------------
DECLARE @DimTable TABLE
(
	dimensione VARCHAR(1),
	valore INT
)

-- inserisco X
SET		@Index = 1 ;
WHILE	@Index <= @NumX 
    BEGIN 
		INSERT @DimTable(dimensione, valore)
		VALUES ('X', @Index)
		SET @Index = @Index + 1 ;
	END	
-- inserisco Y
SET		@Index = 1 ;
WHILE	@Index <= @NumY
    BEGIN 
		INSERT @DimTable(dimensione, valore)
		VALUES ('Y', @Index)
		SET @Index = @Index + 1 ;
	END	
-- inserisco Z
SET		@Index = 1 ;
WHILE	@Index <= @NumZ
    BEGIN 
		INSERT @DimTable(dimensione, valore)
		VALUES ('Z', @Index)
		SET @Index = @Index + 1 ;
	END	


---------------------------------------------------------------------
-- creazione temp table x schema COMPLETO posizioni blocco
---------------------------------------------------------------------
DECLARE @SchemaBlocco TABLE
(
	X INT,
	Y INT,
	Z INT
)
INSERT INTO @SchemaBlocco
SELECT X_val.valore, Y_val.valore, Z_val.valore 
FROM	(SELECT * FROM @DimTable WHERE dimensione='X') AS X_val, 
		(SELECT * FROM @DimTable WHERE dimensione='Y') AS Y_val,
		(SELECT * FROM @DimTable WHERE dimensione='Z') AS Z_val

---------------------------------------------------------------------
-- cerco primo tipo di celle per il mag indicato
---------------------------------------------------------------------
SET @IdxTipoCella = (SELECT        TOP (1) ISNULL(IdxTipoCella, 0) AS IdxTipoCella
                     FROM            TipoCella
                     WHERE        (CodCS = @CodCS) AND (CodMag = @CodMag))
---------------------------------------------------------------------
-- inserisco le celle nelle posizioni LIBERE del blocco
---------------------------------------------------------------------
INSERT INTO Celle(CodCS, CodCella, IdxTipoCella, Descrizione, Attiva, IdxBlocco,X,Y,Z) 
SELECT @CodCS, @CodBlocco + dbo.f_padLeft(CAST(sb.X AS VARCHAR),2,'0') + dbo.f_padLeft(CAST(sb.Y AS VARCHAR),2,'0') + dbo.f_padLeft(CAST(sb.Z AS VARCHAR),2,'0'), @IdxTipoCella, '-', 1, @IdxBlocco, sb.X, sb.Y, sb.Z
FROM @SchemaBlocco sb LEFT OUTER JOIN (SELECT	*
FROM	Celle 
WHERE	IdxBlocco = @IdxBlocco) c
ON sb.X = c.X AND sb.Y = c.Y AND sb.Z = c.Z
WHERE c.IdxCella IS NULL
ORDER BY sb.X,sb.Y,sb.Z ASC


RETURN
go

/***************************************
* STORED stp_ContaCelle4Blocchi
*
* effettua conteggio celle dai blocchi assegnati dato codice magazzino
*
* Steamware, S.E.L.
* mod: 2010.05.17
*
****************************************/
create PROCEDURE stp_ContaCelle4Blocchi
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50), 
	@TotCelle INT OUTPUT
)
AS

	SET @TotCelle = (SELECT		SUM(NumX * NumY * NumZ) AS Totale
	FROM		Blocchi
	WHERE		(CodCS = @CodCS) AND (CodMag = @CodMag))


RETURN @TotCelle
go

/***************************************
* STORED stp_ContaCelle4Tipo
*
* effettua conteggio celle dai tipi assegnati dato codice magazzino
*
* Steamware, S.E.L.
* mod: 2010.05.17
*
****************************************/
create PROCEDURE stp_ContaCelle4Tipo
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50), 
	@TotCelle INT OUTPUT
)
AS

	SET @TotCelle = (SELECT		SUM(Quantita * Capienza) AS Totale
	FROM		TipoCella
	WHERE		(CodCS = @CodCS) AND (CodMag = @CodMag))


RETURN @TotCelle
go

/***************************************
* STORED stp_ContaCelle4Tipo
*
* effettua conteggio celle x blocco, dato filtro su attive (si/no) e su posizioen assegnata (0 = non assegnata, 1 = assegnata)
*
* Steamware, S.E.L.
* mod: 2010.05.18
*
****************************************/
create PROCEDURE stp_ContaCelleBlocco
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50),
	@FiltAttive BIT,
	@PosAssegnata BIT,
	@TotCelle INT OUTPUT
)
AS

	SET @TotCelle = (SELECT		Count(IdxCella) AS Totale
	FROM		Celle
	WHERE		(IdxBlocco IN (SELECT IdxBlocco FROM Blocchi WHERE (CodCS = @CodCS) AND (CodMag = @CodMag))) -- cerco i blocchi
	AND			(Attiva = @FiltAttive) -- cerco attive/non attive
	AND			((ISNULL(X,0)+ISNULL(Y,0)+ISNULL(Z,0)) = (CASE @PosAssegnata WHEN 0 THEN 0 ELSE (ISNULL(X,0)+ISNULL(Y,0)+ISNULL(Z,0)) END))
	AND			((ISNULL(X,0)+ISNULL(Y,0)+ISNULL(Z,0)) > (CASE @PosAssegnata WHEN 0 THEN (ISNULL(X,0)+ISNULL(Y,0)+ISNULL(Z,0)) - 1 ELSE 0 END))
	)

RETURN @TotCelle
go

/***************************************
* STORED stp_ContaCelleCreate
*
* effettua conteggio celle create nei blocchi del magazzino
*
* Steamware, S.E.L.
* mod: 2010.05.18
*
****************************************/
create PROCEDURE stp_ContaCelleCreate
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50), 
	@TotCelle INT OUTPUT
)
AS

	SET @TotCelle = (SELECT		Count(IdxCella) AS Totale
	FROM		Celle
	WHERE		(IdxBlocco IN (SELECT IdxBlocco FROM Blocchi WHERE (CodCS = @CodCS) AND (CodMag = @CodMag)))
	)

RETURN @TotCelle
go

/***************************************
* STORED stp_ContaDeltaCelleBlocco
*
* effettua conteggio celle x blocco, restituisce la differenza tra le celle necessarie al blocco e quelle già create (0 = tutto ok)
*
* Steamware, S.E.L.
* mod: 2010.05.18
*
****************************************/
create PROCEDURE stp_ContaDeltaCelleBlocco
(
	@IdxBlocco INT,
	@DeltaCelle INT OUTPUT
)
AS
	-- calcolo quanto richiesto dai blocchi
	DECLARE @NumInBlocco INT
	SET @NumInBlocco = (SELECT		SUM(NumX * NumY * NumZ) AS Totale
	FROM		Blocchi
	WHERE		IdxBlocco = @IdxBlocco)
	
	-- calcolo quante celle create
	DECLARE @NumCelle INT
	SET @NumCelle = (SELECT		COUNT(IdxCella) AS Totale
	FROM		Celle
	WHERE		IdxBlocco = @IdxBlocco)
	
	SET @DeltaCelle = @NumInBlocco - @NumCelle


RETURN @DeltaCelle
go

commit
go


-- altra tranche di stored!
set xact_abort on
go

begin transaction
go

set ANSI_NULLS on
go

/***************************************
* STORED stp_getUdcDetailFullCode
*
* ottiene l'elenco degli UDC con i dati significativi partendo da un codice UDC COMPLETO
*
* Steamware, S.E.L.
* mod: 2010.05.24
*
****************************************/
create PROCEDURE stp_getUdcDetailFullCode
(
	@UDC VARCHAR(50),
	@CodCS VARCHAR(2)	
)
AS

SELECT        ElencoCartellini.UDC, ElencoCartellini.RagSociale, ElencoCartellini.Particolare, ElencoCartellini.DescParticolare, ElencoCartellini.DisegnoGrezzo, 
                         ElencoCartellini.Esponente, ElencoCartellini.DescImpianto, ElencoCartellini.DataFus, ElencoCartellini.TurnoFus, ElencoCartellini.CodImballo, ElencoCartellini.Qta, 
                         AnagStatiProdotto.DescStato, ElencoCartellini.ModDate, ISNULL(Blocchi.CodMag, N'') AS CodMag, ISNULL(Blocchi.CodBlocco, N'') AS CodBlocco, 
                         ISNULL(Celle.CodCella, N'') AS CodCella, ISNULL(Celle.X, 0) AS X, ISNULL(Celle.Y, 0) AS Y, ISNULL(Celle.Z, 0) AS Z
FROM            AnagStatiProdotto RIGHT OUTER JOIN
                         ElencoCartellini ON AnagStatiProdotto.CodStato = ElencoCartellini.CodStato AND AnagStatiProdotto.CodStato = ElencoCartellini.CodStato LEFT OUTER JOIN
                         Celle INNER JOIN
                         PosizioneUdcCorrente ON Celle.IdxCella = PosizioneUdcCorrente.IdxCella AND Celle.IdxCella = PosizioneUdcCorrente.IdxCella AND 
                         Celle.IdxCella = PosizioneUdcCorrente.IdxCella INNER JOIN
                         Blocchi ON Celle.IdxBlocco = Blocchi.IdxBlocco INNER JOIN
                         AnagMag ON Blocchi.CodMag = AnagMag.CodMag AND Blocchi.CodCS = AnagMag.CodCS AND Blocchi.CodMag = AnagMag.CodMag AND 
                         Blocchi.CodCS = AnagMag.CodCS AND Blocchi.CodMag = AnagMag.CodMag AND Blocchi.CodCS = AnagMag.CodCS ON 
                         ElencoCartellini.UDC = PosizioneUdcCorrente.UDC
WHERE        (ElencoCartellini.UDC = @UDC) AND (ElencoCartellini.CodCS = @CodCS)

RETURN
go

/***************************************
* STORED stp_getUdcDetailFullCode
*
* ottiene l'elenco degli UDC con i dati significativi partendo da un valore da cercare come LIKE in 
*  - UDC
*  - Particolare
*
* Steamware, S.E.L.
* mod: 2010.05.24
*
****************************************/
create PROCEDURE stp_getUdcDetailLikeSearch
(
	@searchVal VARCHAR(50),
	@CodCS VARCHAR(2)	
)
AS

SELECT        ElencoCartellini.UDC, ElencoCartellini.RagSociale, ElencoCartellini.Particolare, ElencoCartellini.DescParticolare, ElencoCartellini.DisegnoGrezzo, 
                         ElencoCartellini.Esponente, ElencoCartellini.DescImpianto, ElencoCartellini.DataFus, ElencoCartellini.TurnoFus, ElencoCartellini.CodImballo, ElencoCartellini.Qta, 
                         AnagStatiProdotto.DescStato, ElencoCartellini.ModDate, ISNULL(Blocchi.CodMag, N'') AS CodMag, ISNULL(Blocchi.CodBlocco, N'') AS CodBlocco, 
                         ISNULL(Celle.CodCella, N'') AS CodCella, ISNULL(Celle.X, 0) AS X, ISNULL(Celle.Y, 0) AS Y, ISNULL(Celle.Z, 0) AS Z
FROM            AnagStatiProdotto RIGHT OUTER JOIN
                         ElencoCartellini ON AnagStatiProdotto.CodStato = ElencoCartellini.CodStato AND AnagStatiProdotto.CodStato = ElencoCartellini.CodStato LEFT OUTER JOIN
                         Celle INNER JOIN
                         PosizioneUdcCorrente ON Celle.IdxCella = PosizioneUdcCorrente.IdxCella AND Celle.IdxCella = PosizioneUdcCorrente.IdxCella AND 
                         Celle.IdxCella = PosizioneUdcCorrente.IdxCella INNER JOIN
                         Blocchi ON Celle.IdxBlocco = Blocchi.IdxBlocco INNER JOIN
                         AnagMag ON Blocchi.CodMag = AnagMag.CodMag AND Blocchi.CodCS = AnagMag.CodCS AND Blocchi.CodMag = AnagMag.CodMag AND 
                         Blocchi.CodCS = AnagMag.CodCS AND Blocchi.CodMag = AnagMag.CodMag AND Blocchi.CodCS = AnagMag.CodCS ON 
                         ElencoCartellini.UDC = PosizioneUdcCorrente.UDC
WHERE        (ElencoCartellini.CodCS = @CodCS) AND ((ElencoCartellini.UDC like '%'+ @searchVal+'%') OR (ElencoCartellini.Particolare like '%'+ @searchVal+'%'))

RETURN
go

/***************************************
* STORED stp_magGetByCodMag
*
* ottiene l'elenco dei magazzini dal codice Company/Sito + codice magazzino richiesti
*
* Steamware, S.E.L.
* mod: 2010.05.12
*
****************************************/
create PROCEDURE stp_magGetByCodMag
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50)
)
AS

	SELECT	* 
	FROM	AnagMag
	WHERE	CodCS = @CodCS
	AND		CodMag = @CodMag

RETURN
go

/***************************************
* STORED stp_magGetByCS
*
* ottiene l'elenco dei magazzini dal codice Company/Sito richiesto
*
* Steamware, S.E.L.
* mod: 2010.05.12
*
****************************************/
create PROCEDURE stp_magGetByCS
(
	@CodCS VARCHAR(2)
)
AS

	SELECT * 
	FROM AnagMag
	WHERE CodCS = @CodCS

RETURN
go

/***************************************
* STORED stp_TipoCellaGetByCodMag
*
* ottiene l'elenco dei tipi di celle dal codice Company/Sito + codice magazzino richiesti
*
* Steamware, S.E.L.
* mod: 2010.05.17
*
****************************************/
create PROCEDURE stp_TipoCellaGetByCodMag
(
	@CodCS VARCHAR(2),
	@CodMag VARCHAR(50)
)
AS

	SELECT	* 
	FROM	TipoCella
	WHERE	CodCS = @CodCS
	AND		CodMag = @CodMag

RETURN
go

/***************************************
* STORED stp_TipoCellaGetByIdx
*
* ottiene l'elenco dei tipi di celle dal codice Idx
*
* Steamware, S.E.L.
* mod: 2010.05.19
*
****************************************/
create PROCEDURE stp_TipoCellaGetByIdx
(
	@IdxTipoCella INT
)
AS

	SELECT	* 
	FROM	TipoCella
	WHERE	IdxTipoCella = @IdxTipoCella

RETURN
go

commit
go


-- update UDC con "U" iniziale
set xact_abort on
go

begin transaction
go

drop procedure stp_getStatoByUDC
go

set ANSI_NULLS on
go

/***************************************
* STORED stp_UDC_insNew
*
* crea un nuovo record nella TabStatoOdpUdc e restituisce il codice UDC appena creato
*
* Steamware, S.E.L.
* mod: 2010.04.28
*
****************************************/
alter PROCEDURE stp_UDC_insNew
(
	@CodCS VARCHAR(2),
	@Flusso VARCHAR(2),
	@Anno VARCHAR(2),
	@Tara FLOAT,
	@CodImballo AS VARCHAR(50),
	@CodTipoDichiaraz CHAR(1),
	@CodOperatore AS VARCHAR(50),
	@CodEvento VARCHAR(10)
)
AS

-- DECLARE iniziali
DECLARE @UDC AS VARCHAR(20)
DECLARE @numFlu AS INT
DECLARE @numUdc AS INT
DECLARE @nextUdc AS INT
	
------------------------------------------------------------------------------------------------------
-- Flusso
------------------------------------------------------------------------------------------------------
-- controllo se esiste il flusso (bilancia)...
SET @numFlu = (
	SELECT count(*)
	FROM AnagBilance
	WHERE	CodBilancia	= @Flusso
)
-- ...sennò lo creo...
IF(@numFlu = 0)
	BEGIN
		-- se c'è inserisco in tab
		INSERT INTO AnagBilance(CodBilancia, DescrImpianto, CodCS)
		VALUES (@Flusso, @Flusso, @CodCS)
	END
------------------------------------------------------------------------------------------------------

		
------------------------------------------------------------------------------------------------------
-- UDC
------------------------------------------------------------------------------------------------------
-- controllo se ci sia già un UDC per company / flusso anno
BEGIN TRAN
	-- cerco nella tab contatori UDC l'ultimo valido
	SET @numUdc = (
		SELECT count(*)
		FROM ContatoriUdc
		WHERE	CodCS		=	@CodCS
		AND		Flusso		=	@Flusso
		AND		Anno		=	@Anno
	)
	-- controllo se record c'è...
	IF(@numUdc > 0)
		BEGIN
			-- se c'è incremento di 1 in tab
			UPDATE ContatoriUdc
			SET LastIdx = LastIdx  + 1
			WHERE	CodCS		=	@CodCS
			AND		Flusso		=	@Flusso
			AND		Anno		=	@Anno
		END
	ELSE
		BEGIN
			-- lo creo!
			INSERT INTO ContatoriUdc(CodCS, Flusso, Anno, LastIdx)
			VALUES (@CodCS, @Flusso, @Anno, 1)
		END		
	-- aggiorno numero UDC
	SET @numUdc = (
		SELECT LastIdx
		FROM ContatoriUdc
		WHERE	CodCS		=	@CodCS
		AND		Flusso		=	@Flusso
		AND		Anno		=	@Anno
	)
COMMIT TRAN
------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------
-- Ciclo principale x inserimento nuovo record
------------------------------------------------------------------------------------------------------
-- ottengo il nuovo codice UDC completo
SET @UDC = 'U' + @CodCS + @Flusso + @Anno + dbo.f_padLeft(CAST(@numUdc AS VARCHAR(6)), 6, '0')
	
-- inserisco un nuovo record
INSERT INTO ElencoCartellini(CodCS, UDC, Tara, IdxPosizione, Qta, CodImballo, CreateDate, ModDate)
VALUES	(@CodCS, @UDC, @Tara, 0, 0, @CodImballo, GETDATE(), GETDATE())
------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------
-- restituisco la tab dati con l'udc appena inserito
------------------------------------------------------------------------------------------------------
SELECT * 
FROM ElencoCartellini
WHERE  UDC = @UDC
------------------------------------------------------------------------------------------------------

RETURN
go

/***************************************
* STORED stp_UDC_insNewFull
*
* crea un nuovo record nella TabStatoOdpUdc FULL (con pesi, qta...) e restituisce il codice UDC appena creato
*
* Steamware, S.E.L.
* mod: 2010.04.28
*
****************************************/
alter PROCEDURE stp_UDC_insNewFull
(
	@CodCS VARCHAR(2),
	@Flusso VARCHAR(2),
	@Anno VARCHAR(2),
	@CodCliente VARCHAR(6),
	@Particolare VARCHAR(15),
	@CodImpianto AS VARCHAR(50),
	@CodStampo VARCHAR(8),
	@Esponente VARCHAR(6),
	@Figura VARCHAR(4),
	@DataFus DATETIME,
	@TurnoFus INT,
	@CodImballo VARCHAR(15),
	@CodSoggetto VARCHAR(16),	
	@Tara FLOAT,
	@IdxPosizione INT,
	@CodTipoDichiaraz CHAR(1),
	@CodEvento VARCHAR(10),
	@Qta DECIMAL(10,2),
	@PesoTot FLOAT,
	@PesoCad FLOAT,
	@CodStato VARCHAR(50),
	@UDC_parent VARCHAR(20)
)
AS

-- DECLARE iniziali
DECLARE @UDC AS VARCHAR(20)
DECLARE @RagSociale AS VARCHAR(35)
DECLARE @DescParticolare AS VARCHAR(30)
DECLARE @DescImpianto AS VARCHAR(50)
DECLARE @DisegnoGrezzo AS VARCHAR(30)
DECLARE @NumCont AS INT
DECLARE @numFlu AS INT
DECLARE @numUdc AS INT
DECLARE @nextUdc AS INT

------------------------------------------------------------------------------------------------------
-- Caricamento Dati da anagrafica
------------------------------------------------------------------------------------------------------
-- cerco la ragione sociale...
SET @RagSociale = (
	SELECT        ISNULL(RagSociale, 'ND') AS RagSociale
	FROM            RilPro.AnagClienti
	WHERE        (CodCliente = @CodCliente)
)

-- Cerco descrizione del particolare...
SET @DescParticolare = (
	SELECT        ISNULL(DescParticolare, 'ND') AS DescParticolare
	FROM            RilPro.AnagParticolari
	WHERE        (Particolare = @Particolare)
)

-- cerco codice disegno grezzo
SET @DisegnoGrezzo = (
	SELECT        ISNULL(DisegnoGrezzo, 'ND') AS DescParticolare
	FROM            RilPro.AnagParticolari
	WHERE        (Particolare = @Particolare)
)

-- cerco descrizione Impianto
SET @DescImpianto = (
	SELECT        ISNULL(DescImpianto, 'ND') AS DescImpianto
	FROM            AnagImpianti
	WHERE        (CodImpianto = @CodImpianto)
)



-- Calcolo contatore intero successivo x il contenitore...
SET @NumCont = (
	SELECT      ISNULL(MAX(NumCont), 0) + 1 AS NumCont
	FROM        ElencoCartellini
	WHERE       (Particolare = @Particolare)
	AND			(DataFus = @DataFus)
	AND			(TurnoFus = @TurnoFus)
	AND			(CodImpianto = @CodImpianto)
	AND			(CodStampo = @CodStampo)
	AND			(Figura = @Figura)	
)


------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------
-- Flusso
------------------------------------------------------------------------------------------------------
-- controllo se esiste il flusso (bilancia)...
SET @numFlu = (
	SELECT count(*)
	FROM AnagBilance
	WHERE	CodBilancia	= @Flusso
)
-- ...sennò lo creo...
IF(@numFlu = 0)
	BEGIN
		-- se c'è inserisco in tab
		INSERT INTO AnagBilance(CodBilancia, DescrImpianto, CodCS)
		VALUES (@Flusso, @Flusso, @CodCS)
	END
------------------------------------------------------------------------------------------------------

		
------------------------------------------------------------------------------------------------------
-- UDC
------------------------------------------------------------------------------------------------------
-- controllo se ci sia già un UDC per company / flusso anno
BEGIN TRAN
	-- cerco nella tab contatori UDC l'ultimo valido
	SET @numUdc = (
		SELECT count(*)
		FROM ContatoriUdc
		WHERE	CodCS		=	@CodCS
		AND		Flusso		=	@Flusso
		AND		Anno		=	@Anno
	)
	-- controllo se record c'è...
	IF(@numUdc > 0)
		BEGIN
			-- se c'è incremento di 1 in tab
			UPDATE ContatoriUdc
			SET LastIdx = LastIdx  + 1
			WHERE	CodCS		=	@CodCS
			AND		Flusso		=	@Flusso
			AND		Anno		=	@Anno
		END
	ELSE
		BEGIN
			-- lo creo!
			INSERT INTO ContatoriUdc(CodCS, Flusso, Anno, LastIdx)
			VALUES (@CodCS, @Flusso, @Anno, 1)
		END
	-- aggiorno numero UDC
	SET @numUdc = (
		SELECT LastIdx
		FROM ContatoriUdc
		WHERE	CodCS		=	@CodCS
		AND		Flusso		=	@Flusso
		AND		Anno		=	@Anno
	)
COMMIT TRAN
------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------
-- Ciclo principale x inserimento nuovo record
------------------------------------------------------------------------------------------------------
BEGIN TRAN
	-- ottengo il nuovo codice UDC completo
	SET @UDC = 'U' + @CodCS + @Flusso + @Anno + dbo.f_padLeft(CAST(@numUdc AS VARCHAR(6)), 6, '0')
		
	-- inserisco un nuovo record
	INSERT INTO ElencoCartellini(UDC, CodCS, CodCliente, RagSociale, Particolare, DescParticolare, DisegnoGrezzo, Esponente, CodImpianto, DescImpianto, CodStampo, Figura, DataFus, TurnoFus, CodImballo, CodSoggetto, NumCont, Tara, Qta, CodStato, IdxPosizione, PesoTot, PesoCad, CreateDate, ModDate)
	VALUES	(@UDC, @CodCS, @CodCliente, @RagSociale, @Particolare, @DescParticolare, @DisegnoGrezzo, @Esponente, @CodImpianto, @DescImpianto, @CodStampo, @Figura, @DataFus, @TurnoFus, @CodImballo, @CodSoggetto, @NumCont, @Tara, @Qta, @CodStato, @IdxPosizione, @PesoTot, @PesoCad, GETDATE(), GETDATE())

	-- inserisco relazione aprent-child tra UDC vecchio (tara) e nuovo (pesa)
	INSERT INTO RelazUDC(UDC_parent, UDC_child)
	VALUES (@UDC_parent, @UDC)
COMMIT TRAN
------------------------------------------------------------------------------------------------------

/*
------------------------------------------------------------------------------------------------------
-- Salvataggio dati evento in tab StoricoEventi
------------------------------------------------------------------------------------------------------
INSERT INTO StoricoEventi(DataEv, CodEvento, CodOperatore, CodTipoDichiaraz, CodCS, UDC, Qta, PesoTot, PesoCad, Particolare, CodStato, CodStampo, Figura, FiguraIncisa)
VALUES	(GETDATE(), @CodEvento, @CodOperatore, @CodTipoDichiaraz, @CodCS, @UDC, @Qta, @PesoTot, @PesoCad, @Particolare, @CodStato, @CodStampo, @Figura, @FiguraIncisa)
------------------------------------------------------------------------------------------------------
*/

------------------------------------------------------------------------------------------------------
-- restituisco la tab dati con l'udc appena inserito
------------------------------------------------------------------------------------------------------
SELECT * 
FROM ElencoCartellini
WHERE  UDC = @UDC
------------------------------------------------------------------------------------------------------

RETURN
go

commit
go






-- registro versione...
INSERT INTO [dbo].[LogUpdateDb] ([Versione],[Data]) VALUES(51, GETDATE())
GO