﻿
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__r_getBalanceByYearTopCustomer]
	@year int,
	
	@authuser varchar(100)
AS
BEGIN
	SET NOCOUNT ON;

    DECLARE @today date = GETDATE()
	DECLARE @tomorrow date = DATEADD(DAY,1,@today);

	IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2
		THROW 60000, N'not authorized', 1;  

	DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable];

	--Admin Table
	INSERT INTO @Admin
	VALUES (
		'bbm'
		,'Umsatz der Top 100 Kunden für Jahr ' + CAST( @year  as varchar(10))
		,'Umsatz der Top 100 Kunden pro Jahr ' + CAST( @year  as varchar(10))
		,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm')
		,''
		,'table' --typ
		, ''  --settings
		, ''
		, 0);

	SELECT * FROM @Admin;


	WITH inv as(
		select 
				[InvoiceBalance] = SUM(  ISNULL(_i.[InvoiceBalance],0) )
				,[Dateofcreation] = CAST(_i.[DateCreated] as date)
				,_i.CustomerId
				,[customerName] = cy.Name
				,[seq] = ROW_NUMBER() OVER (ORDER BY CAST(_i.[DateCreated] as date))
			FROM [dbo].[fds__invoices] as _i 
				JOIN [dbo].[mfr__companies] as cy on _i.CustomerId = cy.id
			where YEAR(_i.[DateCreated]) = @year and _i.[isfinal] = 1
			GROUP BY CAST(_i.[DateCreated] as date), CustomerId, cy.name
	), yr1 as (
		SELECT
			[year] = YEAR( _i.[DateCreated] )
			, [total] = SUM(  ISNULL(_i.[InvoiceBalance],0) )
		FROM [dbo].[fds__invoices] as _i 
		WHERE _i.[isfinal] = 1
		GROUP BY YEAR( _i.[DateCreated])
	), yr as (
		SELECT [year], [total] = SUM([total])
		from yr1 GROUP BY [year]
	)
	SELECT TOP(100) 
		[Jahr]			= CAST(  YEAR( inv.[Dateofcreation] ) as varchar(4))
		, [Name d. Kunden] = [customerName]
		, [∑ Umsätze]		= FORMAT(  SUM(  ISNULL(inv.[InvoiceBalance],0) ), '#,0.00 €', 'de')
		, [style:∑ Umsätze]  = 'text-align: right'
		, [% Anteil]		= CASE WHEN yr.[total] > 0 THEN  FORMAT(  SUM( ISNULL(inv.[InvoiceBalance],0) ) / [total], '0 %', 'de') ELSE NULL END
		, [style:% Anteil]  = 'text-align: right'
		, [order]		= ROW_NUMBER() OVER ( ORDER By SUM(  ISNULL(inv.[InvoiceBalance],0) ) DESC)
	FROM inv LEFT JOIN yr on YEAR( inv.[Dateofcreation] ) = yr.[year]
	GROUP BY YEAR( inv.[Dateofcreation] ), yr.[total], [customerName];

END