ALTER PROCEDURE HM.hm_DK_UsunDokumentHn
	@idDk INT,
	@bAnuluj SMALLINT,
	@opis varchar(80),
	@userId INT,
	@kodUser varchar(40)
AS
	SET NOCOUNT ON

	DECLARE @err INT
	DECLARE @idTr INT
	DECLARE @idKh INT
	DECLARE @idOd INT
	DECLARE @idKhAd INT
	DECLARE @idOdAd INT
	DECLARE @serianr INT
	DECLARE @seriadzial INT
	DECLARE @iddokkoryg INT
	DECLARE @idlastkorekt INT
	DECLARE @idTransOrig INT
	DECLARE @idDkPn INT

	DECLARE @kodDk varchar(40)

	DECLARE @seria varchar(5)

	DECLARE @subtyp SMALLINT
	DECLARE @typ SMALLINT
	DECLARE @idBazy SMALLINT
	DECLARE @exp_fk	SMALLINT
	DECLARE @flag SMALLINT
	DECLARE @okres SMALLINT
	DECLARE @bKontrolaNumeracji SMALLINT
	DECLARE @bufor SMALLINT
	DECLARE @anulowany SMALLINT

	DECLARE @dataDk DATETIME
	DECLARE @wart FLOAT
	DECLARE @wartosc FLOAT
	DECLARE @wartosc_rozl FLOAT

	DECLARE @idLongNames TABLE (id INT)
	DECLARE @tIdOperKor TABLE (id INT)

	DECLARE @tLuzneZwiazki TABLE (id INT, idZw INT, baseZw SMALLINT)
	DECLARE @iloscWierszy INT

	DECLARE @idPeriodicSaleReport INT


	SELECT @kodDk = kod, @typ = typ, @subtyp = subtyp, @dataDk = data, @wart = netto + vat,
		@seria = seria, @seriadzial = seriadzial, @okres = okres, @serianr = serianr,
		@exp_fk = exp_fk, @flag = flag, @bufor = bufor, @iddokkoryg = ISNULL(iddokkoryg, 0), @anulowany = anulowany,
		@idKh = ISNULL(khid, 0),  @idKhAd = ISNULL(khadid, 0),
		@idOd = ISNULL(odid, 0),  @idOdAd = ISNULL(odadid, 0),
		@idPeriodicSaleReport = idPeriodicSaleReport
	FROM DK WHERE id = @idDk
	IF (@typ = 0)
		SET @idBazy = 16
	ELSE
		SET @idBazy = 34
	IF ((0 <> @iddokkoryg) OR (0x0020 & @flag <> 0))
	BEGIN
		SET @idTr = 0
		SELECT @idTransOrig = ISNULL(id, 0) FROM TR WHERE owner_base = @idBazy AND owner_id = @iddokkoryg AND typ = 1
	END
	ELSE
	BEGIN
		SELECT @idTr = ISNULL(id, 0) FROM TR WHERE owner_base = @idBazy AND owner_id = @idDk AND typ = 1
		SET @idTransOrig = @idTr
	END


	IF (@wart IS NULL)
	BEGIN
		SET @err = 4
		RETURN @err
	END


    exec @err = hm_DK_check_UsunDokumentHn @idDk
    if @err <> 0
        return @err

	IF ((50 = @subtyp) AND (@bAnuluj = 0))
	BEGIN
		IF (EXISTS(SELECT id FROM ZZ WHERE typ = 150 AND id1 = @idDk and baza1 = @idBazy))
		BEGIN
			SET @err = -4308
			RETURN @err
		END
	END


	SET @bKontrolaNumeracji = 1
	IF (0 <> @bAnuluj)
		SET @bKontrolaNumeracji = 0
	IF (32 = (32 & @exp_fk))
		SET @bKontrolaNumeracji = 0
	IF (16384 = (16384 & @flag))
		SET @bKontrolaNumeracji = 0
	IF (0 <> @bufor)
		SET @bKontrolaNumeracji = 0
	IF (0 <> @bKontrolaNumeracji)
	BEGIN
		UPDATE DK SET seria = @seria, seriadzial = @seriadzial, okres = @okres, serianr = 2147483647 FROM DK WITH (HOLDLOCK) WHERE seria = @seria AND seriadzial = @seriadzial AND okres = @okres AND serianr = @serianr
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err
		IF (EXISTS(SELECT TOP 1 id FROM DK WHERE seria = @seria AND seriadzial = @seriadzial AND okres = @okres AND serianr > @serianr AND serianr <> 2147483647 order by seria ASC, seriadzial ASC, okres ASC, serianr ASC))
		BEGIN
			SET @err = -4203
			RETURN @err
		END
	END


	INSERT INTO ZZ (flag, subtyp, typ, baza1, id1, baza2, id2, kod1, kod2, data,
		termin, ilosc, cena, waluta, opis, id3, baza3, ilosc2, magazyn, iddkreal,id3pos)
	VALUES (0, @subtyp, 160, @idBazy, @idDk, 16, 0, @kodDk, @kodUser, @dataDk,
		GETDATE(), 0, @wart, '', '', NULL, 0, 0, 0, NULL, NULL)



	DECLARE @idKontraktu INT
	IF (@subtyp IN (135, 136, 137, 151, 152, 153))
	BEGIN
		EXEC @idKontraktu = hm_ZZ_GetIdKontraktu @idDk, 16
	END


	IF (@subtyp IN (108, 128, 112, 113, 134, 135, 136, 137, 150, 151, 152, 153))
	BEGIN

		INSERT LOCAL_LOG (baseName, rec_id, operation, term)
		SELECT 'ZZ', ZZ.id, 4, @@SPID FROM ZZ WHERE typ = 152 AND id2 = @idDk and baza2 = @idBazy
		DELETE FROM ZZ WHERE typ = 152 AND id2 = @idDk and baza2 = @idBazy
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err
	END


	IF ((@subtyp = 115) OR (@subtyp = 121))
	BEGIN
		IF (32 = (32 & @exp_fk))
		BEGIN
			DELETE FROM ZZ WHERE typ = 151 AND id2 = @idDk and baza2 = @idBazy
			SET @err = @@ERROR
			IF (@err <> 0) RETURN @err
		END
		ELSE
		BEGIN
			IF (EXISTS(SELECT id FROM ZZ WHERE typ = 151 AND id2 = @idDk and baza2 = @idBazy))
			BEGIN
				SET @err = -4330
				RETURN @err
			END
		END
	END


	IF (16 = @idBazy)
	BEGIN
		EXEC @err = hm_RZ_UsunRezerwacje_DK @idDk
		IF (@err <> 0) RETURN @err

		EXEC @err = hm_CP_UsunCenniki @idDk, @idBazy
		IF (@err <> 0) RETURN @err
	END

	IF (0 <> @iddokkoryg OR (0x0020 & @flag <> 0))
	BEGIN
		INSERT @tIdOperKor
			SELECT id FROM OP WHERE (OP.owner_base=18 AND owner_id IN (SELECT id FROM DP WHERE super = @idDk))


		DELETE FROM OP WHERE id IN (SELECT id FROM @tIdOperKor)
	END
	ELSE IF (@idTr <> 0)
	BEGIN

		DELETE FROM OP WHERE id_transakcji = @idTr
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err

		DELETE FROM TR WHERE id = @idTr
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err
	END


	DELETE FROM RV WHERE dkid = @idDk
	SET @err = @@ERROR
	IF (@err <> 0) RETURN @err


	IF ((@subtyp = 69) OR (@subtyp = 100) OR (@subtyp = 113) OR (@subtyp = 139)
			OR (@subtyp = 68) OR (@subtyp = 99) OR (@subtyp = 128) OR (@subtyp = 138))
	BEGIN
		DELETE FP FROM FP WITH (ROWLOCK, INDEX(UC_FP_FUNDUSZ_IDDK)) WHERE idDk = @idDk
		SET @err = @@ERROR
		IF @err <> 0 RETURN @err
	END


	INSERT @idLongNames
		SELECT idlongname FROM DP WHERE super = @idDk


	if ((0 = @anulowany) AND (0 = @bufor)
		AND (116 <> @subtyp) AND (117 <> @subtyp) AND (118 <> @subtyp) AND (119 <> @subtyp))
	BEGIN
		SELECT @idDkPn = ISNULL(id, 0) FROM PN WHERE dkid = @idDk

		IF (0 <> @idDkPn)
		BEGIN
			EXEC @err =  hm_PN_delete @idDkPn, @kodUser
			IF (@err <> 0) RETURN @err
		END
	END

	if (0 = @bAnuluj)
	BEGIN
	 	-- usuniecie korekty zbiorczej przychodu dotyczy wielu transakcji
		IF (SELECT OBJECT_ID('tempdb..#ChangedTr')) IS NOT NULL
			DROP TABLE #ChangedTr
		CREATE TABLE #ChangedTr (id INT PRIMARY KEY)

		IF ( @flag & 0x0020 <> 0 )
		BEGIN
			INSERT #ChangedTr
				select t.id from hm.dk d 
				inner join HM.ZZ z on d.id = z.id2 and z.id1 = @idDk and z.typ = 201
				inner join hm.tr t on t.owner_id = d.id and t.owner_base = @idBazy
				union ALL
				select t.id from hm.dk d 
				inner join hm.tr t on t.owner_id = d.iddokkoryg 
				where d.id = @idDk and d.iddokkoryg IS NOT NULL and t.owner_base = @idBazy
		END

       if (((0 <> @iddokkoryg) OR (0x0020 & @flag <> 0)) AND (0 <> @bufor))
        BEGIN


    	    UPDATE TR SET flag = (~16384 & flag) WHERE id = @idTransOrig OR id IN ( SELECT id FROM #ChangedTr )
        	EXEC hm_TR_RecalcStatus @idTransOrig
        END


 		DELETE FROM DP WHERE super = @idDk
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err


		DELETE FROM NT WHERE typ = 0 AND baza = @idBazy AND super = @idDk
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err

		DELETE FROM [HM].[DocumentAttachments] WHERE DocumentId = @idDk AND TableId = @idBazy
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err

		DELETE FROM [HM].[DocumentNotes] WHERE DocumentId = @idDk AND TableId = @idBazy
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err

		--usuwanie flagi korekty
		--nie w buforze	i	  korekta zwykla  lub		zbiorcza		
		IF((0 = @bufor) AND (0 <> @iddokkoryg OR (0x0020 & @flag <> 0)))
		BEGIN
			declare @targetTable TABLE
			(id int, idOryg int, idKorekty int );	

			WITH Tmp as(
				select dk.id id, dk.id idOryg,dk.id idKorekty from HM.DK dk 
				inner join hm.zz z on DK.id = z.id2 and z.id1 = @idDK and z.typ=201 and z.baza1 = @idBazy and z.baza2 = @idBazy
				union ALL
				select d.iddokkoryg id, d.iddokkoryg ,d.iddokkoryg from HM.DK d 
				where d.id=@idDK and d.iddokkoryg is not null
				union ALL
				select 0 id, d.idOryg,dk.id from HM.DK dk 
				inner join Tmp d on d.id=dk.iddokkoryg and dk.id<>@idDK
				union ALL
				select 0 id,t1.idOryg,dk.id from HM.DK dk 
				inner join HM.ZZ z on DK.id = z.id1 and z.baza1 = @idBazy and z.baza2 = @idBazy 
				inner join Tmp t1 on t1.id= z.id2 and z.typ=201 and z.baza1 = @idBazy and z.baza2 = @idBazy 
			)
			, Tmp2 as (			-- maxID potencjalnie z tych zdejmujemy flage
				select max(t1.idKorekty) maxID,t1.idOryg
				from Tmp t1
				where t1.idKorekty<@idDK
				group by t1.idOryg 
			)
			, Tmp3 as(
				select dk.id id, dk.id idOryg,dk.id idKorekty, z.id1 maxID, 0 n from HM.DK dk 
				inner join HM.ZZ z on dk.id = z.id2 and z.typ = 201
				inner join Tmp2 t2 on z.id1 = t2.maxID
				union ALL
				select 0 id, t.idOryg,dk.id, t.maxID, 1 n from HM.DK dk 
				inner join Tmp3 t on t.id=dk.iddokkoryg and t.maxID<dk.id
				union ALL
				select 0 id,t.idOryg,dk.id, t.maxID, 2 n from HM.DK dk 
				inner join HM.ZZ z on dk.id = z.id1 
				inner join Tmp3 t on t.id = z.id2 and z.typ=201 and t.maxID<dk.id
			)
			, Tmp4 as (			-- tu mam wszystkie pozostale galezie ktore koryguja dokument z ktorego chce zdjac flage.
				select max(t3.idKorekty) maxID2, t3.idOryg, MAX(t3.maxID) idBazowe
				from Tmp3 t3
				where t3.idKorekty>t3.maxID and t3.idKorekty <> @idDK
				group by t3.idOryg
			)
			--i jezeli jest jakas inna scieszka to nie zdejmujemy flagi
			insert into @targetTable(id,idOryg,idKorekty) 
				select t2.maxID, t2.idOryg,0 from Tmp2 t2 where t2.maxid not in (select idbazowe from Tmp4);

			IF EXISTS(select 1 from @targetTable)
			BEGIN
				update d set d.flag=(~8192 & d.flag)
				from HM.DK d inner join @targetTable tt on d.id = tt.id 

				INSERT INTO LOCAL_LOG (baseName, rec_id, operation, term) SELECT 'DK', d.id, 3, @@SPID 
				from HM.DK d inner join @targetTable tt on d.id = tt.id

				-- usuwanie korekty faktury powstalej z paragonu --> zdejmujemy znacznik 'korygowany' rowniez z paragonu
				update d set d.flag=(~8192 & d.flag) from hm.DK d
				inner join HM.ZZ z 
				on d.id=z.id1 AND z.typ=150 AND z.baza1=z.baza2 AND baza1=16
				inner join @targetTable tt 
				on z.id2=tt.id 

				INSERT INTO LOCAL_LOG (baseName, rec_id, operation, term) SELECT 'DK', d.id, 3, @@SPID  from hm.DK d
				inner join HM.ZZ z 
				on d.id=z.id1 AND z.typ=150 AND z.baza1=z.baza2 AND baza1=16
				inner join @targetTable tt 
				on z.id2=tt.id 
			END

		END

		DELETE FROM DK WHERE id = @idDk
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err


		IF 0 <> @idKhAd
		BEGIN
			EXEC @err = hm_AD_UsunDk @idKhAd
			SET @err = @@ERROR
			IF (@err <> 0) RETURN @err
		END

		IF 0 <> @idOdAd AND @idKhAd <> @idOdAd
		BEGIN
			EXEC @err = hm_AD_UsunDk @idOdAd
			SET @err = @@ERROR
			IF (@err <> 0) RETURN @err
		END

        if ((0 <> @iddokkoryg) OR (0x0020 & @flag <> 0))
		BEGIN

			IF ((256 <> (256 & @flag)) AND (0 <> @iddokkoryg))
			BEGIN
				EXEC @err = hm_OP_SumujOperacjeKompletow @idTransOrig
				IF (@err <> 0) RETURN @err
			END

			UPDATE	TR
			   SET	TR.wartosc = ISNULL( ( SELECT SUM(CASE WHEN ((32768 & OP.flag) = 32768) THEN 0 WHEN ((2048 & OP.flag) = 2048) THEN -OP.wartosc ELSE OP.wartosc END) FROM OP WHERE OP.id_transakcji = TR.id ), 0 ),
					TR.wartosc_rozl = ISNULL( ( SELECT SUM(CASE WHEN ((32768 & OP.flag) = 32768) THEN 0 WHEN ((2048 & OP.flag) = 2048) THEN -OP.wartosc_rozl ELSE OP.wartosc_rozl END) FROM OP WHERE OP.id_transakcji = TR.id ), 0 )
			 WHERE	TR.id = @idTransOrig OR TR.id IN ( SELECT id FROM #ChangedTr )

		END

		SET NOCOUNT OFF

		INSERT @tLuzneZwiazki
			SELECT id, id2 AS idZw, baza2 AS baseZw FROM ZZ WHERE typ = 155 AND baza1 = @idBazy AND id1 = @idDk
			UNION
			SELECT id, id1 AS idZw, baza1 AS baseZw FROM ZZ WHERE typ = 155 AND baza2 = @idBazy AND id2 = @idDk
			UNION
			SELECT id, id2 AS idZw, baza2 AS baseZw FROM ZZ WHERE typ = 156 AND baza1 = @idBazy AND id1 = @idDk
			UNION
			SELECT id, id1 AS idZw, baza1 AS baseZw FROM ZZ WHERE typ = 156 AND baza2 = @idBazy AND id2 = @idDk
		SELECT @err = @@ERROR, @iloscWierszy = @@ROWCOUNT
		SET NOCOUNT ON
		IF (@err <> 0) RETURN @err
		IF (0 <> @iloscWierszy)
		BEGIN
			DELETE ZZ FROM ZZ
			JOIN @tLuzneZwiazki lz ON lz.id = ZZ.id
			INSERT INTO LOCAL_LOG (baseName, rec_id, operation, term)
				SELECT 'ZZ', id, 4, @@SPID FROM @tLuzneZwiazki
			INSERT INTO LOCAL_LOG (baseName, rec_id, operation, term)
				SELECT HM.hm_UTIL_GetBaseNameFromId(baseZw), idZw AS id, 3, @@SPID FROM @tLuzneZwiazki
		END


		INSERT INTO LOCAL_LOG (baseName, rec_id, operation, term) VALUES ('DK', @idDk, 4, @@SPID)
	END
	ELSE
	BEGIN
		IF @subtyp IN (50, 51) --paragon lub paragon korygujący, czy anulowanie sprawdzane wyżej
		BEGIN
			UPDATE DP SET typ = typ | 0x01, flag = flag | 0x2000, idlongname = idlongname WHERE super = @idDk
		END
		ELSE
		BEGIN
			UPDATE DP SET typ = typ | 0x01, flag = flag | 0x2000, idlongname = NULL WHERE super = @idDk
		END
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err

		UPDATE DK SET anulowany = 1, opis = @opis, rozlmg = rozlmg | 0x20, ok = 1, modifiedBy = @userId, modifiedDate = GETDATE() WHERE id = @idDk
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err
    
		IF (@bAnuluj <> 3)
		BEGIN
		  UPDATE DK SET IdPeriodicSaleReport = NULL WHERE id = @idDk
  			SET @err = @@ERROR
  			IF (@err <> 0) RETURN @err
		END

		INSERT INTO LOCAL_LOG (baseName, rec_id, operation, term) VALUES ('DK', @idDk, 3, @@SPID)
	END

	IF @bAnuluj = 0 OR @subtyp NOT IN (50, 51) --paragon lub paragon korygujący
	BEGIN
		DELETE TX FROM TX
		JOIN @idLongNames iln
		ON iln.id = TX.id
		SET @err = @@ERROR
		IF (@err <> 0) RETURN @err
	END


	IF (@subtyp IN (135, 136, 137, 151, 152, 153))
	BEGIN
		DECLARE @isRozl SMALLINT
		EXEC @isRozl = hm_DK_IsKontraktRozl @idKontraktu
		EXEC hm_DK_SetKontraktRozl @idKontraktu
	END


	IF (0 <> @bKontrolaNumeracji)
	BEGIN
		IF (EXISTS(SELECT TOP 1 id FROM DK WHERE seria = @seria AND seriadzial = @seriadzial AND okres = @okres AND serianr > @serianr order by seria ASC, seriadzial ASC, okres ASC, serianr ASC))
		BEGIN
			SET @err = -4203
			RETURN @err
		END
	END

	DECLARE @KZFlag smallint = 0x0020;
	DECLARE @KZType smallint = 0xC9;

	IF(@flag & @KZFlag <> 0 )
	BEGIN
		DELETE FROM HM.ZZ WHERE id1 = @idDk AND baza1 = @idBazy AND baza2 = @idBazy AND typ = @KZType
	END

	IF @idPeriodicSaleReport IS NOT NULL
	BEGIN
		IF NOT EXISTS (SELECT TOP 1 id FROM DK WHERE IdPeriodicSaleReport = @idPeriodicSaleReport)
		BEGIN
			DELETE FROM PeriodicSaleReports WHERE Id = @idPeriodicSaleReport
			INSERT INTO LOCAL_LOG (baseName, rec_id,operation,term) VALUES ('PeriodicSaleReports', @idPeriodicSaleReport, 4, @@SPID)
		END
		ELSE
			EXEC RecalculatePeriodicSaleReport NULL, @idPeriodicSaleReport
	END

	RETURN 0