
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		marek
-- Create date: 22/07/2009
-- Description:	Dodaje lub uaktualnia rekord zmiany emisji w tabeli ZmianyEmisji
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddUpdateIssueChange]
	-- Add the parameters for the stored procedure here
	@issueId DECIMAL(18,0),
	@currentIssueNumer INT,
	@newIssueNumber INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

DECLARE @invoiceId INT
DECLARE @sellDate DATETIME
DECLARE @currentIssueDate DATETIME
DECLARE @newIssueDate DATETIME
DECLARE @adName VARCHAR(20)

SELECT @invoiceId=F.Id_Faktury, 
@sellDate=F.Data_Sprzedazy, 
@currentIssueDate = N.Data_W, 
@newIssueDate=N1.data_w,
@adName=R.[Id Reklamy]
FROM dbo.[Ukaże się w Nr] U
INNER JOIN Reklama R ON U.ReklamaId=R.ReklamaId
INNER JOIN Nr N ON N.Tyt=R.[tytuł] AND N.Nrw=U.[Nr Wydania]
INNER JOIN Faktury F ON F.id_Faktury=U.idFaktury
INNER JOIN Nr N1 ON N1.Tyt=R.[tytuł] AND N1.Nrw=@newIssueNumber
WHERE U.id=@issueId

IF @invoiceId IS NULL GOTO END_PROC

IF (MONTH(@sellDate)=MONTH(GETDATE()) AND YEAR(@sellDate)=YEAR(GETDATE()))
	AND
	(
	(MONTH(@currentIssueDate)=MONTH(GETDATE()) AND YEAR(@currentIssueDate)=YEAR(GETDATE()))
	OR
	(MONTH(@newIssueDate)=MONTH(GETDATE()) AND YEAR(@newIssueDate)=YEAR(GETDATE()))
	)
BEGIN

UPDATE dbo.Faktury
SET ZmianaEmisji=1
WHERE id_faktury=@invoiceId

UPDATE dbo.Faktura_Details
SET Rok=YEAR(@newIssueDate), Miesiac=MONTH(@newIssueDate), 
Nazwa_Uslugi=@adName + ' | ' + CAST(@newIssueNumber AS VARCHAR),
Nr_Wydania=@newIssueNumber
WHERE id_faktury=@invoiceId AND Nr_Wydania=@currentIssueNumer


GOTO END_PROC
END


    -- Insert statements for procedure here
	DECLARE @rows INT

	SELECT @rows = COUNT(Id) FROM zmianyEmisji WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())

	IF @rows>0
		BEGIN
			UPDATE zmianyEmisji 
			SET nastNrWyd=@newIssueNumber, dataZmiany=GETDATE()
			WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())

			--sprawdz czy nowy numer emisji nie jest taki sam jak stary numer, jesli tak to usun zmiane emisji
			DECLARE @issueNumber INT
			SELECT @issueNumber=popNrWyd FROM zmianyEmisji WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())
			IF @issueNumber=@newIssueNumber
				DELETE FROM zmianyEmisji WHERE idEmisji=@issueId AND YEAR(dataZmiany)=YEAR(GETDATE()) AND MONTH(dataZmiany)=MONTH(GETDATE())
		END
	ELSE 
		BEGIN
			INSERT INTO zmianyEmisji(idEmisji, popNrWyd, nastNrWyd, dataZmiany)
			VALUES(@issueId, @currentIssueNumer, @newIssueNumber, GETDATE())
		END

END_PROC:

END
GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

