CREATE
	OR

ALTER FUNCTION [HM].[ft_ForeignOrderPositions] (
	@foreignOrderId INT,
	@removeInvalidXMLCharacters BIT = 0
	)
RETURNS TABLE
AS
RETURN (
		SELECT 'true' AS [IsDocumentPosition],
			IIF(@removeInvalidXMLCharacters = 0, ZP.opis, HM.RemoveInvalidXMLCharacters(ZP.opis)) AS [Description],
			[sbp].[PriceOfSetCalculatedBasedOfElements],
			[sbp].[NoEditOfSet],
			[sbp].[VatRateId],
			[sbp].[PricePLN],
			[sbp].[PriceGross],
			[sbp].[PriceGrossPLN],
			[sbp].[PriceListPrice],
			[sbp].[PriceListPriceGross],
			[sbp].[OriginalPriceListPrice],
			[sbp].[OriginalPriceListPriceCurrency],
			[sbp].[OriginalBasePrice],
			[sbp].[OriginalBasePriceCurrency],
			[sbp].[BasePricePLN],
			[sbp].[ValueGross],
			[sbp].[ValueVat],
			[sbp].[ValuePLN],
			[sbp].[ValueGrossPLN],
			[sbp].[ValueVatPLN],
			[sbp].[PriceTypeId],
			[sbp].[OO],
			[sbp].[CodePKWIU],
			[sbp].[Discount],
			[sbp].[IsProductDiscountAllowed],            
			[sbp].[ReservationStockCode],
			[sbp].[StockStatus],
			[sbp].[ServiceExpense],
			[sbp].[Id],
			[sbp].[NodeId],
			[sbp].[ParentId],
			[sbp].[UserOrdinalNumber],
			[sbp].[OrdinalNumber],
			[sbp].[DocumentId],
			[sbp].[OriginalDocumentId],
			[sbp].[BaseType],
			[sbp].[Guid],
			[sbp].[ProductId],
			[sbp].[ProductShortcut],
			[sbp].[IsElementOfSet],
			[sbp].[IsSet],
			[sbp].[UnitOfMeasurement],
			[sbp].[EvidenceUnitOfMeasurement],
			[sbp].[ConversionFactorUoM],
			[sbp].[Quantity],
			[sbp].[UnitQuantity],
			[sbp].[ReservationQuantity],
			[sbp].[EvidenceQuantity],
			[sbp].[ReservationType],
			[sbp].[AccountingPattern],
			[sbp].[Price],
			[sbp].[Value],
			[sbp].[PriceRounding],
			[sbp].[IsService],
			[sbp].[CompletedQuantity],
			DpForSettlement.ForSettlement AS ForSettlement,
			DpForSettlement.ForSettlementPLN AS ForSettlementPLN,
			CASE WHEN DpForSettlement.UsedInAdvanceInvoice = 1 THEN 'true' ELSE 'false' END AS UsedInAdvanceInvoice,
			CAST(IIF(ABS(DpForSettlement.AdvanceInvoiceValueGross) < 0.009, NULL, DpForSettlement.AdvanceInvoiceValueGross) AS DECIMAL(24, 2)) AS AdvanceInvoiceValueGross,
			zp.lp
		FROM HM.ft_SaleBasePositions(45, @foreignOrderId, 0 /* nieużywane */, @removeInvalidXMLCharacters) sbp -- Rozliczona kwota zaliczek
		JOIN HM.ZP zp ON sbp.id = zp.id
		LEFT JOIN hm.ft_AdvanceInvoiceSummaryByZo(@foreignOrderId) DpForSettlement ON sbp.id = DpForSettlement.zpid
		WHERE ZP.subtyp IN (1, 2)
		)