SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [PRCUST_SET_JSON_INVOICE_DATA]
-- =================================================================
-- Reads invoice data from relational tables and returns a normalized
-- JSON response matching the CreateInvoice_Request structure.
--
-- Parameter: @DocumentID INT = NULL (NULL = alle Dokumente)
-- Returns:   RESULTSET; success/message/data
-- =================================================================
-- Copyright (c) 2026 by Digital Data GmbH
--
-- Digital Data GmbH • Ludwig-Rinn-Strasse 16 • D-35452 Heuchelheim
-- Tel.: 0641/202360 • E-Mail: info-flow@digitaldata.works
-- =================================================================
-- Creation Date / Author:    26.02.2026 / MK
-- Version Date / Editor:     26.02.2026 / MK
-- Version Number:            2.0.0.0
-- =================================================================
-- History:
-- 26.02.2026 / MK - Initial version based on JSON invoice import
-- 26.02.2026 / MK - Style harmonized to PRDEX convention
-- 26.02.2026 / MK - #3 CAST(NULL AS NVARCHAR(MAX)) for consistent data type
-- 26.02.2026 / MK - #4 RETURN @RETURN_STATUS for proper return codes
-- 26.02.2026 / MK - #12 Extended error diagnostics in CATCH
-- 26.02.2026 / MK - #16 success column as BIT
-- 26.02.2026 / MK - Umstellung auf Export-Prozedur (Tabellen → JSON)
-- 26.02.2026 / MK - JSON-Ausgabe: camelCase, INCLUDE_NULL_VALUES, CreateInvoice_Request-Vorlage

CREATE OR ALTER PROCEDURE [dbo].[PRCUST_SET_JSON_INVOICE_DATA](
	@DocumentID				INT = NULL
)
AS
BEGIN TRY

	SET NOCOUNT ON;

	-- declare runtime vars
	DECLARE @MY_PROCEDURE_NAME				NVARCHAR(128)	= OBJECT_NAME(@@PROCID),
			@RETURN_STATUS					INT				= 0,
			@RETURN_STATUS_TEXT				NVARCHAR(MAX)	= CONCAT('START PROCEDURE [',OBJECT_NAME(@@PROCID),'] @ ',CONVERT(VARCHAR(50),GETDATE(),120)),
			@RETURN_ERROR_TEXT				NVARCHAR(MAX)	= N'';

	DECLARE @output							NVARCHAR(MAX);

	PRINT '====================================================================================================';
	PRINT @RETURN_STATUS_TEXT;
	PRINT '';

	--==========================================-- Validate: Document exists --==========================================--
	IF @DocumentID IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dbo.PurchaseDocument WHERE DocumentID = @DocumentID) BEGIN

		SET @RETURN_STATUS		= 40001;
		SET @RETURN_STATUS_TEXT	= N'Document not found.';
		SET @RETURN_ERROR_TEXT	= N'Kein PurchaseDocument mit DocumentID = ' + CAST(@DocumentID AS NVARCHAR(20)) + N' gefunden.';

		PRINT 'ERROR: ' + @RETURN_ERROR_TEXT;

		SELECT
			  success = CAST(0 AS BIT)
			, message = @RETURN_ERROR_TEXT
			, data = CAST(NULL AS NVARCHAR(MAX));

		RETURN @RETURN_STATUS;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	--========================================-- Validate: Any documents available --========================================--
	IF NOT EXISTS (SELECT 1 FROM dbo.PurchaseDocument WHERE @DocumentID IS NULL OR DocumentID = @DocumentID) BEGIN

		SET @RETURN_STATUS		= 40002;
		SET @RETURN_STATUS_TEXT	= N'No documents available.';
		SET @RETURN_ERROR_TEXT	= N'Keine PurchaseDocuments vorhanden.';

		PRINT 'ERROR: ' + @RETURN_ERROR_TEXT;

		SELECT
			  success = CAST(0 AS BIT)
			, message = @RETURN_ERROR_TEXT
			, data = CAST(NULL AS NVARCHAR(MAX));

		RETURN @RETURN_STATUS;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	PRINT 'INFO: Erzeuge JSON-Ausgabe...';

	--===============================================-- Build output JSON result --===============================================--
	SELECT @output =
	(
		SELECT
			JSON_QUERY(
				COALESCE(
					(
						SELECT
							  [documentType] = pd.DocumentType
							, [no] = pd.No_
							, [noSeries] = pd.NoSeries
							, [processIDTransfer] = pd.ProcessIDTransfer
							, [buyFromVendorNo] = pd.BuyFromVendorNo
							, [payToVendorNo] = pd.PayToVendorNo
							, [postingDate] = pd.PostingDate
							, [paymentTermsCode] = pd.PaymentTermsCode
							, [paymentTermsCodeIR] = pd.PaymentTermsCodeIR
							, [dueDate] = pd.DueDate
							, [pmtDiscountDate] = pd.PmtDiscountDate
							, [paymentDiscount] = pd.PaymentDiscount
							, [paymentDiscountIR] = pd.PaymentDiscountIR
							, [currencyCode] = pd.CurrencyCode
							, [invoiceDiscCode] = pd.InvoiceDiscCode
							, [postingDescription] = pd.PostingDescription
							, [paymentMethodCode] = pd.PaymentMethodCode
							, [vendorInvoiceNo] = pd.VendorInvoiceNo
							, [vendorCrMemoNo] = pd.VendorCrMemoNo
							, [phrVendorBankAccountCode] = pd.PhrVendorBankAccountCode
							, [phrBankBranchNo] = pd.PhrBankBranchNo
							, [phrBankAccountNo] = pd.PhrBankAccountNo
							, [phrIBAN] = pd.PhrIBAN
							, [phrSWIFTCode] = pd.PhrSWIFTCode
							, [phrBankName] = pd.PhrBankName
							, [phrBankAccountEntryPriority] = pd.PhrBankAccountEntryPriority
							, [phrRMCashDiscountReceived] = pd.PhrRMCashDiscountReceived
							, [phrRMAmountIncludingVAT] = pd.PhrRMAmountIncludingVAT
							, [phrRMAmountLessDiscount] = pd.PhrRMAmountLessDiscount
							, purchaseLines = JSON_QUERY(
								COALESCE(
									(
										SELECT
											  [attachedToLineNo] = pl.AttachedToLineNo
											, [type] = pl.Type
											, [no] = pl.No_
											, [description] = pl.Description
											, [description2] = pl.Description2
											, [locationCode] = pl.LocationCode
											, [variantCode] = pl.VariantCode
											, [quantity] = pl.Quantity
											, [unitOfMeasureCode] = pl.UnitOfMeasureCode
											, [directUnitCost] = pl.DirectUnitCost
											, [lineDiscount] = pl.LineDiscount
											, [ableToDiscount] = pl.AbleToDiscount
											, [discountCalculated] = pl.DiscountCalculated
											, [workOrderNo] = pl.WorkOrderNo
											, [genBusPostingGroup] = pl.GenBusPostingGroup
											, [genProdPostingGroup] = pl.GenProdPostingGroup
											, [vatBusPostingGroup] = pl.VatBusPostingGroup
											, [vatProdPostingGroup] = pl.VatProdPostingGroup
											, [applToItemEntry] = pl.ApplToItemEntry
											, [postingWithoutApply] = pl.PostingWithoutApply
											, [anticipatedPayment] = pl.AnticipatedPayment
											, [receiptNo] = pl.ReceiptNo
											, [receiptLineNo] = pl.ReceiptLineNo
											, [irOrderNo] = pl.IrOrderNo
											, [irOrderLineNo] = pl.IrOrderLineNo
											, dimSetEntries = JSON_QUERY(
												COALESCE(
													(
														SELECT
															  [dimensionCode] = d.DimensionCode
															, [dimensionValueCode] = d.DimensionValueCode
														FROM dbo.DimSetEntry d
														WHERE d.LineID = pl.LineID
														FOR JSON PATH, INCLUDE_NULL_VALUES
													)
													, '[]'
												)
											)
											, itemChargeAssignmentLines = JSON_QUERY(
												COALESCE(
													(
														SELECT
															  [itemChargeNo] = ia.ItemChargeNo
															, [unitCost] = ia.UnitCost
															, [appliesToDocType] = ia.AppliesToDocType
															, [appliesToDocNo] = ia.AppliesToDocNo
															, [appliesToDocLineNo] = ia.AppliesToDocLineNo
															, [itemNo] = ia.ItemNo
															, [description] = ia.Description
															, [qtyToAssign] = ia.QtyToAssign
															, [qtyAssigned] = ia.QtyAssigned
															, [amountToAssign] = ia.AmountToAssign
															, [appliesToDocLineAmount] = ia.AppliesToDocLineAmount
														FROM dbo.ItemChargeAssignment ia
														WHERE ia.LineID = pl.LineID
														FOR JSON PATH, INCLUDE_NULL_VALUES
													)
													, '[]'
												)
											)
										FROM dbo.PurchaseLine pl
										WHERE pl.DocumentID = pd.DocumentID
										FOR JSON PATH, INCLUDE_NULL_VALUES
									)
									, '[]'
								)
							)
						FROM dbo.PurchaseDocument pd
						WHERE @DocumentID IS NULL OR pd.DocumentID = @DocumentID
						ORDER BY pd.DocumentID
						FOR JSON PATH, INCLUDE_NULL_VALUES
					)
					, '[]'
				)
			) AS purchaseDocuments
		FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
	);
	-----------------------------------------------------------------------------------------------------------------------------------

	SET @RETURN_STATUS		= 0;
	SET @RETURN_STATUS_TEXT	= CONCAT('END PROCEDURE [',@MY_PROCEDURE_NAME,'] @ ',CONVERT(NVARCHAR(50),GETDATE(),120));

	PRINT '';
	PRINT @RETURN_STATUS_TEXT;
	PRINT '====================================================================================================';

	SELECT
		  success = CAST(1 AS BIT)
		, message = N'Daten erfolgreich verarbeitet.'
		, data = @output;

	RETURN @RETURN_STATUS;

END TRY BEGIN CATCH

	--====================================================-- exception / error --====================================================--

	SET @RETURN_STATUS		= 50000;
	SET @RETURN_STATUS_TEXT	= CONCAT('END PROCEDURE [',OBJECT_NAME(@@PROCID),'] @ ',CONVERT(NVARCHAR(50),GETDATE(),120));
	SET @RETURN_ERROR_TEXT	= CONCAT('ERR ',ERROR_NUMBER(),' SEV ',ERROR_SEVERITY(),' STATE ',ERROR_STATE(),' LINE ',ERROR_LINE(),': ',ERROR_MESSAGE());

	PRINT 'ERROR IN PROCEDURE: [' + OBJECT_NAME(@@PROCID) + ']' + CHAR(13) + @RETURN_ERROR_TEXT;
	PRINT @RETURN_STATUS_TEXT;
	PRINT '====================================================================================================';
	-----------------------------------------------------------------------------------------------------------------------------------

	SELECT
		  success = CAST(0 AS BIT)
		, message = ERROR_MESSAGE()
		, data = CAST(NULL AS NVARCHAR(MAX));

	RETURN @RETURN_STATUS;

END CATCH;
GO
