/*
Uwaga zadziala tylko dla przypadku gdzie
wszystko wrocilo na stan.

Zmiana wartosci np
jelsi mamy 2 szt za 108,94 a wartosc powinna byc 217,89 zamiast ..,78
*/

begin transaction

	declare  @documentlineid uniqueidentifier
	select @documentlineid = 'a00a10a4-9a7b-e811-80d2-9c8e994dc647'
	declare @itemprice decimal(18,2) = 217.89
	declare @itemid uniqueidentifier

	-- check before
	select @itemid=itemid from   [document].documentline
	where documentlineid = @documentlineid

	select * from   [document].documentline
	where initialincomesourcelineid = @documentlineid
	order by adddate desc

	update  [document].documentline set
		itemvalue = @itemprice * SIGN(itemvalue),
		sysitemvalue = @itemprice * SIGN(sysitemvalue),
		syscorrecteditemvalueqcorrExcluded = @itemprice* SIGN(syscorrecteditemvalueqcorrExcluded)
	where initialincomesourcelineid = @documentlineid

	update  [document].documentline set
		itemvalueleft = @itemprice* SIGN(itemvalue),
		sysitemvalueleft = @itemprice* SIGN(itemvalue)
	where initialincomesourcelineid = @documentlineid
	and itemvalueleft <>0

		update  [document].documentline set
		correcteditemvalue = @itemprice* SIGN(correcteditemvalue)
	where initialincomesourcelineid = @documentlineid
	and correcteditemvalue <>0

	update document.document
	set
		[sumItemValue] =total.a,
		[sumSysItemValue]=total.b
	from document.document d
	inner join
	(select sum(itemvalue) a,sum(SysItemValue) b,documentid from document.documentline
	where status =1
	group by documentid) total on d.documentid = total.documentid
	where d.documentid in (
	select documentid from   [document].documentline
	where initialincomesourcelineid = @documentlineid
	)

	-- naprawienie stanow

	-- check after
	select * from   [document].documentline
	where initialincomesourcelineid = @documentlineid
	order by adddate desc

	exec wms.stockBalanceFix @itemID = @itemid, @username = 'sys'

rollback transaction
