﻿DROP PROCEDURE IF EXISTS uspGetNemNaplozottOrakSzama
GO

CREATE PROCEDURE uspGetNemNaplozottOrakSzama
   @pTanevId int
  ,@pIntezmenyId int
  ,@pFeladatKategoriaId int = null
AS
SET NOCOUNT ON;

DECLARE
     @IdoszakKezdete DATE
    ,@IdoszakVege DATE = GETDATE();

SELECT @IdoszakKezdete = tv.C_KEZDONAP 
FROM T_TANEV_OSSZES tv WHERE ID = @pTanevId;

SELECT
    f.C_NYOMTATASINEV AS Tanar,
    f.C_OKTATASIAZONOSITO AS TanarOktAzon,
    RIGHT(CONCAT('00', o.Honap), 2) AS Honap,
    o.Darab
FROM (
    SELECT
        ISNULL(oo.C_HELYETTESTANAROKID, oo.C_TANARID) AS C_TANARID,
        MONTH(oo.C_DATUM) AS Honap,
        COUNT(*) AS Darab
    FROM T_ORARENDTELJES_OSSZES oo
    WHERE oo.C_INTEZMENYID = @pIntezmenyId
    AND oo.C_TANEVID = @pTanevId
    AND oo.C_DATUM >= @IdoszakKezdete 
    AND oo.C_DATUM < @IdoszakVege
    AND oo.C_FELADATKATEGORIAID = CASE WHEN @pFeladatKategoriaId IS NOT NULL THEN @pFeladatKategoriaId ELSE oo.C_FELADATKATEGORIAID END
    AND NOT EXISTS(
        SELECT *
        FROM dbo.T_TANITASIORA_OSSZES tt 
        WHERE tt.TOROLT = 'F'
        AND tt.C_INTEZMENYID = oo.C_INTEZMENYID
        AND tt.C_TANEVID = oo.C_TANEVID
        AND tt.C_DATUM = oo.C_DATUM
        AND tt.C_OSZTALYCSOPORTID = oo.C_OSZTALYCSOPORTID
        AND tt.C_TANTARGYID = oo.C_TANTARGYID
        AND tt.C_TANARID = oo.C_TANARID 
        AND (
            tt.C_ORASZAM = oo.C_ORASZAM
            OR
            (
                tt.C_ORAKEZDETE = CAST(oo.C_DATUM AS DATETIME) + CAST(oo.C_ORAKEZDETE AS DATETIME)
                AND
                tt.C_ORAVEGE = CAST(oo.C_DATUM AS DATETIME) + CAST(oo.C_ORAVEGE AS DATETIME)
            )
        )
    )
    GROUP BY 
        ISNULL(oo.C_HELYETTESTANAROKID, oo.C_TANARID),
        MONTH(oo.C_DATUM)
) o
LEFT JOIN T_FELHASZNALO_OSSZES f ON f.ID = o.C_TANARID and f.TOROLT = 'F'
GO
