USE [Polaris]
GO
/****** Object:  StoredProcedure [Lss].[Rpt_PrintInvoices]    Script Date: 4/3/2026 7:31:08 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Daniel Messer>
-- Create date: <April 3, 2026>
-- Description:	<This stored procedure replicates the printing of invoices from the Polaris Find Tool.>
-- =============================================

CREATE PROCEDURE [Lss].[Rpt_PrintInvoices]
	@StartDate DATETIME, 
	@EndDate DATETIME
AS

BEGIN
	SET NOCOUNT ON;

-- Set up a global temp table for collecting InvoiceIDs. This table is predictably named based on the 
-- WorkstationID and PolarisUserID. While it's initially set up as below, the RPT_CreateTempTable
-- sproc will adjust the naming.
	DECLARE @p3 nvarchar(255) SET @p3=N'##1158861';

-- 861 = PolarisUserID for Dan, 1158 = Dan's WorkstationID, @p3 provides a variable for the temp table
	EXEC Polaris.Polaris.Rpt_CreateTempTable 861,1158,@p3 OUTPUT;

-- Populate the temp table created by the sproc above
	INSERT INTO ##1158_861

	SELECT
		ph.invoiceID
	FROM
		Polaris.Polaris.PaymentHistories ph
	INNER JOIN
		Polaris.Polaris.Invoices i
		ON (i.InvoiceID = ph.InvoiceID)
	WHERE -- Invoice status of PAID
		i.InvoiceStatusID = 5
	AND
		i.InvStatusDate between @StartDate and @EndDate
	GROUP BY
		ph.InvoiceID HAVING COUNT (ph.invoiceID) = 1;

-- Pass the temp table to the sproc below to pull invoice related data
	EXEC Polaris.Polaris.Rpt_Vouchers1 @InvoiceID = 1, @PayHistoryID = 1, @sTempTable = N'##1158_861'

-- Tidy up
	DROP TABLE IF EXISTS ##1158_861;
	
END
