
CREATE PROCEDURE [dbo].[API_TaskAfter]
@SyncDbId int,
 @OrgId int,
 @NewId int,
 @Sch_Id int
AS
BEGIN
	SET NOCOUNT ON;

	/*
declare @SyncDbId int;
declare @OrgId int;
declare @NewId int;
declare @Sch_Id int;
*/

update dbo.ApiCrmTasks set ErpId = @NewId where Id = @OrgId and ErpId =0;


-- elememmty oznaczanie
update dbo.ApiDeviceLines 
set ErpId= uu.ID
from dbo.UrzadzeniaUzyte uu
where
ErpId=0 and
TaskId = @OrgId 
and uu.Urzadzenie = DeviceId
and uu.Zadanie = @NewId;


-- te linie które były usuwane zakłdamy, ze zostały usunięte
update dbo.ApiDeviceLines set Modified=-2 where Modified =-1 and TaskId = @OrgId ;


-- pobieramy HistId
declare @HistId int;
set @HistId   = (select Max(Id) from dbo.ChangeInfos where SourceTable = 'Zadania');

INSERT INTO [dbo].[ApiSyncItems]
           ([SyncId],[ObjectSaveTS],[SchemaId],[ObjectType],[ObjectId],[Message],[Status],[TS], HistId)
     VALUES
           (@SyncDbId,[dbo].[ApiGetSec](CURRENT_TIMESTAMP),@Sch_Id,1, @OrgId,'',2,CURRENT_TIMESTAMP,@HistId);
           
END



