SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [FNCUST_GET_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:   TABLE (success BIT, message NVARCHAR(MAX), data NVARCHAR(MAX))
-- Usage:     SELECT * FROM dbo.FNCUST_GET_JSON_INVOICE_DATA(NULL)
--            SELECT * FROM dbo.FNCUST_GET_JSON_INVOICE_DATA(42)
-- =================================================================
-- 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:            3.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 - Umstellung auf Export-Prozedur (Tabellen → JSON)
-- 26.02.2026 / MK - JSON-Ausgabe: camelCase, INCLUDE_NULL_VALUES, CreateInvoice_Request-Vorlage
-- 26.02.2026 / MK - Umbau zu Inline-Tabellenwertfunktion (ITVF)

CREATE OR ALTER FUNCTION [dbo].[FNCUST_GET_JSON_INVOICE_DATA](
	@DocumentID				INT = NULL
)
RETURNS TABLE
AS
RETURN
(
	SELECT
		--==== success ====--
		  success = CAST(IIF(v.status = 0, 1, 0) AS BIT)

		--==== message ====--
		, message = CAST(
			CASE v.status
				WHEN 1 THEN N'Kein PurchaseDocument mit DocumentID = ' + CAST(@DocumentID AS NVARCHAR(20)) + N' gefunden.'
				WHEN 2 THEN N'Keine PurchaseDocuments vorhanden.'
				ELSE        N'Daten erfolgreich verarbeitet.'
			END
		  AS NVARCHAR(MAX))

		--==== data ====--
		, data = CAST(
			CASE WHEN v.status > 0 THEN NULL
			ELSE (
				--===============================================-- Build output JSON result --===============================================--
				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
				-----------------------------------------------------------------------------------------------------------------------------------
			)
			END
		  AS NVARCHAR(MAX))

	FROM (VALUES (1)) AS src(x)
	CROSS APPLY (
		SELECT status = CASE
			WHEN @DocumentID IS NOT NULL
				 AND NOT EXISTS (SELECT 1 FROM dbo.PurchaseDocument WHERE DocumentID = @DocumentID)
				THEN 1
			WHEN NOT EXISTS (SELECT 1 FROM dbo.PurchaseDocument WHERE @DocumentID IS NULL OR DocumentID = @DocumentID)
				THEN 2
			ELSE 0
		END
	) AS v
);
GO
