SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [PRCUST_SET_JSON_INVOICE_DATA]
-- =================================================================
-- Imports invoice JSON payload into relational tables and returns
-- normalized JSON response for all imported documents.
-- 
-- 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:            1.0.0.0
-- =================================================================
-- History:
-- 26.02.2026 / MK - Initial version based on JSON invoice import
-- 26.02.2026 / MK - Style harmonized to PRDEX convention

CREATE OR ALTER PROCEDURE [dbo].[PRCUST_SET_JSON_INVOICE_DATA](
	@json				NVARCHAR(MAX)
)
AS
BEGIN TRY

	SET NOCOUNT ON;
	SET XACT_ABORT 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 @doc						NVARCHAR(MAX),
			@line						NVARCHAR(MAX),
			@DocumentID					INT,
			@LineID						INT,
			@output						NVARCHAR(MAX);

	DECLARE @docs					TABLE (doc NVARCHAR(MAX));
	DECLARE @lines					TABLE (line NVARCHAR(MAX));
	DECLARE @InsertedDocuments	TABLE (DocumentID INT PRIMARY KEY);

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

	--==============================================-- Validate JSON payload --==============================================--
	IF dbo.FN_VALIDATE_JSON_INVOICE_DATA(@json) = 0 BEGIN

		SET @RETURN_STATUS		= 40001;
		SET @RETURN_STATUS_TEXT	= N'JSON validation failed.';
		SET @RETURN_ERROR_TEXT	= N'Ungültige JSON-Struktur.';

		PRINT 'ERROR: ' + @RETURN_ERROR_TEXT;

		SELECT
			  success = 0
			, message = @RETURN_ERROR_TEXT
			, data = NULL;

		RETURN;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	PRINT 'INFO: JSON-Validierung erfolgreich.';

	BEGIN TRANSACTION;

	--===========================================-- Extract purchaseDocuments array --===========================================--
	INSERT INTO @docs(doc)
	SELECT [value]
	FROM OPENJSON(@json, '$.purchaseDocuments');
	-----------------------------------------------------------------------------------------------------------------------------------

	DECLARE doc_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT doc FROM @docs;
	OPEN doc_cursor;
	FETCH NEXT FROM doc_cursor INTO @doc;

	WHILE @@FETCH_STATUS = 0 BEGIN

		PRINT 'INFO: Füge PurchaseDocument ein...';

		--=============================================-- Insert PurchaseDocument row --=============================================--
		INSERT INTO dbo.PurchaseDocument (
			  DocumentType
			, No_
			, NoSeries
			, ProcessIDTransfer
			, BuyFromVendorNo
			, PayToVendorNo
			, PostingDate
			, PaymentTermsCode
			, PaymentTermsCodeIR
			, DueDate
			, PmtDiscountDate
			, PaymentDiscount
			, CurrencyCode
			, InvoiceDiscCode
			, PostingDescription
			, PaymentMethodCode
			, VendorInvoiceNo
			, VendorCrMemoNo
			, PhrVendorBankAccountCode
			, PhrBankBranchNo
			, PhrBankAccountNo
			, PhrIBAN
			, PhrSWIFTCode
			, PhrBankName
			, PhrBankAccountEntryPriority
			, PhrRMCashDiscountReceived
			, PhrRMAmountIncludingVAT
			, PhrRMAmountLessDiscount
		)
		SELECT
			  DocumentType
			, No
			, NoSeries
			, ProcessIDTransfer
			, BuyFromVendorNo
			, PayToVendorNo
			, PostingDate
			, PaymentTermsCode
			, PaymentTermsCodeIR
			, DueDate
			, PmtDiscountDate
			, PaymentDiscount
			, CurrencyCode
			, InvoiceDiscCode
			, PostingDescription
			, PaymentMethodCode
			, VendorInvoiceNo
			, VendorCrMemoNo
			, PhrVendorBankAccountCode
			, PhrBankBranchNo
			, PhrBankAccountNo
			, PhrIBAN
			, PhrSWIFTCode
			, PhrBankName
			, PhrBankAccountEntryPriority
			, PhrRMCashDiscountReceived
			, PhrRMAmountIncludingVAT
			, PhrRMAmountLessDiscount
		FROM OPENJSON(@doc)
		WITH (
			  DocumentType INT
			, No NVARCHAR(50)
			, NoSeries NVARCHAR(50)
			, ProcessIDTransfer NVARCHAR(50)
			, BuyFromVendorNo NVARCHAR(50)
			, PayToVendorNo NVARCHAR(50)
			, PostingDate DATE
			, PaymentTermsCode NVARCHAR(20)
			, PaymentTermsCodeIR NVARCHAR(20)
			, DueDate DATE
			, PmtDiscountDate DATE
			, PaymentDiscount DECIMAL(10,2)
			, CurrencyCode NVARCHAR(10)
			, InvoiceDiscCode NVARCHAR(50)
			, PostingDescription NVARCHAR(250)
			, PaymentMethodCode NVARCHAR(20)
			, VendorInvoiceNo NVARCHAR(50)
			, VendorCrMemoNo NVARCHAR(50)
			, PhrVendorBankAccountCode NVARCHAR(50)
			, PhrBankBranchNo NVARCHAR(50)
			, PhrBankAccountNo NVARCHAR(50)
			, PhrIBAN NVARCHAR(50)
			, PhrSWIFTCode NVARCHAR(50)
			, PhrBankName NVARCHAR(100)
			, PhrBankAccountEntryPriority BIT
			, PhrRMCashDiscountReceived BIT
			, PhrRMAmountIncludingVAT DECIMAL(18,2)
			, PhrRMAmountLessDiscount DECIMAL(18,2)
			, purchaseLines NVARCHAR(MAX) AS JSON
		);
		-----------------------------------------------------------------------------------------------------------------------------------

		SET @DocumentID = SCOPE_IDENTITY();
		INSERT INTO @InsertedDocuments (DocumentID) VALUES (@DocumentID);

		PRINT 'INFO: PurchaseDocument eingefügt. DocumentID = ' + CAST(@DocumentID AS NVARCHAR(20));

		--=============================================-- Extract purchaseLines array --==============================================--
		DELETE FROM @lines;
		INSERT INTO @lines(line)
		SELECT [value]
		FROM OPENJSON(@doc, '$.purchaseLines');
		-----------------------------------------------------------------------------------------------------------------------------------

		DECLARE line_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT line FROM @lines;
		OPEN line_cursor;
		FETCH NEXT FROM line_cursor INTO @line;

		WHILE @@FETCH_STATUS = 0 BEGIN

			PRINT 'INFO: Füge PurchaseLine ein...';

			INSERT INTO dbo.PurchaseLine (
				  DocumentID
				, AttachedToLineNo
				, Type
				, No_
				, Description
				, Description2
				, LocationCode
				, VariantCode
				, Quantity
				, UnitOfMeasureCode
				, DirectUnitCost
				, LineDiscount
				, AbleToDiscount
				, DiscountCalculated
				, WorkOrderNo
				, GenBusPostingGroup
				, GenProdPostingGroup
				, VatBusPostingGroup
				, VatProdPostingGroup
				, ApplToItemEntry
				, PostingWithoutApply
				, AnticipatedPayment
				, ReceiptNo
				, ReceiptLineNo
				, IrOrderNo
				, IrOrderLineNo
			)
			SELECT
				  @DocumentID
				, AttachedToLineNo
				, Type
				, No
				, Description
				, Description2
				, LocationCode
				, VariantCode
				, Quantity
				, UnitOfMeasureCode
				, DirectUnitCost
				, LineDiscount
				, AbleToDiscount
				, DiscountCalculated
				, WorkOrderNo
				, GenBusPostingGroup
				, GenProdPostingGroup
				, VatBusPostingGroup
				, VatProdPostingGroup
				, ApplToItemEntry
				, PostingWithoutApply
				, AnticipatedPayment
				, ReceiptNo
				, ReceiptLineNo
				, IrOrderNo
				, IrOrderLineNo
			FROM OPENJSON(@line)
			WITH (
				  AttachedToLineNo INT
				, Type INT
				, No NVARCHAR(50)
				, Description NVARCHAR(250)
				, Description2 NVARCHAR(250)
				, LocationCode NVARCHAR(50)
				, VariantCode NVARCHAR(50)
				, Quantity DECIMAL(18,4)
				, UnitOfMeasureCode NVARCHAR(20)
				, DirectUnitCost DECIMAL(18,4)
				, LineDiscount DECIMAL(18,4)
				, AbleToDiscount BIT
				, DiscountCalculated BIT
				, WorkOrderNo NVARCHAR(50)
				, GenBusPostingGroup NVARCHAR(20)
				, GenProdPostingGroup NVARCHAR(20)
				, VatBusPostingGroup NVARCHAR(20)
				, VatProdPostingGroup NVARCHAR(20)
				, ApplToItemEntry INT
				, PostingWithoutApply BIT
				, AnticipatedPayment DECIMAL(18,2)
				, ReceiptNo NVARCHAR(50)
				, ReceiptLineNo INT
				, IrOrderNo NVARCHAR(50)
				, IrOrderLineNo INT
				, dimSetEntries NVARCHAR(MAX) AS JSON
				, itemChargeAssignmentLines NVARCHAR(MAX) AS JSON
			);

			SET @LineID = SCOPE_IDENTITY();
			PRINT 'INFO: PurchaseLine eingefügt. LineID = ' + CAST(@LineID AS NVARCHAR(20));

			--===============================================-- Insert dimSetEntries --===============================================--
			INSERT INTO dbo.DimSetEntry (LineID, DimensionCode, DimensionValueCode)
			SELECT @LineID, DimensionCode, DimensionValueCode
			FROM OPENJSON(@line, '$.dimSetEntries')
			WITH (
				  DimensionCode NVARCHAR(50)
				, DimensionValueCode NVARCHAR(50)
			);
			-----------------------------------------------------------------------------------------------------------------------------------

			--=========================================-- Insert itemChargeAssignmentLines --==========================================--
			INSERT INTO dbo.ItemChargeAssignment (
				  LineID
				, ItemChargeNo
				, UnitCost
				, AppliesToDocType
				, AppliesToDocNo
				, AppliesToDocLineNo
				, ItemNo
				, Description
				, QtyToAssign
				, QtyAssigned
				, AmountToAssign
				, AppliesToDocLineAmount
			)
			SELECT
				  @LineID
				, ItemChargeNo
				, UnitCost
				, AppliesToDocType
				, AppliesToDocNo
				, AppliesToDocLineNo
				, ItemNo
				, Description
				, QtyToAssign
				, QtyAssigned
				, AmountToAssign
				, AppliesToDocLineAmount
			FROM OPENJSON(@line, '$.itemChargeAssignmentLines')
			WITH (
				  ItemChargeNo NVARCHAR(50)
				, UnitCost DECIMAL(18,4)
				, AppliesToDocType INT
				, AppliesToDocNo NVARCHAR(50)
				, AppliesToDocLineNo INT
				, ItemNo NVARCHAR(50)
				, Description NVARCHAR(250)
				, QtyToAssign DECIMAL(18,4)
				, QtyAssigned DECIMAL(18,4)
				, AmountToAssign DECIMAL(18,4)
				, AppliesToDocLineAmount DECIMAL(18,4)
			);
			-----------------------------------------------------------------------------------------------------------------------------------

			FETCH NEXT FROM line_cursor INTO @line;
		END;

		CLOSE line_cursor;
		DEALLOCATE line_cursor;

		FETCH NEXT FROM doc_cursor INTO @doc;
	END;

	CLOSE doc_cursor;
	DEALLOCATE doc_cursor;

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

	--===============================================-- Build output JSON result --===============================================--
	SELECT @output =
	(
		SELECT
			JSON_QUERY(
				COALESCE(
					(
						SELECT
							  pd.DocumentType
							, [No] = pd.No_
							, pd.NoSeries
							, pd.ProcessIDTransfer
							, pd.BuyFromVendorNo
							, pd.PayToVendorNo
							, pd.PostingDate
							, pd.PaymentTermsCode
							, pd.PaymentTermsCodeIR
							, pd.DueDate
							, pd.PmtDiscountDate
							, pd.PaymentDiscount
							, pd.CurrencyCode
							, pd.InvoiceDiscCode
							, pd.PostingDescription
							, pd.PaymentMethodCode
							, pd.VendorInvoiceNo
							, pd.VendorCrMemoNo
							, pd.PhrVendorBankAccountCode
							, pd.PhrBankBranchNo
							, pd.PhrBankAccountNo
							, pd.PhrIBAN
							, pd.PhrSWIFTCode
							, pd.PhrBankName
							, pd.PhrBankAccountEntryPriority
							, pd.PhrRMCashDiscountReceived
							, pd.PhrRMAmountIncludingVAT
							, pd.PhrRMAmountLessDiscount
							, purchaseLines = JSON_QUERY(
								COALESCE(
									(
										SELECT
											  pl.AttachedToLineNo
											, pl.Type
											, [No] = pl.No_
											, pl.Description
											, pl.Description2
											, pl.LocationCode
											, pl.VariantCode
											, pl.Quantity
											, pl.UnitOfMeasureCode
											, pl.DirectUnitCost
											, pl.LineDiscount
											, pl.AbleToDiscount
											, pl.DiscountCalculated
											, pl.WorkOrderNo
											, pl.GenBusPostingGroup
											, pl.GenProdPostingGroup
											, pl.VatBusPostingGroup
											, pl.VatProdPostingGroup
											, pl.ApplToItemEntry
											, pl.PostingWithoutApply
											, pl.AnticipatedPayment
											, pl.ReceiptNo
											, pl.ReceiptLineNo
											, pl.IrOrderNo
											, pl.IrOrderLineNo
											, dimSetEntries = JSON_QUERY(
												COALESCE(
													(
														SELECT
															  d.DimensionCode
															, d.DimensionValueCode
														FROM dbo.DimSetEntry d
														WHERE d.LineID = pl.LineID
														FOR JSON PATH
													)
													, '[]'
												)
											)
											, itemChargeAssignmentLines = JSON_QUERY(
												COALESCE(
													(
														SELECT
															  ia.ItemChargeNo
															, ia.UnitCost
															, ia.AppliesToDocType
															, ia.AppliesToDocNo
															, ia.AppliesToDocLineNo
															, ia.ItemNo
															, ia.Description
															, ia.QtyToAssign
															, ia.QtyAssigned
															, ia.AmountToAssign
															, ia.AppliesToDocLineAmount
														FROM dbo.ItemChargeAssignment ia
														WHERE ia.LineID = pl.LineID
														FOR JSON PATH
													)
													, '[]'
												)
											)
										FROM dbo.PurchaseLine pl
										WHERE pl.DocumentID = pd.DocumentID
										FOR JSON PATH
									)
									, '[]'
								)
							)
						FROM dbo.PurchaseDocument pd
						INNER JOIN @InsertedDocuments id ON id.DocumentID = pd.DocumentID
						ORDER BY pd.DocumentID
						FOR JSON PATH
					)
					, '[]'
				)
			) AS purchaseDocuments
		FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
	);
	-----------------------------------------------------------------------------------------------------------------------------------

	COMMIT TRANSACTION;

	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 = 1
		, message = N'Daten erfolgreich verarbeitet.'
		, data = @output;

END TRY BEGIN CATCH

	--====================================================-- exception / error --====================================================--
	IF (@@TRANCOUNT > 0) BEGIN
		ROLLBACK TRANSACTION;
	END;

	SET @RETURN_STATUS		= 50000;
	SET @RETURN_STATUS_TEXT	= CONCAT('END PROCEDURE [',OBJECT_NAME(@@PROCID),'] @ ',CONVERT(NVARCHAR(50),GETDATE(),120));
	SET @RETURN_ERROR_TEXT	= CONCAT('ERROR MESSAGE: ',CONVERT(NVARCHAR(500),ERROR_MESSAGE()));

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

	SELECT
		  success = 0
		, message = ERROR_MESSAGE()
		, data = NULL;

END CATCH;
GO
