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

    DECLARE @idbigint bigint = TRY_CAST(@invoiceid as bigint);


	DECLARE @SReq TABLE  ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(20), [customer.ExternalId] bigint, [customer.Id] bigint, [mfr] bit, [fds] bit);

	INSERT INTO @SReq
		SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], [mfr] = i.[IsExternal], [fds] = IIF(i.[isexternal] = 0,1,0)
			FROM [dbo].[mfr__servicerequests] as s 
				JOIN [dbo].[fds__invoice_servicerequests] as iq ON s.[id] = iq.[mfr__servicerequest]
				JOIN [dbo].[fds__invoices] as i on iq.[InvId] = i.[id] AND i.[id] = @invoiceid 
				LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id 
			where i.[id] = @invoiceid 
		;
	
	SELECT 
		[id],[DateOfCreation],[name],[invoice.Id],[customer.ExternalId],[customer.Id], [mfr]
		,[order] = ROW_NUMBER() OVER (ORDER BY [DateOfCreation])
	FROM @SReq;


	SELECT
		itm.[Id]
		, [net_pos]	= CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE		FORMAT(	CAST(    (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)     as numeric(7,2))	, '#0.00 €','de')	END
		, [bo_pos]	= CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE		FORMAT(	CAST(    ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01))    as numeric(7,2))	, '#0.00 €','de')	END
		, [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END
		, itm.[ServiceRequestId]
		, itm.[SortOrder]
		, itm.[Type]
		, itm.[NameOrNumber]
		, sreq.[invoice.Id]
		, [order] = ROW_NUMBER() OVER (PARTITION BY itm.[ServiceRequestId] ORDER BY itm.[SortOrder])
	FROM [dbo].[mfr__items] as itm 
		JOIN @sreq as sreq ON itm.[ServiceRequestId] = SReq.[id]
		LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item'
	;
	
	


END