﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[fds__newInvoiceId]
(
	@year int
)
RETURNS varchar(25)
AS
BEGIN
	DECLARE @lastid_int bigint;
	SELECT @lastid_int = MAX(  TRY_PARSE(RIGHT([InvoiceId], 4) as integer) ) FROM [dbo].[fds__invoices] WHERE LEFT(ISNULL([InvoiceId],''),5) = ('R' + CAST(@year as varchar(4)));
	DECLARE @invoice_id varchar(25) = 'R' + CAST(@year as varchar(4)) + '-' + FORMAT(ISNULL(  @lastid_int , CASE WHEN @year = 2021 THEN 1593 ELSE 0 END) + 1, '0000');

	RETURN @invoice_id;

END