-- This file is part of the it-crafts software and is subject to copyright protection.
-- (C) 2022..2023, All rights reserved by Steffen Anders, Elsteraue - Germany
-- Visit also https://www.it-crafts.de.
--

--------------------------------------------------------------------------------------------------
--
IF 0 < (SELECT count(*) from [sysobjects] where [xtype] = 'P'   and [name] = 'itcproc_WebLog_write')
  DROP PROCEDURE [dbo].[itcproc_WebLog_write]
GO
CREATE PROCEDURE [dbo].[itcproc_WebLog_write]
  @Parm_Knr char(20)
 ,@Parm_Uid char(30)
 ,@Parm_Aktion varchar(50)
 ,@Parm_SessionId varchar(40)
 ,@Parm_IPAddress varchar(20)
 ,@Parm_Success tinyint
AS
  DECLARE @NeueId integer
  DECLARE @m_DatumUndZeit char(19) = convert(char(19), getdate(), 120)
  DECLARE @m_Datum char(10) = left(@m_DatumUndZeit,10)
  DECLARE @m_Uhrzeit char(10) = right(@m_DatumUndZeit,8)

  DECLARE @m_CountDown integer = 10
  WHILE @m_CountDown > 0 BEGIN
    BEGIN TRANSACTION
    BEGIN TRY
	    SET @NeueId = dbo.itcfunc_NextRecId_WebLog()
		INSERT INTO [dbo].[ut_WebLog] (
			RecId
		   ,[Knr]
		   ,[Uid]
		   ,[Datum]
		   ,[Uhrzeit]
		   ,[Aktion]
		   ,[SessionId]
		   ,[IPAddress]
		   ,[Success]
			 ) VALUES (
			@NeueId
		   ,RTRIM(@Parm_Knr)
		   ,RTRIM(@Parm_Uid)
		   ,RTRIM(@m_Datum)
		   ,RTRIM(@m_Uhrzeit)
		   ,RTRIM(@Parm_Aktion)
		   ,RTRIM(@Parm_SessionId)
		   ,RTRIM(@Parm_IPAddress)
		   ,@Parm_Success
			   )
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
	    SET @NeueId = 0
	END CATCH

	IF @NeueId <> 0
		SET @m_CountDown = 0
	ELSE
		SET @m_CountDown = @m_CountDown - 1

	IF @m_CountDown > 0
        WAITFOR DELAY '00:00:00.050'

  END
  RETURN 0
GO

--------------------------------------------------------------------------------------------------
--
IF 0 < (SELECT count(*) from [sysobjects] where [xtype] = 'V' and [name] = 'itcview_WebLog_Login')
  DROP VIEW [dbo].[itcview_WebLog_Login]
GO
CREATE VIEW [dbo].[itcview_WebLog_Login] AS
  select * from dbo.ut_WebLog where Success = 1
GO

--------------------------------------------------------------------------------------------------
--
IF 0 < (SELECT count(*) from [sysobjects] where [xtype] = 'V' and [name] = 'itcview_WebLog_Full')
  DROP VIEW [dbo].[itcview_WebLog_Full]
GO
CREATE VIEW [dbo].[itcview_WebLog_Full] AS
  select l.*, (select max(Datum) from itcview_WebLog_Login l2 where l2.Knr = l.Knr AND l2.[Uid] = l.[Uid] and l2.Datum <= l.Datum) as LoginDatum from ut_WebLog l
GO

