USE [master] GO /****** Object: Database [site_fuchs] Script Date: 13/10/2022 21:16:38 ******/ CREATE DATABASE [site_fuchs] CONTAINMENT = NONE ON PRIMARY ( NAME = N'site_fuchs', FILENAME = N'C:\DATA\MSSQL14.SQL\MSSQL\DATA\site_fuchs.mdf' , SIZE = 3067904KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) LOG ON ( NAME = N'site_fuchs_log', FILENAME = N'C:\DATA\MSSQL14.SQL\MSSQL\DATA\site_fuchs_log.ldf' , SIZE = 2200000KB , MAXSIZE = 2048GB , FILEGROWTH = 5120KB ) GO ALTER DATABASE [site_fuchs] SET COMPATIBILITY_LEVEL = 140 GO IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) begin EXEC [site_fuchs].[dbo].[sp_fulltext_database] @action = 'enable' end GO ALTER DATABASE [site_fuchs] SET ANSI_NULL_DEFAULT OFF GO ALTER DATABASE [site_fuchs] SET ANSI_NULLS OFF GO ALTER DATABASE [site_fuchs] SET ANSI_PADDING OFF GO ALTER DATABASE [site_fuchs] SET ANSI_WARNINGS OFF GO ALTER DATABASE [site_fuchs] SET ARITHABORT OFF GO ALTER DATABASE [site_fuchs] SET AUTO_CLOSE OFF GO ALTER DATABASE [site_fuchs] SET AUTO_SHRINK OFF GO ALTER DATABASE [site_fuchs] SET AUTO_UPDATE_STATISTICS ON GO ALTER DATABASE [site_fuchs] SET CURSOR_CLOSE_ON_COMMIT OFF GO ALTER DATABASE [site_fuchs] SET CURSOR_DEFAULT GLOBAL GO ALTER DATABASE [site_fuchs] SET CONCAT_NULL_YIELDS_NULL OFF GO ALTER DATABASE [site_fuchs] SET NUMERIC_ROUNDABORT OFF GO ALTER DATABASE [site_fuchs] SET QUOTED_IDENTIFIER OFF GO ALTER DATABASE [site_fuchs] SET RECURSIVE_TRIGGERS OFF GO ALTER DATABASE [site_fuchs] SET DISABLE_BROKER GO ALTER DATABASE [site_fuchs] SET AUTO_UPDATE_STATISTICS_ASYNC OFF GO ALTER DATABASE [site_fuchs] SET DATE_CORRELATION_OPTIMIZATION OFF GO ALTER DATABASE [site_fuchs] SET TRUSTWORTHY OFF GO ALTER DATABASE [site_fuchs] SET ALLOW_SNAPSHOT_ISOLATION OFF GO ALTER DATABASE [site_fuchs] SET PARAMETERIZATION SIMPLE GO ALTER DATABASE [site_fuchs] SET READ_COMMITTED_SNAPSHOT OFF GO ALTER DATABASE [site_fuchs] SET HONOR_BROKER_PRIORITY OFF GO ALTER DATABASE [site_fuchs] SET RECOVERY FULL GO ALTER DATABASE [site_fuchs] SET MULTI_USER GO ALTER DATABASE [site_fuchs] SET PAGE_VERIFY CHECKSUM GO ALTER DATABASE [site_fuchs] SET DB_CHAINING OFF GO ALTER DATABASE [site_fuchs] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) GO ALTER DATABASE [site_fuchs] SET TARGET_RECOVERY_TIME = 0 SECONDS GO ALTER DATABASE [site_fuchs] SET DELAYED_DURABILITY = DISABLED GO ALTER DATABASE [site_fuchs] SET QUERY_STORE = OFF GO ALTER AUTHORIZATION ON DATABASE::[site_fuchs] TO [sa] GO USE [site_fuchs] GO /****** Object: User [fuchs_web] Script Date: 13/10/2022 21:16:38 ******/ CREATE USER [fuchs_web] FOR LOGIN [fuchs_web] WITH DEFAULT_SCHEMA=[dbo] GO /****** Object: User [fuchs_fds] Script Date: 13/10/2022 21:16:38 ******/ CREATE USER [fuchs_fds] FOR LOGIN [fuchs_fds] WITH DEFAULT_SCHEMA=[dbo] GO /****** Object: DatabaseRole [ocms_rwe] Script Date: 13/10/2022 21:16:39 ******/ CREATE ROLE [ocms_rwe] GO /****** Object: DatabaseRole [fuchs_rwe] Script Date: 13/10/2022 21:16:39 ******/ CREATE ROLE [fuchs_rwe] GO /****** Object: DatabaseRole [fds_rwe] Script Date: 13/10/2022 21:16:39 ******/ CREATE ROLE [fds_rwe] GO ALTER AUTHORIZATION ON ROLE::[ocms_rwe] TO [dbo] GO ALTER AUTHORIZATION ON ROLE::[fuchs_rwe] TO [dbo] GO ALTER AUTHORIZATION ON ROLE::[fds_rwe] TO [dbo] GO ALTER ROLE [ocms_rwe] ADD MEMBER [fuchs_web] GO ALTER ROLE [fuchs_rwe] ADD MEMBER [fuchs_web] GO ALTER ROLE [fds_rwe] ADD MEMBER [fuchs_fds] GO GRANT ALTER TO [fds_rwe] AS [dbo] GO GRANT CONNECT TO [fds_rwe] AS [dbo] GO GRANT CREATE TABLE TO [fds_rwe] AS [dbo] GO GRANT DELETE TO [fds_rwe] AS [dbo] GO GRANT EXECUTE TO [fds_rwe] AS [dbo] GO GRANT INSERT TO [fds_rwe] AS [dbo] GO GRANT SELECT TO [fds_rwe] AS [dbo] GO GRANT UPDATE TO [fds_rwe] AS [dbo] GO GRANT VIEW DATABASE STATE TO [fds_rwe] AS [dbo] GO GRANT CONNECT TO [fuchs_fds] AS [dbo] GO GRANT CONNECT TO [fuchs_web] AS [dbo] GO GRANT CONNECT TO [ocms_rwe] AS [dbo] GO GRANT DELETE TO [ocms_rwe] AS [dbo] GO GRANT EXECUTE TO [ocms_rwe] AS [dbo] GO GRANT INSERT TO [ocms_rwe] AS [dbo] GO GRANT SELECT TO [ocms_rwe] AS [dbo] GO GRANT UPDATE TO [ocms_rwe] AS [dbo] GO GRANT VIEW ANY COLUMN ENCRYPTION KEY DEFINITION TO [public] AS [dbo] GO GRANT VIEW ANY COLUMN MASTER KEY DEFINITION TO [public] AS [dbo] GO /****** Object: UserDefinedTableType [dbo].[fds__tt__admin_ReportAdminTable] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__admin_ReportAdminTable] AS TABLE( [class] [varchar](255) NULL, [title] [varchar](255) NULL, [label] [varchar](255) NULL, [sublabel] [varchar](255) NULL, [style] [varchar](2000) NULL, [typ] [varchar](10) NULL, [settings] [varchar](2000) NULL, [legend] [nvarchar](max) NULL, [order] [int] NOT NULL, PRIMARY KEY NONCLUSTERED ( [order] ASC )WITH (IGNORE_DUP_KEY = OFF) ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__admin_ReportAdminTable] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__bankingtransactions] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__bankingtransactions] AS TABLE( [AccountIdentification] [varchar](50) NULL, [ValueDate] [date] NULL, [Amount] [numeric](9, 2) NULL, [FundsCode] [varchar](1) NULL, [AccountNumberOfPayer] [varchar](30) NULL, [BankCodeOfPayer] [varchar](11) NULL, [CompensationAmount] [varchar](50) NULL, [CreditorReference] [varchar](30) NULL, [CreditorsReferenceParty] [varchar](50) NULL, [CustomerReference] [varchar](50) NULL, [EndToEndReference] [varchar](50) NULL, [JournalNumber] [varchar](10) NULL, [MandateReference] [varchar](50) NULL, [NameOfPayer] [nvarchar](60) NULL, [OriginalAmount] [varchar](150) NULL, [OriginatorsIdentificationCode] [varchar](150) NULL, [PayersReferenceParty] [varchar](150) NULL, [PostingText] [varchar](30) NULL, [SepaRemittanceInformation] [varchar](200) NULL, [TextKeyAddition] [int] NULL, [TransactionCode] [int] NULL, [IsUnstructuredData] [bit] NULL, [UnstructuredData] [nvarchar](390) NULL, [UnstructuredRemittanceInformation] [nvarchar](390) NULL, [DebitCreditMark] [varchar](2) NULL, [TransactionTypeIdCode] [varchar](3) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__bankingtransactions] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__idlist] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__idlist] AS TABLE( [Id] [bigint] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__idlist] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__idlist_vchar] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__idlist_vchar] AS TABLE( [Id] [varchar](15) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__idlist_vchar] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__invoice_base] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__invoice_base] AS TABLE( [Id] [varchar](10) NULL, [Version] [int] NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [nvarchar](255) NULL, [InvoiceBalance] [numeric](10, 2) NULL, [InvoiceBalance_net] [numeric](10, 2) NULL, [InvoiceVAT_net1] [numeric](10, 2) NULL, [InvoiceVAT_1] [numeric](5, 2) NULL, [InvoiceVAT_net2] [numeric](10, 2) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NULL, [DueDate] [date] NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NULL, [IsSent] [bit] NULL, [IsFinal] [bit] NULL, [IsCanceled] [bit] NULL, [Replaces_InvId] [varchar](50) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NULL, [UserCreated] [varchar](25) NULL, [DateModified] [datetime] NULL, [UserModified] [varchar](25) NULL, [ExternalId] [varchar](25) NULL, [isExternal] [bit] NULL, [hasFile] [bit] NULL, [UserNameFinalized] [nvarchar](255) NULL, [UserEmailFinalized] [varchar](255) NULL, [PaymentTermPhrase] [nvarchar](255) NULL, [InvoiceService] [numeric](10, 2) NULL, [InvoiceService_net] [numeric](10, 2) NULL, [InvoiceService_VAT] [numeric](10, 2) NULL, [InvoiceOptions] [varchar](50) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__invoice_base] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__invoice_core] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__invoice_core] AS TABLE( [Id] [varchar](10) NULL, [Version] [int] NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [varchar](50) NULL, [InvoiceBalance] [numeric](10, 2) NULL, [InvoiceBalance_net] [numeric](10, 2) NULL, [InvoiceVAT_net1] [numeric](10, 2) NULL, [InvoiceVAT_1] [numeric](5, 2) NULL, [InvoiceVAT_net2] [numeric](10, 2) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NULL, [DueDate] [date] NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NULL, [IsSent] [bit] NULL, [IsFinal] [bit] NULL, [IsCanceled] [bit] NULL, [Replaces_InvId] [varchar](10) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NULL, [UserCreated] [varchar](25) NULL, [DateModified] [datetime] NULL, [UserModified] [varchar](25) NULL, [file] [varbinary](max) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__invoice_core] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__invoice_items] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__invoice_items] AS TABLE( [Id] [bigint] NULL, [InvId] [varchar](10) NULL, [InvRqId] [bigint] NULL, [mfr__item] [bigint] NULL, [reference_InvId] [varchar](20) NULL, [Type] [nvarchar](255) NULL, [Position] [varchar](5) NULL, [Quantity] [nvarchar](25) NULL, [Text] [nvarchar](max) NULL, [value] [numeric](10, 2) NULL, [value_total] [numeric](10, 2) NULL, [vat] [numeric](5, 2) NULL, [value_service] [numeric](10, 2) NULL, [det] [bit] NULL, [SortOrder] [tinyint] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__invoice_items] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__invoice_servicerequests] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__invoice_servicerequests] AS TABLE( [Id] [bigint] NULL, [InvId] [varchar](10) NULL, [mfr__servicerequest] [bigint] NULL, [title] [nvarchar](max) NULL, [value_net] [numeric](10, 2) NULL, [SortOrder] [tinyint] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__invoice_servicerequests] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__mfr_items] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__mfr_items] AS TABLE( [Id] [bigint] NULL, [Version] [int] NULL, [QuantityHours] [numeric](10, 3) NULL, [PlannedQuantityHours] [numeric](10, 3) NULL, [ItemTypeId] [bigint] NULL, [ItemNumber] [nvarchar](255) NULL, [TrackingId] [nvarchar](255) NULL, [Manufacture] [nvarchar](255) NULL, [Price] [numeric](10, 3) NULL, [Costs] [numeric](10, 3) NULL, [NameOrNumber] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [Note] [nvarchar](max) NULL, [ExternalId] [nvarchar](255) NULL, [Discount] [numeric](10, 3) NULL, [VAT] [numeric](10, 3) NULL, [IsManual] [bit] NULL, [SortOrder] [int] NULL, [Type] [nvarchar](255) NULL, [ServiceRequestId] [bigint] NULL, [ServiceObjectId] [bigint] NULL, [CreatorId] [bigint] NULL, [UnitId] [bigint] NULL, [UnitString] [nvarchar](255) NULL, [baseorder] [int] NULL, [order] [int] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__mfr_items] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__mfr_steps] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__mfr_steps] AS TABLE( [Id] [bigint] NOT NULL, [MobileId] [bigint] NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [IsDone] [bit] NOT NULL, [HasError] [bit] NOT NULL, [TrackingId] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [SortOrder] [int] NOT NULL, [Data] [nvarchar](max) NULL, [DateModifiedOffline] [datetime] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [Comment] [nvarchar](max) NULL, [InternalComment] [nvarchar](max) NULL, [ServiceObjectId] [bigint] NULL, [StepListTemplateId] [bigint] NULL, [ParentId] [bigint] NULL, [baseorder] [int] NOT NULL, [order] [int] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__mfr_steps] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[fds__tt__reminder_core] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[fds__tt__reminder_core] AS TABLE( [Id] [varchar](10) NULL, [Version] [int] NULL, [DocumentName] [varchar](100) NULL, [InvId] [varchar](15) NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [type] [varchar](3) NULL, [amount] [numeric](10, 3) NULL, [amount_payed] [numeric](10, 3) NULL, [amount_open] [numeric](10, 3) NULL, [subject] [nvarchar](255) NULL, [text] [nvarchar](2000) NULL, [IsSent] [bit] NULL, [IsFinal] [bit] NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCreated] [datetime] NULL, [UserCreated] [varchar](25) NULL, [DateModified] [datetime] NULL, [UserModified] [varchar](25) NULL, [file] [varbinary](max) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[fds__tt__reminder_core] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__#customvalues] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__#customvalues] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [EntityId] [bigint] NOT NULL, [Property] [varchar](255) NOT NULL, [Meta] [varchar](255) NOT NULL, [Value] [varchar](1000) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__#customvalues] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__#locations] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__#locations] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [EntityId] [bigint] NULL, [Property] [varchar](255) NOT NULL, [Version] [int] NOT NULL, [AddressString] [nvarchar](255) NULL, [Postal] [nvarchar](255) NULL, [City] [nvarchar](255) NULL, [State] [nvarchar](255) NULL, [Country] [varchar](15) NULL, [Longitude] [numeric](8, 5) NULL, [Latitude] [numeric](8, 5) NULL, [IsValidLocation] [bit] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__#locations] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__*PartnerSet] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__*PartnerSet] AS TABLE( [setid] [varchar](5) NULL, [Property] [varchar](50) NOT NULL, [PartnerType] [varchar](25) NOT NULL, [PartnerId] [bigint] NOT NULL, [EntityId] [bigint] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__*PartnerSet] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__appointments] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__appointments] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [State] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [EndDateTime] [datetime] NULL, [StartDateTime] [datetime] NOT NULL, [DrivingDistanceFrom] [int] NULL, [DrivingDistanceTo] [int] NULL, [WasReadOnClientSide] [bit] NOT NULL, [ContactIds] [varchar](max) NULL, [ServiceRequestId] [bigint] NOT NULL, [ContactId] [bigint] NOT NULL, [Note] [nvarchar](max) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__appointments] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__attachments] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__attachments] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [URI] [nvarchar](255) NULL, [StepId] [bigint] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__attachments] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__comments] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__comments] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [DateOfCreation] [datetime] NOT NULL, [IsInternal] [bit] NOT NULL, [ServiceRequestId] [bigint] NOT NULL, [CompanyId] [bigint] NOT NULL, [Content] [nvarchar](max) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__comments] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__companies] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__companies] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsPhysicalPerson] [bit] NOT NULL, [IsOwner] [bit] NOT NULL, [IsEmailInvoicingActive] [bit] NOT NULL, [IsSupplier] [bit] NOT NULL, [MappingId] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [SupportTelephone] [nvarchar](255) NULL, [SupportFax] [nvarchar](255) NULL, [SupportMail] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [MainContactId] [bigint] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__companies] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__contacts] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__contacts] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [FirstName] [nvarchar](255) NULL, [LastName] [nvarchar](255) NULL, [Email] [nvarchar](255) NULL, [JobTitle] [nvarchar](255) NULL, [MobilePhone] [nvarchar](255) NULL, [Telephone] [nvarchar](255) NULL, [Fax] [nvarchar](255) NULL, [Note] [nvarchar](1000) NULL, [DateModified] [datetime] NOT NULL, [Version] [int] NOT NULL, [CompanyId] [bigint] NOT NULL, [IsUser] [bit] NOT NULL, [ExternalId] [nvarchar](255) NULL, [Gender] [nvarchar](255) NULL, [UserId] [bigint] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__contacts] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__costcenters] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__costcenters] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__costcenters] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__documents] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__documents] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [Version] [int] NOT NULL, [State] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [URI] [nvarchar](255) NULL, [IsGlobal] [bit] NOT NULL, [StartDateTime] [datetime] NULL, [EndDateTime] [datetime] NULL, [FileName] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [UploadDate] [datetime] NOT NULL, [IsLink] [bit] NOT NULL, [ContentType] [nvarchar](255) NULL, [HTMLCode] [nvarchar](255) NULL, [ServiceRequestId] [bigint] NOT NULL, [Note] [nvarchar](255) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__documents] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__invoices] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__invoices] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NULL, [Version] [int] NULL, [DateOfCreation] [datetime] NULL, [URI] [nvarchar](255) NULL, [DocumentName] [nvarchar](255) NULL, [ReportDefinitionCode] [nvarchar](255) NULL, [FileType] [nvarchar](255) NULL, [InvoiceBalance] [numeric](10, 2) NULL, [InvoiceBalanceNetto] [numeric](10, 2) NULL, [WageBalanceNet] [numeric](10, 2) NULL, [DatePayed] [datetime] NULL, [InvoiceId] [nvarchar](50) NULL, [DueDate] [datetime] NULL, [WithoutVAT] [bit] NULL, [Skonto] [numeric](10, 2) NULL, [PartialPayment] [numeric](10, 2) NULL, [InvoiceState] [nvarchar](255) NULL, [Note] [nvarchar](max) NULL, [file_guid] [uniqueidentifier] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__invoices] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__items] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__items] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [QuantityHours] [numeric](10, 3) NOT NULL, [PlannedQuantityHours] [numeric](10, 3) NOT NULL, [ItemTypeId] [bigint] NULL, [ItemNumber] [varchar](255) NULL, [TrackingId] [varchar](255) NULL, [Manufacture] [varchar](255) NULL, [Price] [numeric](10, 3) NOT NULL, [Costs] [numeric](10, 3) NULL, [NameOrNumber] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [Note] [nvarchar](max) NULL, [ExternalId] [nvarchar](255) NULL, [Discount] [numeric](10, 3) NOT NULL, [VAT] [numeric](10, 3) NOT NULL, [IsManual] [bit] NOT NULL, [SortOrder] [int] NOT NULL, [Type] [varchar](255) NULL, [ServiceRequestId] [bigint] NOT NULL, [ServiceObjectId] [bigint] NOT NULL, [CreatorId] [bigint] NOT NULL, [UnitId] [bigint] NULL, [UnitString] [varchar](50) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__items] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__itemtypes] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__itemtypes] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [Version] [int] NOT NULL, [Costs] [numeric](10, 3) NOT NULL, [Description] [nvarchar](max) NULL, [ListPrice] [numeric](10, 3) NOT NULL, [Manufacture] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [ItemNumber] [nvarchar](255) NULL, [NameOrNumber] [nvarchar](1000) NULL, [GlobalTradeItemNr] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [Price] [numeric](10, 3) NOT NULL, [VAT] [numeric](10, 3) NOT NULL, [IsPortalOnly] [bit] NOT NULL, [Discount] [numeric](10, 3) NOT NULL, [DateModified] [datetime] NOT NULL, [IsDiscontinued] [bit] NOT NULL, [IsWarehouse] [bit] NOT NULL, [UnitId] [bigint] NULL, [UnitString] [nvarchar](255) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__itemtypes] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__itemunits] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__itemunits] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__itemunits] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__products] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__products] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [SubKey] [nvarchar](255) NULL, [Description] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [MappingId] [nvarchar](255) NULL, [CustomValueStepTemplateId] [bigint] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__products] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__qualifications] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__qualifications] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__qualifications] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__reports] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__reports] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [DateOfCreation] [datetime] NOT NULL, [URI] [nvarchar](255) NULL, [DocumentName] [nvarchar](255) NULL, [FileTypeString] [nvarchar](255) NULL, [ReportDefinitionCode] [nvarchar](255) NULL, [ServiceObjectId] [bigint] NOT NULL, [CanBeDeleted] [bit] NOT NULL, [InvoiceBalance] [numeric](10, 3) NOT NULL, [InvoiceId] [nvarchar](255) NULL, [DueDate] [datetime] NOT NULL, [IsPayed] [bit] NOT NULL, [IsInvoice] [bit] NOT NULL, [IsCanceled] [bit] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__reports] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__serviceobjects] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__serviceobjects] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NOT NULL, [DateModified] [datetime] NOT NULL, [ExternalId] [nvarchar](255) NULL, [MappingId] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [Version] [int] NOT NULL, [CreateGeoLocation] [bit] NOT NULL, [IsWarehouse] [bit] NOT NULL, [ParentServiceObjectId] [bigint] NOT NULL, [CompanyId] [bigint] NOT NULL, [ProductId] [bigint] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__serviceobjects] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__servicerequests] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__servicerequests] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] [nvarchar](255) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NOT NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [varchar](100) NULL, [CustomValues] [nvarchar](max) NOT NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsTemplate] [bit] NOT NULL, [IsTemplateMobile] [bit] NOT NULL, [CreateFromServiceRequestTemplateId] [bigint] NOT NULL, [Type] [nvarchar](255) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__servicerequests] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__steplisttemplateinstances] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__steplisttemplateinstances] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [ServiceRequestId] [bigint] NULL, [TemplateId] [bigint] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__steplisttemplateinstances] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__steplisttemplates] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__steplisttemplates] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [MappingId] [nvarchar](255) NULL, [DateModified] [datetime] NULL, [IsReleased] [bit] NOT NULL, [IsDurable] [bit] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__steplisttemplates] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__steps] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__steps] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [MobileId] [bigint] NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [IsDone] [bit] NOT NULL, [HasError] [bit] NOT NULL, [TrackingId] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [SortOrder] [int] NOT NULL, [Data] [nvarchar](max) NULL, [DateModifiedOffline] [datetime] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [Comment] [nvarchar](max) NULL, [InternalComment] [nvarchar](max) NULL, [ServiceObjectId] [bigint] NULL, [StepListTemplateId] [bigint] NULL, [ParentId] [bigint] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__steps] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__stockmovements] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__stockmovements] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Amount] [numeric](10, 3) NOT NULL, [AmountReceived] [numeric](10, 3) NOT NULL, [ExternalId] [varchar](255) NULL, [ItemId] [bigint] NULL, [ItemTypeId] [bigint] NULL, [StockMovementType] [varchar](255) NULL, [State] [varchar](255) NULL, [ServiceRequestId] [bigint] NOT NULL, [WarehouseId] [bigint] NOT NULL, [DateOfCreation] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL, [TargetDate] [datetime] NOT NULL, [CreatedById] [bigint] NOT NULL, [ConfirmedById] [bigint] NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__stockmovements] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__tags] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__tags] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [ColorDefinition] [nvarchar](255) NULL, [Type] [nvarchar](255) NOT NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__tags] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__timeevents] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__timeevents] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [State] [nvarchar](255) NULL, [IsApproved] [bit] NOT NULL, [TimeEventType] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [StartDateTime] [datetime] NOT NULL, [EndDateTime] [datetime] NOT NULL, [ProposedDrivingDistance] [int] NOT NULL, [ContactId] [bigint] NOT NULL, [ServiceRequestId] [bigint] NOT NULL, [Description] [nvarchar](max) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__timeevents] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[mfr__tt__users] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[mfr__tt__users] AS TABLE( [setid] [varchar](5) NULL, [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [UserName] [nvarchar](255) NULL, [IsSystem] [bit] NOT NULL, [CreationDate] [datetime] NOT NULL, [IsApproved] [bit] NOT NULL, [ContactId] [bigint] NOT NULL, [PreferedLanguage] [nvarchar](255) NULL, [EmailChannelEnabled] [bit] NOT NULL, [HasFullScreenPreference] [bit] NOT NULL, [TimeZone] [int] NOT NULL, [PreferedCulture] [nvarchar](255) NULL, [IsActive] [bit] NOT NULL, [IsMobile] [bit] NOT NULL, [LastLoginDate] [datetime] NULL, [UserGuideProgress] [nvarchar](255) NULL, [DashboardSettings] [nvarchar](4000) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[mfr__tt__users] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[ocms_type_itemtree] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[ocms_type_itemtree] AS TABLE( [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [ocms_pid] [bigint] NULL, [name] [nvarchar](255) NULL, [view] [bit] NOT NULL, [template_id] [bigint] NULL, [hide] [bit] NOT NULL, [order] [int] NOT NULL, [DateCreated] [datetime] NULL, [DateModified] [datetime] NULL, [level] [int] NULL, [sub] [bit] NULL, [sitepropsub] [bit] NULL, [focus] [bit] NULL, [new_order] [int] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[ocms_type_itemtree] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[ocms_type_navigation_base] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[ocms_type_navigation_base] AS TABLE( [ocms_iid] [bigint] NOT NULL, [locale] [varchar](5) NOT NULL, [alias] [varchar](25) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[ocms_type_navigation_base] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[ocms_type_properties_base] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[ocms_type_properties_base] AS TABLE( [ocms_iid] [bigint] NOT NULL, [key] [varchar](50) NULL, [value] [nvarchar](max) NOT NULL, [locale] [varchar](5) NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[ocms_type_properties_base] TO SCHEMA OWNER GO /****** Object: UserDefinedTableType [dbo].[ocms_type_viewtree_full] Script Date: 13/10/2022 21:16:40 ******/ CREATE TYPE [dbo].[ocms_type_viewtree_full] AS TABLE( [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [ocms_pid] [bigint] NULL, [name] [nvarchar](255) NULL, [view] [bit] NOT NULL, [template_id] [bigint] NULL, [hide] [bit] NOT NULL, [order] [int] NOT NULL, [DateCreated] [datetime] NULL, [DateModified] [datetime] NULL, [locale] [varchar](5) NOT NULL, [alias] [varchar](25) NULL, [path] [varchar](2000) NULL, [level] [int] NULL, [sub] [bit] NULL, [focus] [bit] NULL, [nav] [bit] NULL, [new_order] [int] NULL ) GO ALTER AUTHORIZATION ON TYPE::[dbo].[ocms_type_viewtree_full] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[AddBusinessDays] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION[dbo].[AddBusinessDays](@Date DATE,@n INT) RETURNS DATE AS BEGIN DECLARE @d INT,@f INT,@DW INT; SET @f=CAST(abs(1^SIGN(DATEPART(DW, @Date)-(7-@@DATEFIRST))) AS BIT) SET @DW=DATEPART(DW,@Date)-(7-@@DATEFIRST)*(@f^1)+@@DATEFIRST*(@f&1) SET @d=4-SIGN(@n)*(4-@DW); RETURN DATEADD(D,@n+((ABS(@n)+(@d%(8+SIGN(@n)))-2)/5)*2*SIGN(@n)-@d/7,@Date); END GO ALTER AUTHORIZATION ON [dbo].[AddBusinessDays] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[backup__fds__fn_bankingtransactions] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[backup__fds__fn_bankingtransactions] ( @startdate date = NULL ,@enddate date = NULL ,@invoice_startdate date = NULL ,@invoice_enddate date = NULL ,@invoice_idlist [dbo].[fds__tt__idlist_vchar] READONLY ) RETURNS @bankingtransactions TABLE ( [uid] bigint ,[AccountIdentification] varchar(50) ,[ValueDate] date ,[Amount] numeric(9,2) ,[AccountNumberOfPayer] varchar(30) ,[NameOfPayer] nvarchar(60) ,[SepaRemittanceInformation] varchar(150) ,[EndToEndReference] varchar(50) ,[manu] bit ,[InvId] varchar(15) ,[done_manually] bit ,[fds] bit ) AS BEGIN -- Fill the table variable with the rows for your result set DECLARE @firstever date = '1900-01-01', @tomorrow date = DATEADD(dAy, 1, GETDATE()); SELECT @invoice_startdate = ISNULL(@invoice_startdate, @firstever), @invoice_enddate = ISNULL(@invoice_enddate, @tomorrow); DECLARE @idlistempty bit = IIF(EXISTS (SELECT 0 FROM @invoice_idlist) ,0,1); with bt as ( SELECT [uid],[AccountIdentification],[ValueDate],[Amount],AccountNumberOfPayer,NameOfPayer, SepaRemittanceInformation, EndToEndReference FROM [dbo].[fds__bankingtransactions] as bt_ where (@startdate is null OR bt_.ValueDate >= @startdate) AND (@enddate is null or bt_.ValueDate <= @enddate) ), bs0manu as ( SELECT bs.[banking_uid], [invid] = spl.[value], [manu] = cast(1 as bit) FROM [dbo].[fds__bankingtransactions_settings] as bs CROSS APPLY STRING_SPLIT(bs.assigned_invoice_id, ',') as spl JOIN bt on bt.[uid] = bs.[banking_uid] WHERE bs.assigned_invoice_id is not null ), bs1 as ( SELECT * FROM bs0manu UNION SELECT bs.[banking_uid], [invid] = spl.[value], [manu] = cast(0 as bit) FROM [dbo].[fds__bankingtransactions_settings] as bs CROSS APPLY STRING_SPLIT(bs.auto_invoice_id, ',') as spl JOIN bt on bt.[uid] = bs.[banking_uid] WHERE bs.auto_invoice_id is not null and bt.[uid] NOT IN (SELECT [banking_uid] FROM bs0manu) ), bs as ( SELECT banking_uid, [invid], manu = CAST(MAX(CAST([manu] as int)) as bit) from bs1 WHERE @idlistempty = 1 OR bs1.[invid] in (SELECT [id] FROM @invoice_idlist) GROUP BY banking_uid, [invid] ) INSERT INTO @bankingtransactions SELECT bt.[uid] ,[AccountIdentification] , bt.[ValueDate] , [Amount] ,bt.AccountNumberOfPayer ,bt.NameOfPayer ,bt.SepaRemittanceInformation ,bt.EndToEndReference ,[manu] ,[invid] ,[done_manually] = IIF(ISNULL(bs2.[done_manually],'') <> '', 1,0) ,[fds] = IIF(mi.id is null, 1, 0) FROM bt JOIN bs ON bt.[uid] = bs.[banking_uid] LEFT JOIN [dbo].[fds__bankingtransactions_settings] as bs2 ON bt.[uid] = bs2.[banking_uid] LEFT JOIN [dbo].[fds__invoices] as fi on bs.[invid] = fi.[id] AND fi.[DateFinalized] BETWEEN @invoice_startdate AND @invoice_enddate LEFT JOIN [dbo].[mfr__invoices] as mi on try_cast(bs.[invid] as bigint) = mi.[id] AND mi.[DateOfCreation] BETWEEN @invoice_startdate AND @invoice_enddate; RETURN END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__fn_bankingtransactions] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[backup__fds__fn_invoice_customerid] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[backup__fds__fn_invoice_customerid] ( @InvId varchar(15) ) RETURNS bigint AS BEGIN DECLARE @ret bigint; SELECT TOP(1) @ret = [customerid] FROM dbo.[fds__invoices] WHERE [id] = @InvId; IF @ret is null SELECT TOP(1) @ret = [customerid] FROM (SELECT TOP(1) [invid] = p.[PartnerId], s.[CustomerId], cy.[supportmail], cy.[Name] FROM dbo.[mfr__*PartnerSet] as p JOIN [dbo].[mfr__servicerequests] as s on p.[EntityId] = s.[Id] AND p.[Property] = 'ServiceRequest:Invoices' JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE p.PartnerId = TRY_CAST(@invId as bigint))z; RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__fn_invoice_customerid] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[backup__fds__fn_InvoiceIdByName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[backup__fds__fn_InvoiceIdByName] ( @nme varchar(255) ) RETURNS varchar(20) AS BEGIN DECLARE @Id varchar(20); SET @nme = TRIM((SELECT TOP(1) [value] FROM string_split(@nme, '('))); SET @Id = ISNULL( (SELECT TOP(1) [Id] FROM ( SELECT TOP(1) [Id], [fds] = 1 FROM [dbo].[fds__invoices] WHERE [InvoiceId] = @nme UNION SELECT TOP(1) try_Cast([Id] as varchar(20)), [fds] = 0 FROM [dbo].[mfr__invoices] WHERE [InvoiceId] = @nme )z ORDER BY [fds] DESC ),''); RETURN @id; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__fn_InvoiceIdByName] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[backup__fds__r_getBalanceThisMonth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[backup__fds__r_getBalanceThisMonth]( @authuser varchar(100) ) RETURNS varchar(25) BEGIN DECLARE @today date = GETDATE(); DECLARE @tomorrow date = DATEADD(DAY,1,@today); DECLARE @thismonthfirst date = [dbo].[date_monthfirst](@today); DECLARE @ret varchar(25) = '' IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 SET @ret = ''; ELSE BEGIN WITH inv as ( SELECT i.[Dateofcreation] ,i.[InvoiceBalance] ,i.[InvoiceBalanceNetto] FROM [dbo].[mfr__invoices] as i where --i.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') and i.[FileType] in( 'PdfInvoice','PdfCancelInvoice','PdfPartialInvoice') and ISNULL(InvoiceId,'') not in ('Preview','') AND [dbo].[date_monthfirst](i.[Dateofcreation]) = @thismonthfirst UNION SELECT [Dateofcreation] = i.[DateFinalized] ,i.[InvoiceBalance] ,[InvoiceBalanceNetto] = i.[InvoiceBalance_net] FROM [dbo].[fds__invoices] as i WHERE i.[isFinal] = 1 AND [dbo].[date_monthfirst](i.[DateFinalized]) = @thismonthfirst ) SELECT TOP(1) @ret = FORMAT( SUM( ISNULL(inv.[InvoiceBalanceNetto],0) ) * 0.001, '#,0 k€', 'de') FROM inv; END RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__r_getBalanceThisMonth] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[bo_val] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[bo_val] ( @price numeric(10,3) ,@quantityhours numeric(10,3) ,@discount numeric(10,3) ,@VAT numeric(10,3) ) RETURNS numeric(7,2) AS BEGIN DECLARE @Ret numeric(7,2) SET @RET = [dbo].[net_val](@price, @quantityhours, @discount) * (1 + (ISNULL(@vat, 19.0) * 0.01)); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[bo_val] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[date_add] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[date_add] ( @date date ,@addition varchar(10) ,@shift_to_first bit = 1 ) RETURNS date AS BEGIN DECLARE @Ret date = @date; SET @addition = LOWER(ISNULL(@addition,'')); DECLARE @negative bit = 0; IF LEFT(@addition,1) = '-' BEGIN SET @negative = 1; SET @addition = REPLACE(@addition, '-', ''); END IF @addition like '[1-9]%[dwmqy]' BEGIN DECLARE @num int = TRY_CONVERT(int, LEFT(@addition, patindex('%[^0-9]%', @addition) - 1)) * IIF(@negative = 1, -1, 1), @unit varchar(2) = LOWER(RIGHT(@addition, LEN(@addition) - patindex('%[^0-9]%', @addition) + 1)) ; if @num is not null BEGIN SET @ret = CASE WHEN ISNULL(@shift_to_first,1) = 1 THEN CASE WHEN @unit = 'y' THEN DATEADD(YEAR, @num - 1, dbo.date_nextFirst(@date, 'y')) WHEN @unit = 'q' THEN DATEADD(QUARTER, @num - 1, dbo.date_nextFirst(@date, 'q')) WHEN @unit = 'm' THEN DATEADD(Month, @num - 1, dbo.date_nextFirst(@date, 'm')) WHEN @unit = 'w' THEN DATEADD(WEEK, @num - 1, dbo.date_nextFirst(@date, 'w')) WHEN @unit = 'd' THEN DATEADD(DAY, @num - 1, dbo.date_nextFirst(@date, 'd')) WHEN @unit in ('bd','wd') THEN [dbo].[AddBusinessDays](@date, @num) ELSE @date END ELSE CASE WHEN @unit = 'y' THEN DATEADD(YEAR, @num, @date) WHEN @unit = 'q' THEN DATEADD(QUARTER, @num, @date) WHEN @unit = 'm' THEN DATEADD(Month, @num, @date) WHEN @unit = 'w' THEN DATEADD(WEEK, @num, @date) WHEN @unit = 'd' THEN DATEADD(DAY, @num, @date) WHEN @unit in ('bd','wd') THEN [dbo].[AddBusinessDays](@date, @num) ELSE @date END END; END END RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[date_add] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[date_addcustom] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[date_addcustom] ( @date date ,@phrase varchar(10) ) RETURNS date AS BEGIN DECLARE @returndate date, @numpart integer = TRY_PARSE(left(@phrase, patindex('%[^0-9]%', @phrase + '.') - 1) as integer), @defpart varchar(10) = LOWER(RIGHT(@phrase, LEN(@phrase) - patindex('%[^0-9]%', @phrase + '.') + 1)); SET @returndate = CASE WHEN @numpart is null then null WHEN @defpart = 'wd' THEN [dbo].[AddBusinessDays](@date, @numpart) WHEN @defpart = 'd' THEN DATEADD(DAY, @numpart, @date) WHEN @defpart = 'y' THEN DATEADD(YEAR, @numpart, @date) WHEN @defpart = 'm' THEN DATEADD(Month, @numpart, @date) WHEN @defpart = 'wk' THEN DATEADD(WEEK, @numpart, @date) ELSE @date END; RETURN @returndate; END GO ALTER AUTHORIZATION ON [dbo].[date_addcustom] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[date_monthend] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[date_monthend] ( @date date ) RETURNS date AS BEGIN DECLARE @monthend date = CASE WHEN @date is null THEN NULL ELSE DATEADD(DAY, -1, DATEADD(MONTH, 1, DATEFROMPARTS(YEAR(@date), MONTH(@date),1))) END; return @monthend; END GO ALTER AUTHORIZATION ON [dbo].[date_monthend] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[date_monthfirst] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[date_monthfirst] ( @date date ) RETURNS date AS BEGIN DECLARE @monthfirst date = CASE WHEN @date is null THEN NULL ELSE DATEFROMPARTS(YEAR(@date), MONTH(@date), 1) END; return @monthfirst; END GO ALTER AUTHORIZATION ON [dbo].[date_monthfirst] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[date_nextFirst] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[date_nextFirst] ( @date date ,@unit varchar(1) ) RETURNS date AS BEGIN DECLARE @ret date; SET @unit = LOWER(ISNULL(@unit, '')); SET @ret = CASE WHEN @unit = 'y' THEN DATEADD(YEAR, 1, DATEFROMPARTS(YEAR(@date), 1,1)) WHEN @unit = 'q' THEN DATEADD(MONTH, 4 - Month(@date) % 3, DATEFROMPARTS(YEAR(@date),MONTH(@date),1)) WHEN @unit = 'm' THEN DATEADD(MONTH, 1, DATEFROMPARTS(YEAR(@date), MONTH(@date),1)) WHEN @unit = 'w' THEN DATEADD(WEEK, 1, [dbo].[date_weekfirst](@date)) WHEN @unit = 'd' THEN DATEADD(DAY, 1, @date) ELSE NULL END; RETURN @ret END GO ALTER AUTHORIZATION ON [dbo].[date_nextFirst] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[date_weekend] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: 31.01.2013 -- Description: first day of week -- ============================================= CREATE FUNCTION [dbo].[date_weekend] ( @TargetDate date ) RETURNS date AS BEGIN DECLARE @Corretor smallint = -((@@DATEFIRST % 7) - 1); DECLARE @ret date = CASE WHEN @TargetDate is null THEN null ELSE dateadd(d ,-((datepart(weekday,@TargetDate) - 1 - @Corretor)%7), @TargetDate) END; return DATEADD(DAY, 6, @ret); END GO ALTER AUTHORIZATION ON [dbo].[date_weekend] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[date_weekfirst] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: 31.01.2013 -- Description: first day of week -- ============================================= CREATE FUNCTION [dbo].[date_weekfirst] ( @TargetDate date ) RETURNS date AS BEGIN DECLARE @Corretor smallint = -((@@DATEFIRST % 7) - 1); DECLARE @ret date = CASE WHEN @TargetDate is null THEN null ELSE dateadd(d ,-((datepart(weekday,@TargetDate) - 1 - @Corretor)%7), @TargetDate) END; return @ret; END GO ALTER AUTHORIZATION ON [dbo].[date_weekfirst] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_bankingtransactions] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_bankingtransactions] ( @startdate date = NULL ,@enddate date = NULL ,@invoice_startdate date = NULL ,@invoice_enddate date = NULL ,@invoice_idlist [dbo].[fds__tt__idlist_vchar] READONLY ) RETURNS @bankingtransactions TABLE ( [uid] bigint ,[AccountIdentification] varchar(50) ,[ValueDate] date ,[Amount] numeric(9,2) ,[AccountNumberOfPayer] varchar(30) ,[NameOfPayer] nvarchar(60) ,[SepaRemittanceInformation] varchar(150) ,[EndToEndReference] varchar(50) ,[manu] bit ,[InvId] varchar(15) ,[done_manually] bit ,[fds] bit ) AS BEGIN -- Fill the table variable with the rows for your result set DECLARE @firstever date = '1900-01-01', @tomorrow date = DATEADD(dAy, 1, GETDATE()); SELECT @invoice_startdate = ISNULL(@invoice_startdate, @firstever), @invoice_enddate = ISNULL(@invoice_enddate, @tomorrow); DECLARE @idlistempty bit = IIF(EXISTS (SELECT 0 FROM @invoice_idlist) ,0,1); with bt as ( SELECT [uid],[AccountIdentification],[ValueDate],[Amount],AccountNumberOfPayer,NameOfPayer, SepaRemittanceInformation, EndToEndReference FROM [dbo].[fds__bankingtransactions] as bt_ where (@startdate is null OR bt_.ValueDate >= @startdate) AND (@enddate is null or bt_.ValueDate <= @enddate) AND (bt_.[DebitCreditMark] in ('C') AND NOT (ISNULL(bt_.[AccountNumberOfPayer],'') IN ('DE52301502000002091478') AND ISNULL(bt_.[SepaRemittanceInformation],'') like ('%umbuchung%')) AND NOT (ISNULL(bt_.[AccountNumberOfPayer],'') IN ('DE23501108006161606386') AND ISNULL(bt_.[SepaRemittanceInformation],'') like ('%ebay%')) AND NOT (ISNULL(bt_.[SepaRemittanceInformation],'') like ('%Umsatzsteuer%')) AND ISNULL(bt_.AccountNumberOfPayer,'') <> '' ) ), bs0manu as ( SELECT bs.[banking_uid], [invid] = spl.[value], [manu] = cast(1 as bit) FROM [dbo].[fds__bankingtransactions_settings] as bs CROSS APPLY STRING_SPLIT(bs.assigned_invoice_id, ',') as spl JOIN bt on bt.[uid] = bs.[banking_uid] WHERE bs.assigned_invoice_id is not null ), bs1 as ( SELECT * FROM bs0manu UNION SELECT bs.[banking_uid], [invid] = spl.[value], [manu] = cast(0 as bit) FROM [dbo].[fds__bankingtransactions_settings] as bs CROSS APPLY STRING_SPLIT(bs.auto_invoice_id, ',') as spl JOIN bt on bt.[uid] = bs.[banking_uid] WHERE bs.auto_invoice_id is not null and bt.[uid] NOT IN (SELECT [banking_uid] FROM bs0manu) ), bs as ( SELECT banking_uid, [invid], manu = CAST(MAX(CAST([manu] as int)) as bit) from bs1 WHERE @idlistempty = 1 OR bs1.[invid] in (SELECT [id] FROM @invoice_idlist) GROUP BY banking_uid, [invid] ) INSERT INTO @bankingtransactions SELECT bt.[uid] ,[AccountIdentification] , bt.[ValueDate] , [Amount] ,bt.AccountNumberOfPayer ,bt.NameOfPayer ,bt.SepaRemittanceInformation ,bt.EndToEndReference ,[manu] ,[invid] ,[done_manually] = IIF(ISNULL(bs2.[done_manually],'') <> '', 1,0) ,[fds] = IIF(fi.isExternal = 0, 1, 0) FROM bt JOIN bs ON bt.[uid] = bs.[banking_uid] LEFT JOIN [dbo].[fds__bankingtransactions_settings] as bs2 ON bt.[uid] = bs2.[banking_uid] LEFT JOIN [dbo].[fds__invoices] as fi on bs.[invid] = fi.[id] AND fi.[DateFinalized] BETWEEN @invoice_startdate AND @invoice_enddate RETURN END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_bankingtransactions] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_bankingtransactions_perInvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_bankingtransactions_perInvoice] ( @startdate date = NULL ,@enddate date = NULL ) RETURNS @bankingtransactions TABLE ( [InvId] varchar(15) ,[Amount] numeric(9,2) ,[manu] bit ) AS BEGIN -- Fill the table variable with the rows for your result set DECLARE @invoice_idlist [dbo].[fds__tt__idlist_vchar]; INSERT INTO @bankingtransactions SELECT [invid] , [amount] = SUM(ISNULL([amount], 0.0)) , [manu] = CAST(MAX(ISNULL(CAST([manu] as int),0)) as bit) FROM dbo.fds__fn_bankingtransactions(null, null, @startdate, @enddate, @invoice_idlist) -- start and enddates will filter by invoice date and not by banking transactions' value dates GROUP BY [invid]; RETURN END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_bankingtransactions_perInvoice] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_combineAddress] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_combineAddress] ( @AddressString nvarchar(255) ,@AddressString2 nvarchar(255) ,@AddressString3 nvarchar(255) ,@Postal nvarchar(255) ,@City nvarchar(255) ,@State nvarchar(255) ,@Country nvarchar(255) ) RETURNS nvarchar(1000) AS BEGIN DECLARE @address nvarchar(1000) = STUFF( (SELECT (CHAR(10) + [t]) as [text()] FROM (SELECT * FROM (VALUES(@AddressString), (@AddressString2), (@AddressString3), (LTRIM(RTRIM(ISNULL(@postal, '') + ' ' + ISNULL(@city, '')))), (@state), (@country)) z ([t]) WHERE ISNULL([t], '') <> '')y FOR XML PATH , TYPE).value('.[1]','nvarchar(1000)') , 1, 1, ''); RETURN @address; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_combineAddress] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_creanupTransactionInfo] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_creanupTransactionInfo] ( @info varchar(255) ) RETURNS varchar(255) AS BEGIN DECLARE @RET varchar(255); SET @RET = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@info, 'R ', 'R'), 'Rg', 'R'), '2 0', '20'), CHAR(10),''), CHAR(13), ''), '/', ' ') RETURN ISNULL(@RET, ''); END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_creanupTransactionInfo] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_DocumentName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_DocumentName] ( @InvoiceId varchar(10) , @InvoiceType char(1) , @InvoiceTitle varchar(100) , @DateFinalized datetime ) RETURNS varchar(50) AS BEGIN DECLARE @doc varchar(50); SET @doc = CASE WHEN @DateFinalized is null THEN '' WHEN ISNULL(@InvoiceTitle,'') <> '' THEN @InvoiceTitle + ' ' + @InvoiceId WHEN @InvoiceType = 'a' THEN 'Abschlagsrechnung ' + @InvoiceId WHEN @InvoiceType = 'c' THEN 'Stornorechnung ' + @InvoiceId WHEN @InvoiceType = 'f' THEN 'Schlussrechnung ' + @InvoiceId ELSE 'Rechnung ' + @InvoiceId END; RETURN @doc + '.pdf'; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_DocumentName] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_IntermediateIsAllocatedToOther] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_IntermediateIsAllocatedToOther] ( @Intermediate_InvID varchar(10) ,@Target_InvID varchar(10) ) RETURNS bit AS BEGIN DECLARE @IsA bit = CASE WHEN EXISTS (SELECT * FROM [dbo].[fds__invoices] as intermediates JOIN [dbo].[fds__invoice_details] as id on intermediates.[Id] = id.[InvId] and id.[AllocatedTo_InvId] is not null JOIN [dbo].[fds__invoices] as non_intermediates ON id.[AllocatedTo_InvId] = non_intermediates.[Id] and id.[AllocatedTo_InvId] is not null WHERE intermediates.[Id] = @Intermediate_InvID and (@Target_InvID is null or non_intermediates.[Id] <> @Target_InvID)) THEN 1 ELSE 0 END; RETURN @isA; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_IntermediateIsAllocatedToOther] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_invoice_customerid] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_invoice_customerid] ( @InvId varchar(15) ) RETURNS bigint AS BEGIN DECLARE @ret bigint; SELECT TOP(1) @ret = [customerid] FROM dbo.[fds__invoices] WHERE [id] = @InvId; RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_invoice_customerid] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_invoice_id] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[fds__fn_invoice_id] ( ) RETURNS varchar(8) AS BEGIN DECLARE @NewAccount varchar(5) = [dbo].[ocms_fn_generatePassword] (8,0,1,0); WHILE EXISTS( SELECT * FROM [dbo].[fds__invoices] WHERE [id] = @NewAccount) BEGIN SET @NewAccount = [dbo].[ocms_fn_generatePassword] (8,0,1,0); END RETURN @NewAccount; END; GO ALTER AUTHORIZATION ON [dbo].[fds__fn_invoice_id] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_InvoiceIdByName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_InvoiceIdByName] ( @nme varchar(255) ) RETURNS varchar(20) AS BEGIN DECLARE @Id varchar(20); SET @nme = TRIM((SELECT TOP(1) [value] FROM string_split(@nme, '('))); SET @Id = ISNULL((SELECT TOP(1) [Id] FROM [dbo].[fds__invoices] WHERE [InvoiceId] = @nme),''); RETURN @id; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_InvoiceIdByName] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_InvoiceIDs_mfr] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_InvoiceIDs_mfr] ( @invoiceid varchar(255), @other varchar(1000) ) RETURNS varchar(1000) AS BEGIN DECLARE @RET varchar(1000) = REPLACE(LTRIM(ISNULL(@invoiceid,'')),'Preview',''); IF @RET <> '' SET @RET = TRIM(REPLACE(@RET, ' ', ' ')); IF @RET <> '' SET @RET = REPLACE(@RET, ' ',' (mfr)' + CHAR(10)) + ' (mfr)'; IF @RET <> '' AND ISNULL(@other, '') <> '' SET @RET = @RET + CHAR(10); SET @RET = @RET + ISNULL(@other, ''); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_InvoiceIDs_mfr] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_InvoicePaymentAmount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_InvoicePaymentAmount] ( @InvID varchar(15) ) RETURNS numeric(9,2) AS BEGIN DECLARE @RES numeric(9,2); DECLARE @invoice_idlist [dbo].[fds__tt__idlist_vchar]; INSERT INTO @invoice_idlist VALUES(@invid); With bs as ( SELECT * FROM [dbo].[fds__fn_bankingtransactions](null,null, null, null,@invoice_idlist) ), b as ( SELECT [InvID] = @InvID ,[amount] = SUM(ISNULL(bs.[amount], 0.0)) FROM bs WHERE bs.[invid] = @InvID ) SELECT TOP(1) @RES = [amount] FROM b; RETURN ISNULL(@RES, 0.0); END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_InvoicePaymentAmount] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_InvoicePaymentAmount_full] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_InvoicePaymentAmount_full] ( @InvID varchar(15) ) RETURNS numeric(9,2) AS BEGIN DECLARE @RES numeric(9,2); DECLARE @invoice_idlist [dbo].[fds__tt__idlist_vchar]; INSERT INTO @invoice_idlist VALUES(@invid); With bs as ( SELECT * FROM [dbo].[fds__fn_bankingtransactions](null,null, null, null,@invoice_idlist) ), ci as( SELECT [InvId] = d.[StornoTo_InvId], [amount] = ISNULL(i.[InvoiceBalance],0.0) * -1 FROM [dbo].[fds__invoices] as i JOIN [dbo].[fds__invoice_details] as d on i.[Id] = d.[InvId] where d.[StornoTo_InvId] = @InvID AND i.[IsFinal] = 1 ), tp as ( SELECT [InvId], [amount] from bs where [invid] = @InvID union SELECT [InvId], [amount] from ci ), b as ( SELECT [InvID] = @InvID ,[amount] = SUM(ISNULL(tp.[amount], 0.0)) FROM tp WHERE tp.[invid] = @InvID ) SELECT TOP(1) @RES = [amount] FROM b; RETURN ISNULL(@RES, 0.0); END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_InvoicePaymentAmount_full] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_isInvoiceCancelled] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_isInvoiceCancelled] ( @InvId varchar(20) ) RETURNS bit AS BEGIN DECLARE @res bit; --SET @res = CASE WHEN EXISTS (SELECT 0 FROM [dbo].[fds__invoices] as i2 JOIN [dbo].[fds__invoice_details] as id2 ON i2.[id] = id2.[InvId] where id2.[StornoTo_InvId] = @invId AND i2.[IsFinal] = 1 ) THEN 1 ELSE 0 END; with storno as( SELECT [amount] = SUM(ISNULL(ORIG.[invoicebalance],0.0)), [stornoamount] = SUM(ISNULL(i2.[invoicebalance],0.0) * -1.0) FROM [dbo].[fds__invoices] as ORIG LEFT JOIN [dbo].[fds__invoice_details] as id2 ON id2.StornoTo_InvId = ORIG.[id] and id2.StornoTo_InvId = @invId LEFT JOIN [dbo].[fds__invoices] as i2 on i2.[id] = id2.[InvId] AND i2.[IsFinal] = 1 WHERE ORIG.[Id] = @invId ) SELECT @res = CASE WHEN [amount] = [stornoamount] THEN 1 ELSE 0 END from storno; RETURN cast(ISNULL(@res,0) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_isInvoiceCancelled] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_reminder_id] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[fds__fn_reminder_id] ( ) RETURNS varchar(8) AS BEGIN DECLARE @NewAccount varchar(5) = [dbo].[ocms_fn_generatePassword] (8,0,1,0); WHILE EXISTS( SELECT * FROM [dbo].[fds__reminder] WHERE [id] = @NewAccount) BEGIN SET @NewAccount = [dbo].[ocms_fn_generatePassword] (8,0,1,0); END RETURN @NewAccount; END; GO ALTER AUTHORIZATION ON [dbo].[fds__fn_reminder_id] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_ReminderDocumentName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_ReminderDocumentName] ( @ReminderType char(1) , @ReminderTitle varchar(100) , @DateFinalized datetime , @InvoiceId varchar(10) ) RETURNS varchar(50) AS BEGIN DECLARE @doc varchar(50); SET @doc = CASE WHEN @DateFinalized is null THEN '' WHEN ISNULL(@ReminderTitle,'') <> '' THEN @ReminderTitle WHEN @ReminderType = 'f' THEN 'Zahlungserinnerung ' + @InvoiceId WHEN @ReminderType = 'c' THEN 'Mahnung ' + @InvoiceId WHEN @ReminderType = 'f' THEN 'Mahnung ' + @InvoiceId ELSE 'Zahlungserinnerung ' + @InvoiceId END; RETURN @doc + '.pdf'; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_ReminderDocumentName] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_vatfrombalances] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_vatfrombalances] ( @brutto numeric(10,3) ,@netto numeric(10,3) ) RETURNS numeric(5,2) AS BEGIN DECLARE @vat numeric(5,2) = CASE WHEN ISNULL(@netto, 0) > 0 and ISNULL(@brutto, 0) > 0 THEN ROUND(( (@brutto / @netto) -1) * 100, 2) ELSE NULL END RETURN @vat; END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_vatfrombalances] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getCompanyAddress] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getCompanyAddress] ( @companyid bigint ) RETURNS nvarchar(1000) AS BEGIN DECLARE @locationid bigint, @address nvarchar(1000); SELECT TOP(1) @locationid = cy.[Location#ID] from [dbo].[mfr__companies] as cy WHERE cy.id = @companyid; IF @locationid is null SELECT TOP(1) @locationid = l.[ID], @address = [dbo].[fds__fn_combineAddress] (l.[AddressString], null, null ,l.[Postal] ,l.[City] ,l.[State] ,l.[Country]) FROM [mfr__#locations] as l JOIN [dbo].[mfr__companies] as cy on l.[Property] = 'Company:Location' AND l.[EntityId] = cy.[Id] WHERE cy.[id] = @companyid; -- Return the result of the function IF @address is null SELECT TOP(1) @address = [dbo].[fds__fn_combineAddress] (loc.[AddressString], null, null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM [dbo].[mfr__#locations] as loc WHERE [id] = @locationid; RETURN @address; END GO ALTER AUTHORIZATION ON [dbo].[fds__getCompanyAddress] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getCompanyEmail] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getCompanyEmail] ( @companyid bigint ) RETURNS varchar(255) AS BEGIN DECLARE @email varchar(255) = (SELECT [supportmail] FROM [dbo].[mfr__companies] as cy WHERE cy.[id] = @companyid); RETURN @email; END GO ALTER AUTHORIZATION ON [dbo].[fds__getCompanyEmail] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getCompanyName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getCompanyName] ( @companyid bigint ) RETURNS nvarchar(1000) AS BEGIN DECLARE @name nvarchar(255); SELECT TOP(1) @name = cy.[name] FROM [dbo].[mfr__companies] as cy WHERE cy.id = @companyid; RETURN @name; END GO ALTER AUTHORIZATION ON [dbo].[fds__getCompanyName] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getCompanyNameAddress] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getCompanyNameAddress] ( @companyid bigint ) RETURNS nvarchar(1000) AS BEGIN DECLARE @locationid bigint, @address nvarchar(1000), @name nvarchar(255); SELECT TOP(1) @locationid = cy.[Location#ID], @name = cy.[name] FROM [dbo].[mfr__companies] as cy WHERE cy.id = @companyid; IF @locationid is null SELECT TOP(1) @locationid = l.[ID], @address = [dbo].[fds__fn_combineAddress] (l.[AddressString], null, null ,l.[Postal] ,l.[City] ,l.[State] ,l.[Country]) FROM [mfr__#locations] as l JOIN [dbo].[mfr__companies] as cy on l.[Property] = 'Company:Location' AND l.[EntityId] = cy.[Id] WHERE cy.[id] = @companyid; -- Return the result of the function IF @address is null SELECT TOP(1) @address = [dbo].[fds__fn_combineAddress] (loc.[AddressString], null, null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM [dbo].[mfr__#locations] as loc WHERE [id] = @locationid; RETURN @name + CHAR(10) + @address; END GO ALTER AUTHORIZATION ON [dbo].[fds__getCompanyNameAddress] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getUpdateableRequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getUpdateableRequests] ( ) RETURNS @RET TABLE ( [entity_name] varchar(255) ,[Id] bigint ,[order] bigint ) AS BEGIN DECLARE @threshold_minutes_full int = 60, @threshold_minutes_short int = 8; DECLARE @utcnow datetime = GETUTCDATE(); DECLARE @UTCTimeInMinutes int = DATEDIFF(MINUTE, CAST(CAST(@utcnow as date) as datetime), @utcnow); DECLARe @AS XML = [dbo].[mfr__schema](); DECLARE @EntityTypes TABLE([#] int, [typ] varchar(50), [name] varchar(255), [set] varchar(255), [EntitySet] varchar(255), [tablename] varchar(255), [url] varchar(500), [DateColumn] varchar(25)); WITH XMLNAMESPACES ( 'http://schemas.microsoft.com/ado/2007/06/edmx' as edmx, 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' as m ), et as ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('local-name(.)', 'varchar(50)') as [type] , xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' , xS.value('@Name', 'varchar(255)') as [Set] , o.[name] as [tablename] from @as.nodes('/Schema[1]/EntityType') as xm(xD) JOIN @as.nodes('/Schema/EntityContainer/EntitySet') as xn(xS) ON (xS.value('@EntityType', 'varchar(255)')) like ('MFR.%[.]' + (xD.value('@Name', 'varchar(255)'))) JOIN sys.objects as o ON o.[name] like ('mfr__' + (LOWER(xS.value('@Name', 'varchar(255)')))) union SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('local-name(.)', 'varchar(50)') as [type] , xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' , '' as [Set] , o.[name] as [tablename] from @as.nodes('/Schema[1]/ComplexType') as xm(xD) JOIN sys.objects as o ON o.[name] like ('mfr__[#]' + (LOWER(xD.value('@Name', 'varchar(255)'))) + 's') ) INSERT INTO @EntityTypes SELECT [#],[type],[EntityType],[set] = LOWER([set]), [EntitySet] = [set], [tablename], null, null FROM et; WITH tbl as( SELECT --QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.[name]) AS [TABLE_NAME] sOBJ.[name] AS [TABLE_NAME] , SUM(sPTN.Rows) AS [RowCount] ,sOBJ.[create_date] FROM sys.objects AS sOBJ INNER JOIN sys.partitions AS sPTN ON sOBJ.object_id = sPTN.object_id AND sOBJ.[name] like 'mfr__%' WHERE sOBJ.[type] = 'U' AND sOBJ.is_ms_shipped = 0x0 AND index_id < 2 -- 0:Heap, 1:Clustered GROUP BY sOBJ.schema_id , sOBJ.name , sObj.[create_date] ), pro as (SELECT * FROM sys.procedures WHERE LEFT([name], 11) = 'mfr__updt__') , lu as (SELECT [table], MAX([timestamp]) as 'lu' FROM [dbo].[fds__status] WHERE [action] like 'update%' group by [table]) , luf as (SELECT [table], MAX([timestamp]) as 'luf' FROM [dbo].[fds__status] WHERE [action] like 'update_full' group by [table]) , lur as (SELECT [table], MAX([timestamp]) as 'lur' FROM [dbo].[fds__status] WHERE [action] like 'update_reset' group by [table]) , luc as (SELECT lu.[table], [lu], [luf], [lur] , DATEDIFF(MINUTE, [lu], @utcnow) as [dlu] , DATEDIFF(MINUTE, [lur], @utcnow) as [dlr] , DATEDIFF(MINUTE, [luf], @utcnow) as [dluf] , CASE --WHEN [dbo].[ctm__getUpdateLockStatus] () = Cast(1 as bit) THEN 0 WHEN [lu] is null then 5 --WHEN DATEDIFF(MINUTE, [lu], @utcnow) > @threshold_minutes_full -- OR DATEDIFF(MINUTE, [luf], @utcnow) > @threshold_minutes_full -- THEN 2 WHEN DATEDIFF(MINUTE, [lu], @utcnow) > @threshold_minutes_short THEN 1 ELSE 0 END as 'need' from lu LEFT JOIN luf on lu.[table] = luf.[table] LEFT JOIN lur on lu.[table] = lur.[table] ), cols as (SELECT DISTINCT [TABLE_NAME] FROM INFORMATION_SCHEMA.COLUMNS WHERE LEFT(TABLE_NAME, 5) = N'mfr__' AND ([column_name] COLLATE Latin1_General_CI_AS in ('DateModified', 'DateCreated', 'DateOfCreation'))) , updateabletables as ( SELECT DISTINCT [entity_name] = et.[name] , 'table_name' = tbl.[table_name] , 'temp_table' = pro.[name] , 'locked' = 0 --ISNULL([dbo].[ctm__getUpdateLockStatus_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')), 0) , 'locked_reset' = 0 --ISNULL([dbo].[ctm__getUpdateLockStatus_reset_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')), 0) , 'updateneed' = CASE --WHEN [dbo].[ctm__getUpdateLockStatus_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')) = Cast(1 as bit) THEN 0 WHEN et.[name] COLLATE Latin1_General_CI_AS IN ('Attachment','Comment','Item','StepListTemplateInstance','Step') THEN 0 WHEN tbl.[RowCount] = 0 THEN 5 WHEN NOT EXISTS (SELECT * FROM cols WHERE tbl.[TABLE_NAME] = cols.[TABLE_NAME]) THEN 0 WHEN luc.need is null then 5 WHEN tbl.[TABLE_NAME] COLLATE Latin1_General_CI_AS in ('') AND ISNULL(luc.[dlr], 1440) >= 720 AND @UTCTimeInMinutes BETWEEN 45 AND 90 THEN 5 -- once every day, between 02:45 and 03:30 in the morning ELSE luc.[need]--ISNULL(luc.[need], 0) END , 'datebased' = CASE WHEN EXISTS (SELECT * FROM cols WHERE tbl.[TABLE_NAME] = cols.[TABLE_NAME]) THEN 1 ELSE 0 END FROM tbl JOIN @EntityTypes as et on tbl.[TABLE_NAME] = et.[tablename] JOIN pro on REPLACE(pro.[name], 'mfr__updt__', 'mfr__') = tbl.[TABLE_NAME] LEFT JOIN luc on tbl.[table_name] = luc.[table] ) insert into @RET SELECT rq.[entity_name], rq.[Id], ROW_NUMBER() OVER (ORDER BY [date_requested]) FROM [dbo].[fds__mfr_updaterequests] as rq JOIN updateabletables ON rq.[entity_name] = updateabletables.[entity_name] AND rq.Id is not null ; RETURN END GO ALTER AUTHORIZATION ON [dbo].[fds__getUpdateableRequests] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getUpdateableTables] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getUpdateableTables] ( ) RETURNS @RET TABLE ( [entity_name] varchar(255) ,[table_name] varchar(255) ,[proc_name] varchar(255) ,[locked] bit ,[locked_reset] bit ,[updateneed] tinyint ,[datebased] bit ) AS BEGIN DECLARE @threshold_minutes_full int = 60, @threshold_minutes_short int = 8; DECLARE @utcnow datetime = GETUTCDATE(); DECLARE @UTCTimeInMinutes int = DATEDIFF(MINUTE, CAST(CAST(@utcnow as date) as datetime), @utcnow); DECLARe @AS XML = [dbo].[mfr__schema](); DECLARE @EntityTypes TABLE([#] int, [typ] varchar(50), [name] varchar(255), [set] varchar(255), [EntitySet] varchar(255), [tablename] varchar(255), [url] varchar(500), [DateColumn] varchar(25)); WITH XMLNAMESPACES ( 'http://schemas.microsoft.com/ado/2007/06/edmx' as edmx, 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' as m ), et as ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('local-name(.)', 'varchar(50)') as [type] , xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' , xS.value('@Name', 'varchar(255)') as [Set] , o.[name] as [tablename] from @as.nodes('/Schema[1]/EntityType') as xm(xD) JOIN @as.nodes('/Schema/EntityContainer/EntitySet') as xn(xS) ON (xS.value('@EntityType', 'varchar(255)')) like ('MFR.%[.]' + (xD.value('@Name', 'varchar(255)'))) JOIN sys.objects as o ON o.[name] like ('mfr__' + (LOWER(xS.value('@Name', 'varchar(255)')))) union SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('local-name(.)', 'varchar(50)') as [type] , xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' , '' as [Set] , o.[name] as [tablename] from @as.nodes('/Schema[1]/ComplexType') as xm(xD) JOIN sys.objects as o ON o.[name] like ('mfr__[#]' + (LOWER(xD.value('@Name', 'varchar(255)'))) + 's') ) INSERT INTO @EntityTypes SELECT [#],[type],[EntityType],[set] = LOWER([set]), [EntitySet] = [set], [tablename], null, null FROM et; WITH tbl as( SELECT --QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.[name]) AS [TABLE_NAME] sOBJ.[name] AS [TABLE_NAME] , SUM(sPTN.Rows) AS [RowCount] ,sOBJ.[create_date] FROM sys.objects AS sOBJ INNER JOIN sys.partitions AS sPTN ON sOBJ.object_id = sPTN.object_id AND sOBJ.[name] like 'mfr__%' WHERE sOBJ.[type] = 'U' AND sOBJ.is_ms_shipped = 0x0 AND index_id < 2 -- 0:Heap, 1:Clustered GROUP BY sOBJ.schema_id , sOBJ.name , sObj.[create_date] ), pro as (SELECT * FROM sys.procedures WHERE LEFT([name], 11) = 'mfr__updt__') , lu as (SELECT [table], MAX([timestamp]) as 'lu' FROM [dbo].[fds__status] WHERE [action] like 'update%' group by [table]) , luf as (SELECT [table], MAX([timestamp]) as 'luf' FROM [dbo].[fds__status] WHERE [action] like 'update_full' group by [table]) , lur as (SELECT [table], MAX([timestamp]) as 'lur' FROM [dbo].[fds__status] WHERE [action] like 'update_reset' group by [table]) , luc as (SELECT lu.[table], [lu], [luf], [lur] , DATEDIFF(MINUTE, [lu], @utcnow) as [dlu] , DATEDIFF(MINUTE, [lur], @utcnow) as [dlr] , DATEDIFF(MINUTE, [luf], @utcnow) as [dluf] , CASE --WHEN [dbo].[ctm__getUpdateLockStatus] () = Cast(1 as bit) THEN 0 WHEN [lu] is null then 5 --WHEN DATEDIFF(MINUTE, [lu], @utcnow) > @threshold_minutes_full -- OR DATEDIFF(MINUTE, [luf], @utcnow) > @threshold_minutes_full -- THEN 2 WHEN DATEDIFF(MINUTE, [lu], @utcnow) > @threshold_minutes_short THEN 1 ELSE 0 END as 'need' from lu LEFT JOIN luf on lu.[table] = luf.[table] LEFT JOIN lur on lu.[table] = lur.[table] ), cols as (SELECT DISTINCT [TABLE_NAME] FROM INFORMATION_SCHEMA.COLUMNS WHERE LEFT(TABLE_NAME, 5) = N'mfr__' AND ([column_name] COLLATE Latin1_General_CI_AS in ('DateModified', 'DateCreated', 'DateOfCreation'))) INSERT INTO @RET SELECT DISTINCT [entity_name] = et.[name] , 'table_name' = tbl.[table_name] , 'temp_table' = pro.[name] , 'locked' = 0 --ISNULL([dbo].[ctm__getUpdateLockStatus_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')), 0) , 'locked_reset' = 0 --ISNULL([dbo].[ctm__getUpdateLockStatus_reset_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')), 0) , 'updateneed' = CASE --WHEN [dbo].[ctm__getUpdateLockStatus_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')) = Cast(1 as bit) THEN 0 WHEN et.[name] COLLATE Latin1_General_CI_AS IN ('Attachment','Comment','Item','StepListTemplateInstance','Step') THEN 0 WHEN tbl.[RowCount] = 0 THEN 5 WHEN NOT EXISTS (SELECT * FROM cols WHERE tbl.[TABLE_NAME] = cols.[TABLE_NAME]) THEN 0 WHEN luc.need is null then 5 WHEN tbl.[TABLE_NAME] COLLATE Latin1_General_CI_AS in ('') AND ISNULL(luc.[dlr], 1440) >= 720 AND @UTCTimeInMinutes BETWEEN 45 AND 90 THEN 5 -- once every day, between 02:45 and 03:30 in the morning ELSE luc.[need]--ISNULL(luc.[need], 0) END , 'datebased' = CASE WHEN EXISTS (SELECT * FROM cols WHERE tbl.[TABLE_NAME] = cols.[TABLE_NAME]) THEN 1 ELSE 0 END FROM tbl JOIN @EntityTypes as et on tbl.[TABLE_NAME] = et.[tablename] JOIN pro on REPLACE(pro.[name], 'mfr__updt__', 'mfr__') = tbl.[TABLE_NAME] LEFT JOIN luc on tbl.[table_name] = luc.[table]; RETURN END GO ALTER AUTHORIZATION ON [dbo].[fds__getUpdateableTables] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__newInvoiceId] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__newInvoiceId] ( @year int ) RETURNS varchar(25) AS BEGIN DECLARE @lastid_int bigint; SELECT @lastid_int = MAX( TRY_PARSE(RIGHT([InvoiceId], 4) as integer) ) FROM [dbo].[fds__invoices] WHERE LEFT(ISNULL([InvoiceId],''),5) = ('R' + CAST(@year as varchar(4))); DECLARE @invoice_id varchar(25) = 'R' + CAST(@year as varchar(4)) + '-' + FORMAT(ISNULL( @lastid_int , CASE WHEN @year = 2021 THEN 1593 ELSE 0 END) + 1, '0000'); RETURN @invoice_id; END GO ALTER AUTHORIZATION ON [dbo].[fds__newInvoiceId] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__r_getBalanceThisMonth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__r_getBalanceThisMonth]( @authuser varchar(100) ) RETURNS varchar(25) BEGIN DECLARE @today date = GETDATE(); DECLARE @tomorrow date = DATEADD(DAY,1,@today); DECLARE @thismonthfirst date = [dbo].[date_monthfirst](@today); DECLARE @ret varchar(25) = '' IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 SET @ret = ''; ELSE BEGIN WITH inv as ( SELECT [Dateofcreation] = i.[DateFinalized] ,i.[InvoiceBalance] ,[InvoiceBalanceNetto] = i.[InvoiceBalance_net] FROM [dbo].[fds__invoices] as i WHERE i.[isFinal] = 1 AND [dbo].[date_monthfirst](i.[DateFinalized]) = @thismonthfirst ) SELECT TOP(1) @ret = FORMAT( SUM( ISNULL(inv.[InvoiceBalanceNetto],0) ) * 0.001, '#,0 k€', 'de') FROM inv; END RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[fds__r_getBalanceThisMonth] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__updateNeed] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[fds__updateNeed] ( @threshold_minutes_full int ,@threshold_minutes_short int ) RETURNS tinyint AS BEGIN --[Reset] = 5 -- [Full] = 2 -- [Short] = 1 -- [None] = 0 SET @threshold_minutes_full = 60; SET @threshold_minutes_short = 8; DECLARE @RET tinyint = 1 DECLARE @UpDate datetime DECLARE @UpDateFull datetime RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[fds__updateNeed] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_authenticate] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_authenticate] ( @email varchar(255), @password nvarchar(20) ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(100) null, [firstname] nvarchar(100) null, [email] varchar(255) NULL, [mobile] varchar(50) null, [functions] varchar(1000), [language] varchar(2), [fullname] nvarchar(255) null, [fullname_rev] nvarchar(255) null) AS BEGIN DECLARE @auth smallint = -1; DECLARE @useraccount_id varchar(10), @name nvarchar(255), @mobile varchar(50), @functions varchar(1000) = ''; SELECT TOP(1) @useraccount_id = [useraccount_id] FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null AND CAST(DECRYPTBYKEY(ua.[email_enc]) as varchar(255)) = @email AND @email <> '' AND CAST(DECRYPTBYKEY(ua.[password_enc]) as nvarchar(20)) = @password AND @password <> '' AND ua.[password_enc] is not null; INSERT INTO @RET SELECT * FROM [dbo].[fis_admin_getUserAccount](@useraccount_id); RETURN; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_authenticate] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_authenticate_byID] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_authenticate_byID] ( @useraccount_id varchar(10), @password nvarchar(20) ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(100) null, [firstname] nvarchar(100) null, [email] varchar(255) NULL, [mobile] varchar(50) null, [functions] varchar(1000), [language] varchar(2), [fullname] nvarchar(255) null, [fullname_rev] nvarchar(255) null) AS BEGIN DECLARE @auth smallint = -1; DECLARE @name nvarchar(255), @mobile varchar(50), @functions varchar(1000) = ''; IF EXISTS( SELECT 0 FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null AND [useraccount_id] = @useraccount_id and ISNULL(@useraccount_id, '') <> '' AND CAST(DECRYPTBYKEY(ua.[password_enc]) as nvarchar(20)) = @password AND @password <> '' AND ua.[password_enc] is not null ) BEGIN INSERT INTO @RET SELECT * FROM [dbo].[fis_admin_getUserAccount](@useraccount_id); END RETURN; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_authenticate_byID] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_checkUserExists] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_checkUserExists] ( @useraccount_id varchar(5) ) RETURNS bit AS BEGIN DECLARE @RET bit; SET @RET = IIF(EXISTS (SELECT * FROM [dbo].[fis_useraccounts] as ua WHERE [useraccount_id] = @useraccount_id AND ua.[DateDeleted] is null AND ua.[DateDisabled] is null), 1, 0); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_checkUserExists] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserAccount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserAccount] ( @useraccount_id varchar(5) ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(100) null, [firstname] nvarchar(100) null, [email] varchar(255) NULL, [mobile] varchar(50) null, [functions] varchar(1000), [language] varchar(2), [fullname] nvarchar(255) null, [fullname_rev] nvarchar(255) null) AS BEGIN DECLARE @auth smallint = -1; DECLARE @email varchar(255), @name nvarchar(100), @firstname nvarchar(100), @mobile varchar(50), @functions varchar(1000) = '', @title varchar(50), @gender varchar(1), @password varchar(5), @language varchar(2), @fullname nvarchar(255), @fullname_rev nvarchar(255); SELECT TOP(1) @useraccount_id = [useraccount_id] ,@auth = CASE WHEN [useraccount_id] is null THEN -1 ELSE 1 END ,@name = CAST(DECRYPTBYKEY(ua.[name_enc]) as nvarchar(100)) ,@firstname = CAST(DECRYPTBYKEY(ua.[firstname_enc]) as nvarchar(100)) ,@title = CAST(DECRYPTBYKEY(ua.[title_enc]) as varchar(50)) ,@gender = CAST(DECRYPTBYKEY(ua.[gender_enc]) as varchar(1)) --,@password = DECRYPTBYKEY(ua.[password_enc]) ,@email = CAST(DECRYPTBYKEY(ua.[email_enc]) as varchar(255)) ,@mobile = CAST(DECRYPTBYKEY(ua.[mobile_enc]) as varchar(50)) ,@language = ua.[language] ,@fullname = [dbo].[fis_admin_getUserName](ua.[name_enc], ua.[firstname_enc], ua.[title_enc]) ,@fullname_rev = [dbo].[fis_admin_getUserName_rev](ua.[name_enc], ua.[firstname_enc], ua.[title_enc]) FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null AND ua.[useraccount_id] = @useraccount_id; SET @auth = ISNULL(TRY_CAST((SELECT TOP(1) [value] FROM [fis_useraccounts_settings] WHERE [useraccount_id] = @useraccount_id and [key] = 'intranet_admin') as smallint), @auth); SET @functions = STUFF( (SELECT ',' + [value] as [text()] FROM [fis_useraccounts_settings] WHERE [useraccount_id] = @useraccount_id and [key] = 'intranet_function' FOR XML PATH(''), TYPE).value('.','nvarchar(max)') , 1,1,''); INSERT INTO @RET VALUES( @useraccount_id ,IIF(@useraccount_id is null, -1, @auth) ,IIF(@useraccount_id is null, null, @name) ,IIF(@useraccount_id is null, null, @firstname) ,IIF(@useraccount_id is null, null, @email) ,IIF(@useraccount_id is null, null, @mobile) ,IIF(@useraccount_id is null, null, @functions) ,IIF(@useraccount_id is null, null, @language) ,IIF(@useraccount_id is null, null, @fullname) ,IIF(@useraccount_id is null, null, @fullname_rev) ); RETURN; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserAccount] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserAccount_byemail] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserAccount_byemail] ( @email varchar(255) ,@include_password bit = 0 ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(100) null, [firstname] nvarchar(100) null, [title] varchar(50) null, [gender] varchar(1) NULL, [email] varchar(255) NULL, [mobile] varchar(50) null, [password] nvarchar(25) null, [functions] varchar(1000), [language] varchar(2) , [fullname] nvarchar(255) null, [fullname_rev] nvarchar(255) null ) AS BEGIN DECLARE @auth smallint = -1; DECLARE @useraccount_id varchar(5), @name nvarchar(100), @firstname nvarchar(100), @mobile varchar(50), @functions varchar(1000) = '', @title varchar(50), @gender varchar(1), @password varchar(25), @language varchar(2), @fullname nvarchar(255), @fullname_rev nvarchar(255); SELECT TOP(1) @useraccount_id = [useraccount_id] ,@auth = CASE WHEN [useraccount_id] is null THEN -1 ELSE 1 END ,@name = CAST(DECRYPTBYKEY(ua.[name_enc]) as nvarchar(100)) ,@firstname = CAST(DECRYPTBYKEY(ua.[firstname_enc]) as nvarchar(100)) ,@title = CAST(DECRYPTBYKEY(ua.[title_enc]) as varchar(50)) ,@gender = CAST(DECRYPTBYKEY(ua.[gender_enc]) as varchar(1)) ,@password = IIF(ISNULL(@include_password,0) = 1, CAST(DECRYPTBYKEY(ua.[password_enc]) as nvarchar(25)) , null) ,@email = CAST(DECRYPTBYKEY(ua.[email_enc]) as varchar(255)) ,@mobile = CAST(DECRYPTBYKEY(ua.[mobile_enc]) as varchar(50)) ,@language = ua.[language] ,@fullname = [dbo].[fis_admin_getUserName](ua.[name_enc], ua.[firstname_enc], ua.[title_enc]) ,@fullname_rev = [dbo].[fis_admin_getUserName_rev](ua.[name_enc], ua.[firstname_enc], ua.[title_enc]) FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null AND LOWER(RTRIM(CAST(DECRYPTBYKEY(ua.[email_enc]) as varchar(255)))) = LOWER(RTRIM(@email)); SET @auth = ISNULL(TRY_CAST((SELECT TOP(1) [value] FROM [fis_useraccounts_settings] WHERE [useraccount_id] = @useraccount_id and [key] = 'intranet_admin') as smallint), @auth); SET @functions = STUFF( (SELECT ',' + [value] as [text()] FROM [fis_useraccounts_settings] WHERE [useraccount_id] = @useraccount_id and [key] = 'intranet_function' FOR XML PATH(''), TYPE).value('.','nvarchar(max)') , 1,1,''); INSERT INTO @RET VALUES( @useraccount_id ,IIF(@useraccount_id is null, -1, @auth) ,IIF(@useraccount_id is null, null, @name) ,IIF(@useraccount_id is null, null, @firstname) ,IIF(@useraccount_id is null, null, @title) ,IIF(@useraccount_id is null, null, @gender) ,IIF(@useraccount_id is null, null, @email) ,IIF(@useraccount_id is null, null, @mobile) ,IIF(@useraccount_id is null, null, @password) ,IIF(@useraccount_id is null, null, @functions) ,IIF(@useraccount_id is null, null, @language) ,IIF(@useraccount_id is null, null, @fullname) ,IIF(@useraccount_id is null, null, @fullname_rev) ); RETURN; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserAccount_byemail] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserAccount_Namelist] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserAccount_Namelist] ( @authaccount varchar(5) ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [name] nvarchar(100) null, [firstname] nvarchar(100) null, [order] int) AS BEGIN DECLARE @auth smallint = [dbo].[fis_admin_getUserAuth](@authaccount); IF @auth > 1 BEGIN INSERT INTO @RET SELECT ua.[useraccount_id] ,CAST(DECRYPTBYKEY(ua.[name_enc]) as nvarchar(100)) ,CAST(DECRYPTBYKEY(ua.[firstname_enc]) as nvarchar(100)) ,'order' = ROW_NUMBER() OVER (ORDER BY CAST(DECRYPTBYKEY(ua.[name_enc]) as nvarchar(255))) FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null; END RETURN; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserAccount_Namelist] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserAccountList] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserAccountList] ( @authaccount varchar(5) , @useraccount_id varchar(5) , @usergroup_id varchar(5) , @include_nonmembers as bit ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(100) null, [firstname] nvarchar(100) null, [title] varchar(50) NULL, [gender] varchar(1), [email] varchar(255) NULL, [mobile] varchar(50) null, [functions] varchar(1000), [language] varchar(2), [disabled] bit, [nologin] bit, [member] bit, [order] int) AS BEGIN DECLARE @auth smallint = [dbo].[fis_admin_getUserAuth](@authaccount); IF @auth > 1 OR (ISNULL(@useraccount_id, '') <>'' AND @useraccount_id = @authaccount) BEGIN DECLARE @ungrouped bit = CASE WHEN @usergroup_id is null THEN 1 ELSE 0 END; /* if no usergroup is selected => ungrouped */ IF @ungrouped = 1 OR EXISTS(SELECT * FROM [dbo].[fis_usergroups] as ug where ug.[usergroup_id] = @usergroup_id AND ug.[DateDeleted] is null) /* Validate selected group, alternatively do not even look for accounts */ BEGIN WITH SelectedGroupMembers as ( SELECT ug.[usergroup_id], ugm.[useraccount_id] FROM [dbo].[fis_usergroups_members] as ugm JOIN [dbo].[fis_usergroups] as ug ON ugm.[usergroup_id] = ug.[usergroup_id] WHERE ug.[DateDeleted] is null AND ugm.[DateDeleted] is null AND ug.[usergroup_id] = @usergroup_id ) INSERT INTO @RET SELECT ua.[useraccount_id] ,'auth' = ISNULL(TRY_CAST((SELECT TOP(1) [value] FROM [fis_useraccounts_settings] as s WHERE s.[useraccount_id] = ua.[useraccount_id] and s.[key] = 'intranet_admin') as smallint), CASE WHEN ua.[useraccount_id] is null THEN -1 WHEN [DateDisabled] is not null THEN 0 ELSE 1 END ) ,CAST(DECRYPTBYKEY(ua.[name_enc]) as nvarchar(100)) ,CAST(DECRYPTBYKEY(ua.[firstname_enc]) as nvarchar(100)) ,CAST(DECRYPTBYKEY(ua.[title_enc]) as varchar(50)) ,CAST(DECRYPTBYKEY(ua.[gender_enc]) as varchar(1)) ,CAST(DECRYPTBYKEY(ua.[email_enc]) as varchar(255)) ,CAST(DECRYPTBYKEY(ua.[mobile_enc]) as varchar(50)) ,'functions' = STUFF( (SELECT ',' + [value] as [text()] FROM [fis_useraccounts_settings] as s WHERE s.[useraccount_id] = ua.[useraccount_id] and s.[key] = 'intranet_function' FOR XML PATH(''), TYPE).value('.','nvarchar(max)') , 1,1,'') ,ua.[language] ,'disabled' = CASE WHEN ua.[DateDisabled] IS NULL THEN 0 ELSE 1 END ,'nologin' = CAST(CASE WHEN ua.[password_enc] is null THEN 1 WHEN ISNULL(CAST(DECRYPTBYKEY(ua.[password_enc]) as varchar(20)),'') = '' THEN 1 ELSE 0 END as bit) ,'member' = CASE WHEN @usergroup_id IS NULL THEN NULL WHEN sgm.[useraccount_id] is not null THEN 1 ELSE 0 END ,'order' = ROW_NUMBER() OVER (ORDER BY CAST(DECRYPTBYKEY(ua.[name_enc]) as nvarchar(255))) FROM [dbo].[fis_useraccounts] as ua LEFT JOIN SelectedGroupMembers as sgm on sgm.[useraccount_id] = ua.[useraccount_id] WHERE ua.[DateDeleted] is null /*never return deleted useraccounts */ AND (@useraccount_id is null OR (ua.[useraccount_id] = @useraccount_id)) /* if single useraccount is selected, return only this selected one */ AND (@ungrouped = 1 -- is no useraccount is selected OR ISNULL(@include_nonmembers,0) = 1 -- or if useraccount is selected, but non-members should be included also OR sgm.[useraccount_id] is not null) -- or if accounts are valid members END END RETURN; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserAccountList] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserAddressForm] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserAddressForm] ( @name_enc varbinary(260) ,@title_enc varbinary(50) ,@gender_enc varbinary(100) ,@language varchar(2) ) RETURNS nvarchar(255) AS BEGIN DECLARE @Username nvarchar(255); DECLARE @l varchar(2) = LOWER(ISNULL(@language, 'de')); DECLARE @g varchar(1) = LOWER(ISNULL(CAST(DECRYPTBYKEY(@gender_enc) as varchar(1)), 'm')); SET @Username = CAST( CASE WHEN @l = 'de' THEN 'Sehr geehrte' + CASE WHEN @g = 'm' THEN 'r Herr ' ELSE ' Frau ' END ELSE 'Dear ' + CASE WHEN @g = 'm' THEN 'Mr ' ELSE ' Ms ' END END + ISNULL(CASE WHEN @title_enc is null THEN '' ELSE CAST(DECRYPTBYKEY(@title_enc) as varchar(50)) + ' ' END,'') + ISNULL(CASE WHEN @name_enc is null THEN '' ELSE CAST(DECRYPTBYKEY(@name_enc ) as nvarchar(100)) END, '') as nvarchar(255) ); RETURN @username; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserAddressForm] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserAuth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserAuth] ( @useraccount_id varchar(5) ) RETURNS smallint AS BEGIN DECLARE @auth smallint = -1; SET @auth = ISNULL((SELECT TOP(1) ISNULL(TRY_CAST((SELECT TOP(1) [value] FROM [fis_useraccounts_settings] as s WHERE s.[useraccount_id] = ua.[useraccount_id] and s.[key] = 'intranet_admin') as smallint), CASE WHEN [useraccount_id] is null THEN -1 WHEN [DateDisabled] is not null THEN 0 ELSE 1 END ) FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[useraccount_id] = @useraccount_id), -1); RETURN @auth; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserAuth] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserEmail_byID] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserEmail_byID] ( @useraccount_id varchar(5) ) RETURNS nvarchar(255) AS BEGIN DECLARE @UserEmail varchar(255); SELECT TOP(1) @UserEmail = ISNULL(CASE WHEN [email_enc] is null THEN '' ELSE CAST(DECRYPTBYKEY([email_enc] ) as varchar(255)) END, '') FROM [dbo].[fis_useraccounts] as ua WHERE [useraccount_id] = @useraccount_id AND [DateDeleted] is null; RETURN @userEmail; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserEmail_byID] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserGroupList] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserGroupList] ( @authaccount varchar(5) , @usergroup_id varchar(5) ) RETURNS @RET TABLE ( [usergroup_id] varchar(5), [name] nvarchar(255) null, [order] int) AS BEGIN DECLARE @auth smallint = [dbo].[fis_admin_getUserAuth](@authaccount); IF @auth > 1 BEGIN INSERT INTO @RET SELECT [usergroup_id] ,CAST(DECRYPTBYKEY(ug.[name_enc]) as nvarchar(255)) ,'order' = ROW_NUMBER() OVER (ORDER BY CAST(DECRYPTBYKEY(ug.[name_enc]) as nvarchar(255))) FROM [dbo].[fis_usergroups] as ug WHERE ug.[DateDeleted] is null AND (@usergroup_id is null OR ug.[usergroup_id] = @usergroup_id); END RETURN; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserGroupList] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserName] ( @name_enc varbinary(260) ,@firstname_enc varbinary(260) ,@title_enc varbinary(50) ) RETURNS nvarchar(255) AS BEGIN DECLARE @Username nvarchar(255); SET @Username = CAST( ISNULL(CASE WHEN @title_enc is null THEN '' ELSE CAST(DECRYPTBYKEY(@title_enc) as varchar(50)) + ' ' END,'') + ISNULL(CASE WHEN @firstname_enc is null THEN '' ELSE CAST(DECRYPTBYKEY(@firstname_enc) as nvarchar(100)) + ' ' END,'') + ISNULL(CASE WHEN @name_enc is null THEN '' ELSE CAST(DECRYPTBYKEY(@name_enc ) as nvarchar(100)) END, '') as nvarchar(255)) RETURN @username; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserName] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserName_byID] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserName_byID] ( @useraccount_id varchar(5) ) RETURNS nvarchar(255) AS BEGIN DECLARE @Username nvarchar(255); SELECT TOP(1) @Username = [dbo].[fis_admin_getUserName]([name_enc],[firstname_enc],[title_enc]) FROM [dbo].[fis_useraccounts] as ua WHERE [useraccount_id] = @useraccount_id AND [DateDeleted] is null; RETURN @username; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserName_byID] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserName_rev] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserName_rev] ( @name_enc varbinary(260) ,@firstname_enc varbinary(260) ,@title_enc varbinary(50) ) RETURNS nvarchar(255) AS BEGIN DECLARE @Username nvarchar(255); SET @Username = CAST( ISNULL(CASE WHEN @name_enc is null THEN '' ELSE CAST(DECRYPTBYKEY(@name_enc ) as nvarchar(100)) END, '') + N', ' + ISNULL(CASE WHEN @firstname_enc is null THEN '' ELSE CAST(DECRYPTBYKEY(@firstname_enc) as nvarchar(100)) + ' ' END,'') as nvarchar(255)) RETURN @username; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserName_rev] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserName_rev_byID] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserName_rev_byID] ( @useraccount_id varchar(5) ) RETURNS nvarchar(255) AS BEGIN DECLARE @Username nvarchar(255); SELECT TOP(1) @Username = [dbo].[fis_admin_getUserName_rev]([name_enc],[firstname_enc],[title_enc]) FROM [dbo].[fis_useraccounts] as ua WHERE [useraccount_id] = @useraccount_id AND [DateDeleted] is null; RETURN @username; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserName_rev_byID] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_getUserSetting] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_getUserSetting] ( @useraccount_id varchar(5) , @key varchar(25) ) RETURNS varchar(255) AS BEGIN DECLARE @ret varchar(25); SET @ret = ISNULL((SELECT TOP(1) ISNULL((SELECT TOP(1) [value] FROM [fis_useraccounts_settings] as s WHERE s.[useraccount_id] = ua.[useraccount_id] and s.[key] = @key), '') FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[useraccount_id] = @useraccount_id), ''); RETURN ISNULL(@ret,''); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_getUserSetting] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_admin_testGroupMembership] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_admin_testGroupMembership] ( @useraccount_id varchar(5) ,@usergroup_id varchar(1000) ) RETURNS bit AS BEGIN DECLARE @groups TABLE([usergroup_id] varchar(5)); INSERT INTO @groups SELECT * from STRING_SPLIT(@usergroup_id,','); DECLARE @isMember bit = CASE WHEN EXISTS (SELECT * FROM [dbo].[fis_usergroups] as g JOIN @groups as groupstotest On groupstotest.[usergroup_id] = g.[usergroup_id] JOIN [dbo].[fis_usergroups_members] as gm on g.[usergroup_id] = gm.[usergroup_id] and gm.[DateDeleted] is null AND g.[DateDeleted] is null JOIN [dbo].[fis_useraccounts] as u on gm.[useraccount_id] = u.[useraccount_id] WHERE u.[DateDeleted] is null AND u.[DateDisabled] is null and u.[useraccount_id] = @useraccount_id and g.[DateDeleted] is null ) THEN 1 ELSE 0 END; RETURN @isMember; END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_testGroupMembership] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_fn_id] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[fis_fn_id] ( @table varchar(25) ) RETURNS varchar(5) AS BEGIN DECLARE @NewAccount varchar(5) = [dbo].[ocms_fn_generatePassword] (5,0,1,0); SET @table = ISNULL(@table, ''); IF @table = 'fis_usergroups' BEGIN WHILE EXISTS( SELECT * FROM [dbo].[fis_usergroups] WHERE [usergroup_id] = @NewAccount) BEGIN SET @NewAccount = [dbo].[ocms_fn_generatePassword] (5,0,1,0); END END RETURN @NewAccount; END; GO ALTER AUTHORIZATION ON [dbo].[fis_fn_id] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_fn_useraccount_id] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[fis_fn_useraccount_id] ( ) RETURNS varchar(5) AS BEGIN DECLARE @NewAccount varchar(5) = [dbo].[ocms_fn_generatePassword] (5,0,1,0); WHILE EXISTS( SELECT * FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @NewAccount) BEGIN SET @NewAccount = [dbo].[ocms_fn_generatePassword] (5,0,1,0); END RETURN @NewAccount; END; GO ALTER AUTHORIZATION ON [dbo].[fis_fn_useraccount_id] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_getModuleAuth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_getModuleAuth] ( @module varchar(50), @useraccount_id varchar(10) -- length is 5; content would be cut to 5 is variable-length is 5 also ) RETURNS int AS BEGIN DECLARE @RET int, @TMP int, @module_base varchar(50), @module_qualifier varchar(50); SET @module = ISNULL(@module,''); SET @module_base = CASE WHEN CHARINDEX('-', @module) = 0 THEN @module ELSE LEFT(@module, CHARINDEX('-', @module) -1) END; SET @module_qualifier = CASE WHEN CHARINDEX('-', @module) = 0 THEN '' ELSE RIGHT(@module, LEN(@module) - CHARINDEX('-', @module)) END; SET @RET = CASE WHEN @module = '' OR LEFT(@module,1) ='-' -- OR ISNULL(@account, '') IN ('','*')) THEN -3 WHEN @useraccount_id = 'sa' THEN 10 WHEN NOT EXISTS (SELECT 0 FROM [dbo].[fis_useraccounts] as u WHERE u.[useraccount_id] = @useraccount_id and u.[DateDeleted] is null) THEN -2 WHEN EXISTS (SELECT 0 FROM [dbo].[fis_useraccounts] as u WHERE u.[useraccount_id] = @useraccount_id and u.[DateDeleted] is null AND u.[DateDisabled] is not null) THEN -1 WHEN @module <> 'fds-admin' AND NOT EXISTS (SELECT 0 from [dbo].[fis_module_auth] as a WHERE a.[module] = @module) THEN 0 ELSE NULL END; IF @RET is null BEGIN WITH maCTE as ( SELECT * FROM [dbo].[fis_module_auth] as a_ ) SELECT @RET = Max(a.[auth]) FROM maCTE as a WHERE ( ((@module LIKE (a.[module] + '%') OR @module = a.[module]) AND @module <> '') OR a.[module] = 'admin' ) AND ( (a.[isgroup] = 0 AND a.[group_or_user] = @useraccount_id) OR (a.[isgroup] = 1 AND [dbo].[fis_admin_testGroupMembership](@useraccount_id, a.[group_or_user]) = 1) ); END IF @module_qualifier not in ('manage','admin') AND @RET between -1 and 9 AND @RET between -1 and 9 SET @RET = [dbo].[ott_max](@RET, [dbo].[fis_getModuleAuth](@module_base + '-manage', @useraccount_id )); IF @module <> 'fds-admin' AND ISNULL(@RET, -1) between -1 and 9 SET @RET = [dbo].[ott_max](@RET, [dbo].[fis_getModuleAuth]('fds-admin', @useraccount_id )); --SET @RET = CASE WHEN @module = 'fds_inv' and @useraccount_id = 'J5KL8' THEN 1 ELSE @RET END; SET @RET = ISNULL(@RET, -3); RETURN @RET END GO ALTER AUTHORIZATION ON [dbo].[fis_getModuleAuth] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_getONEPersonWidgets] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_getONEPersonWidgets] ( @useraccount_id varchar(10) ) RETURNS @RET TABLE ( [short_name] [varchar](50) NOT NULL, [account] [varchar](50) NOT NULL, [type] [nvarchar](50) NOT NULL, [name] [nvarchar](255) NOT NULL, [description] [nvarchar](1000) NULL, [sql] [nvarchar](2000) NULL, [sql_admin_columns] [nvarchar](500) NULL, [sql_datatypes] [nvarchar](255) NULL, [url] [nvarchar](500) NULL, [html] [nvarchar](max) NULL, [visible_groups] [varchar](1000) NULL, [visible] [tinyint] NOT NULL, [auth_module] [varchar](50) NULL, [rendering_options] [nvarchar](255) NULL, [server_options] [nvarchar](2000) NULL, [daycache] [bit] NOT NULL, [personalized] [bit] NOT NULL, [safemode] [bit] NOT NULL, [variables] [varchar](1000) NULL, [order] int ) AS BEGIN --DECLARE @account varchar(50) = ''; -- kept in function for reuse purposes INSERT INTO @RET SELECT w.* , ROW_NUMBER() OVER (ORDER BY s.[display_order], s.[DateCreated] DESC, w.[name]) as 'order' FROM [dbo].[fis_widgets] as w JOIN [dbo].[fis_widget_subscriptions] as s ON w.[short_name] = s.[widget_name] WHERE --(s.[account] = @account OR s.[account] = '*') (s.[person_guid] = @useraccount_id OR s.[person_guid] = '*') AND (ISNULL(w.[visible],0) = 0 OR ([dbo].[fis_getModuleAuth](ISNULL(w.[auth_module], 'fis_widgets'), @useraccount_id) >= w.[visible])) --UNION -- SELECT * FROM [dbo].[fis_getONEPersonWidgets_ownevents](@account, @person_guid) RETURN END GO ALTER AUTHORIZATION ON [dbo].[fis_getONEPersonWidgets] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[mfr__schema] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[mfr__schema] ( ) RETURNS XML AS BEGIN DECLARe @AS XML; SET @AS = N' '; RETURN @as; END GO ALTER AUTHORIZATION ON [dbo].[mfr__schema] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[mfr_fn_dateSent_fromNotes] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[mfr_fn_dateSent_fromNotes] ( @notes nvarchar(500) ) RETURNS date AS BEGIN DECLARE @DateSent date = TRY_PARSE((SELECT '20'+STRING_AGG(TRIM([string]), '-') WITHIN GROUP(ORDER BY [rowno] DESC) FROM dbo.string_SplitString_ordered((SELECT REPLACE(REPLACE(TRIM([value]), CHAR(10),''), CHAR(13),'') from string_split(@notes,':') where CHARINDEX('@',[value]) = 0 AND [value] like '%[-]__[-]21'),'-') WHERE ISNULL([string],'') <> '') as date) RETURN @DateSent END GO ALTER AUTHORIZATION ON [dbo].[mfr_fn_dateSent_fromNotes] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ne] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ne] ( @value SQL_VARIANT ,@alternative SQL_VARIANT ) RETURNS SQL_VARIANT AS BEGIN DECLARE @ret SQL_VARIANT; IF SQL_VARIANT_PROPERTY(@value, 'BaseType') = 'varchar' BEGIN If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 50 BEGIN DECLARE @v1 varchar(50) = ISNULL(try_cast(@value as varchar(50)), ''); SET @ret = IIF( @v1 <> '', @v1, try_CAST(@alternative as varchar(50))); END ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 255 BEGIN DECLARE @v2 varchar(255) = ISNULL(try_cast(@value as varchar(255)), ''); SET @ret = IIF( @v2 <> '', @v2, try_CAST(@alternative as varchar(255))); END ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 1000 BEGIN DECLARE @v3 varchar(1000) = ISNULL(try_cast(@value as varchar(1000)), ''); SET @ret = IIF( @v2 <> '', @v2, try_CAST(@alternative as varchar(1000))); END ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 4000 BEGIN DECLARE @v4 varchar(4000) = ISNULL(try_cast(@value as varchar(4000)), ''); SET @ret = IIF( @v4 <> '', @v4, try_CAST(@alternative as varchar(4000))); END ELSE BEGIN DECLARE @v5 varchar(8000) = ISNULL(try_cast(@value as varchar(8000)), ''); SET @ret = IIF( @v5 <> '', @v4, try_CAST(@alternative as varchar(8000))); END END ELSE IF SQL_VARIANT_PROPERTY(@value, 'BaseType') = 'nvarchar' BEGIN If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 50 BEGIN DECLARE @nv1 nvarchar(50) = ISNULL(try_cast(@value as nvarchar(50)), ''); SET @ret = IIF(@nv1 <> '', @nv1, try_CAST(@alternative as nvarchar(50))); END ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 255 BEGIN DECLARE @nv2 nvarchar(255) = ISNULL(try_cast(@value as nvarchar(255)), ''); SET @ret = IIF(@nv2 <> '',@nv2, try_CAST(@alternative as nvarchar(255))); END ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 1000 BEGIN DECLARE @nv3 nvarchar(1000) = ISNULL(try_cast(@value as nvarchar(1000)), ''); SET @ret = IIF(@nv2 <> '',@nv2, try_CAST(@alternative as nvarchar(1000))); END ELSE BEGIN DECLARE @nv4 nvarchar(4000) = ISNULL(try_cast(@value as nvarchar(4000)), ''); SET @ret = IIF(@nv4 <> '',@nv4, try_CAST(@alternative as nvarchar(4000))); END END RETURN @ret END GO ALTER AUTHORIZATION ON [dbo].[ne] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[net_val] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[net_val] ( @price numeric(10,3) ,@quantityhours numeric(10,3) ,@discount numeric(10,3) ) RETURNS numeric(7,2) AS BEGIN DECLARE @Ret numeric(7,2) SET @RET = ISNULL(@Price,0) * ISNULL(@quantityhours,1) * (100 - ISNULL(@discount,0)) * 0.01; RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[net_val] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_admin_authenticate] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_admin_authenticate] ( @email varchar(255), @password nvarchar(20) ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(255) null, [email] varchar(255) NULL, [mobile] varchar(50) null) AS BEGIN DECLARE @auth smallint = -1; DECLARE @useraccount_id varchar(10), @name nvarchar(255), @mobile varchar(50); SELECT TOP(1) @useraccount_id = [useraccount_id] ,@name = DECRYPTBYKEY(ua.[name_enc]) ,@email = DECRYPTBYKEY(ua.[email_enc]) ,@mobile = DECRYPTBYKEY(ua.[mobile_enc]) FROM [dbo].[ocms_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null AND DECRYPTBYKEY(ua.[email_enc]) = @email AND DECRYPTBYKEY(ua.[password_enc]) = @password AND ua.[password_enc] is not null; INSERT INTO @RET VALUES( @useraccount_id ,IIF(@useraccount_id is null, -1, 1) ,IIF(@useraccount_id is null, null, @name) ,IIF(@useraccount_id is null, null, @email) ,IIF(@useraccount_id is null, null, @mobile) ); RETURN; END GO ALTER AUTHORIZATION ON [dbo].[ocms_admin_authenticate] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_admin_checkUserExists] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_admin_checkUserExists] ( @useraccount_id varchar(5) ) RETURNS bit AS BEGIN DECLARE @RET bit; SET @RET = IIF(EXISTS (SELECT * FROM [dbo].[ocms_useraccounts] as ua WHERE [useraccount_id] = @useraccount_id AND ua.[DateDeleted] is null AND ua.[DateDisabled] is null), 1, 0); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ocms_admin_checkUserExists] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_admin_getUserAccount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_admin_getUserAccount] ( @useraccount_id varchar(5) ) RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(255) null, [email] varchar(255) NULL, [mobile] varchar(50) null) AS BEGIN DECLARE @auth smallint = -1; DECLARE @name nvarchar(255), @email varchar(255), @mobile varchar(50); SELECT TOP(1) @useraccount_id = [useraccount_id] ,@name = DECRYPTBYKEY(ua.[name_enc]) ,@email = DECRYPTBYKEY(ua.[email_enc]) ,@mobile = DECRYPTBYKEY(ua.[mobile_enc]) FROM [dbo].[ocms_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null AND ua.[useraccount_id] = @useraccount_id; INSERT INTO @RET VALUES( @useraccount_id ,IIF(@useraccount_id is null, -1, 1) ,IIF(@useraccount_id is null, null, @name) ,IIF(@useraccount_id is null, null, @email) ,IIF(@useraccount_id is null, null, @mobile) ); RETURN; END GO ALTER AUTHORIZATION ON [dbo].[ocms_admin_getUserAccount] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_currentaccount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_currentaccount] ( ) RETURNS varchar(7) AS BEGIN RETURN 'fuchs'; END GO ALTER AUTHORIZATION ON [dbo].[ocms_currentaccount] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_fn_generatePassword] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[ocms_fn_generatePassword] ( @length int , @specialChars bit = 1 , @nums bit = 1 , @lowerCase bit = 1 ) RETURNS varchar(255) AS BEGIN DECLARE @randInt int; DECLARE @NewCharacter varchar(1); DECLARE @NewPassword TABLE([typ] char(1), [char] char(1), [order] int); SET @length = CASE WHEN @length > 255 THEN 255 ELSE @length END; DECLARE @cnt int = 0, @position as int; --random characters WHILE (@cnt < @length) BEGIN SELECT @randInt = [dbo].[ocms_fn_randbetween](33,122) IF (CASE WHEN (@randInt>=33 AND @randInt<=47) AND @specialChars = 1 THEN 1 WHEN (@randInt>=48 AND @randInt<=57) AND @nums = 1 THEN 1 WHEN (@randInt>=58 AND @randInt<=64) AND @specialChars = 1 THEN 1 WHEN (@randInt>=65 AND @randInt<=90) THEN 1 WHEN (@randInt>=91 AND @randInt<=93) AND @specialChars = 1 THEN 1 WHEN (@randInt>=97 AND @randInt<=122) AND @lowerCase = 1 THEN 1 ELSE 0 END) = 1 BEGIN SET @cnt = @cnt + 1; INSERT INTO @NewPassword VALUES (CASE WHEN (@randInt>=33 AND @randInt<=47) THEN 's' WHEN (@randInt>=48 AND @randInt<=57) THEN 'n' WHEN (@randInt>=58 AND @randInt<=64) THEN 's' WHEN (@randInt>=65 AND @randInt<=90) THEN 'u' WHEN (@randInt>=91 AND @randInt<=93) THEN 's' WHEN (@randInt>=97 AND @randInt<=122) THEN 'l' END, CHAR(@randInt), @cnt); END END DECLARE @min_n int = CASE WHEN @length > 4 AND @length < 11 THEN 1 ELSE FLOOR(@length * 0.1) END; DECLARE @min_s int = FLOOR(@length * 0.1); DECLARE @min_l int = FLOOR(@length * 0.4); DECLARE @min_u int = FLOOR(@length * 0.4); WHILE (SELECT COUNT(*) FROM @NewPassword WHERE [typ] = 'n') < @min_n AND @length > 0 AND @nums = 1 BEGIN SET @position = [dbo].[ocms_fn_randbetween](1,@length); UPDATE @NewPassword SET [char] = CHAR([dbo].[ocms_fn_randbetween](48,57)), [typ] = 'n' WHERE [order] = @position; END WHILE (SELECT COUNT(*) FROM @NewPassword WHERE [typ] = 'l') < @min_l AND @length > 0 AND @lowerCase = 1 BEGIN SET @position = [dbo].[ocms_fn_randbetween](1,@length); UPDATE @NewPassword SET [char] = CHAR([dbo].[ocms_fn_randbetween](97,122)), [typ] = 'l' WHERE [order] = @position; END WHILE (SELECT COUNT(*) FROM @NewPassword WHERE [typ] = 'u') < @min_n AND @length > 0 BEGIN SET @position = [dbo].[ocms_fn_randbetween](1,@length); UPDATE @NewPassword SET [char] = CHAR([dbo].[ocms_fn_randbetween](65,90)), [typ] = 'u' WHERE [order] = @position; END WHILE (SELECT COUNT(*) FROM @NewPassword WHERE [typ] = 's') < @min_s AND @length > 0 AND @specialChars = 1 BEGIN SET @position = [dbo].[ocms_fn_randbetween](1,@length); DECLARE @nc char(1), @nt char(1); select @randInt=[dbo].[ocms_fn_randbetween](33,122) UPDATE @NewPassword SET [char] = CHAR(@randint), [typ] = 's' WHERE [order] = @position AND (CASE WHEN (@randInt>=33 AND @randInt<=47) THEN 's' WHEN (@randInt>=48 AND @randInt<=57) THEN 'n' WHEN (@randInt>=58 AND @randInt<=64) THEN 's' WHEN (@randInt>=65 AND @randInt<=90) THEN 'u' WHEN (@randInt>=91 AND @randInt<=93) THEN 's' WHEN (@randInt>=97 AND @randInt<=122) THEN 'l' END) = 's'; END RETURN (Cast((SELECT [CHAR] as [text()] FROM @NewPassword FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)') as varchar(255))); END; GO ALTER AUTHORIZATION ON [dbo].[ocms_fn_generatePassword] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_fn_link_csv] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_fn_link_csv] ( @inp1 varchar(4000) ,@inp2 varchar(4000) ) RETURNS varchar(4000) AS BEGIN DECLARE @RET varchar(4000) = ISNULL(@inp1, '') + CASE WHEN ISNULL(@inp1, '') <> '' AND ISNULL(@inp2, '') <> '' THEN ',' ELSE '' END + ISNULL(@inp2, ''); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ocms_fn_link_csv] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_fn_randbetween] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[ocms_fn_randbetween](@bottom integer, @top integer) RETURNS integer AS BEGIN RETURN (select cast(round((@top-@bottom) * [rn] +@bottom,0) as integer) from [dbo].[ocms_fn_rand]) END GO ALTER AUTHORIZATION ON [dbo].[ocms_fn_randbetween] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_fn_useraccount_id] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[ocms_fn_useraccount_id] ( ) RETURNS varchar(5) AS BEGIN DECLARE @NewAccount varchar(5) = [dbo].[ocms_fn_generatePassword] (5,0,1,0); WHILE EXISTS( SELECT * FROM [dbo].[ocms_useraccounts] WHERE [useraccount_id] = @NewAccount) BEGIN SET @NewAccount = [dbo].[ocms_fn_generatePassword] (5,0,1,0); END RETURN @NewAccount; END; GO ALTER AUTHORIZATION ON [dbo].[ocms_fn_useraccount_id] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_getFullItemTree] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_getFullItemTree] ( @view_iid bigint ,@include_hidden bit ) RETURNS @itemtree TABLE ( [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [ocms_pid] [bigint] NULL, [name] [nvarchar](255) NULL, [view] [bit] NOT NULL, [template_id] [bigint] NULL, [hide] [bit] NOT NULL, [order] [int] NOT NULL, [DateCreated] [datetime] NULL, [DateModified] [datetime] NULL, [level] int, [sub] bit, [sitepropsub] bit, [focus] bit, [new_order] int ) AS BEGIN -- get basics DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); IF @site is NOT null BEGIN WITH cteLevels as ( SELECT t.* , CAST(0 as int) as [level] , 0 as [sub] , 0 as [sitepropsub] FROM [dbo].[ocms_items] as t WHERE t.[ocms_iid] = @site UNION ALL SELECT t.* , CAST(c.[level] + 1 as int) as [level] , CASE WHEN c.[sub] = 1 THEN 1 WHEN t.[parent_iid] = @view_iid THEN 1 ELSE 0 END as [sub] , CASE WHEN c.[sitepropsub] = 1 THEN 1 WHEN t.[parent_iid] = @site and t.[view] = 0 THEN 1 ELSE 0 END as [sitepropsub] FROM [dbo].[ocms_items] as t inner JOIN cteLevels c on t.[parent_iid] = c.[ocms_iid] WHERE (t.[hide] = 0 Or @include_hidden = 1) ) INSERT INTO @itemtree SELECT t.* , IIF( t.[ocms_iid] = @view_iid , 1, 0) as [focus] , ROW_NUMBER() OVER (PARTITION BY [parent_iid] ORDER BY [order], [ocms_iid]) as [new_order] FROM cteLevels as t; --SELECT * FROM @itemtree END RETURN END GO ALTER AUTHORIZATION ON [dbo].[ocms_getFullItemTree] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_getFullViewTree] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_getFullViewTree] ( @view_path varchar(255), @locale varchar(5) ) RETURNS @itemtree TABLE ( [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [ocms_pid] [bigint] NULL, [name] [nvarchar](255) NULL, [view] [bit] NOT NULL, [template_id] [bigint] NULL, [hide] [bit] NOT NULL, [order] [int] NOT NULL, [DateCreated] datetime null, [DateModified] datetime null, [locale] varchar(5) NOT NULL, [alias] varchar(25) NULL, [path] varchar(2000), [level] int, [sub] bit, [focus] bit, [nav] bit, [new_order] int ) AS BEGIN -- get basics DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); SET @view_path = ISNULL(@view_path, ''); SET @locale = IIF(ISNULL(@locale, '')='', null, @locale); IF @site is NOT null BEGIN --get locales DECLARE @locales TABLE([locale] varchar(5), [order] int); INSERT INTO @locales SELECT * FROM [dbo].[ocms_locales](); -- tree in all locales WITH itm as( -- items are not localized SELECT i.*, l.[locale] FROM [dbo].[ocms_items] as i CROSS JOIN (SELECT * FROM @locales as l_ WHERE l_.[locale] <> '*') as l WHERE i.[view] = 1 OR ([ocms_iid] = @site) ), navitm as ( select itm.* ,IIF(itm.[name] COLLATE Latin1_General_CI_AS = 'index', 'index', n.[alias]) as 'alias' FROM itm LEFT JOIN [dbo].[ocms_navigation] as n ON itm.[ocms_iid] = n.[ocms_iid] and itm.[locale] = n.[locale] AND n.[locale] <> '*' ), cteLevels as ( SELECT t.* , Cast('//' as varchar(2000)) as [path] , CAST(0 as int) as [level] , 0 as [sub] FROM navitm as t WHERE t.[ocms_iid] = @site UNION ALL SELECT navitm.* , IIF( navitm.[view] = 0, '', CAST(IIF( c.[path] = '//' , '' , c.[path] + '/' ) + LOWER(navitm.[alias]) as varchar(2000)) ) as [path] , CAST(c.[level] + 1 as int) as [level] , CASE WHEN c.[sub] = 1 THEN 1 WHEN IIF( CAST(IIF( c.[path] = '//' , '' , c.[path] + '/' ) + ISNULL(LOWER(navitm.[name]), '') as varchar(2000)) = LOWER(@view_path), 1, 0) = 1 THEN 1 ELSE 0 END as [sub] FROM navitm inner JOIN cteLevels c on navitm.[parent_iid] = c.[ocms_iid] AND navitm.[locale] = c.[locale] ) INSERT INTO @itemtree SELECT t.* , IIF( [path] COLLATE Latin1_General_CI_AS = @view_path OR [path] COLLATE Latin1_General_CI_AS like (@view_path + '?%'), 1, 0) as [focus] , IIF( [view] = 1 AND [level] > 0 AND [path] <> '' AND [path] <> '//' AND ISNULL(t.[hide],0) = 0 , 1, 0 ) as [nav] , ROW_NUMBER() OVER (PARTITION BY [parent_iid] ORDER BY [order], [ocms_iid]) as [new_order] FROM cteLevels as t; UPDATE @itemtree SET [path] = null WHERE [nav] = 0; IF(ISNULL(@locale, '') <> '') BEGIN DECLARE @view_iid bigint = null, @view_level int; SELECT TOP(1) @view_iid = it.[ocms_iid] , @view_level = it.[level] , @locale = it.[locale] -- will override the selected language FROM @itemtree as it WHERE [focus] = 1 AND ([locale] = @locale OR [name] COLLATE Latin1_General_CI_AS <> 'index'); -- index is available in any language DELETE FROM @itemtree WHERE [locale] <> @locale; -- remove anything that is not in selected language END --SELECT * FROM @itemtree END RETURN END GO ALTER AUTHORIZATION ON [dbo].[ocms_getFullViewTree] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_locales] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_locales] ( ) RETURNS @RET TABLE ([locale] varchar(5), [order] int) AS BEGIN DECLARE @set_value varchar(2000) = ISNULL((SELECT [value] FROM [ocms_settings] where [key] = 'locales'), '*,de'); DECLARE @c char = ','; INSERT INTO @RET SELECT [value], [order] = ROW_NUMBER() OVER (ORDER BY CHARINDEX(@c + value + @c, @c + @set_value + @c)) FROM STRING_SPLIT(@set_value, @c); RETURN; END GO ALTER AUTHORIZATION ON [dbo].[ocms_locales] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_20_randomStrings] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_20_randomStrings] ( @digits tinyint ) RETURNS @RET TABLE ( [s] varchar(5) ) AS BEGIN DECLARE @new_sessionid varchar(36), @trys int, @chars varchar(100), @UPPER int, @LOWER int; SELECT @chars = '012KLMN34STUVWEFGHIJXYZ567OPQR89ABCD'; SELECT @UPPER = LEN(@chars), @LOWER = 1; INSERT INTO @RET SELECT * FROM (SELECT TOP(20) SUBSTRING(SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1) + SUBSTRING(@chars, [dbo].[ott_random_int](@UPPER,@LOWER), 1), 1, @digits) as id FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16),(17),(18),(19),(20)) vl(id))z WHERE LEN(id) = @digits; RETURN END GO ALTER AUTHORIZATION ON [dbo].[ott_20_randomStrings] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_b10] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_b10] ( @string varchar(10) ) RETURNS int AS BEGIN DECLARE @RET int; DECLARE @str VARCHAR(10) = REVERSE(LOWER(@string)); WITH Split(stpos,endpos) AS( SELECT 1 AS stpos, 2 AS endpos UNION ALL SELECT endpos, endpos+1 FROM Split WHERE endpos <= LEN(@str) ) , c as ( SELECT 'character' = SUBSTRING(@str,stpos,COALESCE(NULLIF(endpos,0),LEN(@str)+1)-stpos) ,'charindex' = stpos FROM Split ) , s as ( SELECT * ,'num' = ASCII(character) - ASCII('a') + 1 ,'fac' = POWER(26,([charindex] -1)) ,'val' = POWER(26,([charindex] -1)) * (ASCII(character) - ASCII('a') + 1) FROM c ) select @RET = SUM([val]) FROM s; RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ott_b10] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_b26] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_b26] ( @number int ) RETURNS varchar(10) AS BEGIN DECLARE @RET varchar(10) /* SELECT *, LetterCode = Coalesce((SELECT Char(65 + (N.Num - 475255) / 456976 % 26) WHERE N.Num >= 475255), '') + Coalesce((SELECT Char(65 + (N.Num - 18279) / 17576 % 26) WHERE N.Num >= 18279), '') + Coalesce((SELECT Char(65 + (N.Num - 703) / 676 % 26) WHERE N.Num >= 703), '') + Coalesce((SELECT Char(65 + (N.Num - 27) / 26 % 26) WHERE N.Num >= 27), '') + (SELECT Char(65 + (N.Num - 1) % 26)) FROM (VALUES(18931)) as N(Num) ORDER BY N.Num */ SET @RET = LOWER( Coalesce((SELECT Char(65 + (@number - 475255) / 456976 % 26) WHERE @number >= 475255), '') + Coalesce((SELECT Char(65 + (@number - 18279) / 17576 % 26) WHERE @number >= 18279), '') + Coalesce((SELECT Char(65 + (@number - 703) / 676 % 26) WHERE @number >= 703), '') + Coalesce((SELECT Char(65 + (@number - 27) / 26 % 26) WHERE @number >= 27), '') + (SELECT Char(65 + (@number - 1) % 26)) ); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ott_b26] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_csv_contains] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_csv_contains] ( @text varchar(500) ,@fragment varchar(500) ) RETURNS bit AS BEGIN DECLARE @RET bit; IF ISNULL(@text, '') = '' OR ISNULL(@fragment, '') = '' SET @REt = 0; ELSE BEGIN -- Will be true -- if any of the fragments exist in the list of text-items WITH texts as (SELECT * FROM string_split(ISNULL(@text,''), ',')) ,fragments as (SELECT * FROM string_split(ISNULL(@fragment,''), ',')) SELECT @RET = CASE WHEN EXISTS (SELECT * FROM texts JOIN fragments ON texts.[value] = fragments.[value]) THEN 1 ELSE 0 END; END; RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ott_csv_contains] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_jcontent] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_jcontent] ( @groupcode varchar(10) ,@text varchar(4000) ) RETURNS varchar(4000) AS BEGIN DECLARE @RET varchar(4000); DECLARE @textinput varchar(4000) = REPLACE(ISNULL(@text, ''), ' ', ''); IF (@textinput = '' OR @textinput = '{}') BEGIN SET @RET = 0; END ELSE BEGIN DECLARE @Pattern varchar(20) = '%"' + @groupcode + '":"%'; DECLARE @P0 int = PATINDEX(@pattern, @textinput); DECLARE @P1 int = @P0 + LEN(@pattern) -2; DECLARE @P2 int = CHARINDEX('"',@textinput,@p1); SELECT @RET = CASE WHEN @P0 = 0 THEN '' ELSE SUBSTRING(@textinput, @P1, @P2 - @P1) END; END RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ott_jcontent] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_jcsv_contains] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_jcsv_contains] ( @groupcode varchar(10) ,@text varchar(4000) ,@fragment varchar(500) ) RETURNS bit AS BEGIN DECLARE @RET bit; DECLARE @textinput varchar(4000) = REPLACE(ISNULL(@text, ''), ' ', ''); IF (@textinput = '' OR @textinput = '{}' OR @fragment = '') BEGIN SET @RET = 0; END ELSE BEGIN -- Will be true -- if any of the fragments exist in the list of text-items DECLARE @Pattern varchar(20) = '%"' + @groupcode + '":"%'; DECLARE @P0 int = PATINDEX(@pattern, @textinput); DECLARE @P1 int = @P0 + LEN(@pattern) -2; DECLARE @P2 int = CHARINDEX('"',@textinput,@p1); IF @P0 = 0 BEGIN SET @RET = 0; END ELSE BEGIN DECLARE @text2 varchar(4000) = SUBSTRING(@textinput, @P1, @P2 - @P1); WITH texts as (SELECT * FROM string_split(ISNULL(@text2,''), ',')) ,fragments as (SELECT * FROM string_split(ISNULL(@fragment,''), ',')) SELECT @RET = CASE WHEN EXISTS (SELECT * FROM texts JOIN fragments ON texts.[value] = fragments.[value]) THEN 1 ELSE 0 END; END END RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ott_jcsv_contains] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_jcsv_containskey] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_jcsv_containskey] ( @groupcode varchar(10) ,@text varchar(4000) ) RETURNS bit AS BEGIN DECLARE @RET bit; DECLARE @textinput varchar(4000) = REPLACE(ISNULL(@text, ''), ' ', ''); IF (@textinput = '' OR @textinput = '{}') BEGIN SET @RET = 0; END ELSE BEGIN -- Will be true -- if any of the fragments exist in the list of text-items DECLARE @Pattern varchar(20) = '%"' + @groupcode + '":"%'; DECLARE @P0 int = PATINDEX(@pattern, @textinput); SET @RET = Case WHEN @P0 = 0 THEN 0 ELSE 1 END; END RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ott_jcsv_containskey] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_max] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_max] ( @val1 int, @val2 int ) RETURNS int AS BEGIN DECLARE @RES int; IF @val1 is null and @val2 is not null SET @val1 = @val2 IF @val2 is null and @val1 is not null SET @val2 = @val1 IF @val1 is null and @val2 is null SELECT @val1 = 0, @val2 = 0; SELECT @RES = CASE WHEN @val1 > @val2 THEN @val1 ELSE @val2 END; RETURN @RES; END GO ALTER AUTHORIZATION ON [dbo].[ott_max] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_max_float] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_max_float] ( @val1 float, @val2 float ) RETURNS float AS BEGIN DECLARE @RES float; IF @val1 is null and @val2 is not null SET @val1 = @val2 IF @val2 is null and @val1 is not null SET @val2 = @val1 IF @val1 is null and @val2 is null SELECT @val1 = 0, @val2 = 0; SELECT @RES = CASE WHEN @val1 > @val2 THEN @val1 ELSE @val2 END; RETURN @RES; END GO ALTER AUTHORIZATION ON [dbo].[ott_max_float] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_merge_csv] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_merge_csv] ( @inp1 varchar(2000) ,@inp2 varchar(2000) ) RETURNS varchar(4000) AS BEGIN DECLARE @ret varchar(4000); with sp as( SELECT [value] FROM string_split(@inp1,',') UNION SELECT [value] FROM string_split(@inp2,',') ), sp2 as ( SELECT DISTINCT [value] FROM sp where ISNULL([value], '') <> '' ) SELECT @ret = ISNULL(STRING_AGG([value], ','),'') FROM sp2; RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[ott_merge_csv] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_min] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_min] ( @val1 int, @val2 int ) RETURNS int AS BEGIN DECLARE @RES int; IF @val1 is null and @val2 is not null SET @val1 = @val2 IF @val2 is null and @val1 is not null SET @val2 = @val1 IF @val1 is null and @val2 is null SELECT @val1 = 0, @val2 = 0; SELECT @RES = CASE WHEN @val1 < @val2 THEN @val1 ELSE @val2 END; RETURN @RES; END GO ALTER AUTHORIZATION ON [dbo].[ott_min] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_min_date] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_min_date] ( @val1 date, @val2 date ) RETURNS date AS BEGIN DECLARE @RES date; IF @val1 is null and @val2 is not null SET @val1 = @val2 IF @val2 is null and @val1 is not null SET @val2 = @val1; SELECT @RES = CASE WHEN @val1 is null and @val2 is null THEN NULL WHEN @val1 < @val2 THEN @val1 ELSE @val2 END; RETURN @RES; END GO ALTER AUTHORIZATION ON [dbo].[ott_min_date] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_min_float] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_min_float] ( @val1 float, @val2 float ) RETURNS float AS BEGIN DECLARE @RES float; IF @val1 is null and @val2 is not null SET @val1 = @val2 IF @val2 is null and @val1 is not null SET @val2 = @val1 IF @val1 is null and @val2 is null SELECT @val1 = 0, @val2 = 0; SELECT @RES = CASE WHEN @val1 < @val2 THEN @val1 ELSE @val2 END; RETURN @RES; END GO ALTER AUTHORIZATION ON [dbo].[ott_min_float] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_quote] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_quote] ( @txt as nvarchar(max) ) RETURNS nvarchar(max) AS BEGIN DECLARE @res nvarchar(max); SET @res = CHAR(34) + REPLACE(ISNULL(@txt,''), CHAR(34), CHAR(34) + CHAR(34)) + CHAR(34); RETURN @res; END GO ALTER AUTHORIZATION ON [dbo].[ott_quote] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_quote_255] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_quote_255] ( @txt as nvarchar(255) ) RETURNS nvarchar(255) AS BEGIN DECLARE @res nvarchar(255); SET @res = CHAR(34) + REPLACE(ISNULL(@txt,''), CHAR(34), CHAR(34) + CHAR(34)) + CHAR(34); RETURN @res; END GO ALTER AUTHORIZATION ON [dbo].[ott_quote_255] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_random_int] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_random_int] (@UPPER int, @LOWER int) RETURNS int AS BEGIN DECLARE @RET INT = CAST(ROUND(((@UPPER - @LOWER - 1) * (SELECT TOP(1) [rn] FROM [dbo].[ocms_fn_rand]) + @LOWER), 0) as int); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[ott_random_int] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ott_remove_csv] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ott_remove_csv] ( @inp1 varchar(2000) ,@fragment varchar(500) ) RETURNS varchar(4000) AS BEGIN DECLARE @ret varchar(4000); with sp as( SELECT [value] FROM string_split(@inp1,',') ), sp2 as ( SELECT DISTINCT [value] FROM sp where ISNULL([value], '') <> '' AND ISNULL([value], '') <> @fragment ) SELECT @ret = ISNULL(STRING_AGG([value], ','),'') FROM sp2; RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[ott_remove_csv] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[string_SplitString_ordered] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[string_SplitString_ordered] ( @String VARCHAR(MAX) , @Delimiter VARCHAR(10) ) RETURNS @RetTable TABLE( String varchar(MAX), RowNo int ) AS BEGIN DECLARE @i INT , @j INT , @cnt INT SELECT @i = 1 SET @cnt = 1 WHILE @i <= LEN(@String) BEGIN SELECT @j = CHARINDEX(@Delimiter, @String, @i) IF @j = 0 BEGIN SELECT @j = LEN(@String) + 1 END INSERT INTO @RetTable SELECT SUBSTRING(@String, @i, @j - @i), @cnt SET @cnt = @cnt + 1 SELECT @i = @j + LEN(@Delimiter) END RETURN END GO ALTER AUTHORIZATION ON [dbo].[string_SplitString_ordered] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[strings_removeLeading0] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[strings_removeLeading0] ( @Data NVARCHAR(MAX) ) RETURNS nvarchar(max) AS BEGIN DECLARE @ret nvarchar(max) = SUBSTRING(@Data, PATINDEX('%[^0]%', @Data), LEN(@Data)); RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[strings_removeLeading0] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[strings_removeLeading0_255] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[strings_removeLeading0_255] ( @Data NVARCHAR(255) ) RETURNS nvarchar(255) AS BEGIN DECLARE @ret nvarchar(255) = SUBSTRING(@Data, PATINDEX('%[^0]%', @Data), LEN(@Data)); RETURN @ret; END GO ALTER AUTHORIZATION ON [dbo].[strings_removeLeading0_255] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[vat_val] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[vat_val] ( @price numeric(10,3) ,@quantityhours numeric(10,3) ,@discount numeric(10,3) ,@VAT numeric(10,3) ) RETURNS numeric(7,2) AS BEGIN DECLARE @Ret numeric(7,2) SET @RET = [dbo].[net_val](@price, @quantityhours, @discount) * ((ISNULL(@vat, 19.0) * 0.01)); RETURN @RET; END GO ALTER AUTHORIZATION ON [dbo].[vat_val] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__admin_settings] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__admin_settings]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [type] [varchar](50) NOT NULL, [key] [varchar](50) NULL, [value] [nvarchar](max) NULL, [value2] [nvarchar](1000) NULL, CONSTRAINT [PK_fds__admin_settings] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__admin_settings] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__admin_reminderSettings] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__admin_reminderSettings] ( ) RETURNS TABLE AS RETURN ( WITH rs as ( SELECT * FROM [dbo].[fds__admin_settings] WHERE [type] = 'reminder' ) SELECT [stage1] = (SELECT TOP(1) [value] FROM rs WHERE [key] = 1) , [stage2] = (SELECT TOP(1) [value] FROM rs WHERE [key] = 2) , [stage3] = (SELECT TOP(1) [value] FROM rs WHERE [key] = 3) ) GO ALTER AUTHORIZATION ON [dbo].[fds__admin_reminderSettings] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__*PartnerSet] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__*PartnerSet]( [Property] [varchar](50) NOT NULL, [PartnerType] [varchar](25) NOT NULL, [PartnerId] [bigint] NOT NULL, [EntityId] [bigint] NOT NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__*PartnerSet] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__contacts] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__contacts]( [Id] [bigint] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [FirstName] [nvarchar](255) NULL, [LastName] [nvarchar](255) NULL, [Email] [nvarchar](255) NULL, [JobTitle] [nvarchar](255) NULL, [MobilePhone] [nvarchar](255) NULL, [Telephone] [nvarchar](255) NULL, [Fax] [nvarchar](255) NULL, [Note] [nvarchar](1000) NULL, [DateModified] [datetime] NOT NULL, [Version] [int] NOT NULL, [CompanyId] [bigint] NOT NULL, [IsUser] [bit] NOT NULL, [ExternalId] [nvarchar](255) NULL, [Gender] [nvarchar](255) NULL, [UserId] [bigint] NOT NULL, CONSTRAINT [PK_mfr__contact] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__contacts] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__companies] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__companies]( [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsPhysicalPerson] [bit] NOT NULL, [IsOwner] [bit] NOT NULL, [IsEmailInvoicingActive] [bit] NOT NULL, [IsSupplier] [bit] NOT NULL, [MappingId] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [SupportTelephone] [nvarchar](255) NULL, [SupportFax] [nvarchar](255) NULL, [SupportMail] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [CustomValues] [nvarchar](max) NULL, [MainContactId] [bigint] NULL, CONSTRAINT [PK_mfr__company] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__companies] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getCompanyContacts] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getCompanyContacts] ( @companyid bigint ) RETURNS TABLE AS RETURN ( WITH ps as ( SELECT [contactid] = p.[EntityId] from [mfr__*PartnerSet] as p WHERE p.property = 'Contact:Company' and p.[partnerId] = @companyid UNION SELECT [contactid] = p.[PartnerId] from [mfr__*PartnerSet] as p WHERE p.property = 'Company:Contacts' and p.[EntityId] = @companyid ) SELECT ct.* ,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as ct JOIN [dbo].[mfr__companies] as cy ON ct.[CompanyId] = cy.[id] WHERE ct.CompanyId = @companyid UNION SELECT ct.* ,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as ct JOIN ps ON ct.[id] = ps.[contactid] JOIN [dbo].[mfr__companies] as cy ON cy.[id] = @companyid ) GO ALTER AUTHORIZATION ON [dbo].[fds__getCompanyContacts] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getCompanysContacts] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getCompanysContacts] ( @companyids [dbo].[fds__tt__idlist] READONLY ) RETURNS TABLE AS RETURN ( WITH ps as ( SELECT [companyid] = p.[partnerId], [contactid] = p.[EntityId] from [mfr__*PartnerSet] as p WHERE p.property = 'Contact:Company' and p.[partnerId] IN (SELECT [Id] FROM @companyids) UNION SELECT [companyid] = p.[PartnerId], [contactid] = p.[PartnerId] from [mfr__*PartnerSet] as p WHERE p.property = 'Company:Contacts' and p.[EntityId] = (SELECT [Id] FROM @companyids) ) SELECT [CyId] = cyid.[Id] ,ct.* ,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as ct JOIN @companyids as cyid ON ct.[CompanyId] = cyid.[id] JOIN [dbo].[mfr__companies] as cy ON cyid.[id] = cy.[id] UNION SELECT [CyId] = cyid.[Id] ,ct.* ,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as ct JOIN ps ON ct.[id] = ps.[contactid] JOIN @companyids as cyid ON ps.[CompanyId] = cyid.[id] JOIN [dbo].[mfr__companies] as cy ON cyid.[id] = cy.[id] ) GO ALTER AUTHORIZATION ON [dbo].[fds__getCompanysContacts] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__invoices] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__invoices]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [DateOfCreation] [datetime] NOT NULL, [URI] [nvarchar](255) NULL, [DocumentName] [nvarchar](255) NULL, [ReportDefinitionCode] [nvarchar](255) NULL, [FileType] [nvarchar](255) NULL, [InvoiceBalance] [numeric](10, 3) NULL, [InvoiceBalanceNetto] [numeric](10, 3) NULL, [WageBalanceNet] [numeric](10, 3) NULL, [DatePayed] [datetime] NULL, [InvoiceId] [nvarchar](50) NULL, [DueDate] [datetime] NOT NULL, [WithoutVAT] [bit] NOT NULL, [Skonto] [numeric](10, 3) NOT NULL, [PartialPayment] [numeric](10, 3) NULL, [InvoiceState] [nvarchar](255) NULL, [Note] [nvarchar](max) NULL, [file_guid] [uniqueidentifier] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__invoices] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__bankingtransactions] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__bankingtransactions]( [uid] [bigint] IDENTITY(1,1) NOT NULL, [AccountIdentification] [varchar](50) NULL, [ValueDate] [date] NULL, [Amount] [numeric](9, 2) NULL, [FundsCode] [varchar](1) NULL, [AccountNumberOfPayer] [varchar](30) NULL, [BankCodeOfPayer] [varchar](11) NULL, [CompensationAmount] [varchar](50) NULL, [CreditorReference] [varchar](30) NULL, [CreditorsReferenceParty] [varchar](50) NULL, [CustomerReference] [varchar](50) NULL, [EndToEndReference] [varchar](50) NULL, [JournalNumber] [varchar](10) NULL, [MandateReference] [varchar](50) NULL, [NameOfPayer] [nvarchar](60) NULL, [OriginalAmount] [varchar](150) NULL, [OriginatorsIdentificationCode] [varchar](150) NULL, [PayersReferenceParty] [varchar](150) NULL, [PostingText] [varchar](30) NULL, [SepaRemittanceInformation] [varchar](200) NULL, [TextKeyAddition] [int] NULL, [TransactionCode] [int] NULL, [IsUnstructuredData] [bit] NULL, [UnstructuredData] [nvarchar](390) NULL, [UnstructuredRemittanceInformation] [nvarchar](390) NULL, [DebitCreditMark] [varchar](2) NULL, [TransactionTypeIdCode] [varchar](3) NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__bankingtransactions] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__invoices] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__invoices]( [Id] [varchar](10) NOT NULL, [Version] [int] NOT NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NOT NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [varchar](50) NULL, [InvoiceBalance] [numeric](10, 2) NOT NULL, [InvoiceBalance_net] [numeric](10, 2) NOT NULL, [InvoiceVAT_net1] [numeric](10, 2) NOT NULL, [InvoiceVAT_1] [numeric](5, 2) NOT NULL, [InvoiceVAT_net2] [numeric](10, 2) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NOT NULL, [DueDate] [date] NOT NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NOT NULL, [IsSent] [bit] NOT NULL, [IsFinal] AS (CONVERT([bit],case when [DateFinalized] IS NULL then (0) else (1) end)), [IsCanceled] AS (CONVERT([bit],case when [DateCancelled] IS NULL then (0) else (1) end)), [Replaces_InvId] [varchar](50) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](25) NOT NULL, [DateModified] [datetime] NOT NULL, [UserModified] [varchar](25) NOT NULL, [ExternalId] [varchar](25) NULL, [IsExternal] [bit] NULL, [file] [varbinary](max) NULL, [file_guid] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_fds__invoices] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__invoices] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getInvoiceCredits] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE function [dbo].[fds__getInvoiceCredits] ( @startdate date ,@enddate date ) RETURNS TABLE AS RETURN ( with b0 as ( SELECT [uid] --,[AccountIdentification] ,[Amount] --,[EntryDate] ,[FundsCode] ,[AccountNumberOfPayer] ,[BankCodeOfPayer] ,[EndToEndReference] --,[JournalNumber] ,[NameOfPayer] ,'info' = [dbo].[fds__fn_creanupTransactionInfo]([SepaRemittanceInformation]) ,'e2e' = [dbo].[fds__fn_creanupTransactionInfo]([EndToEndReference]) --,[PayersReferenceParty] --,[PostingText] ,[SepaRemittanceInformation] ,[TextKeyAddition] ,[TransactionCode] ,[DebitCreditMark] ,[TransactionTypeIdCode] ,[ValueDate] FROM [dbo].[fds__bankingtransactions] WHERE [DebitCreditMark] in ('C') AND (@startdate is null or CAST([valuedate] AS DATE) >= @startdate) AND (@enddate is null or CAST([valuedate] AS DATE) <= @enddate) AND NOT (ISNULL([AccountNumberOfPayer],'') IN ('DE52301502000002091478') AND ISNULL([SepaRemittanceInformation],'') like ('%umbuchung%')) AND NOT (ISNULL([AccountNumberOfPayer],'') IN ('DE23501108006161606386') AND ISNULL([SepaRemittanceInformation],'') like ('%ebay%')) AND NOT (ISNULL([SepaRemittanceInformation],'') like ('%Umsatzsteuer%')) ) , b as ( SELECT * ,'exact' = PATINDEX('%R202[0-9][- ][0-9][0-9][0-9][0-9]%',[info]) ,'exact2' = PATINDEX('%R202[0-9][- ][0-9][0-9][0-9][0-9]%',REPLACE([info], ' ', '')) ,'test1' = PATINDEX('%202[0-9]%',[info]) ,'E2E_exact' = PATINDEX('%R202[0-9][- ][0-9][0-9][0-9][0-9]%',[e2e]) ,'E2E_exact2' = PATINDEX('%R202[0-9][- ][0-9][0-9][0-9][0-9]%',REPLACE([e2e], ' ', '')) ,'E2E_test1' = PATINDEX('%202[0-9]%',[e2e]) from b0 ), b2 as ( SELECT * ,[info2] = REPLACE([info], ' ', '') ,[info3] = CASE WHEN test1 > 0 THEN REPLACE(SUBSTRING([info], [test1] - 1, 10), ' ' , '-') ELSE '' END ,[info4] = REPLACE(REPLACE([info], 'RE ', 'NO '), 'RE-NR. ', 'NO ') ,[e2e_info2] = REPLACE([e2e], ' ', '') ,[e2e_info3] = CASE WHEN [E2E_test1] > 0 THEN REPLACE(SUBSTRING([e2e], [E2E_test1] - 1, 10), ' ' , '-') ELSE '' END FROM b ), c as ( select * , 'lv' = CASE WHEN exact > 0 THEN 0 WHEN exact2 > 0 THEN 1 WHEN [test1] > 0 AND PATINDEX('%202[0-9][- ][0-9][0-9][0-9][0-9]%', [info3]) > 0 THEN 2 WHEN [test1] > 0 AND PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [info3]) > 0 THEN 3 WHEN [e2e_exact] > 0 THEN 10 WHEN [e2e_exact2] > 0 THEN 11 WHEN [e2e_test1] > 0 AND PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [e2e_info3]) > 0 THEN 12 WHEN [e2e_test1] > 0 AND PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [e2e_info3]) > 0 THEN 13 WHEN PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) > 0 AND EXISTS (SELECT * FROM [dbo].[fds__invoices] as i where RIGHT(i.[InvoiceId],4) = SUBSTRING([info4],PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) + 3, 4) ) THEN 21 WHEN PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) > 0 AND EXISTS (SELECT * FROM [dbo].[mfr__invoices] as i where RIGHT(i.[InvoiceId],4) = SUBSTRING([info4],PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) + 3, 4) ) THEN 22 ELSE 99 END , 'Rg' = CASe WHEN [exact] > 0 THEN REPLACE(SUBSTRING([info], [exact], 10), ' ' , '-') WHEN [exact2] > 0 THEN REPLACE(SUBSTRING([info2], [exact2], 10), ' ' , '-') WHEN [test1] > 0 AND PATINDEX('%202[0-9][- ][0-9][0-9][0-9][0-9]%', [info3]) > 0 THEN 'R' + SUBSTRING([info3], PATINDEX('%202[0-9][- ][0-9][0-9][0-9][0-9]%', [info3]) ,9) WHEN [test1] > 0 AND PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [info3]) > 0 THEN 'R' + SUBSTRING([info3], PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [info3]) ,4) + '-' + + SUBSTRING([info3], PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [info3]) +4 ,4) WHEN [e2e_exact] > 0 THEN REPLACE(SUBSTRING([e2e], [e2e_exact], 10), ' ' , '-') WHEN [e2e_exact2] > 0 THEN REPLACE(SUBSTRING([e2e_info2], [e2e_exact2], 10), ' ' , '-') WHEN [e2e_test1] > 0 AND PATINDEX('%202[0-9][- ][0-9][0-9][0-9][0-9]%', [e2e_info3]) > 0 THEN 'R' + SUBSTRING([e2e_info3], PATINDEX('%202[0-9][- ][0-9][0-9][0-9][0-9]%', [e2e_info3]) ,9) WHEN [e2e_test1] > 0 AND PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [e2e_info3]) > 0 THEN 'R' + SUBSTRING([e2e_info3], PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [e2e_info3]) ,4) + '-' + + SUBSTRING([e2e_info3], PATINDEX('%202[0-9][0-9][0-9][0-9][0-9]%', [e2e_info3]) +4 ,4) WHEN PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) > 0 AND EXISTS (SELECT * FROM [dbo].[fds__invoices] as i where RIGHT(i.[InvoiceId],4) = SUBSTRING([info4],PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) + 3, 4) ) THEN (SELECT TOP(1) [invoiceid] FROM [dbo].[fds__invoices] as i where RIGHT(i.[InvoiceId],4) = SUBSTRING([info4],PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) + 3, 4) ) WHEN PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) > 0 AND EXISTS (SELECT * FROM [dbo].[mfr__invoices] as i where RIGHT(i.[InvoiceId],4) = SUBSTRING([info4],PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) + 3, 4) ) THEN (SELECT TOP(1) [invoiceid] FROM [dbo].[mfr__invoices] as i where RIGHT(i.[InvoiceId],4) = SUBSTRING([info4],PATINDEX('%NO [0-9][0-9][0-9][0-9] %', [info4]) + 3, 4) ) ELSE NULL END from b2 ) SELECT [uid] , [InvoiceId] = UPPER([rg]) , [info4] , [Amount] --,[EntryDate] , [FundsCode] , [AccountNumberOfPayer] , [BankCodeOfPayer] , [EndToEndReference] --,[JournalNumber] , [NameOfPayer] --,[PayersReferenceParty] --,[PostingText] , [SepaRemittanceInformation] , [TextKeyAddition] , [TransactionCode] , [DebitCreditMark] , [TransactionTypeIdCode] , [ValueDate] --,ASCII(LEFT(RIGHT([info], 2),1)) FROM c --where lv >90--Rg is null ) GO ALTER AUTHORIZATION ON [dbo].[fds__getInvoiceCredits] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__servicerequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__servicerequests]( [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] [nvarchar](255) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NOT NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [varchar](100) NULL, [CustomValues] [nvarchar](max) NOT NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsTemplate] [bit] NOT NULL, [IsTemplateMobile] [bit] NOT NULL, [CreateFromServiceRequestTemplateId] [bigint] NOT NULL, [Type] [nvarchar](255) NULL, CONSTRAINT [PK_mfr__servicerequest] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__servicerequests] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__invoice_servicerequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__invoice_servicerequests]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [InvId] [varchar](10) NOT NULL, [mfr__servicerequest] [bigint] NULL, [title] [nvarchar](max) NULL, [value_net] [numeric](10, 2) NULL, [SortOrder] [tinyint] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__invoice_servicerequests] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getInvoiceTreeIds] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getInvoiceTreeIds] ( @invid varchar(20) ) RETURNS TABLE AS RETURN ( with fds_srq as ( SELECT distinct [type] = 'servicerequest', [id] = mfrs.[id] FROM [dbo].[fds__invoices] as _fi JOIN [dbo].[fds__invoice_servicerequests] as _fs on _fi.Id = _fs.[InvId] and _fs.[mfr__servicerequest] is not null JOIN [dbo].[mfr__servicerequests] as mfrs on _fs.[mfr__servicerequest] = mfrs.id WHERE _fi.[Id] = @invid ) SELECT * FROM fds_srq ) GO ALTER AUTHORIZATION ON [dbo].[fds__getInvoiceTreeIds] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__getRequestTreeIds] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getRequestTreeIds] ( @srqid bigint ) RETURNS TABLE AS RETURN ( with sp as ( SELECT DISTINCT [parentid] = CASE WHEN ISNULL([parentservicerequestid],0) = 0 THEN [id] ELSE [parentservicerequestid] END FROM [dbo].[mfr__servicerequests] as _s where _s.[Id] = @srqid OR _s.[ParentServiceRequestId] = @srqid ) SELECT DISTINCT r.[Id] from [dbo].[mfr__servicerequests] as r JOIN sp on r.[Id] = sp.[parentid] OR r.[ParentServiceRequestId] = sp.[parentid] and ISNULL(sp.parentid,0) > 0 ) GO ALTER AUTHORIZATION ON [dbo].[fds__getRequestTreeIds] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__custom_invoiceinfo] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__custom_invoiceinfo]( [InvID] [bigint] NOT NULL, [PaymentStatus] [char](1) NULL, [isPayed] [bit] NOT NULL, [file] [varbinary](max) NULL, CONSTRAINT [PK_fds__custom_i] PRIMARY KEY CLUSTERED ( [InvID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__custom_invoiceinfo] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[backup__fds__fn_unpaidInvoices] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[backup__fds__fn_unpaidInvoices] ( ) RETURNS TABLE AS RETURN ( WITH inv as ( SELECT [Id] = cast([id] as varchar(15)) ,[Invoiceid] ,[DateFinalized] ,[InvoiceBalance] ,[DocumentName] ,[file] ,[InvoiceTitle] ,[customerid] ,[dateSent] ,[fds] = CAST(1 as bit) FROM [dbo].[fds__invoices] as iv WHERE [isfinal] = 1 and CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END as bit) = 0 and InvoiceBalance > 0 UNION SELECT [Id] = cast([id] as varchar(15)) ,[Invoiceid] ,[DateFinalized] = [DateOfCreation] ,[InvoiceBalance] ,[DocumentName] ,[file] = NULL ,[InvoiceTitle] = '' ,[customerid] = [dbo].[fds__fn_invoice_customerid](mfri.[id]) ,[datesent] = NULL ,[fds] = CAST(0 as bit) FROM [dbo].[mfr__invoices] as mfri LEFT JOIN [dbo].[fds__custom_invoiceinfo] as ivi on mfri.[id] = ivi.[invid] WHERE [invoicestate] in ('eIsSent','eIsOpen') AND ISNULL(ivi.isPayed,0) = 0 AND not [invoiceId] like 'preview' and InvoiceBalance > 0 ) SELECT * /*[Rechnung] = [invoiceId], [Name] = [InvoiceTitle] + CHAR(10) + ' (' + (SELECT TOP(1) c.[name] FROM [dbo].[mfr__companies] as c WHERE inv.[customerid] = c.[id]) + ')', [Betrag (net)] = FORMAT([invoicebalance], '#0.00€', 'de'), [Datum] = FORMAT([DateFinalized], 'dd.MM.yy' , 'de'), [Zahlungen] = FORMAT([dbo].[fds__fn_InvoicePaymentAmount]([id]), '#0.00€', 'de'), [order] = ROW_NUMBER() OVER (ORDER BY [DateFinalized], [DateSent]) */ FROM inv ) GO ALTER AUTHORIZATION ON [dbo].[backup__fds__fn_unpaidInvoices] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[backup__fds__getInvoiceTreeIds] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[backup__fds__getInvoiceTreeIds] ( @invid varchar(20) ) RETURNS TABLE AS RETURN ( with mfr_inv as ( SELECT [type] = 'invoice', [id] = [id] FROM [dbo].[mfr__invoices] as _mfri where _mfri.[id] = TRY_CAST(@invid as bigint) ), mfr_srq as ( SELECT DISTINCT [type] = 'servicerequest', [id] = mfrs.[id] FROM mfr_inv JOIN [dbo].[mfr__*PartnerSet] as ps on Property = 'Invoice:SourceServiceRequest' and ps.EntityId = mfr_inv.[id] JOIN [dbo].[mfr__servicerequests] as mfrs on ps.[PartnerId] = mfrs.id ), fds_srq as ( SELECT distinct [type] = 'servicerequest', [id] = mfrs.[id] FROM [dbo].[fds__invoices] as _fi JOIN [dbo].[fds__invoice_servicerequests] as _fs on _fi.Id = _fs.[InvId] and _fs.[mfr__servicerequest] is not null JOIN [dbo].[mfr__servicerequests] as mfrs on _fs.[mfr__servicerequest] = mfrs.id WHERE _fi.[Id] = @invid ) SELECT * FROM mfr_inv union SELECT * FROM mfr_srq union SELECT * FROM fds_srq ) GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getInvoiceTreeIds] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__invoice_details] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__invoice_details]( [InvId] [varchar](10) NOT NULL, [InvoiceService_net] [numeric](10, 2) NULL, [InvoiceService_VAT] [numeric](10, 2) NULL, [AllocatedTo_InvId] [varchar](10) NULL, [StornoTo_InvId] [varchar](20) NULL, [InvoiceOptions] [varchar](50) NULL, [log] [varchar](max) NULL, CONSTRAINT [PK_fds__invoice_details] PRIMARY KEY CLUSTERED ( [InvId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__invoice_details] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_unpaidInvoices] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_unpaidInvoices] ( ) RETURNS TABLE AS RETURN ( WITH inv as ( SELECT [Id] ,[Invoiceid] ,[DateFinalized] ,[InvoiceBalance] ,[DocumentName] --,[file] ,[InvoiceTitle] ,[customerid] ,[dateSent] ,[fds] = CAST(IIF(iv.isexternal = 0,1,0) as bit) FROM [dbo].[fds__invoices] as iv WHERE [isfinal] = 1 and CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END as bit) = 0 and InvoiceBalance > 0 AND NOT exists (SELECT 0 FROM [dbo].[fds__invoice_details] as d where d.[StornoTo_InvId] = iv.[id]) ) SELECT * /*[Rechnung] = [invoiceId], [Name] = [InvoiceTitle] + CHAR(10) + ' (' + (SELECT TOP(1) c.[name] FROM [dbo].[mfr__companies] as c WHERE inv.[customerid] = c.[id]) + ')', [Betrag (net)] = FORMAT([invoicebalance], '#0.00€', 'de'), [Datum] = FORMAT([DateFinalized], 'dd.MM.yy' , 'de'), [Zahlungen] = FORMAT([dbo].[fds__fn_InvoicePaymentAmount]([id]), '#0.00€', 'de'), [order] = ROW_NUMBER() OVER (ORDER BY [DateFinalized], [DateSent]) */ FROM inv ) GO ALTER AUTHORIZATION ON [dbo].[fds__fn_unpaidInvoices] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fds__fn_requestsforinvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__fn_requestsforinvoice] ( ) RETURNS TABLE AS RETURN ( SELECT [Id] ,sreq.[ExternalId] ,sreq.[Name] ,sreq.[workdoneat] ,sreq.[ReleasedAt] ,sreq.[CustomerId] FROM [dbo].[mfr__servicerequests] as sreq WHERE [state] not in ('Closed') AND [type] in ('IsProject', 'IsMaintenance') AND EXISTS (SELECT 0 FROM dbo.[mfr__*PartnerSet] as ps WHERE ps.[Property] = 'ServiceRequest:Tags' and ps.[PartnerId] = '16034758659' and sreq.[id] = ps.[EntityId]) AND NOT EXISTS( SELECT 0 FROM [dbo].[fds__invoice_servicerequests] as isr join [dbo].[fds__invoices] as inv on isr.[InvId] = inv.[id] and isr.[mfr__servicerequest] = sreq.[id]) ) GO ALTER AUTHORIZATION ON [dbo].[fds__fn_requestsforinvoice] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[fis_getModuleAuthList] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fis_getModuleAuthList] ( @module varchar(100) ,@authuser varchar(10) ) RETURNS TABLE AS RETURN ( SELECT [module] = [value] , [auth] = [dbo].[fis_getModuleAuth]([value], @authuser) FROM string_split(ISNULL(@module, ''),',') WHERE TRIM([value]) <> '' ) GO ALTER AUTHORIZATION ON [dbo].[fis_getModuleAuthList] TO SCHEMA OWNER GO /****** Object: UserDefinedFunction [dbo].[ocms_admin_getConfig] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[ocms_admin_getConfig] ( ) RETURNS TABLE AS RETURN ( SELECT TOP(1) [ocms_mt] = CAST(ISNULL(pvt.[ocms_mt],0) as bit) , [ocms_version] = Cast(ISNULL(pvt.[ocms_version],1.0) as numeric(4,1)) , [account] = [dbo].[ocms_currentaccount]() , [USER] = LOWER(SYSTEM_USER) FROM ( select [name], [value] from sys.extended_properties as eprop where eprop.class = 0 -- database ) as z PIVOT ( MAX([value]) FOR [name] IN ([ocms_mt],[ocms_version]) ) as pvt right JOIN (VALUES(1)) as SOURCE([#]) on 1=1 ) GO ALTER AUTHORIZATION ON [dbo].[ocms_admin_getConfig] TO SCHEMA OWNER GO /****** Object: View [dbo].[ocms_fn_rand] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[ocms_fn_rand] AS select rand(Cast(newid() as varbinary)) as rn GO ALTER AUTHORIZATION ON [dbo].[ocms_fn_rand] TO SCHEMA OWNER GO /****** Object: Table [dbo].[20220727_backup_inv] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[20220727_backup_inv]( [Id] [varchar](10) NOT NULL, [Version] [int] NOT NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NOT NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [varchar](50) NULL, [InvoiceBalance] [numeric](10, 2) NOT NULL, [InvoiceBalance_net] [numeric](10, 2) NOT NULL, [InvoiceVAT_net1] [numeric](10, 2) NOT NULL, [InvoiceVAT_1] [numeric](5, 2) NOT NULL, [InvoiceVAT_net2] [numeric](10, 2) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NOT NULL, [DueDate] [date] NOT NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NOT NULL, [IsSent] [bit] NOT NULL, [IsFinal] [bit] NULL, [IsCanceled] [bit] NULL, [Replaces_InvId] [varchar](50) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](25) NOT NULL, [DateModified] [datetime] NOT NULL, [UserModified] [varchar](25) NOT NULL, [ExternalId] [varchar](25) NULL, [IsExternal] [bit] NULL, [file] [varbinary](max) NULL, [file_guid] [uniqueidentifier] NOT NULL, [InvId] [varchar](10) NOT NULL, [InvoiceService_net] [numeric](10, 2) NULL, [InvoiceService_VAT] [numeric](10, 2) NULL, [AllocatedTo_InvId] [varchar](10) NULL, [StornoTo_InvId] [varchar](20) NULL, [InvoiceOptions] [varchar](50) NULL, [log] [varchar](max) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[20220727_backup_inv] TO SCHEMA OWNER GO /****** Object: Table [dbo].[backup 20220405_fds__bankingtransactions_settings] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[backup 20220405_fds__bankingtransactions_settings]( [banking_uid] [bigint] NOT NULL, [done_manually] [varchar](25) NULL, [assigned_invoice_id] [varchar](255) NULL, [auto_invoice_id] [varchar](255) NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[backup 20220405_fds__bankingtransactions_settings] TO SCHEMA OWNER GO /****** Object: Table [dbo].[backup__fds__mfr_invoices] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[backup__fds__mfr_invoices]( [Id] [varchar](10) NOT NULL, [Version] [int] NOT NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NOT NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [varchar](50) NULL, [InvoiceBalance] [numeric](10, 2) NOT NULL, [InvoiceBalance_net] [numeric](10, 2) NOT NULL, [InvoiceVAT_net1] [numeric](10, 2) NOT NULL, [InvoiceVAT_1] [numeric](5, 2) NOT NULL, [InvoiceVAT_net2] [numeric](10, 2) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NOT NULL, [DueDate] [date] NOT NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NOT NULL, [IsSent] [bit] NOT NULL, [IsFinal] AS (CONVERT([bit],case when [DateFinalized] IS NULL then (0) else (1) end)), [IsCanceled] AS (CONVERT([bit],case when [DateCancelled] IS NULL then (0) else (1) end)), [Replaces_InvId] [varchar](50) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](25) NOT NULL, [DateModified] [datetime] NOT NULL, [UserModified] [varchar](25) NOT NULL, [ExternalID] [varchar](25) NOT NULL, [external] [bit] NULL, [file] [varbinary](max) NULL, [file_guid] [uniqueidentifier] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[backup__fds__mfr_invoices] TO SCHEMA OWNER GO /****** Object: Table [dbo].[bs_bup] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[bs_bup]( [banking_uid] [bigint] NOT NULL, [done_manually] [varchar](25) NULL, [assigned_invoice_id] [varchar](15) NULL, [auto_invoice_id] [varchar](15) NULL, [#] [bigint] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[bs_bup] TO SCHEMA OWNER GO /****** Object: Table [dbo].[email_list_2020] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[email_list_2020]( [uid] [int] IDENTITY(1,1) NOT NULL, [email] [varchar](255) NULL, [sent] [datetime] NULL, [result] [bit] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[email_list_2020] TO SCHEMA OWNER GO /****** Object: Table [dbo].[email_list_2021] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[email_list_2021]( [uid] [int] IDENTITY(1,1) NOT NULL, [email] [varchar](255) NULL, [sent] [datetime] NULL, [result] [bit] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[email_list_2021] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__admin_activity] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__admin_activity]( [uid] [bigint] IDENTITY(1,1) NOT NULL, [timestamp] [datetime] NOT NULL, [activity] [varchar](50) NOT NULL, [authuser] [varchar](10) NULL, [info] [varchar](1000) NULL, [data] [nvarchar](max) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__admin_activity] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__admin_dberrors] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__admin_dberrors]( [ErrorID] [int] IDENTITY(1,1) NOT NULL, [UserName] [varchar](100) NULL, [ErrorNumber] [int] NULL, [ErrorState] [int] NULL, [ErrorSeverity] [int] NULL, [ErrorLine] [int] NULL, [ErrorProcedure] [varchar](max) NULL, [ErrorMessage] [varchar](max) NULL, [ErrorDateTime] [datetime] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__admin_dberrors] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__admin_reportcatalog] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__admin_reportcatalog]( [type] [varchar](50) NOT NULL, [key] [varchar](100) NOT NULL, [label] [varchar](255) NOT NULL, [description] [nvarchar](4000) NULL, [tags_csv] [varchar](255) NULL, [category] [varchar](255) NULL, [image_dataurl] [varchar](max) NULL, [link] [varchar](255) NULL, [functions] [varchar](10) NULL, [hidden] [bit] NOT NULL, [refresh] [smallint] NULL, [auth] [varchar](1000) NULL, [help_url] [varchar](255) NULL, [display_order] [smallint] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__admin_reportcatalog] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__bankingtransactions_assigns] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__bankingtransactions_assigns]( [banking_uid] [bigint] NOT NULL, [invoice_id] [varchar](15) NULL, [auto] [bit] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__bankingtransactions_assigns] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__bankingtransactions_settings] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__bankingtransactions_settings]( [banking_uid] [bigint] NOT NULL, [done_manually] [varchar](25) NULL, [assigned_invoice_id] [varchar](255) NULL, [auto_invoice_id] [varchar](255) NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__bankingtransactions_settings] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__custom_servicerequest] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__custom_servicerequest]( [EntityId] [bigint] NOT NULL, [hidden] [bit] NOT NULL, CONSTRAINT [PK_fds__custom_servicerequest] PRIMARY KEY CLUSTERED ( [EntityId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__custom_servicerequest] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__custom_vat] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__custom_vat]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [EntityType] [varchar](50) NOT NULL, [EntityID] [bigint] NOT NULL, [VAT] [numeric](5, 2) NOT NULL, CONSTRAINT [PK_fds__custom_vat] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__custom_vat] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__debuglog] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__debuglog]( [uid] [bigint] IDENTITY(1,1) NOT NULL, [CodeReference] [varchar](255) NULL, [ExceptionMessage] [varchar](max) NULL, [StackTrace] [varchar](max) NULL, [Data] [varchar](max) NULL, [timestamp] [datetime] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__debuglog] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__emaillog] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__emaillog]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Ref] [varchar](25) NOT NULL, [guid] [varchar](50) NULL, [DateSent] [datetime] NOT NULL, [config] [nvarchar](max) NOT NULL, [success] [bit] NOT NULL, [log] [nvarchar](max) NOT NULL, CONSTRAINT [PK_fds__emaillog] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__emaillog] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__invoice_items] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__invoice_items]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [InvId] [varchar](10) NOT NULL, [InvRqId] [bigint] NOT NULL, [mfr__item] [bigint] NULL, [reference_InvId] [varchar](20) NULL, [Type] [nvarchar](255) NULL, [Position] [varchar](5) NULL, [Quantity] [nvarchar](25) NULL, [Text] [nvarchar](max) NULL, [value] [numeric](10, 2) NULL, [value_total] [numeric](10, 2) NULL, [vat] [numeric](5, 2) NULL, [value_service] [numeric](10, 2) NULL, [det] [bit] NULL, [SortOrder] [tinyint] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__invoice_items] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__log] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__log]( [table] [varchar](50) NOT NULL, [action] [varchar](50) NOT NULL, [timestamp] [datetime] NOT NULL, [setid] [varchar](10) NULL, [info] [varchar](250) NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__log] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__mfr_invoicefiles] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__mfr_invoicefiles]( [Id] [bigint] NOT NULL, [filename] [varchar](100) NOT NULL, [file] [varbinary](max) NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__mfr_invoicefiles] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__mfr_updaterequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__mfr_updaterequests]( [entity_name] [varchar](255) NOT NULL, [Id] [bigint] NOT NULL, [date_requested] [datetime] NOT NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__mfr_updaterequests] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__payments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__payments]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [ExternalID] [varchar](50) NULL, [InvId] [varchar](10) NOT NULL, [CustomerId] [bigint] NULL, [DateReceived] [datetime] NOT NULL, [AllocationStatus] [char](1) NULL, [IBAN] [varchar](25) NULL, [sender] [varchar](255) NULL, [reference] [varchar](35) NULL, [purpose] [varchar](140) NULL, [amount] [numeric](10, 3) NOT NULL, [rec_account] [varchar](25) NULL, CONSTRAINT [PK_fds__payments] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__payments] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__reminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__reminder]( [Id] [varchar](10) NOT NULL, [Version] [int] NOT NULL, [DocumentName] [varchar](100) NULL, [InvId] [varchar](15) NOT NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [type] [varchar](3) NOT NULL, [amount] [numeric](10, 3) NULL, [amount_payed] [numeric](10, 3) NULL, [amount_open] AS (CONVERT([numeric](10,3),isnull([amount],(0))-isnull([amount_payed],(0)))), [subject] [nvarchar](255) NULL, [text] [nvarchar](2000) NULL, [IsSent] [bit] NOT NULL, [IsFinal] AS (CONVERT([bit],case when [DateFinalized] IS NULL then (0) else (1) end)), [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](25) NOT NULL, [DateModified] [datetime] NOT NULL, [UserModified] [varchar](25) NOT NULL, [file] [varbinary](max) NULL, CONSTRAINT [PK_fds__reminder] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__reminder] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fds__status] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fds__status]( [table] [varchar](50) NOT NULL, [action] [varchar](50) NOT NULL, [timestamp] [datetime] NOT NULL, [setid] [varchar](10) NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fds__status] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_admin_debuglog] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_admin_debuglog]( [uid] [int] IDENTITY(1,1) NOT NULL, [machine] [varchar](50) NULL, [type] [varchar](10) NULL, [url] [varchar](255) NULL, [uniquekey] [varchar](5) NULL, [authuser] [varchar](5) NULL, [query] [varchar](max) NULL, [form / content] [nvarchar](max) NULL, [server_variables] [varchar](max) NULL, [cookies] [varchar](max) NULL, [authcookie] [varchar](max) NULL, [files] [varchar](max) NULL, [isdebug] [bit] NULL, [timestamp] [datetime] NULL, CONSTRAINT [PK_fis_admin_debuglog] PRIMARY KEY CLUSTERED ( [uid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_admin_debuglog] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_module_auth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_module_auth]( [id] [bigint] IDENTITY(1,1) NOT NULL, [account] [varchar](50) NULL, [module] [varchar](50) NOT NULL, [group_or_user] [varchar](5) NOT NULL, [isgroup] [bit] NOT NULL, [auth] [int] NOT NULL, CONSTRAINT [PK_fis_module_auth] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_module_auth] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_useraccounts] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_useraccounts]( [useraccount_id] [varchar](5) NOT NULL, [name_enc] [varbinary](260) NOT NULL, [firstname_enc] [varbinary](260) NULL, [title_enc] [varbinary](120) NULL, [gender_enc] [varbinary](100) NULL, [email_enc] [varbinary](350) NOT NULL, [mobile_enc] [varbinary](120) NULL, [password_enc] [varbinary](100) NOT NULL, [language] [varchar](2) NULL, [UserDisabled] [varchar](36) NULL, [DateDisabled] [datetime] NULL, [UserCreated] [varchar](36) NOT NULL, [DateCreated] [datetime] NOT NULL, [UserModified] [varchar](36) NULL, [DateModified] [datetime] NOT NULL, [UserDeleted] [varchar](36) NULL, [DateDeleted] [datetime] NULL, CONSTRAINT [PK_fis_useraccounts] PRIMARY KEY CLUSTERED ( [useraccount_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_useraccounts] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_useraccounts_settings] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_useraccounts_settings]( [useraccount_set_uid] [int] IDENTITY(1,1) NOT NULL, [useraccount_id] [varchar](5) NOT NULL, [key] [varchar](25) NOT NULL, [value] [varchar](255) NULL, [UserModified] [varchar](36) NOT NULL, [DateModified] [datetime] NOT NULL, CONSTRAINT [PK_fis_useraccounts_settings] PRIMARY KEY CLUSTERED ( [useraccount_set_uid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_useraccounts_settings] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_usergroups] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_usergroups]( [usergroup_id] [varchar](5) NOT NULL, [name_enc] [varbinary](600) NOT NULL, [UserCreated] [varchar](36) NOT NULL, [DateCreated] [datetime] NOT NULL, [UserModified] [varchar](36) NOT NULL, [DateModified] [datetime] NOT NULL, [UserDeleted] [varchar](36) NULL, [DateDeleted] [datetime] NULL, CONSTRAINT [PK_fis_usergroups] PRIMARY KEY CLUSTERED ( [usergroup_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_usergroups] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_usergroups_members] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_usergroups_members]( [uid] [int] IDENTITY(1,1) NOT NULL, [usergroup_id] [varchar](5) NULL, [useraccount_id] [varchar](5) NULL, [UserCreated] [varchar](36) NOT NULL, [DateCreated] [datetime] NOT NULL, [UserDeleted] [varchar](36) NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_usergroups_members] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_widget_subscriptions] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_widget_subscriptions]( [uid] [bigint] IDENTITY(1,1) NOT NULL, [account] [varchar](50) NOT NULL, [person_guid] [varchar](36) NOT NULL, [widget_name] [varchar](50) NOT NULL, [display_order] [int] NOT NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](36) NOT NULL, CONSTRAINT [PK_fis_widget_subscriptions] PRIMARY KEY CLUSTERED ( [uid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_widget_subscriptions] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_widgets] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_widgets]( [short_name] [varchar](50) NOT NULL, [account] [varchar](50) NOT NULL, [type] [nvarchar](50) NOT NULL, [name] [nvarchar](255) NOT NULL, [description] [nvarchar](1000) NULL, [sql] [nvarchar](2000) NULL, [sql_admin_columns] [nvarchar](500) NULL, [sql_datatypes] [nvarchar](255) NULL, [url] [nvarchar](500) NULL, [html] [nvarchar](max) NULL, [visible_groups] [varchar](1000) NULL, [visible] [tinyint] NOT NULL, [auth_module] [varchar](50) NULL, [rendering_options] [nvarchar](255) NULL, [server_options] [nvarchar](2000) NULL, [daycache] [bit] NOT NULL, [personalized] [bit] NOT NULL, [safemode] [bit] NOT NULL, [variables] [varchar](1000) NULL, CONSTRAINT [PK_fis_widgets] PRIMARY KEY CLUSTERED ( [short_name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_widgets] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fis_widgets_cache] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fis_widgets_cache]( [account] [varchar](50) NOT NULL, [short_name] [varchar](50) NOT NULL, [person_guid] [varchar](36) NULL, [date] [date] NOT NULL, [data] [nvarchar](max) NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fis_widgets_cache] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fuchs_debug] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fuchs_debug]( [rn] [bigint] IDENTITY(1,1) NOT NULL, [interface] [varchar](50) NOT NULL, [url] [varchar](500) NULL, [data] [nvarchar](max) NULL, [date] [datetime] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fuchs_debug] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fuchs_planner] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fuchs_planner]( [planner_id] [tinyint] IDENTITY(1,1) NOT NULL, [shortname] [varchar](10) NOT NULL, [name] [varchar](100) NULL, [description] [varchar](2000) NULL, [active] [bit] NOT NULL, CONSTRAINT [PK_fuchs_planner] PRIMARY KEY CLUSTERED ( [planner_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fuchs_planner_groups] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fuchs_planner_groups]( [group_id] [int] NOT NULL, [code] AS ([dbo].[ott_b26]([group_id])), [planner_id] [tinyint] NOT NULL, [sequence_order] [tinyint] NOT NULL, [parent_codes] [varchar](50) NULL, [condition] [varchar](50) NULL, [shortname] [varchar](15) NULL, [name] [varchar](100) NULL, [description] [varchar](max) NULL, [selection_type] [varchar](10) NULL, [final] [bit] NOT NULL, [hide] [bit] NOT NULL, CONSTRAINT [PK_fuchs_planner_groups] PRIMARY KEY CLUSTERED ( [group_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner_groups] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fuchs_planner_options] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fuchs_planner_options]( [option_id] [int] IDENTITY(1,1) NOT NULL, [planner_id] [tinyint] NOT NULL, [group_id] [int] NOT NULL, [code] AS (([dbo].[ott_b26]([group_id])+'.')+[dbo].[ott_b26]([option_id])), [subgroup] [varchar](10) NULL, [option_order] [tinyint] NOT NULL, [option_type] [char](1) NULL, [condition] [varchar](100) NULL, [name] [varchar](100) NULL, [description] [varchar](2000) NULL, [tooltip] [varchar](500) NULL, [icon_url] [varchar](max) NULL, [hide] [bit] NOT NULL, CONSTRAINT [PK_fuchs_planner_options] PRIMARY KEY CLUSTERED ( [option_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner_options] TO SCHEMA OWNER GO /****** Object: Table [dbo].[fuchs_planner_traffic] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[fuchs_planner_traffic]( [uid] [bigint] IDENTITY(1,1) NOT NULL, [planner_id] [tinyint] NOT NULL, [sessionid] [varchar](10) NOT NULL, [group_code] [varchar](10) NULL, [values] [nvarchar](4000) NULL, [DateSubmitted] [datetime] NOT NULL, CONSTRAINT [PK_fuchs_planner_traffic] PRIMARY KEY CLUSTERED ( [uid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner_traffic] TO SCHEMA OWNER GO /****** Object: Table [dbo].[inv_backup_6VM7S] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[inv_backup_6VM7S]( [Id] [varchar](10) NOT NULL, [Version] [int] NOT NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NOT NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [varchar](50) NULL, [InvoiceBalance] [numeric](10, 2) NOT NULL, [InvoiceBalance_net] [numeric](10, 2) NOT NULL, [InvoiceVAT_net1] [numeric](10, 2) NOT NULL, [InvoiceVAT_1] [numeric](5, 2) NOT NULL, [InvoiceVAT_net2] [numeric](10, 2) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NOT NULL, [DueDate] [date] NOT NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NOT NULL, [IsSent] [bit] NOT NULL, [IsFinal] [bit] NULL, [IsCanceled] [bit] NULL, [Replaces_InvId] [varchar](50) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](25) NOT NULL, [DateModified] [datetime] NOT NULL, [UserModified] [varchar](25) NOT NULL, [file] [varbinary](max) NULL, [file_guid] [uniqueidentifier] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[inv_backup_6VM7S] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__#customvalues] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__#customvalues]( [Id] [bigint] NOT NULL, [EntityID] [bigint] NOT NULL, [Property] [varchar](255) NOT NULL, [Meta] [varchar](255) NOT NULL, [Value] [varchar](1000) NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__#customvalues] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__#locations] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__#locations]( [Id] [bigint] NOT NULL, [EntityId] [bigint] NOT NULL, [Property] [varchar](255) NOT NULL, [Version] [int] NOT NULL, [AddressString] [nvarchar](255) NULL, [Postal] [nvarchar](255) NULL, [City] [nvarchar](255) NULL, [State] [nvarchar](255) NULL, [Country] [varchar](15) NULL, [Longitude] [numeric](8, 5) NULL, [Latitude] [numeric](8, 5) NULL, [IsValidLocation] [bit] NOT NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__#locations] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__appointments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__appointments]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [State] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [EndDateTime] [datetime] NULL, [StartDateTime] [datetime] NOT NULL, [DrivingDistanceFrom] [int] NULL, [DrivingDistanceTo] [int] NULL, [WasReadOnClientSide] [bit] NOT NULL, [ContactIds] [varchar](max) NULL, [ServiceRequestId] [bigint] NOT NULL, [ContactId] [bigint] NOT NULL, [Note] [nvarchar](max) NULL, CONSTRAINT [PK_mfr__appointment] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__appointments] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__attachments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__attachments]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [URI] [nvarchar](255) NULL, [StepId] [bigint] NOT NULL, CONSTRAINT [PK_mfr__attachment] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__attachments] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__comments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__comments]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [DateOfCreation] [datetime] NOT NULL, [IsInternal] [bit] NOT NULL, [ServiceRequestId] [bigint] NOT NULL, [CompanyId] [bigint] NOT NULL, [Content] [nvarchar](max) NULL, CONSTRAINT [PK_mfr__comment] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__comments] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__costcenters] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__costcenters]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, CONSTRAINT [PK_mfr__costcenter] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__costcenters] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_#customvalues] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_#customvalues]( [Id] [bigint] NULL, [EntityID] [bigint] NULL, [Property] [varchar](255) NULL, [Meta] [varchar](255) NULL, [Value] [varchar](1000) NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_#customvalues] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_#locations] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_#locations]( [Id] [bigint] NULL, [EntityId] [bigint] NULL, [Property] [varchar](255) NULL, [Version] [int] NULL, [AddressString] [nvarchar](255) NULL, [Postal] [nvarchar](255) NULL, [City] [nvarchar](255) NULL, [State] [nvarchar](255) NULL, [Country] [varchar](15) NULL, [Longitude] [numeric](8, 5) NULL, [Latitude] [numeric](8, 5) NULL, [IsValidLocation] [bit] NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_#locations] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_*PartnerSet] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_*PartnerSet]( [Property] [varchar](50) NULL, [PartnerType] [varchar](25) NULL, [PartnerId] [bigint] NULL, [EntityId] [bigint] NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_*PartnerSet] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_appointments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_appointments]( [Id] [bigint] NULL, [Version] [int] NULL, [State] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [EndDateTime] [datetime] NULL, [StartDateTime] [datetime] NULL, [DrivingDistanceFrom] [int] NULL, [DrivingDistanceTo] [int] NULL, [WasReadOnClientSide] [bit] NULL, [ContactIds] [varchar](max) NULL, [ServiceRequestId] [bigint] NULL, [ContactId] [bigint] NULL, [Note] [nvarchar](max) NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_appointments] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_comments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_comments]( [Id] [bigint] NULL, [Version] [int] NULL, [DateOfCreation] [datetime] NULL, [IsInternal] [bit] NULL, [ServiceRequestId] [bigint] NULL, [CompanyId] [bigint] NULL, [Content] [nvarchar](max) NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_comments] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_items] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_items]( [Id] [bigint] NULL, [Version] [int] NULL, [QuantityHours] [numeric](10, 3) NULL, [PlannedQuantityHours] [numeric](10, 3) NULL, [ItemTypeId] [bigint] NULL, [ItemNumber] [varchar](255) NULL, [TrackingId] [varchar](255) NULL, [Manufacture] [varchar](255) NULL, [Price] [numeric](10, 3) NULL, [Costs] [numeric](10, 3) NULL, [NameOrNumber] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [Note] [nvarchar](max) NULL, [ExternalId] [nvarchar](255) NULL, [Discount] [numeric](10, 3) NULL, [VAT] [numeric](10, 3) NULL, [IsManual] [bit] NULL, [SortOrder] [int] NULL, [Type] [varchar](255) NULL, [ServiceRequestId] [bigint] NULL, [ServiceObjectId] [bigint] NULL, [CreatorId] [bigint] NULL, [UnitId] [bigint] NULL, [UnitString] [varchar](50) NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_items] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_steps] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_steps]( [Id] [bigint] NULL, [MobileId] [bigint] NULL, [Version] [int] NULL, [Name] [nvarchar](255) NULL, [IsDone] [bit] NULL, [HasError] [bit] NULL, [TrackingId] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [SortOrder] [int] NULL, [Data] [nvarchar](max) NULL, [DateModifiedOffline] [datetime] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [Comment] [nvarchar](max) NULL, [InternalComment] [nvarchar](max) NULL, [ServiceObjectId] [bigint] NULL, [StepListTemplateId] [bigint] NULL, [ParentId] [bigint] NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_steps] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_stockmovements] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_stockmovements]( [Id] [bigint] NULL, [Version] [int] NULL, [Amount] [numeric](10, 3) NULL, [AmountReceived] [numeric](10, 3) NULL, [ExternalId] [varchar](255) NULL, [ItemId] [bigint] NULL, [ItemTypeId] [bigint] NULL, [StockMovementType] [varchar](255) NULL, [State] [varchar](255) NULL, [ServiceRequestId] [bigint] NULL, [WarehouseId] [bigint] NULL, [DateOfCreation] [datetime] NULL, [DateModified] [datetime] NULL, [TargetDate] [datetime] NULL, [CreatedById] [bigint] NULL, [ConfirmedById] [bigint] NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_stockmovements] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__d_timeevents] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__d_timeevents]( [Id] [bigint] NULL, [Version] [int] NULL, [State] [nvarchar](255) NULL, [IsApproved] [bit] NULL, [TimeEventType] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [DateModified] [datetime] NULL, [StartDateTime] [datetime] NULL, [EndDateTime] [datetime] NULL, [ProposedDrivingDistance] [int] NULL, [ContactId] [bigint] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [DateDeleted] [datetime] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__d_timeevents] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__documents] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__documents]( [Id] [bigint] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [Version] [int] NOT NULL, [State] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [URI] [nvarchar](255) NULL, [IsGlobal] [bit] NOT NULL, [StartDateTime] [datetime] NULL, [EndDateTime] [datetime] NULL, [FileName] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [UploadDate] [datetime] NOT NULL, [IsLink] [bit] NOT NULL, [ContentType] [nvarchar](255) NULL, [HTMLCode] [nvarchar](255) NULL, [ServiceRequestId] [bigint] NOT NULL, [Note] [nvarchar](255) NULL, CONSTRAINT [PK_mfr__document] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__documents] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__items] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__items]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [QuantityHours] [numeric](10, 3) NOT NULL, [PlannedQuantityHours] [numeric](10, 3) NOT NULL, [ItemTypeId] [bigint] NULL, [ItemNumber] [varchar](255) NULL, [TrackingId] [varchar](255) NULL, [Manufacture] [varchar](255) NULL, [Price] [numeric](10, 3) NOT NULL, [Costs] [numeric](10, 3) NULL, [NameOrNumber] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [Note] [nvarchar](max) NULL, [ExternalId] [nvarchar](255) NULL, [Discount] [numeric](10, 3) NOT NULL, [VAT] [numeric](10, 3) NOT NULL, [IsManual] [bit] NOT NULL, [SortOrder] [int] NOT NULL, [Type] [varchar](255) NULL, [ServiceRequestId] [bigint] NOT NULL, [ServiceObjectId] [bigint] NOT NULL, [CreatorId] [bigint] NOT NULL, [UnitId] [bigint] NULL, [UnitString] [varchar](50) NULL, CONSTRAINT [PK_mfr__item] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__items] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__itemtypes] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__itemtypes]( [Id] [bigint] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [Version] [int] NOT NULL, [Costs] [numeric](10, 3) NOT NULL, [Description] [nvarchar](max) NULL, [ListPrice] [numeric](10, 3) NOT NULL, [Manufacture] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [ItemNumber] [nvarchar](255) NULL, [NameOrNumber] [nvarchar](1000) NULL, [GlobalTradeItemNr] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [Price] [numeric](10, 3) NOT NULL, [VAT] [numeric](10, 3) NOT NULL, [IsPortalOnly] [bit] NOT NULL, [Discount] [numeric](10, 3) NOT NULL, [DateModified] [datetime] NOT NULL, [IsDiscontinued] [bit] NOT NULL, [IsWarehouse] [bit] NOT NULL, [UnitId] [bigint] NULL, [UnitString] [nvarchar](255) NULL, CONSTRAINT [PK_mfr__itemtype] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__itemtypes] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__itemunits] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__itemunits]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, CONSTRAINT [PK_mfr__itemunit] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__itemunits] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__products] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__products]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [SubKey] [nvarchar](255) NULL, [Description] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [MappingId] [nvarchar](255) NULL, [CustomValueStepTemplateId] [bigint] NOT NULL, CONSTRAINT [PK_mfr__product] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__products] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__qualifications] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__qualifications]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, CONSTRAINT [PK_mfr__qualification] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__qualifications] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__reports] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__reports]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [DateOfCreation] [datetime] NOT NULL, [URI] [nvarchar](255) NULL, [DocumentName] [nvarchar](255) NULL, [FileTypeString] [nvarchar](255) NULL, [ReportDefinitionCode] [nvarchar](255) NULL, [ServiceObjectId] [bigint] NOT NULL, [CanBeDeleted] [bit] NOT NULL, [InvoiceBalance] [numeric](10, 3) NOT NULL, [InvoiceId] [nvarchar](255) NULL, [DueDate] [datetime] NOT NULL, [IsPayed] [bit] NOT NULL, [IsInvoice] [bit] NOT NULL, [IsCanceled] [bit] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, CONSTRAINT [PK_mfr__report] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__reports] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__serviceobjects] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__serviceobjects]( [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NOT NULL, [DateModified] [datetime] NOT NULL, [ExternalId] [nvarchar](255) NULL, [MappingId] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [Version] [int] NOT NULL, [CreateGeoLocation] [bit] NOT NULL, [IsWarehouse] [bit] NOT NULL, [ParentServiceObjectId] [bigint] NOT NULL, [CompanyId] [bigint] NOT NULL, [ProductId] [bigint] NOT NULL, CONSTRAINT [PK_mfr__serviceobject] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__serviceobjects] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__steplisttemplateinstances] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__steplisttemplateinstances]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [ServiceRequestId] [bigint] NULL, [TemplateId] [bigint] NULL, CONSTRAINT [PK_mfr__steplisttemplateinstance] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__steplisttemplateinstances] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__steplisttemplates] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__steplisttemplates]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [MappingId] [nvarchar](255) NULL, [DateModified] [datetime] NULL, [IsReleased] [bit] NOT NULL, [IsDurable] [bit] NOT NULL, CONSTRAINT [PK_mfr__steplisttemplate] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__steplisttemplates] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__steps] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__steps]( [Id] [bigint] NOT NULL, [MobileId] [bigint] NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [IsDone] [bit] NOT NULL, [HasError] [bit] NOT NULL, [TrackingId] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [SortOrder] [int] NOT NULL, [Data] [nvarchar](max) NULL, [DateModifiedOffline] [datetime] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [Comment] [nvarchar](max) NULL, [InternalComment] [nvarchar](max) NULL, [ServiceObjectId] [bigint] NULL, [StepListTemplateId] [bigint] NULL, [ParentId] [bigint] NULL, CONSTRAINT [PK_mfr__step] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__steps] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__stockmovements] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__stockmovements]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Amount] [numeric](10, 3) NOT NULL, [AmountReceived] [numeric](10, 3) NOT NULL, [ExternalId] [varchar](255) NULL, [ItemId] [bigint] NULL, [ItemTypeId] [bigint] NULL, [StockMovementType] [varchar](255) NULL, [State] [varchar](255) NULL, [ServiceRequestId] [bigint] NOT NULL, [WarehouseId] [bigint] NOT NULL, [DateOfCreation] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL, [TargetDate] [datetime] NOT NULL, [CreatedById] [bigint] NOT NULL, [ConfirmedById] [bigint] NOT NULL, CONSTRAINT [PK_mfr__stockmovement] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__stockmovements] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__tags] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__tags]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [ColorDefinition] [nvarchar](255) NULL, [Type] [nvarchar](255) NOT NULL, CONSTRAINT [PK_mfr__tag] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__tags] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__timeevents] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__timeevents]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [State] [nvarchar](255) NULL, [IsApproved] [bit] NOT NULL, [TimeEventType] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [StartDateTime] [datetime] NOT NULL, [EndDateTime] [datetime] NOT NULL, [ProposedDrivingDistance] [int] NOT NULL, [ContactId] [bigint] NOT NULL, [ServiceRequestId] [bigint] NOT NULL, [Description] [nvarchar](max) NULL, CONSTRAINT [PK_mfr__timeevent] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__timeevents] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__users] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__users]( [Id] [bigint] NOT NULL, [Version] [int] NOT NULL, [UserName] [nvarchar](255) NULL, [IsSystem] [bit] NOT NULL, [CreationDate] [datetime] NOT NULL, [IsApproved] [bit] NOT NULL, [ContactId] [bigint] NOT NULL, [PreferedLanguage] [nvarchar](255) NULL, [EmailChannelEnabled] [bit] NOT NULL, [HasFullScreenPreference] [bit] NOT NULL, [TimeZone] [int] NOT NULL, [PreferedCulture] [nvarchar](255) NULL, [IsActive] [bit] NOT NULL, [IsMobile] [bit] NOT NULL, [LastLoginDate] [datetime] NULL, [UserGuideProgress] [nvarchar](255) NULL, [DashboardSettings] [nvarchar](max) NULL, CONSTRAINT [PK_mfr__user] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__users] TO SCHEMA OWNER GO /****** Object: Table [dbo].[mfr__xl__servicerequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[mfr__xl__servicerequests]( [servicerequest_id] [bigint] NOT NULL, [invoice_id] [bigint] NOT NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[mfr__xl__servicerequests] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_archive__items] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_archive__items]( [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [ocms_pid] [bigint] NULL, [name] [nvarchar](255) NULL, [view] [bit] NOT NULL, [template_id] [bigint] NULL, [hide] [bit] NOT NULL, [order] [int] NOT NULL, [DateCreated] [datetime] NULL, [DateModified] [datetime] NULL, [DateDeleted] [datetime] NULL, [UserDeleted] [varchar](36) NULL ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_archive__items] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_archive__properties] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_archive__properties]( [ocms_pid] [bigint] NULL, [ocms_iid] [bigint] NULL, [key] [varchar](50) NULL, [value] [nvarchar](max) NULL, [locale] [varchar](5) NULL, [DateCreated] [datetime] NULL, [DateModified] [datetime] NULL, [DateDeleted] [datetime] NULL, [UserDeleted] [varchar](36) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_archive__properties] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_debug] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_debug]( [uid] [bigint] IDENTITY(1,1) NOT NULL, [machine] [varchar](50) NULL, [error] [varchar](2000) NULL, [exception] [varchar](max) NULL, [procedure] [varchar](255) NULL, [authuser] [varchar](25) NULL, [data] [nvarchar](max) NULL, [isdebug] [bit] NULL, [timestamp] [datetime] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_debug] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_items] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_items]( [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [ocms_pid] [bigint] NULL, [name] [nvarchar](255) NULL, [view] [bit] NOT NULL, [template_id] [bigint] NULL, [hide] [bit] NOT NULL, [order] [int] NOT NULL, [DateCreated] [datetime] NULL, [DateModified] [datetime] NULL, CONSTRAINT [PK_ocms_items] PRIMARY KEY CLUSTERED ( [ocms_iid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_items] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_log__properties] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_log__properties]( [ocms_pid] [bigint] NULL, [action] [varchar](50) NULL, [n_ocms_iid] [bigint] NULL, [n_key] [varchar](50) NULL, [n_value] [nvarchar](max) NULL, [n_locale] [varchar](5) NULL, [n_DateCreated] [datetime] NULL, [n_DateModified] [datetime] NULL, [n_DateDeleted] [datetime] NULL, [n_UserDeleted] [varchar](36) NULL, [o_ocms_iid] [bigint] NULL, [o_key] [varchar](50) NULL, [o_value] [nvarchar](max) NULL, [o_locale] [varchar](5) NULL, [o_DateCreated] [datetime] NULL, [o_DateModified] [datetime] NULL, [o_DateDeleted] [datetime] NULL, [o_UserDeleted] [varchar](36) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_log__properties] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_navigation] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_navigation]( [ocms_nid] [bigint] IDENTITY(1,1) NOT NULL, [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [locale] [varchar](5) NOT NULL, [alias] [varchar](25) NOT NULL, CONSTRAINT [PK_ocms_navigation] PRIMARY KEY CLUSTERED ( [ocms_nid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_navigation] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_properties] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_properties]( [ocms_pid] [bigint] NOT NULL, [ocms_iid] [bigint] NOT NULL, [key] [varchar](50) NULL, [value] [nvarchar](max) NOT NULL, [locale] [varchar](5) NULL, [DateCreated] [datetime] NULL, [DateModified] [datetime] NULL, CONSTRAINT [PK_ocms_properties] PRIMARY KEY CLUSTERED ( [ocms_pid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_properties] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_settings] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_settings]( [ocms_set] [bigint] IDENTITY(1,1) NOT NULL, [key] [varchar](25) NOT NULL, [value] [varchar](2000) NULL, CONSTRAINT [PK_ocms_settings] PRIMARY KEY CLUSTERED ( [ocms_set] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_settings] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_template_properties] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_template_properties]( [ocms_tpid] [bigint] NOT NULL, [ocms_tid] [bigint] NOT NULL, [key] [varchar](50) NOT NULL, [mandatory] [bit] NOT NULL, [type] [varchar](50) NOT NULL, [default] [nvarchar](max) NULL, [condition] [varchar](max) NULL, [order] [int] NOT NULL, CONSTRAINT [PK_ocms_template_properties] PRIMARY KEY CLUSTERED ( [ocms_tpid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_template_properties] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_templates] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_templates]( [ocms_tid] [bigint] IDENTITY(1,1) NOT NULL, [name] [varchar](255) NULL, [partial_view] [varchar](255) NULL, CONSTRAINT [PK_ocms_templates] PRIMARY KEY CLUSTERED ( [ocms_tid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_templates] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_translations] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_translations]( [ocms_tln] [bigint] IDENTITY(1,1) NOT NULL, [context_typ] [nvarchar](15) NOT NULL, [context] [bigint] NULL, [value] [nvarchar](255) NOT NULL, [translation] [nvarchar](255) NOT NULL, [locale] [varchar](5) NOT NULL, CONSTRAINT [PK_ocms_translations] PRIMARY KEY CLUSTERED ( [ocms_tln] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_translations] TO SCHEMA OWNER GO /****** Object: Table [dbo].[ocms_useraccounts] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ocms_useraccounts]( [useraccount_id] [varchar](5) NOT NULL, [name_enc] [varbinary](600) NOT NULL, [email_enc] [varbinary](350) NOT NULL, [mobile_enc] [varbinary](120) NULL, [password_enc] [varbinary](100) NOT NULL, [UserDisabled] [varchar](36) NULL, [DateDisabled] [datetime] NULL, [UserCreated] [varchar](36) NOT NULL, [DateCreated] [datetime] NOT NULL, [UserModified] [varchar](36) NULL, [DateModified] [datetime] NOT NULL, [UserDeleted] [varchar](36) NULL, [DateDeleted] [datetime] NULL, CONSTRAINT [PK_ocms_useraccounts] PRIMARY KEY CLUSTERED ( [useraccount_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[ocms_useraccounts] TO SCHEMA OWNER GO /****** Object: Table [dbo].[t_ves6u_mfr__servicerequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[t_ves6u_mfr__servicerequests]( [setid] [nvarchar](max) NULL, [Id] [bigint] NULL, [Name] [nvarchar](max) NULL, [ExternalId] [nvarchar](max) NULL, [InvoiceId] [nvarchar](max) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](max) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](max) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](max) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER AUTHORIZATION ON [dbo].[t_ves6u_mfr__servicerequests] TO SCHEMA OWNER GO /****** Object: Index [fds__bankingtransactions__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [fds__bankingtransactions__ix1] ON [dbo].[fds__bankingtransactions] ( [uid] ASC ) INCLUDE([Amount]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [fds__invoice_items__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [fds__invoice_items__ix1] ON [dbo].[fds__invoice_items] ( [InvId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO /****** Object: Index [fds__invoice_servicerequests__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [fds__invoice_servicerequests__ix1] ON [dbo].[fds__invoice_servicerequests] ( [mfr__servicerequest] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ARITHABORT ON SET CONCAT_NULL_YIELDS_NULL ON SET QUOTED_IDENTIFIER ON SET ANSI_NULLS ON SET ANSI_PADDING ON SET ANSI_WARNINGS ON SET NUMERIC_ROUNDABORT OFF GO /****** Object: Index [fds__invoices__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [fds__invoices__ix1] ON [dbo].[fds__invoices] ( [IsFinal] ASC, [InvoiceBalance] ASC ) INCLUDE([IsPayed],[IsCanceled],[DateFinalized]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO /****** Object: Index [IX_fuchs_planner_groups] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [IX_fuchs_planner_groups] ON [dbo].[fuchs_planner_groups] ( [planner_id] ASC, [sequence_order] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO /****** Object: Index [IX_fuchs_planner_options] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [IX_fuchs_planner_options] ON [dbo].[fuchs_planner_options] ( [planner_id] ASC, [group_id] ASC, [option_order] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [fuchs_planner_traffic__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [fuchs_planner_traffic__ix1] ON [dbo].[fuchs_planner_traffic] ( [sessionid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [fuchs_planner_traffic__ix2] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [fuchs_planner_traffic__ix2] ON [dbo].[fuchs_planner_traffic] ( [planner_id] ASC, [sessionid] ASC ) INCLUDE([group_code],[DateSubmitted]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__#locations__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__#locations__ix1] ON [dbo].[mfr__#locations] ( [EntityId] ASC, [Property] ASC ) INCLUDE([AddressString],[Postal],[City],[Country]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO /****** Object: Index [mfr__#locations__ix2] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__#locations__ix2] ON [dbo].[mfr__#locations] ( [Id] ASC ) INCLUDE([AddressString],[Postal],[City],[State],[Country],[Longitude],[Latitude]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__*PartnerSet__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__*PartnerSet__ix1] ON [dbo].[mfr__*PartnerSet] ( [Property] ASC ) INCLUDE([PartnerId],[EntityId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__*PartnerSet__ix2] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__*PartnerSet__ix2] ON [dbo].[mfr__*PartnerSet] ( [EntityId] ASC, [Property] ASC ) INCLUDE([PartnerId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__*PartnerSet__ix3] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__*PartnerSet__ix3] ON [dbo].[mfr__*PartnerSet] ( [Property] ASC, [PartnerId] ASC ) INCLUDE([EntityId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__appointments__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__appointments__ix1] ON [dbo].[mfr__appointments] ( [State] ASC ) INCLUDE([EndDateTime],[StartDateTime],[ServiceRequestId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__appointments__ix2] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__appointments__ix2] ON [dbo].[mfr__appointments] ( [State] ASC, [ServiceRequestId] ASC ) INCLUDE([EndDateTime],[StartDateTime]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO /****** Object: Index [mfr__contacts__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__contacts__ix1] ON [dbo].[mfr__contacts] ( [CompanyId] ASC ) INCLUDE([CustomValues],[FirstName],[LastName],[Email],[JobTitle],[MobilePhone],[Telephone],[Fax],[Note],[DateModified],[Version],[IsUser],[ExternalId],[Gender],[UserId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__invoices__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__invoices__ix1] ON [dbo].[mfr__invoices] ( [Id] ASC, [InvoiceId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO /****** Object: Index [mfr__items__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__items__ix1] ON [dbo].[mfr__items] ( [ServiceRequestId] ASC ) INCLUDE([QuantityHours],[Price]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [mfr__servicerequests__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__servicerequests__ix1] ON [dbo].[mfr__servicerequests] ( [InvoiceId] ASC ) INCLUDE([Name],[DateOfCreation],[CustomerId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO /****** Object: Index [mfr__steps__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE NONCLUSTERED INDEX [mfr__steps__ix1] ON [dbo].[mfr__steps] ( [ServiceRequestId] ASC ) INCLUDE([MobileId],[Version],[Name],[IsDone],[HasError],[TrackingId],[Type],[SortOrder],[Data],[DateModifiedOffline],[Description],[Comment],[InternalComment],[ServiceObjectId],[StepListTemplateId],[ParentId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [ocms_items__ix0] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [ocms_items__ix0] ON [dbo].[ocms_items] ( [parent_iid] ASC, [name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [ocms_items__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [ocms_items__ix1] ON [dbo].[ocms_items] ( [name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [ocms_navigation__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [ocms_navigation__ix1] ON [dbo].[ocms_navigation] ( [ocms_iid] ASC, [locale] ASC, [alias] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [ocms_template_properties__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [ocms_template_properties__ix1] ON [dbo].[ocms_template_properties] ( [ocms_tid] ASC, [key] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [ocms_templates__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [ocms_templates__ix1] ON [dbo].[ocms_templates] ( [name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO SET ANSI_PADDING ON GO /****** Object: Index [ocms_useraccounts__ix1] Script Date: 13/10/2022 21:16:40 ******/ CREATE UNIQUE NONCLUSTERED INDEX [ocms_useraccounts__ix1] ON [dbo].[ocms_useraccounts] ( [email_enc] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO ALTER TABLE [dbo].[fds__admin_activity] ADD CONSTRAINT [DF_fds__admin_activity_timestamp] DEFAULT (getutcdate()) FOR [timestamp] GO ALTER TABLE [dbo].[fds__invoices] ADD CONSTRAINT [DF_fds__invoices_Version] DEFAULT ((0)) FOR [Version] GO ALTER TABLE [dbo].[fds__invoices] ADD CONSTRAINT [DF_fds__invoices_InvoiceTitle] DEFAULT ('Rechnung') FOR [InvoiceTitle] GO ALTER TABLE [dbo].[fds__invoices] ADD CONSTRAINT [DF_fds__invoices_IsPayed] DEFAULT ((0)) FOR [IsPayed] GO ALTER TABLE [dbo].[fds__invoices] ADD CONSTRAINT [DF_fds__invoices_IsSent] DEFAULT ((0)) FOR [IsSent] GO ALTER TABLE [dbo].[fds__invoices] ADD CONSTRAINT [DF_fds__invoices_external] DEFAULT ((0)) FOR [IsExternal] GO ALTER TABLE [dbo].[fds__invoices] ADD CONSTRAINT [DF_fds__invoices_file_guid] DEFAULT (newid()) FOR [file_guid] GO ALTER TABLE [dbo].[fds__mfr_updaterequests] ADD CONSTRAINT [DF_fds__mfr_updaterequests_date_requested] DEFAULT (getutcdate()) FOR [date_requested] GO ALTER TABLE [dbo].[fds__payments] ADD CONSTRAINT [DF_fds__payments_IsAllocated] DEFAULT ((0)) FOR [AllocationStatus] GO ALTER TABLE [dbo].[fds__reminder] ADD CONSTRAINT [DF_fds__reminder_Version] DEFAULT ((0)) FOR [Version] GO ALTER TABLE [dbo].[fds__reminder] ADD CONSTRAINT [DF_fds__reminder_IsSent] DEFAULT ((0)) FOR [IsSent] GO ALTER TABLE [dbo].[fis_module_auth] ADD CONSTRAINT [DF_fis_module_auth_auth] DEFAULT ((1)) FOR [auth] GO ALTER TABLE [dbo].[fis_useraccounts] ADD CONSTRAINT [DF_fis_useraccounts_language] DEFAULT ('de') FOR [language] GO ALTER TABLE [dbo].[fis_useraccounts] ADD CONSTRAINT [DF_fis_useraccounts_DateCreated] DEFAULT (getutcdate()) FOR [DateCreated] GO ALTER TABLE [dbo].[fis_useraccounts] ADD CONSTRAINT [DF_fis_useraccounts_DateModified] DEFAULT (getutcdate()) FOR [DateModified] GO ALTER TABLE [dbo].[fis_widget_subscriptions] ADD CONSTRAINT [DF_fis_widget_subscriptions_display_order] DEFAULT ((0)) FOR [display_order] GO ALTER TABLE [dbo].[fis_widget_subscriptions] ADD CONSTRAINT [DF_fis_widget_subscriptions_DateCreated] DEFAULT (getutcdate()) FOR [DateCreated] GO ALTER TABLE [dbo].[fis_widget_subscriptions] ADD CONSTRAINT [DF_fis_widget_subscriptions_UserCreated] DEFAULT ('') FOR [UserCreated] GO ALTER TABLE [dbo].[fis_widgets] ADD CONSTRAINT [DF_fis_widgets_visible] DEFAULT ((1)) FOR [visible] GO ALTER TABLE [dbo].[fis_widgets] ADD CONSTRAINT [DF_fis_widgets_daychache] DEFAULT ((0)) FOR [daycache] GO ALTER TABLE [dbo].[fis_widgets] ADD CONSTRAINT [DF_fis_widgets_personalized] DEFAULT ((0)) FOR [personalized] GO ALTER TABLE [dbo].[fis_widgets] ADD CONSTRAINT [DF_fis_widgets_safemode] DEFAULT ((0)) FOR [safemode] GO ALTER TABLE [dbo].[fuchs_debug] ADD CONSTRAINT [DF_fuchs_debug_date] DEFAULT (getutcdate()) FOR [date] GO ALTER TABLE [dbo].[fuchs_planner] ADD CONSTRAINT [DF_fuchs_planner_active] DEFAULT ((1)) FOR [active] GO ALTER TABLE [dbo].[fuchs_planner_groups] ADD CONSTRAINT [DF_fuchs_planner_groups_order] DEFAULT ((0)) FOR [sequence_order] GO ALTER TABLE [dbo].[fuchs_planner_groups] ADD CONSTRAINT [DF_fuchs_planner_groups_final] DEFAULT ((0)) FOR [final] GO ALTER TABLE [dbo].[fuchs_planner_groups] ADD CONSTRAINT [DF_fuchs_planner_groups_hide] DEFAULT ((0)) FOR [hide] GO ALTER TABLE [dbo].[fuchs_planner_options] ADD CONSTRAINT [DF_Table_1_item_oder] DEFAULT ((0)) FOR [option_order] GO ALTER TABLE [dbo].[fuchs_planner_options] ADD CONSTRAINT [DF_fuchs_planner_options_hide] DEFAULT ((0)) FOR [hide] GO ALTER TABLE [dbo].[fuchs_planner_traffic] ADD CONSTRAINT [DF_fuchs_planner_traffic_DateSubmitted] DEFAULT (getutcdate()) FOR [DateSubmitted] GO ALTER TABLE [dbo].[mfr__invoices] ADD CONSTRAINT [DF_mfr__invoices_file_guid] DEFAULT (newid()) FOR [file_guid] GO ALTER TABLE [dbo].[ocms_debug] ADD CONSTRAINT [DF_ocms_debug_timestamp] DEFAULT (getutcdate()) FOR [timestamp] GO ALTER TABLE [dbo].[ocms_items] ADD CONSTRAINT [DF_ocms_items_view] DEFAULT ((0)) FOR [view] GO ALTER TABLE [dbo].[ocms_items] ADD CONSTRAINT [DF_ocms_items_hide] DEFAULT ((0)) FOR [hide] GO ALTER TABLE [dbo].[ocms_items] ADD CONSTRAINT [DF_ocms_items_order] DEFAULT ((0)) FOR [order] GO ALTER TABLE [dbo].[ocms_items] ADD CONSTRAINT [DF_ocms_items_DateCreated] DEFAULT (getutcdate()) FOR [DateCreated] GO ALTER TABLE [dbo].[ocms_items] ADD CONSTRAINT [DF_ocms_items_DateModified] DEFAULT (getutcdate()) FOR [DateModified] GO ALTER TABLE [dbo].[ocms_properties] ADD CONSTRAINT [DF_ocms_properties_DateCreated] DEFAULT (getutcdate()) FOR [DateCreated] GO ALTER TABLE [dbo].[ocms_properties] ADD CONSTRAINT [DF_ocms_properties_DateModified] DEFAULT (getutcdate()) FOR [DateModified] GO ALTER TABLE [dbo].[ocms_template_properties] ADD CONSTRAINT [DF_ocms_template_properties_mandatory] DEFAULT ((0)) FOR [mandatory] GO ALTER TABLE [dbo].[ocms_template_properties] ADD CONSTRAINT [DF_ocms_template_properties_order] DEFAULT ((0)) FOR [order] GO ALTER TABLE [dbo].[ocms_useraccounts] ADD CONSTRAINT [DF_ocms_useraccounts_DateCreated] DEFAULT (getutcdate()) FOR [DateCreated] GO ALTER TABLE [dbo].[ocms_useraccounts] ADD CONSTRAINT [DF_ocms_useraccounts_DateModified] DEFAULT (getutcdate()) FOR [DateModified] GO ALTER TABLE [dbo].[fuchs_planner_groups] WITH CHECK ADD CONSTRAINT [FK_fuchs_planner_groups_fuchs_planner] FOREIGN KEY([planner_id]) REFERENCES [dbo].[fuchs_planner] ([planner_id]) GO ALTER TABLE [dbo].[fuchs_planner_groups] CHECK CONSTRAINT [FK_fuchs_planner_groups_fuchs_planner] GO ALTER TABLE [dbo].[fuchs_planner_groups] WITH CHECK ADD CONSTRAINT [FK_fuchs_planner_groups_fuchs_planner_groups] FOREIGN KEY([group_id]) REFERENCES [dbo].[fuchs_planner_groups] ([group_id]) GO ALTER TABLE [dbo].[fuchs_planner_groups] CHECK CONSTRAINT [FK_fuchs_planner_groups_fuchs_planner_groups] GO ALTER TABLE [dbo].[fuchs_planner_options] WITH CHECK ADD CONSTRAINT [FK_fuchs_planner_options_fuchs_planner] FOREIGN KEY([planner_id]) REFERENCES [dbo].[fuchs_planner] ([planner_id]) GO ALTER TABLE [dbo].[fuchs_planner_options] CHECK CONSTRAINT [FK_fuchs_planner_options_fuchs_planner] GO ALTER TABLE [dbo].[fuchs_planner_options] WITH CHECK ADD CONSTRAINT [FK_fuchs_planner_options_fuchs_planner_groups] FOREIGN KEY([group_id]) REFERENCES [dbo].[fuchs_planner_groups] ([group_id]) GO ALTER TABLE [dbo].[fuchs_planner_options] CHECK CONSTRAINT [FK_fuchs_planner_options_fuchs_planner_groups] GO ALTER TABLE [dbo].[ocms_items] WITH CHECK ADD CONSTRAINT [FK_ocms_items_ocms_items] FOREIGN KEY([ocms_iid]) REFERENCES [dbo].[ocms_items] ([ocms_iid]) GO ALTER TABLE [dbo].[ocms_items] CHECK CONSTRAINT [FK_ocms_items_ocms_items] GO ALTER TABLE [dbo].[ocms_items] WITH CHECK ADD CONSTRAINT [FK_ocms_items_ocms_properties] FOREIGN KEY([ocms_pid]) REFERENCES [dbo].[ocms_properties] ([ocms_pid]) GO ALTER TABLE [dbo].[ocms_items] CHECK CONSTRAINT [FK_ocms_items_ocms_properties] GO ALTER TABLE [dbo].[ocms_items] WITH CHECK ADD CONSTRAINT [FK_ocms_items_ocms_templates] FOREIGN KEY([template_id]) REFERENCES [dbo].[ocms_templates] ([ocms_tid]) GO ALTER TABLE [dbo].[ocms_items] CHECK CONSTRAINT [FK_ocms_items_ocms_templates] GO ALTER TABLE [dbo].[ocms_items] WITH CHECK ADD CONSTRAINT [FK_ocms_items_parent__ocms_items] FOREIGN KEY([parent_iid]) REFERENCES [dbo].[ocms_items] ([ocms_iid]) GO ALTER TABLE [dbo].[ocms_items] CHECK CONSTRAINT [FK_ocms_items_parent__ocms_items] GO ALTER TABLE [dbo].[ocms_properties] WITH CHECK ADD CONSTRAINT [FK_ocms_properties_ocms_items] FOREIGN KEY([ocms_iid]) REFERENCES [dbo].[ocms_items] ([ocms_iid]) ON DELETE CASCADE GO ALTER TABLE [dbo].[ocms_properties] CHECK CONSTRAINT [FK_ocms_properties_ocms_items] GO ALTER TABLE [dbo].[ocms_template_properties] WITH CHECK ADD CONSTRAINT [FK_ocms_template_properties_ocms_items] FOREIGN KEY([ocms_tid]) REFERENCES [dbo].[ocms_templates] ([ocms_tid]) GO ALTER TABLE [dbo].[ocms_template_properties] CHECK CONSTRAINT [FK_ocms_template_properties_ocms_items] GO /****** Object: StoredProcedure [dbo].[backup__fds__createCredit_simple] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__createCredit_simple] @InvId varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createCredit_simple' ,@authuser , 'invid: ' + ISNULL(@InvId, '')); DECLARE @now datetime = GETDATE(); DECLARE @today date = CAST(@now as date); DECLARE @newid varchar(10) = [dbo].[fds__fn_invoice_id](); DECLARE @inv_DocumentName varchar(50), @inv_DateFinalized datetime, @inv_vat numeric(5,2), @inv_net numeric(10,3); IF EXISTS (SELECT 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1) BEGIN SELECT @inv_DocumentName = [documentname], @inv_DateFinalized = [DateFinalized], @inv_vat = [InvoiceVAT_1], @inv_net = 1 FROM [dbo].[fds__invoices] WHERE [id] = @InvId INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified]) SELECT [Id] = @newid ,[Version] = 0 ,[InvoiceId] = NULL ,[InvoiceType] = 'g' ,[InvoiceTitle] = 'Gutschrift' ,[DocumentName] = NULL ,[InvoiceBalance] = (@inv_net * -1) * (1 + 0.01 * ISNULL(@inv_vat,19)) ,[InvoiceBalance_net] = (@inv_net * -1) ,[InvoiceVAT_net1] = (@inv_net * -1) * (0.01 * ISNULL(@inv_vat,19)) ,[InvoiceVAT_1] = @inv_net ,[InvoiceVAT_net2] = null ,[InvoiceVAT_2] = null ,[PaymentTerm] ,[DueDate] = @today ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] = NULL ,[IsPayed] = 0 ,[IsSent] = 0 ,[Replaces_InvId] = @InvId ,[CustomValues] ,[DateSent] = NULL ,[UserSent] = @authuser ,[DateFinalized] = NULL ,[UserFinalized] = NULL ,[DateCancelled] = NULL ,[UserCancelled] = NULL ,[DateCreated] = @now ,[UserCreated] = @authuser ,[DateModified] = @now ,[UserModified] = @authuser FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1; END ELSE IF EXISTS (SELECT 0 FROM [dbo].[mfr__invoices] as _i where TRY_CAST(_i.[Id] as varchar(20)) = @InvId AND [FileType] in ('PdfInvoice','PdfPartialInvoice')) BEGIN SELECT @inv_DocumentName = [documentname], @inv_DateFinalized = [DateOfCreation] , @inv_vat = CASE WHEN ISNULL([InvoiceBalanceNetto], 0) <> 0 THEN (([InvoiceBalance] / [InvoiceBalanceNetto]) - 1)*100 ELSE (SELECT TOP(1) TRY_CAST([value] as numeric(5,2)) FROM [dbo].[fds__admin_settings] as st where st.[type] = 'defaults' and st.[key] = 'vat') END , @inv_net = 1 --[InvoiceBalanceNetto] FROM [dbo].[mfr__invoices] as _i where TRY_CAST(_i.[Id] as varchar(20)) = @InvId AND [FileType] in ('PdfInvoice','PdfPartialInvoice'); INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified]) SELECT [Id] = @newid ,[Version] = 0 ,[InvoiceId] = NULL ,[InvoiceType] = 'g' ,[InvoiceTitle] = 'Gutschrift' ,[DocumentName] = NULL ,[InvoiceBalance] = (@inv_net * -1) * (1 + 0.01 * ISNULL(@inv_vat,19)) ,[InvoiceBalance_net] = (@inv_net * -1) ,[InvoiceVAT_net1] = (@inv_net * -1) * (0.01 * ISNULL(@inv_vat,19)) ,[InvoiceVAT_1] = @inv_vat ,[InvoiceVAT_net2] = NULL ,[InvoiceVAT_2] = NULL ,[PaymentTerm] = '10wd' ,[DueDate] = _i.DueDate ,[CustomerId] = (SELECT TOP(1) [partnerid] from [mfr__*PartnerSet] as ps where ps.[Property] = 'Invoice:Customer' and ps.[EntityId] = _i.[id]) ,[SendToAddress] = NULL ,[SendToEmail] = NULL ,[ProvisionPeriod] = null ,[ProvisionLocation] = NULL ,[PaymentStatus] = NULL ,[IsPayed] = 0 ,[IsSent] = 0 ,[Replaces_InvId] = @InvId ,[CustomValues] = null ,[DateSent] = NULL ,[UserSent] = @authuser ,[DateFinalized] = NULL ,[UserFinalized] = NULL ,[DateCancelled] = NULL ,[UserCancelled] = NULL ,[DateCreated] = @now ,[UserCreated] = @authuser ,[DateModified] = @now ,[UserModified] = @authuser FROM [dbo].[mfr__invoices] as _i where TRY_CAST(_i.[Id] as varchar(20)) = @InvId AND [FileType] in ('PdfInvoice','PdfPartialInvoice'); UPDATE [dbo].[fds__invoices] SET [SendToAddress] = [dbo].[fds__getCompanyNameAddress]([CustomerId]), [SendToEmail] = [dbo].[fds__getCompanyEmail]([CustomerId]) WHERE [Id] = @newid; END -- continue creating storno DECLARE @inv_srq [dbo].[fds__tt__invoice_servicerequests]; INSERT INTO [dbo].[fds__invoice_servicerequests] ([InvId] ,[mfr__servicerequest] ,[title] ,[value_net] ,[SortOrder]) OUTPUT inserted.* INTO @inv_srq SELECT [InvId] = [id] ,NULL -- ,'Gutschrift' ,(@inv_net * -1) ,0 FROM [dbo].[fds__invoices] WHERE [id] = @newid; INSERT INTO [dbo].[fds__invoice_items] ([InvId] ,[InvRqId] ,[mfr__item] ,[reference_InvId] ,[Type] ,[Position] ,[Quantity] ,[Text] ,[value] ,[value_total] ,[vat] ,[value_service] ,[det] ,[SortOrder]) SELECT @newid -- ,[id]-- ,NULL -- ,@InvId -- ,'CreditInvoice' -- ,NULL -- ,'1' --- ,[Text] = '

' + 'Gutschrift zu der ' + REPLACE(@inv_DocumentName, '.pdf','') + ' vom ' + FORMAT(@inv_dateFinalized, 'dd.MM.yyyy', 'de-de') + '

' ,[value] = (@inv_net * -1) ,[value_total] = (@inv_net * -1) ,[vat] = @inv_vat ,0 -- ,1 -- ,1 --) FROM @inv_srq; INSERT INTO [dbo].[fds__invoice_details] ([InvId] ,[InvoiceService_net] ,[InvoiceService_VAT] ,[AllocatedTo_InvId] ,[StornoTo_InvId]) VALUES( @newid ,NULL --[InvoiceService_net] ,NULL --[InvoiceService_VAT] ,NULL --[AllocatedTo_InvId] ,@InvId --[StornoTo_InvId] ); EXECUTE [dbo].[fds__getInvoice] @newid, @authuser; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__createCredit_simple] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__createReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__createReminder] @InvId varchar(15) , @type varchar(3) , @amount numeric(10,3) , @amount_payed numeric(10,3) , @SendToAddress [nvarchar](1000) , @SendToEmail [nvarchar](255) , @subject nvarchar(255) , @text nvarchar(2000) , @authuser varchar(25) , @Id varchar(10) OUT AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createReminder' ,@authuser , 'invid: ' + ISNULL(@invid, '')); DECLARE @now datetime = GETUTCDATE(); DECLARE @today date = @now; DECLARE @newid varchar(10) = [dbo].[fds__fn_reminder_id](); DECLARE @OUT [dbo].[fds__tt__reminder_core]; DECLARE @CustomerId bigint = dbo.fds__fn_invoice_customerid(@InvId); INSERT INTO [dbo].[fds__reminder] ([Id] ,[version] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[subject] ,[text] ,[IsSent] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[file]) OUTPUT inserted.* INTO @OUT VALUES (@newid ,0 --version ,@InvId ,@CustomerId ,@SendToAddress ,@SendToEmail ,@type ,@amount ,@amount_payed ,@subject ,@text ,0 --IsSent, bit,> ,null -- ,NULL -- ,NULL --[UserSent] ,NULL -- ,NULL -- ,@now ,@authuser ,@now ,@authuser ,NULL); SELECT TOP(1) @Id = [id] FROM @out; With inv1 as( select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId ), inv as( SELECT [Id] = cast([id] as varchar(15)) ,[Invoiceid] ,[DateFinalized] ,[InvoiceBalance] FROM inv1 UNION SELECT [Id] = cast([id] as varchar(15)) ,[Invoiceid] ,[DateFinalized] = [DateOfCreation] ,[InvoiceBalance] FROM [dbo].[mfr__invoices] as mfri WHERE [id] = TRY_CAST(@invId as bigint) AND NOT EXISTS( SELECT 0 FROM inv1 ) --will only be used, if id not present in fds__invoices ) SELECT TOP(1) o.* , [InvoiceId] = inv.[InvoiceId] , [InvoiceDate] = inv.[DateFinalized] , [hasFile] = CAST ( CASE WHEN o.[file] is null THEN 0 ELSE 1 END as bit) , [UserNameFinalized] = [dbo].[fis_admin_getUserName_byID](o.[UserFinalized]) , [UserEmailFinalized] = [dbo].[fis_admin_getUserEmail_byID](o.[UserFinalized]) from @out as o join inv on o.[invid] = inv.[id]; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__createReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__createStorno_simple] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__createStorno_simple] @InvId varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createStorno_simple' ,@authuser , 'invid: ' + ISNULL(@InvId, '')); DECLARE @now datetime = GETDATE(); DECLARE @today date = CAST(@now as date); DECLARE @newid varchar(10) = [dbo].[fds__fn_invoice_id](); DECLARE @inv_DocumentName varchar(50), @inv_DateFinalized datetime, @inv_vat numeric(5,2), @inv_net numeric(10,3); IF EXISTS (SELECT 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1) BEGIN SELECT @inv_DocumentName = [documentname], @inv_DateFinalized = [DateFinalized], @inv_vat = [InvoiceVAT_1], @inv_net = [invoicebalance_net] FROM [dbo].[fds__invoices] WHERE [id] = @InvId INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified]) SELECT [Id] = @newid ,[Version] = 0 ,[InvoiceId] = NULL ,[InvoiceType] = 'c' ,[InvoiceTitle] = 'Stornorechnung' ,[DocumentName] = NULL ,[InvoiceBalance] = ([InvoiceBalance] * -1) ,[InvoiceBalance_net] = ([InvoiceBalance_net] *-1) ,[InvoiceVAT_net1] = ([InvoiceVAT_net1] * -1) ,[InvoiceVAT_1] ,[InvoiceVAT_net2] = ([InvoiceVAT_net2] * -1) ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] = @today ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] = NULL ,[IsPayed] = 0 ,[IsSent] = 0 ,[Replaces_InvId] = @InvId ,[CustomValues] ,[DateSent] = NULL ,[UserSent] = NULL ,[DateFinalized] = NULL ,[UserFinalized] = NULL ,[DateCancelled] = NULL ,[UserCancelled] = NULL ,[DateCreated] = @now ,[UserCreated] = @authuser ,[DateModified] = @now ,[UserModified] = @authuser FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1; END ELSE IF EXISTS (SELECT 0 FROM [dbo].[mfr__invoices] as _i where TRY_CAST(_i.[Id] as varchar(20)) = @InvId AND [FileType] in ('PdfInvoice','PdfPartialInvoice')) BEGIN SELECT @inv_DocumentName = [documentname], @inv_DateFinalized = [DateOfCreation] , @inv_vat = CASE WHEN ISNULL([InvoiceBalanceNetto], 0) <> 0 THEN (([InvoiceBalance] / [InvoiceBalanceNetto]) - 1)*100 ELSE (SELECT TOP(1) TRY_CAST([value] as numeric(5,2)) FROM [dbo].[fds__admin_settings] as st where st.[type] = 'defaults' and st.[key] = 'vat') END , @inv_net = [InvoiceBalanceNetto] FROM [dbo].[mfr__invoices] as _i where TRY_CAST(_i.[Id] as varchar(20)) = @InvId AND [FileType] in ('PdfInvoice','PdfPartialInvoice'); INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified]) SELECT [Id] = @newid ,[Version] = 0 ,[InvoiceId] = NULL ,[InvoiceType] = 'c' ,[InvoiceTitle] = 'Stornorechnung' ,[DocumentName] = NULL ,[InvoiceBalance] = ([InvoiceBalance] * -1) ,[InvoiceBalance_net] = ([InvoiceBalanceNetto] *-1) ,[InvoiceVAT_net1] = ((ISNULL([InvoiceBalance],0) - ISNULL([InvoiceBalanceNetto],0)) * -1) ,[InvoiceVAT_1] = @inv_vat ,[InvoiceVAT_net2] = NULL ,[InvoiceVAT_2] = NULL ,[PaymentTerm] = '10wd' ,[DueDate] = _i.DueDate ,[CustomerId] = (SELECT TOP(1) [partnerid] from [mfr__*PartnerSet] as ps where ps.[Property] = 'Invoice:Customer' and ps.[EntityId] = _i.[id]) ,[SendToAddress] = NULL ,[SendToEmail] = NULL ,[ProvisionPeriod] = null ,[ProvisionLocation] = NULL ,[PaymentStatus] = NULL ,[IsPayed] = 0 ,[IsSent] = 0 ,[Replaces_InvId] = @InvId ,[CustomValues] = null ,[DateSent] = NULL ,[UserSent] = NULL ,[DateFinalized] = NULL ,[UserFinalized] = NULL ,[DateCancelled] = NULL ,[UserCancelled] = NULL ,[DateCreated] = @now ,[UserCreated] = @authuser ,[DateModified] = @now ,[UserModified] = @authuser FROM [dbo].[mfr__invoices] as _i where TRY_CAST(_i.[Id] as varchar(20)) = @InvId AND [FileType] in ('PdfInvoice','PdfPartialInvoice'); UPDATE [dbo].[fds__invoices] SET [SendToAddress] = [dbo].[fds__getCompanyNameAddress]([CustomerId]), [SendToEmail] = [dbo].[fds__getCompanyEmail]([CustomerId]) WHERE [Id] = @newid; END -- continue creating storno DECLARE @inv_srq [dbo].[fds__tt__invoice_servicerequests]; INSERT INTO [dbo].[fds__invoice_servicerequests] ([InvId] ,[mfr__servicerequest] ,[title] ,[value_net] ,[SortOrder]) OUTPUT inserted.* INTO @inv_srq SELECT TOP(1) [InvId] = [id] ,NULL -- ,'Storno' ,0 ,0 FROM [dbo].[fds__invoices] WHERE [id] = @newid; INSERT INTO [dbo].[fds__invoice_items] ([InvId] ,[InvRqId] ,[mfr__item] ,[reference_InvId] ,[Type] ,[Position] ,[Quantity] ,[Text] ,[value] ,[value_total] ,[vat] ,[value_service] ,[det] ,[SortOrder]) SELECT @newid -- ,[id]-- ,NULL -- ,@InvId -- ,'CanceledInvoice' -- ,NULL -- ,'1' --- ,[Text] = '

' + 'Storno der ' + REPLACE(@inv_DocumentName, '.pdf','') + ' vom ' + FORMAT(@inv_dateFinalized, 'dd.MM.yyyy', 'de-de') + '

' ,[value] = (@inv_net * -1) ,[value_total] = (@inv_net * -1) ,[vat] = @inv_vat ,0 -- ,1 -- ,1 --) FROM @inv_srq; INSERT INTO [dbo].[fds__invoice_details] ([InvId] ,[InvoiceService_net] ,[InvoiceService_VAT] ,[AllocatedTo_InvId] ,[StornoTo_InvId]) VALUES( @newid ,NULL --[InvoiceService_net] ,NULL --[InvoiceService_VAT] ,NULL --[AllocatedTo_InvId] ,@InvId --[StornoTo_InvId] ); EXECUTE [dbo].[fds__getInvoice] @newid, @authuser; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__createStorno_simple] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getBankingtransfers] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getBankingtransfers] @mode varchar(1) = 'm' , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getBankingtransfers_questionable' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; SET @mode = LOWER(@mode); DECLARE @invidlist [dbo].[fds__tt__idlist_vchar]; --output admin SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode, [title] = 'Zahlungen (neueste zuerst)' ,[note] = 'Letzes Buchungsdatum: ' + FORMAT((SELECT MAX([valuedate]) from [fds__bankingtransactions]), 'dd.MM.yy'); select ic.[uid] --inv.InvoiceId, --[IsPayed], , ic.fds , InvoiceId = ISNULL(fi.[invoiceid], mi.[invoiceid]) , [ValueDate] = FORMAT(ic.[ValueDate], 'dd.MM.yy') , [InvoiceBalance] = FORMAT((ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0)), '0.00€', 'de') , [Amount] = FORMAT(ic.[amount], '0.00€', 'de') , [Skonto] = CAST(CASE WHEN ic.[amount] between (0.965 * (ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0))) and (0.975 * (ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0))) THEN 1 ELSE 0 END as bit) , [Deviation] = FORMAT(CASE WHEN ISNULL((ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0)),0) > 9 THEN ic.[amount] / (ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0)) ELSE NULL END , '0.00%') --, ic.* ,ic.AccountNumberOfPayer ,ic.NameOfPayer ,ic.SepaRemittanceInformation ,ic.EndToEndReference , [order] = ROW_NUMBER() OVER (ORDER BY [valuedate] DESC) FROM [dbo].[fds__fn_bankingtransactions](null, null, @startdate, @enddate, @invidlist) as ic LEFT JOIN [dbo].[fds__invoices] as fi on ic.[fds] = 1 and ic.[invid] = fi.id LEFT JOIN [dbo].[mfr__invoices] as mi on ic.[fds] = 0 and ic.[invid] = mi.id END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getBankingtransfers] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getBankingtransfers_questionable] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getBankingtransfers_questionable] @mode varchar(1) = 'm' , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getBankingtransfers_questionable' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; SET @mode = LOWER(@mode); --output admin SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode, [title] = 'Auffällige Zahlungen (neueste zuerst)' ,[note] = 'Letzes Buchungsdatum: ' + FORMAT((SELECT MAX([valuedate]) from [fds__bankingtransactions]), 'dd.MM.yy'); with inv as ( SELECT [fds] = CAST(1 as bit), [InvId] = CAST([Id] as varchar(25)), [InvoiceId], [InvoiceBalance] = CAST([InvoiceBalance] as numeric(10,2)), [ispayed] FROM [dbo].[fds__invoices] as i UNION SELECT [fds] = CAST(0 as bit), [InvId] = CAST([Id] as varchar(25)), [InvoiceId], [InvoiceBalance] = CAST([InvoiceBalance] as numeric(10,2)), [ispayed] = CAST(CASE WHEN [InvoiceState] = 'eIsCancelled' THEN 1 WHEN [InvoiceState] = 'eIsPaid' THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__invoices] as i ) select ic.[uid] --inv.InvoiceId, --[IsPayed], , inv.fds , ic.InvoiceId , [ValueDate] = FORMAT(ic.[ValueDate], 'dd.MM.yy') , [InvoiceBalance] = FORMAT(inv.[InvoiceBalance], '0.00€', 'de') + ISNULL( CASE WHEN id2.[invid] is not null then (SELECT TOP(1) FORMAT(inv2.[InvoiceBalance], '0.00€', 'de') FROM [dbo].[fds__invoices] as inv2 where inv2.Id = id2.[invid]) ELSE '' END ,'') , [Amount] = FORMAT(ic.[amount], '0.00€', 'de') , [Skonto] = CAST(CASE WHEN ic.[amount] between (0.965 * inv.[InvoiceBalance]) and (0.975 * inv.[InvoiceBalance]) THEN 1 ELSE 0 END as bit) , [Deviation] = FORMAT(CASE WHEN ISNULL(inv.[InvoiceBalance],0) > 9 THEN ic.[amount] / inv.[InvoiceBalance] ELSE NULL END , '0.00%') --, ic.* ,ic.AccountNumberOfPayer ,ic.NameOfPayer ,ic.SepaRemittanceInformation ,ic.EndToEndReference , [order] = ROW_NUMBER() OVER (ORDER BY [valuedate] DESC) FROM [dbo].[fds__getInvoiceCredits] (null, null) as ic LEFT JOIN inv on inv.[InvoiceId] = ic.[invoiceid] LEFT JOIN [dbo].[fds__invoice_details] as id2 ON inv.InvId = id2.[stornoto_invid] WHERE ((ISNULL(inv.ispayed,0) = 0 and fds = 1) OR ic.[amount] not between (inv.InvoiceBalance - 0.99) and (inv.InvoiceBalance + 0.99) OR ic.invoiceid is null oR inv.invoiceid is null ) AND NOT EXISTS (SELECT 0 FROM [dbo].[fds__bankingtransactions_settings] as bs WHERE bs.[banking_uid] = ic.[uid] AND (ISNULL(bs.[done_manually],'') <> '' OR ISNULL(bs.[assigned_invoice_id],'') <> '')) END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getBankingtransfers_questionable] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getDatevExports] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getDatevExports] @tgtdate date ,@mode varchar(1) = 'm' ,@files bit ,@authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @startdate date, @enddate date; SET @mode = LOWER(@mode); If @mode = 'm' BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END DECLARE @contraaccounts as table([account] varchar(10), [vat] numeric(5,2)); insert into @contraaccounts SELECT [account] = [key], [vat] = TRY_PARSE([value2] as numeric(5,2) USING 'en-US') FROM [dbo].[fds__admin_settings] WHERE [type] = 'contra_account' SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [beraternummer] = 11653 , [mandantennummer] = 62321 , [WJ-Beginn] = DATEFROMPARTS(YEAR(@tgtDate), 1, 1) , [Sachkontenlänge] = ISNULL((SELECT MAX(LEN([account])) FROM @contraaccounts), 4) ; DECLARE @inv TABLE([Id] varchar(20), [InvoiceID] varchar(255), [URI] nvarchar(255), [DocumentName] nvarchar(255), [DateOfCreation] date, [fds] bit, [file_guid] varchar(36)); --INSERT INTO @inv SELECT [Id],[invoiceid],[URI],[DocumentName],[DateOfCreation],[fds] = 0 FROM [dbo].[mfr__reports] where [IsInvoice] = 1 AND CAST([DateOfCreation] as date) between @startdate AND @enddate; INSERT INTO @inv SELECT [Id],[invoiceid],[URI],[DocumentName],[DateOfCreation],[fds] = 0, [file_guid] FROM [dbo].[mfr__invoices] where CAST([DateOfCreation] as date) between @startdate AND @enddate and [FileType] in( 'PdfInvoice','PdfCancelInvoice','PdfPartialInvoice') and ISNULL(InvoiceId,'') not in ('Preview','') ; INSERT INTO @inv SELECT [Id],[invoiceid],[URI] = null,[DocumentName],[DateOfCreation] = [DateCreated],[fds] = 1, [file_guid] FROM [dbo].[fds__invoices] where CAST([DateCreated] as date) between @startdate AND @enddate and [isfinal] = 1; SELECT inv.[Id],inv.[InvoiceID],inv.[URI],inv.[DocumentName],inv.[fds] , [file] = CASE WHEN @files = 1 then finv.[file] ELSE NULL END , inv.[file_guid], [DateOfCreation] --,[order] = ROW_NUMBER() OVER (ORDER BY [DateOfCreation] ASC) FROM @inv as inv LEFT JOIN [dbo].[fds__invoices] as finv on inv.[id] = finv.[id]; DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(15), [customer.ExternalId] bigint, [customer.Id] bigint, [ExternalId] nvarchar(255), [fds] bit); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId], [fds] FROM [dbo].[mfr__servicerequests] as s JOIN @inv as i on s.[InvoiceId] like ('%' + i.[InvoiceId] + '%') LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE i.fds = 0; INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId], [fds] FROM [dbo].[fds__invoice_servicerequests] as irq JOIN @inv as i on irq.[InvId] = i.[Id] LEFT JOIN [dbo].[mfr__servicerequests] as s ON irq.[mfr__servicerequest] = s.[id] LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE i.fds = 1; With itm as ( SELECT [net_itemsum] = CAST( SUM((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL(vat.[vat], 19.0) * 0.01)) , sreq.[invoice.Id] ,[fds] = 0 FROM [dbo].[mfr__items] as itm JOIN @sreq as sreq ON itm.[ServiceRequestId] = SReq.[id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' WHERE [fds] = 0 GROUP BY sreq.[invoice.Id] UNION SELECT [net_itemsum] = CAST( SUM(ISNULL([value_total],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM(ISNULL([value_total],0) * (1 + (ISNULL([vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL([vat], 19.0) * 0.01)) , [invoice.Id] = inv.[id] --sreq.[invoice.Id] , [fds] = 1 FROM [dbo].[fds__invoice_items] as itm --JOIN @sreq as sreq ON itm.[InvRqId] = SReq.[id] JOIN @inv as inv ON itm.[invid] = inv.[id] and [fds] = 1 WHERE [fds] = 1 GROUP BY inv.[id] --sreq.[invoice.Id] ),sc as( SELECT s.[invoice.Id], [fds], [#] = COUNT(s.[id]) FROM @SReq as s GROUP BY s.[invoice.Id], [fds] ), inv as( --select -- [Id] = CAST(iv.[Id] as varchar(20)) -- ,[InvoiceId] = iv.[InvoiceId] -- ,[requestcount] = sc.[#] -- ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) -- ,[balance] = ABS([invoiceBalance]) -- ,[EINZELPOS_brutto] = itm.bo_itemsum -- ,[EINZELPOS_netto] = itm.net_itemsum -- ,[vf] -- ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END -- ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) -- ,[contra_account] = ca.[account] -- ,[Belegdatum] = iv.[DateOfCreation] -- ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) -- ,iv.[DateOfCreation] -- from [dbo].[mfr__reports] as iv -- LEFT JOIN itm on iv.Id = itm.[invoice.Id] -- LEFT JOIN [dbo].[fds__custom_vat] as vat ON iv.[Id] = vat.[EntityId] and vat.[EntityType] = 'report' -- LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 0 -- LEFT JOIN contra_accounts as ca ON ISNULL(vat.[vat], 19.0) = ca.[vat] -- where iv.Id in (SELECT [Id] FROM @inv Where fds = 0) --UNION select [Id] = CAST(iv.[Id] as varchar(20)) ,[InvoiceId] = iv.[InvoiceId] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = ABS([invoiceBalance]) ,[EINZELPOS_brutto] = itm.bo_itemsum ,[EINZELPOS_netto] = itm.net_itemsum ,[vf] ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = iv.[DateOfCreation] ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,iv.[DateOfCreation] ,[file_guid] from [dbo].[mfr__invoices] as iv LEFT JOIN itm on iv.Id = itm.[invoice.Id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON iv.[Id] = vat.[EntityId] and vat.[EntityType] = 'report' LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 0 LEFT JOIN @contraaccounts as ca ON ISNULL(vat.[vat], ISNULL([dbo].[fds__fn_vatfrombalances]([invoiceBalance], [invoiceBalancenetto]),19.0)) = ca.[vat] where iv.Id in (SELECT [Id] FROM @inv Where fds = 0) UNION select iv.[Id] ,[InvoiceId] = iv.[InvoiceId] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = ABS([invoiceBalance]) ,[EINZELPOS_brutto] = itm.bo_itemsum ,[EINZELPOS_netto] = itm.net_itemsum ,[vf] ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END ,[customer] = (SELECT TOP(1) [ExternalId] FROM [dbo].[mfr__companies] as c WHERE c.[Id] = iv.[CustomerId]) ,[contra_account] = ca.[account] ,[Belegdatum] = iv.[DateCreated] ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,[DateOfCreation] = iv.[DateCreated] ,[file_guid] from [dbo].[fds__invoices] as iv LEFT JOIN itm on iv.Id = itm.[invoice.Id] LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 1 LEFT JOIN @contraaccounts as ca ON ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] where iv.Id in (SELECT [Id] FROM @inv Where fds = 1) ) select [Umsatz (ohne Soll/Haben-Kz)] = ABS([balance])--CAST(FORMAT(ABS([balance]), '0.00', 'de') as varchar(13)) --,[EINZELPOS_brutto] --,[EINZELPOS_netto] --,vf ,[Soll/Haben-Kennzeichen] = [dbo].[ott_quote_255](UPPER([deb_cred])) ,[WKZ Umsatz] = [dbo].[ott_quote_255]('') ,[Kurs] = NULL ,[Basis-Umsatz] = NULL ,[WKZ Basis-Umsatz] = [dbo].[ott_quote_255]('') ,[Konto] = CAST(iv.[customer] as bigint) --CAST(iv.[customer] as varchar(9)) --(SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] ORDER BY SReq.DateOfCreation ASC) ,[Gegenkonto (ohne BU-Schlüssel)] = CAST([contra_account] as bigint )--CAST([contra_account] as varchar(9))] ,[BU-Schlüssel] = [dbo].[ott_quote_255]('') ,[Belegdatum] = FORMAT(iv.[Belegdatum], 'ddMM') ,[Belegfeld 1] = [dbo].[ott_quote_255](iv.[InvoiceId]) ,[Belegfeld 2] = [dbo].[ott_quote_255]([dbo].[strings_removeLeading0_255](FORMAT(iv.[Belegdatum], 'ddMMyy'))) ,[Skonto] = [dbo].[ott_quote_255]('') ,[Buchungstext] = [dbo].[ott_quote_255](CAST(ISNULL(LEFT( TRIM(CAST((SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) as varchar(255)) ), 60) ,'') as varchar(60))) ,[Postensperre] = NULL ,[Diverse Adressnummer] = [dbo].[ott_quote_255]('') ,[Geschäftspartnerbank] = null ,[Sachverhalt] = null ,[Zinssperre] = null ,[Beleglink] = [dbo].[ott_quote_255](CASE WHEN [file_guid] is null THEN NULL ELSE CAST( 'BEDI "' + LOWER(CAST([file_guid] as varchar(36))) + '"' as varchar(50)) end) --,[order] = ROW_NUMBER() OVER (ORDER BY iv.[DateOfCreation] ASC)] ,[Beleginfo - Art 1] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 1] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 2] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 2] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 3] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 3] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 4] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 4] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 5] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 5] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 6] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 6] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 7] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 7] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 8] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 8] = [dbo].[ott_quote_255]('') ,[KOST1 - Kostenstelle] = [dbo].[ott_quote_255]('') ,[KOST2 - Kostenstelle] = [dbo].[ott_quote_255]('') ,[Kost-Menge] = null ,[EU-Land u. UStID (Bestimmung)] = [dbo].[ott_quote_255]('') ,[EU-Steuersatz (Bestimmung)] = null ,[Abw. Versteuerungsart] = [dbo].[ott_quote_255]('') ,[Sachverhalt L+L] = null ,[Funktionsergänzung L+L] = null ,[BU 49 Hauptfunktionstyp] = null ,[BU 49 Hauptfunktionsnummer] = null ,[BU 49 Funktionsergänzung] = null ,[Zusatzinformation - Art 1] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 1] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 2] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 2] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 3] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 3] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 4] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 4] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 5] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 5] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 6] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 6] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 7] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 7] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 8] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 8] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 9] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 9] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 10] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 10] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 11] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 11] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 12] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 12] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 13] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 13] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 14] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 14] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 15] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 15] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 16] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 16] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 17] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 17] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 18] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 18] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 19] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 19] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 20] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 20] = [dbo].[ott_quote_255]('') ,[Stück] = null ,[Gewicht] = null ,[Zahlweise] = null ,[Forderungsart] = [dbo].[ott_quote_255]('') ,[Veranlagungsjahr] = null ,[Zugeordnete Fälligkeit] = null ,[Skontotyp] = null ,[Auftragsnummer] = [dbo].[ott_quote_255]('') ,[Buchungstyp] = [dbo].[ott_quote_255]('') ,[USt-Schlüssel (Anzahlungen)] = null ,[EU-Land (Anzahlungen)] = [dbo].[ott_quote_255]('') ,[Sachverhalt L+L (Anzahlungen)] = null ,[EU-Steuersatz (Anzahlungen)] = null ,[Erlöskonto (Anzahlungen)] = null ,[Herkunft-Kz] = [dbo].[ott_quote_255]('') ,[Buchungs GUID] = [dbo].[ott_quote_255]('') ,[KOST-Datum] = null ,[Mandatsreferenz] = [dbo].[ott_quote_255]('') ,[Skontosperre] = null ,[Gesellschaftername] = [dbo].[ott_quote_255]('') ,[Beteiligtennummer] = null ,[Identifikationsnummer] = [dbo].[ott_quote_255]('') ,[Zeichnernummer] = [dbo].[ott_quote_255]('') ,[Postensperre bis] = null ,[Bezeichnung SoBil-Sachverhalt] = [dbo].[ott_quote_255]('') ,[Kennzeichen SoBil-Buchung] = [dbo].[ott_quote_255]('') ,[Festschreibung] = 1 ,[Leistungsdatum] = null ,[Datum Zuord. Steuerperiode] = null ,[Fälligkeit] = null ,[Generalumkehr (GU)] = 0 ,[Steuersatz] = null ,[Land] = null --,[Abrechnungsreferenz] --,[BVV-Position] --,[EU-Land u. UStID (Ursprung)] --,[EU-Steuersatz (Ursprung)] from inv as iv order by TRY_CONVERT(integer, SUBSTRING(iv.[InvoiceId], 2,4)), TRY_CONVERT(integer, RIGHT(iv.[InvoiceId], 4)), iv.[DateOfCreation] ASC; WIth debs as ( SELECT ROW_NUMBER() OVER (PARTITION BY [customer.Id] ORDER BY SReq.DateOfCreation ASC) as [#] , [customer.ExternalId] , [customer.Id] FROM @SReq as sreq ), dd as ( SELECT distinct cy.* FROM [mfr__companies] as cy WHERE EXISTS ( SELECT * FROM debs WHERE debs.[customer.Id] = cy.[id] AND debs.[#] = 1) ), cc as ( SELECT ROW_NUMBER() OVER (PARTITION BY dd.[id] ORDER BY CASE WHEN dd.[MainContactId] = c.[id] THEN 0 ELSE 1 END) as '#' , c.* , [company_id] = dd.[id] , [company_name] = dd.[Name] , [isCompany] = CAST ( CASE WHEN ( not dd.[name] like '%c[/]o %' AND ( dd.[Name] like '%mbH%' OR dd.[Name] like '%Ltd%' OR dd.[Name] like '% gbr%' OR dd.[Name] like 'gbr %' OR dd.[Name] like '% OHG%' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% AG %' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% KG %' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% SA %' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% UG %' OR dd.[Name] like '% eV%' or dd.[Name] like '%e[.]V[.]%' OR dd.[Name] like '%Gesellschaft%' OR dd.[Name] like '%Gemeinde%' OR dd.[Name] like '%Verwaltung%' OR dd.[Name] like '%Stadtwerke%' OR dd.[Name] like '%tagesstätte%' OR dd.[Name] like '%schützenverein%' OR dd.[Name] like '%akademie%' OR dd.[Name] like '%universität%' OR dd.[Name] like '%schule%' OR dd.[Name] like '%spedition%' OR dd.[Name] like '%immobilien%' OR dd.[Name] like '%krankenkasse%' OR dd.[Name] like '% holding %' OR dd.[Name] like '% Bautenschutz %' OR dd.[Name] like '%dienstleistung%' OR dd.[Name] like '%weinlokal%' OR dd.[Name] like '%restaurant%' OR dd.[Name] like '% hotel%' OR dd.[Name] like '%kanzlei%' OR dd.[Name] like '%praxis%' OR dd.[Name] like '%großhandel%' OR dd.[Name] like '%tischlerei%' OR dd.[Name] like '%haustechnik%' OR dd.[Name] like '%holztechnik%' OR dd.[Name] like '%heizungsbau%' OR dd.[Name] like '%bautenschutz%' OR dd.[Name] like '%tischlerei%' OR dd.[Name] like '%architekt%' OR dd.[Name] like '%sanitär%' OR dd.[Name] like '%pafümerie%' OR dd.[Name] like '%bauamt%' OR dd.[Name] like '%gebäudereinigung%' OR dd.[Name] like '%handwerksmeister%' OR dd.[Name] like '%fachbetrieb%' OR dd.[Name] like '%ausbau und montagen%' OR dd.[Name] like '%verband %' OR dd.[Name] like '%vermietung%' OR dd.[Name] like '%Bad [&] Heizung%' OR dd.[Name] like '%Bad[&]Wärme%' OR dd.[Name] like '% Düsseldorf%' OR dd.[Name] like '%niederlassung%' OR dd.[Name] like 'zentrum für %' OR dd.[Name] like '% Generalvertretung %' )) THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as c JOIN dd on c.[CompanyId] = dd.[Id] OR dd.[MainContactId] = c.[id] ) SELECT [Konto] = CAST(dd.[ExternalId] as bigint) --CAST(dd.[ExternalId] as varchar(9)) ,[Name (Adressatentyp Unternehmen)] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN cc.[isCompany] = 0 THEN '' ELSE REPLACE(REPLACE(REPLACE(ISNULL( cc.[company_name] ,''), CHAR(13), ' '), CHAR(10), ' '), ' ', ' ') END as varchar(255)), 50) as varchar(50))) ,[Unternehmensgegenstand] = [dbo].[ott_quote_255]('') ,[Name (Adressattyp natürl. Person)] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN cc.[isCompany] = 1 THEN '' ELSE REPLACE(REPLACE(REPLACE(ISNULL( cc.[LastName] ,''), CHAR(13), ' '), CHAR(10), ' '), ' ', ' ') END as varchar(255)), 30) as varchar(30))) ,[Vorname (Adressattyp natürl. Person)] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN cc.[isCompany] = 1 THEN '' ELSE REPLACE(REPLACE(REPLACE(ISNULL( cc.[FirstName] ,''), CHAR(13), ' '), CHAR(10), ' '), ' ', ' ') END as varchar(255)), 30) as varchar(30))) ,[Name (Adressattyp keine Angabe)] = [dbo].[ott_quote_255]('') ,[Adressattyp] = [dbo].[ott_quote_255](CAST(CASE WHEN cc.[isCompany] = 1 THEN 2 ELSE 1 END as varchar(1))) ,[Kurzbezeichnung] = [dbo].[ott_quote_255]('') ,[EU-Land] = [dbo].[ott_quote_255]('') ,[EU-UStID] = [dbo].[ott_quote_255]('') ,[Anrede] = [dbo].[ott_quote_255]('') --CASE WHEN LOWER(LEFT(cc.[Gender],1)) = 'm' THEN 'Herrn' WHEN LOWER(LEFT(cc.[Gender],1)) = 'w' THEN 'Frau' ELSE '' END ,[Titel/Akad. Grad] = [dbo].[ott_quote_255]('') ,[Adelstitel] = [dbo].[ott_quote_255]('') ,[Namensvorsatz] = [dbo].[ott_quote_255]('') ,[Adressart] = [dbo].[ott_quote_255](CAST( CASE WHEN ISNULL(l.[AddressString],'') like '%postfach%' THEN 'PF' ELSE 'STR' END as varchar(3))) ,[Straße] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN ISNULL(l.[AddressString],'') like '%postfach%' THEN '' ELSE ISNULL(l.[AddressString],'') END as varchar(255)),36) as varchar(36))) ,[Postfach] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN ISNULL(l.[AddressString],'') like '%postfach%' THEN TRIM(SUBSTRING(ISNULL(l.[AddressString],''), PATINDEX('%postfach%', ISNULL(l.[AddressString],'')) + 8 , 12)) ELSE '' END as varchar(255)),36) as varchar(36))) ,[Postleitzahl] = [dbo].[ott_quote_255](CAST(l.[Postal] as varchar(10))) ,[Ort] = [dbo].[ott_quote_255](CAST(l.City as varchar(30))) ,[Land] = [dbo].[ott_quote_255](CAST(REPLACE(UPPER(ISNULL(l.[Country], '')),'KE','') as varchar(2))) ,[Versandzusatz] = [dbo].[ott_quote_255]('') ,[Adresszusatz] = [dbo].[ott_quote_255]('') ,[Abweichende Anrede] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 1] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 2] = [dbo].[ott_quote_255]('') ,[Kennz. Korrespondenzadresse] = Cast(1 as int) ,[Adresse Gültig von] = [dbo].[ott_quote_255]('') ,[Adresse Gültig bis] = [dbo].[ott_quote_255]('') ,[Telefon] = [dbo].[ott_quote_255](CAST(ISNULL(cc.[Telephone], dd.[SupportTelephone]) as varchar(60))) ,[Bemerkung (Telefon)] = [dbo].[ott_quote_255]('') ,[Telefon GL] = [dbo].[ott_quote_255]('') ,[Bemerkung (Telefon GL)] = [dbo].[ott_quote_255]('') ,[E-Mail] = [dbo].[ott_quote_255](CAST( CASE WHEN ISNULL(cc.[Email], dd.[SupportMail]) like '%[@]%' THEN REPLACE(LOWER(ISNULL(cc.[Email], dd.[SupportMail])), ' ', '') ELSE NULL END as varchar(60))) ,[Bemerkung (E-Mail)] = [dbo].[ott_quote_255]('') ,[Internet] = [dbo].[ott_quote_255]('') ,[Bemerkung (Internet)] = [dbo].[ott_quote_255]('') ,[Fax] = [dbo].[ott_quote_255]('') ,[Bemerkung (Fax)] = [dbo].[ott_quote_255]('') ,[Sonstige] = [dbo].[ott_quote_255]('') ,[Bemerkung (Sonstige)] = [dbo].[ott_quote_255]('') ,[Bankleitzahl 1] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 1] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 1] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 1] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 1] = [dbo].[ott_quote_255]('') ,[IBAN1 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 1] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 1] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 1] = [dbo].[ott_quote_255]('') ,[Bankverb 1 Gültig von] = null ,[Bankverb 1 Gültig bis] = null ,[Bankleitzahl 2] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 2] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 2] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 2] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 2] = [dbo].[ott_quote_255]('') ,[IBAN2 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 2] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 2] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 2] = [dbo].[ott_quote_255]('') ,[Bankverb 2 Gültig von] = null ,[Bankverb 2 Gltig bis] = null ,[Bankleitzahl 3] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 3] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 3] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 3] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 3] = [dbo].[ott_quote_255]('') ,[IBAN3 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 3] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 3] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 3] = [dbo].[ott_quote_255]('') ,[Bankverb 3 Gültig von] = null ,[Bankverb 3 Gültig bis] = null ,[Bankleitzahl 4] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 4] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 4] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 4] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 4] = [dbo].[ott_quote_255]('') ,[IBAN4 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 4] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 4] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 4] = [dbo].[ott_quote_255]('') ,[Bankverb 4 Gültig von] = null ,[Bankverb 4 Gültig bis] = null ,[Bankleitzahl 5] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 5] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 5] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 5] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 5] = [dbo].[ott_quote_255]('') ,[IBAN5 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 5] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 5] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 5] = [dbo].[ott_quote_255]('') ,[Bankverb 5 Gültig von] = null ,[Bankverb 5 Gültig bis] = null ,[Leerfeld] = null ,[Briefanrede] = [dbo].[ott_quote_255]('') ,[Grußformel] = [dbo].[ott_quote_255]('') ,[Kundennummer] = [dbo].[ott_quote_255]('') ,[Steuernummer] = [dbo].[ott_quote_255]('') ,[Sprache] = null ,[Ansprechpartner] = [dbo].[ott_quote_255]('') ,[Vertreter] = [dbo].[ott_quote_255]('') ,[Sachbearbeiter] = [dbo].[ott_quote_255]('') ,[Diverse-Konto] = null ,[Ausgabeziel] = null ,[Währungssteuerung] = [dbo].[ott_quote_255]('') ,[Kreditlimit (Debitor)] = null ,[Zahlungsbedingung] = null ,[Fälligkeit in Tagen (Debitor)] = null ,[Skonto in Prozent (Debitor)] = null ,[Kreditoren-Ziel 1 Tg.] = null ,[Kreditoren-Skonto 1 %] = null ,[Kreditoren-Ziel 2 Tg.] = null ,[Kreditoren-Skonto 2 %] = null ,[Kreditoren-Ziel 3 Brutto Tg.] = null ,[Kreditoren-Ziel 4 Tg.] = null ,[Kreditoren-Skonto 4 %] = null ,[Kreditoren-Ziel 5 Tg.] = null ,[Kreditoren-Skonto 5 %] = null ,[Mahnung] = null ,[Kontoauszug] = null ,[Mahntext 1] = null ,[Mahntext 2] = null ,[Mahntext 3] = null ,[Kontoauszugstext] = null ,[Mahnlimit Betrag] = null ,[Mahnlimit %] = null ,[Zinsberechnung] = null ,[Mahnzinssatz 1] = null ,[Mahnzinssatz 2] = null ,[Mahnzinssatz 3] = null ,[Lastschrift] = [dbo].[ott_quote_255]('') ,[Verfahren] = [dbo].[ott_quote_255]('') ,[Mandantenbank] = null ,[Zahlungsträger] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 1] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 2] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 3] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 4] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 5] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 6] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 7] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 8] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 9] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 10] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 11] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 12] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 13] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 14] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 15] = [dbo].[ott_quote_255]('') ,[Abweichende Anrede (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Adressart (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Straße (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Postfach (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Postleitzahl (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Ort (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Land (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Versandzusatz (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Adresszusatz (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 1 (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 2 (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Adresse Gültig von (Rechnungsadresse)] = null ,[Adresse Gültig bis (Rechnungsadresse)] = null ,[Bankleitzahl 6] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 6] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 6] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 6] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 6] = [dbo].[ott_quote_255]('') ,[IBAN6 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 6] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 6] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 6] = [dbo].[ott_quote_255]('') ,[Bankverb 6 Gültig von] = null ,[Bankverb 6 Gültig bis] = null ,[Bankleitzahl 7] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 7] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 7] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 7] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 7] = [dbo].[ott_quote_255]('') ,[IBAN7 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 7] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 7] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 7] = [dbo].[ott_quote_255]('') ,[Bankverb 7 Gültig von] = null ,[Bankverb 7 Gültig bis] = null ,[Bankleitzahl 8] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 8] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 8] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 8] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 8] = [dbo].[ott_quote_255]('') ,[IBAN8 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 8] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 8] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 8] = [dbo].[ott_quote_255]('') ,[Bankverb 8 Gültig von] = null ,[Bankverb 8 Gültig bis] = null ,[Bankleitzahl 9] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 9] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 9] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 9] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 9] = [dbo].[ott_quote_255]('') ,[IBAN9 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 9] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 9] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 9] = [dbo].[ott_quote_255]('') ,[Bankverb 9 Gültig von] = null ,[Bankverb 9 Gültig bis] = null ,[Bankleitzahl 10] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 10] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 10] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 10] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 10] = [dbo].[ott_quote_255]('') ,[IBAN10 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 10] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 10] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 10] = [dbo].[ott_quote_255]('') ,[Bankverb 10 Gültig von] = null ,[Bankverb 10 Gültig bis] = null ,[Nummer Fremdsystem] = [dbo].[ott_quote_255]('') ,[Insolvent] = null ,[Mandatsreferenz 1] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 2] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 3] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 4] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 5] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 6] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 7] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 8] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 9] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 10] = [dbo].[ott_quote_255]('') ,[Verknüpftes OPOS-Konto] = null ,[Mahnsperre bis] = null ,[Lastschriftsperre bis] = null ,[Zahlungssperre bis] = null ,[gebührenberechnung] = null ,[Mahngebühr 1] = null ,[Mahngebühr 2] = null ,[Mahngebühr 3] = null ,[Pauschalenberechnung] = null ,[Verzugspauschale 1] = null ,[Verzugspauschale 2] = null ,[Verzugspauschale 3] = null ,[Alternativer Suchname] = null ,[Status] = null ,[Anschrift manuell geändert (Korrespondenzadresse)] = null ,[Anschrift individuell (Korrespondenzadresse)] = null ,[Anschrift manuell geändert (Rechnungsadresse)] = null ,[Anschrift individuell (Rechnungsadresse)] = null ,[Fristberechnung bei Debitor] = null ,[Mahnfrist 1] = null ,[Mahnfrist 2] = null ,[Mahnfrist 3] = null ,[Letzte Frist] = null FROM dd JOIN cc on cc.[#] = 1 AND cc.[company_id] = dd.[id] LEFT JOIN [dbo].[mfr__#locations] as l ON l.[EntityID] = dd.[id] and l.Property = 'Company:Location' END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getDatevExports] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getInvoiceReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getInvoiceReminder] @InvId varchar(15) , @include_drafts bit = 0 ,@authuser varchar(25) AS BEGIN SET NOCOUNT ON; With inv as ( SELECT TOP(1) [Id] = CAST([id] as varchar(15)), [InvoiceId], [DocumentName] FROM [dbo].[fds__invoices] WHERE [id] = @InvId ), inv2 as( SELECT * FROM inv UNION SELECT TOP(1) [Id] = CAST([id] as varchar(15)), [InvoiceId], [DocumentName] FROM [dbo].[mfr__invoices] as mi WHERE NOT EXISTS( SELECT 0 FROM inv ) AND TRY_CAST(@InvId as bigint) is not null AND mi.[id] = TRY_CAST(@InvId as bigint) ) SELECT rem.[Id] ,rem.[DateSent] ,[status] = CAST(CASE WHEN rem.[isSent] = 1 THEN 'versandt' WHEN rem.[isfinal] = 1 THEN 'fertig' WHEN rem.isfinal = 0 THEN 'Entwurf' ELSE '' END AS varchar(50)) ,rem.[subject] ,rem.[DocumentName] ,rem.[amount_open] ,rem.[InvId] ,[InvoiceId] = inv2.[InvoiceId] --,[InvoiceDocumentName] = inv2.[DocumentName] ,[hasFile] = cast( IIF(rem.[file] is null, 0, 1) as bit) FROM [dbo].[fds__reminder] as rem LEFT JOIN inv2 on rem.[InvId] = inv2.[Id] WHERE [invId] = @InvId; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getInvoiceReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getInvoices_list_vario] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getInvoices_list_vario] @tgtdate date ,@mode varchar(1) = 'm' , @includes varchar(50) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @include_drafts bit = [dbo].[ott_csv_contains](@includes, 'd'); DECLARE @only_drafts bit = 0, @only_unpayed bit = 0, @only_reminded bit = 0, @only_akonto bit = 0, @only_storno bit = 0, @only_remindedunpayed bit = 0; DECLARE @includetext varchar(50) = ''; IF @includes = '#d' SELECT @includetext = ' (nur Entwürfe) ', @include_drafts = 1, @only_drafts = 1, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = 'all' SELECT @includetext = ' (alle) ', @include_drafts = 1, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = '#r' SELECT @includetext = ' (nur angemahnte) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 1, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = '#u' SELECT @includetext = ' (nur unbezahlte) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 1, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = '#a' SELECT @includetext = ' (nur Akonto) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 1, @only_storno = 0; ELSE IF @includes = '#c' SELECT @includetext = ' (nur Storno) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 1; ELSE IF @includes = '#ru' SELECT @includetext = ' (nur gemahnt + unbez. + nicht storniert) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0, @only_remindedunpayed = 1; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getInvoices_list' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; SET @mode = LOWER(@mode); If @mode = 'm' BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END ELSE If @mode = 'a' BEGIN SELECT @startdate = [dbo].[date_weekfirst]('2000-01-01') ,@enddate = [dbo].[date_weekend](DATEADD(year, 1, @today)); END --Reminder settings DECLARE @stage1 varchar(10), @stage2 varchar(10), @stage3 varchar(10); SELECT @stage1 = [stage1], @stage2 = [stage2], @stage3 = [stage3] FROM [dbo].[fds__admin_reminderSettings](); SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = 'Rechnungsübersicht ' + @includetext + ' für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') WHEN @mode = 'a' THEN 'den gesamten Zeitraum' ELSE '' END ,[ust_options] = '19,0%;16,0%;0,0%'; DECLARE @inv TABLE([Id] varchar(15), [InvoiceID] varchar(255), [URI] nvarchar(255), [DocumentName] nvarchar(255), [DateOfCreation] date, [fds] bit); --INSERT INTO @inv SELECT [Id],[invoiceid],[URI],[DocumentName],[DateOfCreation],[fds] = 0 FROM [dbo].[mfr__reports] where [IsInvoice] = 1 AND CAST([DateOfCreation] as date) between @startdate AND @enddate; INSERT INTO @inv SELECT [Id],[invoiceid],[URI],[DocumentName],[DateOfCreation],[fds] = 0 FROM [dbo].[mfr__invoices] where CAST([DateOfCreation] as date) between @startdate AND @enddate and (ISNULL(@include_drafts,0) = 1 OR [FileType] in( 'PdfInvoice','PdfCancelInvoice','PdfPartialInvoice') and ISNULL(InvoiceId,'') not in ('Preview','')) and (@only_drafts = 0 OR ISNULL(InvoiceId,'') in ('Preview','')) and (@only_akonto = 0 OR [FileType] = 'PdfPartialInvoice') and (@only_storno = 0 OR [FileType] = 'PdfCancelInvoice') and ((@only_unpayed = 0 AND @only_remindedunpayed = 0) OR [InvoiceState] not IN ('eIsCancelled', 'eIsPaid')); INSERT INTO @inv SELECT [Id],[invoiceid],[URI] = null,[DocumentName],[DateOfCreation] = [DateCreated],[fds] = 1 FROM [dbo].[fds__invoices] where CAST([DateCreated] as date) between @startdate AND @enddate and (ISNULL(@include_drafts,0) = 1 OR [isfinal] = 1) and (@only_drafts = 0 OR [isfinal] = 0) and (@only_akonto = 0 OR [InvoiceType] = 'i') and (@only_storno = 0 OR [InvoiceType] = 'c') and ((@only_unpayed = 0 AND @only_remindedunpayed = 0) OR (IsPayed = 0 AND IsCanceled = 0)); DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(15), [customer.ExternalId] bigint, [customer.Id] bigint, [ExternalId] nvarchar(255), [fds] bit); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId], [fds] FROM [dbo].[mfr__servicerequests] as s JOIN dbo.[mfr__*PartnerSet] as p on p.[EntityId] = s.[Id] AND p.[Property] = 'ServiceRequest:Invoices' JOIN @inv as i on i.fds = 0 and p.[PartnerId] = i.[id] --s.[InvoiceId] like ('%' + i.[InvoiceId] + '%') LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE i.fds = 0; INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId], [fds] FROM [dbo].[fds__invoice_servicerequests] as irq JOIN @inv as i on irq.[InvId] = i.[Id] LEFT JOIN [dbo].[mfr__servicerequests] as s ON irq.[mfr__servicerequest] = s.[id] LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE i.fds = 1; With itm as ( SELECT [net_itemsum] = CAST( SUM((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL(vat.[vat], 19.0) * 0.01)) , sreq.[invoice.Id] ,[fds] = 0 FROM [dbo].[mfr__items] as itm JOIN @sreq as sreq ON itm.[ServiceRequestId] = SReq.[id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' WHERE [fds] = 0 GROUP BY sreq.[invoice.Id] UNION SELECT [net_itemsum] = CAST( SUM(ISNULL([value_total],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM(ISNULL([value_total],0) * (1 + (ISNULL([vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL([vat], 19.0) * 0.01)) , [invoice.Id] = inv.[id] --sreq.[invoice.Id] , [fds] = 1 FROM [dbo].[fds__invoice_items] as itm --JOIN @sreq as sreq ON itm.[InvRqId] = SReq.[id] JOIN @inv as inv ON itm.[invid] = inv.[id] and [fds] = 1 WHERE [fds] = 1 GROUP BY inv.[id] --sreq.[invoice.Id] ),sc as( SELECT s.[invoice.Id], [fds], [#] = COUNT(s.[id]) FROM @SReq as s GROUP BY s.[invoice.Id], [fds] ),contra_accounts as( SELECT [account] = [key], [vat] = TRY_PARSE([value2] as numeric(5,2) USING 'en-US') FROM [dbo].[fds__admin_settings] WHERE [type] = 'contra_account' ), inv as( --select -- [Id] = CAST(iv.[Id] as varchar(15)) -- ,[InvoiceId] = iv.[InvoiceId] -- ,[InvoiceType] = CAST( CASE WHEN LEFT([documentname],5) = 'absch' THEN 'i' -- WHEN LEFT([documentname],5) = 'storn' THEN 'c' -- ELSE 'r' -- END -- as char(1)) -- ,[DocumentName] -- ,[requestcount] = sc.[#] -- ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) -- ,[balance] = FORMAT(ABS([invoiceBalance]), '#0.00', 'de') + ' €' -- ,[EINZELPOS_brutto] = FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' -- ,[EINZELPOS_netto] = FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' -- ,[vat] = FORMAT(ISNULL(vat.[vat], 19.0), '#0.0', 'de') + ' %' -- ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END -- ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) -- ,[contra_account] = ca.[account] -- ,[Belegdatum] = FORMAT(iv.[DateOfCreation], 'dd.MM.yy') -- ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) -- ,iv.[DateOfCreation] -- ,iv.[DueDate] -- ,[PaymentTerm] = @stage1 -- ,ivi.[PaymentStatus] -- ,[IsPayed] = CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL(ivi.[IsPayed],0) END as bit) -- ,[IsCanceled] -- ,[isSent] = @true -- ,[isFinal] = @true -- ,[hasFile] = CAST( CASE wHEN ISNULL([URI], '') <> '' THEN 1 ELSE 0 END as bit) -- ,[fds] = @false -- from [dbo].[mfr__reports] as iv -- LEFT JOIN [dbo].[fds__custom_invoiceinfo] as ivi on iv.[id] = ivi.[invid] -- LEFT JOIN itm on iv.Id = itm.[invoice.Id] -- LEFT JOIN [dbo].[fds__custom_vat] as vat ON iv.[Id] = vat.[EntityId] and vat.[EntityType] = 'report' -- LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 0 -- LEFT JOIN contra_accounts as ca ON ISNULL(vat.[vat], 19.0) = ca.[vat] -- where iv.Id in (SELECT [Id] FROM @inv Where fds = 0) --UNION select [Id] = CAST(iv.[Id] as varchar(15)) ,[InvoiceId] = iv.[InvoiceId] ,[InvoiceType] = CAST( CASE WHEN LEFT([documentname],5) = 'absch' THEN 'i' WHEN LEFT([documentname],5) = 'storn' THEN 'c' ELSE 'r' END as char(1)) ,[DocumentName] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = TRY_CAST(iv.id as varchar(50))) ,[balance] = FORMAT([invoiceBalance], '#0.00', 'de') + ' €' ,[EINZELPOS_brutto] = NULL --FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' ,[EINZELPOS_netto] = NULL --FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' ,[vat] = FORMAT(ISNULL(vat.[vat], ISNULL([dbo].[fds__fn_vatfrombalances]([invoiceBalance], [invoiceBalancenetto]) ,19.0)), '#0.0', 'de') + ' %' ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE TRY_CAST(iv.id as varchar(50)) = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = FORMAT(iv.[DateOfCreation], 'dd.MM.yy') ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE TRY_CAST(iv.id as varchar(50)) = sreq.[invoice.Id]) ,iv.[DateOfCreation] ,iv.[DueDate] ,[PaymentTerm] = @stage1 ,ivi.[PaymentStatus] ,[IsPayed] = CAST(CASE WHEN ISNULL(ivi.isPayed,0) = 1 THEN 1 WHEN [InvoiceState] = 'eIsCancelled' THEN 1 WHEN [InvoiceState] = 'eIsPaid' THEN 1 ELSE 0 END as bit) ,[IsCanceled] = CAST(CASE WHEN [InvoiceState] = 'eIsCancelled' THEN 1 ELSE 0 END as bit) ,[isSent] = @true ,[isFinal] = @true ,[hasFile] = CAST( CASE wHEN ISNULL([URI], '') <> '' THEN 1 ELSE 0 END as bit) ,[fds] = @false ,[customer_id] = ps.[PartnerId] from [dbo].[mfr__invoices] as iv LEFT JOIN [dbo].[fds__custom_invoiceinfo] as ivi on iv.[id] = ivi.[invid] LEFT JOIN itm on TRY_CAST(iv.id as varchar(50)) = itm.[invoice.Id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON iv.[Id] = vat.[EntityId] and vat.[EntityType] = 'report' LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 0 LEFT JOIN contra_accounts as ca ON ISNULL(vat.[vat], 19.0) = ca.[vat] LEFT JOIN [dbo].[mfr__*PartnerSet] as ps ON iv.[Id] = ps.[EntityId] AND ps.[Property] = 'Invoice:Customer' where TRY_CAST(iv.id as varchar(50)) in (SELECT [Id] FROM @inv Where fds = 0) UNION select iv.[Id] ,[InvoiceId] = iv.[InvoiceId] + ISNULL((CASE WHEN iv.InvoiceType = 'c' THEN (SELECT TOP(1) ' >> ' + i2.[InvoiceId] FROM [dbo].[fds__invoices] as i2 JOIN [dbo].[fds__invoice_details] as id2 on i2.[Id] = id2.[StornoTo_InvId] where id2.[InvId] = iv.[id] and i2.[IsFinal] = 1) ELSE '' END), '') ,[InvoiceType] ,[DocumentName] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = FORMAT([invoiceBalance], '#0.00', 'de') + ' €' ,[EINZELPOS_brutto] = NULL --FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' ,[EINZELPOS_netto] = NULL --FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' ,[vat] = FORMAT(ISNULL(iv.[InvoiceVAT_1], 19.0), '#0.0', 'de') + ' %' ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = FORMAT(iv.[DateCreated], 'dd.MM.yy') ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,[DateOfCreation] = iv.[DateCreated] ,[DueDate] ,[PaymentTerm] = ISNULL([PaymentTerm], @stage1) ,[PaymentStatus] ,[IsPayed] = CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END as bit) ,[IsCanceled] = CAST(IIF(ISNULL([IsCanceled],0) = 1 OR [dbo].[fds__fn_isInvoiceCancelled](iv.[Id]) = 1, 1,0) as bit) ,[isSent] ,[isFinal] ,[hasFile] = CAST( CASE wHEN [file] is not null and [DocumentNAme] is not null THEN 1 ELSE 0 END as bit) ,[fds] = @true ,[customer_id] = iv.[CustomerId] from [dbo].[fds__invoices] as iv LEFT JOIN itm on iv.Id = itm.[invoice.Id] LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 1 LEFT JOIN contra_accounts as ca ON ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] where iv.Id in (SELECT [Id] FROM @inv Where fds = 1) ), reminder as ( SELECT [InvId], [lastReminder] = MAX([DateFinalized]), [#] = COUNT(*) FROM [dbo].[fds__reminder] WHERE [isFinal] = 1 AND [invId] IN (SELECT [Id] FROM @inv) GROUP BY [InvId] ) select inv.* ,[reminderstatus] = CASE WHEN [ispayed] = 1 THEN 0 WHEN [iscanceled] = 1 THEN 0 WHEN DueDate is null THEN 0 WHEN [deb_cred] = 'H' THEN 0 WHEN @stage3 <> '' AND rem.[#] = 2 AND @today > [dbo].[date_addcustom]([lastReminder], @stage3) THEN 3 WHEN @stage2 <> '' AND rem.[#] = 1 AND @today > [dbo].[date_addcustom]([lastReminder], @stage2) THEN 2 WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), ISNULL([PaymentTerm],@stage1)) THEN 1 ELSE 0 END ,[invstatus] = CASE WHEN [IsPayed] = 1 AND [isCanceled] = 0 THEN 'pyd' WHEN [isCanceled] = 1 THEN 'cc' WHEN [isFinal] = 0 THEN 'dft' WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN [deb_cred] = 'H' THEN '' WHEN @today >= [DueDate] THEN 'due' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), @stage1) THEN 'ovd' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' END ,[reminder] = rem.[#] ,[CustomerName] = c.[name] ,[order] = CASE WHEN @include_drafts = 1 THEN ROW_NUMBER() OVER (ORDER BY inv.[DateOfCreation] ASC) ELSE ROW_NUMBER() OVER (ORDER BY TRY_CAST(SUBSTRING([invoiceid], 2,4) AS int), TRY_CAST(SUBSTRING([invoiceid], 7,4) AS int), inv.[DateOfCreation] ASC) END ,[Payment] = IIF(py.[amount] is null,'',FORMAT(ISNULL(py.[amount],0.0), '0.00€', 'de') + IIF(py.[manu] = 1, ' man.','')) /*CASE WHEN [paymentstatus] = 'a' THEN 'vollst.' WHEN [paymentstatus] = 'p' THEN FORMAT(ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.[Id]),0.0), '0.00€', 'de') ELSE '' END*/ FROM inv left JOIN reminder as rem ON inv.[Id] = rem.[InvId] --inv.[id] is already converted to varchar LEFT JOIN [dbo].[mfr__companies] as c ON inv.[customer_id] = c.[id] LEFT JOIN [dbo].[fds__fn_bankingtransactions_perInvoice](@startdate, @enddate) as py ON py.[invid] = inv.[Id] WHERE ((@only_reminded = 0 AND @only_remindedunpayed = 0) OR ISNULL(rem.[#],0) > 0) AND (CASE WHEN @only_unpayed = 0 AND @only_remindedunpayed = 0 THEN 1 WHEN [IsCanceled] = 1 THEN 0 ELSE 1 END) = 1 order by inv.[DateOfCreation] ASC; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getInvoices_list_vario] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getInvoices_list2] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getInvoices_list2] @tgtdate date ,@mode varchar(1) = 'm' , @include_drafts bit = 0 , @search varchar(100) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getInvoices_list' ,@authuser , @search); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; DECLARE @searchmode as varchar(1) = CASE WHEN SUBSTRING(ISNULL(@search, '') + ' ', 2,1) <> ':' THEN '' ELSE LOWER(LEFT(@search,1 )) END; DECLARE @customerfilter TABLE ([CustomerID] bigint); IF @searchmode <> '' BEGIN SELECT @mode = 's', @search = SUBSTRING(@search,3, 1000); IF @searchmode = 'c' AND LEN(@search) > 3 BeGIN INSERT INTO @customerfilter SELECT [id] FROM [dbo].[mfr__companies] WHERE [Name] like ('%' + @search + '%'); END END ELSE SET @mode = LOWER(@mode); If @mode = 'm' BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END; --Reminder settings DECLARE @stage1 varchar(10), @stage2 varchar(10), @stage3 varchar(10); SELECT @stage1 = [stage1], @stage2 = [stage2], @stage3 = [stage3] FROM [dbo].[fds__admin_reminderSettings](); SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = 'Rechnungsübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') WHEN @searchmode = 'i' THEN 'Suche nach Rechnungsnummer ''' + @search + '''' WHEN @searchmode = 'c' THEN 'Suche nach Kunde ''' + @search + '''' ELSE '' END ,[ust_options] = '19,0%;16,0%;0,0%'; DECLARE @inv TABLE([Id] varchar(15), [InvoiceID] varchar(255), [URI] nvarchar(255), [DocumentName] nvarchar(255), [DateOfCreation] date, [fds] bit); --INSERT INTO @inv SELECT [Id],[invoiceid],[URI],[DocumentName],[DateOfCreation],[fds] = 0 FROM [dbo].[mfr__reports] where [IsInvoice] = 1 AND CAST([DateOfCreation] as date) between @startdate AND @enddate; INSERT INTO @inv SELECT [Id],[invoiceid],[URI],[DocumentName],[DateOfCreation],[fds] = 0 FROM [dbo].[mfr__invoices] where (CASE WHEN @searchmode = 'i' THEN (CASE WHEN [InvoiceID] = @search OR [InvoiceID] like ('R20[0-9][0-9][-]' + @search) THEN 1 ELSE 0 END) ELSE (CASE WHEN CAST([DateOfCreation] as date) between @startdate AND @enddate and (ISNULL(@include_drafts,0) = 1 OR [FileType] in( 'PdfInvoice','PdfCancelInvoice','PdfPartialInvoice') and ISNULL(InvoiceId,'') not in ('Preview','')) THEN 1 ELSE 0 END) END) = 1; INSERT INTO @inv SELECT [Id],[invoiceid],[URI] = null,[DocumentName],[DateOfCreation] = [DateCreated],[fds] = 1 FROM [dbo].[fds__invoices] where (CASE WHEN @searchmode = 'i' THEN (CASE WHEN [InvoiceID] = @search OR [InvoiceID] like ('R20[0-9][0-9][-]' + @search) THEN 1 ELSE 0 END) WHEN @searchmode = 'c' THEN (CASE WHEN [CustomerId] IN (SELECT [CustomerId] fROM @customerfilter) THEN 1 ELSE 0 END) ELSE (CASE WHEN CAST([DateCreated] as date) between @startdate AND @enddate and (ISNULL(@include_drafts,0) = 1 OR [isfinal] = 1) THEN 1 ELSE 0 END) END) = 1; DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(15), [customer.ExternalId] bigint, [customer.Id] bigint, [ExternalId] nvarchar(255), [fds] bit); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId], [fds] FROM [dbo].[mfr__servicerequests] as s JOIN dbo.[mfr__*PartnerSet] as p on p.[EntityId] = s.[Id] AND p.[Property] = 'ServiceRequest:Invoices' JOIN @inv as i on i.fds = 0 and p.[PartnerId] = i.[id] --s.[InvoiceId] like ('%' + i.[InvoiceId] + '%') LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE i.fds = 0; INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId], [fds] FROM [dbo].[fds__invoice_servicerequests] as irq JOIN @inv as i on irq.[InvId] = i.[Id] LEFT JOIN [dbo].[mfr__servicerequests] as s ON irq.[mfr__servicerequest] = s.[id] LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE i.fds = 1; With itm as ( SELECT [net_itemsum] = CAST( SUM((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL(vat.[vat], 19.0) * 0.01)) , sreq.[invoice.Id] ,[fds] = 0 FROM [dbo].[mfr__items] as itm JOIN @sreq as sreq ON itm.[ServiceRequestId] = SReq.[id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' WHERE [fds] = 0 GROUP BY sreq.[invoice.Id] UNION SELECT [net_itemsum] = CAST( SUM(ISNULL([value_total],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM(ISNULL([value_total],0) * (1 + (ISNULL([vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL([vat], 19.0) * 0.01)) , [invoice.Id] = inv.[id] --sreq.[invoice.Id] , [fds] = 1 FROM [dbo].[fds__invoice_items] as itm --JOIN @sreq as sreq ON itm.[InvRqId] = SReq.[id] JOIN @inv as inv ON itm.[invid] = inv.[id] and [fds] = 1 WHERE [fds] = 1 GROUP BY inv.[id] --sreq.[invoice.Id] ),sc as( SELECT s.[invoice.Id], [fds], [#] = COUNT(s.[id]) FROM @SReq as s GROUP BY s.[invoice.Id], [fds] ),contra_accounts as( SELECT [account] = [key], [vat] = TRY_PARSE([value2] as numeric(5,2) USING 'en-US') FROM [dbo].[fds__admin_settings] WHERE [type] = 'contra_account' ), inv as( --select -- [Id] = CAST(iv.[Id] as varchar(15)) -- ,[InvoiceId] = iv.[InvoiceId] -- ,[InvoiceType] = CAST( CASE WHEN LEFT([documentname],5) = 'absch' THEN 'i' -- WHEN LEFT([documentname],5) = 'storn' THEN 'c' -- ELSE 'r' -- END -- as char(1)) -- ,[DocumentName] -- ,[requestcount] = sc.[#] -- ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) -- ,[balance] = FORMAT(ABS([invoiceBalance]), '#0.00', 'de') + ' €' -- ,[EINZELPOS_brutto] = FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' -- ,[EINZELPOS_netto] = FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' -- ,[vat] = FORMAT(ISNULL(vat.[vat], 19.0), '#0.0', 'de') + ' %' -- ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END -- ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) -- ,[contra_account] = ca.[account] -- ,[Belegdatum] = FORMAT(iv.[DateOfCreation], 'dd.MM.yy') -- ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) -- ,iv.[DateOfCreation] -- ,iv.[DueDate] -- ,[PaymentTerm] = @stage1 -- ,ivi.[PaymentStatus] -- ,[IsPayed] = CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL(ivi.[IsPayed],0) END as bit) -- ,[IsCanceled] -- ,[isSent] = @true -- ,[isFinal] = @true -- ,[hasFile] = CAST( CASE wHEN ISNULL([URI], '') <> '' THEN 1 ELSE 0 END as bit) -- ,[fds] = @false -- from [dbo].[mfr__reports] as iv -- LEFT JOIN [dbo].[fds__custom_invoiceinfo] as ivi on iv.[id] = ivi.[invid] -- LEFT JOIN itm on iv.Id = itm.[invoice.Id] -- LEFT JOIN [dbo].[fds__custom_vat] as vat ON iv.[Id] = vat.[EntityId] and vat.[EntityType] = 'report' -- LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 0 -- LEFT JOIN contra_accounts as ca ON ISNULL(vat.[vat], 19.0) = ca.[vat] -- where iv.Id in (SELECT [Id] FROM @inv Where fds = 0) --UNION select [Id] = CAST(iv.[Id] as varchar(15)) ,[InvoiceId] = iv.[InvoiceId] ,[InvoiceType] = CAST( CASE WHEN LEFT([documentname],5) = 'absch' THEN 'i' WHEN LEFT([documentname],5) = 'storn' THEN 'c' ELSE 'r' END as char(1)) ,[DocumentName] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = TRY_CAST(iv.id as varchar(50))) ,[balance] = FORMAT([invoiceBalance], '#0.00', 'de') + ' €' ,[EINZELPOS_brutto] = NULL --FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' ,[EINZELPOS_netto] = NULL --FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' ,[vat] = FORMAT(ISNULL(vat.[vat], ISNULL([dbo].[fds__fn_vatfrombalances]([invoiceBalance], [invoiceBalancenetto]) ,19.0)), '#0.0', 'de') + ' %' ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END --,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE TRY_CAST(iv.id as varchar(50)) = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = FORMAT(iv.[DateOfCreation], 'dd.MM.yy') ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE TRY_CAST(iv.id as varchar(50)) = sreq.[invoice.Id]) ,iv.[DateOfCreation] ,iv.[DueDate] ,[PaymentTerm] = @stage1 ,ivi.[PaymentStatus] ,[IsPayed] = CAST(CASE WHEN ISNULL(ivi.isPayed,0) = 1 THEN 1 WHEN [InvoiceState] = 'eIsCancelled' THEN 1 WHEN [InvoiceState] = 'eIsPaid' THEN 1 ELSE 0 END as bit) ,[IsCanceled] = CAST(CASE WHEN [InvoiceState] = 'eIsCancelled' THEN 1 ELSE 0 END as bit) ,[isSent] = @true ,[isFinal] = @true ,[hasFile] = CAST( CASE wHEN ISNULL([URI], '') <> '' THEN 1 ELSE 0 END as bit) ,[fds] = @false ,[customer_id] = ps.[PartnerId] from [dbo].[mfr__invoices] as iv LEFT JOIN [dbo].[fds__custom_invoiceinfo] as ivi on iv.[id] = ivi.[invid] LEFT JOIN itm on TRY_CAST(iv.id as varchar(50)) = itm.[invoice.Id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON iv.[Id] = vat.[EntityId] and vat.[EntityType] = 'report' LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 0 LEFT JOIN contra_accounts as ca ON ISNULL(vat.[vat], 19.0) = ca.[vat] LEFT JOIN [dbo].[mfr__*PartnerSet] as ps ON iv.[Id] = ps.[EntityId] AND ps.[Property] = 'Invoice:Customer' where TRY_CAST(iv.id as varchar(50)) in (SELECT [Id] FROM @inv Where fds = 0) UNION select iv.[Id] ,[InvoiceId] = iv.[InvoiceId] + ISNULL((CASE WHEN iv.InvoiceType = 'c' THEN (SELECT TOP(1) ' >> ' + i2.[InvoiceId] FROM [dbo].[fds__invoices] as i2 JOIN [dbo].[fds__invoice_details] as id2 on i2.[Id] = id2.[StornoTo_InvId] where id2.[InvId] = iv.[id] and i2.[IsFinal] = 1) ELSE '' END), '') ,[InvoiceType] ,[DocumentName] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = FORMAT([invoiceBalance], '#0.00', 'de') + ' €' ,[EINZELPOS_brutto] = NULL --FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' ,[EINZELPOS_netto] = NULL --FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' ,[vat] = FORMAT(ISNULL(iv.[InvoiceVAT_1], 19.0), '#0.0', 'de') + ' %' ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END --,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = FORMAT(iv.[DateCreated], 'dd.MM.yy') ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,[DateOfCreation] = iv.[DateCreated] ,[DueDate] ,[PaymentTerm] = ISNULL([PaymentTerm], @stage1) ,[PaymentStatus] ,[IsPayed] = CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END as bit) ,[IsCanceled] ,[isSent] ,[isFinal] ,[hasFile] = CAST( CASE wHEN [file] is not null and [DocumentNAme] is not null THEN 1 ELSE 0 END as bit) ,[fds] = @true ,[customer_id] = iv.[CustomerId] from [dbo].[fds__invoices] as iv LEFT JOIN itm on iv.Id = itm.[invoice.Id] LEFT JOIN sc on iv.[id] = sc.[invoice.Id] and sc.[fds] = 1 LEFT JOIN contra_accounts as ca ON ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] where iv.Id in (SELECT [Id] FROM @inv Where fds = 1) ), reminder as ( SELECT [InvId], [lastReminder] = MAX([DateFinalized]), [#] = COUNT(*) FROM [dbo].[fds__reminder] WHERE [IsFinal] = 1 AND [invId] IN (SELECT [Id] FROM @inv) GROUP BY [InvId] ) select inv.* ,[reminderstatus] = CASE WHEN [ispayed] = 1 THEN 0 WHEN [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 0 WHEN DueDate is null THEN 0 WHEN [deb_cred] = 'H' THEN 0 WHEN @stage3 <> '' AND rem.[#] = 2 AND @today > [dbo].[date_addcustom]([lastReminder], @stage3) THEN 3 WHEN @stage2 <> '' AND rem.[#] = 1 AND @today > [dbo].[date_addcustom]([lastReminder], @stage2) THEN 2 WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), ISNULL([PaymentTerm],@stage1)) THEN 1 ELSE 0 END ,[invstatus] = CASE WHEN [IsPayed] = 1 AND [isCanceled] = 0 THEN 'pyd' WHEN [isCanceled] = 1 OR [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 'cc' WHEN [isFinal] = 0 THEN 'dft' WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN [deb_cred] = 'H' THEN '' WHEN @today >= [DueDate] THEN 'due' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), @stage1) THEN 'ovd' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' END ,[reminder] = rem.[#] ,[CustomerName] = c.[name] ,[order] = CASE WHEN @include_drafts = 1 THEN ROW_NUMBER() OVER (ORDER BY inv.[DateOfCreation] ASC) ELSE ROW_NUMBER() OVER (ORDER BY TRY_CAST(SUBSTRING([invoiceid], 2,4) AS int), TRY_CAST(SUBSTRING([invoiceid], 7,4) AS int), inv.[DateOfCreation] ASC) END ,[Payment] = CASE WHEN [paymentstatus] = 'a' THEN 'vollst.' WHEN [paymentstatus] = 'p' THEN FORMAT(ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.[Id]),0.0), '0.00€', 'de') ELSE '' END FROM inv left JOIN reminder as rem ON inv.[Id] = rem.[InvId] --inv.[id] is already converted to varchar LEFT JOIN [dbo].[mfr__companies] as c ON inv.[customer_id] = c.[id] WHERE (CASE WHEN @searchmode = 'c' THEN (CASE WHEN inv.[customer_id] IN (SELECT [CustomerId] fROM @customerfilter) THEN 1 ELSE 0 END) ELSE 1 END) = 1 order by inv.[DateOfCreation] ASC; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getInvoices_list2] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getInvRequestItems] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getInvRequestItems] @invoiceid varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @idbigint bigint = TRY_CAST(@invoiceid as bigint); DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(20), [customer.ExternalId] bigint, [customer.Id] bigint, [mfr] bit); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = TRY_CAST(i.[Id] as varchar(20)), [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], [mfr] = 1 FROM [dbo].[mfr__servicerequests] as s JOIN [mfr__reports] as i on i.[id] = @idbigint and s.[InvoiceId] like ('%' + i.[InvoiceId] + '%') LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id where i.[id] = @idbigint UNION SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], [mfr] = 0 FROM [dbo].[mfr__servicerequests] as s JOIN [dbo].[fds__invoice_servicerequests] as iq ON s.[id] = iq.[mfr__servicerequest] JOIN [dbo].[fds__invoices] as i on iq.[InvId] = i.[id] AND i.[id] = @invoiceid LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id where i.[id] = @invoiceid ; SELECT [id],[DateOfCreation],[name],[invoice.Id],[customer.ExternalId],[customer.Id], [mfr] ,[order] = ROW_NUMBER() OVER (ORDER BY [DateOfCreation]) FROM @SReq; SELECT itm.[Id] , [net_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , '#0.00 €','de') END , [bo_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , '#0.00 €','de') END , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , sreq.[invoice.Id] , [order] = ROW_NUMBER() OVER (PARTITION BY itm.[ServiceRequestId] ORDER BY itm.[SortOrder]) FROM [dbo].[mfr__items] as itm JOIN @sreq as sreq ON itm.[ServiceRequestId] = SReq.[id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' ; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getInvRequestItems] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getReminder] @Id varchar(8), @includefile bit, @authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 1 THROW 60000, N'not authorized', 1; DECLARE @rem [dbo].[fds__tt__reminder_core]; INSERT INTO @rem SELECT TOP(1) [Id] ,[Version] ,[DocumentName] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[amount_open] ,[subject] ,[text] ,[IsSent] ,[IsFinal] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[file] = CASE WHEN ISNULL(@includefile,0) = 1 THEN [file] else NULL END -- do not return file if not explicitly requested FROM [dbo].[fds__reminder] WHERE [Id] = @Id AND @Id is not null; DECLARE @InvId varchar(15) = (SELECT TOP(1) [InvId] fROM @rem); ---output --admin SELECT TOP(1) [today] , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [CustomerId] = rem.[CustomerId] , [type] = rem.[type] FROM (VALUES(CAST(GETDATE() as date)))base ([today]) cross JOIN @rem as rem; --rem With inv1 as( select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId ), inv as( SELECT [Id] = cast([id] as varchar(15)) ,[Invoiceid] ,[DateFinalized] ,[InvoiceBalance] ,[DocumentName] ,[file] FROM inv1 UNION SELECT [Id] = cast([id] as varchar(15)) ,[Invoiceid] ,[DateFinalized] = [DateOfCreation] ,[InvoiceBalance] ,[DocumentName] ,[file] = NULL FROM [dbo].[mfr__invoices] as mfri WHERE [id] = TRY_CAST(@invId as bigint) AND NOT EXISTS( SELECT 0 FROM inv1 ) --will only be used, if id not present in fds__invoices ) SELECT TOP(1) o.* ,inv.[InvoiceId] ,[InvoiceDate] = inv.[DateFinalized] ,[InvoiceFileName] = inv.[DocumentName] ,[InvoiceFile] = CASE WHEN ISNULL(@includefile,0) = 1 THEN inv.[file] else NULL END -- do not return file if not explicitly requested ,[hasFile] = CAST ( CASE WHEN o.[file] is null THEN 0 ELSE 1 END as bit) ,[UserNameFinalized] = [dbo].[fis_admin_getUserName_byID](o.[UserFinalized]) ,[UserEmailFinalized] = [dbo].[fis_admin_getUserEmail_byID](o.[UserFinalized]) from @rem as o join inv on o.[invid] = inv.[id]; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getReportDocument] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getReportDocument] @reportid varchar(20) AS BEGIN SET NOCOUNT ON; DECLARE @idbigint bigint = TRY_CAST(@reportid as bigint); SELECT TOP(1) [Id] = CAST([Id] as varchar(20)),[InvoiceID],[URI],[DocumentName],[isInvoice] = 1,[DateOfCreation],[fds] = CAST( 0 as bit),[file] = CAST( null as varbinary(max)) ,[order] = ROW_NUMBER() OVER (ORDER BY [DateOfCreation] ASC) FROM [dbo].[mfr__invoices] WHERE [id] = @idbigint and @idbigint is not null UNION SELECT TOP(1) [Id] = CAST([Id] as varchar(20)),[InvoiceID],[URI] = '',[DocumentName],[isInvoice] = 1,[DateOfCreation] = [DateCreated],[fds] = CAST( 1 as bit), [file] ,[order] = ROW_NUMBER() OVER (ORDER BY [DateCreated] ASC) FROM [dbo].[fds__invoices] WHERE [id] = @reportid AND [isFinal] = 1; ; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getReportDocument] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getRequest_details] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getRequest_details] @servicerequestid bigint , @mode varchar(3) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_req', @authuser) < 1 THROW 60000, N'not authorized', 1; DECLARE @today date = GETDATE(); DECLARE @SReq TABLE ( [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] [nvarchar](255) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NOT NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NOT NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] [nvarchar](255) NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsTemplate] [bit] NOT NULL, [IsTemplateMobile] [bit] NOT NULL, [CreateFromServiceRequestTemplateId] [bigint] NOT NULL, [Type] [nvarchar](255) NULL, [Summary] nvarchar(255) NULL, [isChild] bit NULL, [baseorder] int, [provision] varchar(255) NULL, [open] bit NULL ); insert into @SReq SELECT [Id] ,[Name] ,[ExternalId] ,[InvoiceId] ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,[DateModified] ,[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,[CustomValues] ,[CurrentOwnerId] ,[CustomerId] ,[ParentServiceRequestId] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then [id] ELSE [ParentServiceRequestId] END ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 ,[provision] = NULL ,[open] = 1 FROM [dbo].[mfr__servicerequests] as s WHERE [id] = @servicerequestid; INSERT INTO @SReq SELECT s.[Id] ,s.[Name] ,s.[ExternalId] ,s.[InvoiceId] ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 , [provision] = null ,[open] = 1 from [dbo].[mfr__servicerequests] as s JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs WHERE NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) ; -- need to use CTE, because row_number is not available with update statements WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), ISNULL([ParentServiceRequestId],[id])) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder FROM @SReq as s JOIN q ON s.[id] = q.[id]; -- need to use CTE, because row_number is not available with update statements WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; DECLARE @inv TABLE ([Id] bigint, [Invoices] varchar(1000), [isOpen] bit); With fdsinv as( SELECT [Id] = fdsr.[mfr__servicerequest], fdsi.[InvoiceId], fdsi.[InvoiceType], [isCanceled] = ISNULL(fdsi.[isCanceled],0) FROM [dbo].[fds__invoice_servicerequests] as fdsr JOIN [dbo].[fds__invoices] as fdsi on fdsr.[invid] = fdsi.[id] JOIN @SReq as s ON fdsr.[mfr__servicerequest] = s.[id] WHERE [isFinal] = 1 AND fdsr.[mfr__servicerequest] is not null ), fi as( SELECT [Id], [isOpen] = MIN(CASE WHEN ISNULL([invoicetype],'r') = 'r' AND [isCanceled] = 0 THEN 0 ELSE 1 END) FROM fdsinv GROUP BY [Id] ) INSERT INTO @inv SELECT [Id] , [invoices] = ISNULL(STUFF( (SELECT CHAR(10) + [InvoiceId] + ' (' + [InvoiceTYpe] + ')' FROM fdsinv as f2 WHERE f2.[id] = fi.[Id] FOR XML PATH, TYPE).value('.[1]','nvarchar(max)') ,1,1,'') , '') , [isOpen] FROM fi; UPDATE s SET s.[invoiceid] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,[open] = 1 --CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END FROM @SReq as s LEFT JOIN @inv as inv on s.[id] = inv.[id]; DECLARE @step TABLE ( [Id] [bigint] NOT NULL, [MobileId] [bigint] NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [IsDone] [bit] NOT NULL, [HasError] [bit] NOT NULL, [TrackingId] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [SortOrder] [int] NOT NULL, [Data] [nvarchar](max) NULL, [DateModifiedOffline] [datetime] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [Comment] [nvarchar](max) NULL, [InternalComment] [nvarchar](max) NULL, [ServiceObjectId] [bigint] NULL, [StepListTemplateId] [bigint] NULL, [ParentId] [bigint] NULL, [order] int NOT NULL ); DECLARE @company TABLE ( [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsPhysicalPerson] [bit] NOT NULL, [IsOwner] [bit] NOT NULL, [IsEmailInvoicingActive] [bit] NOT NULL, [IsSupplier] [bit] NOT NULL, [MappingId] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [SupportTelephone] [nvarchar](255) NULL, [SupportFax] [nvarchar](255) NULL, [SupportMail] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [MainContactId] [bigint] NOT NULL, [address] nvarchar(1000) null ); INSERT INTO @company SELECT DISTINCT cy.*, [address] = [dbo].[fds__getCompanyAddress](cy.[id]) FROM [mfr__companies] as cy JOIN @SReq as s on cy.id = s.[CustomerId]; DECLARE @companyids [dbo].[fds__tt__idlist]; INSERT INTO @companyids SELECT DISTINCT [id] FROM @company; /** OUTPUT + get other types **/ IF @mode in ('r','ov', '','f', 'ful') BEGIN WITH app as( SELECT [start] = MIN(CAST(CASE WHEN a.[StartDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[StartDateTime] as date) > s.[workdoneat] THEN CAST(a.[StartDateTime] as date) ELSE s.[workdoneat] END as date)) , [end] = MAX(CAST(CASE WHEN a.[EndDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[EndDateTime] as date) > s.[workdoneat] THEN CAST(a.[EndDateTime] as date) ELSE s.[workdoneat] END as date)) , [CustomerId] = MAX (s.customerid) , [ParentServiceRequestId] = ISNULL(MIN(CASE WHEN [isChild] = 1 then null else s.[Id] END), MAX([ParentServiceRequestId])) --make sure only one returned FROM [dbo].[mfr__appointments] as a RIGHT JOIN @SReq as s on a.[ServiceRequestId] = s.[Id] AND a.[State] in ('IsWorkDone') ) SELECT TOP(1) [today] , [provisionstart] = CASe WHEN [start] = [end] THEN NULL ELSE [start] END , [provisionend] = [end] , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [paymentterms] = N'10wd' , [invoiceemail] = (SELECT TOP(1) [SupportMail] FROM @company where IsEmailInvoicingActive = 1) , [invoiceaddress] = (SELECT TOP(1) CONCAT([name], CHAR(10), [address]) FROM @company ORDER BY IsEmailInvoicingActive DESC) , [tax_servicerefund] = 0.2 , [CustomerId] = [CustomerId] , [search] = @servicerequestid , [parent] = app.[ParentServiceRequestId] FROM (VALUES(CAST(GETDATE() as date)))base ([today]) CROSS JOIN app; SELECT * ,[order] = ROW_NUMBER() OVER (ORDER BY [baseorder]) FROM @SReq; END IF @mode in ('i','ov') BEGIN SELECT itm.[Id] , [net_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , '#0.00 €','de') END , [bo_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , '#0.00 €','de') END , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , itm.[Note] , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY itm.[ServiceRequestId] ORDER BY itm.[SortOrder]) FROM [dbo].[mfr__items] as itm JOIN @SReq as s ON itm.ServiceRequestId = s.[Id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' ; END ELSE IF @mode in ('f', 'ful') BEGIN SELECT itm.[Id] , [net] = ISNULL([Price],0) , [quantityhours] = ISNULL([quantityhours],1) , itm.[UnitString] , [net_val] = CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , [bo_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , [vat_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * ((ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , itm.[Note] , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY itm.[ServiceRequestId] ORDER BY itm.[SortOrder], itm.[Id]) FROM [dbo].[mfr__items] as itm JOIN @SReq as s ON itm.ServiceRequestId = s.[Id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' ; END IF @mode in ('f', 'ful') BEGIN INSERT INTO @step SELECT stp.* , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY stp.[ServiceRequestId] ORDER BY stp.[SortOrder], stp.[Id]) FROM [dbo].[mfr__steps] as stp JOIN @SReq as s ON stp.ServiceRequestId = s.[Id]; SELECT * from @step; SELECT cc.[Id] , [CompanyName] = cc.[name] , ct.[Gender] , ct.[FirstName] , ct.[LastName] , ct.[Email] , cc.[address] FROM [dbo].[fds__getCompanysContacts](@companyids) as ct join @company as cc on cc.[Id] = ct.[CyId]; SELECT DISTINCT [ref] = 'Einsatzort ' + so.[name] ,[address] = [dbo].[fds__fn_combineAddress] (so.[Name], loc.[AddressString], null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:ServiceObjects' and p.[EntityId] = s.[id] LEFT JOIN [mfr__serviceobjects] as so ON so.id = p.[PartnerId] LEFT JOIN [mfr__*PartnerSet] as po ON p.property = 'ServiceObject:Location' and po.[EntityId] = so.[Id] LEFT join [dbo].[mfr__#locations] as loc ON (loc.[id] = so.[Location#ID] OR po.[PartnerId] = loc.[Id] OR (so.[Id] = loc.[EntityId] and loc.Property = 'ServiceObject:Location')) WHERE so.id is not null and loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Auftragsort ' + [name] ,[address] = [dbo].[fds__fn_combineAddress] (loc.[AddressString], null, null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:Location' and p.[EntityId] = s.[id] join [dbo].[mfr__#locations] as loc ON (s.[Location#ID] = loc.[id] OR p.[PartnerId] = loc.[Id] OR (s.[Id] = loc.[EntityId] and loc.Property = 'ServiceRequest:Location')) WHERE loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Kunde' , [address] FROM @company; END --get invoices --Reminder settings DECLARE @stage1 varchar(10), @stage2 varchar(10), @stage3 varchar(10); SELECT @stage1 = [stage1], @stage2 = [stage2], @stage3 = [stage3] FROM [dbo].[fds__admin_reminderSettings](); With inv as( SELECT [id] = CAST(ir.invid as varchar(20)), [isChild] = CAST(MIN(CAST(s.[isChild] as tinyint)) as BIT), [baseorder] = MIN(s.[baseorder]), [sopen] = CAST( MIN( CAST(s.[open] as tinyint) ) as bit) FROM [dbo].[fds__invoice_servicerequests] as ir JOIN @sreq as s ON ir.[mfr__servicerequest] = s.[id] GROUP by ir.invid UNION SELECT [id] = CAST(i.[id] as varchar(20)), [isChild] = CAST(MIN(CAST(s.[isChild] as tinyint)) as BIT), [baseorder] = MIN(s.[baseorder]), [sopen] = CAST( MIN( CAST(s.[open] as tinyint) ) as bit) FROM [dbo].[mfr__servicerequests] as ms JOIN @sreq as s on ms.[id] = s.[id] JOIN [mfr__invoices] as i on ms.[InvoiceId] like ('%' + i.[InvoiceId] + '%') GROUP by i.[id] ),reminder as ( SELECT [InvId], [lastReminder] = MAX([DateSent]), [#] = COUNT(*) FROM [dbo].[fds__reminder] WHERE [isSent] = 1 AND [invId] IN (SELECT [Id] FROM inv) GROUP BY [InvId] ) SELECT [Id] = CAST(i.[Id] as varchar(20)) ,i.[DateCreated] ,[isFinal] ,[isSent] ,i.[DocumentName] ,[invstatus] = CASE WHEN [IsPayed] = 1 AND [isCanceled] = 0 THEN 'pyd' WHEN [isCanceled] = 1 OR [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 'cc' WHEN [isFinal] = 0 THEN 'dft' WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN [invoiceBalance] < 0 THEN '' WHEN @today >= [DueDate] THEN 'due' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, i.[DateCreated]), @stage1) THEN 'ovd' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' END ,[order] = ROW_NUMBER() OVER ( ORDER BY inv.[isChild], inv.[baseorder], i.[isFinal] DESC, i.[datecreated] ASC ) FROM [dbo].[fds__invoices] as i JOIN inv on i.[Id] = inv.[Id] LEFT JOIN reminder as rem on inv.id = rem.[InvId] WHERE (inv.[sopen] = 1 OR i.[isfinal] = 1) --- don't show any draft invoices for final tasks; UNION SELECT [Id] = CAST(i.[Id] as varchar(20)) ,[DateCreated] = i.[DateOfCreation] ,[isFinal] = 1 ,[isSent] = 1 ,i.[DocumentName] ,[invstatus] = CASE WHEN [invoicestate] in ('eIsPaid') THEN 'pyd' WHEN [invoicestate] in ('eIsCancelled') THEN 'cc' --WHEN [isFinal] = 0 THEN 'dft' --WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN @today >= [DueDate] THEN 'due' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, i.[DateofCreation]), @stage1) THEN 'ovd' END ,[order] = ROW_NUMBER() OVER ( ORDER BY inv.[isChild], inv.baseorder, i.[dateofcreation] ASC) FROM [dbo].[mfr__invoices] as i JOIN inv on TRY_CAST(i.[Id] as varchar(20)) = inv.[Id] LEFT JOIN reminder as rem on inv.id = rem.[InvId]; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getRequest_details] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getRequests_list] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getRequests_list] @tgtdate date ,@mode varchar(1) = '' ,@completed bit = 1 ,@authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_req', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getRequests_list' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); SET @mode = ISNULL(LOWER(@mode),''); If @mode in ('r') -- r = open recent BEGIN SET @tgtdate = @today; SELECT @startdate = DATEADD(week, -4, [dbo].[date_weekfirst](@tgtdate)) ,@enddate = @today; END else If @mode in ('m') -- r = open recent BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END DECLARE @openmode as bit = CASE WHEN LOWER(LEFT(ISNULL(@mode, ''),1)) IN ('o', 'r') THEN 1 ELSE 0 END; SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = CASE WHEN @openmode = 1 AND @mode = 'r' THEN 'Übersicht der offenen Aufträge (letzte 4 Wochen seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ')' WHEN @openmode = 1 THEN 'Übersicht der offenen Aufträge' ELSE 'Auftragsübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') ELSE '' END END , [note] = CASE WHEN @openmode = 1 and @mode = 'r' THEN 'Es werden alle Aufträge angezeigt, die selbst offen sind und seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden, oder deren Folgeauftrag offen ist und/oder seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden.' WHEN @openmode = 1 THEN 'Es werden alle Aufträge angezeigt, die selbst oder ein Folgeeauftrag offen ist.' ELSE '' END; DECLARE @SReq TABLE ( [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] varchar(1000) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] varchar(1000) NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](255) NULL, [CustomerName] [nvarchar](255) NULL, [isChild] bit NULL, [open] bit, [baseorder] int ); DECLARE @inv TABLE ([Id] bigint, [Invoices] varchar(1000), [isOpen] bit); With fdsinv as( SELECT [Id] = fdsr.[mfr__servicerequest], fdsi.[InvoiceId], fdsi.[InvoiceType], [isCanceled] = ISNULL(fdsi.[isCanceled],0) FROM [dbo].[fds__invoice_servicerequests] as fdsr JOIN [dbo].[fds__invoices] as fdsi on fdsr.[invid] = fdsi.[id] WHERE [isFinal] = 1 AND fdsr.[mfr__servicerequest] is not null ), fi as( SELECT [Id], [isOpen] = MIN(CASE WHEN ISNULL([invoicetype],'r') = 'r' AND [isCanceled] = 0 THEN 0 ELSE 1 END) FROM fdsinv GROUP BY [Id] ) INSERT INTO @inv SELECT [Id] , [invoices] = ISNULL(STUFF( (SELECT CHAR(10) + [InvoiceId] + ' (' + [InvoiceTYpe] + ')' FROM fdsinv as f2 WHERE f2.[id] = fi.[Id] FOR XML PATH, TYPE).value('.[1]','nvarchar(max)') ,1,1,'') , '') , [isOpen] FROM fi; insert into @SReq SELECT s.[Id] ,[Name] ,[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,s.[CustomValues] ,[CurrentOwnerId] ,s.[CustomerId] ,[ParentServiceRequestId] ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,s.[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 FROM [dbo].[mfr__servicerequests] as s -- parent and childs; LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE ([type] in ('IsProject', 'IsMaintenance') AND (CASE WHEN @openmode = 1 AND @mode = 'r' THEN ( CASE WHEN [workdoneat] is not null --AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' --AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) AND (CAST([DateOfCreation] as date) BETWEEN @startdate AND @today OR CAST([DateModified] as date) BETWEEN @startdate AND @today) AND EXISTS (SELECT 0 FROM [dbo].[mfr__*PartnerSet] as ps JOIN [dbo].[mfr__tags] as tg on ps.Property = 'ServiceRequest:Tags' and tg.Id = ps.[PartnerId] where EntityId = s.[id] and ps.partnerid = 16034758659 and [Type] = 'ServiceRequest') THEN 1 ELSE 0 END) WHEN @openmode = 1 AND @mode <> 'r' THEN ( CASE WHEN [workdoneat] is not null AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) THEN 1 ELSE 0 END) WHEN @openmode = 0 THEN ( CASE WHEN CAST([DateOfCreation] as date) BETWEEN @startdate AND @enddate THEN 1 ELSE 0 END) ELSE 0 END ) = 1); INSERT INTO @SReq SELECT DISTINCT ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) ,ISNULL(s.[Name], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN ' - - unbekannt - - ' ELSE NULL END) ,s.[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 from [dbo].[mfr__servicerequests] as s RIGHT JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE (s.[type] in ('IsProject', 'IsMaintenance') AND NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) AND ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) is not null ) ; WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), CASE WHEN ISNULL([ParentServiceRequestId],0) = 0 THEN [id] ELSE [ParentServiceRequestId] END) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder ,[ParentServiceRequestId] = CASE WHEN s.isChild = 0 THEN s.[Id] ELSE s.[ParentServiceRequestId] END FROM @SReq as s JOIN q ON s.[id] = q.[id]; UPDATE s SET [CustomerName] = c.[name] FROM @SReq as s JOIN [mfr__companies] as c ON s.[CustomerId] = c.[id]; WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation], s.[Id]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; ---OUTPUT WITH tgs as( SELECT ps.[EntityId], tg.* FROM [dbo].[mfr__tags] as tg JOIN [dbo].[mfr__*PartnerSet] as ps ON ps.[Property] = 'ServiceRequest:Tags' and tg.[Id] = ps.[PartnerId] AND ISNULL(tg.[Name],'') <> '' and [Type] = 'ServiceRequest' WHERE tg.Id in (16288120843 ,15842181123 ,16034758659 ,16050520064 ,16783966210 ,16802480128 ,16830398466 ,19650019330 ,19670532096 ,18925977600) AND EXISTS (SELECT 0 FROM @SReq as _s where _s.Id = ps.[EntityId]) ) SELECT s.* ,[tags] = STUFF( (SELECT ',' + TRIM([Name]) FROM tgs where tgs.[EntityId] = s.[Id] order by tgs.[name] FOR XML PATH, TYPE).value('.[1]','varchar(255)'), 1,1,'') FROM @SReq as s order by baseorder SELECT [requestID] = s.[Id] ,r.* ,[order] = ROW_NUMBER() OVER (PARTITION BY s.[Id] ORDER BY r.[dateofcreation] ASC, r.[Id]) FROM [dbo].[mfr__invoices] as r JOIN [dbo].[mfr__*PartnerSet] as ps ON ps.[Property] like 'ServiceRequest:Invoices' and r.[id] = ps.PartnerId JOIN @SReq as s ON s.[Id] = ps.[EntityId] ORDER BY s.[Id], r.[dateofcreation] ASC; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getRequests_list] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__getRequests_list2] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__getRequests_list2] @tgtdate date ,@mode varchar(1) = '' ,@completed bit = 1 , @search varchar(100) ,@authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_req', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getRequests_list' ,@authuser , @search); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @searchmode as varchar(1) = CASE WHEN SUBSTRING(ISNULL(@search, '') + ' ', 2,1) <> ':' THEN '' ELSE LOWER(LEFT(@search,1 )) END; IF @searchmode <> '' BEGIN SELECT @mode = 's', @search = SUBSTRING(@search,3, 1000); END ELSE SET @mode = LOWER(@mode); If @mode in ('r') -- r = open recent BEGIN SET @tgtdate = @today; SELECT @startdate = DATEADD(week, -4, [dbo].[date_weekfirst](@tgtdate)) ,@enddate = @today; END else If @mode in ('m') -- r = open recent BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END DECLARE @openmode as bit = CASE WHEN LOWER(LEFT(ISNULL(@mode, ''),1)) IN ('o', 'r') THEN 1 ELSE 0 END; SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = CASE WHEN @searchmode = 'n' THEN 'Übersicht der Aufträge mit der Auftragsnummer ' + @search WHEN @openmode = 1 AND @mode = 'r' THEN 'Übersicht der offenen Aufträge (letzte 4 Wochen seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ')' WHEN @openmode = 1 THEN 'Übersicht der offenen Aufträge' ELSE 'Auftragsübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') ELSE '' END END , [note] = CASE WHEN @searchmode = 'n' THEN 'Es wird nur der Auftrag mit der Nummer ' + @search + ' angezeigt' WHEN @openmode = 1 and @mode = 'r' THEN 'Es werden alle Aufträge angezeigt, die selbst offen sind und seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden, oder deren Folgeauftrag offen ist und/oder seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden.' WHEN @openmode = 1 THEN 'Es werden alle Aufträge angezeigt, die selbst oder ein Folgeeauftrag offen ist.' ELSE '' END; DECLARE @SReq TABLE ( [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] varchar(1000) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] varchar(1000) NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](255) NULL, [CustomerName] [nvarchar](255) NULL, [isChild] bit NULL, [open] bit, [baseorder] int ); DECLARE @inv TABLE ([Id] bigint, [Invoices] varchar(1000), [isOpen] bit); With fdsinv as( SELECT [Id] = fdsr.[mfr__servicerequest], fdsi.[InvoiceId], fdsi.[InvoiceType], [isCanceled] = ISNULL(fdsi.[isCanceled],0) FROM [dbo].[fds__invoice_servicerequests] as fdsr JOIN [dbo].[fds__invoices] as fdsi on fdsr.[invid] = fdsi.[id] WHERE [isFinal] = 1 AND fdsr.[mfr__servicerequest] is not null ), fi as( SELECT [Id], [isOpen] = MIN(CASE WHEN ISNULL([invoicetype],'r') = 'r' AND [isCanceled] = 0 THEN 0 ELSE 1 END) FROM fdsinv GROUP BY [Id] ) INSERT INTO @inv SELECT [Id] , [invoices] = ISNULL(STUFF( (SELECT CHAR(10) + [InvoiceId] + ' (' + [InvoiceTYpe] + ')' FROM fdsinv as f2 WHERE f2.[id] = fi.[Id] FOR XML PATH, TYPE).value('.[1]','nvarchar(max)') ,1,1,'') , '') , [isOpen] FROM fi; WITH s as ( SELECT * FROM [dbo].[mfr__servicerequests] as _s WHERE (CASE WHEN @searchmode = 'n' THEN ( CASE WHEN [ExternalId] = @search OR [ExternalId] like ('_[-]' + @search) THEN 1 ELSE 0 END ) WHEN @openmode = 1 AND @mode = 'r' THEN ( CASE WHEN [workdoneat] is not null --AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' --AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = _s.[id] and sr.[hidden] = 1) AND (CAST([DateOfCreation] as date) BETWEEN @startdate AND @today OR CAST([DateModified] as date) BETWEEN @startdate AND @today) AND EXISTS (SELECT 0 FROM [dbo].[mfr__*PartnerSet] as ps JOIN [dbo].[mfr__tags] as tg on ps.Property = 'ServiceRequest:Tags' and tg.Id = ps.[PartnerId] where EntityId = _s.[id] and ps.partnerid = 16034758659 and [Type] = 'ServiceRequest') THEN 1 ELSE 0 END) WHEN @openmode = 1 AND @mode <> 'r' THEN -- will be covered later because invoice info is included 1 --( CASE WHEN -- [workdoneat] is not null -- AND ISNULL(s.[invoiceid],'') = '' -- AND ISNULL([State], '') <> 'Closed' -- AND ISNULL(inv.[isOpen],1) = 1 -- AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) -- THEN 1 ELSE 0 END) WHEN @openmode = 0 THEN ( CASE WHEN CAST([DateOfCreation] as date) BETWEEN @startdate AND @enddate THEN 1 ELSE 0 END) ELSE 0 END ) = 1 ) insert into @SReq SELECT s.[Id] ,[Name] ,[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,s.[CustomValues] ,[CurrentOwnerId] ,s.[CustomerId] ,[ParentServiceRequestId] ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,s.[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 FROM s -- parent and childs; LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE ([type] in ('IsProject', 'IsMaintenance') AND (CASE WHEN @openmode = 1 AND @mode <> 'r' THEN ( CASE WHEN [workdoneat] is not null AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) THEN 1 ELSE 0 END) ELSE 1 END -- heres the difference, because main filter is applied in CTE ) = 1); INSERT INTO @SReq SELECT DISTINCT ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) ,ISNULL(s.[Name], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN ' - - unbekannt - - ' ELSE NULL END) ,s.[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 from [dbo].[mfr__servicerequests] as s RIGHT JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE (s.[type] in ('IsProject', 'IsMaintenance') AND NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) AND ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) is not null ) ; WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), CASE WHEN ISNULL([ParentServiceRequestId],0) = 0 THEN [id] ELSE [ParentServiceRequestId] END) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder ,[ParentServiceRequestId] = CASE WHEN s.isChild = 0 THEN s.[Id] ELSE s.[ParentServiceRequestId] END FROM @SReq as s JOIN q ON s.[id] = q.[id]; UPDATE s SET [CustomerName] = c.[name] FROM @SReq as s JOIN [mfr__companies] as c ON s.[CustomerId] = c.[id]; WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation], s.[Id]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; ---OUTPUT WITH tgs as( SELECT ps.[EntityId], tg.* FROM [dbo].[mfr__tags] as tg JOIN [dbo].[mfr__*PartnerSet] as ps ON ps.[Property] = 'ServiceRequest:Tags' and tg.[Id] = ps.[PartnerId] AND ISNULL(tg.[Name],'') <> '' and [Type] = 'ServiceRequest' WHERE tg.Id in (16288120843 ,15842181123 ,16034758659 ,16050520064 ,16783966210 ,16802480128 ,16830398466 ,19650019330 ,19670532096 ,18925977600) AND EXISTS (SELECT 0 FROM @SReq as _s where _s.Id = ps.[EntityId]) ) SELECT s.* ,[tags] = STUFF( (SELECT ',' + TRIM([Name]) FROM tgs where tgs.[EntityId] = s.[Id] order by tgs.[name] FOR XML PATH, TYPE).value('.[1]','varchar(255)'), 1,1,'') FROM @SReq as s order by baseorder SELECT [requestID] = s.[Id] ,r.* ,[order] = ROW_NUMBER() OVER (PARTITION BY s.[Id] ORDER BY r.[dateofcreation] ASC, r.[Id]) FROM [dbo].[mfr__invoices] as r JOIN [dbo].[mfr__*PartnerSet] as ps ON ps.[Property] like 'ServiceRequest:Invoices' and r.[id] = ps.PartnerId JOIN @SReq as s ON s.[Id] = ps.[EntityId] ORDER BY s.[Id], r.[dateofcreation] ASC; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__getRequests_list2] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__lookupReminders] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__lookupReminders] @InvId varchar(15) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2 THROW 60000, N'not authorized', 1; ELSE IF NOT EXISTS (select 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId) AND NOT EXISTS (select 0 FROM [dbo].[mfr__invoices] WHERE [id] = TRY_CAST(@InvId as bigint)) THROW 60000, N'invoice not found', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__lookupReminders' ,@authuser , (SELECT * FROM (VALUES(@InvId, @authuser)) as z ([InvId],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); DECLARE @REM TABLE ( [Id] [varchar](10) NOT NULL, [Version] [int] NOT NULL, [DocumentName] [varchar](100) NULL, [InvId] [varchar](15) NOT NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [type] [varchar](3) NOT NULL, [amount] [numeric](10, 3) NULL, [amount_payed] [numeric](10, 3) NULL, [amount_open] [numeric](10, 3) NULL, [subject] [nvarchar](255) NULL, [text] [nvarchar](2000) NULL, [IsSent] [bit] NOT NULL, [IsFinal] [bit] NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](25) NOT NULL, [DateModified] [datetime] NOT NULL, [UserModified] [varchar](25) NOT NULL, [order] int ); INSERT INTO @REM ([Id] ,[Version] ,[DocumentName] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[subject] ,[text] ,[IsSent] ,[IsFinal] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[order]) SELECT [Id] ,[Version] ,[DocumentName] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[subject] ,[text] ,[IsSent] ,[IsFinal] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] , [order] = ROW_NUMBER() OVER (ORDER BY DateFinalized ASC) FROM [dbo].[fds__reminder] WHERE [invid] = @InvId AND [IsFinal] = 1; DECLARE @last varchar(1) = ISNULL(( SELECT TOP(1) [type] FROM @rem ORDER BY [DateFinalized] DESC), ''); DECLARE @newnum int = CASE WHEN @last IN('l','f') THEN (SELECT COUNT(*) FROM @REM) + 1 WHEN @last = 'm' THEN ISNULL( (SELECT TOP(1) TRY_CAST(LEFT([type],1) as int) FROM @rem ORDER BY [DateFinalized] DESC) , (SELECT COUNT(*) FROM @REM) + 1) ELSE 1 END; ---output SELECT [type] = CAST( CASE WHEN @last = 'f' THEN 'm' WHEN @last = 'm' THEN 'l' ELSE 'f' END as varchar(1)) ,[level] = @newnum; SELECT [subject], [amount], [amount_payed], [DateFinalized] FROM @REM; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__lookupReminders] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__prepReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__prepReminder] @InvId varchar(15) , @authuser varchar(100) , @type varchar(1) , @level int AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2 THROW 60000, N'not authorized', 1; ELSE IF ISNULL(@type,'') NOT IN ('f','m','l') OR ISNULL(@level, 0) < 1 THROW 60000, N'inputs not valid', 1; ELSE IF NOT EXISTS (select 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId) AND NOT EXISTS (select 0 FROM [dbo].[mfr__invoices] WHERE [id] = TRY_CAST(@InvId as bigint)) THROW 60000, N'invoice not found', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__prepReminder' ,@authuser , (SELECT * FROM (VALUES(@InvId, @authuser, @type, @level)) as z ([InvId],[authuser],[type],[level]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); DECLARE @now datetime = GETDATE(); DECLARE @today date = CAST(@now as date); --output With inv1 as( select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId ), inv as( SELECT [Id] = cast([id] as varchar(15)) ,[PaymentTerm] ,[SendToemail] ,[SendToAddress] ,[CustomerId] ,[Invoiceid] ,[DateFinalized] ,[InvoiceBalance] FROM inv1 UNION SELECT [Id] = cast([id] as varchar(15)) ,[PaymentTerm] = '10wd' ,[SendToEmail] = sy.[SupportMail] ,[SendToAddress] = (select TOP(1) sy.[name] + CHAR(10) + l.[addressString] + CHAR(10) + l.[postal] + ' ' + l.[city] + CHAR(10) + l.[country] from [dbo].[mfr__#locations] as l where l.[EntityId] = sy.[CustomerId]) ,[CustomerId] ,[Invoiceid] ,[DateFinalized] = [DateOfCreation] ,[InvoiceBalance] FROM [dbo].[mfr__invoices] as mfri LEFT JOIN (SELECT TOP(1) [invid] = p.[PartnerId], s.[CustomerId], cy.[supportmail], cy.[Name] FROM dbo.[mfr__*PartnerSet] as p JOIN [dbo].[mfr__servicerequests] as s on p.[EntityId] = s.[Id] AND p.[Property] = 'ServiceRequest:Invoices' JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id WHERE p.PartnerId = TRY_CAST(@invId as bigint)) as sy on mfri.Id = sy.[invid] WHERE [id] = TRY_CAST(@invId as bigint) AND NOT EXISTS( SELECT 0 FROM inv1 ) --will only be used, if id not present in fds__invoices AND [Filetype] not in ('PdfCancelInvoice') AND [invoiceState] not in ('eIsCancelled','eIsPaid') ) SELECT TOP(1) [today] = @today , [invid] = inv.[id] , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [paymentterms] = [PaymentTerm] , [invoiceemail] = [SendToemail] , [invoiceaddress] = [SendToAddress] , [CustomerId] = [CustomerId] , [subject] = CASE WHEN @type = 'f' THEN N'Zahlungserinnerung' WHEN @type = 'm' THEN FORMAT(@level,'0','de-de') + N'. Mahnung' WHEN @type = 'l' THEN N'Letzte außergerichtliche Mahnung' ELSE N'Zahlungserinnerung' END , [type] = @type , [invoiceid] = inv.[Invoiceid] , [invoicedate] = inv.[DateFinalized] , [amount] = inv.[InvoiceBalance] , [amount_payed] = CAST( ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.[Id]),0.0) as numeric(10,2)) FROM inv; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__prepReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__prepStorno_recreate] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__prepStorno_recreate] @InvId varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__prepStorno_recreate' ,@authuser , ''); DECLARE @today date = GETDATE(); DECLARE @type char(1) = 'r'; DECLARE @selReq as TABLE ([id] bigint); IF EXISTS (SELECT 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1) BEGIN INSERT INTO @selReq SELECT DISTINCT irq.[mfr__servicerequest] from [dbo].[fds__invoice_servicerequests] as irq where InvId = @InvId; END ELSE IF EXISTS (SELECT 0 FROM [dbo].[mfr__invoices] as _i where TRY_CAST(_i.[Id] as varchar(20)) = @InvId AND [FileType] in ('PdfInvoice','PdfPartialInvoice')) BEGIN INSERT INTO @selReq SELECT DISTINCT ps.[PartnerId] from [dbo].[mfr__invoices] as _i JOIN [mfr__*PartnerSet] as ps ON _i.[Id] = ps.[EntityId] and ps.[Property] = 'Invoice:SourceServiceRequest' where TRY_CAST(_i.Id as varchar(20)) = @InvId and EXISTS ( SELECT 0 FROM [dbo].[mfr__servicerequests] as _s WHERE _s.[Id] = ps.[PartnerId]); END DECLARE @SReq TABLE ( [Id] [bigint] NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] [nvarchar](255) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] [nvarchar](255) NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](255) NULL, [Summary] nvarchar(255) NULL, [isChild] bit NULL, [baseorder] int, [provision] varchar(255) NULL ); insert into @SReq SELECT [Id] ,[Name] ,[ExternalId] ,[InvoiceId] ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,[DateModified] ,[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,[CustomValues] ,[CurrentOwnerId] ,[CustomerId] ,[ParentServiceRequestId] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then [id] ELSE s.[ParentServiceRequestId] END ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 ,[provision] = NULL FROM [dbo].[mfr__servicerequests] as s WHERE [id] IN (SELECT [Id] from @selReq); IF @type <> 'i' -- for interim invoices, only one selected servicerequest is allowed -> childs and parents are ignored BEGIN INSERT INTO @SReq SELECT s.[Id] ,s.[Name] ,s.[ExternalId] ,s.[InvoiceId] ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 , [provision_start] = null from [dbo].[mfr__servicerequests] as s JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs WHERE NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) END; WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), ISNULL([ParentServiceRequestId],[id])) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder FROM @SReq as s JOIN q ON s.[id] = q.[id]; WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; IF @type <> 'i' BEGIN DELETE s FROM @SReq as s WHERE NOT EXISTS(SELECT * FROM @selReq as sel where sel.[id] = s.[Id]) END DECLARE @step [dbo].[fds__tt__mfr_steps]; DECLARE @itm [dbo].[fds__tt__mfr_items]; DECLARE @company TABLE ( [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsPhysicalPerson] [bit] NOT NULL, [IsOwner] [bit] NOT NULL, [IsEmailInvoicingActive] [bit] NOT NULL, [IsSupplier] [bit] NOT NULL, [MappingId] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [SupportTelephone] [nvarchar](255) NULL, [SupportFax] [nvarchar](255) NULL, [SupportMail] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [MainContactId] [bigint] NOT NULL, [address] nvarchar(1000) null ); INSERT INTO @company SELECT DISTINCT cy.*, [address] = [dbo].[fds__getCompanyAddress](cy.[id]) FROM [mfr__companies] as cy JOIN @SReq as s on cy.id = s.[CustomerId]; DECLARE @companyids [dbo].[fds__tt__idlist]; INSERT INTO @companyids SELECT DISTINCT [id] FROM @company; INSERT INTO @itm SELECT itm.*, [baseorder] = s.[baseorder], [order] = ROW_NUMBER() OVER (PARTITION BY [ServiceRequestId] ORDER BY [SortOrder], itm.[Id]) from [dbo].[mfr__items] as itm JOIN @SReq as s ON itm.ServiceRequestId = s.[Id]; DECLARE @NUM_of_int_Invoices int = 0; -- Add virtual items for intermediate invoices INSERT INTO @itm SELECT [Id] = -2 ,[Version] = 0 ,[QuantityHours] = 1 ,[PlannedQuantityHours] = 1 ,[ItemTypeId] = NULL ,[ItemNumber] = NULL ,[TrackingId] = NULL ,[Manufacture] = NULL ,[Price] = inv.InvoiceBalance_net * -1.0 --without VAT ,[Costs] = inv.InvoiceBalance_net * -1.0 --without VAT ,[NameOrNumber] = REPLACE(inv.DocumentName, '.pdf','') ,[CustomValues] = NULL ,[Note] = '

' + 'Anrechnung der ' + REPLACE(inv.DocumentName, '.pdf','') + ' vom ' + FORMAT(inv.[dateFinalized], 'dd.MM.yyyy', 'de-de') + '

' ,[ExternalId] = NULL ,[Discount] = NULL ,[VAT] = inv.InvoiceVAT_1 ,[IsManual] = 1 ,[SortOrder] = ROW_NUMBER() OVER (PARTITION BY srq.[mfr__servicerequest] ORDER BY inv.[dateFinalized], inv.DateCreated) ,[Type] = 'PartialInvoice' ,[ServiceRequestId] = -2 --s.[id] ,[ServiceObjectId] = Null ,[CreatorId] = NULL ,[UnitId] = 15825600513 ,[UnitString] = 'Pauschal' ,[baseorder] = s.[baseorder], [order] = 10000 + ROW_NUMBER() OVER (PARTITION BY srq.[mfr__servicerequest] ORDER BY inv.[dateFinalized], inv.DateCreated) from [dbo].[fds__invoices] as inv JOIN [dbo].[fds__invoice_servicerequests] as srq ON inv.[Id] = srq.[InvId] AND inv.[InvoiceType] = 'i' --important JOIN @SReq as s ON srq.[mfr__servicerequest] = s.[Id] WHERE inv.[InvoiceType] = 'i' --important; AND ISNULL(inv.[isFinal],0) = 1 AND ISNULL(inv.[IsCanceled],0) = 0 AND [dbo].[fds__fn_IntermediateIsAllocatedToOther](inv.[id],@InvId) = 0; --inonly those intermediates that are not already allocated to any other (than the to be replaced Inv); IF EXISTS (SELECT * FROM @itm WHERE [ServiceRequestId] = -2) BEGIN -- Add virtual request INSERT INTO @SReq ([Id] ,[Name] ,[Type] ,[isChild] ,[baseorder]) VALUES(-2 ,'Abschlagszahlungen' ,'vrii' ,0 ,999); SET @type = 'f'; END; -- Add virtual item (to front) for (to-be) replaced invoice INSERT INTO @itm SELECT TOP(1) --can only be one [Id] = -2 ,[Version] = 0 ,[QuantityHours] = 1 ,[PlannedQuantityHours] = 1 ,[ItemTypeId] = NULL ,[ItemNumber] = NULL ,[TrackingId] = NULL ,[Manufacture] = NULL ,[Price] = inv.InvoiceBalance_net * -1.0 --without VAT ,[Costs] = inv.InvoiceBalance_net * -1.0 --without VAT ,[NameOrNumber] = REPLACE(inv.DocumentName, '.pdf','') ,[CustomValues] = NULL ,[Note] = '

' + 'Storno der ' + REPLACE(inv.DocumentName, '.pdf','') + ' vom ' + FORMAT(inv.[dateFinalized], 'dd.MM.yyyy', 'de-de') + '

' ,[ExternalId] = NULL ,[Discount] = NULL ,[VAT] = inv.InvoiceVAT_1 ,[IsManual] = 1 ,[SortOrder] = 1 ,[Type] = 'CanceledInvoice' ,[ServiceRequestId] = -3 --s.[id] ,[ServiceObjectId] = Null ,[CreatorId] = NULL ,[UnitId] = 15825600513 ,[UnitString] = 'Pauschal' ,[baseorder] = 0, [order] = 1 from [dbo].[fds__invoices] as inv WHERE ISNULL(inv.[isFinal],0) = 1 AND ISNULL(inv.[IsCanceled],0) = 0 AND inv.[Id] = @InvId; IF EXISTS (SELECT * FROM @itm WHERE [ServiceRequestId] = -3) BEGIN -- Add virtual request INSERT INTO @SReq ([Id] ,[Name] ,[Type] ,[isChild] ,[baseorder]) VALUES(-3 ,'Storno' ,'vrci' ,0 ,-999); END; /** OUTPUT + get other types **/ WITH app as( SELECT [start] = MIN(CAST(CASE WHEN a.[StartDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[StartDateTime] as date) > s.[workdoneat] THEN CAST(a.[StartDateTime] as date) ELSE s.[workdoneat] END as date)) , [end] = MAX(CAST(CASE WHEN a.[EndDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[EndDateTime] as date) > s.[workdoneat] THEN CAST(a.[EndDateTime] as date) ELSE s.[workdoneat] END as date)) , [CustomerId] = MIN (s.customerid) FROM [dbo].[mfr__appointments] as a RIGHT JOIN @SReq as s on a.[ServiceRequestId] = s.[Id] AND a.[State] in ('IsWorkDone') ) SELECT TOP(1) [today] , [provisionstart] = CASe WHEN @type = 'i' THEN NULL WHEN [start] = [end] THEN NULL ELSE [start] END , [provisionend] = CASe WHEN @type = 'i' THEN @today ELSE [end] END -- Abschlagsrechnungen immer mit Tagesdatum , [provisionlocation] = ISNULL((SELECT TOP(1) [provisionlocation] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([provisionlocation],'') <>''),N'') , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [paymentterms] = ISNULL((SELECT TOP(1) [PaymentTerm] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([PaymentTerm],'') <>''),N'10wd') , [invoiceemail] = ISNULL((SELECT TOP(1) [SendToemail] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([sendToEmail],'') <>''),(SELECT TOP(1) [SupportMail] FROM @company where IsEmailInvoicingActive = 1)) , [invoiceaddress] = ISNULL((SELECT TOP(1) [SendToAddress] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([SendToAddress],'') <>''),(SELECT TOP(1) CONCAT([name], CHAR(10), [address]) FROM @company ORDER BY IsEmailInvoicingActive DESC)) , [tax_servicerefund] = 0.2 , [CustomerId] = [CustomerId] , [invoicetitle] = CASE WHEN @type = 'i' THEN (CASE WHEN @NUM_of_int_Invoices > 0 THEN CAST((@NUM_of_int_Invoices + 1) as varchar(3)) + '. ' ELSE '' END) + 'Abschlagsrechnung' WHEN @type = 'f' THEN 'Schlussrechnung' WHEN @type = 'c' THEN 'Stornorechnung' ELSE 'Rechnung' END , [type] = @type FROM (VALUES(CAST(GETDATE() as date)))base ([today]) CROSS JOIN app; SELECT * ,[order] = ROW_NUMBER() OVER (ORDER BY [baseorder]) FROM @SReq; IF @type <> 'i' BEGIN SELECT itm.[Id] , [net] = ISNULL([Price],0) , [quantityhours] = ISNULL([quantityhours],1) , itm.[UnitString] , [net_val] = CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , [bo_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , [vat_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * ((ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , itm.[Note] , [order] = (itm.[baseorder] * 100) + itm.[order] FROM @itm as itm LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item'; END ELSE BEGIN WITH citm as ( SELECT itm.[ServiceRequestId], [net_val] = CAST( SUM( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) ) as numeric(7,2)) FROM @itm as itm WHERE itm.[Type] = 'Material' GROUP BY itm.[ServiceRequestId] ) SELECT [Id] = -1 , [net] = 1000.0 , [quantityhours] = 1 , [UnitString] = 'Pauschal' , [net_val] = CAST( 1000.0 as numeric(7,2)) , [bo_val] = CAST( 1000.0 * 1.19 as numeric(7,2)) , [vat] = FORMAT( 19.0, '#0.0','de') + '%' , [vat_val] = CAST( 1000.0 * 0.19 as numeric(7,2)) , [ServiceRequestId] = s.[id] , [SortOrder] = 0 , [Type] = 'PartialInvoice' , [NameOrNumber] = 'Abschlagsbetrag für bereits erbrachte Arbeiten, Dienstleistungen, Materiallieferungen und getätigte Bestellvorgänge zum oben genannten Bauvorhaben' , [Note] = '' , [order] = 1 FROM @SReq as s; END INSERT INTO @step SELECT stp.* , s.[baseorder] , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY stp.[ServiceRequestId] ORDER BY stp.[SortOrder], stp.[Id]) FROM [dbo].[mfr__steps] as stp JOIN @SReq as s ON stp.ServiceRequestId = s.[Id]; SELECT * from @step; SELECT cc.[Id] , [CompanyName] = cc.[name] , ct.[Gender] , ct.[FirstName] , ct.[LastName] , ct.[Email] , cc.[address] FROM [dbo].[fds__getCompanysContacts](@companyids) as ct join @company as cc on cc.[Id] = ct.[CyId]; SELECT DISTINCT [ref] = 'Einsatzort ' + so.[name] ,[address] = [dbo].[fds__fn_combineAddress] (so.[Name], loc.[AddressString], null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:ServiceObjects' and p.[EntityId] = s.[id] LEFT JOIN [mfr__serviceobjects] as so ON so.id = p.[PartnerId] LEFT JOIN [mfr__*PartnerSet] as po ON p.property = 'ServiceObject:Location' and po.[EntityId] = so.[Id] LEFT join [dbo].[mfr__#locations] as loc ON (loc.[id] = so.[Location#ID] OR po.[PartnerId] = loc.[Id] OR (so.[Id] = loc.[EntityId] and loc.Property = 'ServiceObject:Location')) WHERE so.id is not null and loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Auftragsort ' + [name] ,[address] = [dbo].[fds__fn_combineAddress] (loc.[AddressString], null, null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:Location' and p.[EntityId] = s.[id] join [dbo].[mfr__#locations] as loc ON (s.[Location#ID] = loc.[id] OR p.[PartnerId] = loc.[Id] OR (s.[Id] = loc.[EntityId] and loc.Property = 'ServiceRequest:Location')) WHERE loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Kunde' , [address] FROM @company; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__prepStorno_recreate] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__r_getBalanceByMonth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__r_getBalanceByMonth] @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'Umsatz nach Monaten' ,'Umsatz nach Monaten' ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'table' --typ , '' --settings , '' , 0) SELECT * FROM @Admin; WITH inv as ( SELECT i.[Dateofcreation] ,i.[InvoiceBalance] ,i.[InvoiceBalanceNetto] FROM [dbo].[mfr__invoices] as i where --i.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') and i.[FileType] in( 'PdfInvoice','PdfCancelInvoice','PdfPartialInvoice') and ISNULL(InvoiceId,'') not in ('Preview','') UNION SELECT [Dateofcreation] = i.[DateCreatEd] ,i.[InvoiceBalance] ,[InvoiceBalanceNetto] = i.[InvoiceBalance_net] FROM [dbo].[fds__invoices] as i WHERE i.[isFinal] = 1 ) SELECT [Monat] = FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de') , [∑ Umsätze] = FORMAT( SUM( ISNULL(inv.[InvoiceBalance],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze] = 'text-align: right' , [∑ Umsätze_netto] = FORMAT( SUM( ISNULL(inv.[InvoiceBalanceNetto],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze_netto] = 'text-align: right' FROM inv GROUP BY FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de'); END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__r_getBalanceByMonth] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__r_getBalanceByYearTopCustomer] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__r_getBalanceByYearTopCustomer] @year int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'Umsatz der Top 10 Kunden für Jahr ' + CAST( @year as varchar(10)) ,'Umsatz der Top 10 Kunden pro Jahr ' + CAST( @year as varchar(10)) ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'table' --typ , '' --settings , '' , 0); SELECT * FROM @Admin; WITH inv as( select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST(_i.[Dateofcreation] as date) ,srq.CustomerId ,[customerName] = cy.Name ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST(_i.[Dateofcreation] as date)) FROM [dbo].[mfr__invoices] as _i JOIN [dbo].[mfr__servicerequests] as srq on srq.InvoiceId like ('%' + _i.[InvoiceId] + '%') JOIN [dbo].[mfr__companies] as cy on srq.CustomerId = cy.id where _i.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') and YEAR(_i.[Dateofcreation]) = @year GROUP BY CAST(_i.[Dateofcreation] as date), CustomerId, cy.name UNION select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST(_i.[DateCreated] as date) ,_i.CustomerId ,[customerName] = cy.Name ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST(_i.[DateCreated] as date)) FROM [dbo].[fds__invoices] as _i JOIN [dbo].[mfr__companies] as cy on _i.CustomerId = cy.id where YEAR(_i.[DateCreated]) = @year and _i.[isfinal] = 1 GROUP BY CAST(_i.[DateCreated] as date), CustomerId, cy.name ), yr1 as ( SELECT [year] = YEAR( inv.[Dateofcreation] ) , [total] = SUM( ISNULL(inv.[InvoiceBalance],0) ) FROM [dbo].[mfr__invoices] as inv where inv.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') GROUP BY YEAR( inv.[Dateofcreation]) UNION SELECT [year] = YEAR( _i.[DateCreated] ) , [total] = SUM( ISNULL(_i.[InvoiceBalance],0) ) FROM [dbo].[fds__invoices] as _i WHERE _i.[isfinal] = 1 GROUP BY YEAR( _i.[DateCreated]) ), yr as ( SELECT [year], [total] = SUM([total]) from yr1 GROUP BY [year] ) SELECT TOP(10) [Jahr] = CAST( YEAR( inv.[Dateofcreation] ) as varchar(4)) , [Name d. Kunden] = [customerName] , [∑ Umsätze] = FORMAT( SUM( ISNULL(inv.[InvoiceBalance],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze] = 'text-align: right' , [% Anteil] = CASE WHEN yr.[total] > 0 THEN FORMAT( SUM( ISNULL(inv.[InvoiceBalance],0) ) / [total], '0 %', 'de') ELSE NULL END , [style:% Anteil] = 'text-align: right' , [order] = ROW_NUMBER() OVER ( ORDER By SUM( ISNULL(inv.[InvoiceBalance],0) ) DESC) FROM inv LEFT JOIN yr on YEAR( inv.[Dateofcreation] ) = yr.[year] GROUP BY YEAR( inv.[Dateofcreation] ), yr.[total], [customerName]; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__r_getBalanceByYearTopCustomer] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__r_getBalanceByYearTopMaterial] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__r_getBalanceByYearTopMaterial] @year int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'Umsatz der Top 10 Materialien für Jahr ' + CAST( @year as varchar(10)) ,'Umsatz der Top 10 Materialien für Jahr ' + CAST( @year as varchar(10)) ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'table' --typ , '' --settings , '' , 0); SELECT * FROM @Admin; WITH inv as( select [itmPrice] = SUM( (ISNULL(itm.[price],0) * ISNULL(itm.[QuantityHours],0) ) -ISNULL(itm.[discount],0) ) ,[Dateofcreation] = CAST(_i.[Dateofcreation] as date) ,[material] = itm.NameOrNumber ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST(_i.[Dateofcreation] as date)) FROM [dbo].[mfr__invoices] as _i JOIN [dbo].[mfr__servicerequests] as srq on srq.InvoiceId like ('%' + _i.[InvoiceId] + '%') JOIN [dbo].[mfr__items] as itm on srq.Id = itm.[ServiceRequestId] and itm.[Type] like 'Material' where _i.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') and YEAR(_i.[Dateofcreation]) = @year GROUP BY CAST(_i.[Dateofcreation] as date), itm.NameOrNumber UNION SELECT [itmPrice] = SUM( ISNULL(itm.[value_total],0) ) ,[Dateofcreation] = CAST(_i.[DateCreated] as date) ,[material] = itm.[text] ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST(_i.[DateCreated] as date)) FROM [dbo].[fds__invoices] as _i JOIN [fds__invoice_items] as itm on itm.[invid] = _i.[id] AND itm.[Type] like 'Material' where YEAR(_i.[DateCreated]) = @year and _i.[isfinal] = 1 GROUP BY CAST(_i.[DateCreated] as date), itm.[text] ), yr1 as ( SELECT [year] = YEAR( inv.[Dateofcreation] ) , [total] = SUM( ISNULL(inv.[InvoiceBalance],0) ) FROM [dbo].[mfr__invoices] as inv where inv.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') GROUP BY YEAR( inv.[Dateofcreation]) UNION SELECT [year] = YEAR( _i.[DateCreated] ) , [total] = SUM( ISNULL(_i.[InvoiceBalance],0) ) FROM [dbo].[fds__invoices] as _i WHERE _i.[isfinal] = 1 GROUP BY YEAR( _i.[DateCreated]) ), yr as ( SELECT [year], [total] = SUM([total]) from yr1 GROUP BY [year] ) SELECT TOP(10) [Jahr] = CAST( YEAR( inv.[Dateofcreation] ) as varchar(4)) , [Material] = [material] , [∑ Umsätze] = FORMAT( SUM( ISNULL(inv.[itmPrice],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze] = 'text-align: right' , [% Anteil] = CASE WHEN yr.[total] > 0 THEN FORMAT( SUM( ISNULL(inv.[itmPrice],0) ) / [total], '0 %', 'de') ELSE NULL END , [style:% Anteil] = 'text-align: right' , [order] = ROW_NUMBER() OVER ( ORDER By SUM( ISNULL(inv.[itmPrice],0) ) DESC) FROM inv LEFT JOIN yr on YEAR( inv.[Dateofcreation] ) = yr.[year] GROUP BY YEAR( inv.[Dateofcreation] ), yr.[total], [material]; END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__r_getBalanceByYearTopMaterial] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__r_getBalanceTrendByMonth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__r_getBalanceTrendByMonth] @year int ,@month int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; set @month = ISNULL(@month, Month(@today)); set @year= ISNULL(@year, Year(@year)); DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'UmsatzTrend für Monat ' + FORMAT(@Month, '00') + ' / ' + FORMAT(@year, '0000') ,'UmsatzTrend für Monat ' + FORMAT(@Month, '00') + ' / ' + FORMAT(@year, '0000') ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'chart' --typ , '{ "charttype": "line", "x1_label_angle": -90, "color": "e0301e", "linewidth": 2, "valuelabels": false, "marker": "none", "colorpalette": "00B050;00B050;00B050", "x1_column": "date", "y1_column": "Value", "y1_title": "Actuals", "x1_title": "", "series_column": "series", "legend_position": "bottom", "show_datalabel": true, "datalabelfontsizescale": 0.6, "height": 600, "width": 1200, "x1_labelformat": "ddd, dd/MM"}' --settings , '' , 0) SELECT * FROM @Admin; with inv as( select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST([Dateofcreation] as date) ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST([Dateofcreation] as date)) FROM [dbo].[mfr__invoices] as _i where _i.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') and month([Dateofcreation]) = @Month and YEAR([Dateofcreation]) = @year GROUP BY CAST([Dateofcreation] as date) UNION select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST([Datecreated] as date) ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST([Datecreated] as date)) FROM [dbo].[fds__invoices] as _i where _i.IsFinal = 1 and month([Datecreated]) = @Month and YEAR([Datecreated]) = @year GROUP BY CAST([Datecreated] as date) ) SELECT --[Monat] = FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de') --,[Umsatz] = FORMAT( ISNULL(inv.[InvoiceBalance],0) , '#0.00', 'de') [series] = 'Umsatz' ,[date] = CAST(inv.[Dateofcreation] as date) ,[value] = CAST( SUM( ISNULL(inv.[InvoiceBalance],0) ) OVER (ORDER BY [seq]) as numeric(9,2)) FROM inv ORDER BY [seq] END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__r_getBalanceTrendByMonth] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__r_getBalanceTrendByYear] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__r_getBalanceTrendByYear] @year int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; set @year= ISNULL(@year, Year(@year)); DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'UmsatzTrend für Jahr ' + FORMAT(@year, '0000') ,'UmsatzTrend für Jahr ' + FORMAT(@year, '0000') ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'chart' --typ , '{ "charttype": "line", "x1_label_angle": -90, "color": "e0301e", "linewidth": 2, "valuelabels": false, "marker": "none", "colorpalette": "00B050;00B050;00B050", "x1_column": "date", "y1_column": "Value", "y1_title": "Actuals", "x1_title": "", "series_column": "series", "legend_position": "bottom", "show_datalabel": true, "datalabelfontsizescale": 0.6, "height": 600, "width": 1200, "x1_labelformat": "ddd, dd/MM"}' --settings , '' , 0) SELECT * FROM @Admin; with inv as( select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST([Dateofcreation] as date) ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST([Dateofcreation] as date)) FROM [dbo].[mfr__invoices] as _i where _i.[invoicestate] in('eIsSent','eIsPaid','eIsOpen') and YEAR([Dateofcreation]) = @year GROUP BY CAST([Dateofcreation] as date) UNION select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST([Datecreated] as date) ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST([Datecreated] as date)) FROM [dbo].[fds__invoices] as _i where _i.IsFinal = 1 and YEAR([Datecreated]) = @year GROUP BY CAST([Datecreated] as date) ) SELECT --[Monat] = FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de') --,[Umsatz] = FORMAT( ISNULL(inv.[InvoiceBalance],0) , '#0.00', 'de') [series] = 'Umsatz' ,[date] = CAST(inv.[Dateofcreation] as date) ,[value] = CAST( SUM( ISNULL(inv.[InvoiceBalance],0) ) OVER (ORDER BY [seq]) as numeric(9,2)) FROM inv ORDER BY [seq] END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__r_getBalanceTrendByYear] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__setBankingtransaction_autoAssigns] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__setBankingtransaction_autoAssigns] AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setBankingtransaction_autoAssigns' ,'', ''); with icr as ( SELECT * FROM [dbo].[fds__getInvoiceCredits] (null, null) ), ic as ( SELECT icr.[uid] , icr.[InvoiceId] , [InvID] = CAST(i.[Id] as varchar(15)) , icr.amount , [auto] = CAST(1 as bit) FROM icr JOIN [dbo].[fds__invoices] as i on icr.[InvoiceId] = i.[InvoiceId] and i.[InvoiceId] is not null and i.[IsFinal] = 1 UNION SELECT icr.[uid] , icr.[InvoiceId] , [InvID] = CAST(i.[Id] as varchar(15)) , icr.amount , [auto] = CAST(1 as bit) FROM icr JOIN [dbo].[mfr__invoices] as i on icr.[InvoiceId] = i.[InvoiceId] and i.[InvoiceId] is not null --UNION --SELECT -- bt.[uid] -- , i.[InvoiceId] -- , [InvID] = i.[Id] -- , bt.[amount] -- , [auto] = CAST(0 as bit) --FROM [dbo].[fds__bankingtransactions] as bt JOIN [dbo].[fds__bankingtransactions_settings] as bs ON bt.uid = bs.[banking_uid] AND ISNULL(bs.[assigned_invoice_id], '') <> '' -- JOIN [dbo].[fds__invoices] as i on bs.[assigned_invoice_id] = i.[Id] and i.[IsFinal] = 1 ), ic2 as ( SELECT [banking_uid] = ic.[uid] , [amount] = SUM(ISNULL(ic.[amount], 0.0)) , [InvID_csv] = STRING_AGG(ic.[InvID], ',') from ic WHERE ic.[InvID] is not null GROUP BY ic.[uid] ) --select * from ic2 MERGE [dbo].[fds__bankingtransactions_settings] as TARGET USING ic2 as SOURCE ON TARGET.[banking_uid] = SOURCE.[banking_uid] WHEN NOT MATCHED BY TARGET THEN INSERT ([banking_uid] ,[auto_invoice_id]) VALUES (SOURCE.[banking_uid] ,SOURCE.[InvID_csv]) WHEN MATCHED THEN UPDATE SET [auto_invoice_id] = [dbo].[ott_merge_csv](TARGET.[auto_invoice_id],SOURCE.[InvID_csv]); END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__setBankingtransaction_autoAssigns] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[backup__fds__setInvoicePayed] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[backup__fds__setInvoicePayed] @Id varchar(15), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoicePayed' ,@authuser , (SELECT * FROM (VALUES(@Id, @authuser)) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); UPDATE [dbo].[fds__invoices] SET [IsPayed] = 1, [paymentstatus] = 'm', [DateModified] = @now, [UserModified] = @authuser, [version] = (ISNULL([version],0) + 1) OUTPUT inserted.* WHERE [Id] = @Id AND @Id is not null and [IsPayed] = 0; IF TRY_CAST(@id as bigint) is not null and EXISTS(SELECT 0 FROM [dbo].[mfr__invoices] as i where i.[id] = TRY_CAST(@id as bigint)) BEGIN MERGE [dbo].[fds__custom_invoiceinfo] as TARGET USING (VALUES (TRY_CAST(@id as bigint) ,CAST('m' as char(1)) ,CAST(1 as bit))) as SOURCE([InvId],[PaymentStatus],[isPayed]) ON TARGET.[InvID] = SOURCE.[InvID] WHEN MATCHED THEN UPDATE SET TARGET.[PaymentStatus] = SOURCE.[PaymentStatus] ,TARGET.[isPayed] = SOURCE.[isPayed] WHEN NOT MATCHED THEN INSERT ([InvId],[PaymentStatus],[isPayed],[file]) VALUES( SOURCE.[InvId] ,SOURCE.[PaymentStatus] ,SOURCE.[isPayed] ,NULL ); END END GO ALTER AUTHORIZATION ON [dbo].[backup__fds__setInvoicePayed] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__admin_getReportCatalog] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__admin_getReportCatalog] @report_name nvarchar(255) ,@authuser varchar(100) = '' AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE(); DECLARE @PROCEDURES TABLE ([object_id] bigint null, [typ] varchar(5), [ctype] varchar(50), [name] nvarchar(255), [label] nvarchar(255), [description] nvarchar(4000) , [tags_csv] varchar(255) , [categories_csv] varchar(255) , [link] varchar(255) , [functions] varchar(10) , [refresh] smallint , [auth] bit , [parameter] nvarchar(1000) NULL , [help_url] varchar(255) , [display_order] smallint); DECLARE @PARAMS TABLE([object_id] bigint, [name] nvarchar(255), [Type] varchar(100), [order] tinyint, [default] nvarchar(255), [ValueList] nvarchar(max)); --WITH nfo as (SELECT * FROM [dbo].[ctm__generic] where [typ] = 'udp_info') WITH nfo as (SELECT *, ROW_NUMBER() OVER (ORDER BY [category],[display_order],[key]) as '#' FROM [dbo].[fds__admin_reportcatalog]) ,report_objects as (SELECT [object_id], [name] FROM [site_fuchs].[sys].[all_objects] WHERE [type_desc] = 'SQL_STORED_PROCEDURE' AND [schema_id] = 1 and (([name] like 'fds[_][_]r[_]%' or [name] like 'fds[_][_]xls[_]%') and [name] COLLATE SQL_Latin1_General_CP1_CI_AS not in ('ctm_r_base')) ) INSERT INTO @PROCEDURES ([object_id], [typ], [ctype], [name], [label], [description], [tags_csv], [categories_csv], [link], [functions], [refresh], [auth], [help_url], [display_order]) SELECT o.[object_id] , [typ] = ISNULL(SUBSTRING([name], PATINDEX('%[_]%[_]%', [name]) + 1, CHARINDEX('_', [name], PATINDEX('%[_]%[_]%', [name]) + 1) - PATINDEX('%[_]%[_]%', [name]) - 1),'s') , [ctype] = ISNULL(nfo.[type],'report') , LOWER(ISNULL(o.[name], nfo.[key])) , nfo.[label] , nfo.[description] , nfo.[tags_csv] , CASE WHEN nfo.[key] is null THEN 'Draft' ELSE ISNULL(nfo.[category], 'Common') END , nfo.[link] , nfo.[functions] , ISNULL(nfo.[refresh],-1) , [auth] = CASE WHEN ISNULL(nfo.[auth],'') = '' THEN 1 WHEN (';' + ISNULL(nfo.[auth],'') + ';') like ('%;' + @authuser + ';%') then 1 else 0 end , nfo.[help_url] , ISNULL(nfo.[display_order], 10000) FROM report_objects as o FULL OUTER JOIN nfo ON LOWER(nfo.[key]) COLLATE SQL_Latin1_General_CP1_CI_AS = LOWER(o.[name]) AND nfo.[type] = 'report' WHERE ([name] = @report_name OR ISNULL(@report_name, '') = '') AND (nfo.[type] <> 'report' OR o.[object_id] is not NULL) -- make sure no orphaned catalog entries are included AND ISNULL(nfo.[hidden], 0) = 0 -- exclude all that are set as hidden --AND ([object_id] = @report_id OR @report_id is null); AND [dbo].[fis_admin_testGroupMembership] (@authuser, 'K2EIR') = 1; --'manager UPDATE @PROCEDURES --SET [functions] = CASE WHEN [typ] = 'xls' and [functions] is null THEN 'd' ELSE [functions] END SET [functions] = CASE WHEN [typ] = 'xls' THEN 'd' ELSE [functions] END ,[categories_csv] = CASE WHEN [typ] = 'xls' and ISNULL([categories_csv],'') = '' THEN 'Data Download' WHEN [typ] = 'link' and ISNULL([categories_csv],'') = '' THEN 'Data Download' ELSE [categories_csv] END; UPDATE @PROCEDURES SET [categories_csv] = CASE WHEN ISNULL([categories_csv], '') = '' THEN '' ELSE REPLACE(',' + [categories_csv] + ',', ',,', ',') END -- this is necessary to apply contains with commas ,[tags_csv] = CASE WHEN ISNULL([tags_csv], '') = '' THEN '' ELSE REPLACE(',' + [tags_csv] + ',', ',,', ',') END; -- this is necessary to apply contains with commas --SELECT OBJECT_ID('ctm_r_DefectsByCategory') INSERT INTO @PARAMS SELECT params.[object_id] ,'Parameter_name' = params.[name] , 'Type' = type_name([user_type_id]) --, 'Length' = [max_length] --, 'Prec' = case when type_name([system_type_id]) = 'uniqueidentifier' then precision else OdbcPrec([system_type_id], [max_length], [precision]) end --, 'Scale' = OdbcScale([system_type_id], [scale]) , 'Param_order' = [parameter_id] --, 'Collation' = convert(sysname, case when [system_type_id] in (35, 99, 167, 175, 231, 239) then ServerProperty('collation') end) , 'default' = CASE WHEN params.[name] = '@month' THEN MONTH(@today) WHEN params.[name] = '@year' THEN YEAR(@today) ELSE '' END , 'ValueList' = '' /*CASE WHEN ISNULL(type_name([user_type_id]),'') LIKE 'ctm_%' AND NOT ISNULL(type_name([user_type_id]),'') COLLATE SQL_Latin1_General_CP1_CI_AS in ('ctm_scopekey','ctm_deployment_package','ctm_displaystream','ctm_systemintegrator','ctm_truefalse','ctm_relevant_for','ctm_supplier','ctm_pillar','ctm_spl_release') THEN '[ ' + STUFF( (SELECT ', ''' + [key] + '''' as [text()] FROM [dbo].[ctm__generic] as g WHERE g.[typ] = type_name([user_type_id]) FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_scopekey' THEN '[ ' + STUFF( (SELECT ', ''' + [scopekey] + '''' as [text()] FROM [dbo].[ctm__scopes] as g WHERE [active] = 1 ORDER BY g.[display_order] FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_systemintegrator' THEN '[ ' + STUFF( (SELECT ', ''' + si.[si] + '''' as [text()] FROM (SELECT DISTINCT [dbo].[ctm_fnc_removeLeadingNumber]([value],'.') as [si] FROM [dbo].[alm_config__list_items] WHERE [list_id] = 1017)si ORDER BY si.[si] FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_deployment_package' THEN '[ ' + STUFF( (SELECT DISTINCT ', ''' + UPPER([deployment_package]) + '''' as [text()] FROM [dbo].[ctm__scopes] as g WHERE [active] = 1 ORDER BY ', ''' + UPPER([deployment_package]) + '''' ASC FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_displaystream' THEN '[ ' + STUFF( (SELECT DISTINCT ', ''' + [stream] + '''' as [text()] FROM (SELECT distinct map as [stream]--, CASE WHEN ISNULL(condition,'') <>'' THEN [condition] + ' -> ' ELSE '' END + [map] as [label] FROM [dbo].[ctm__mappings] WHERE typ = 'StreamDisplayMapping') as g ORDER BY ', ''' + [stream] + '''' ASC FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_truefalse' THEN '[ ''true'', ''false'' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_supplier' THEN '[ '''', ' + STUFF( (SELECT ', ''' + si.[rf] + '''' as [text()] FROM (SELECT DISTINCT [value] as [rf] FROM [dbo].[alm_config__list_items] WHERE [list_id] = 1017)si ORDER BY si.[rf] FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_relevant_for' THEN '[ '''', ' + STUFF( (SELECT ', ''' + si.[rf] + '''' as [text()] FROM (SELECT DISTINCT [value] as [rf] FROM [dbo].[alm_config__list_items] WHERE [list_id] = 1396)si ORDER BY si.[rf] FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_pillar' THEN '[ '''', ' + STUFF( (SELECT ', ''' + si.[rf] + '''' as [text()] FROM (SELECT DISTINCT [pillar] as [rf] FROM [dbo].[ctm__mappings] Where pillar is not null)si ORDER BY si.[rf] FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' WHEN ISNULL(type_name([user_type_id]),'') = 'ctm_spl_release' THEN '[ ' + STUFF( (SELECT ', ''' + si.[rf] + '''' as [text()] FROM (SELECT DISTINCT [name] as [rf] FROM [dbo].[CTM__release] )si ORDER BY si.[rf] FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '') + ' ]' ELSE '' END */ from sys.parameters as params JOIN @PROCEDURES as p on params.[object_id] = p.[object_id] --WHERE params.[name] <> '@authuser' ; UPDATE p SET p.[parameter] = ISNULL(STUFF( (SELECT ', ' + [name] as [text()] FROM @PARAMS as params WHERE params.[object_id]= p.[object_id] order by params.[order] ASC FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, ''), '') FROM @PROCEDURES as p; --INSERT INTO @PROCEDURES ([typ], [name], [label], [description], [tags_csv], [categories_csv], [link], [functions], [refresh], [auth], [help_url], [display_order]) --SELECT [typ] = 'fix' -- , [name] = REPLACE(c.[label], ' ','') -- , [label] -- , [description] -- , [tags_csv] -- , [categories_csv] = ISNULL([category], 'Common') -- , [image_dataurl], [functions], [refresh], [auth], [help_url], [display_order] -- FROM [dbo].[fds__admin_reportcatalog] as c where [type] = 'fix'; ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --output reports SELECT 'object_id' = ISNULL([object_id], -1) ,[typ] , [ctype] , [name] , [label] , [description] , [tags_csv] , [categories_csv] , [link] , [functions] , [refresh] , [auth] , [parameter] , [help_url] , [display_order] , 'order' = ROW_NUMBER() OVER (PARTITION BY [categories_csv] ORDER BY [display_order],[label],[name],[object_id]) FROM @PROCEDURES; --output parameter options SELECT * fROM @PARAMS; --output categories SELECT [value] as [category] ,CASE WHEN [value] COLLATE SQL_Latin1_General_CP1_CI_AS in ('Archive','Archived') THEN 999 WHEN [value] COLLATE SQL_Latin1_General_CP1_CI_AS in ('Draft','Drafts') THEN 998 WHEN [value] COLLATE SQL_Latin1_General_CP1_CI_AS in ('Administrative', 'Admin', 'Reports for System Admins') OR [value] COLLATE SQL_Latin1_General_CP1_CI_AS like '%Admins' THEN 997 WHEN [value] COLLATE SQL_Latin1_General_CP1_CI_AS in ('Raw Data') THEN 996 ELSE ROW_NUMBER() OVER (ORDER BY CASE WHEN [value] COLLATE SQL_Latin1_General_CP1_CI_AS in ('Standards','Standards','Daily Execution') THEN 1 ELSE 10 END, [value]) END as 'order' FROM (SELECT DISTINCT [value] FROM string_split(STUFF((SELECT ',' + [categories_csv] as [text()] FROM @PROCEDURES WHERE ISNULL([categories_csv],'') <> '' FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1,1,''), ',') WHERE [value] <> '')z --output tags SELECT [value] as [tag], ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC, [value] ASC) as 'order' FROM (SELECT [value] FROM string_split(STUFF((SELECT ',' + [tags_csv] as [text()] FROM @PROCEDURES WHERE ISNULL([tags_csv],'') <> '' FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1,1,''), ',') WHERE [value] <> '')tg group by [value]; END GO ALTER AUTHORIZATION ON [dbo].[fds__admin_getReportCatalog] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__admin_logdebug] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__admin_logdebug] @CodeReference varchar(255) ,@ExceptionMessage varchar(max) ,@StackTrace varchar(max) ,@Data varchar(MAX) AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fds__debuglog] ([CodeReference] ,[ExceptionMessage] ,[StackTrace] ,[Data] ,[timestamp]) VALUES (@CodeReference ,@ExceptionMessage ,@StackTrace ,@Data ,GETUTCDATE()); END GO ALTER AUTHORIZATION ON [dbo].[fds__admin_logdebug] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__admin_removeconflicttables] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__admin_removeconflicttables] @entitytype nvarchar(255) AS BEGIN SET NOCOUNT ON; DECLARE @name nvarchar(255); IF RIGHT(@entitytype,1) <> 's' SET @entitytype = @entitytype + 's'; DECLARE db_cursor CURSOR FOR select [name] from sys.objects where LEFT(name,2) = 't_' order by create_date asc; OPEN db_cursor FETCH NEXT FROM db_cursor INTO @name ; WHILE @@FETCH_STATUS = 0 BEGIN PRINT( @name); IF LEFT(@name, 2) = 't_' and @name like ('%[_mfr__]%') BEGIN DECLARE @sql nvarchar(2000) = 'DROP TABLE [dbo].[' + @name + N'];'; EXECUTE sp_executesql @sql, N'@name nvarchar(255)', @name; PRINT( @name + ' --> dropped'); END FETCH NEXT FROM db_cursor INTO @name END CLOSE db_cursor DEALLOCATE db_cursor END GO ALTER AUTHORIZATION ON [dbo].[fds__admin_removeconflicttables] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__admin_updateconflicttables] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__admin_updateconflicttables] @entitytype nvarchar(255) AS BEGIN SET NOCOUNT ON; DECLARE @name nvarchar(255); IF RIGHT(@entitytype,1) <> 's' SET @entitytype = @entitytype + 's'; DECLARE db_cursor CURSOR FOR select [name] from sys.objects where LEFT(name,2) = 't_' order by create_date asc; OPEN db_cursor FETCH NEXT FROM db_cursor INTO @name ; WHILE @@FETCH_STATUS = 0 BEGIN PRINT( @name); IF LEFT(@name, 2) = 't_' and @name like ('%' + @entitytype + '%') BEGIN DECLARE @sql nvarchar(2000) = 'EXECUTE [dbo].[mfr__updt__' + @entitytype + '] @name, null, null;DROP TABLE [dbo].[' + @name + N'];'; EXECUTE sp_executesql @sql, N'@name nvarchar(255)', @name; PRINT( @name + ' --> done'); END FETCH NEXT FROM db_cursor INTO @name END CLOSE db_cursor DEALLOCATE db_cursor END GO ALTER AUTHORIZATION ON [dbo].[fds__admin_updateconflicttables] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__createCredit_simple] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__createCredit_simple] @InvId varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createCredit_simple' ,@authuser , 'invid: ' + ISNULL(@InvId, '')); DECLARE @now datetime = GETDATE(); DECLARE @today date = CAST(@now as date); DECLARE @newid varchar(10) = [dbo].[fds__fn_invoice_id](); DECLARE @inv_DocumentName varchar(50), @inv_DateFinalized datetime, @inv_vat numeric(5,2), @inv_net numeric(10,3); IF EXISTS (SELECT 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1) BEGIN SELECT @inv_DocumentName = [documentname], @inv_DateFinalized = [DateFinalized], @inv_vat = [InvoiceVAT_1], @inv_net = 1 FROM [dbo].[fds__invoices] WHERE [id] = @InvId INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[ExternalId] ,[isExternal]) SELECT [Id] = @newid ,[Version] = 0 ,[InvoiceId] = NULL ,[InvoiceType] = 'g' ,[InvoiceTitle] = 'Gutschrift' ,[DocumentName] = NULL ,[InvoiceBalance] = (@inv_net * -1) * (1 + 0.01 * ISNULL(@inv_vat,19)) ,[InvoiceBalance_net] = (@inv_net * -1) ,[InvoiceVAT_net1] = (@inv_net * -1) * (0.01 * ISNULL(@inv_vat,19)) ,[InvoiceVAT_1] = @inv_net ,[InvoiceVAT_net2] = null ,[InvoiceVAT_2] = null ,[PaymentTerm] ,[DueDate] = @today ,[CustomerId] ,[SendToAddress] = ISNULL([SendToAddress], [dbo].[fds__getCompanyNameAddress]([customerid])) ,[SendToEmail] = ISNULL([SendToEmail], [dbo].[fds__getCompanyNameAddress]([customerid])) ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] = NULL ,[IsPayed] = 0 ,[IsSent] = 0 ,[Replaces_InvId] = @InvId ,[CustomValues] ,[DateSent] = NULL ,[UserSent] = @authuser ,[DateFinalized] = NULL ,[UserFinalized] = NULL ,[DateCancelled] = NULL ,[UserCancelled] = NULL ,[DateCreated] = @now ,[UserCreated] = @authuser ,[DateModified] = @now ,[UserModified] = @authuser ,[ExternalId] = NULL ,[isExternal] = 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1; END -- continue creating storno DECLARE @inv_srq [dbo].[fds__tt__invoice_servicerequests]; INSERT INTO [dbo].[fds__invoice_servicerequests] ([InvId] ,[mfr__servicerequest] ,[title] ,[value_net] ,[SortOrder]) OUTPUT inserted.* INTO @inv_srq SELECT [InvId] = [id] ,NULL -- ,'Gutschrift' ,(@inv_net * -1) ,0 FROM [dbo].[fds__invoices] WHERE [id] = @newid; INSERT INTO [dbo].[fds__invoice_items] ([InvId] ,[InvRqId] ,[mfr__item] ,[reference_InvId] ,[Type] ,[Position] ,[Quantity] ,[Text] ,[value] ,[value_total] ,[vat] ,[value_service] ,[det] ,[SortOrder]) SELECT @newid -- ,[id]-- ,NULL -- ,@InvId -- ,'CreditInvoice' -- ,NULL -- ,'1' --- ,[Text] = '

' + 'Gutschrift zu der ' + REPLACE(@inv_DocumentName, '.pdf','') + ' vom ' + FORMAT(@inv_dateFinalized, 'dd.MM.yyyy', 'de-de') + '

' ,[value] = (@inv_net * -1) ,[value_total] = (@inv_net * -1) ,[vat] = @inv_vat ,0 -- ,1 -- ,1 --) FROM @inv_srq; INSERT INTO [dbo].[fds__invoice_details] ([InvId] ,[InvoiceService_net] ,[InvoiceService_VAT] ,[AllocatedTo_InvId] ,[StornoTo_InvId]) VALUES( @newid ,NULL --[InvoiceService_net] ,NULL --[InvoiceService_VAT] ,NULL --[AllocatedTo_InvId] ,@InvId --[StornoTo_InvId] ); EXECUTE [dbo].[fds__getInvoice] @newid, @authuser; END GO ALTER AUTHORIZATION ON [dbo].[fds__createCredit_simple] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__createInvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__createInvoice] @InvoiceType char(1), @InvoiceTitle varchar(100), @InvoiceBalance numeric(10,2), @InvoiceBalance_net numeric(10,2), @InvoiceVAT_net1 numeric(10,2), @InvoiceVAT_1 numeric(5,2), @PaymentTerm varchar(5), @CustomerId bigint, @SendToAddress nvarchar(1000), @SendToEmail nvarchar(255), @ProvisionPeriod varchar(50), @CustomValues nvarchar(max), @authuser varchar(25), @Id varchar(10) OUT AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createInvoice' ,@authuser , ''); DECLARE @now datetime = GETUTCDATE(); DECLARE @today date = @now; SET @PaymentTerm = ISNULL(@PaymentTerm, '10wd'); DECLARE @days tinyint = ISNULL(TRY_PARSE(REPLACE(REPLACE(@PaymentTerm, 'w',''),'d','') as tinyint), 10); DECLARE @duedate date = CASE WHEN RIGHT(@PaymentTerm, 2) = 'wd' THEN DATEADD(weekday, @days, @today) ELSE DATEADd(DAY, @days, @today) END; DECLARE @newid varchar(10) = [dbo].[fds__fn_invoice_id](); DECLARE @out TABLE ( [Id] [varchar](10) NULL, [Version] [int] NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [nvarchar](255) NULL, [InvoiceBalance] [numeric](10, 2) NULL, [InvoiceBalance_net] [numeric](10, 2) NULL, [InvoiceVAT_net1] [numeric](10, 2) NULL, [InvoiceVAT_1] [numeric](5, 2) NULL, [InvoiceVAT_net2] [numeric](10, 2) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NULL, [DueDate] [date] NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NULL, [IsSent] [bit] NULL, [IsFinal] [bit] NULL, [IsCanceled] [bit] NULL, [Replaces_InvId] [varchar](10) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NULL, [UserCreated] [varchar](25) NULL, [DateModified] [datetime] NULL, [UserModified] [varchar](25) NULL, [ExternalId] [varchar](25) NULL, [isExternal] [bit] NULL, [file] [varbinary](max) NULL, [file_guid] uniqueidentifier null ); INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[ExternalId] ,[isExternal] ,[file] ,[file_guid]) OUTPUT inserted.* INTO @out VALUES (@newid ,0 --Version ,NULL --InvoiceID ,ISNULL(@InvoiceType,'r') ,ISNULL(@InvoiceTitle,'Rechnung') ,@InvoiceBalance ,@InvoiceBalance_net ,@InvoiceVAT_net1 ,@InvoiceVAT_1 ,NULL -- ,NULL -- ,@PaymentTerm ,@DueDate ,@CustomerId ,@SendToAddress ,@SendToEmail ,@ProvisionPeriod ,NULL --[ProvisionLocation] ,NULL --[PaymentStatus] ,0 -- ,0 -- ,@CustomValues , NULL --[DateSent] , NULL --[UserSent] ,NULL -- ,NULL -- ,NULL -- ,NULL -- ,@now ,@authuser ,@now ,@authuser ,NULL--ExternalId ,0 --isExternal ,NULL --file ,NEWID() --file_guid ); SELECT TOP(1) @Id = [id] FROM @out; SELECT TOP(1) * ,[hasFile] = CAST ( CASE WHEN [file] is null THEN 0 ELSE 1 END as bit) ,[UserNameFinalized] = [dbo].[fis_admin_getUserName_byID]([UserFinalized]) ,[UserEmailFinalized] = [dbo].[fis_admin_getUserEmail_byID]([UserFinalized]) from @out END GO ALTER AUTHORIZATION ON [dbo].[fds__createInvoice] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__createInvoice_Details] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__createInvoice_Details] @InvId varchar(10) ,@InvoiceService_net numeric(10,2) ,@InvoiceService_VAT numeric(10,2) ,@InvoiceOptions varchar(50) ,@authuser varchar(25) AS BEGIN SET NOCOUNT ON; MERGE [dbo].[fds__invoice_details] AS TARGET USING (VALUES(@InvId,@InvoiceService_net,@InvoiceService_VAT,@InvoiceOptions)) SOURCE ([InvId],[InvoiceService_net],[InvoiceService_VAT],[InvoiceOptions]) ON TARGET.[InvID] = SOURCE.[InvID] WHEN MATCHED THEN UPDATE SET [InvoiceService_net] = ISNULL(SOURCE.[InvoiceService_net], TARGET.[InvoiceService_net]) ,[InvoiceService_VAT] = ISNULL(SOURCE.[InvoiceService_VAT], TARGET.[InvoiceService_VAT]) ,[InvoiceOptions] = ISNULL(SOURCE.[InvoiceOptions], TARGET.[InvoiceOptions]) WHEN NOT MATCHED BY TARGET THEN INSERT ([InvId] ,[InvoiceService_net] ,[InvoiceService_VAT] ,[InvoiceOptions]) VALUES( SOURCE.[InvId] ,SOURCE.[InvoiceService_net] ,SOURCE.[InvoiceService_VAT] ,SOURCE.[InvoiceOptions] ) OUTPUT inserted.* ; END GO ALTER AUTHORIZATION ON [dbo].[fds__createInvoice_Details] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__createInvoice_ServiceRequest] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__createInvoice_ServiceRequest] @InvId varchar(10) ,@mfr__servicerequest bigint ,@title nvarchar(max) ,@value_net numeric(10,3) ,@SortOrder tinyint AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fds__invoice_servicerequests] ([InvId] ,[mfr__servicerequest] ,[title] ,[value_net] ,[SortOrder]) OUTPUT inserted.* VALUES (@InvId ,@mfr__servicerequest ,@title ,@value_net ,@SortOrder); END GO ALTER AUTHORIZATION ON [dbo].[fds__createInvoice_ServiceRequest] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__createReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__createReminder] @InvId varchar(15) , @type varchar(3) , @amount numeric(10,3) , @amount_payed numeric(10,3) , @SendToAddress [nvarchar](1000) , @SendToEmail [nvarchar](255) , @subject nvarchar(255) , @text nvarchar(2000) , @authuser varchar(25) , @Id varchar(10) OUT AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createReminder' ,@authuser , 'invid: ' + ISNULL(@invid, '')); DECLARE @now datetime = GETUTCDATE(); DECLARE @today date = @now; DECLARE @newid varchar(10) = [dbo].[fds__fn_reminder_id](); DECLARE @OUT [dbo].[fds__tt__reminder_core]; DECLARE @CustomerId bigint = dbo.fds__fn_invoice_customerid(@InvId); INSERT INTO [dbo].[fds__reminder] ([Id] ,[version] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[subject] ,[text] ,[IsSent] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[file]) OUTPUT inserted.* INTO @OUT VALUES (@newid ,0 --version ,@InvId ,@CustomerId ,@SendToAddress ,@SendToEmail ,@type ,@amount ,@amount_payed ,@subject ,@text ,0 --IsSent, bit,> ,null -- ,NULL -- ,NULL --[UserSent] ,NULL -- ,NULL -- ,@now ,@authuser ,@now ,@authuser ,NULL); SELECT TOP(1) @Id = [id] FROM @out; With inv as( select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId ) SELECT TOP(1) o.* , [InvoiceId] = inv.[InvoiceId] , [InvoiceDate] = inv.[DateFinalized] , [hasFile] = CAST ( CASE WHEN o.[file] is null THEN 0 ELSE 1 END as bit) , [UserNameFinalized] = [dbo].[fis_admin_getUserName_byID](o.[UserFinalized]) , [UserEmailFinalized] = [dbo].[fis_admin_getUserEmail_byID](o.[UserFinalized]) from @out as o join inv on o.[invid] = inv.[id]; END GO ALTER AUTHORIZATION ON [dbo].[fds__createReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__createStorno_copy] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__createStorno_copy] @InvId varchar(10) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createStorno_copy' ,@authuser , 'invid: ' + ISNULL(@InvId, '')); DECLARE @now datetime = GETDATE(); DECLARE @today date = CAST(@now as date); DECLARE @newid varchar(10) = [dbo].[fds__fn_invoice_id](); DECLARE @inv_DocumentName varchar(50), @inv_DateFinalized datetime, @inv_vat numeric(5,2), @inv_net numeric(10,3), @13b bit; SELECT @inv_DocumentName = [documentname], @inv_DateFinalized = [DateFinalized], @inv_vat = [InvoiceVAT_1], @inv_net = [invoicebalance_net], @13b = IIF(_d.InvoiceOptions like '§13b', 1, 0) FROM [dbo].[fds__invoices] as _i LEFT JOIN [dbo].[fds__invoice_details] as _d ON _i.[Id] = _d.[InvId] WHERE [id] = @InvId; INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[ExternalId] ,[isExternal]) SELECT [Id] = @newid ,[Version] = 0 ,[InvoiceId] = NULL ,[InvoiceType] = 'c' ,[InvoiceTitle] = [InvoiceTitle] ,[DocumentName] = NULL ,[InvoiceBalance] = ([InvoiceBalance] * -1) ,[InvoiceBalance_net] = ([InvoiceBalance_net] *-1) ,[InvoiceVAT_net1] = IIF(_d.InvoiceOptions like '§13b', 0, ([InvoiceVAT_net1] * -1)) ,[InvoiceVAT_1] ,[InvoiceVAT_net2] = IIF(_d.InvoiceOptions like '§13b', 0, ([InvoiceVAT_net2] * -1)) ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] = @today ,[CustomerId] ,[SendToAddress] = ISNULL([SendToAddress], [dbo].[fds__getCompanyNameAddress]([customerid])) ,[SendToEmail] = ISNULL([SendToEmail], [dbo].[fds__getCompanyNameAddress]([customerid])) ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] = NULL ,[IsPayed] = 0 ,[IsSent] = 0 ,[Replaces_InvId] = @InvId ,[CustomValues] ,[DateSent] = NULL ,[UserSent] = NULL ,[DateFinalized] = NULL ,[UserFinalized] = NULL ,[DateCancelled] = NULL ,[UserCancelled] = NULL ,[DateCreated] = @now ,[UserCreated] = @authuser ,[DateModified] = @now ,[UserModified] = @authuser ,[ExternalId] = null ,[isExternal] = 0 FROM [dbo].[fds__invoices] as _i LEFT JOIN [dbo].[fds__invoice_details] as _d ON _i.[Id] = _d.[InvId] WHERE _i.[id] = @InvId AND ISNULL(_i.[isfinal],0) = 1; DECLARE @inv_srq [dbo].[fds__tt__invoice_servicerequests]; DECLARE @oldinv_srq [dbo].[fds__tt__invoice_servicerequests]; INSERT INTO @oldinv_srq SELECT irq.* FROM [dbo].[fds__invoices] as i JOIN [fds__invoice_servicerequests] as irq on i.[id] = irq.[InvId] WHERE i.[id] = @InvId; WIth nsrq as ( --SELECT -- create the virtual one -- [InvId] = @newid -- ,[mfr__servicerequest] = NULL -- ,[title] = 'Storno' -- ,[value_net] = 0 -- ,[SortOrder] = 0 --FROM [dbo].[fds__invoices] as newinv where newinv.[id] = @newid --UNION SELECT --copy existing [InvId] = @newid ,[mfr__servicerequest] ,[title] ,[value_net] ,[SortOrder] FROM @oldinv_srq as irq WHERE EXISTS (SELECT * fROM [dbo].[fds__invoices] as newinv where newinv.[id] = @newid) ) INSERT INTO [dbo].[fds__invoice_servicerequests] ([InvId] ,[mfr__servicerequest] ,[title] ,[value_net] ,[SortOrder]) OUTPUT inserted.* INTO @inv_srq SELECT * FROM nsrq; --INSERT INTO [dbo].[fds__invoice_items] -- ([InvId] -- ,[InvRqId] -- ,[mfr__item] -- ,[reference_InvId] -- ,[Type] -- ,[Position] -- ,[Quantity] -- ,[Text] -- ,[value] -- ,[value_total] -- ,[vat] -- ,[value_service] -- ,[det] -- ,[SortOrder]) -- SELECT -- @newid -- -- ,[id]-- -- ,NULL -- -- ,@InvId -- -- ,'CanceledInvoice' -- -- ,NULL -- -- ,'1' --- -- ,[Text] = '

' + 'Storno der ' + REPLACE(@inv_DocumentName, '.pdf','') + ' vom ' + FORMAT(@inv_dateFinalized, 'dd.MM.yyyy', 'de-de') + '

' -- ,[value] = (@inv_net * -1) -- ,[value_total] = (@inv_net * -1) -- ,[vat] = @inv_vat -- ,0 -- -- ,1 -- -- ,1 --) --FROM @inv_srq WHERE [title] = 'Storno' and [sortorder] = 0; -- add copies INSERT INTO [dbo].[fds__invoice_items] ([InvId] ,[InvRqId] ,[mfr__item] ,[reference_InvId] ,[Type] ,[Position] ,[Quantity] ,[Text] ,[value] ,[value_total] ,[vat] ,[value_service] ,[det] ,[SortOrder]) SELECT @newid -- ,newsrq.Id -- ,itm.[mfr__item] ,itm.reference_InvId ,itm.[Type] ,itm.[Position] ,itm.[Quantity] ,itm.[Text] ,itm.[value] ,itm.[value_total] ,itm.[vat] ,itm.value_service ,itm.det ,itm.SortOrder FROM @inv_srq as newsrq JOIN @oldinv_srq as oldsrq on newsrq.SortOrder = oldsrq.SortOrder and newsrq.mfr__servicerequest = oldsrq.mfr__servicerequest JOIN [dbo].[fds__invoice_items] as itm on oldsrq.[Id] = itm.[InvRqId] and oldsrq.[InvId] = itm.[InvId] WHERE [newsrq].title <> 'Storno'; INSERT INTO [dbo].[fds__invoice_details] ([InvId] ,[InvoiceService_net] ,[InvoiceService_VAT] ,[AllocatedTo_InvId] ,[StornoTo_InvId] ,[InvoiceOptions]) SELECT top(1) @newid ,[InvoiceService_net] ,[InvoiceService_VAT] ,[AllocatedTo_InvId] ,[StornoTo_InvId] = @InvId ,[InvoiceOptions] FROM [dbo].[fds__invoice_details] WHERE [InvId] = @InvId; EXECUTE [dbo].[fds__getInvoice] @newid, @authuser; END GO ALTER AUTHORIZATION ON [dbo].[fds__createStorno_copy] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__createStorno_simple] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__createStorno_simple] @InvId varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__createStorno_simple' ,@authuser , 'invid: ' + ISNULL(@InvId, '')); DECLARE @now datetime = GETDATE(); DECLARE @today date = CAST(@now as date); DECLARE @newid varchar(10) = [dbo].[fds__fn_invoice_id](); DECLARE @inv_DocumentName varchar(50), @inv_DateFinalized datetime, @inv_vat numeric(5,2), @inv_net numeric(10,3), @13b bit; IF EXISTS (SELECT 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1) BEGIN SELECT @inv_DocumentName = [documentname], @inv_DateFinalized = [DateFinalized], @inv_vat = [InvoiceVAT_1], @inv_net = [invoicebalance_net] , @13b = IIF(_d.InvoiceOptions like '§13b', 1, 0) FROM [dbo].[fds__invoices] as _i LEFT JOIN [dbo].[fds__invoice_details] as _d ON _i.[Id] = _d.[InvId] WHERE [id] = @InvId; INSERT INTO [dbo].[fds__invoices] ([Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[ExternalId] ,[isExternal]) SELECT [Id] = @newid ,[Version] = 0 ,[InvoiceId] = NULL ,[InvoiceType] = 'c' ,[InvoiceTitle] = 'Stornorechnung' ,[DocumentName] = NULL ,[InvoiceBalance] = ([InvoiceBalance] * -1) ,[InvoiceBalance_net] = ([InvoiceBalance_net] *-1) ,[InvoiceVAT_net1] = IIF(_d.InvoiceOptions like '§13b', 0, ([InvoiceVAT_net1] * -1)) ,[InvoiceVAT_1] ,[InvoiceVAT_net2] = IIF(_d.InvoiceOptions like '§13b', 0, ([InvoiceVAT_net2] * -1)) ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] = @today ,[CustomerId] ,[SendToAddress] = ISNULL([SendToAddress], [dbo].[fds__getCompanyNameAddress]([customerid])) ,[SendToEmail] = ISNULL([SendToEmail], [dbo].[fds__getCompanyNameAddress]([customerid])) ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] = NULL ,[IsPayed] = 0 ,[IsSent] = 0 ,[Replaces_InvId] = @InvId ,[CustomValues] ,[DateSent] = NULL ,[UserSent] = NULL ,[DateFinalized] = NULL ,[UserFinalized] = NULL ,[DateCancelled] = NULL ,[UserCancelled] = NULL ,[DateCreated] = @now ,[UserCreated] = @authuser ,[DateModified] = @now ,[UserModified] = @authuser ,[ExternalId] = null ,[isExternal] = 0 FROM [dbo].[fds__invoices] as _i LEFT JOIN [dbo].[fds__invoice_details] as _d ON _i.[Id] = _d.[InvId] WHERE _i.[id] = @InvId AND ISNULL(_i.[isfinal],0) = 1; END -- continue creating storno DECLARE @inv_srq [dbo].[fds__tt__invoice_servicerequests]; INSERT INTO [dbo].[fds__invoice_servicerequests] ([InvId] ,[mfr__servicerequest] ,[title] ,[value_net] ,[SortOrder]) OUTPUT inserted.* INTO @inv_srq SELECT TOP(1) [InvId] = [id] ,NULL -- ,'Storno' ,0 ,0 FROM [dbo].[fds__invoices] WHERE [id] = @newid; INSERT INTO [dbo].[fds__invoice_items] ([InvId] ,[InvRqId] ,[mfr__item] ,[reference_InvId] ,[Type] ,[Position] ,[Quantity] ,[Text] ,[value] ,[value_total] ,[vat] ,[value_service] ,[det] ,[SortOrder]) SELECT @newid -- ,[id]-- ,NULL -- ,@InvId -- ,'CanceledInvoice' -- ,NULL -- ,'1' --- ,[Text] = '

' + 'Storno der ' + REPLACE(@inv_DocumentName, '.pdf','') + ' vom ' + FORMAT(@inv_dateFinalized, 'dd.MM.yyyy', 'de-de') + '

' ,[value] = (@inv_net * -1) ,[value_total] = (@inv_net * -1) ,[vat] = @inv_vat ,0 -- ,1 -- ,1 --) FROM @inv_srq; INSERT INTO [dbo].[fds__invoice_details] ([InvId] ,[InvoiceService_net] ,[InvoiceService_VAT] ,[AllocatedTo_InvId] ,[StornoTo_InvId] ,[InvoiceOptions]) VALUES( @newid ,NULL --[InvoiceService_net] ,NULL --[InvoiceService_VAT] ,NULL --[AllocatedTo_InvId] ,@InvId --[StornoTo_InvId] ,IIF(@13b = 1, '§13b', '') ); EXECUTE [dbo].[fds__getInvoice] @newid, @authuser; END GO ALTER AUTHORIZATION ON [dbo].[fds__createStorno_simple] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__fn_getMFRInvoicesWithoutfiles] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__fn_getMFRInvoicesWithoutfiles] AS BEGIN SET NOCOUNT ON; select TOP(0) [id],i.[URI],i.[DocumentName] from mfr__invoices as i where not exists (SELECT 0 FROM [dbo].[fds__mfr_invoicefiles] as f where f.[Id] = i.[id]) AND i.[documentname] like '%.pdf' ORDER by (SELECT TOP(1) [rn] FROM [dbo].[ocms_fn_rand]); END GO ALTER AUTHORIZATION ON [dbo].[fds__fn_getMFRInvoicesWithoutfiles] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getBankingtransfers_list] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getBankingtransfers_list] @tgtdate date ,@mode varchar(1) = '' , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getBankingtransfers_list' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); SET @mode = ISNULL(LOWER(@mode),''); If @mode in ('r') -- r = open recent BEGIN SET @tgtdate = @today; SELECT @startdate = DATEADD(week, -4, [dbo].[date_weekfirst](@tgtdate)) ,@enddate = @today; END else If @mode in ('m') -- r = open recent BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END; DECLARE @invidlist [dbo].[fds__tt__idlist_vchar]; --output admin SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = 'Zahlungübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy', 'de') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy', 'de') + ' - ' + FORMAT(@enddate, 'dd.MM.', 'de') ELSE '' END , [note] = 'neueste zuerst'; select ic.[uid] --inv.InvoiceId, --[IsPayed], --, ic.fds , InvoiceId = fi.[invoiceid] , [ValueDate] , [InvoiceBalance] = FORMAT(ISNULL(fi.[InvoiceBalance],0.0), '0.00€', 'de') , [Amount] = FORMAT(ic.[amount], '0.00€', 'de') , [Skonto] = CAST(CASE WHEN ic.[amount] between (0.965 * ISNULL(fi.[InvoiceBalance],0.0)) and (0.975 * ISNULL(fi.[InvoiceBalance],0.0)) THEN 1 ELSE 0 END as bit) , [Deviation] = FORMAT(CASE WHEN ISNULL(ISNULL(fi.[InvoiceBalance],0.0),0) > 9 THEN ic.[amount] / ISNULL(fi.[InvoiceBalance],0.0) ELSE NULL END , '0.00%', 'de') --, ic.* ,ic.AccountNumberOfPayer ,ic.NameOfPayer ,ic.SepaRemittanceInformation ,ic.EndToEndReference , [order] = ROW_NUMBER() OVER (ORDER BY [valuedate] DESC) FROM [dbo].[fds__fn_bankingtransactions](@startdate, @enddate, null, null, @invidlist) as ic LEFT JOIN [dbo].[fds__invoices] as fi on ic.[invid] = fi.id WHERE [ValueDate] BETWEEN @startdate and @enddate; END GO ALTER AUTHORIZATION ON [dbo].[fds__getBankingtransfers_list] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getBankingtransfers_list2] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getBankingtransfers_list2] @tgtdate date ,@mode varchar(1) = '' , @search varchar(100) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getBankingtransfers_list' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @searchmode as varchar(1) = CASE WHEN SUBSTRING(ISNULL(@search, '') + ' ', 2,1) <> ':' THEN '' ELSE LOWER(LEFT(@search,1 )) END; IF @searchmode <> '' BEGIN SELECT @mode = 's', @search = SUBSTRING(@search,3, 1000); END ELSE SET @mode = LOWER(@mode); If @mode in ('r') -- r = open recent BEGIN SET @tgtdate = @today; SELECT @startdate = DATEADD(week, -4, [dbo].[date_weekfirst](@tgtdate)) ,@enddate = @today; END else If @mode in ('m') -- r = open recent BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END; DECLARE @invidlist [dbo].[fds__tt__idlist_vchar]; --output admin SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = CASE WHEN @searchmode = 'n' THEN 'Übersicht der Aufträge mit der Auftragsnummer ' + @search ELSE 'Zahlungübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy', 'de') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy', 'de') + ' - ' + FORMAT(@enddate, 'dd.MM.', 'de') ELSE '' END END , [note] = 'neueste zuerst'; select ic.[uid] --inv.InvoiceId, --[IsPayed], --, ic.fds , InvoiceId = fi.[invoiceid] , [ValueDate] , [InvoiceBalance] = FORMAT(ISNULL(fi.[InvoiceBalance],0.0), '0.00€', 'de') , [Amount] = FORMAT(ic.[amount], '0.00€', 'de') , [Skonto] = CAST(CASE WHEN ic.[amount] between (0.965 * ISNULL(fi.[InvoiceBalance],0.0)) and (0.975 * ISNULL(fi.[InvoiceBalance],0.0)) THEN 1 ELSE 0 END as bit) , [Deviation] = FORMAT(CASE WHEN ISNULL(ISNULL(fi.[InvoiceBalance],0.0),0) > 9 THEN ic.[amount] / ISNULL(fi.[InvoiceBalance],0.0) ELSE NULL END , '0.00%', 'de') --, ic.* ,ic.AccountNumberOfPayer ,ic.NameOfPayer ,ic.SepaRemittanceInformation ,ic.EndToEndReference , [order] = ROW_NUMBER() OVER (ORDER BY [valuedate] DESC) FROM [dbo].[fds__fn_bankingtransactions](IIF(@mode <> 's',@startdate,NULL), IIF(@mode <> 's',@enddate,NULL), null, null, @invidlist) as ic -- dates not filtered LEFT JOIN [dbo].[fds__invoices] as fi on ic.[invid] = fi.id WHERE (CASE WHEN @mode <> 's' AND ic.[valuedate] between @startdate and @enddate THEN 1 WHEN @searchmode = 'i' AND (fi.InvoiceId = @search OR fi.InvoiceId like ('R____-%' + @search) ) THEN 1 WHEN @searchmode = 'b' AND (ic.SepaRemittanceInformation like ('%' + @search + '%') OR ic.EndToEndReference like ('%' + @search + '%') OR ic.NameOfPayer like ('%' + @search + '%')) THEN 1 WHEN @searchmode = 'v' AND (ROUND(try_parse(REPLACE(TRIM(@search),',','.') as numeric(10,2)),0) = ROUND(ic.Amount,0)) THEN 1 ELSE 0 END) = 1; END GO ALTER AUTHORIZATION ON [dbo].[fds__getBankingtransfers_list2] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getBankingtransfers_questionable] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getBankingtransfers_questionable] @mode varchar(1) = 'm' , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getBankingtransfers_questionable' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; SET @mode = LOWER(@mode); --output admin SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode, [title] = 'Auffällige Zahlungen (neueste zuerst)' ,[note] = 'Letzes Buchungsdatum: ' + FORMAT((SELECT MAX([valuedate]) from [fds__bankingtransactions]), 'dd.MM.yy'); with inv1 as ( SELECT [InvId] = CAST([Id] as varchar(25)), [InvoiceId], [InvoiceBalance] = CAST([InvoiceBalance] as numeric(10,2)), [ispayed], i.[IsCanceled], i.IsExternal, i.ExternalId FROM [dbo].[fds__invoices] as i ), inv as ( SELECT [fds] = IIF(inv1.IsExternal = 1,0,1), [InvId], [InvoiceId], [InvoiceBalance], [ispayed], [IsCanceled]--, i.IsExternal, i.ExternalId ,bta.banking_uid FROM inv1 JOIN dbo.[fds__bankingtransactions_assigns] as bta on [InvId] = bta.[invoice_id] OR (inv1.IsExternal = 1 AND inv1.ExternalId = bta.[invoice_id]) ) select bt.[uid] --inv.InvoiceId, --[IsPayed], , inv.IsCanceled , inv.fds , inv.InvoiceId , [auto] = [dbo].[ott_csv_contains](bts.auto_invoice_id,inv.InvId) , [ValueDate] = FORMAT(bt.[ValueDate], 'dd.MM.yy') , [InvoiceBalance] = FORMAT(inv.[InvoiceBalance], '0.00€', 'de') + ISNULL( CASE WHEN id2.[invid] is not null then (SELECT TOP(1) FORMAT(inv2.[InvoiceBalance], '0.00€', 'de') FROM [dbo].[fds__invoices] as inv2 where inv2.Id = id2.[invid]) ELSE '' END ,'') , [Amount] = FORMAT(bt.[amount], '0.00€', 'de') , [Skonto] = CAST(CASE WHEN bt.[amount] between (0.965 * inv.[InvoiceBalance]) and (0.975 * inv.[InvoiceBalance]) THEN 1 ELSE 0 END as bit) , [Deviation] = FORMAT(CASE WHEN ISNULL(inv.[InvoiceBalance],0) > 9 THEN bt.[amount] / inv.[InvoiceBalance] ELSE NULL END , '0.00%') --, ic.* , bt.AccountNumberOfPayer , bt.NameOfPayer , bt.SepaRemittanceInformation , bt.EndToEndReference , [order] = ROW_NUMBER() OVER (ORDER BY bt.[valuedate] DESC) FROM dbo.[fds__bankingtransactions] as bt LEft JOIN dbo.[fds__bankingtransactions_settings] as bts on bt.[uid] = bts.banking_uid --LEFT JOIN [dbo].[fds__getInvoiceCredits] (null, null) as ic ON ic.[uid] = bt.[uid] --LEFT JOIN inv on inv.[InvoiceId] = ic.[invoiceid] LEFT JOIN inv on inv.banking_uid = bt.[uid] LEFT JOIN [dbo].[fds__invoice_details] as id2 ON inv.InvId = id2.[stornoto_invid] WHERE (bt.[DebitCreditMark] in ('C') AND NOT (ISNULL(bt.[AccountNumberOfPayer],'') IN ('DE52301502000002091478') AND ISNULL(bt.[SepaRemittanceInformation],'') like ('%umbuchung%')) AND NOT (ISNULL(bt.[AccountNumberOfPayer],'') IN ('DE23501108006161606386') AND ISNULL(bt.[SepaRemittanceInformation],'') like ('%ebay%')) AND NOT (ISNULL(bt.[SepaRemittanceInformation],'') like ('%Umsatzsteuer%')) AND ISNULL(bt.AccountNumberOfPayer ,'') <> '' ) AND CASE WHEN inv.[InvId] is null THEN 1 WHEN (ISNULL(inv.ispayed,0) = 1 and fds = 1) THEN 0 WHEN inv.[IsCanceled] = 1 THEN 1 WHEN bt.[amount] not between (inv.InvoiceBalance - 0.99) and (inv.InvoiceBalance + 0.99) THEN 1 ELSE 0 END = 1 --AND NOT EXISTS (SELECT 0 FROM [dbo].[fds__bankingtransactions_settings] as bs WHERE bs.[banking_uid] = bt.[uid] AND (ISNULL(bs.[done_manually],'') <> '' OR ISNULL(bs.[assigned_invoice_id],'') <> '')) AND ISNULL(bts.[done_manually],'') = '' END GO ALTER AUTHORIZATION ON [dbo].[fds__getBankingtransfers_questionable] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getDatevExports] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getDatevExports] @tgtdate date ,@mode varchar(1) = 'm' ,@files bit ,@authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @startdate date, @enddate date; SET @mode = LOWER(@mode); If @mode = 'm' BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END DECLARE @contraaccounts as table([account] varchar(10), [vat] numeric(5,2)); insert into @contraaccounts SELECT [account] = [key], [vat] = TRY_PARSE([value2] as numeric(5,2) USING 'en-US') FROM [dbo].[fds__admin_settings] WHERE [type] = 'contra_account' SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [beraternummer] = 11653 , [mandantennummer] = 62321 , [WJ-Beginn] = DATEFROMPARTS(YEAR(@tgtDate), 1, 1) , [Sachkontenlänge] = ISNULL((SELECT MAX(LEN([account])) FROM @contraaccounts), 4) ; DECLARE @inv TABLE([Id] varchar(20), [InvoiceID] varchar(255), [DocumentName] nvarchar(255), [DateOfCreation] date, [fds] bit, [file_guid] varchar(36)); INSERT INTO @inv SELECT [Id],[invoiceid],[DocumentName],[DateOfCreation] = [DateCreated],[fds] = IIF([isExternal] = 0,1,0), [file_guid] FROM [dbo].[fds__invoices] where CAST([DateCreated] as date) between @startdate AND @enddate and [isfinal] = 1; SELECT inv.[Id],inv.[InvoiceID],inv.[DocumentName],inv.[fds] , [file] = CASE WHEN @files = 1 then finv.[file] ELSE NULL END , inv.[file_guid], [DateOfCreation] --,[order] = ROW_NUMBER() OVER (ORDER BY [DateOfCreation] ASC) FROM @inv as inv LEFT JOIN [dbo].[fds__invoices] as finv on inv.[id] = finv.[id]; DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(15), [customer.ExternalId] bigint, [customer.Id] bigint, [ExternalId] nvarchar(255)); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId] FROM [dbo].[fds__invoice_servicerequests] as irq JOIN @inv as i on irq.[InvId] = i.[Id] LEFT JOIN [dbo].[mfr__servicerequests] as s ON irq.[mfr__servicerequest] = s.[id] LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id; With sc as( SELECT s.[invoice.Id], [#] = COUNT(s.[id]) FROM @SReq as s GROUP BY s.[invoice.Id] ), inv as( select iv.[Id] ,[InvoiceId] = iv.[InvoiceId] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = ABS([invoiceBalance]) ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END ,[customer] = (SELECT TOP(1) [ExternalId] FROM [dbo].[mfr__companies] as c WHERE c.[Id] = iv.[CustomerId]) ,[contra_account] = ca.[account] ,[Belegdatum] = iv.[DateCreated] ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,[DateOfCreation] = iv.[DateCreated] ,[file_guid] from [dbo].[fds__invoices] as iv LEFT JOIN sc on iv.[id] = sc.[invoice.Id] LEFT JOIN @contraaccounts as ca ON ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] where iv.Id in (SELECT [Id] FROM @inv) ) select [Umsatz (ohne Soll/Haben-Kz)] = ABS([balance])--CAST(FORMAT(ABS([balance]), '0.00', 'de') as varchar(13)) ,[Soll/Haben-Kennzeichen] = [dbo].[ott_quote_255](UPPER([deb_cred])) ,[WKZ Umsatz] = [dbo].[ott_quote_255]('') ,[Kurs] = NULL ,[Basis-Umsatz] = NULL ,[WKZ Basis-Umsatz] = [dbo].[ott_quote_255]('') ,[Konto] = CAST(iv.[customer] as bigint) --CAST(iv.[customer] as varchar(9)) --(SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] ORDER BY SReq.DateOfCreation ASC) ,[Gegenkonto (ohne BU-Schlüssel)] = CAST([contra_account] as bigint )--CAST([contra_account] as varchar(9))] ,[BU-Schlüssel] = [dbo].[ott_quote_255]('') ,[Belegdatum] = FORMAT(iv.[Belegdatum], 'ddMM') ,[Belegfeld 1] = [dbo].[ott_quote_255](iv.[InvoiceId]) ,[Belegfeld 2] = [dbo].[ott_quote_255]([dbo].[strings_removeLeading0_255](FORMAT(iv.[Belegdatum], 'ddMMyy'))) ,[Skonto] = [dbo].[ott_quote_255]('') ,[Buchungstext] = [dbo].[ott_quote_255](CAST(ISNULL(LEFT( TRIM(CAST((SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) as varchar(255)) ), 60) ,'') as varchar(60))) ,[Postensperre] = NULL ,[Diverse Adressnummer] = [dbo].[ott_quote_255]('') ,[Geschäftspartnerbank] = null ,[Sachverhalt] = null ,[Zinssperre] = null ,[Beleglink] = [dbo].[ott_quote_255](CASE WHEN [file_guid] is null THEN NULL ELSE CAST( 'BEDI "' + LOWER(CAST([file_guid] as varchar(36))) + '"' as varchar(50)) end) --,[order] = ROW_NUMBER() OVER (ORDER BY iv.[DateOfCreation] ASC)] ,[Beleginfo - Art 1] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 1] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 2] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 2] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 3] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 3] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 4] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 4] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 5] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 5] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 6] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 6] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 7] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 7] = [dbo].[ott_quote_255]('') ,[Beleginfo - Art 8] = [dbo].[ott_quote_255]('') ,[Beleginfo - Inhalt 8] = [dbo].[ott_quote_255]('') ,[KOST1 - Kostenstelle] = [dbo].[ott_quote_255]('') ,[KOST2 - Kostenstelle] = [dbo].[ott_quote_255]('') ,[Kost-Menge] = null ,[EU-Land u. UStID (Bestimmung)] = [dbo].[ott_quote_255]('') ,[EU-Steuersatz (Bestimmung)] = null ,[Abw. Versteuerungsart] = [dbo].[ott_quote_255]('') ,[Sachverhalt L+L] = null ,[Funktionsergänzung L+L] = null ,[BU 49 Hauptfunktionstyp] = null ,[BU 49 Hauptfunktionsnummer] = null ,[BU 49 Funktionsergänzung] = null ,[Zusatzinformation - Art 1] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 1] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 2] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 2] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 3] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 3] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 4] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 4] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 5] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 5] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 6] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 6] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 7] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 7] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 8] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 8] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 9] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 9] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 10] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 10] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 11] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 11] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 12] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 12] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 13] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 13] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 14] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 14] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 15] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 15] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 16] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 16] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 17] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 17] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 18] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 18] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 19] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 19] = [dbo].[ott_quote_255]('') ,[Zusatzinformation - Art 20] = [dbo].[ott_quote_255]('') ,[Zusatzinformation- Inhalt 20] = [dbo].[ott_quote_255]('') ,[Stück] = null ,[Gewicht] = null ,[Zahlweise] = null ,[Forderungsart] = [dbo].[ott_quote_255]('') ,[Veranlagungsjahr] = null ,[Zugeordnete Fälligkeit] = null ,[Skontotyp] = null ,[Auftragsnummer] = [dbo].[ott_quote_255]('') ,[Buchungstyp] = [dbo].[ott_quote_255]('') ,[USt-Schlüssel (Anzahlungen)] = null ,[EU-Land (Anzahlungen)] = [dbo].[ott_quote_255]('') ,[Sachverhalt L+L (Anzahlungen)] = null ,[EU-Steuersatz (Anzahlungen)] = null ,[Erlöskonto (Anzahlungen)] = null ,[Herkunft-Kz] = [dbo].[ott_quote_255]('') ,[Buchungs GUID] = [dbo].[ott_quote_255]('') ,[KOST-Datum] = null ,[Mandatsreferenz] = [dbo].[ott_quote_255]('') ,[Skontosperre] = null ,[Gesellschaftername] = [dbo].[ott_quote_255]('') ,[Beteiligtennummer] = null ,[Identifikationsnummer] = [dbo].[ott_quote_255]('') ,[Zeichnernummer] = [dbo].[ott_quote_255]('') ,[Postensperre bis] = null ,[Bezeichnung SoBil-Sachverhalt] = [dbo].[ott_quote_255]('') ,[Kennzeichen SoBil-Buchung] = [dbo].[ott_quote_255]('') ,[Festschreibung] = 1 ,[Leistungsdatum] = null ,[Datum Zuord. Steuerperiode] = null ,[Fälligkeit] = null ,[Generalumkehr (GU)] = 0 ,[Steuersatz] = null ,[Land] = null --,[Abrechnungsreferenz] --,[BVV-Position] --,[EU-Land u. UStID (Ursprung)] --,[EU-Steuersatz (Ursprung)] from inv as iv order by TRY_CONVERT(integer, SUBSTRING(iv.[InvoiceId], 2,4)), TRY_CONVERT(integer, RIGHT(iv.[InvoiceId], 4)), iv.[DateOfCreation] ASC; WIth debs as ( SELECT ROW_NUMBER() OVER (PARTITION BY [customer.Id] ORDER BY SReq.DateOfCreation ASC) as [#] , [customer.ExternalId] , [customer.Id] FROM @SReq as sreq ), dd as ( SELECT distinct cy.* FROM [mfr__companies] as cy WHERE EXISTS ( SELECT * FROM debs WHERE debs.[customer.Id] = cy.[id] AND debs.[#] = 1) ), cc as ( SELECT ROW_NUMBER() OVER (PARTITION BY dd.[id] ORDER BY CASE WHEN dd.[MainContactId] = c.[id] THEN 0 ELSE 1 END) as '#' , c.* , [company_id] = dd.[id] , [company_name] = dd.[Name] , [isCompany] = CAST ( CASE WHEN ( not dd.[name] like '%c[/]o %' AND ( dd.[Name] like '%mbH%' OR dd.[Name] like '%Ltd%' OR dd.[Name] like '% gbr%' OR dd.[Name] like 'gbr %' OR dd.[Name] like '% OHG%' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% AG %' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% KG %' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% SA %' OR (REPLACE(dd.[Name], '|' , ' ') + ' ') like '% UG %' OR dd.[Name] like '% eV%' or dd.[Name] like '%e[.]V[.]%' OR dd.[Name] like '%Gesellschaft%' OR dd.[Name] like '%Gemeinde%' OR dd.[Name] like '%Verwaltung%' OR dd.[Name] like '%Stadtwerke%' OR dd.[Name] like '%tagesstätte%' OR dd.[Name] like '%schützenverein%' OR dd.[Name] like '%akademie%' OR dd.[Name] like '%universität%' OR dd.[Name] like '%schule%' OR dd.[Name] like '%spedition%' OR dd.[Name] like '%immobilien%' OR dd.[Name] like '%krankenkasse%' OR dd.[Name] like '% holding %' OR dd.[Name] like '% Bautenschutz %' OR dd.[Name] like '%dienstleistung%' OR dd.[Name] like '%weinlokal%' OR dd.[Name] like '%restaurant%' OR dd.[Name] like '% hotel%' OR dd.[Name] like '%kanzlei%' OR dd.[Name] like '%praxis%' OR dd.[Name] like '%großhandel%' OR dd.[Name] like '%tischlerei%' OR dd.[Name] like '%haustechnik%' OR dd.[Name] like '%holztechnik%' OR dd.[Name] like '%heizungsbau%' OR dd.[Name] like '%bautenschutz%' OR dd.[Name] like '%tischlerei%' OR dd.[Name] like '%architekt%' OR dd.[Name] like '%sanitär%' OR dd.[Name] like '%pafümerie%' OR dd.[Name] like '%bauamt%' OR dd.[Name] like '%gebäudereinigung%' OR dd.[Name] like '%handwerksmeister%' OR dd.[Name] like '%fachbetrieb%' OR dd.[Name] like '%ausbau und montagen%' OR dd.[Name] like '%verband %' OR dd.[Name] like '%vermietung%' OR dd.[Name] like '%Bad [&] Heizung%' OR dd.[Name] like '%Bad[&]Wärme%' OR dd.[Name] like '% Düsseldorf%' OR dd.[Name] like '%niederlassung%' OR dd.[Name] like 'zentrum für %' OR dd.[Name] like '% Generalvertretung %' )) THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as c JOIN dd on c.[CompanyId] = dd.[Id] OR dd.[MainContactId] = c.[id] ) SELECT [Konto] = CAST(dd.[ExternalId] as bigint) --CAST(dd.[ExternalId] as varchar(9)) ,[Name (Adressatentyp Unternehmen)] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN cc.[isCompany] = 0 THEN '' ELSE REPLACE(REPLACE(REPLACE(ISNULL( cc.[company_name] ,''), CHAR(13), ' '), CHAR(10), ' '), ' ', ' ') END as varchar(255)), 50) as varchar(50))) ,[Unternehmensgegenstand] = [dbo].[ott_quote_255]('') ,[Name (Adressattyp natürl. Person)] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN cc.[isCompany] = 1 THEN '' ELSE REPLACE(REPLACE(REPLACE(ISNULL( cc.[LastName] ,''), CHAR(13), ' '), CHAR(10), ' '), ' ', ' ') END as varchar(255)), 30) as varchar(30))) ,[Vorname (Adressattyp natürl. Person)] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN cc.[isCompany] = 1 THEN '' ELSE REPLACE(REPLACE(REPLACE(ISNULL( cc.[FirstName] ,''), CHAR(13), ' '), CHAR(10), ' '), ' ', ' ') END as varchar(255)), 30) as varchar(30))) ,[Name (Adressattyp keine Angabe)] = [dbo].[ott_quote_255]('') ,[Adressattyp] = [dbo].[ott_quote_255](CAST(CASE WHEN cc.[isCompany] = 1 THEN 2 ELSE 1 END as varchar(1))) ,[Kurzbezeichnung] = [dbo].[ott_quote_255]('') ,[EU-Land] = [dbo].[ott_quote_255]('') ,[EU-UStID] = [dbo].[ott_quote_255]('') ,[Anrede] = [dbo].[ott_quote_255]('') --CASE WHEN LOWER(LEFT(cc.[Gender],1)) = 'm' THEN 'Herrn' WHEN LOWER(LEFT(cc.[Gender],1)) = 'w' THEN 'Frau' ELSE '' END ,[Titel/Akad. Grad] = [dbo].[ott_quote_255]('') ,[Adelstitel] = [dbo].[ott_quote_255]('') ,[Namensvorsatz] = [dbo].[ott_quote_255]('') ,[Adressart] = [dbo].[ott_quote_255](CAST( CASE WHEN ISNULL(l.[AddressString],'') like '%postfach%' THEN 'PF' ELSE 'STR' END as varchar(3))) ,[Straße] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN ISNULL(l.[AddressString],'') like '%postfach%' THEN '' ELSE ISNULL(l.[AddressString],'') END as varchar(255)),36) as varchar(36))) ,[Postfach] = [dbo].[ott_quote_255](CAST(LEFT(CAST(CASE WHEN ISNULL(l.[AddressString],'') like '%postfach%' THEN TRIM(SUBSTRING(ISNULL(l.[AddressString],''), PATINDEX('%postfach%', ISNULL(l.[AddressString],'')) + 8 , 12)) ELSE '' END as varchar(255)),36) as varchar(36))) ,[Postleitzahl] = [dbo].[ott_quote_255](CAST(l.[Postal] as varchar(10))) ,[Ort] = [dbo].[ott_quote_255](CAST(l.City as varchar(30))) ,[Land] = [dbo].[ott_quote_255](CAST(REPLACE(UPPER(ISNULL(l.[Country], '')),'KE','') as varchar(2))) ,[Versandzusatz] = [dbo].[ott_quote_255]('') ,[Adresszusatz] = [dbo].[ott_quote_255]('') ,[Abweichende Anrede] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 1] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 2] = [dbo].[ott_quote_255]('') ,[Kennz. Korrespondenzadresse] = Cast(1 as int) ,[Adresse Gültig von] = [dbo].[ott_quote_255]('') ,[Adresse Gültig bis] = [dbo].[ott_quote_255]('') ,[Telefon] = [dbo].[ott_quote_255](CAST(ISNULL(cc.[Telephone], dd.[SupportTelephone]) as varchar(60))) ,[Bemerkung (Telefon)] = [dbo].[ott_quote_255]('') ,[Telefon GL] = [dbo].[ott_quote_255]('') ,[Bemerkung (Telefon GL)] = [dbo].[ott_quote_255]('') ,[E-Mail] = [dbo].[ott_quote_255](CAST( CASE WHEN ISNULL(cc.[Email], dd.[SupportMail]) like '%[@]%' THEN REPLACE(LOWER(ISNULL(cc.[Email], dd.[SupportMail])), ' ', '') ELSE NULL END as varchar(60))) ,[Bemerkung (E-Mail)] = [dbo].[ott_quote_255]('') ,[Internet] = [dbo].[ott_quote_255]('') ,[Bemerkung (Internet)] = [dbo].[ott_quote_255]('') ,[Fax] = [dbo].[ott_quote_255]('') ,[Bemerkung (Fax)] = [dbo].[ott_quote_255]('') ,[Sonstige] = [dbo].[ott_quote_255]('') ,[Bemerkung (Sonstige)] = [dbo].[ott_quote_255]('') ,[Bankleitzahl 1] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 1] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 1] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 1] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 1] = [dbo].[ott_quote_255]('') ,[IBAN1 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 1] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 1] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 1] = [dbo].[ott_quote_255]('') ,[Bankverb 1 Gültig von] = null ,[Bankverb 1 Gültig bis] = null ,[Bankleitzahl 2] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 2] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 2] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 2] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 2] = [dbo].[ott_quote_255]('') ,[IBAN2 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 2] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 2] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 2] = [dbo].[ott_quote_255]('') ,[Bankverb 2 Gültig von] = null ,[Bankverb 2 Gltig bis] = null ,[Bankleitzahl 3] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 3] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 3] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 3] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 3] = [dbo].[ott_quote_255]('') ,[IBAN3 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 3] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 3] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 3] = [dbo].[ott_quote_255]('') ,[Bankverb 3 Gültig von] = null ,[Bankverb 3 Gültig bis] = null ,[Bankleitzahl 4] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 4] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 4] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 4] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 4] = [dbo].[ott_quote_255]('') ,[IBAN4 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 4] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 4] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 4] = [dbo].[ott_quote_255]('') ,[Bankverb 4 Gültig von] = null ,[Bankverb 4 Gültig bis] = null ,[Bankleitzahl 5] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 5] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 5] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 5] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 5] = [dbo].[ott_quote_255]('') ,[IBAN5 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 5] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 5] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 5] = [dbo].[ott_quote_255]('') ,[Bankverb 5 Gültig von] = null ,[Bankverb 5 Gültig bis] = null ,[Leerfeld] = null ,[Briefanrede] = [dbo].[ott_quote_255]('') ,[Grußformel] = [dbo].[ott_quote_255]('') ,[Kundennummer] = [dbo].[ott_quote_255]('') ,[Steuernummer] = [dbo].[ott_quote_255]('') ,[Sprache] = null ,[Ansprechpartner] = [dbo].[ott_quote_255]('') ,[Vertreter] = [dbo].[ott_quote_255]('') ,[Sachbearbeiter] = [dbo].[ott_quote_255]('') ,[Diverse-Konto] = null ,[Ausgabeziel] = null ,[Währungssteuerung] = [dbo].[ott_quote_255]('') ,[Kreditlimit (Debitor)] = null ,[Zahlungsbedingung] = null ,[Fälligkeit in Tagen (Debitor)] = null ,[Skonto in Prozent (Debitor)] = null ,[Kreditoren-Ziel 1 Tg.] = null ,[Kreditoren-Skonto 1 %] = null ,[Kreditoren-Ziel 2 Tg.] = null ,[Kreditoren-Skonto 2 %] = null ,[Kreditoren-Ziel 3 Brutto Tg.] = null ,[Kreditoren-Ziel 4 Tg.] = null ,[Kreditoren-Skonto 4 %] = null ,[Kreditoren-Ziel 5 Tg.] = null ,[Kreditoren-Skonto 5 %] = null ,[Mahnung] = null ,[Kontoauszug] = null ,[Mahntext 1] = null ,[Mahntext 2] = null ,[Mahntext 3] = null ,[Kontoauszugstext] = null ,[Mahnlimit Betrag] = null ,[Mahnlimit %] = null ,[Zinsberechnung] = null ,[Mahnzinssatz 1] = null ,[Mahnzinssatz 2] = null ,[Mahnzinssatz 3] = null ,[Lastschrift] = [dbo].[ott_quote_255]('') ,[Verfahren] = [dbo].[ott_quote_255]('') ,[Mandantenbank] = null ,[Zahlungsträger] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 1] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 2] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 3] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 4] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 5] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 6] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 7] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 8] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 9] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 10] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 11] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 12] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 13] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 14] = [dbo].[ott_quote_255]('') ,[Indiv. Feld 15] = [dbo].[ott_quote_255]('') ,[Abweichende Anrede (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Adressart (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Straße (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Postfach (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Postleitzahl (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Ort (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Land (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Versandzusatz (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Adresszusatz (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 1 (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Abw. Zustellbezeichnung 2 (Rechnungsadresse)] = [dbo].[ott_quote_255]('') ,[Adresse Gültig von (Rechnungsadresse)] = null ,[Adresse Gültig bis (Rechnungsadresse)] = null ,[Bankleitzahl 6] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 6] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 6] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 6] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 6] = [dbo].[ott_quote_255]('') ,[IBAN6 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 6] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 6] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 6] = [dbo].[ott_quote_255]('') ,[Bankverb 6 Gültig von] = null ,[Bankverb 6 Gültig bis] = null ,[Bankleitzahl 7] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 7] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 7] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 7] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 7] = [dbo].[ott_quote_255]('') ,[IBAN7 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 7] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 7] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 7] = [dbo].[ott_quote_255]('') ,[Bankverb 7 Gültig von] = null ,[Bankverb 7 Gültig bis] = null ,[Bankleitzahl 8] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 8] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 8] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 8] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 8] = [dbo].[ott_quote_255]('') ,[IBAN8 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 8] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 8] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 8] = [dbo].[ott_quote_255]('') ,[Bankverb 8 Gültig von] = null ,[Bankverb 8 Gültig bis] = null ,[Bankleitzahl 9] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 9] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 9] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 9] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 9] = [dbo].[ott_quote_255]('') ,[IBAN9 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 9] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 9] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 9] = [dbo].[ott_quote_255]('') ,[Bankverb 9 Gültig von] = null ,[Bankverb 9 Gültig bis] = null ,[Bankleitzahl 10] = [dbo].[ott_quote_255]('') ,[Bankbezeichnung 10] = [dbo].[ott_quote_255]('') ,[Bank-Kontonummer 10] = [dbo].[ott_quote_255]('') ,[Länderkennzeichen 10] = [dbo].[ott_quote_255]('') ,[IBAN-Nr. 10] = [dbo].[ott_quote_255]('') ,[IBAN10 korrekt] = [dbo].[ott_quote_255]('') ,[SWIFT-Code 10] = [dbo].[ott_quote_255]('') ,[Abw. Kontoinhaber 10] = [dbo].[ott_quote_255]('') ,[Kennz. Hauptbankverb. 10] = [dbo].[ott_quote_255]('') ,[Bankverb 10 Gültig von] = null ,[Bankverb 10 Gültig bis] = null ,[Nummer Fremdsystem] = [dbo].[ott_quote_255]('') ,[Insolvent] = null ,[Mandatsreferenz 1] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 2] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 3] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 4] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 5] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 6] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 7] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 8] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 9] = [dbo].[ott_quote_255]('') ,[Mandatsreferenz 10] = [dbo].[ott_quote_255]('') ,[Verknüpftes OPOS-Konto] = null ,[Mahnsperre bis] = null ,[Lastschriftsperre bis] = null ,[Zahlungssperre bis] = null ,[gebührenberechnung] = null ,[Mahngebühr 1] = null ,[Mahngebühr 2] = null ,[Mahngebühr 3] = null ,[Pauschalenberechnung] = null ,[Verzugspauschale 1] = null ,[Verzugspauschale 2] = null ,[Verzugspauschale 3] = null ,[Alternativer Suchname] = null ,[Status] = null ,[Anschrift manuell geändert (Korrespondenzadresse)] = null ,[Anschrift individuell (Korrespondenzadresse)] = null ,[Anschrift manuell geändert (Rechnungsadresse)] = null ,[Anschrift individuell (Rechnungsadresse)] = null ,[Fristberechnung bei Debitor] = null ,[Mahnfrist 1] = null ,[Mahnfrist 2] = null ,[Mahnfrist 3] = null ,[Letzte Frist] = null FROM dd JOIN cc on cc.[#] = 1 AND cc.[company_id] = dd.[id] LEFT JOIN [dbo].[mfr__#locations] as l ON l.[EntityID] = dd.[id] and l.Property = 'Company:Location' END GO ALTER AUTHORIZATION ON [dbo].[fds__getDatevExports] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getFDSDocument] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getFDSDocument] @type varchar(10), @reportid varchar(20) AS BEGIN SET NOCOUNT ON; DECLARE @idbigint bigint = TRY_CAST(@reportid as bigint); IF @type = 'invoice' BEGIN SELECT TOP(1) [Id] = CAST([Id] as varchar(20)),[type] = @type, [InvoiceID],[DocumentName],[DateOfCreation] = [DateCreated],[fds] = CAST( 1 as bit), [file] ,[order] = ROW_NUMBER() OVER (ORDER BY [DateCreated] ASC) FROM [dbo].[fds__invoices] WHERE [id] = @reportid AND [isFinal] = 1; END ELSE IF @type = 'reminder' BEGIN SELECT TOP(1) [Id] = CAST([Id] as varchar(20)),[type] = @type, [ReminderID] = '',[DocumentName],[isInvoice] = 1,[DateOfCreation] = [DateCreated],[fds] = CAST( 1 as bit), [file] ,[order] = ROW_NUMBER() OVER (ORDER BY [DateCreated] ASC) FROM [dbo].[fds__reminder] WHERE [id] = @reportid AND [isFinal] = 1; END END GO ALTER AUTHORIZATION ON [dbo].[fds__getFDSDocument] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getInvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getInvoice] @Id varchar(10), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 THROW 60000, N'not authorized', 1; DECLARE @inv [dbo].[fds__tt__invoice_base]; DECLARE @req [dbo].[fds__tt__invoice_servicerequests]; DECLARE @itm [dbo].[fds__tt__invoice_items]; INSERT INTO @inv SELECT TOP(1) [Id] ,[Version] ,[InvoiceId] ,[InvoiceType] ,[InvoiceTitle] ,[DocumentName] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[InvoiceVAT_net2] ,[InvoiceVAT_2] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[IsFinal] ,[IsCanceled] ,[Replaces_InvId] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[ExternalId] ,[isExternal] ,[hasFile] = CAST ( CASE WHEN [file] is null THEN 0 ELSE 1 END as bit) ,[UserNameFinalized] = [dbo].[fis_admin_getUserName_byID]([UserFinalized]) ,[UserEmailFinalized] = [dbo].[fis_admin_getUserEmail_byID]([UserFinalized]) ,[PaymentTermPhrase] = null ,[InvoiceService] = [InvoiceService_net] + [InvoiceService_VAT] ,[InvoiceService_net] ,[InvoiceService_VAT] ,[InvoiceOptions] = ISNULL(_d.[InvoiceOptions], '') FROM [dbo].[fds__invoices] as _i LEFT JOIN [dbo].[fds__invoice_details] as _d ON _i.[Id] = _d.[InvId] WHERE [Id] = @Id AND @Id is not null; INSERT INTO @req SELECT * FROM [dbo].[fds__invoice_servicerequests] WHERE [invId] = @Id AND @Id is not null; INSERT INTO @itm SELECT _i.* FROM [dbo].[fds__invoice_items] as _i WHERE _i.[invId] = @Id AND @Id is not null AND EXISTS( SELECT * from @req as _r WHERE _r.[id] = _i.[InvRqId]); DELETE _R FROM @req as _R WHERE NOT EXISTS (SELECT * FROM @itm as _i WHERE _i.[InvRqId] = _R.[Id] AND (ISNULL(_i.[text], '') <> '' OR ISNULL(_i.[value_total],0) <> 0)); DELETE _i FROM @itm as _i WHERE NOT EXISTS( SELECT * from @req as _r WHERE _r.[id] = _i.[InvRqId]); ---output --admin SELECT TOP(1) [today] , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [tax_servicerefund] = 0.2 , [paymentterms] = iv.[PaymentTerm] , [CustomerId] = iv.[CustomerId] , [type] = iv.[InvoiceType] FROM (VALUES(CAST(GETDATE() as date)))base ([today]) cross JOIN @inv as iv; --inv SELECT TOP(1) * ,[tax_servicerefund] = 0.2 FROM @inv; SELECT * , [order] = ROW_NUMBER() OVER (ORDER BY [SortOrder]) FROM @req; SELECT * , [order] = ROW_NUMBER() OVER (PARTITION BY [InvRqId] ORDER BY [SortOrder]) FROM @itm; END GO ALTER AUTHORIZATION ON [dbo].[fds__getInvoice] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getInvoiceReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getInvoiceReminder] @InvId varchar(15) , @include_drafts bit = 0 ,@authuser varchar(25) AS BEGIN SET NOCOUNT ON; With inv as ( SELECT TOP(1) [Id] = CAST([id] as varchar(15)), [InvoiceId], [DocumentName] FROM [dbo].[fds__invoices] WHERE [id] = @InvId ) SELECT rem.[Id] ,rem.[DateSent] ,[status] = CAST(CASE WHEN rem.[isSent] = 1 THEN 'versandt' WHEN rem.[isfinal] = 1 THEN 'fertig' WHEN rem.isfinal = 0 THEN 'Entwurf' ELSE '' END AS varchar(50)) ,rem.[subject] ,rem.[DocumentName] ,rem.[amount_open] ,rem.[InvId] ,[InvoiceId] = inv.[InvoiceId] --,[InvoiceDocumentName] = inv2.[DocumentName] ,[hasFile] = cast( IIF(rem.[file] is null, 0, 1) as bit) FROM [dbo].[fds__reminder] as rem LEFT JOIN inv on rem.[InvId] = inv.[Id] WHERE [invId] = @InvId; END GO ALTER AUTHORIZATION ON [dbo].[fds__getInvoiceReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getInvoices_list] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getInvoices_list] @tgtdate date ,@mode varchar(1) = 'm' , @include_drafts bit = 0 , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getInvoices_list' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; SET @mode = LOWER(@mode); If @mode = 'm' BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END --Reminder settings DECLARE @stage1 varchar(10), @stage2 varchar(10), @stage3 varchar(10); SELECT @stage1 = [stage1], @stage2 = [stage2], @stage3 = [stage3] FROM [dbo].[fds__admin_reminderSettings](); SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = 'Rechnungsübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') ELSE '' END ,[ust_options] = '19,0%;16,0%;0,0%'; DECLARE @inv TABLE([Id] varchar(15), [InvoiceID] varchar(255), [URI] nvarchar(255), [DocumentName] nvarchar(255), [DateOfCreation] date, [fds] bit); SELECT [Id],[invoiceid],[DocumentName],[DateOfCreation] = [DateCreated],[fds] = IIF([isExternal] = 0,1,0) FROM [dbo].[fds__invoices] where CAST([DateCreated] as date) between @startdate AND @enddate and (ISNULL(@include_drafts,0) = 1 OR [isfinal] = 1); DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(15), [customer.ExternalId] bigint, [customer.Id] bigint, [ExternalId] nvarchar(255), [fds] bit); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId], [fds] FROM [dbo].[fds__invoice_servicerequests] as irq JOIN @inv as i on irq.[InvId] = i.[Id] LEFT JOIN [dbo].[mfr__servicerequests] as s ON irq.[mfr__servicerequest] = s.[id] LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id; With itm as ( SELECT [net_itemsum] = CAST( SUM(ISNULL([value_total],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM(ISNULL([value_total],0) * (1 + (ISNULL([vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL([vat], 19.0) * 0.01)) , [invoice.Id] = inv.[id] --sreq.[invoice.Id] FROM [dbo].[fds__invoice_items] as itm --JOIN @sreq as sreq ON itm.[InvRqId] = SReq.[id] JOIN @inv as inv ON itm.[invid] = inv.[id] GROUP BY inv.[id] --sreq.[invoice.Id] ),sc as( SELECT s.[invoice.Id], [#] = COUNT(s.[id]) FROM @SReq as s GROUP BY s.[invoice.Id] ),contra_accounts as( SELECT [account] = [key], [vat] = TRY_PARSE([value2] as numeric(5,2) USING 'en-US') FROM [dbo].[fds__admin_settings] WHERE [type] = 'contra_account' ), inv as( select [Id] = CAST(iv.[Id] as varchar(15)) ,[InvoiceId] = iv.[InvoiceId] + ISNULL((CASE WHEN iv.InvoiceType = 'c' THEN (SELECT TOP(1) ' >> ' + i2.[InvoiceId] FROM [dbo].[fds__invoices] as i2 JOIN [dbo].[fds__invoice_details] as id2 on i2.[Id] = id2.[StornoTo_InvId] where id2.[InvId] = iv.[id] and i2.[IsFinal] = 1) ELSE '' END), '') ,[InvoiceType] ,[DocumentName] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = FORMAT([invoiceBalance], '#0.00', 'de') + ' €' ,[EINZELPOS_brutto] = NULL --FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' ,[EINZELPOS_netto] = NULL --FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' ,[vat] = FORMAT(ISNULL(iv.[InvoiceVAT_1], 19.0), '#0.0', 'de') + ' %' ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = FORMAT(iv.[DateCreated], 'dd.MM.yy') ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,[DateOfCreation] = iv.[DateCreated] ,[DueDate] ,[PaymentTerm] = ISNULL([PaymentTerm], @stage1) ,[PaymentStatus] ,[IsPayed] = CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END as bit) ,[IsCanceled] ,[isSent] ,[isFinal] ,[hasFile] =CAST( CASE wHEN iv.[file] is not null and [DocumentNAme] is not null THEN 1 WHEN mfrf.[file] is not null THEN 1 ELSE 0 END as bit) --,[fds] = @true ,[customer_id] = iv.[CustomerId] from [dbo].[fds__invoices] as iv LEFT JOIN itm on iv.Id = itm.[invoice.Id] LEFT JOIN sc on iv.[id] = sc.[invoice.Id] LEFT JOIN contra_accounts as ca ON ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] LEFT JOIN [dbo].[fds__mfr_invoicefiles] as mfrf on iv.[IsExternal] = 1 and mfrf.[Id] = iv.[ExternalId] where iv.Id in (SELECT [Id] FROM @inv) ), reminder as ( SELECT [InvId], [lastReminder] = MAX([DateFinalized]), [#] = COUNT(*) FROM [dbo].[fds__reminder] WHERE [isFinal] = 1 AND [invId] IN (SELECT [Id] FROM @inv) GROUP BY [InvId] )select inv.* ,[reminderstatus] = CASE WHEN [ispayed] = 1 THEN 0 WHEN [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 0 WHEN DueDate is null THEN 0 WHEN [deb_cred] = 'H' THEN 0 WHEN @stage3 <> '' AND rem.[#] = 2 AND @today > [dbo].[date_addcustom]([lastReminder], @stage3) THEN 3 WHEN @stage2 <> '' AND rem.[#] = 1 AND @today > [dbo].[date_addcustom]([lastReminder], @stage2) THEN 2 WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), ISNULL([PaymentTerm],@stage1)) THEN 1 ELSE 0 END ,[invstatus] = CASE WHEN [IsPayed] = 1 AND [isCanceled] = 0 THEN 'pyd' WHEN [isCanceled] = 1 OR [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 'cc' WHEN [isFinal] = 0 THEN 'dft' WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN [deb_cred] = 'H' THEN '' WHEN @today >= [DueDate] THEN 'due' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), @stage1) THEN 'ovd' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' END ,[reminder] = rem.[#] ,[CustomerName] = c.[name] ,[order] = CASE WHEN @include_drafts = 1 THEN ROW_NUMBER() OVER (ORDER BY inv.[DateOfCreation] ASC) ELSE ROW_NUMBER() OVER (ORDER BY TRY_CAST(SUBSTRING([invoiceid], 2,4) AS int), TRY_CAST(SUBSTRING([invoiceid], 7,4) AS int), inv.[DateOfCreation] ASC) END ,[Payment] = IIF(py.[amount] is null,'',FORMAT(ISNULL(py.[amount],0.0), '0.00€', 'de') + IIF(py.[manu] = 1, ' man.','')) /*CASE WHEN [paymentstatus] = 'a' THEN 'vollst.' WHEN [paymentstatus] = 'p' THEN FORMAT(ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.[Id]),0.0), '0.00€', 'de') ELSE '' END*/ FROM inv left JOIN reminder as rem ON inv.[Id] = rem.[InvId] --inv.[id] is already converted to varchar LEFT JOIN [dbo].[mfr__companies] as c ON inv.[customer_id] = c.[id] LEFT JOIN [dbo].[fds__fn_bankingtransactions_perInvoice](@startdate, @enddate) as py ON py.[invid] = inv.[Id] order by inv.[DateOfCreation] ASC; END GO ALTER AUTHORIZATION ON [dbo].[fds__getInvoices_list] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getInvoices_list_vario] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getInvoices_list_vario] @tgtdate date ,@mode varchar(1) = 'm' , @includes varchar(50) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @include_drafts bit = [dbo].[ott_csv_contains](@includes, 'd'); DECLARE @only_drafts bit = 0, @only_unpayed bit = 0, @only_reminded bit = 0, @only_akonto bit = 0, @only_storno bit = 0, @only_remindedunpayed bit = 0; DECLARE @includetext varchar(50) = ''; IF @includes = '#d' SELECT @includetext = ' (nur Entwürfe) ', @include_drafts = 1, @only_drafts = 1, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = 'all' SELECT @includetext = ' (alle) ', @include_drafts = 1, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = '#r' SELECT @includetext = ' (nur angemahnte) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 1, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = '#u' SELECT @includetext = ' (nur unbezahlte) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 1, @only_akonto = 0, @only_storno = 0; ELSE IF @includes = '#a' SELECT @includetext = ' (nur Akonto) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 1, @only_storno = 0; ELSE IF @includes = '#c' SELECT @includetext = ' (nur Storno) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 1; ELSE IF @includes = '#ru' SELECT @includetext = ' (nur gemahnt + unbez. + nicht storniert) ', @include_drafts = 0, @only_drafts = 0, @only_reminded = 0, @only_unpayed = 0, @only_akonto = 0, @only_storno = 0, @only_remindedunpayed = 1; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getInvoices_list' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; SET @mode = LOWER(@mode); If @mode = 'm' BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END ELSE If @mode = 'a' BEGIN SELECT @startdate = [dbo].[date_weekfirst]('2000-01-01') ,@enddate = [dbo].[date_weekend](DATEADD(year, 1, @today)); END --Reminder settings DECLARE @stage1 varchar(10), @stage2 varchar(10), @stage3 varchar(10); SELECT @stage1 = [stage1], @stage2 = [stage2], @stage3 = [stage3] FROM [dbo].[fds__admin_reminderSettings](); SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = 'Rechnungsübersicht ' + @includetext + ' für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') WHEN @mode = 'a' THEN 'den gesamten Zeitraum' ELSE '' END ,[ust_options] = '19,0%;16,0%;0,0%'; DECLARE @inv TABLE([Id] varchar(15), [InvoiceID] varchar(255), [DocumentName] nvarchar(255), [DateOfCreation] date, [fds] bit); INSERT INTO @inv SELECT [Id],[invoiceid],[DocumentName],[DateOfCreation] = [DateCreated],[fds] = IIF([isExternal] = 0,1,0) FROM [dbo].[fds__invoices] where CAST([DateCreated] as date) between @startdate AND @enddate and (ISNULL(@include_drafts,0) = 1 OR [isfinal] = 1) and (@only_drafts = 0 OR [isfinal] = 0) and (@only_akonto = 0 OR [InvoiceType] = 'i') and (@only_storno = 0 OR [InvoiceType] = 'c') and ((@only_unpayed = 0 AND @only_remindedunpayed = 0) OR (IsPayed = 0 AND IsCanceled = 0 AND [InvoiceBalance] > 0 )); DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(15), [customer.ExternalId] bigint, [customer.Id] bigint, [ExternalId] nvarchar(255)); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId] FROM [dbo].[fds__invoice_servicerequests] as irq JOIN @inv as i on irq.[InvId] = i.[Id] LEFT JOIN [dbo].[mfr__servicerequests] as s ON irq.[mfr__servicerequest] = s.[id] LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id; With itm as ( SELECT [net_itemsum] = CAST( SUM(ISNULL([value_total],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM(ISNULL([value_total],0) * (1 + (ISNULL([vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL([vat], 19.0) * 0.01)) , [invoice.Id] = inv.[id] --sreq.[invoice.Id] FROM [dbo].[fds__invoice_items] as itm --JOIN @sreq as sreq ON itm.[InvRqId] = SReq.[id] JOIN @inv as inv ON itm.[invid] = inv.[id] GROUP BY inv.[id] --sreq.[invoice.Id] ),sc as( SELECT s.[invoice.Id], [#] = COUNT(s.[id]) FROM @SReq as s GROUP BY s.[invoice.Id] ),contra_accounts as( SELECT [account] = [key], [vat] = TRY_PARSE([value2] as numeric(5,2) USING 'en-US') FROM [dbo].[fds__admin_settings] WHERE [type] = 'contra_account' ), inv as( select iv.[Id] ,[InvoiceId] = iv.[InvoiceId] + ISNULL((CASE WHEN iv.InvoiceType = 'c' THEN (SELECT TOP(1) ' >> ' + i2.[InvoiceId] FROM [dbo].[fds__invoices] as i2 JOIN [dbo].[fds__invoice_details] as id2 on i2.[Id] = id2.[StornoTo_InvId] where id2.[InvId] = iv.[id] and i2.[IsFinal] = 1) ELSE '' END), '') ,[InvoiceType] ,[DocumentName] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = FORMAT([invoiceBalance], '#0.00', 'de') + ' €' ,[EINZELPOS_brutto] = NULL --FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' ,[EINZELPOS_netto] = NULL --FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' ,[vat] = FORMAT(ISNULL(iv.[InvoiceVAT_1], 19.0), '#0.0', 'de') + ' %' ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END ,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = FORMAT(iv.[DateCreated], 'dd.MM.yy') ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,[DateOfCreation] = iv.[DateCreated] ,[DueDate] ,[PaymentTerm] = ISNULL([PaymentTerm], @stage1) ,[PaymentStatus] ,[IsPayed] = CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END as bit) ,[IsCanceled] = CAST(IIF(ISNULL([IsCanceled],0) = 1 OR [dbo].[fds__fn_isInvoiceCancelled](iv.[Id]) = 1, 1,0) as bit) ,[isSent] ,[isFinal] ,[hasFile] = CAST( CASE wHEN iv.[file] is not null and [DocumentNAme] is not null THEN 1 WHEN mfrf.[file] is not null THEN 1 ELSE 0 END as bit) --,[fds] = @true ,[customer_id] = iv.[CustomerId] from [dbo].[fds__invoices] as iv LEFT JOIN itm on iv.Id = itm.[invoice.Id] LEFT JOIN sc on iv.[id] = sc.[invoice.Id] LEFT JOIN contra_accounts as ca ON ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] LEFT JOIN [dbo].[fds__mfr_invoicefiles] as mfrf on iv.[IsExternal] = 1 and mfrf.[Id] = iv.[ExternalId] where iv.Id in (SELECT [Id] FROM @inv) ), reminder as ( SELECT [InvId], [lastReminder] = MAX([DateFinalized]), [#] = COUNT(*) FROM [dbo].[fds__reminder] WHERE [isFinal] = 1 AND [invId] IN (SELECT [Id] FROM @inv) GROUP BY [InvId] ) select inv.* ,[reminderstatus] = CASE WHEN [ispayed] = 1 THEN 0 WHEN [iscanceled] = 1 THEN 0 WHEN DueDate is null THEN 0 WHEN [deb_cred] = 'H' THEN 0 WHEN @stage3 <> '' AND rem.[#] = 2 AND @today > [dbo].[date_addcustom]([lastReminder], @stage3) THEN 3 WHEN @stage2 <> '' AND rem.[#] = 1 AND @today > [dbo].[date_addcustom]([lastReminder], @stage2) THEN 2 WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), ISNULL([PaymentTerm],@stage1)) THEN 1 ELSE 0 END ,[invstatus] = CASE WHEN [IsPayed] = 1 AND [isCanceled] = 0 THEN 'pyd' WHEN [isCanceled] = 1 THEN 'cc' WHEN [isFinal] = 0 THEN 'dft' WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN [deb_cred] = 'H' THEN '' WHEN @today >= [DueDate] THEN 'due' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), @stage1) THEN 'ovd' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' END ,[reminder] = rem.[#] ,[CustomerName] = c.[name] ,[order] = CASE WHEN @include_drafts = 1 THEN ROW_NUMBER() OVER (ORDER BY inv.[DateOfCreation] ASC) ELSE ROW_NUMBER() OVER (ORDER BY TRY_CAST(SUBSTRING([invoiceid], 2,4) AS int), TRY_CAST(SUBSTRING([invoiceid], 7,4) AS int), inv.[DateOfCreation] ASC) END ,[Payment] = IIF(py.[amount] is null,'',FORMAT(ISNULL(py.[amount],0.0), '0.00€', 'de') + IIF(py.[manu] = 1, ' man.','')) /*CASE WHEN [paymentstatus] = 'a' THEN 'vollst.' WHEN [paymentstatus] = 'p' THEN FORMAT(ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.[Id]),0.0), '0.00€', 'de') ELSE '' END*/ FROM inv left JOIN reminder as rem ON inv.[Id] = rem.[InvId] --inv.[id] is already converted to varchar LEFT JOIN [dbo].[mfr__companies] as c ON inv.[customer_id] = c.[id] LEFT JOIN [dbo].[fds__fn_bankingtransactions_perInvoice](@startdate, @enddate) as py ON py.[invid] = inv.[Id] WHERE ((@only_reminded = 0 AND @only_remindedunpayed = 0) OR ISNULL(rem.[#],0) > 0) AND (CASE WHEN @only_unpayed = 0 AND @only_remindedunpayed = 0 THEN 1 WHEN [IsCanceled] = 1 THEN 0 ELSE 1 END) = 1 order by inv.[DateOfCreation] ASC; END GO ALTER AUTHORIZATION ON [dbo].[fds__getInvoices_list_vario] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getInvoices_list2] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getInvoices_list2] @tgtdate date ,@mode varchar(1) = 'm' , @include_drafts bit = 0 , @search varchar(100) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getInvoices_list' ,@authuser , @search); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @true bit = 1, @false bit = 0; DECLARE @searchmode as varchar(1) = CASE WHEN SUBSTRING(ISNULL(@search, '') + ' ', 2,1) <> ':' THEN '' ELSE LOWER(LEFT(@search,1 )) END; DECLARE @customerfilter TABLE ([CustomerID] bigint); IF @searchmode <> '' BEGIN SELECT @mode = 's', @search = SUBSTRING(@search,3, 1000); IF @searchmode = 'c' AND LEN(@search) > 3 BeGIN INSERT INTO @customerfilter SELECT [id] FROM [dbo].[mfr__companies] WHERE [Name] like ('%' + @search + '%'); END END ELSE SET @mode = LOWER(@mode); If @mode = 'm' BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END; --Reminder settings DECLARE @stage1 varchar(10), @stage2 varchar(10), @stage3 varchar(10); SELECT @stage1 = [stage1], @stage2 = [stage2], @stage3 = [stage3] FROM [dbo].[fds__admin_reminderSettings](); SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = 'Rechnungsübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') WHEN @searchmode = 'i' THEN 'Suche nach Rechnungsnummer ''' + @search + '''' WHEN @searchmode = 'c' THEN 'Suche nach Kunde ''' + @search + '''' ELSE '' END ,[ust_options] = '19,0%;16,0%;0,0%'; DECLARE @inv TABLE([Id] varchar(15), [InvoiceID] varchar(255), [DocumentName] nvarchar(255), [DateOfCreation] date, [fds] bit); IF @searchmode = 'i' BEGIN insert into @inv SELECT [Id],[invoiceid],[DocumentName],[DateOfCreation] = [DateCreated],[fds] = IIF([isExternal] = 0,1,0) FROM [dbo].[fds__invoices] where [InvoiceID] = @search OR [InvoiceID] like ('R20[0-9][0-9][-]' + @search); END ELSE IF @searchmode = 'c' BEGIN insert into @inv SELECT [Id],[invoiceid],[DocumentName],[DateOfCreation] = [DateCreated],[fds] = IIF([isExternal] = 0,1,0) FROM [dbo].[fds__invoices] WHERE [CustomerId] IN (SELECT [CustomerId] fROM @customerfilter); END ELSE BEGIN insert into @inv SELECT [Id],[invoiceid],[DocumentName],[DateOfCreation] = [DateCreated],[fds] = IIF([isExternal] = 0,1,0) FROM [dbo].[fds__invoices] WHERE CAST([DateCreated] as date) between @startdate AND @enddate and (ISNULL(@include_drafts,0) = 1 OR [isfinal] = 1); END; DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(15), [customer.ExternalId] bigint, [customer.Id] bigint, [ExternalId] nvarchar(255)); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], s.[ExternalId] FROM [dbo].[fds__invoice_servicerequests] as irq JOIN @inv as i on irq.[InvId] = i.[Id] LEFT JOIN [dbo].[mfr__servicerequests] as s ON irq.[mfr__servicerequest] = s.[id] LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id; With itm as ( SELECT [net_itemsum] = CAST( SUM(ISNULL([value_total],0)) as numeric(12,2)) , [bo_itemsum] = CAST( SUM(ISNULL([value_total],0) * (1 + (ISNULL([vat], 19.0) * 0.01))) as numeric(12,2)) , [vf] = MAX(1 + (ISNULL([vat], 19.0) * 0.01)) , [invoice.Id] = inv.[id] --sreq.[invoice.Id] FROM [dbo].[fds__invoice_items] as itm --JOIN @sreq as sreq ON itm.[InvRqId] = SReq.[id] JOIN @inv as inv ON itm.[invid] = inv.[id] GROUP BY inv.[id] --sreq.[invoice.Id] ),sc as( SELECT s.[invoice.Id], [#] = COUNT(s.[id]) FROM @SReq as s GROUP BY s.[invoice.Id] ),contra_accounts as( SELECT [account] = [key], [vat] = TRY_PARSE([value2] as numeric(5,2) USING 'en-US') FROM [dbo].[fds__admin_settings] WHERE [type] = 'contra_account' ), inv as( select iv.[Id] ,[InvoiceId] = iv.[InvoiceId] + ISNULL((CASE WHEN iv.InvoiceType = 'c' THEN (SELECT TOP(1) ' >> ' + i2.[InvoiceId] FROM [dbo].[fds__invoices] as i2 JOIN [dbo].[fds__invoice_details] as id2 on i2.[Id] = id2.[StornoTo_InvId] where id2.[InvId] = iv.[id] and i2.[IsFinal] = 1) ELSE '' END), '') ,[InvoiceType] ,[DocumentName] ,[requestcount] = sc.[#] ,[request] = (SELECT TOP(1) s.[ExternalId] FROM @SReq as s WHERE s.[invoice.Id] = iv.id) ,[balance] = FORMAT([invoiceBalance], '#0.00', 'de') + ' €' ,[EINZELPOS_brutto] = NULL --FORMAT(itm.bo_itemsum, '#0.00', 'de') + ' €' ,[EINZELPOS_netto] = NULL --FORMAT(itm.net_itemsum, '#0.00', 'de') + ' €' ,[vat] = FORMAT(ISNULL(iv.[InvoiceVAT_1], 19.0), '#0.0', 'de') + ' %' ,[deb_cred] = CASE WHEN [invoiceBalance] >= 0 THEN 'S' ELSE 'H' END --,[customer] = (SELECT TOP(1) [customer.ExternalId] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id] and [customer.ExternalId] is not null ORDER BY SReq.DateOfCreation ASC) ,[contra_account] = ca.[account] ,[Belegdatum] = FORMAT(iv.[DateCreated], 'dd.MM.yy') ,[Buchungstext] = (SELECT TOP(1) SReq.[name] FROM @SReq as sreq WHERE iv.[Id] = sreq.[invoice.Id]) ,[DateOfCreation] = iv.[DateCreated] ,[DueDate] ,[PaymentTerm] = ISNULL([PaymentTerm], @stage1) ,[PaymentStatus] ,[IsPayed] = CAST(CASE WHEN [dbo].[fds__fn_isInvoiceCancelled](iv.[Id]) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END as bit) ,[IsCanceled] = [dbo].[fds__fn_isInvoiceCancelled](iv.[Id]) ,[isSent] ,[isFinal] ,[hasFile] = CAST( CASE wHEN iv.[file] is not null and [DocumentNAme] is not null THEN 1 WHEN mfrf.[file] is not null THEN 1 ELSE 0 END as bit) ,[customer_id] = iv.[CustomerId] from [dbo].[fds__invoices] as iv LEFT JOIN itm on iv.Id = itm.[invoice.Id] LEFT JOIN sc on iv.[id] = sc.[invoice.Id] LEFT JOIN contra_accounts as ca ON ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] LEFT JOIN [dbo].[fds__mfr_invoicefiles] as mfrf on iv.[IsExternal] = 1 and mfrf.[Id] = iv.[ExternalId] where iv.Id in (SELECT [Id] FROM @inv) ), reminder as ( SELECT [InvId], [lastReminder] = MAX([DateFinalized]), [#] = COUNT(*) FROM [dbo].[fds__reminder] WHERE [IsFinal] = 1 AND [invId] IN (SELECT [Id] FROM @inv) GROUP BY [InvId] ) select inv.* ,[reminderstatus] = CASE WHEN [ispayed] = 1 THEN 0 WHEN [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 0 WHEN DueDate is null THEN 0 WHEN [deb_cred] = 'H' THEN 0 WHEN @stage3 <> '' AND rem.[#] = 2 AND @today > [dbo].[date_addcustom]([lastReminder], @stage3) THEN 3 WHEN @stage2 <> '' AND rem.[#] = 1 AND @today > [dbo].[date_addcustom]([lastReminder], @stage2) THEN 2 WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), ISNULL([PaymentTerm],@stage1)) THEN 1 ELSE 0 END ,[invstatus] = CASE WHEN [IsPayed] = 1 AND [isCanceled] = 0 THEN 'pyd' WHEN [isCanceled] = 1 OR [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 'cc' WHEN [isFinal] = 0 THEN 'dft' WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN [deb_cred] = 'H' THEN '' WHEN @today >= [DueDate] THEN 'due' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, [DateOfCreation]), @stage1) THEN 'ovd' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' END ,[reminder] = rem.[#] ,[CustomerName] = c.[name] ,[order] = CASE WHEN @include_drafts = 1 THEN ROW_NUMBER() OVER (ORDER BY inv.[DateOfCreation] ASC) ELSE ROW_NUMBER() OVER (ORDER BY TRY_CAST(SUBSTRING([invoiceid], 2,4) AS int), TRY_CAST(SUBSTRING([invoiceid], 7,4) AS int), inv.[DateOfCreation] ASC) END ,[Payment] = CASE WHEN [paymentstatus] = 'a' THEN 'vollst.' WHEN [paymentstatus] = 'p' THEN FORMAT(ISNULL([dbo].[fds__fn_InvoicePaymentAmount_full](inv.[Id]),0.0), '0.00€', 'de') ELSE '' END FROM inv left JOIN reminder as rem ON inv.[Id] = rem.[InvId] --inv.[id] is already converted to varchar LEFT JOIN [dbo].[mfr__companies] as c ON inv.[customer_id] = c.[id] WHERE (CASE WHEN @searchmode = 'c' THEN (CASE WHEN inv.[customer_id] IN (SELECT [CustomerId] fROM @customerfilter) THEN 1 ELSE 0 END) ELSE 1 END) = 1 order by inv.[DateOfCreation] ASC; END GO ALTER AUTHORIZATION ON [dbo].[fds__getInvoices_list2] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getInvPayments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getInvPayments] @InvID varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 OR [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getInvPayments' ,@authuser , ''); DECLARE @InvoiceId varchar(50) = (SELECT TOP(1) [invoiceid] FROM [fds__invoices] WHERE [id] = @InvID); WITH bs1 as ( SELECT bs.banking_uid, [invid] = value, [manu] = cast(1 as bit) FROM [dbo].[fds__bankingtransactions_settings] as bs CROSS APPLY STRING_SPLIT(bs.assigned_invoice_id, ',') WHERE bs.assigned_invoice_id is not null AND [value] = @InvID UNION SELECT bs.banking_uid, [invid] = value, [manu] = cast(0 as bit) FROM [dbo].[fds__bankingtransactions_settings] as bs CROSS APPLY STRING_SPLIT(bs.auto_invoice_id, ',') WHERE bs.auto_invoice_id is not null AND [value] = @InvID ), bs as ( SELECT banking_uid, [invid], manu = CAST(MAX(CAST([manu] as int)) as bit) from bs1 GROUP BY banking_uid, [invid] ) SELECT bs.[banking_uid] , [account] = bt.[AccountIdentification] , [name] = bt.[NameOfPayer] , [text] = bt.[SepaRemittanceInformation] , [InvID] = @InvID , [InvoiceID] = @InvoiceId , [amount] = FORMAT(ISNULL(bt.[amount], 0.0), '0.00€', 'de') , [date] = FORMAT([ValueDate], 'dd.MM.yyyy', 'de-de') , [manual] = IIF(bs.manu = 1, 'manuell','') , [order] = ROW_NUMBER() OVER (ORDER BY [ValueDate] ASC, [AccountIdentification] ASC) FROM [dbo].[fds__bankingtransactions] as bt JOIN bs ON bt.[uid] = bs.[banking_uid]; END GO ALTER AUTHORIZATION ON [dbo].[fds__getInvPayments] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getInvRequestItems] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getInvRequestItems] @invoiceid varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @idbigint bigint = TRY_CAST(@invoiceid as bigint); DECLARE @SReq TABLE ([id] bigint, [DateOfCreation] datetime, [name] nvarchar(255), [invoice.Id] varchar(20), [customer.ExternalId] bigint, [customer.Id] bigint, [mfr] bit, [fds] bit); INSERT INTO @SReq SELECT s.[Id], s.[DateOfCreation], s.[name], [invoice.Id] = i.[Id], [customer.ExternalId] = cy.ExternalId , [customer.Id] = cy.[id], [mfr] = i.[IsExternal], [fds] = IIF(i.[isexternal] = 0,1,0) FROM [dbo].[mfr__servicerequests] as s JOIN [dbo].[fds__invoice_servicerequests] as iq ON s.[id] = iq.[mfr__servicerequest] JOIN [dbo].[fds__invoices] as i on iq.[InvId] = i.[id] AND i.[id] = @invoiceid LEFT JOIN [dbo].[mfr__companies] as cy on s.[CustomerId] = cy.id where i.[id] = @invoiceid ; SELECT [id],[DateOfCreation],[name],[invoice.Id],[customer.ExternalId],[customer.Id], [mfr] ,[order] = ROW_NUMBER() OVER (ORDER BY [DateOfCreation]) FROM @SReq; SELECT itm.[Id] , [net_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , '#0.00 €','de') END , [bo_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , '#0.00 €','de') END , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , sreq.[invoice.Id] , [order] = ROW_NUMBER() OVER (PARTITION BY itm.[ServiceRequestId] ORDER BY itm.[SortOrder]) FROM [dbo].[mfr__items] as itm JOIN @sreq as sreq ON itm.[ServiceRequestId] = SReq.[id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' ; END GO ALTER AUTHORIZATION ON [dbo].[fds__getInvRequestItems] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getReminder] @Id varchar(8), @includefile bit, @authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 1 THROW 60000, N'not authorized', 1; DECLARE @rem [dbo].[fds__tt__reminder_core]; INSERT INTO @rem SELECT TOP(1) [Id] ,[Version] ,[DocumentName] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[amount_open] ,[subject] ,[text] ,[IsSent] ,[IsFinal] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[file] = CASE WHEN ISNULL(@includefile,0) = 1 THEN [file] else NULL END -- do not return file if not explicitly requested FROM [dbo].[fds__reminder] WHERE [Id] = @Id AND @Id is not null; DECLARE @InvId varchar(15) = (SELECT TOP(1) [InvId] fROM @rem); ---output --admin SELECT TOP(1) [today] , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [CustomerId] = rem.[CustomerId] , [type] = rem.[type] FROM (VALUES(CAST(GETDATE() as date)))base ([today]) cross JOIN @rem as rem; --rem With inv as( select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId ) SELECT TOP(1) o.* ,inv.[InvoiceId] ,[InvoiceDate] = inv.[DateFinalized] ,[InvoiceFileName] = inv.[DocumentName] ,[InvoiceFile] = CASE WHEN ISNULL(@includefile,0) = 1 THEN inv.[file] else NULL END -- do not return file if not explicitly requested ,[hasFile] = CAST ( CASE WHEN o.[file] is null THEN 0 ELSE 1 END as bit) ,[UserNameFinalized] = [dbo].[fis_admin_getUserName_byID](o.[UserFinalized]) ,[UserEmailFinalized] = [dbo].[fis_admin_getUserEmail_byID](o.[UserFinalized]) from @rem as o join inv on o.[invid] = inv.[id]; END GO ALTER AUTHORIZATION ON [dbo].[fds__getReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getReportDocument] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getReportDocument] @reportid varchar(20) AS BEGIN SET NOCOUNT ON; DECLARE @idbigint bigint = TRY_CAST(@reportid as bigint); SELECT TOP(1) [Id] = CAST([Id] as varchar(20)),[InvoiceID],[URI] = '',[DocumentName],[isInvoice] = 1,[DateOfCreation] = [DateCreated],[fds] = CAST( 1 as bit) , [file] = ISNULL(iv.[file], (SELECT TOP(1) mfrf.[file] FROM [dbo].[fds__mfr_invoicefiles] as mfrf where iv.[IsExternal] = 1 and mfrf.[id] = iv.[externalid])) , [order] = ROW_NUMBER() OVER (ORDER BY [DateCreated] ASC) FROM [dbo].[fds__invoices] as iv WHERE [id] = @reportid AND [isFinal] = 1; ; END GO ALTER AUTHORIZATION ON [dbo].[fds__getReportDocument] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getRequest_details] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getRequest_details] @servicerequestid bigint , @mode varchar(3) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_req', @authuser) < 1 THROW 60000, N'not authorized', 1; DECLARE @today date = GETDATE(); DECLARE @SReq TABLE ( [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] [nvarchar](255) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NOT NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NOT NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] [nvarchar](255) NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsTemplate] [bit] NOT NULL, [IsTemplateMobile] [bit] NOT NULL, [CreateFromServiceRequestTemplateId] [bigint] NOT NULL, [Type] [nvarchar](255) NULL, [Summary] nvarchar(255) NULL, [isChild] bit NULL, [baseorder] int, [provision] varchar(255) NULL, [open] bit NULL ); insert into @SReq SELECT [Id] ,[Name] ,[ExternalId] ,[InvoiceId] ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,[DateModified] ,[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,[CustomValues] ,[CurrentOwnerId] ,[CustomerId] ,[ParentServiceRequestId] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then [id] ELSE [ParentServiceRequestId] END ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 ,[provision] = NULL ,[open] = 1 FROM [dbo].[mfr__servicerequests] as s WHERE [id] = @servicerequestid; INSERT INTO @SReq SELECT s.[Id] ,s.[Name] ,s.[ExternalId] ,s.[InvoiceId] ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 , [provision] = null ,[open] = 1 from [dbo].[mfr__servicerequests] as s JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs WHERE NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) ; -- need to use CTE, because row_number is not available with update statements WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), ISNULL([ParentServiceRequestId],[id])) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder FROM @SReq as s JOIN q ON s.[id] = q.[id]; -- need to use CTE, because row_number is not available with update statements WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; DECLARE @inv TABLE ([Id] bigint, [Invoices] varchar(1000), [isOpen] bit); With fdsinv as( SELECT [Id] = fdsr.[mfr__servicerequest], fdsi.[InvoiceId], fdsi.[InvoiceType], [isCanceled] = ISNULL(fdsi.[isCanceled],0) FROM [dbo].[fds__invoice_servicerequests] as fdsr JOIN [dbo].[fds__invoices] as fdsi on fdsr.[invid] = fdsi.[id] JOIN @SReq as s ON fdsr.[mfr__servicerequest] = s.[id] WHERE [isFinal] = 1 AND fdsr.[mfr__servicerequest] is not null ), fi as( SELECT [Id], [isOpen] = MIN(CASE WHEN ISNULL([invoicetype],'r') = 'r' AND [isCanceled] = 0 THEN 0 ELSE 1 END) FROM fdsinv GROUP BY [Id] ) INSERT INTO @inv SELECT [Id] , [invoices] = ISNULL(STUFF( (SELECT CHAR(10) + [InvoiceId] + ' (' + [InvoiceTYpe] + ')' FROM fdsinv as f2 WHERE f2.[id] = fi.[Id] FOR XML PATH, TYPE).value('.[1]','nvarchar(max)') ,1,1,'') , '') , [isOpen] FROM fi; UPDATE s SET s.[invoiceid] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,[open] = 1 --CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END FROM @SReq as s LEFT JOIN @inv as inv on s.[id] = inv.[id]; DECLARE @step TABLE ( [Id] [bigint] NOT NULL, [MobileId] [bigint] NULL, [Version] [int] NOT NULL, [Name] [nvarchar](255) NULL, [IsDone] [bit] NOT NULL, [HasError] [bit] NOT NULL, [TrackingId] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [SortOrder] [int] NOT NULL, [Data] [nvarchar](max) NULL, [DateModifiedOffline] [datetime] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [Comment] [nvarchar](max) NULL, [InternalComment] [nvarchar](max) NULL, [ServiceObjectId] [bigint] NULL, [StepListTemplateId] [bigint] NULL, [ParentId] [bigint] NULL, [order] int NOT NULL ); DECLARE @company TABLE ( [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsPhysicalPerson] [bit] NOT NULL, [IsOwner] [bit] NOT NULL, [IsEmailInvoicingActive] [bit] NOT NULL, [IsSupplier] [bit] NOT NULL, [MappingId] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [SupportTelephone] [nvarchar](255) NULL, [SupportFax] [nvarchar](255) NULL, [SupportMail] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [MainContactId] [bigint] NOT NULL, [address] nvarchar(1000) null ); INSERT INTO @company SELECT DISTINCT cy.*, [address] = [dbo].[fds__getCompanyAddress](cy.[id]) FROM [mfr__companies] as cy JOIN @SReq as s on cy.id = s.[CustomerId]; DECLARE @companyids [dbo].[fds__tt__idlist]; INSERT INTO @companyids SELECT DISTINCT [id] FROM @company; /** OUTPUT + get other types **/ IF @mode in ('r','ov', '','f', 'ful') BEGIN WITH app as( SELECT [start] = MIN(CAST(CASE WHEN a.[StartDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[StartDateTime] as date) > s.[workdoneat] THEN CAST(a.[StartDateTime] as date) ELSE s.[workdoneat] END as date)) , [end] = MAX(CAST(CASE WHEN a.[EndDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[EndDateTime] as date) > s.[workdoneat] THEN CAST(a.[EndDateTime] as date) ELSE s.[workdoneat] END as date)) , [CustomerId] = MAX (s.customerid) , [ParentServiceRequestId] = ISNULL(MIN(CASE WHEN [isChild] = 1 then null else s.[Id] END), MAX([ParentServiceRequestId])) --make sure only one returned FROM [dbo].[mfr__appointments] as a RIGHT JOIN @SReq as s on a.[ServiceRequestId] = s.[Id] AND a.[State] in ('IsWorkDone') ) SELECT TOP(1) [today] , [provisionstart] = CASe WHEN [start] = [end] THEN NULL ELSE [start] END , [provisionend] = [end] , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [paymentterms] = N'10wd' , [invoiceemail] = (SELECT TOP(1) [SupportMail] FROM @company where IsEmailInvoicingActive = 1) , [invoiceaddress] = (SELECT TOP(1) CONCAT([name], CHAR(10), [address]) FROM @company ORDER BY IsEmailInvoicingActive DESC) , [tax_servicerefund] = 0.2 , [CustomerId] = [CustomerId] , [search] = @servicerequestid , [parent] = app.[ParentServiceRequestId] FROM (VALUES(CAST(GETDATE() as date)))base ([today]) CROSS JOIN app; SELECT * ,[order] = ROW_NUMBER() OVER (ORDER BY [baseorder]) FROM @SReq; END IF @mode in ('i','ov') BEGIN SELECT itm.[Id] , [net_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , '#0.00 €','de') END , [bo_pos] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN '' ELSE FORMAT( CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , '#0.00 €','de') END , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , itm.[Note] , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY itm.[ServiceRequestId] ORDER BY itm.[SortOrder]) FROM [dbo].[mfr__items] as itm JOIN @SReq as s ON itm.ServiceRequestId = s.[Id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' ; END ELSE IF @mode in ('f', 'ful') BEGIN SELECT itm.[Id] , [net] = ISNULL([Price],0) , [quantityhours] = ISNULL([quantityhours],1) , itm.[UnitString] , [net_val] = CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , [bo_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , [vat_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * ((ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , itm.[Note] , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY itm.[ServiceRequestId] ORDER BY itm.[SortOrder], itm.[Id]) FROM [dbo].[mfr__items] as itm JOIN @SReq as s ON itm.ServiceRequestId = s.[Id] LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item' ; END IF @mode in ('f', 'ful') BEGIN INSERT INTO @step SELECT stp.* , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY stp.[ServiceRequestId] ORDER BY stp.[SortOrder], stp.[Id]) FROM [dbo].[mfr__steps] as stp JOIN @SReq as s ON stp.ServiceRequestId = s.[Id]; SELECT * from @step; SELECT cc.[Id] , [CompanyName] = cc.[name] , ct.[Gender] , ct.[FirstName] , ct.[LastName] , ct.[Email] , cc.[address] FROM [dbo].[fds__getCompanysContacts](@companyids) as ct join @company as cc on cc.[Id] = ct.[CyId]; SELECT DISTINCT [ref] = 'Einsatzort ' + so.[name] ,[address] = [dbo].[fds__fn_combineAddress] (so.[Name], loc.[AddressString], null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:ServiceObjects' and p.[EntityId] = s.[id] LEFT JOIN [mfr__serviceobjects] as so ON so.id = p.[PartnerId] LEFT JOIN [mfr__*PartnerSet] as po ON p.property = 'ServiceObject:Location' and po.[EntityId] = so.[Id] LEFT join [dbo].[mfr__#locations] as loc ON (loc.[id] = so.[Location#ID] OR po.[PartnerId] = loc.[Id] OR (so.[Id] = loc.[EntityId] and loc.Property = 'ServiceObject:Location')) WHERE so.id is not null and loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Auftragsort ' + [name] ,[address] = [dbo].[fds__fn_combineAddress] (loc.[AddressString], null, null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:Location' and p.[EntityId] = s.[id] join [dbo].[mfr__#locations] as loc ON (s.[Location#ID] = loc.[id] OR p.[PartnerId] = loc.[Id] OR (s.[Id] = loc.[EntityId] and loc.Property = 'ServiceRequest:Location')) WHERE loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Kunde' , [address] FROM @company; END --get invoices --Reminder settings DECLARE @stage1 varchar(10), @stage2 varchar(10), @stage3 varchar(10); SELECT @stage1 = [stage1], @stage2 = [stage2], @stage3 = [stage3] FROM [dbo].[fds__admin_reminderSettings](); With inv as( SELECT [id] = CAST(ir.invid as varchar(20)), [isChild] = CAST(MIN(CAST(s.[isChild] as tinyint)) as BIT), [baseorder] = MIN(s.[baseorder]), [sopen] = CAST( MIN( CAST(s.[open] as tinyint) ) as bit) FROM [dbo].[fds__invoice_servicerequests] as ir JOIN @sreq as s ON ir.[mfr__servicerequest] = s.[id] GROUP by ir.invid ),reminder as ( SELECT [InvId], [lastReminder] = MAX([DateSent]), [#] = COUNT(*) FROM [dbo].[fds__reminder] WHERE [isSent] = 1 AND [invId] IN (SELECT [Id] FROM inv) GROUP BY [InvId] ) SELECT [Id] = CAST(i.[Id] as varchar(20)) ,i.[DateCreated] ,[isFinal] ,[isSent] ,i.[DocumentName] ,[invstatus] = CASE WHEN [IsPayed] = 1 AND [isCanceled] = 0 THEN 'pyd' WHEN [isCanceled] = 1 OR [dbo].[fds__fn_isInvoiceCancelled](inv.[Id]) = 1 THEN 'cc' WHEN [isFinal] = 0 THEN 'dft' WHEN [isFinal] = 1 AND [isSent] = 0 THEN 'uns' WHEN [DueDate] is null THEN 'op' WHEN [invoiceBalance] < 0 THEN '' WHEN @today >= [DueDate] THEN 'due' WHEN @stage1 <> '' AND ISNULL(rem.[#],0) = 0 AND @today > [dbo].[date_addcustom](ISNULL(DueDate, i.[DateCreated]), @stage1) THEN 'ovd' WHEN ISNULL(rem.[#],0) > 0 THEN 'rem' END ,[order] = ROW_NUMBER() OVER ( ORDER BY inv.[isChild], inv.[baseorder], i.[isFinal] DESC, i.[datecreated] ASC ) FROM [dbo].[fds__invoices] as i JOIN inv on i.[Id] = inv.[Id] LEFT JOIN reminder as rem on inv.id = rem.[InvId] WHERE (inv.[sopen] = 1 OR i.[isfinal] = 1) --- don't show any draft invoices for final tasks; ; END GO ALTER AUTHORIZATION ON [dbo].[fds__getRequest_details] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getRequests_list] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getRequests_list] @tgtdate date ,@mode varchar(1) = '' ,@completed bit = 1 ,@authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_req', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getRequests_list' ,@authuser , ''); DECLARE @startdate date, @enddate date, @today date = GETDATE(); SET @mode = ISNULL(LOWER(@mode),''); If @mode in ('r') -- r = open recent BEGIN SET @tgtdate = @today; SELECT @startdate = DATEADD(week, -4, [dbo].[date_weekfirst](@tgtdate)) ,@enddate = @today; END else If @mode in ('m') -- r = open recent BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END DECLARE @openmode as bit = CASE WHEN LOWER(LEFT(ISNULL(@mode, ''),1)) IN ('o', 'r') THEN 1 ELSE 0 END; SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = CASE WHEN @openmode = 1 AND @mode = 'r' THEN 'Übersicht der offenen Aufträge (letzte 4 Wochen seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ')' WHEN @openmode = 1 THEN 'Übersicht der offenen Aufträge' ELSE 'Auftragsübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') ELSE '' END END , [note] = CASE WHEN @openmode = 1 and @mode = 'r' THEN 'Es werden alle Aufträge angezeigt, die selbst offen sind und seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden, oder deren Folgeauftrag offen ist und/oder seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden.' WHEN @openmode = 1 THEN 'Es werden alle Aufträge angezeigt, die selbst oder ein Folgeeauftrag offen ist.' ELSE '' END; DECLARE @SReq TABLE ( [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] varchar(1000) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] varchar(1000) NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](255) NULL, [CustomerName] [nvarchar](255) NULL, [isChild] bit NULL, [open] bit, [baseorder] int ); DECLARE @inv TABLE ([Id] bigint, [Invoices] varchar(4000), [isOpen] bit); With fdsinv as( SELECT [Id] = fdsr.[mfr__servicerequest], fdsi.[InvoiceId], fdsi.[InvoiceType], [isCanceled] = ISNULL(fdsi.[isCanceled],0) FROM [dbo].[fds__invoice_servicerequests] as fdsr JOIN [dbo].[fds__invoices] as fdsi on fdsr.[invid] = fdsi.[id] WHERE [isFinal] = 1 AND fdsr.[mfr__servicerequest] is not null AND fdsr.[mfr__servicerequest] <> -2 ), fi as( SELECT [Id], [isOpen] = MIN(CASE WHEN ISNULL([invoicetype],'r') = 'r' AND [isCanceled] = 0 THEN 0 ELSE 1 END) FROM fdsinv GROUP BY [Id] ) INSERT INTO @inv SELECT [Id] , [invoices] = ISNULL(STUFF( (SELECT CHAR(10) + [InvoiceId] + ' (' + [InvoiceTYpe] + ')' FROM fdsinv as f2 WHERE f2.[id] = fi.[Id] FOR XML PATH, TYPE).value('.[1]','nvarchar(max)') ,1,1,'') , '') , [isOpen] FROM fi; insert into @SReq SELECT s.[Id] ,[Name] ,[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,s.[CustomValues] ,[CurrentOwnerId] ,s.[CustomerId] ,[ParentServiceRequestId] ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,s.[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 FROM [dbo].[mfr__servicerequests] as s -- parent and childs; LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE ([type] in ('IsProject', 'IsMaintenance', 'IsServiceRequest') AND (CASE WHEN @openmode = 1 AND @mode = 'r' THEN ( CASE WHEN [workdoneat] is not null --AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' --AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) AND (CAST([DateOfCreation] as date) BETWEEN @startdate AND @today OR CAST([DateModified] as date) BETWEEN @startdate AND @today) AND EXISTS (SELECT 0 FROM [dbo].[mfr__*PartnerSet] as ps JOIN [dbo].[mfr__tags] as tg on ps.Property = 'ServiceRequest:Tags' and tg.Id = ps.[PartnerId] where EntityId = s.[id] and ps.partnerid = 16034758659 and [Type] = 'ServiceRequest') THEN 1 ELSE 0 END) WHEN @openmode = 1 AND @mode <> 'r' THEN ( CASE WHEN [workdoneat] is not null AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) THEN 1 ELSE 0 END) WHEN @openmode = 0 THEN ( CASE WHEN CAST([DateOfCreation] as date) BETWEEN @startdate AND @enddate THEN 1 ELSE 0 END) ELSE 0 END ) = 1); INSERT INTO @SReq SELECT DISTINCT ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) ,ISNULL(s.[Name], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN ' - - unbekannt - - ' ELSE NULL END) ,s.[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 from [dbo].[mfr__servicerequests] as s RIGHT JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE (s.[type] in ('IsProject', 'IsMaintenance', 'IsServiceRequest') AND NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) AND ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) is not null ) ; WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), CASE WHEN ISNULL([ParentServiceRequestId],0) = 0 THEN [id] ELSE [ParentServiceRequestId] END) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder ,[ParentServiceRequestId] = CASE WHEN s.isChild = 0 THEN s.[Id] ELSE s.[ParentServiceRequestId] END FROM @SReq as s JOIN q ON s.[id] = q.[id]; UPDATE s SET [CustomerName] = c.[name] FROM @SReq as s JOIN [mfr__companies] as c ON s.[CustomerId] = c.[id]; WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation], s.[Id]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; ---OUTPUT WITH tgs as( SELECT ps.[EntityId], tg.* FROM [dbo].[mfr__tags] as tg JOIN [dbo].[mfr__*PartnerSet] as ps ON ps.[Property] = 'ServiceRequest:Tags' and tg.[Id] = ps.[PartnerId] AND ISNULL(tg.[Name],'') <> '' and [Type] = 'ServiceRequest' WHERE tg.Id in (16288120843 ,15842181123 ,16034758659 ,16050520064 ,16783966210 ,16802480128 ,16830398466 ,19650019330 ,19670532096 ,18925977600) AND EXISTS (SELECT 0 FROM @SReq as _s where _s.Id = ps.[EntityId]) ) SELECT s.* ,[tags] = STUFF( (SELECT ',' + TRIM([Name]) FROM tgs where tgs.[EntityId] = s.[Id] order by tgs.[name] FOR XML PATH, TYPE).value('.[1]','varchar(255)'), 1,1,'') FROM @SReq as s order by baseorder SELECT TOP(0) [id] = NULL; END GO ALTER AUTHORIZATION ON [dbo].[fds__getRequests_list] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__getRequests_list2] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__getRequests_list2] @tgtdate date ,@mode varchar(1) = '' ,@completed bit = 1 , @search varchar(100) ,@authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_req', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__getRequests_list' ,@authuser , @search); DECLARE @startdate date, @enddate date, @today date = GETDATE(); DECLARE @searchmode as varchar(1) = CASE WHEN SUBSTRING(ISNULL(@search, '') + ' ', 2,1) <> ':' THEN '' ELSE LOWER(LEFT(@search,1 )) END; IF @searchmode <> '' BEGIN SELECT @mode = 's', @search = SUBSTRING(@search,3, 1000); END ELSE SET @mode = LOWER(@mode); If @mode in ('r') -- r = open recent BEGIN SET @tgtdate = @today; SELECT @startdate = DATEADD(week, -4, [dbo].[date_weekfirst](@tgtdate)) ,@enddate = @today; END else If @mode in ('m') -- r = open recent BEGIN SELECT @startdate = [dbo].[date_monthfirst](@tgtdate) ,@enddate = [dbo].[date_monthend](@tgtdate); END ELSE If @mode = 'w' BEGIN SELECT @startdate = [dbo].[date_weekfirst](@tgtdate) ,@enddate = [dbo].[date_weekend](@tgtdate); END DECLARE @openmode as bit = CASE WHEN LOWER(LEFT(ISNULL(@mode, ''),1)) IN ('o', 'r') THEN 1 ELSE 0 END; SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode , [title] = CASE WHEN @searchmode = 'n' THEN 'Übersicht der Aufträge mit der Auftragsnummer ' + @search WHEN @openmode = 1 AND @mode = 'r' THEN 'Übersicht der offenen Aufträge (letzte 4 Wochen seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ')' WHEN @openmode = 1 THEN 'Übersicht der offenen Aufträge' ELSE 'Auftragsübersicht für ' + CASE WHEN @mode = 'm' THEN 'MONAT ' + FORMAT(@startdate, 'MMM yyyy') WHEN @mode = 'w' THEN 'WOCHE ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' - ' + FORMAT(@enddate, 'dd.MM.') ELSE '' END END , [note] = CASE WHEN @searchmode = 'n' THEN 'Es wird nur der Auftrag mit der Nummer ' + @search + ' angezeigt' WHEN @openmode = 1 and @mode = 'r' THEN 'Es werden alle Aufträge angezeigt, die selbst offen sind und seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden, oder deren Folgeauftrag offen ist und/oder seit ' + FORMAT(@startdate, 'dd.MM.yyyy') + ' erstellt wurden.' WHEN @openmode = 1 THEN 'Es werden alle Aufträge angezeigt, die selbst oder ein Folgeeauftrag offen ist.' ELSE '' END; DECLARE @SReq TABLE ( [Id] [bigint] NOT NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] varchar(1000) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] varchar(1000) NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](255) NULL, [CustomerName] [nvarchar](255) NULL, [isChild] bit NULL, [open] bit, [baseorder] int ); DECLARE @inv TABLE ([Id] bigint, [Invoices] varchar(4000), [isOpen] bit); With fdsinv as( SELECT [Id] = fdsr.[mfr__servicerequest], fdsi.[InvoiceId], fdsi.[InvoiceType], [isCanceled] = ISNULL(fdsi.[isCanceled],0) FROM [dbo].[fds__invoice_servicerequests] as fdsr JOIN [dbo].[fds__invoices] as fdsi on fdsr.[invid] = fdsi.[id] WHERE [isFinal] = 1 AND fdsr.[mfr__servicerequest] is not null AND fdsr.[mfr__servicerequest] <> -2 ), fi as( SELECT [Id], [isOpen] = MIN(CASE WHEN ISNULL([invoicetype],'r') = 'r' AND [isCanceled] = 0 THEN 0 ELSE 1 END) FROM fdsinv GROUP BY [Id] ) INSERT INTO @inv SELECT [Id] , [invoices] = ISNULL(STUFF( (SELECT CHAR(10) + [InvoiceId] + ' (' + [InvoiceTYpe] + ')' FROM fdsinv as f2 WHERE f2.[id] = fi.[Id] FOR XML PATH, TYPE).value('.[1]','nvarchar(max)') ,1,1,'') , '') , [isOpen] FROM fi; WITH s as ( SELECT * FROM [dbo].[mfr__servicerequests] as _s WHERE (CASE WHEN @searchmode = 'n' THEN ( CASE WHEN [ExternalId] = @search OR [ExternalId] like ('_[-]' + @search) THEN 1 ELSE 0 END ) WHEN @openmode = 1 AND @mode = 'r' THEN ( CASE WHEN [workdoneat] is not null --AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' --AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = _s.[id] and sr.[hidden] = 1) AND (CAST([DateOfCreation] as date) BETWEEN @startdate AND @today OR CAST([DateModified] as date) BETWEEN @startdate AND @today) AND EXISTS (SELECT 0 FROM [dbo].[mfr__*PartnerSet] as ps JOIN [dbo].[mfr__tags] as tg on ps.Property = 'ServiceRequest:Tags' and tg.Id = ps.[PartnerId] where EntityId = _s.[id] and ps.partnerid = 16034758659 and [Type] = 'ServiceRequest') THEN 1 ELSE 0 END) WHEN @openmode = 1 AND @mode <> 'r' THEN -- will be covered later because invoice info is included 1 --( CASE WHEN -- [workdoneat] is not null -- AND ISNULL(s.[invoiceid],'') = '' -- AND ISNULL([State], '') <> 'Closed' -- AND ISNULL(inv.[isOpen],1) = 1 -- AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) -- THEN 1 ELSE 0 END) WHEN @openmode = 0 THEN ( CASE WHEN CAST([DateOfCreation] as date) BETWEEN @startdate AND @enddate THEN 1 ELSE 0 END) ELSE 0 END ) = 1 ) insert into @SReq SELECT s.[Id] ,[Name] ,[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,s.[CustomValues] ,[CurrentOwnerId] ,s.[CustomerId] ,[ParentServiceRequestId] ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,s.[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 FROM s -- parent and childs; LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE ([type] in ('IsProject', 'IsMaintenance', 'IsServiceRequest') AND (CASE WHEN @openmode = 1 AND @mode <> 'r' THEN ( CASE WHEN [workdoneat] is not null AND ISNULL(s.[invoiceid],'') = '' AND ISNULL([State], '') <> 'Closed' AND ISNULL(inv.[isOpen],1) = 1 AND NOT EXISTS (SELECT * FROM [dbo].[fds__custom_servicerequest] as sr where sr.[EntityID] = s.[id] and sr.[hidden] = 1) THEN 1 ELSE 0 END) ELSE 1 END -- heres the difference, because main filter is applied in CTE ) = 1); INSERT INTO @SReq SELECT DISTINCT ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) ,ISNULL(s.[Name], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN ' - - unbekannt - - ' ELSE NULL END) ,s.[ExternalId] ,[InvoiceId] = [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid], inv.[Invoices]) ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[CustomerName] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[open] = CASE WHEN s.[workdoneat] is not null AND [dbo].[fds__fn_InvoiceIDs_mfr](s.[invoiceid],'') = '' AND ISNULL(inv.[isOpen],1) = 1 THEN 1 ELSE 0 END ,[baseorder] = 0 from [dbo].[mfr__servicerequests] as s RIGHT JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs LEFT JOIN @inv as inv on inv.[Id] = s.[Id] WHERE (s.[type] in ('IsProject', 'IsMaintenance', 'IsServiceRequest') AND NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) AND ISNULL(s.[Id], CASE WHEN ISNULL(q.[ParentServiceRequestId],0) > 0 THEN q.[ParentServiceRequestId] ELSE NULL END) is not null ) ; WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), CASE WHEN ISNULL([ParentServiceRequestId],0) = 0 THEN [id] ELSE [ParentServiceRequestId] END) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder ,[ParentServiceRequestId] = CASE WHEN s.isChild = 0 THEN s.[Id] ELSE s.[ParentServiceRequestId] END FROM @SReq as s JOIN q ON s.[id] = q.[id]; UPDATE s SET [CustomerName] = c.[name] FROM @SReq as s JOIN [mfr__companies] as c ON s.[CustomerId] = c.[id]; WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation], s.[Id]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; ---OUTPUT WITH tgs as( SELECT ps.[EntityId], tg.* FROM [dbo].[mfr__tags] as tg JOIN [dbo].[mfr__*PartnerSet] as ps ON ps.[Property] = 'ServiceRequest:Tags' and tg.[Id] = ps.[PartnerId] AND ISNULL(tg.[Name],'') <> '' and [Type] = 'ServiceRequest' WHERE tg.Id in (16288120843 ,15842181123 ,16034758659 ,16050520064 ,16783966210 ,16802480128 ,16830398466 ,19650019330 ,19670532096 ,18925977600) AND EXISTS (SELECT 0 FROM @SReq as _s where _s.Id = ps.[EntityId]) ) SELECT s.* ,[tags] = STUFF( (SELECT ',' + TRIM([Name]) FROM tgs where tgs.[EntityId] = s.[Id] order by tgs.[name] FOR XML PATH, TYPE).value('.[1]','varchar(255)'), 1,1,'') FROM @SReq as s order by baseorder SELECT TOP(0) [id] = NULL; END GO ALTER AUTHORIZATION ON [dbo].[fds__getRequests_list2] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__logEmail] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__logEmail] @Ref varchar(25) ,@guid varchar(50) ,@DateSent datetime ,@config nvarchar(max) ,@success bit ,@log nvarchar(max) AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fds__emaillog] ([Ref] ,[guid] ,[DateSent] ,[config] ,[success] ,[log]) VALUES ( @Ref ,@guid ,@DateSent ,@config ,@success ,@log ); END GO ALTER AUTHORIZATION ON [dbo].[fds__logEmail] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__lookupReminders] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__lookupReminders] @InvId varchar(15) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2 THROW 60000, N'not authorized', 1; ELSE IF NOT EXISTS (select 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId) THROW 60000, N'invoice not found', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__lookupReminders' ,@authuser , (SELECT * FROM (VALUES(@InvId, @authuser)) as z ([InvId],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); DECLARE @REM TABLE ( [Id] [varchar](10) NOT NULL, [Version] [int] NOT NULL, [DocumentName] [varchar](100) NULL, [InvId] [varchar](15) NOT NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [type] [varchar](3) NOT NULL, [amount] [numeric](10, 3) NULL, [amount_payed] [numeric](10, 3) NULL, [amount_open] [numeric](10, 3) NULL, [subject] [nvarchar](255) NULL, [text] [nvarchar](2000) NULL, [IsSent] [bit] NOT NULL, [IsFinal] [bit] NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCreated] [datetime] NOT NULL, [UserCreated] [varchar](25) NOT NULL, [DateModified] [datetime] NOT NULL, [UserModified] [varchar](25) NOT NULL, [order] int ); INSERT INTO @REM ([Id] ,[Version] ,[DocumentName] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[subject] ,[text] ,[IsSent] ,[IsFinal] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[order]) SELECT [Id] ,[Version] ,[DocumentName] ,[InvId] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[type] ,[amount] ,[amount_payed] ,[subject] ,[text] ,[IsSent] ,[IsFinal] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] , [order] = ROW_NUMBER() OVER (ORDER BY DateFinalized ASC) FROM [dbo].[fds__reminder] WHERE [invid] = @InvId AND [IsFinal] = 1; DECLARE @last varchar(1) = ISNULL(( SELECT TOP(1) [type] FROM @rem ORDER BY [DateFinalized] DESC), ''); DECLARE @newnum int = CASE WHEN @last IN('l','f') THEN (SELECT COUNT(*) FROM @REM) + 1 WHEN @last = 'm' THEN ISNULL( (SELECT TOP(1) TRY_CAST(LEFT([type],1) as int) FROM @rem ORDER BY [DateFinalized] DESC) , (SELECT COUNT(*) FROM @REM) + 1) ELSE 1 END; ---output SELECT [type] = CAST( CASE WHEN @last = 'f' THEN 'm' WHEN @last = 'm' THEN 'l' ELSE 'f' END as varchar(1)) ,[level] = @newnum; SELECT [subject], [amount], [amount_payed], [DateFinalized] FROM @REM; END GO ALTER AUTHORIZATION ON [dbo].[fds__lookupReminders] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__maint__updateCancelledStatus] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__maint__updateCancelledStatus] AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); DECLARE @log varchar(100) = 'DateCancelled Set: ' + FORMAT(@now,'yyyy-MM-ddTHH:mm:ssZ') + ';' DECLARE @out TABLE([InvId] varchar(10), [log] varchar(100)); --select [id],[invoiceid],[DocumentName],[IsCanceled],[datefinalized] UPDATE inv SET inv.[Version] = inv.[version] + 1 , inv.[DateCancelled] = storno_inv.[DateFinalized] , inv.[UserCancelled] = storno_inv.[UserFinalized] OUTPUT inserted.id, @log INTO @out FROM [dbo].[fds__invoices] as inv JOIN fds__invoice_details as storno_details on storno_details.[StornoTo_InvId] = inv.[id] JOIN fds__invoices as storno_inv on storno_details.[InvId] = storno_inv.[id] and storno_inv.[isFinal] = 1 and storno_inv.[datefinalized] is not null WHERE inv.[IsCanceled] = 0 AND inv.[DateCancelled] is null ; MERGE [dbo].[fds__invoice_details] as TARGET USING @out as SRC ON TARGET.[InvID] = SRC.[InvId] WHEN MATCHED THEN UPDATE SET TARGET.[log] = ISNULL(TARGET.[log], '') + SRC.[log] WHEN NOT MATCHED BY TARGET THEN INSERT ([InvId] ,[log]) VALUES (SRC.[InvId], SRC.[log]) ; END GO ALTER AUTHORIZATION ON [dbo].[fds__maint__updateCancelledStatus] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__merge_bankingtransactions] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__merge_bankingtransactions] @tblname as nvarchar(50) ,@authuser varchar(25) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); DECLARE @tmp [dbo].[fds__tt__bankingtransactions]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__merge_bankingtransactions' ,ISNULL(@authuser,''), ''); MERGE [dbo].[fds__bankingtransactions] as TARGET USING @tmp as SOURCE ON TARGET.[AccountIdentification] = SOURCE.[AccountIdentification] AND TARGET.[ValueDate] = SOURCE.[ValueDate] AND TARGET.[Amount] = SOURCE.[Amount] AND TARGET.[FundsCode] = SOURCE.[FundsCode] AND TARGET.[AccountNumberOfPayer] = SOURCE.[AccountNumberOfPayer] AND TARGET.[BankCodeOfPayer] = SOURCE.[BankCodeOfPayer] AND TARGET.[EndToEndReference] = SOURCE.[EndToEndReference] AND TARGET.[SepaRemittanceInformation] = SOURCE.[SepaRemittanceInformation] WHEN NOT MATCHED BY TARGET THEN INSERT ([AccountIdentification] ,[ValueDate] ,[Amount] ,[FundsCode] ,[AccountNumberOfPayer] ,[BankCodeOfPayer] ,[CompensationAmount] ,[CreditorReference] ,[CreditorsReferenceParty] ,[CustomerReference] ,[EndToEndReference] ,[JournalNumber] ,[MandateReference] ,[NameOfPayer] ,[OriginalAmount] ,[OriginatorsIdentificationCode] ,[PayersReferenceParty] ,[PostingText] ,[SepaRemittanceInformation] ,[TextKeyAddition] ,[TransactionCode] ,[IsUnstructuredData] ,[UnstructuredData] ,[UnstructuredRemittanceInformation] ,[DebitCreditMark] ,[TransactionTypeIdCode]) VALUES ( SOURCE.[AccountIdentification] , SOURCE.[ValueDate] , SOURCE.[Amount] , SOURCE.[FundsCode] , SOURCE.[AccountNumberOfPayer] , SOURCE.[BankCodeOfPayer] , SOURCE.[CompensationAmount] , SOURCE.[CreditorReference] , SOURCE.[CreditorsReferenceParty] , SOURCE.[CustomerReference] , SOURCE.[EndToEndReference] , SOURCE.[JournalNumber] , SOURCE.[MandateReference] , SOURCE.[NameOfPayer] , SOURCE.[OriginalAmount] , SOURCE.[OriginatorsIdentificationCode] , SOURCE.[PayersReferenceParty] , SOURCE.[PostingText] , LEFT(SOURCE.[SepaRemittanceInformation], 200) , SOURCE.[TextKeyAddition] , SOURCE.[TransactionCode] , SOURCE.[IsUnstructuredData] , SOURCE.[UnstructuredData] , SOURCE.[UnstructuredRemittanceInformation] , SOURCE.[DebitCreditMark] , SOURCE.[TransactionTypeIdCode] ) ; MERGE [dbo].[fds__admin_settings] as TARGET USING (VALUES('log','bankingtransaction_merge',FORMAT(@now, 'yyyy-MM-dd HH:mm:ss', 'de'), NULL)) as SRC ([type],[key],[value],[value2]) ON TARGET.[type] = SRC.[type] AND TARGET.[key] = SRC.[key] WHEN MATCHED THEN UPDATE SET TARGET.[value] = SRC.[Value], TARGET.[value2] = SRC.[value2] WHEN NOT MATCHED BY TARGET THEN INSERT ([type], [key], [value], [value2]) VALUES (SRC.[type], SRC.[key], SRC.[value], SRC.[value2]); with b as ( SELECT *, ROW_NUMBER() OVER (PARTITION BY [AccountIdentification] ,[ValueDate] ,[Amount] ,[FundsCode] ,[AccountNumberOfPayer] ,[BankCodeOfPayer] ,[SepaRemittanceInformation] order by [uid], [valuedate]) as [order] FROM [site_fuchs].[dbo].[fds__bankingtransactions] ) DELETE FROM b where [order] > 1; --Process transactions and assignments EXECUTE [dbo].[fds__setBankingtransaction_autoAssigns]; EXECUTE [dbo].[fds__setInvoicePaymentStatus_auto]; END GO ALTER AUTHORIZATION ON [dbo].[fds__merge_bankingtransactions] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__prepInvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__prepInvoice] @servicerequestid bigint , @mode varchar(3) , @authuser varchar(100) , @type char(1) , @sel varchar(1000) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__prepInvoice' ,@authuser , ''); DECLARE @today date = GETDATE(); SET @type = LOWER(ISNULL(@type, 'r')); DECLARE @selReq as TABLE ([id] bigint); IF ISNULL(@sel,'') = '' AND @servicerequestid is not null SET @sel = CAST(@servicerequestid as varchar(1000)); INSERT INTO @selReq SELECT try_cast(t.[value] as bigint) FROM string_split(ISNULL(@sel,''),',') as t WHERE try_cast(t.[value] as bigint) is not null; DECLARE @SReq TABLE ( [Id] [bigint] NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] [nvarchar](255) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] [nvarchar](255) NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](255) NULL, [Summary] nvarchar(255) NULL, [isChild] bit NULL, [baseorder] int, [provision] varchar(255) NULL ); insert into @SReq SELECT [Id] ,[Name] ,[ExternalId] ,[InvoiceId] ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,[DateModified] ,[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,[CustomValues] ,[CurrentOwnerId] ,[CustomerId] ,[ParentServiceRequestId] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then [id] ELSE s.[ParentServiceRequestId] END ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 ,[provision] = NULL FROM [dbo].[mfr__servicerequests] as s WHERE [id] = @servicerequestid; IF @type <> 'i' -- for interim invoices, only one selected servicerequest is allowed -> childs and parents are ignored BEGIN INSERT INTO @SReq SELECT s.[Id] ,s.[Name] ,s.[ExternalId] ,s.[InvoiceId] ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 , [provision_start] = null from [dbo].[mfr__servicerequests] as s JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs WHERE NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) END; WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), ISNULL([ParentServiceRequestId],[id])) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder FROM @SReq as s JOIN q ON s.[id] = q.[id]; WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; IF @type <> 'i' BEGIN DELETE s FROM @SReq as s WHERE NOT EXISTS(SELECT * FROM @selReq as sel where sel.[id] = s.[Id]) END DECLARE @step [dbo].[fds__tt__mfr_steps]; DECLARE @itm [dbo].[fds__tt__mfr_items]; DECLARE @company TABLE ( [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsPhysicalPerson] [bit] NOT NULL, [IsOwner] [bit] NOT NULL, [IsEmailInvoicingActive] [bit] NOT NULL, [IsSupplier] [bit] NOT NULL, [MappingId] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [SupportTelephone] [nvarchar](255) NULL, [SupportFax] [nvarchar](255) NULL, [SupportMail] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [MainContactId] [bigint] NOT NULL, [address] nvarchar(1000) null ); INSERT INTO @company SELECT DISTINCT cy.*, [address] = [dbo].[fds__getCompanyAddress](cy.[id]) FROM [mfr__companies] as cy JOIN @SReq as s on cy.id = s.[CustomerId]; DECLARE @companyids [dbo].[fds__tt__idlist]; INSERT INTO @companyids SELECT DISTINCT [id] FROM @company; INSERT INTO @itm SELECT itm.* , [baseorder] = s.[baseorder], [order] = ROW_NUMBER() OVER (PARTITION BY [ServiceRequestId] ORDER BY [SortOrder], itm.[Id]) from [dbo].[mfr__items] as itm JOIN @SReq as s ON itm.ServiceRequestId = s.[Id] where itm.[Type] <> 'PartialInvoice'; DECLARE @NUM_of_int_Invoices int = 0; IF @type <> 'i' BEGIN -- Add virtual items for intermediate invoices With associated_interims as ( SELECT inv.InvoiceVAT_1 ,inv.InvoiceBalance_net ,inv.DocumentName ,inv.DateCreated ,inv.[dateFinalized] ,s.[baseorder] ,srq.[mfr__servicerequest] ,[payed] = ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.Id),0.0) ,[open_amount] = CAST( ISNULL(inv.InvoiceBalance,0.0) - ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.Id),0.0) as numeric(10,2)) ,[open_amount_net] = CAST( ISNULL(inv.InvoiceBalance,0.0) - ISNULL([dbo].[fds__fn_InvoicePaymentAmount](inv.Id),0.0) as numeric(10,2)) * (100.0 / (100.0 + inv.[InvoiceVAT_1])) --interim invoices can only have one vat !! from [dbo].[fds__invoices] as inv JOIN [dbo].[fds__invoice_servicerequests] as srq ON inv.[Id] = srq.[InvId] AND inv.[InvoiceType] = 'i' --important JOIN @SReq as s ON srq.[mfr__servicerequest] = s.[Id] WHERE inv.[InvoiceType] = 'i' --important; AND ISNULL(inv.[isFinal],0) = 1 AND ISNULL(inv.[IsCanceled],0) = 0 AND [dbo].[fds__fn_IntermediateIsAllocatedToOther](inv.[id],null) = 0 --inonly those intermediates that are not already allocated to any other ) INSERT INTO @itm SELECT [Id] = -2 ,[Version] = 0 ,[QuantityHours] = 1 ,[PlannedQuantityHours] = 1 ,[ItemTypeId] = NULL ,[ItemNumber] = NULL ,[TrackingId] = NULL ,[Manufacture] = NULL ,[Price] = ai.InvoiceBalance_net * -1.0 --without VAT ,[Costs] = ai.InvoiceBalance_net * -1.0 --without VAT ,[NameOrNumber] = REPLACE(ai.DocumentName, '.pdf','') ,[CustomValues] = NULL ,[Note] = '

' + 'Anrechnung der ' + REPLACE(ai.DocumentName, '.pdf','') + ' vom ' + FORMAT(ai.[dateFinalized], 'dd.MM.yyyy', 'de-de') + '

' ,[ExternalId] = NULL ,[Discount] = NULL ,[VAT] = ai.InvoiceVAT_1 ,[IsManual] = 1 ,[SortOrder] = ROW_NUMBER() OVER (PARTITION BY ai.[mfr__servicerequest] ORDER BY ai.[dateFinalized], ai.DateCreated) ,[Type] = 'IntInvoiceAllocation' ,[ServiceRequestId] = -2 --s.[id] ,[ServiceObjectId] = Null ,[CreatorId] = NULL ,[UnitId] = 15825600513 ,[UnitString] = 'Pauschal' ,[baseorder] = ai.[baseorder] , [order] = 10000 + (ROW_NUMBER() OVER (PARTITION BY ai.[mfr__servicerequest] ORDER BY ai.[dateFinalized], ai.DateCreated) * 10) FROM associated_interims as ai UNION SELECT [Id] = -3 ,[Version] = 0 ,[QuantityHours] = 1 ,[PlannedQuantityHours] = 1 ,[ItemTypeId] = NULL ,[ItemNumber] = NULL ,[TrackingId] = NULL ,[Manufacture] = NULL ,[Price] = ai.open_amount_net --without VAT ! positive, because it's a charge ,[Costs] = ai.open_amount_net --without VAT ! positive, because it's a charge ,[NameOrNumber] = 'offener Betrag aus ' + REPLACE(ai.DocumentName, '.pdf','') ,[CustomValues] = NULL ,[Note] = '

' + 'Berechnung des offenen Betrags aus ' + REPLACE(ai.DocumentName, '.pdf','') + ' vom ' + FORMAT(ai.[dateFinalized], 'dd.MM.yyyy', 'de-de') + '

bereits gezahlt (brutto): ' + FORMAT([payed], '0.00', 'de') + '€.

' ,[ExternalId] = NULL ,[Discount] = NULL ,[VAT] = ai.InvoiceVAT_1 ,[IsManual] = 1 ,[SortOrder] = ROW_NUMBER() OVER (PARTITION BY ai.[mfr__servicerequest] ORDER BY ai.[dateFinalized], ai.DateCreated) ,[Type] = 'IntInvoiceAllocationDiff' ,[ServiceRequestId] = -2 --s.[id] ,[ServiceObjectId] = Null ,[CreatorId] = NULL ,[UnitId] = 15825600513 ,[UnitString] = 'Pauschal' ,[baseorder] = ai.[baseorder] , [order] = 10001 + (ROW_NUMBER() OVER (PARTITION BY ai.[mfr__servicerequest] ORDER BY ai.[dateFinalized], ai.DateCreated) * 10) FROM associated_interims as ai WHERE ISNULL(ai.open_amount,0.0) > 0.0; IF EXISTS (SELECT * FROM @itm WHERE [ServiceRequestId] = -2) BEGIN -- Add virtual request INSERT INTO @SReq ([Id] ,[Name] ,[Type] ,[isChild] ,[baseorder]) VALUES(-2 ,'Abschlagszahlungen' ,'vrii' ,0 ,999); SET @type = 'f'; END END; ELSE BEGIN SET @NUM_of_int_Invoices = ISNULL( (SELECT COUNT(*) FROM (SELECT DISTINCT inv.id FROM [dbo].[fds__invoices] as inv JOIN [dbo].[fds__invoice_servicerequests] as srq ON inv.[Id] = srq.[InvId] AND inv.[InvoiceType] = 'i' --important JOIN @SReq as s ON srq.[mfr__servicerequest] = s.[Id] WHERE inv.[InvoiceType] = 'i' --important; AND [dbo].[fds__fn_isInvoiceCancelled](inv.id) = 0 AND inv.[isFinal] = 1)y ) , 0); END; /** OUTPUT + get other types **/ WITH app as( SELECT [start] = MIN(CAST(CASE WHEN a.[StartDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[StartDateTime] as date) < s.[workdoneat] THEN CAST(a.[StartDateTime] as date) ELSE s.[workdoneat] END as date)) , [end] = MAX(CAST(CASE WHEN a.[EndDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[EndDateTime] as date) < s.[workdoneat] THEN CAST(a.[EndDateTime] as date) ELSE s.[workdoneat] END as date)) , [CustomerId] = MIN (s.customerid) FROM [dbo].[mfr__appointments] as a RIGHT JOIN @SReq as s on a.[ServiceRequestId] = s.[Id] AND a.[State] in ('IsWorkDone') ) SELECT TOP(1) [today] , [provisionstart] = CASe WHEN @type = 'i' THEN NULL WHEN [start] = [end] THEN NULL ELSE [start] END , [provisionend] = CASe WHEN @type = 'i' THEN @today ELSE [end] END -- Abschlagsrechnungen immer mit Tagesdatum , [provisionlocation] = N'' , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [paymentterms] = N'10wd' , [invoiceemail] = (SELECT TOP(1) [SupportMail] FROM @company where IsEmailInvoicingActive = 1) , [invoiceaddress] = (SELECT TOP(1) CONCAT([name], CHAR(10), [address]) FROM @company ORDER BY IsEmailInvoicingActive DESC) , [tax_servicerefund] = 0.2 , [CustomerId] = [CustomerId] , [invoicetitle] = CASE WHEN @type = 'i' THEN (CASE WHEN @NUM_of_int_Invoices > 0 THEN CAST((@NUM_of_int_Invoices + 1) as varchar(3)) + '. ' ELSE '' END) + 'Abschlagsrechnung' WHEN @type = 'f' THEN 'Schlussrechnung' WHEN @type = 'c' THEN 'Stornorechnung' ELSE 'Rechnung' END , [type] = @type FROM (VALUES(CAST(GETDATE() as date)))base ([today]) CROSS JOIN app; SELECT * ,[order] = ROW_NUMBER() OVER (ORDER BY [baseorder]) FROM @SReq; IF @type <> 'i' BEGIN SELECT itm.[Id] , [net] = ISNULL([Price],0) , [quantityhours] = ISNULL([quantityhours],1) , itm.[UnitString] , [net_val] = [dbo].[net_val]([Price],[quantityhours], [discount]) , [bo_val] = [dbo].[bo_val]([Price],[quantityhours], [discount], vat.[vat]) , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , [vat_val] = [dbo].[vat_val]([Price],[quantityhours],[discount],vat.[vat]) --, [net_val] = CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) --, [bo_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) --, [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END --, [vat_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * ((ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , [Note] = IIF(ISNULL([Discount], 0) > 0, 'Rabatt '+ FORMAT([discount]*0.01,'#.0%','de-de') + '', '') + ISNULL(itm.[Note],'') , [order] = (itm.[baseorder] * 100) + itm.[order] FROM @itm as itm LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item'; END ELSE BEGIN WITH citm as ( SELECT itm.[ServiceRequestId], [net_val] = SUM( [dbo].[net_val]([Price],[quantityhours],[discount]) ) FROM @itm as itm WHERE itm.[Type] = 'Material' GROUP BY itm.[ServiceRequestId] ) SELECT [Id] = -1 , [net] = 1000.0 , [quantityhours] = 1 , [UnitString] = 'Pauschal' , [net_val] = CAST( 1000.0 as numeric(7,2)) , [bo_val] = CAST( 1000.0 * 1.19 as numeric(7,2)) , [vat] = FORMAT( 19.0, '#0.0','de') + '%' , [vat_val] = CAST( 1000.0 * 0.19 as numeric(7,2)) , [ServiceRequestId] = s.[id] , [SortOrder] = 0 , [Type] = 'PartialInvoice' , [NameOrNumber] = 'Abschlagsbetrag für bereits erbrachte Arbeiten, Dienstleistungen, Materiallieferungen und getätigte Bestellvorgänge zum oben genannten Bauvorhaben' , [Note] = '' , [order] = 1 FROM @SReq as s; END INSERT INTO @step SELECT stp.* , s.[baseorder] , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY stp.[ServiceRequestId] ORDER BY stp.[SortOrder], stp.[Id]) FROM [dbo].[mfr__steps] as stp JOIN @SReq as s ON stp.ServiceRequestId = s.[Id]; SELECT * from @step; SELECT cc.[Id] , [CompanyName] = cc.[name] , ct.[Gender] , ct.[FirstName] , ct.[LastName] , ct.[Email] , cc.[address] FROM [dbo].[fds__getCompanysContacts](@companyids) as ct join @company as cc on cc.[Id] = ct.[CyId]; SELECT DISTINCT [ref] = 'Einsatzort ' + so.[name] ,[address] = [dbo].[fds__fn_combineAddress] (so.[Name], loc.[AddressString], null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:ServiceObjects' and p.[EntityId] = s.[id] LEFT JOIN [mfr__serviceobjects] as so ON so.id = p.[PartnerId] LEFT JOIN [mfr__*PartnerSet] as po ON p.property = 'ServiceObject:Location' and po.[EntityId] = so.[Id] LEFT join [dbo].[mfr__#locations] as loc ON (loc.[id] = so.[Location#ID] OR po.[PartnerId] = loc.[Id] OR (so.[Id] = loc.[EntityId] and loc.Property = 'ServiceObject:Location')) WHERE so.id is not null and loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Auftragsort ' + [name] ,[address] = [dbo].[fds__fn_combineAddress] (loc.[AddressString], null, null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:Location' and p.[EntityId] = s.[id] join [dbo].[mfr__#locations] as loc ON (s.[Location#ID] = loc.[id] OR p.[PartnerId] = loc.[Id] OR (s.[Id] = loc.[EntityId] and loc.Property = 'ServiceRequest:Location')) WHERE loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Kunde' , [address] FROM @company; END GO ALTER AUTHORIZATION ON [dbo].[fds__prepInvoice] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__prepReminder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__prepReminder] @InvId varchar(15) , @authuser varchar(100) , @type varchar(1) , @level int AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2 THROW 60000, N'not authorized', 1; ELSE IF ISNULL(@type,'') NOT IN ('f','m','l') OR ISNULL(@level, 0) < 1 THROW 60000, N'inputs not valid', 1; ELSE IF NOT EXISTS (select 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId) THROW 60000, N'invoice not found', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__prepReminder' ,@authuser , (SELECT * FROM (VALUES(@InvId, @authuser, @type, @level)) as z ([InvId],[authuser],[type],[level]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); DECLARE @now datetime = GETDATE(); DECLARE @today date = CAST(@now as date); --output With inv as( select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId ) SELECT TOP(1) [today] = @today , [invid] = inv.[id] , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [paymentterms] = [PaymentTerm] , [invoiceemail] = IIF(ISNULL([SendToemail],'') = '', [dbo].[fds__getCompanyEmail](inv.[customerid]), [SendToemail]) , [invoiceaddress] = IIF(ISNULL([SendToAddress],'') = '', [dbo].[fds__getCompanyNameAddress](inv.[customerid]),[SendToAddress]) , [CustomerId] = [CustomerId] , [subject] = CASE WHEN @type = 'f' THEN N'Zahlungserinnerung' WHEN @type = 'm' THEN FORMAT(@level,'0','de-de') + N'. Mahnung' WHEN @type = 'l' THEN N'Letzte außergerichtliche Mahnung' ELSE N'Zahlungserinnerung' END , [type] = @type , [invoiceid] = inv.[Invoiceid] , [invoicedate] = inv.[DateFinalized] , [amount] = inv.[InvoiceBalance] , [amount_payed] = CAST( ISNULL([dbo].[fds__fn_InvoicePaymentAmount_full](inv.[Id]),0.0) as numeric(10,2)) FROM inv; END GO ALTER AUTHORIZATION ON [dbo].[fds__prepReminder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__prepStorno_recreate] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__prepStorno_recreate] @InvId varchar(20) , @authuser varchar(100) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__prepStorno_recreate' ,@authuser , ''); DECLARE @today date = GETDATE(); DECLARE @type char(1) = 'r'; DECLARE @selReq as TABLE ([id] bigint); IF EXISTS (SELECT 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId AND ISNULL([isfinal],0) = 1) BEGIN INSERT INTO @selReq SELECT DISTINCT irq.[mfr__servicerequest] from [dbo].[fds__invoice_servicerequests] as irq where InvId = @InvId; END DECLARE @SReq TABLE ( [Id] [bigint] NULL, [Name] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [InvoiceId] [nvarchar](255) NULL, [ClosedAt] [datetime] NULL, [ReleasedAt] [datetime] NULL, [WorkDoneAt] [datetime] NULL, [TargetTimeInMinutes] [bigint] NULL, [DateModified] [datetime] NULL, [DateOfCreation] [datetime] NULL, [DueDateRangeStart] [datetime] NULL, [DueDateRangeEnd] [datetime] NULL, [PortalLink] [nvarchar](255) NULL, [CostCenterId] [bigint] NULL, [Description] [nvarchar](max) NULL, [State] [nvarchar](255) NULL, [CustomValues] [nvarchar](max) NULL, [CurrentOwnerId] [bigint] NULL, [CustomerId] [bigint] NULL, [ParentServiceRequestId] [bigint] NULL, [ParentExtenalId] [nvarchar](255) NULL, [ParentWorkDoneAt] [date] NULL, [ParentInvoiceId] [nvarchar](255) NULL, [Location#ID] [bigint] NULL, [Version] [int] NULL, [IsTemplate] [bit] NULL, [IsTemplateMobile] [bit] NULL, [CreateFromServiceRequestTemplateId] [bigint] NULL, [Type] [nvarchar](255) NULL, [Summary] nvarchar(255) NULL, [isChild] bit NULL, [baseorder] int, [provision] varchar(255) NULL ); insert into @SReq SELECT [Id] ,[Name] ,[ExternalId] ,[InvoiceId] ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,[DateModified] ,[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,[CustomValues] ,[CurrentOwnerId] ,[CustomerId] ,[ParentServiceRequestId] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then [id] ELSE s.[ParentServiceRequestId] END ,[ParentExtenalId] = cast(CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then null ELSE '?' END as nvarchar(255)) ,[ParentWorkDoneAt] = cast(NULL as datetime) ,[ParentInvoiceId] = cast(NULL as nvarchar(255)) ,[Location#ID] ,[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 ,[provision] = NULL FROM [dbo].[mfr__servicerequests] as s WHERE [id] IN (SELECT [Id] from @selReq); IF @type <> 'i' -- for interim invoices, only one selected servicerequest is allowed -> childs and parents are ignored BEGIN INSERT INTO @SReq SELECT s.[Id] ,s.[Name] ,s.[ExternalId] ,s.[InvoiceId] ,s.[ClosedAt] ,s.[ReleasedAt] ,s.[WorkDoneAt] ,s.[TargetTimeInMinutes] ,s.[DateModified] ,s.[DateOfCreation] ,s.[DueDateRangeStart] ,s.[DueDateRangeEnd] ,s.[PortalLink] ,s.[CostCenterId] ,s.[Description] ,s.[State] ,s.[CustomValues] ,s.[CurrentOwnerId] ,s.[CustomerId] ,s.[ParentServiceRequestId] ,[ParentExtenalId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[ExternalId] ELSE NULL END ,[ParentWorkDoneAt] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[WorkDoneAt] ELSE NULL END ,[ParentInvoiceId] = CASE WHEN s.[ParentServiceRequestId] = q.[id] THEN q.[InvoiceId] ELSE NULL END ,s.[Location#ID] ,s.[Version] ,s.[IsTemplate] ,s.[IsTemplateMobile] ,s.[CreateFromServiceRequestTemplateId] ,s.[Type] ,[Summary] = NULL ,[isChild] = CASE WHEN ISNULL(s.[ParentServiceRequestId],0) = 0 then 0 ELSE 1 END ,[baseorder] = 0 , [provision_start] = null from [dbo].[mfr__servicerequests] as s JOIN @SReq as q ON (s.[ParentServiceRequestId] = q.[id] OR q.[ParentServiceRequestId] = s.[id]) --parents or childs WHERE NOT EXISTS (SELECT * FROM @SReq as s2 WHERE s2.[id] = s.[Id]) END; WITH q as ( SELECT [id], [baseorder] = (ROW_NUMBER() OVER (ORDER BY ISNULL([ParentWorkDoneAt], [WorkDoneAt]), ISNULL([ParentServiceRequestId],[id])) * 100) FROM @SReq as s WHERE [ischild] = 0 ) UPDATE s SET [baseorder] = q.baseorder FROM @SReq as s JOIN q ON s.[id] = q.[id]; WITH q as ( SELECT s.[id] , q.[ExternalId], q.[WorkDoneAt], q.[InvoiceId] , [baseorder] = q.[baseorder] + ROW_NUMBER() OVER (PARTITION BY q.[id] ORDER BY s.[dateofcreation]) FROM @SReq as s JOIN @SReq as q ON s.[ParentServiceRequestId] = q.[id] WHERE s.[ischild] = 1 ) UPDATE s SET [ParentExtenalId] = q.[ExternalId] ,[ParentWorkDoneAt] = q.[WorkDoneAt] ,[ParentInvoiceId] = q.[InvoiceId] ,[baseorder] = q.[baseorder] FROM @SReq as s JOIN q ON s.[Id] = q.[id]; IF @type <> 'i' BEGIN DELETE s FROM @SReq as s WHERE NOT EXISTS(SELECT * FROM @selReq as sel where sel.[id] = s.[Id]) END DECLARE @step [dbo].[fds__tt__mfr_steps]; DECLARE @itm [dbo].[fds__tt__mfr_items]; DECLARE @company TABLE ( [Id] [bigint] NOT NULL, [Location#ID] [bigint] NULL, [Version] [int] NOT NULL, [IsPhysicalPerson] [bit] NOT NULL, [IsOwner] [bit] NOT NULL, [IsEmailInvoicingActive] [bit] NOT NULL, [IsSupplier] [bit] NOT NULL, [MappingId] [nvarchar](255) NULL, [ExternalId] [nvarchar](255) NULL, [Name] [nvarchar](255) NULL, [Note] [nvarchar](255) NULL, [SupportTelephone] [nvarchar](255) NULL, [SupportFax] [nvarchar](255) NULL, [SupportMail] [nvarchar](255) NULL, [QuickSearch] [nvarchar](255) NULL, [DateModified] [datetime] NOT NULL, [CustomValues] [nvarchar](max) NOT NULL, [MainContactId] [bigint] NOT NULL, [address] nvarchar(1000) null ); INSERT INTO @company SELECT DISTINCT cy.*, [address] = [dbo].[fds__getCompanyAddress](cy.[id]) FROM [mfr__companies] as cy JOIN @SReq as s on cy.id = s.[CustomerId]; DECLARE @companyids [dbo].[fds__tt__idlist]; INSERT INTO @companyids SELECT DISTINCT [id] FROM @company; INSERT INTO @itm SELECT itm.*, [baseorder] = s.[baseorder], [order] = ROW_NUMBER() OVER (PARTITION BY [ServiceRequestId] ORDER BY [SortOrder], itm.[Id]) from [dbo].[mfr__items] as itm JOIN @SReq as s ON itm.ServiceRequestId = s.[Id]; DECLARE @NUM_of_int_Invoices int = 0; -- Add virtual items for intermediate invoices INSERT INTO @itm SELECT [Id] = -2 ,[Version] = 0 ,[QuantityHours] = 1 ,[PlannedQuantityHours] = 1 ,[ItemTypeId] = NULL ,[ItemNumber] = NULL ,[TrackingId] = NULL ,[Manufacture] = NULL ,[Price] = inv.InvoiceBalance_net * -1.0 --without VAT ,[Costs] = inv.InvoiceBalance_net * -1.0 --without VAT ,[NameOrNumber] = REPLACE(inv.DocumentName, '.pdf','') ,[CustomValues] = NULL ,[Note] = '

' + 'Anrechnung der ' + REPLACE(inv.DocumentName, '.pdf','') + ' vom ' + FORMAT(inv.[dateFinalized], 'dd.MM.yyyy', 'de-de') + '

' ,[ExternalId] = NULL ,[Discount] = NULL ,[VAT] = inv.InvoiceVAT_1 ,[IsManual] = 1 ,[SortOrder] = ROW_NUMBER() OVER (PARTITION BY srq.[mfr__servicerequest] ORDER BY inv.[dateFinalized], inv.DateCreated) ,[Type] = 'PartialInvoice' ,[ServiceRequestId] = -2 --s.[id] ,[ServiceObjectId] = Null ,[CreatorId] = NULL ,[UnitId] = 15825600513 ,[UnitString] = 'Pauschal' ,[baseorder] = s.[baseorder], [order] = 10000 + ROW_NUMBER() OVER (PARTITION BY srq.[mfr__servicerequest] ORDER BY inv.[dateFinalized], inv.DateCreated) from [dbo].[fds__invoices] as inv JOIN [dbo].[fds__invoice_servicerequests] as srq ON inv.[Id] = srq.[InvId] AND inv.[InvoiceType] = 'i' --important JOIN @SReq as s ON srq.[mfr__servicerequest] = s.[Id] WHERE inv.[InvoiceType] = 'i' --important; AND ISNULL(inv.[isFinal],0) = 1 AND ISNULL(inv.[IsCanceled],0) = 0 AND [dbo].[fds__fn_IntermediateIsAllocatedToOther](inv.[id],@InvId) = 0; --inonly those intermediates that are not already allocated to any other (than the to be replaced Inv); IF EXISTS (SELECT * FROM @itm WHERE [ServiceRequestId] = -2) BEGIN -- Add virtual request INSERT INTO @SReq ([Id] ,[Name] ,[Type] ,[isChild] ,[baseorder]) VALUES(-2 ,'Abschlagszahlungen' ,'vrii' ,0 ,999); SET @type = 'f'; END; -- Add virtual item (to front) for (to-be) replaced invoice INSERT INTO @itm SELECT TOP(1) --can only be one [Id] = -2 ,[Version] = 0 ,[QuantityHours] = 1 ,[PlannedQuantityHours] = 1 ,[ItemTypeId] = NULL ,[ItemNumber] = NULL ,[TrackingId] = NULL ,[Manufacture] = NULL ,[Price] = inv.InvoiceBalance_net * -1.0 --without VAT ,[Costs] = inv.InvoiceBalance_net * -1.0 --without VAT ,[NameOrNumber] = REPLACE(inv.DocumentName, '.pdf','') ,[CustomValues] = NULL ,[Note] = '

' + 'Storno der ' + REPLACE(inv.DocumentName, '.pdf','') + ' vom ' + FORMAT(inv.[dateFinalized], 'dd.MM.yyyy', 'de-de') + '

' ,[ExternalId] = NULL ,[Discount] = NULL ,[VAT] = inv.InvoiceVAT_1 ,[IsManual] = 1 ,[SortOrder] = 1 ,[Type] = 'CanceledInvoice' ,[ServiceRequestId] = -3 --s.[id] ,[ServiceObjectId] = Null ,[CreatorId] = NULL ,[UnitId] = 15825600513 ,[UnitString] = 'Pauschal' ,[baseorder] = 0, [order] = 1 from [dbo].[fds__invoices] as inv WHERE ISNULL(inv.[isFinal],0) = 1 AND ISNULL(inv.[IsCanceled],0) = 0 AND inv.[Id] = @InvId; IF EXISTS (SELECT * FROM @itm WHERE [ServiceRequestId] = -3) BEGIN -- Add virtual request INSERT INTO @SReq ([Id] ,[Name] ,[Type] ,[isChild] ,[baseorder]) VALUES(-3 ,'Storno' ,'vrci' ,0 ,-999); END; /** OUTPUT + get other types **/ WITH app as( SELECT [start] = MIN(CAST(CASE WHEN a.[StartDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[StartDateTime] as date) > s.[workdoneat] THEN CAST(a.[StartDateTime] as date) ELSE s.[workdoneat] END as date)) , [end] = MAX(CAST(CASE WHEN a.[EndDateTime] is null THEN s.[workdoneat] WHEN CAST(a.[EndDateTime] as date) > s.[workdoneat] THEN CAST(a.[EndDateTime] as date) ELSE s.[workdoneat] END as date)) , [CustomerId] = MIN (s.customerid) FROM [dbo].[mfr__appointments] as a RIGHT JOIN @SReq as s on a.[ServiceRequestId] = s.[Id] AND a.[State] in ('IsWorkDone') ) SELECT TOP(1) [today] , [provisionstart] = CASe WHEN @type = 'i' THEN NULL WHEN [start] = [end] THEN NULL ELSE [start] END , [provisionend] = CASe WHEN @type = 'i' THEN @today ELSE [end] END -- Abschlagsrechnungen immer mit Tagesdatum , [provisionlocation] = ISNULL((SELECT TOP(1) [provisionlocation] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([provisionlocation],'') <>''),N'') , [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf' , [paymentterms] = ISNULL((SELECT TOP(1) [PaymentTerm] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([PaymentTerm],'') <>''),N'10wd') , [invoiceemail] = ISNULL((SELECT TOP(1) [SendToemail] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([sendToEmail],'') <>''),(SELECT TOP(1) [SupportMail] FROM @company where IsEmailInvoicingActive = 1)) , [invoiceaddress] = ISNULL((SELECT TOP(1) [SendToAddress] FROM [dbo].[fds__invoices] where [Id] = @InvId and ISNULL([SendToAddress],'') <>''),(SELECT TOP(1) CONCAT([name], CHAR(10), [address]) FROM @company ORDER BY IsEmailInvoicingActive DESC)) , [tax_servicerefund] = 0.2 , [CustomerId] = [CustomerId] , [invoicetitle] = CASE WHEN @type = 'i' THEN (CASE WHEN @NUM_of_int_Invoices > 0 THEN CAST((@NUM_of_int_Invoices + 1) as varchar(3)) + '. ' ELSE '' END) + 'Abschlagsrechnung' WHEN @type = 'f' THEN 'Schlussrechnung' WHEN @type = 'c' THEN 'Stornorechnung' ELSE 'Rechnung' END , [type] = @type FROM (VALUES(CAST(GETDATE() as date)))base ([today]) CROSS JOIN app; SELECT * ,[order] = ROW_NUMBER() OVER (ORDER BY [baseorder]) FROM @SReq; IF @type <> 'i' BEGIN SELECT itm.[Id] , [net] = ISNULL([Price],0) , [quantityhours] = ISNULL([quantityhours],1) , itm.[UnitString] , [net_val] = CAST( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) as numeric(7,2)) , [bo_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , [vat] = CASE WHEN LOWER(itm.[type]) in ('Title','Text') THEN null ELSE FORMAT(ISNULL(vat.[vat], 19.0), '#0.0','de') + '%' END , [vat_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * ((ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(7,2)) , itm.[ServiceRequestId] , itm.[SortOrder] , itm.[Type] , itm.[NameOrNumber] , itm.[Note] , [order] = (itm.[baseorder] * 100) + itm.[order] FROM @itm as itm LEFT JOIN [dbo].[fds__custom_vat] as vat ON itm.[Id] = vat.[EntityId] and vat.[EntityType] = 'item'; END ELSE BEGIN WITH citm as ( SELECT itm.[ServiceRequestId], [net_val] = CAST( SUM( (ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0) ) as numeric(7,2)) FROM @itm as itm WHERE itm.[Type] = 'Material' GROUP BY itm.[ServiceRequestId] ) SELECT [Id] = -1 , [net] = 1000.0 , [quantityhours] = 1 , [UnitString] = 'Pauschal' , [net_val] = CAST( 1000.0 as numeric(7,2)) , [bo_val] = CAST( 1000.0 * 1.19 as numeric(7,2)) , [vat] = FORMAT( 19.0, '#0.0','de') + '%' , [vat_val] = CAST( 1000.0 * 0.19 as numeric(7,2)) , [ServiceRequestId] = s.[id] , [SortOrder] = 0 , [Type] = 'PartialInvoice' , [NameOrNumber] = 'Abschlagsbetrag für bereits erbrachte Arbeiten, Dienstleistungen, Materiallieferungen und getätigte Bestellvorgänge zum oben genannten Bauvorhaben' , [Note] = '' , [order] = 1 FROM @SReq as s; END INSERT INTO @step SELECT stp.* , s.[baseorder] , [order] = (s.[baseorder] * 100) + ROW_NUMBER() OVER (PARTITION BY stp.[ServiceRequestId] ORDER BY stp.[SortOrder], stp.[Id]) FROM [dbo].[mfr__steps] as stp JOIN @SReq as s ON stp.ServiceRequestId = s.[Id]; SELECT * from @step; SELECT cc.[Id] , [CompanyName] = cc.[name] , ct.[Gender] , ct.[FirstName] , ct.[LastName] , ct.[Email] , cc.[address] FROM [dbo].[fds__getCompanysContacts](@companyids) as ct join @company as cc on cc.[Id] = ct.[CyId]; SELECT DISTINCT [ref] = 'Einsatzort ' + so.[name] ,[address] = [dbo].[fds__fn_combineAddress] (so.[Name], loc.[AddressString], null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:ServiceObjects' and p.[EntityId] = s.[id] LEFT JOIN [mfr__serviceobjects] as so ON so.id = p.[PartnerId] LEFT JOIN [mfr__*PartnerSet] as po ON p.property = 'ServiceObject:Location' and po.[EntityId] = so.[Id] LEFT join [dbo].[mfr__#locations] as loc ON (loc.[id] = so.[Location#ID] OR po.[PartnerId] = loc.[Id] OR (so.[Id] = loc.[EntityId] and loc.Property = 'ServiceObject:Location')) WHERE so.id is not null and loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Auftragsort ' + [name] ,[address] = [dbo].[fds__fn_combineAddress] (loc.[AddressString], null, null ,loc.[Postal] ,loc.[City] ,loc.[State] ,loc.[Country]) FROM @SReq as s LEFT JOIN [mfr__*PartnerSet] as p ON p.property = 'ServiceRequest:Location' and p.[EntityId] = s.[id] join [dbo].[mfr__#locations] as loc ON (s.[Location#ID] = loc.[id] OR p.[PartnerId] = loc.[Id] OR (s.[Id] = loc.[EntityId] and loc.Property = 'ServiceRequest:Location')) WHERE loc.[id] is not null UNION SELECT DISTINCT [ref] = 'Kunde' , [address] FROM @company; END GO ALTER AUTHORIZATION ON [dbo].[fds__prepStorno_recreate] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__r_getBalanceByMonth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__r_getBalanceByMonth] @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'Umsatz nach Monaten' ,'Umsatz nach Monaten' ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'table' --typ , '' --settings , '' , 0) SELECT * FROM @Admin; WITH inv as ( SELECT [Dateofcreation] = i.[DateCreatEd] ,i.[InvoiceBalance] ,[InvoiceBalanceNetto] = i.[InvoiceBalance_net] FROM [dbo].[fds__invoices] as i WHERE i.[isFinal] = 1 ) SELECT [Monat] = FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de') , [∑ Umsätze] = FORMAT( SUM( ISNULL(inv.[InvoiceBalance],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze] = 'text-align: right' , [∑ Umsätze_netto] = FORMAT( SUM( ISNULL(inv.[InvoiceBalanceNetto],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze_netto] = 'text-align: right' FROM inv GROUP BY FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de'); END GO ALTER AUTHORIZATION ON [dbo].[fds__r_getBalanceByMonth] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__r_getBalanceByYearTopCustomer] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__r_getBalanceByYearTopCustomer] @year int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'Umsatz der Top 100 Kunden für Jahr ' + CAST( @year as varchar(10)) ,'Umsatz der Top 100 Kunden pro Jahr ' + CAST( @year as varchar(10)) ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'table' --typ , '' --settings , '' , 0); SELECT * FROM @Admin; WITH inv as( select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST(_i.[DateCreated] as date) ,_i.CustomerId ,[customerName] = cy.Name ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST(_i.[DateCreated] as date)) FROM [dbo].[fds__invoices] as _i JOIN [dbo].[mfr__companies] as cy on _i.CustomerId = cy.id where YEAR(_i.[DateCreated]) = @year and _i.[isfinal] = 1 GROUP BY CAST(_i.[DateCreated] as date), CustomerId, cy.name ), yr1 as ( SELECT [year] = YEAR( _i.[DateCreated] ) , [total] = SUM( ISNULL(_i.[InvoiceBalance],0) ) FROM [dbo].[fds__invoices] as _i WHERE _i.[isfinal] = 1 GROUP BY YEAR( _i.[DateCreated]) ), yr as ( SELECT [year], [total] = SUM([total]) from yr1 GROUP BY [year] ) SELECT TOP(100) [Jahr] = CAST( YEAR( inv.[Dateofcreation] ) as varchar(4)) , [Name d. Kunden] = [customerName] , [∑ Umsätze] = FORMAT( SUM( ISNULL(inv.[InvoiceBalance],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze] = 'text-align: right' , [% Anteil] = CASE WHEN yr.[total] > 0 THEN FORMAT( SUM( ISNULL(inv.[InvoiceBalance],0) ) / [total], '0 %', 'de') ELSE NULL END , [style:% Anteil] = 'text-align: right' , [order] = ROW_NUMBER() OVER ( ORDER By SUM( ISNULL(inv.[InvoiceBalance],0) ) DESC) FROM inv LEFT JOIN yr on YEAR( inv.[Dateofcreation] ) = yr.[year] GROUP BY YEAR( inv.[Dateofcreation] ), yr.[total], [customerName]; END GO ALTER AUTHORIZATION ON [dbo].[fds__r_getBalanceByYearTopCustomer] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__r_getBalanceByYearTopMaterial] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__r_getBalanceByYearTopMaterial] @year int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'Umsatz der Top 10 Materialien für Jahr ' + CAST( @year as varchar(10)) ,'Umsatz der Top 10 Materialien für Jahr ' + CAST( @year as varchar(10)) ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'table' --typ , '' --settings , '' , 0); SELECT * FROM @Admin; WITH inv as( SELECT [itmPrice] = SUM( ISNULL(itm.[value_total],0) ) ,[Dateofcreation] = CAST(_i.[DateCreated] as date) ,[material] = itm.[text] ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST(_i.[DateCreated] as date)) FROM [dbo].[fds__invoices] as _i JOIN [fds__invoice_items] as itm on itm.[invid] = _i.[id] AND itm.[Type] like 'Material' where YEAR(_i.[DateCreated]) = @year and _i.[isfinal] = 1 GROUP BY CAST(_i.[DateCreated] as date), itm.[text] ), yr1 as ( SELECT [year] = YEAR( _i.[DateCreated] ) , [total] = SUM( ISNULL(_i.[InvoiceBalance],0) ) FROM [dbo].[fds__invoices] as _i WHERE _i.[isfinal] = 1 GROUP BY YEAR( _i.[DateCreated]) ), yr as ( SELECT [year], [total] = SUM([total]) from yr1 GROUP BY [year] ) SELECT TOP(10) [Jahr] = CAST( YEAR( inv.[Dateofcreation] ) as varchar(4)) , [Material] = [material] , [∑ Umsätze] = FORMAT( SUM( ISNULL(inv.[itmPrice],0) ), '#,0.00 €', 'de') , [style:∑ Umsätze] = 'text-align: right' , [% Anteil] = CASE WHEN yr.[total] > 0 THEN FORMAT( SUM( ISNULL(inv.[itmPrice],0) ) / [total], '0 %', 'de') ELSE NULL END , [style:% Anteil] = 'text-align: right' , [order] = ROW_NUMBER() OVER ( ORDER By SUM( ISNULL(inv.[itmPrice],0) ) DESC) FROM inv LEFT JOIN yr on YEAR( inv.[Dateofcreation] ) = yr.[year] GROUP BY YEAR( inv.[Dateofcreation] ), yr.[total], [material]; END GO ALTER AUTHORIZATION ON [dbo].[fds__r_getBalanceByYearTopMaterial] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__r_getBalanceTrendByMonth] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__r_getBalanceTrendByMonth] @year int ,@month int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; set @month = ISNULL(@month, Month(@today)); set @year= ISNULL(@year, Year(@year)); DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'UmsatzTrend für Monat ' + FORMAT(@Month, '00') + ' / ' + FORMAT(@year, '0000') ,'UmsatzTrend für Monat ' + FORMAT(@Month, '00') + ' / ' + FORMAT(@year, '0000') ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'chart' --typ , '{ "charttype": "line", "x1_label_angle": -90, "color": "e0301e", "linewidth": 2, "valuelabels": false, "marker": "none", "colorpalette": "00B050;00B050;00B050", "x1_column": "date", "y1_column": "Value", "y1_title": "Actuals", "x1_title": "", "series_column": "series", "legend_position": "bottom", "show_datalabel": true, "datalabelfontsizescale": 0.6, "height": 600, "width": 1200, "x1_labelformat": "ddd, dd/MM"}' --settings , '' , 0) SELECT * FROM @Admin; with inv as( select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST([Datecreated] as date) ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST([Datecreated] as date)) FROM [dbo].[fds__invoices] as _i where _i.IsFinal = 1 and month([Datecreated]) = @Month and YEAR([Datecreated]) = @year GROUP BY CAST([Datecreated] as date) ) SELECT --[Monat] = FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de') --,[Umsatz] = FORMAT( ISNULL(inv.[InvoiceBalance],0) , '#0.00', 'de') [series] = 'Umsatz' ,[date] = CAST(inv.[Dateofcreation] as date) ,[value] = CAST( SUM( ISNULL(inv.[InvoiceBalance],0) ) OVER (ORDER BY [seq]) as numeric(9,2)) FROM inv ORDER BY [seq] END GO ALTER AUTHORIZATION ON [dbo].[fds__r_getBalanceTrendByMonth] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__r_getBalanceTrendByYear] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__r_getBalanceTrendByYear] @year int, @authuser varchar(100) AS BEGIN SET NOCOUNT ON; DECLARE @today date = GETDATE() DECLARE @tomorrow date = DATEADD(DAY,1,@today); IF [dbo].[fis_getModuleAuth]('fds_reports', @authuser) < 2 THROW 60000, N'not authorized', 1; set @year= ISNULL(@year, Year(@year)); DECLARE @Admin [dbo].[fds__tt__admin_ReportAdminTable]; --Admin Table INSERT INTO @Admin VALUES ( 'bbm' ,'UmsatzTrend für Jahr ' + FORMAT(@year, '0000') ,'UmsatzTrend für Jahr ' + FORMAT(@year, '0000') ,'' + FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm') ,'' ,'chart' --typ , '{ "charttype": "line", "x1_label_angle": -90, "color": "e0301e", "linewidth": 2, "valuelabels": false, "marker": "none", "colorpalette": "00B050;00B050;00B050", "x1_column": "date", "y1_column": "Value", "y1_title": "Actuals", "x1_title": "", "series_column": "series", "legend_position": "bottom", "show_datalabel": true, "datalabelfontsizescale": 0.6, "height": 600, "width": 1200, "x1_labelformat": "ddd, dd/MM"}' --settings , '' , 0) SELECT * FROM @Admin; with inv as( select [InvoiceBalance] = SUM( ISNULL(_i.[InvoiceBalance],0) ) ,[Dateofcreation] = CAST([Datecreated] as date) ,[seq] = ROW_NUMBER() OVER (ORDER BY CAST([Datecreated] as date)) FROM [dbo].[fds__invoices] as _i where _i.IsFinal = 1 and YEAR([Datecreated]) = @year GROUP BY CAST([Datecreated] as date) ) SELECT --[Monat] = FORMAT( inv.[Dateofcreation], 'yyyy - MM', 'de') --,[Umsatz] = FORMAT( ISNULL(inv.[InvoiceBalance],0) , '#0.00', 'de') [series] = 'Umsatz' ,[date] = CAST(inv.[Dateofcreation] as date) ,[value] = CAST( SUM( ISNULL(inv.[InvoiceBalance],0) ) OVER (ORDER BY [seq]) as numeric(9,2)) FROM inv ORDER BY [seq] END GO ALTER AUTHORIZATION ON [dbo].[fds__r_getBalanceTrendByYear] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__remInvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__remInvoice] @Id varchar(10), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__remInvoice' ,@authuser , ''); DELETE FROM [dbo].[fds__invoices] WHERE [Id] = @Id AND @Id is not null AND [isFinal] = 0 AND [IsSent] = 0; DELETE FROM [dbo].[fds__invoice_items] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id); DELETE FROM [dbo].[fds__invoice_servicerequests] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id); DELETE FROM [dbo].[fds__invoice_details] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id) END GO ALTER AUTHORIZATION ON [dbo].[fds__remInvoice] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__remInvoice_Items] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__remInvoice_Items] @Id varchar(10), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; DELETE FROM [dbo].[fds__invoice_items] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id AND ([isFinal] = 1 OR [isSent] = 1 OR [file] is not null)); --make sure it's not deleted for final invoices END GO ALTER AUTHORIZATION ON [dbo].[fds__remInvoice_Items] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__remInvoice_ServiceRequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__remInvoice_ServiceRequests] @Id varchar(10), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; DELETE FROM [dbo].[fds__invoice_servicerequests] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id AND ([isFinal] = 1 OR [isSent] = 1 OR [file] is not null)); --make sure it's not deleted for final invoices END GO ALTER AUTHORIZATION ON [dbo].[fds__remInvoice_ServiceRequests] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setBankingtransaction_assignToIvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setBankingtransaction_assignToIvoice] @banking_uid bigint ,@invoice_id varchar(10) ,@authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; IF NOT EXISTS (SELECT 0 FROM [dbo].[fds__invoices] as i_ WHERE i_.[id] = @invoice_id) THROW 60000, N'Invoice not found', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setBankingtransaction_assignToIvoice' ,@authuser , ('banking_uid: ' + CAST(@banking_uid as varchar(10)) + ', invoice_id: ' + @invoice_id)); DECLARE @now datetime = GETUTCDATE(); DECLARE @today date = @now; DECLARE @OUT TABLE([uid] bigint, [assigned_invoice_id] varchar(25)); MERGE [dbo].[fds__bankingtransactions_settings] as TARGET USING (SELECT TOP(1) * FROM [dbo].[fds__bankingtransactions] as b WHERE b.[uid] = @banking_uid) as SOURCE ON TARGET.[banking_uid] = SOURCE.[uid] WHEN MATCHED THEN UPDATE SET [assigned_invoice_id] = [dbo].[ott_merge_csv]([assigned_invoice_id], @invoice_id), [auto_invoice_id] = NULL WHEN NOT MATCHED BY TARGET THEN INSERT ([banking_uid],[assigned_invoice_id]) VALUES (SOURCE.[uid], @invoice_id) OUTPUT inserted.banking_uid, inserted.[assigned_invoice_id] INTO @out; ; --Process transactions and assignments EXECUTE [dbo].[fds__setBankingtransaction_autoAssigns]; EXECUTE [dbo].[fds__setInvoicePaymentStatus_auto]; --output to confirm as boolean SELECT CAST( (CASE WHEN ISNULL((SELECT TOP(1) [assigned_invoice_id] FROM @out), '') <> '' THEN 1 ELSE 0 END) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fds__setBankingtransaction_assignToIvoice] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setBankingtransaction_autoAssigns] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setBankingtransaction_autoAssigns] AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setBankingtransaction_autoAssigns' ,'', ''); DECLARE @OUT TABLE([banking_uid] bigint, [auto_invoice_id] varchar(255)); with icr as ( SELECT * FROM [dbo].[fds__getInvoiceCredits] (null, null) ), ic as ( SELECT icr.[uid] , icr.[InvoiceId] , [InvID] = CAST(i.[Id] as varchar(15)) , icr.amount , [auto] = CAST(1 as bit) FROM icr JOIN [dbo].[fds__invoices] as i on icr.[InvoiceId] = i.[InvoiceId] and i.[InvoiceId] is not null and i.[IsFinal] = 1 WHERE i.[IsCanceled] = 0 ), ic2 as ( SELECT [banking_uid] = ic.[uid] , [amount] = SUM(ISNULL(ic.[amount], 0.0)) , [InvID_csv] = STRING_AGG(ic.[InvID], ',') from ic WHERE ic.[InvID] is not null GROUP BY ic.[uid] ) --select * from ic2 MERGE [dbo].[fds__bankingtransactions_settings] as TARGET USING ic2 as SOURCE ON TARGET.[banking_uid] = SOURCE.[banking_uid] WHEN NOT MATCHED BY TARGET THEN INSERT ([banking_uid] ,[auto_invoice_id]) VALUES (SOURCE.[banking_uid] ,SOURCE.[InvID_csv]) WHEN MATCHED AND ISNULL(TARGET.[assigned_invoice_id],'') = '' THEN UPDATE SET [auto_invoice_id] = [dbo].[ott_merge_csv](TARGET.[auto_invoice_id],SOURCE.[InvID_csv]) OUTPUT inserted.[banking_uid], inserted.[auto_invoice_id] INTO @out; WITH SOURCE as ( SELECT [banking_uid], [invoice_id] = CAST([value] as varchar(15)), [auto] = CAST( 1 as bit) FROM @OUT CROSS APPLY string_split(ISNULL([auto_invoice_id], ''), ',') as ai WHERE ai.[value] <> '' ) MERGE [dbo].[fds__bankingtransactions_assigns] AS TARGET USING SOURCE ON TARGET.[banking_uid] = SOURCE.[banking_uid] AND TARGET.[invoice_id] = SOURCE.[invoice_id] WHEN NOT MATCHED BY TARGET THEN INSERT ([banking_uid], [invoice_id], [auto]) VALUES (SOURCE.[banking_uid], SOURCE.[invoice_id], SOURCE.[auto]) WHEN NOT MATCHED BY SOURCE AND EXISTS (SELECT NULL FROM @out as o WHERE o.[banking_uid] = TARGET.[banking_uid]) THEN DELETE; END GO ALTER AUTHORIZATION ON [dbo].[fds__setBankingtransaction_autoAssigns] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setBankingtransaction_done] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setBankingtransaction_done] @banking_uid bigint ,@authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setBankingtransaction_done' ,@authuser , ''); DECLARE @now datetime = GETUTCDATE(); DECLARE @today date = @now; DECLARE @OUT TABLE([uid] bigint, [done_manually] varchar(25)); MERGE [dbo].[fds__bankingtransactions_settings] as TARGET USING (SELECT TOP(1) * FROM [dbo].[fds__bankingtransactions] as b WHERE b.[uid] = @banking_uid) as SOURCE ON TARGET.[banking_uid] = SOURCE.[uid] WHEN MATCHED THEN UPDATE SET [done_manually] = FORMAT(@now, 'yyyy-MM-dd HH:mm:ss') + ';' + @authuser WHEN NOT MATCHED BY TARGET THEN INSERT ([banking_uid],[done_manually]) VALUES (SOURCE.[uid], FORMAT(@now, 'yyyy-MM-dd HH:mm:ss') + ';' + @authuser) OUTPUT inserted.banking_uid, inserted.[done_manually] INTO @out; ; --output to confirm as boolean SELECT CAST( (CASE WHEN ISNULL((SELECT TOP(1) [done_manually] FROM @out), '') <> '' THEN 1 ELSE 0 END) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fds__setBankingtransaction_done] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoice] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoice] @InvId varchar(10), @InvoiceType char(1), @InvoiceTitle varchar(100), @InvoiceBalance numeric(10,3), @InvoiceBalance_net numeric(10,3), @InvoiceVAT_net1 numeric(10,3), @InvoiceVAT_1 numeric(5,2), @PaymentTerm varchar(5), @CustomerId bigint, @SendToAddress nvarchar(1000), @SendToEmail nvarchar(255), @ProvisionPeriod varchar(50), @CustomValues nvarchar(max), @authuser varchar(25), @Id varchar(10) OUT AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoice' ,@authuser , ''); DECLARE @now datetime = GETUTCDATE(); DECLARE @today date = @now; SET @PaymentTerm = ISNULL(@PaymentTerm, '10wd'); DECLARE @days tinyint = ISNULL(TRY_PARSE(REPLACE(REPLACE(@PaymentTerm, 'w',''),'d','') as tinyint), 10); DECLARE @duedate date = CASE WHEN RIGHT(@PaymentTerm, 2) = 'wd' THEN DATEADD(weekday, @days, @today) ELSE DATEADd(DAY, @days, @today) END; DECLARE @newid varchar(8) = [dbo].[fds__fn_invoice_id](); DECLARE @out TABLE ( [Id] [varchar](10) NULL, [Version] [int] NULL, [InvoiceId] [nvarchar](25) NULL, [InvoiceType] [char](1) NULL, [InvoiceTitle] [varchar](100) NULL, [DocumentName] [varchar](50) NULL, [InvoiceBalance] [numeric](10, 3) NULL, [InvoiceBalance_net] [numeric](10, 3) NULL, [InvoiceVAT_net1] [numeric](10, 3) NULL, [InvoiceVAT_1] [numeric](5, 2) NULL, [InvoiceVAT_net2] [numeric](10, 3) NULL, [InvoiceVAT_2] [numeric](5, 2) NULL, [PaymentTerm] [varchar](5) NULL, [DueDate] [date] NULL, [CustomerId] [bigint] NULL, [SendToAddress] [nvarchar](1000) NULL, [SendToEmail] [nvarchar](255) NULL, [ProvisionPeriod] [varchar](50) NULL, [ProvisionLocation] [nvarchar](1000) NULL, [PaymentStatus] [char](1) NULL, [IsPayed] [bit] NULL, [IsSent] [bit] NULL, [IsFinal] [bit] NULL, [IsCanceled] [bit] NULL, [Replaces_InvId] [varchar](50) NULL, [CustomValues] [nvarchar](max) NULL, [DateSent] [datetime] NULL, [UserSent] [varchar](25) NULL, [DateFinalized] [datetime] NULL, [UserFinalized] [varchar](25) NULL, [DateCancelled] [datetime] NULL, [UserCancelled] [varchar](25) NULL, [DateCreated] [datetime] NULL, [UserCreated] [varchar](25) NULL, [DateModified] [datetime] NULL, [UserModified] [varchar](25) NULL, [ExternalId] [varchar](25) NULL, [isExternal] [bit] NULL, [file] [varbinary](max) NULL, [file_guid] uniqueidentifier NULL ); MERGE [dbo].[fds__invoices] as TARGET USING (VALUES (@InvId ,ISNULL(@InvoiceType,'r') ,ISNULL(@InvoiceTitle,'Rechnung') ,@InvoiceBalance ,@InvoiceBalance_net ,@InvoiceVAT_net1 ,@InvoiceVAT_1 ,@PaymentTerm ,@DueDate ,@CustomerId ,@SendToAddress ,@SendToEmail ,@ProvisionPeriod ,NULL --[ProvisionLocation] ,NULL --[PaymentStatus] ,0 -- ,0 -- ,@CustomValues , NULL --[DateSent] , NULL --[UserSent] [varchar](25) NULL, ,NULL -- ,NULL -- ,NULL -- ,NULL -- ,@now ,@authuser ,@now ,@authuser ,NULL -- externalid ,0 --isexternal ,NULL --file )) SOURCE ([Id] ,[InvoiceType] ,[InvoiceTitle] ,[InvoiceBalance] ,[InvoiceBalance_net] ,[InvoiceVAT_net1] ,[InvoiceVAT_1] ,[PaymentTerm] ,[DueDate] ,[CustomerId] ,[SendToAddress] ,[SendToEmail] ,[ProvisionPeriod] ,[ProvisionLocation] ,[PaymentStatus] ,[IsPayed] ,[IsSent] ,[CustomValues] ,[DateSent] ,[UserSent] ,[DateFinalized] ,[UserFinalized] ,[DateCancelled] ,[UserCancelled] ,[DateCreated] ,[UserCreated] ,[DateModified] ,[UserModified] ,[externalId] ,[isExternal] ,[file]) ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND TARGET.[IsFinal] = 0 AND TARGET.[file] is null THEN UPDATE SET [Version] = [Version] + 1 ,[InvoiceType] =SOURCE.[InvoiceType] ,[InvoiceTitle] = SOURCE.[InvoiceTitle] ,[InvoiceBalance] = SOURCE.[InvoiceBalance] ,[InvoiceBalance_net] = SOURCE.[InvoiceBalance_net] ,[InvoiceVAT_net1] = SOURCE.[InvoiceVAT_net1] ,[InvoiceVAT_1] =SOURCE. [InvoiceVAT_1] ,[PaymentTerm] = SOURCE.[PaymentTerm] ,[DueDate] = SOURCE.[DueDate] ,[CustomerId] = SOURCE.[CustomerId] ,[SendToAddress] = SOURCE.[SendToAddress] ,[SendToEmail] = SOURCE.[SendToEmail] ,[ProvisionPeriod] = SOURCE.[ProvisionPeriod] ,[ProvisionLocation] = SOURCE.[ProvisionLocation] ,[CustomValues] = SOURCE.[CustomValues] ,[DateModified] = SOURCE.[DateModified] ,[UserModified] = SOURCE.[UserModified] OUTPUT inserted.* INTO @out; SET @Id = @InvId; SELECT TOP(1) * ,[hasFile] = CAST ( CASE WHEN [file] is null THEN 0 ELSE 1 END as bit) ,[UserNameFinalized] = [dbo].[fis_admin_getUserName_byID]([UserFinalized]) ,[UserEmailFinalized] = [dbo].[fis_admin_getUserEmail_byID]([UserFinalized]) from [fds__invoices] WHERE [id] = @InvId; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoice] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoiceCancelled__deprecated] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoiceCancelled__deprecated] @Id varchar(8), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @now datetime = GETUTCDATE(); UPDATE [dbo].[fds__invoices] SET [DateCancelled] = @now, [UserCancelled] = @authuser, [version] = (ISNULL([version],0) + 1) OUTPUT inserted.* WHERE [Id] = @Id AND @Id is not null and [isFinal] = 1 and [IsCanceled] = 0; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoiceCancelled__deprecated] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoiceFile] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoiceFile] @Id varchar(8), @file varbinary(max) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoiceFile' ,'' , (SELECT * FROM (VALUES(@Id, '')) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); UPDATE [dbo].[fds__invoices] SET [file] = @file, [version] = (ISNULL([version],0) + 1), [DocumentName] = ([dbo].[fds__fn_DocumentName]([InvoiceId],[InvoiceType],[InvoiceTitle],[DateFinalized])) OUTPUT inserted.[Id] WHERE [Id] = @Id AND @Id is not null and [file] is null; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoiceFile] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoiceFinal] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoiceFinal] @Id varchar(8), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoiceFinal' ,@authuser , (SELECT * FROM (VALUES(@Id, @authuser)) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); DECLARE @now datetime = GETUTCDATE(); DECLARE @ids as TABLE([Id] varchar(10)); DECLARE @Replaces TABLE([RefInvID] varchar(10)); INSERT INTO @Replaces SELECT [reference_invid] FROM [dbo].[fds__invoice_items] as itm where itm.[InvId] = @Id and itm.[Type] = 'CanceledInvoice' AND ISNULL([reference_invid],'') <>''; DECLARE @Replaces_InvId varchar(50) = CASE WHEN EXISTS(SELECT * FROM @Replaces) THEN STUFF( (SELECT ',' + [refinvid] as [Text] FROM @replaces FOR XML PATH, TYPE).value('.', 'nvarchar(max)'), 1, 1, '') ELSE NULL END; UPDATE [dbo].[fds__invoices] SET [DateFinalized] = @now, [UserFinalized] = @authuser, [DateModified] = @now, [UserModified] = @authuser, [invoiceid] = [dbo].[fds__newInvoiceId](Year(@now)), [version] = (ISNULL([version],0) + 1), [Replaces_InvId] = @Replaces_InvId OUTPUT inserted.[id] INTO @ids WHERE [Id] = @Id AND @Id is not null and [isFinal] = 0 and [isSent] = 0; SELECT iv.* FROM [dbo].[fds__invoices] as iv JOIN @ids as ids on iv.[id] = ids.Id; --this is necessary to get calculated fields also -- update references of intermediate invoices WITH IntInvoiceAllocs as( SELECT [tgtInvId] = @Id, [reference_InvId] FROM [dbo].[fds__invoice_items] where [Type] = 'IntInvoiceAllocation' AND [InvId] = @Id ), existing as ( SELECT intermediates.Id FROM [dbo].[fds__invoice_details] as id JOIN [dbo].[fds__invoices] as intermediates on id.[InvId] = intermediates.[id] JOIN IntInvoiceAllocs as iia on iia.[reference_InvId] = intermediates.[Id] WHERE ISNULL(intermediates.[iscanceled], 0) = 0 AND isnull(intermediates.[isfinal],0) = 1 -- reallocation is allowed for cancelled inv. and ISNULL(id.[AllocatedTo_InvId], '6AA609E8-1') <> @id ) MERGE [dbo].[fds__invoice_details] as TARGET USING IntInvoiceAllocs as iia ON TARGET.[InvID] = iia.[reference_InvId] WHEN NOT MATCHED BY TARGET AND NOT EXISTS (SELECT * FROM existing WHERE existing.[id] = iia.[reference_InvId]) THEN INSERT ([InvId] ,[AllocatedTo_InvId]) VALUES (iia.[reference_InvId], iia.[tgtInvId]) WHEN NOT MATCHED BY SOURCE THEN UPDATE SET [AllocatedTo_InvId] = NULL ; --updated replaced invoices UPDATE refinv SET [DateCancelled] = @now, [UserCancelled] = @authuser, [version] = (ISNULL([version],0) + 1) FROM [dbo].[fds__invoices] as refinv JOIN @Replaces as r on refinv.Id = r.[RefInvID] WHERE refinv.[isFinal] = 1 and refinv.[IsCanceled] = 0; --update replaced invoices (by stornos) EXECUTE [dbo].[fds__maint__updateCancelledStatus]; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoiceFinal] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoicePayed] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoicePayed] @Id varchar(15), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoicePayed' ,@authuser , (SELECT * FROM (VALUES(@Id, @authuser)) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); UPDATE [dbo].[fds__invoices] SET [IsPayed] = 1, [paymentstatus] = 'm', [DateModified] = @now, [UserModified] = @authuser, [version] = (ISNULL([version],0) + 1) OUTPUT inserted.* WHERE [Id] = @Id AND @Id is not null and [IsPayed] = 0; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoicePayed] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoicePaymentStatus_auto] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoicePaymentStatus_auto] AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoicePaymentStatus_auto' ,'', ''); with ic as ( SELECT bt.[uid] , i.[InvoiceId] , [InvID] = i.[Id] , bt.[amount] , [auto] = CAST(CASE WHEN bs.[assigned_invoice_id] = i.[Id] THEN 0 WHEN bs.[auto_invoice_id] = i.[Id] THEN 1 ELSE NULL END as bit) FROM [dbo].[fds__bankingtransactions] as bt JOIN [dbo].[fds__bankingtransactions_settings] as bs ON bt.uid = bs.[banking_uid] JOIN [dbo].[fds__invoices] as i on (bs.[assigned_invoice_id] = i.[Id] OR bs.[auto_invoice_id] = i.[Id]) and i.[IsFinal] = 1 ), ic2 as ( SELECT [banking_uid] = ic.[uid] , [amount] = SUM(ISNULL(ic.[amount], 0.0)) , ic.[invoiceid] , ic.[InvID] , ic.[auto] from ic WHERE ic.[invoiceid] is not null GROUP BY ic.[uid], ic.[invoiceid], ic.[InvID], ic.[auto] ) --select * from ic2 UPDATE i SET i.IsPayed = CASE WHEN ic.[amount] between (i.InvoiceBalance - 0.01) and (i.InvoiceBalance + 0.01) THEN 1 else 0 END , I.[PaymentStatus] = CASE WHEN ic.[amount] between (i.InvoiceBalance - 0.01) and (i.InvoiceBalance + 0.01) THEN 'a' WHEN ic.[amount] < i.InvoiceBalance THEN 'p' ELSE NULL END FROM [dbo].[fds__invoices] as i JOIN ic2 as ic on i.[InvoiceId] = ic.[invoiceid] WHERE i.ispayed = 0; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoicePaymentStatus_auto] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoicePaymentStatus_auto_single] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoicePaymentStatus_auto_single] @InvID varchar(8) AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoicePaymentStatus_auto_single' ,'', (SELECT * FROM (VALUES(@InvID)) as z ([id]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); with ic as ( SELECT bt.[uid] , i.[InvoiceId] , [InvID] = i.[Id] , bt.[amount] , [auto] = CAST(CASE WHEN bs.[assigned_invoice_id] = i.[Id] THEN 0 WHEN bs.[auto_invoice_id] = i.[Id] THEN 1 ELSE NULL END as bit) FROM [dbo].[fds__bankingtransactions] as bt JOIN [dbo].[fds__bankingtransactions_settings] as bs ON bt.uid = bs.[banking_uid] JOIN [dbo].[fds__invoices] as i on (bs.[assigned_invoice_id] = i.[Id] OR bs.[auto_invoice_id] = i.[Id]) and i.[IsFinal] = 1 wHERE i.[id] = @InvID ), ic2 as ( SELECT [banking_uid] = ic.[uid] , [amount] = SUM(ISNULL(ic.[amount], 0.0)) , ic.[invoiceid] , ic.[InvID] , ic.[auto] from ic WHERE ic.[invoiceid] is not null GROUP BY ic.[uid], ic.[invoiceid], ic.[InvID], ic.[auto] ) --select * from ic2 UPDATE i SET i.IsPayed = CASE WHEN ic.[amount] between (i.InvoiceBalance - 0.01) and (i.InvoiceBalance + 0.01) THEN 1 else 0 END , I.[PaymentStatus] = CASE WHEN ic.[amount] between (i.InvoiceBalance - 0.01) and (i.InvoiceBalance + 0.01) THEN 'a' WHEN ic.[amount] < i.InvoiceBalance THEN 'p' ELSE NULL END FROM [dbo].[fds__invoices] as i JOIN ic2 as ic on i.[InvoiceId] = ic.[invoiceid] WHERE i.ispayed = 0 and i.[id] = @InvID; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoicePaymentStatus_auto_single] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoiceSent] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoiceSent] @Id varchar(8), @auto bit, @authuser varchar(25) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); UPDATE [dbo].[fds__invoices] SET [IsSent] = 1, [DateSent] = @now, [UserSent] = CASE WHEN @auto = 1 THEN 'auto' ELSE @authuser END, [version] = (ISNULL([version],0) + 1) OUTPUT inserted.* WHERE [Id] = @Id AND @Id is not null and [isFinal] = 1 and [isSent] = 0; END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoiceSent] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setInvoiceUNPayed] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setInvoiceUNPayed] @Id varchar(8), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2 THROW 60000, N'not authorized', 1; INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setInvoiceUNPayed' ,@authuser , (SELECT * FROM (VALUES(@Id, @authuser)) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); IF EXISTS (SELECT 0 FROM [dbo].[fds__invoices] WHERE [Id] = @Id AND @Id is not null AND [PaymentStatus] = 'm') BEGIN UPDATE [dbo].[fds__invoices] SET [IsPayed] = 0, [paymentstatus] = NULL, [DateModified] = @now, [UserModified] = @authuser, [version] = (ISNULL([version],0) + 1) OUTPUT inserted.* WHERE [Id] = @Id AND @Id is not null AND [PaymentStatus] = 'm'; --apply auto status EXECUTE [dbo].[fds__setInvoicePaymentStatus_auto_single] @Id; END END GO ALTER AUTHORIZATION ON [dbo].[fds__setInvoiceUNPayed] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setMFRInvoiceFile] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setMFRInvoiceFile] @Id varchar(15), @filename varchar(100), @file varbinary(max) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); DECLARE @Idnum bigint = TRY_CAST(@id as bigint); INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info]) VALUES ('fds__setMFRInvoiceFile' ,'' , (SELECT * FROM (VALUES(@Id, '')) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)); IF @idnum is not null and NOT EXISTS (SELECT 0 FROM [dbo].[fds__mfr_invoicefiles] WHERE [id] = @id) BEGIN INSERT INTO [dbo].[fds__mfr_invoicefiles] ([Id] ,[filename] ,[file]) VALUES (@Id ,@filename ,@file) END; END GO ALTER AUTHORIZATION ON [dbo].[fds__setMFRInvoiceFile] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setReminderFile] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setReminderFile] @Id varchar(8), @file varbinary(max) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); UPDATE rem SET [file] = @file, [version] = (ISNULL([version],0) + 1) , [DocumentName] = ([dbo].[fds__fn_ReminderDocumentName]([type],[subject],[DateFinalized],(SELECT TOP(1) [invoiceid] From [dbo].[fds__invoices] WHERE [id] = rem.[invId]))) OUTPUT inserted.[Id] FROM [dbo].[fds__reminder] as rem WHERE [Id] = @Id AND @Id is not null and [file] is null; END GO ALTER AUTHORIZATION ON [dbo].[fds__setReminderFile] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setReminderFinal] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setReminderFinal] @Id varchar(8), @authuser varchar(25) AS BEGIN SET NOCOUNT ON; IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2 THROW 60000, N'not authorized', 1; DECLARE @now datetime = GETUTCDATE(); DECLARE @ids as TABLE([Id] varchar(10)); UPDATE [dbo].[fds__reminder] SET [DateFinalized] = @now, [UserFinalized] = @authuser, [DateModified] = @now, [UserModified] = @authuser, [version] = (ISNULL([version],0) + 1) OUTPUT inserted.[id] INTO @ids WHERE [Id] = @Id AND @Id is not null and [isFinal] = 0 and [isSent] = 0; SELECT rem.* , [InvoiceFile] = (SELECT TOP(1) [file] FROM [fds__invoices] as i where i.InvoiceId = rem.[InvId] and i.IsFinal = 1 and i.[file] is not null and ISNULL(i.[DocumentName],'') <> '') , [InvoiceFileName] = (SELECT TOP(1) [DocumentName] FROM [fds__invoices] as i where i.InvoiceId = rem.[InvId] and i.IsFinal = 1 and i.[file] is not null and ISNULL(i.[DocumentName],'') <> '') FROM [dbo].[fds__reminder] as rem JOIN @ids as ids on rem.[id] = ids.Id; --this is necessary to get calculated fields also END GO ALTER AUTHORIZATION ON [dbo].[fds__setReminderFinal] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setReminderSent] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setReminderSent] @Id varchar(8), @auto bit, @authuser varchar(25) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); UPDATE [dbo].[fds__reminder] SET [IsSent] = 1, [DateSent] = @now, [UserSent] = CASE WHEN @auto = 1 THEN 'auto' ELSE @authuser END, [version] = (ISNULL([version],0) + 1) OUTPUT inserted.* WHERE [Id] = @Id AND @Id is not null and [isFinal] = 1 and [isSent] = 0; END GO ALTER AUTHORIZATION ON [dbo].[fds__setReminderSent] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setReportVAT] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setReportVAT] @id bigint ,@entitytype varchar(50) ,@vat numeric(5,2) ,@authuser varchar(100) AS BEGIN SET NOCOUNT ON; MERGE [dbo].[fds__custom_vat] as TARGET USING (VALUES(@entitytype, @id, @vat)) as SOURCE ([EntityType],[EntityID],[VAT]) ON TARGET.[EntityType] = SOURCE.[EntityType] AND TARGET.[EntityID] = SOURCE.[EntityID] WHEN MATCHED THEN UPDATE SET [VAT] = SOURCE.[VAT] WHEN NOT MATCHED THEN INSERT ([EntityType],[EntityID],[VAT]) VALUES (SOURCE.[EntityType],SOURCE.[EntityID],SOURCE.[VAT]) ; END GO ALTER AUTHORIZATION ON [dbo].[fds__setReportVAT] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__setStatus] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__setStatus] @table varchar(50) ,@action varchar(50) ,@setid varchar(50) ,@info varchar(250) AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); MERGE [dbo].[fds__status] as TARGET USING (VALUES(@table, @action, @now,@setid)) as src ([table],[action],[timestamp],[setid]) ON TARGET.[table] = src.[table] and TARGET.[action] = src.[action] WHEN MATCHED THEN UPDATE SET [timestamp] = src.[timestamp], [setid] = src.[setid] WHEN NOT MATCHED BY TARGET THEN INSERT ([table],[action],[timestamp],[setid]) VALUES (src.[table],src.[action],src.[timestamp],src.[setid]); INSERT INTO [dbo].[fds__log]([table],[action],[timestamp],[setid], [info]) VALUES (@table,@action,@now,@setid,@info); END GO ALTER AUTHORIZATION ON [dbo].[fds__setStatus] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fds__toggleRequestHidden] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fds__toggleRequestHidden] @Id bigint, @authuser varchar(25) AS BEGIN SET NOCOUNT ON; MERGE [dbo].[fds__custom_servicerequest] as TARGET USING (SELECT [id] FROM [mfr__servicerequests] as sr where [id] = @id) as SOURCE ([id]) ON TARGET.[EntityId] = SOURCE.[Id] WHEN MATCHED THEN UPDATE SET [hidden] = CASE WHEN TARGET.[hidden] = 1 THEN 0 ELSE 1 END WHEN NOT MATCHED BY TARGET THEN INSERT ([EntityId] ,[hidden]) VALUES (SOURCE.[Id] ,1) OUTPUT inserted.*; END GO ALTER AUTHORIZATION ON [dbo].[fds__toggleRequestHidden] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_addGroupMember] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_addGroupMember] @authaccount varchar(5) ,@usergroup_id varchar(5) ,@useraccount_id varchar(5) AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); IF NOT EXISTS (SELECT * FROM [dbo].[fis_usergroups_members] WHERE [usergroup_id] = @usergroup_id AND [useraccount_id] = @useraccount_id and [DateDeleted] is null) BEGIN INSERT INTO [dbo].[fis_usergroups_members] ([usergroup_id] ,[useraccount_id] ,[UserCreated] ,[DateCreated] ,[UserDeleted] ,[DateDeleted]) VALUES (@usergroup_id ,@useraccount_id ,@authaccount ,@utcnow ,NULL ,NULL); END SELECT CAST((CASE WHEN EXISTS (SELECT * FROM [dbo].[fis_usergroups_members] WHERE [usergroup_id] = @usergroup_id AND [useraccount_id] = @useraccount_id and [DateDeleted] is null) THEN 1 ELSE 0 END) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_addGroupMember] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_createUserAccount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_createUserAccount] @name nvarchar(100) ,@firstname nvarchar(100) ,@title varchar(50) ,@gender varchar(1) ,@email varchar(255) ,@mobile varchar(50) ,@password nvarchar(20) ,@enc_key uniqueidentifier AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); INSERT INTO [dbo].[fis_useraccounts] ([useraccount_id] ,[name_enc] ,[firstname_enc] ,[title_enc] ,[gender_enc] ,[email_enc] ,[mobile_enc] ,[password_enc] ,[UserDisabled] ,[DateDisabled] ,[UserCreated] ,[DateCreated] ,[UserModified] ,[DateModified] ,[UserDeleted] ,[DateDeleted]) OUTPUT inserted.[useraccount_id] VALUES ([dbo].[fis_fn_useraccount_id] () ,ENCRYPTBYKEY(@enc_key, @name) ,ENCRYPTBYKEY(@enc_key, @firstname) ,ENCRYPTBYKEY(@enc_key, @title) ,ENCRYPTBYKEY(@enc_key, @gender) ,ENCRYPTBYKEY(@enc_key, @email) ,ENCRYPTBYKEY(@enc_key, @mobile) ,CASE WHEN @password is null then ENCRYPTBYKEY(@enc_key, CAST([dbo].[ocms_fn_generatePassword] (8, 0, 1, 1) AS nvarchar(20))) ELSE ENCRYPTBYKEY(@enc_key, @password) END ,NULL --[UserDisabled] ,NULL --[DateDisabled] ,'sa' ,@utcnow ,'sa' ,@utcnow ,NULL ,NULL); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_createUserAccount] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_debug] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_debug] @machine varchar(50) ,@type varchar(10) ,@url varchar(255) ,@uniquekey varchar(5) ,@authuser varchar(5) ,@query varchar(max) ,@form_content nvarchar(max) ,@server_variables varchar(max) ,@cookies varchar(max) ,@authcookie varchar(max) ,@files varchar(max) ,@isdebug bit AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[fis_admin_debuglog] ([machine] ,[type] ,[url] ,[uniquekey] ,[authuser] ,[query] ,[form / content] ,[server_variables] ,[cookies] ,[authcookie] ,[files] ,[isdebug] ,[timestamp]) VALUES (@machine ,@type ,@url ,@uniquekey ,@authuser ,@query ,@form_content ,@server_variables ,@cookies ,@authcookie ,@files ,@isdebug ,GETUTCDATE() ); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_debug] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_delUserAccount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_delUserAccount] @authaccount varchar(5) ,@useraccount_id varchar(5) AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); IF EXISTS (SELECT * FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id and [DateDeleted] is null) BEGIN UPDATE [dbo].[fis_useraccounts] SET [UserDeleted] = @authaccount ,[DateDeleted] = @utcnow WHERE [useraccount_id] = @useraccount_id; END SELECT CAST((CASE WHEN NOT EXISTS (SELECT * FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id and [DateDeleted] is null) THEN 1 ELSE 0 END) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_delUserAccount] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_delUserGroup] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_delUserGroup] @authaccount varchar(5) ,@usergroup_id varchar(5) AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); IF EXISTS (SELECT * FROM [dbo].[fis_usergroups] WHERE [usergroup_id] = @usergroup_id and [DateDeleted] is null) BEGIN UPDATE [dbo].[fis_usergroups] SET [UserDeleted] = @authaccount ,[DateDeleted] = @utcnow WHERE [usergroup_id] = @usergroup_id; END SELECT CAST((CASE WHEN NOT EXISTS (SELECT * FROM [dbo].[fis_usergroups] WHERE [usergroup_id] = @usergroup_id and [DateDeleted] is null) THEN 1 ELSE 0 END) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_delUserGroup] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_remGroupMember] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_remGroupMember] @authaccount varchar(5) ,@usergroup_id varchar(5) ,@useraccount_id varchar(5) AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); IF EXISTS (SELECT * FROM [dbo].[fis_usergroups_members] WHERE [usergroup_id] = @usergroup_id AND [useraccount_id] = @useraccount_id and [DateDeleted] is null) BEGIN UPDATE [dbo].[fis_usergroups_members] SET [UserDeleted] = @authaccount ,[DateDeleted] = @utcnow WHERE [usergroup_id] = @usergroup_id AND [useraccount_id] = @useraccount_id; END SELECT CAST((CASE WHEN NOT EXISTS (SELECT * FROM [dbo].[fis_usergroups_members] WHERE [usergroup_id] = @usergroup_id AND [useraccount_id] = @useraccount_id and [DateDeleted] is null) THEN 1 ELSE 0 END) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_remGroupMember] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_resetUserPassword] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_resetUserPassword] @authaccount varchar(10) ,@useraccount_id varchar(10) ,@enc_key uniqueidentifier AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); DECLARE @auth smallint = [dbo].[fis_admin_getUserAuth](@authaccount); DECLARE @newpassword nvarchar(20) = [dbo].[ocms_fn_generatePassword] (8, 0, 1, 1); IF @auth > 1 OR @authaccount = @useraccount_id BEGIN UPDATE [dbo].[fis_useraccounts] SET [password_enc] = ENCRYPTBYKEY(@enc_key, @newpassword) , [DateModified] = GETUTCDATE() , [UserModified] = @authaccount WHERE [useraccount_id] = @useraccount_id AND [dateDeleted] is null; SELECT CAST(CASE WHEN DECRYPTBYKEY((SELECT TOP(1) [password_enc] FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id)) = @newpassword THEN 1 ELSE 0 END as bit); END END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_resetUserPassword] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_setNewPassword] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_setNewPassword] @useraccount_id varchar(10) ,@oldpassword nvarchar(20) ,@newpassword nvarchar(20) ,@enc_key uniqueidentifier AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); IF LEN(ISNULL(@newpassword,'')) < 6 THROW 60000, N'password requirements', 1; IF NOT EXISTS( SELECT 0 FROM [dbo].[fis_useraccounts] as ua WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null AND [useraccount_id] = @useraccount_id and ISNULL(@useraccount_id, '') <> '' AND CAST(DECRYPTBYKEY(ua.[password_enc]) as nvarchar(20)) = @oldpassword AND @oldpassword <> '' AND ua.[password_enc] is not null ) THROW 60000, N'not found or not matching', 1; UPDATE [dbo].[fis_useraccounts] SET [password_enc] = ENCRYPTBYKEY(@enc_key, @newpassword) , [DateModified] = GETUTCDATE() , [UserModified] = @useraccount_id WHERE [useraccount_id] = @useraccount_id AND [dateDeleted] is null; SELECT CAST(CASE WHEN DECRYPTBYKEY((SELECT TOP(1) [password_enc] FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id)) = @newpassword THEN 1 ELSE 0 END as bit); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_setNewPassword] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_setUserAccount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_setUserAccount] @authaccount varchar(5) ,@useraccount_id varchar(5) ,@name nvarchar(100) ,@firstname nvarchar(100) ,@title varchar(50) ,@gender varchar(1) ,@email varchar(255) ,@mobile varchar(50) ,@password nvarchar(20) ,@enc_key uniqueidentifier AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); DECLARE @auth smallint = [dbo].[fis_admin_getUserAuth](@authaccount); DECLARE @createdID as TABLE ([id] varchar(5)); IF @auth > 1 BEGIN IF EXISTS (SELECT * FROM [dbo].[fis_useraccounts] WHERE [DateDeleted] is null AND [useraccount_id] <> ISNULL(@useraccount_id, '') AND ISNULL(@email,'') <> '' AND LTRIM(RTRIM(DECRYPTBYKEY([email_enc]))) like LTRIM(RTRIM(@email))) THROW 60001, 'email is already assigned to another account', 1; MERGE [dbo].[fis_useraccounts] as TARGET USING (VALUES( ISNULL(@useraccount_id, [dbo].[fis_fn_useraccount_id] ()) ,ENCRYPTBYKEY(@enc_key, LTRIM(RTRIM(@name))) ,ENCRYPTBYKEY(@enc_key, LTRIM(RTRIM(@firstname))) ,ENCRYPTBYKEY(@enc_key, LTRIM(RTRIM(@title))) ,ENCRYPTBYKEY(@enc_key, LOWER(@gender)) ,ENCRYPTBYKEY(@enc_key, LTRIM(RTRIM(LOWER(@email)))) ,ENCRYPTBYKEY(@enc_key, LTRIM(RTRIM(@mobile))) )) as SOURCE([useraccount_id] ,[name_enc] ,[firstname_enc] ,[title_enc] ,[gender_enc] ,[email_enc] ,[mobile_enc]) ON TARGET.[useraccount_id] = SOURCE.[useraccount_id] WHEN MATCHED THEN UPDATE SET TARGET.[name_enc] = ISNULL(SOURCE.[name_enc],TARGET.[name_enc]) ,TARGET.[firstname_enc] = ISNULL(SOURCE.[firstname_enc],TARGET.[firstname_enc]) ,TARGET.[title_enc] = SOURCE.[title_enc] ,TARGET.[gender_enc] = SOURCE.[gender_enc] ,TARGET.[email_enc] = ISNULL(SOURCE.[email_enc],TARGET.[email_enc]) ,TARGET.[mobile_enc] = SOURCE.[mobile_enc] ,TARGET.[UserModified] = @authaccount ,TARGET.[DateModified] = @utcnow WHEN NOT MATCHED BY TARGET THEN INSERT ([useraccount_id] ,[name_enc] ,[firstname_enc] ,[title_enc] ,[gender_enc] ,[email_enc] ,[mobile_enc] ,[password_enc] ,[UserDisabled] ,[DateDisabled] ,[UserCreated] ,[DateCreated] ,[UserModified] ,[DateModified] ,[UserDeleted] ,[DateDeleted]) VALUES (SOURCE.[useraccount_id] ,SOURCE.[name_enc] ,SOURCE.[firstname_enc] ,SOURCE.[title_enc] ,SOURCE.[gender_enc] ,SOURCE.[email_enc] ,SOURCE.[mobile_enc] ,CASE WHEN @password is null then ENCRYPTBYKEY(@enc_key, CAST([dbo].[ocms_fn_generatePassword] (8, 0, 1, 1) AS nvarchar(20))) ELSE ENCRYPTBYKEY(@enc_key, @password) END ,NULL --[UserDisabled] ,NULL --[DateDisabled] ,@authaccount ,@utcnow ,@authaccount ,@utcnow ,NULL ,NULL) OUTPUT inserted.[useraccount_id] INTO @createdID; SELECT TOP(1) * FROM [dbo].[fis_admin_getUserAccountList](@authaccount, @useraccount_id, null, null) ual JOIN @createdID as id on ual.[useraccount_id] = id.[id]; END END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_setUserAccount] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_setUserAccount_activeStatus] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_setUserAccount_activeStatus] @authaccount varchar(5) ,@useraccount_id varchar(5) ,@activestatus bit AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); IF @activestatus = 1 AND EXISTS (SELECT * FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id and [DateDeleted] is null AND [DateDisabled] is NOT NULL) BEGIN UPDATE [dbo].[fis_useraccounts] SET [UserDisabled] = NULL ,[DateDisabled] = NULL ,[UserModified] = @authaccount ,[DateModified] = @utcnow WHERE [useraccount_id] = @useraccount_id; END ELSE IF @activestatus = 0 AND EXISTS (SELECT * FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id and [DateDeleted] is null AND [DateDisabled] is NULL) BEGIN UPDATE [dbo].[fis_useraccounts] SET [UserDisabled] = @authaccount ,[DateDisabled] = @utcnow ,[UserModified] = @authaccount ,[DateModified] = @utcnow WHERE [useraccount_id] = @useraccount_id; END SELECT CAST((CASE WHEN @activestatus = 1 AND EXISTS (SELECT * FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id and [DateDeleted] is null AND [DateDisabled] IS NULL) THEN 1 WHEN @activestatus = 0 AND EXISTS (SELECT * FROM [dbo].[fis_useraccounts] WHERE [useraccount_id] = @useraccount_id and [DateDeleted] is null AND [DateDisabled] IS NOT NULL) THEN 1 ELSE 0 END) as bit); END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_setUserAccount_activeStatus] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_admin_setUserGroup] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_admin_setUserGroup] @authaccount varchar(5) ,@usergroup_id varchar(5) ,@name nvarchar(255) ,@enc_key uniqueidentifier AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); DECLARE @auth smallint = [dbo].[fis_admin_getUserAuth](@authaccount); DECLARE @createdID as TABLE ([id] varchar(5)); IF @auth > 1 BEGIN MERGE [dbo].[fis_usergroups] as TARGET USING (VALUES( ISNULL(@usergroup_id, [dbo].[fis_fn_id] ('fis_usergroups')) ,ENCRYPTBYKEY(@enc_key, @name) )) as SOURCE([usergroup_id],[name_enc]) ON TARGET.[usergroup_id] = SOURCE.[usergroup_id] WHEN MATCHED THEN UPDATE SET TARGET.[name_enc] = SOURCE.[name_enc] ,TARGET.[UserModified] = @authaccount ,TARGET.[DateModified] = @utcnow WHEN NOT MATCHED BY TARGET THEN INSERT ([usergroup_id] ,[name_enc] ,[UserCreated] ,[DateCreated] ,[UserModified] ,[DateModified] ,[UserDeleted] ,[DateDeleted]) VALUES (SOURCE.[usergroup_id] ,SOURCE.[name_enc] ,@authaccount ,@utcnow ,@authaccount ,@utcnow ,NULL ,NULL) OUTPUT inserted.[usergroup_id] INTO @createdID; SELECT TOP(1) * FROM [dbo].[fis_admin_getUserGroupList](@authaccount, @usergroup_id) ual JOIN @createdID as id on ual.[usergroup_id] = id.[id]; END END GO ALTER AUTHORIZATION ON [dbo].[fis_admin_setUserGroup] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_widgets_getCache] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_widgets_getCache] @account varchar(50) ,@short_name varchar(50) ,@login_guid varchar(36) AS BEGIN SET NOCOUNT ON; DECLARE @RET nvarchar(max); DECLARE @IsCacheable bit, @Personalized bit; SELECT @IsCacheable = [daycache], @personalized = [personalized] FROM [dbo].[fis_widgets] WHERE ([account] = @account OR [account] = '*') AND [short_name] = @short_name; IF @IsCacheable = 1 BEGIN DELETE FROM [dbo].[fis_widgets_cache] WHERE [date] <> CAST(GETUTCDATE() as date); SELECT TOP(1) @RET = [data] FROM [dbo].[fis_widgets_cache] WHERE [account] = @account AND [short_name] = @short_name AND [date] = CAST(GETUTCDATE() as date) AND ((@Personalized = 1 AND [person_guid] = @login_guid) OR (@Personalized = 0)); END SELECT @RET; END GO ALTER AUTHORIZATION ON [dbo].[fis_widgets_getCache] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fis_widgets_setCache] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fis_widgets_setCache] @account varchar(50) ,@short_name varchar(50) ,@login_guid varchar(36) ,@data nvarchar(max) AS BEGIN SET NOCOUNT ON; DECLARE @IsCacheable bit, @Personalized bit; SELECT @IsCacheable = [daycache], @personalized = [personalized] FROM [dbo].[fis_widgets] WHERE ([account] = @account OR [account] = '*') AND [short_name] = @short_name; DELETE FROM [dbo].[fis_widgets_cache] WHERE [date] <> CAST(GETUTCDATE() as date) OR ([account] = @account AND [short_name] = @short_name AND @Personalized = 0) OR ([account] = @account AND [short_name] = @short_name AND @Personalized = 1 AND [person_guid] = @login_guid); IF @IsCacheable = 1 BEGIN INSERT INTO [dbo].[fis_widgets_cache] VALUES( @account, @short_name, @login_guid, CAST(GETUTCDATE() as date), @data ); END END GO ALTER AUTHORIZATION ON [dbo].[fis_widgets_setCache] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fuchs_planner_getNext] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fuchs_planner_getNext] @planner tinyint ,@session varchar(10) ,@group_code varchar(10) ,@values varchar(4000) AS BEGIN SET NOCOUNT ON; DECLARE @GROUPS TABLE ( [sessionid] varchar(5) ,[group_id] int ,[code] varchar(10) ,[planner_id] tinyint ,[sequence_order] tinyint ,[parent_codes] varchar(50) ,[condition] varchar(50) ,[shortname] varchar(15) ,[name] varchar(100) ,[description] varchar(max) ,[selection_type] varchar(10) ,[final] bit ,[hide] bit ,[values] varchar(4000) ,[level] tinyint ,[grouporder] tinyint ); DECLARE @TRAFFIC TABLE( [uid] [bigint] NOT NULL, [planner_id] [tinyint] NOT NULL, [sessionid] [varchar](10) NOT NULL, [group_code] [varchar](10) NULL, [values] [nvarchar](4000) NULL, [DateSubmitted] [datetime] NOT NULL, [last] bit ); SET @session = ISNULL(@session, (SELECT TOP(1) [s] FROM [dbo].[ott_20_randomstrings](5) as rs WHERE NOT EXISTS (SELECT * FROM [fuchs_planner_traffic] as t WHERE t.[sessionid] = rs.[s]))); INSERT INTO [dbo].[fuchs_planner_traffic] ([planner_id], [sessionid],[group_code],[values]) VALUES(@planner, @session, @group_code, ISNULL(@values, '')); INSERT INTO @TRAFFIC SELECT *, CAST(CASE WHEN ROW_NUMBER() OVER (PARTITION BY t.[sessionid],t.[group_code] ORDER BY t.[DateSubmitted] DESC) = 1 THEN 1 ELSE 0 END as bit) as 'last' FROM [dbo].[fuchs_planner_traffic] as t WHERE t.[sessionid] = @session and t.[planner_id] = @planner; with plannergroups as (SELECT * FROM [dbo].[fuchs_planner_groups] where [planner_id] = @planner UNION SELECT * FROM (VALUES ( -1 ,'contact' ,@planner ,255 ,'*' ,NULL ,'contact_form' ,'Ihre Kontaktdaten' ,'

Bitte nennen Sie uns Ihre Kontaktdaten, so dass wir Sie kontaktieren können.

' ,'contact' ,1 ,0 ) ) as cf ( [group_id] ,[code] ,[planner_id] ,[sequence_order] ,[parent_codes] ,[condition] ,[shortname] ,[name] ,[description] ,[selection_type] ,[final] ,[hide] ) ) , vals as (SELECT * FROM @TRAFFIC WHERE [last] = 1) , g as (select plannergroups.* , ISNULL(vals.[values],'') as 'values' , ROW_NUMBER() OVER (PARTITION BY plannergroups.[parent_codes] ORDER BY [sequence_order]) AS 'groupfactor' FROM plannergroups left join vals ON plannergroups.[code] = vals.[group_code] where plannergroups.hide = 0) , cte as ( SELECT @session as [session], g.*, Cast([sequence_order] as tinyint) as [level] , CAST(0 as bit) as [exclude] , CAST(CASE WHEN [group_id] = -1 THEN POWER(10,7) ELSE 0 END as int) as 'roworder' /* contact form is always last */ FROM g WHERE g.[sequence_order] = 0 OR g.group_id = -1 UNION ALL SELECT @session as [session], g.*, Cast(cte.[level] + 1 as tinyint) as [level] , CAST(CASE WHEN cte.[exclude] = 1 THEN 1 WHEN ISNULL(g.[condition], '') in ('', '{}') THEN 0 WHEN EXISTS (SELECT * FROM g as gv JOIN [dbo].[fuchs_planner_options] as o ON gv.[group_id] = o.[group_id] and o.[option_type] in ('a','c','o') AND [dbo].[ott_jcsv_contains](gv.code, gv.[values], o.[code]) = 1 WHERE [dbo].[ott_csv_contains](g.[condition], o.[code]) = 1 ) THEN 0 ELSE 1 END as bit) as [exclude] , cte.[roworder] + Cast(g.[groupfactor] as int) * CAST(POWER(10,4-cte.[level]) as int) as 'roworder' /* by this, the children have a lower number than the following on same level */ FROM g JOIN cte on g.[sequence_order] > cte.[sequence_order] AND cte.group_id >= 0 AND g.group_id >= 0 --not the contact form AND [dbo].[ott_csv_contains](g.[parent_codes], cte.[code]) = 1 AND cte.[final] = 0 --AND cte.[exclude] = 0 ) , f as ( select cte.* , ROW_NUMBER() OVER (ORDER BY [roworder], [sequence_order]) as 'grouporder' FROM cte where exclude = 0 ) , this as (SELECT TOP(1) * FROM f WHERE [code] = @group_code) insert into @GROUPS select TOP(1) f.[session] ,f.[group_id] ,f.[code] ,f.[planner_id] ,f.[sequence_order] ,f.[parent_codes] ,f.[condition] ,f.[shortname] ,f.[name] ,f.[description] ,f.[selection_type] ,f.[final] ,f.[hide] ,f.[values] ,f.[level] ,f.[grouporder] FROM f left join this on f.[grouporder] > this.[grouporder] WHERE NOT EXISTS (SELECT * FROM this) OR (f.grouporder > this.grouporder AND ISNULL(this.final,0) = 0) ORDER BY f.[grouporder] ASC; -- output SELECT * FROM @GROUPS; -- output SELECT o.* FROM [dbo].[fuchs_planner_options] as o JOIN @GROUPS as g on o.[planner_id] = g.[planner_id] AND o.[group_id] = g.[group_id] WHERE ( ISNULL(o.[condition], '') IN ('', '{}') OR EXISTS (SELECT * FROM @GROUPS as gv WHERE [dbo].[ott_csv_contains](o.[condition], gv.[values]) = 1 ) OR (LEFT(o.condition, 1) = '$' AND EXISTS (SELECT * FROM @TRAFFIC as tf JOIN (select * from string_SplitString_ordered(o.condition, ':') PIVOT (MAX([string]) FOR [RowNo] IN([1],[2])) pvt) as oc ON IIF(tf.[values] <> '', JSON_VALUE(tf.[values], oc.[1]), '') = oc.[2] )) ) END GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner_getNext] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fuchs_planner_getPrev] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fuchs_planner_getPrev] @planner tinyint ,@session varchar(10) ,@group_code varchar(10) ,@values varchar(4000) AS BEGIN SET NOCOUNT ON; DECLARE @GROUPS TABLE ( [sessionid] varchar(5) ,[group_id] int ,[code] varchar(10) ,[planner_id] tinyint ,[sequence_order] tinyint ,[parent_codes] varchar(50) ,[condition] varchar(50) ,[shortname] varchar(15) ,[name] varchar(100) ,[description] varchar(max) ,[selection_type] varchar(10) ,[final] bit ,[hide] bit ,[values] varchar(4000) ,[level] tinyint ,[grouporder] tinyint ); DECLARE @TRAFFIC TABLE( [uid] [bigint] NOT NULL, [planner_id] [tinyint] NOT NULL, [sessionid] [varchar](10) NOT NULL, [group_code] [varchar](10) NULL, [values] [nvarchar](4000) NULL, [DateSubmitted] [datetime] NOT NULL, [last] bit ); SET @session = ISNULL(@session, (SELECT TOP(1) [s] FROM [dbo].[ott_20_randomstrings](5) as rs WHERE NOT EXISTS (SELECT * FROM [fuchs_planner_traffic] as t WHERE t.[sessionid] = rs.[s]))); INSERT INTO [dbo].[fuchs_planner_traffic] ([planner_id], [sessionid],[group_code],[values]) VALUES(@planner, @session, @group_code, ISNULL(@values, '')); INSERT INTO @TRAFFIC SELECT *, CAST(CASE WHEN ROW_NUMBER() OVER (PARTITION BY t.[sessionid],t.[group_code] ORDER BY t.[DateSubmitted] DESC) = 1 THEN 1 ELSE 0 END as bit) as 'last' FROM [dbo].[fuchs_planner_traffic] as t WHERE t.[sessionid] = @session and t.[planner_id] = @planner; with plannergroups as (SELECT * FROM [dbo].[fuchs_planner_groups] where [planner_id] = @planner UNION SELECT * FROM (VALUES ( -1 ,'contact' ,@planner ,255 ,'*' ,NULL ,'contact_form' ,'Ihre Kontaktdaten' ,'

Bitte nennen Sie uns Ihre Kontaktdaten, so dass wir Sie kontaktieren können.

' ,'contact' ,1 ,0 ) ) as cf ( [group_id] ,[code] ,[planner_id] ,[sequence_order] ,[parent_codes] ,[condition] ,[shortname] ,[name] ,[description] ,[selection_type] ,[final] ,[hide] ) ) , vals as (SELECT * FROM @TRAFFIC WHERE [last] = 1) , g as (select plannergroups.* , ISNULL(vals.[values],'') as 'values' , ROW_NUMBER() OVER (PARTITION BY plannergroups.[parent_codes] ORDER BY [sequence_order]) AS 'groupfactor' FROM plannergroups left join vals ON plannergroups.[code] = vals.[group_code] where plannergroups.hide = 0) , cte as ( SELECT @session as [session], g.*, Cast([sequence_order] as tinyint) as [level] , CAST(0 as bit) as [exclude] , CAST(CASE WHEN [group_id] = -1 THEN POWER(10,7) ELSE 0 END as int) as 'roworder' /* contact form is always last */ FROM g WHERE g.[sequence_order] = 0 OR g.group_id = -1 UNION ALL SELECT @session as [session], g.*, Cast(cte.[level] + 1 as tinyint) as [level] , CAST(CASE WHEN cte.[exclude] = 1 THEN 1 WHEN ISNULL(g.[condition], '') in ('', '{}') THEN 0 WHEN EXISTS (SELECT * FROM g as gv JOIN [dbo].[fuchs_planner_options] as o ON gv.[group_id] = o.[group_id] and o.[option_type] in ('a','c','o') AND [dbo].[ott_jcsv_contains](gv.code, gv.[values], o.[code]) = 1 WHERE [dbo].[ott_csv_contains](g.[condition], o.[code]) = 1 ) THEN 0 ELSE 1 END as bit) as [exclude] , cte.[roworder] + Cast(g.[groupfactor] as int) * CAST(POWER(10,4-cte.[level]) as int) as 'roworder' /* by this, the children have a lower number than the following on same level */ FROM g JOIN cte on g.[sequence_order] > cte.[sequence_order] AND cte.group_id >= 0 AND g.group_id >= 0 --not the contact form AND [dbo].[ott_csv_contains](g.[parent_codes], cte.[code]) = 1 AND cte.[final] = 0 --AND cte.[exclude] = 0 ) , f as ( select cte.* , ROW_NUMBER() OVER (ORDER BY [roworder], [sequence_order]) as 'grouporder' FROM cte where exclude = 0 ) , this as (SELECT TOP(1) * FROM f WHERE [code] = @group_code) insert into @GROUPS select TOP(1) f.[session] ,f.[group_id] ,f.[code] ,f.[planner_id] ,f.[sequence_order] ,f.[parent_codes] ,f.[condition] ,f.[shortname] ,f.[name] ,f.[description] ,f.[selection_type] ,f.[final] ,f.[hide] ,f.[values] ,f.[level] ,f.[grouporder] FROM f left join this on f.[grouporder] < this.[grouporder] --lower than WHERE NOT EXISTS (SELECT * FROM this) OR f.grouporder < this.grouporder OR f.grouporder = 0 /* =0 to at least have the first page returned */ ORDER BY f.[grouporder] DESC; -- DESCending is important -- output SELECT * FROM @GROUPS; -- output SELECT o.* FROM [dbo].[fuchs_planner_options] as o JOIN @GROUPS as g on o.[planner_id] = g.[planner_id] AND o.[group_id] = g.[group_id] WHERE ( ISNULL(o.[condition], '') = '' OR EXISTS (SELECT * FROM @GROUPS as gv WHERE [dbo].[ott_csv_contains](o.[condition], gv.[values]) = 1 ) OR (LEFT(o.condition, 1) = '$' AND EXISTS (SELECT * FROM @TRAFFIC as tf JOIN (select * from string_SplitString_ordered(o.condition, ':') PIVOT (MAX([string]) FOR [RowNo] IN([1],[2])) pvt) as oc ON IIF(tf.[values] <> '', JSON_VALUE(tf.[values], oc.[1]), '') = oc.[2] )) ); END GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner_getPrev] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fuchs_planner_getSummary] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fuchs_planner_getSummary] @planner tinyint ,@session varchar(10) AS BEGIN SET NOCOUNT ON; DECLARE @GROUPS TABLE ( [sessionid] varchar(5) ,[group_id] int ,[code] varchar(10) ,[planner_id] tinyint ,[sequence_order] tinyint ,[parent_codes] varchar(50) ,[condition] varchar(50) ,[shortname] varchar(15) ,[name] varchar(100) ,[description] varchar(max) ,[selection_type] varchar(10) ,[final] bit ,[hide] bit ,[values] varchar(4000) ,[level] tinyint ,[grouporder] tinyint ); IF ISNULL(@session, '') <> '' BEGIN with traffic as (SELECT *, CAST(CASE WHEN ROW_NUMBER() OVER (PARTITION BY t.[sessionid],t.[group_code] ORDER BY t.[DateSubmitted] DESC) = 1 THEN 1 ELSE 0 END as bit) as 'last' FROM [dbo].[fuchs_planner_traffic] as t WHERE t.[sessionid] = @session and t.[planner_id] = @planner) , plannergroups as (SELECT * FROM [dbo].[fuchs_planner_groups] where [planner_id] = @planner UNION SELECT * FROM (VALUES ( -1 ,'contact' ,@planner ,255 ,'*' ,NULL ,'contact_form' ,'Ihre Kontaktdaten' ,'

Bitte nennen Sie uns Ihre Kontaktdaten, so dass wir Sie kontaktieren können.

' ,'contact' ,1 ,0 ) ) as cf ( [group_id] ,[code] ,[planner_id] ,[sequence_order] ,[parent_codes] ,[condition] ,[shortname] ,[name] ,[description] ,[selection_type] ,[final] ,[hide] ) ) , vals as (SELECT * FROM traffic WHERE [last] = 1) , g as (select plannergroups.* , ISNULL(vals.[values],'') as 'values' , ROW_NUMBER() OVER (PARTITION BY plannergroups.[parent_codes] ORDER BY [sequence_order]) AS 'groupfactor' FROM plannergroups left join vals ON plannergroups.[code] = vals.[group_code] where plannergroups.hide = 0) , cte as ( SELECT @session as [session], g.*, Cast([sequence_order] as tinyint) as [level] , CAST(0 as bit) as [exclude] , CAST(CASE WHEN [group_id] = -1 THEN POWER(10,7) ELSE 0 END as int) as 'roworder' /* contact form is always last */ FROM g WHERE g.[sequence_order] = 0 OR g.group_id = -1 UNION ALL SELECT @session as [session], g.*, Cast(cte.[level] + 1 as tinyint) as [level] , CAST(CASE WHEN cte.[exclude] = 1 THEN 1 WHEN ISNULL(g.[condition], '') in ('', '{}') THEN 0 WHEN EXISTS (SELECT * FROM g as gv JOIN [dbo].[fuchs_planner_options] as o ON gv.[group_id] = o.[group_id] and o.[option_type] in ('a','c','o') AND [dbo].[ott_jcsv_contains](gv.code, gv.[values], o.[code]) = 1 WHERE [dbo].[ott_csv_contains](g.[condition], o.[code]) = 1 ) THEN 0 ELSE 1 END as bit) as [exclude] , cte.[roworder] + Cast(g.[groupfactor] as int) * CAST(POWER(10,4-cte.[level]) as int) as 'roworder' /* by this, the children have a lower number than the following on same level */ FROM g JOIN cte on g.[sequence_order] > cte.[sequence_order] AND cte.group_id >= 0 AND g.group_id >= 0 --not the contact form AND [dbo].[ott_csv_contains](g.[parent_codes], cte.[code]) = 1 AND cte.[final] = 0 --AND cte.[exclude] = 0 ) , f as ( select cte.* , ROW_NUMBER() OVER (ORDER BY [roworder], [sequence_order]) as 'grouporder' FROM cte where exclude = 0 ) insert into @GROUPS select f.[session] ,f.[group_id] ,f.[code] ,f.[planner_id] ,f.[sequence_order] ,f.[parent_codes] ,f.[condition] ,f.[shortname] ,f.[name] ,f.[description] ,f.[selection_type] ,f.[final] ,f.[hide] ,f.[values] ,f.[level] ,f.[grouporder] FROM f ORDER BY f.[grouporder] ASC; -- output SELECT g.[group_id] ,g.[shortname] ,g.[code] ,g.[name] --,[dbo].[ott_jcontent](g.[code],g.[values]) as 'values' , g.[values] ,g.[grouporder] ,g.[selection_type] FROM @GROUPS as g; -- output SELECT o.* ,ISNULL([dbo].[ott_jcontent](o.[code],g.[values]), '') FROM [dbo].[fuchs_planner_options] as o JOIN @GROUPS as g on o.[planner_id] = g.[planner_id] AND o.[group_id] = g.[group_id] AND (ISNULL(o.[condition], '') = '' OR EXISTS (SELECT * FROM @GROUPS as gv WHERE [dbo].[ott_csv_contains](o.[condition], gv.[values]) = 1 ) ) WHERE (CASE WHEN [dbo].[ott_jcsv_contains](g.[code],g.[values],o.[code]) = 1 THEN 1 WHEN [dbo].[ott_jcsv_containskey](o.[code], g.[values]) =1 THEN 1 ELSE 0 END) = 1 or 1= 1 --OR ISNULL([dbo].[ott_jcontent](o.[code],g.[values]), '') <> '' END END GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner_getSummary] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[fuchs_planner_submit] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[fuchs_planner_submit] @planner tinyint ,@session varchar(10) ,@group_code varchar(10) ,@values varchar(4000) AS BEGIN SET NOCOUNT ON; SET @session = ISNULL(@session, (SELECT TOP(1) [s] FROM [dbo].[ott_20_randomstrings](5) as rs WHERE NOT EXISTS (SELECT * FROM [fuchs_planner_traffic] as t WHERE t.[sessionid] = rs.[s]))); INSERT INTO [dbo].[fuchs_planner_traffic] ([planner_id], [sessionid],[group_code],[values]) VALUES(@planner, @session, @group_code, ISNULL(@values, '')); END GO ALTER AUTHORIZATION ON [dbo].[fuchs_planner_submit] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__getSchema] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__getSchema] @info varchar(25) ,@tgttype varchar(50) AS BEGIN SET NOCOUNT ON; DECLARe @AS XML = [dbo].[mfr__schema](); IF @info = 'table' BEGIN DECLARE @AssociationSets TABLE([#] int, [name] varchar(255), [set] varchar(255), [Association] varchar(255), [role1] varchar(255), [role2] varchar(255), [set1] varchar(255), [set2] varchar(255), [arole1] varchar(255), [arole2] varchar(255), [multi1] varchar(255), [multi2] varchar(255), [tablename] varchar(255)); DECLARE @ComplexProps TABLE([#] int, [Type] varchar(255), [typ] varchar(50), [name] varchar(255), [EntityType] varchar(255), [tablename] varchar(255)); DECLARE @NavigationProps TABLE([#] int, [Type] varchar(255), [typ] varchar(50), [name] varchar(255), [ToRole] varchar(255), [FromRole] varchar(255), [countertype] varchar(255), [counterset] varchar(255), [tablename] varchar(255), [countertable] varchar(255), [Association] varchar(255)); DECLARE @EntityTypes TABLE([#] int, [typ] varchar(50), [name] varchar(255), [set] varchar(255), [EntitySet] varchar(255), [tablename] varchar(255), [url] varchar(500), [DateColumn] varchar(25), [DateSQL] varchar(1000)); WITH XMLNAMESPACES ( 'http://schemas.microsoft.com/ado/2007/06/edmx' as edmx, 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' as m ) , x as ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('@Name', 'varchar(255)') as 'set' , xD.value('@Association', 'varchar(255)') as 'association' , xD.value('End[1]/@Role', 'varchar(255)') as 'role1' , xD.value('End[2]/@Role', 'varchar(255)') as 'role2' , LOWER(xD.value('End[1]/@EntitySet', 'varchar(255)')) as 'set1' , LOWER(xD.value('End[2]/@EntitySet', 'varchar(255)')) as 'set2' --, xD.query('.') as 'q' from @as.nodes('/Schema/EntityContainer/AssociationSet') as xm(xD) ) , y as ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('@Name', 'varchar(255)') as 'association' , xD.value('End[1]/@Role', 'varchar(255)') as 'arole1' , xD.value('End[2]/@Role', 'varchar(255)') as 'arole2' , xD.value('End[1]/@Multiplicity', 'varchar(255)') as 'multi1' , xD.value('End[2]/@Multiplicity', 'varchar(255)') as 'multi2' --, xD.query('.') as 'q' from @as.nodes('/Schema/Association') as xm(xD) ), z as ( select x.[#], x.[role1], x.[role2], x.[set1], x.[set2], RIGHT(x.[set],CHARINDEX('_', REVERSE(x.[set])) - 1) as [name],x.[set],x.[association], y.[arole1], y.[arole2], y.[multi1], y.[multi2] from x LEFT JOIN y on x.association like ('%[.]' + y.[association]) ) INSERT INTO @AssociationSets SELECT [#], z.[name],[set], [association],[role1],[role2], [set1], [set2] , [arole1], [arole2], [multi1], [multi2], 'mfr__*PartnerSet' as [tablename] FROM z LEFT JOIN sys.objects as o ON o.[name] like ('mfr__[*]' + (LOWER(z.[name]))); WITH XMLNAMESPACES ( 'http://schemas.microsoft.com/ado/2007/06/edmx' as edmx, 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' as m ), et as ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('local-name(.)', 'varchar(50)') as [type] , xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' , xS.value('@Name', 'varchar(255)') as [Set] , o.[name] as [tablename] from @as.nodes('/Schema[1]/EntityType') as xm(xD) JOIN @as.nodes('/Schema/EntityContainer/EntitySet') as xn(xS) ON (xS.value('@EntityType', 'varchar(255)')) like ('MFR.%[.]' + (xD.value('@Name', 'varchar(255)'))) JOIN sys.objects as o ON o.[name] like ('mfr__' + (LOWER(xS.value('@Name', 'varchar(255)')))) union SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('local-name(.)', 'varchar(50)') as [type] , xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' , '' as [Set] , o.[name] as [tablename] from @as.nodes('/Schema[1]/ComplexType') as xm(xD) JOIN sys.objects as o ON o.[name] like ('mfr__[#]' + (LOWER(xD.value('@Name', 'varchar(255)'))) + 's') ) INSERT INTO @EntityTypes SELECT [#],[type],[EntityType],[set] = LOWER([set]), [EntitySet] = [set], [tablename], null, null, null FROM et; WITH XMLNAMESPACES ( 'http://schemas.microsoft.com/ado/2007/06/edmx' as edmx, 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' as m ), np as ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('../@Name', 'varchar(255)') as [property] , xD.value('@Type', 'varchar(255)') as [nodetype] , xD.value('@Name', 'varchar(255)') as [name] from @as.nodes('/Schema[1]/EntityType/Property') as xm(xD) ) INSERT INTO @ComplexProps SELECT np.[#] , [property] , [type] = CASE WHEN [nodetype] like 'collection%' THEN 'array' ELSE '' END , np.[name] , [EntityType] = et.[name] , et.[tablename] from np LEFT JOIN @EntityTypes as et on np.[name] like (et.[name] + '%') WHERE nodetype like '%MFR[.]%'; WITH XMLNAMESPACES ( 'http://schemas.microsoft.com/ado/2007/06/edmx' as edmx, 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' as m ), np as ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#' , xD.value('../@Name', 'varchar(255)') as [property] , CASE WHEN a.[arole1] = xD.value('@ToRole', 'varchar(255)') AND a.[multi1] = '*' THEN 'array' WHEN a.[arole1] = xD.value('@ToRole', 'varchar(255)') AND a.[multi1] = '0..1' THEN 'ref' WHEN a.[arole2] = xD.value('@ToRole', 'varchar(255)') AND a.[multi2] = '*' THEN 'array' WHEN a.[arole2] = xD.value('@ToRole', 'varchar(255)') AND a.[multi2] = '0..1' THEN 'ref' END as [typ] , xD.value('@Name', 'varchar(255)') as [name] , xD.value('@ToRole', 'varchar(255)') as [ToRole] , xD.value('@FromRole', 'varchar(255)') as [FromRole] , CASE WHEN xD.value('@ToRole', 'varchar(255)') = a.[role2] THEN [set2] ELSE [set1] END [counterset] , a.[tablename] --xD.value('@Relationship', 'varchar(255)') as , a.[Association] -- , xD.query('.') as 'q' from @as.nodes('/Schema[1]/EntityType/NavigationProperty') as xm(xD) LEFT JOIN @AssociationSets as a on (xD.value('@Relationship', 'varchar(255)')) like a.[Association] ) INSERT INTO @NavigationProps SELECT np.[#], [property], np.[typ],np.[name],[ToRole], [FromRole],[countertype] = et.[name], [counterset],np.[tablename], [countertable] = et.tablename, [Association] = NULL from np LEFT JOIN @EntityTypes as et on np.counterset = et.[set]; UPDATE et SET [url] = [EntitySet] + CASE WHEN EXISTS (SELECT * FROM @NavigationProps as np WHERE np.[type] = et.[name]) THEN '?$expand=' + STUFF((SELECT ',' + [name] as [text()] FROM @NavigationProps as np WHERE np.[type] = et.[name] ORDER BY [#] FOR XML PATH('')),1,1, '') ELSE '' END ,[DateColumn] = (SELECT TOP(1) cols.[COLUMN_NAME] FROM INFORMATION_SCHEMA.COLUMNS as cols WHERE cols.[TABLE_NAME] = et.[tablename] AND ([COLUMN_NAME] COLLATE Latin1_General_CI_AS IN ('DateModified','DateCreated','DateOfCreation')) ORDER BY cols.[COLUMN_NAME] DESC) ,[DateSQL] = IIF((SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS as cols WHERE cols.[TABLE_NAME] = et.[tablename] AND ([COLUMN_NAME] COLLATE Latin1_General_CI_AS IN ('DateModified','DateOfCreation'))) = 2, 'SELECT [dbo].[ott_min_date](MAX([DateModified]),MAX([DateOfCreation])) FROM [dbo].[' + et.[tablename] + '];','') FROM @EntityTypes as et; SELECT * FROM @EntityTypes as et WHERE @tgttype is null or et.name = @tgttype; SELECT * FROM @ComplexProps as cp where @tgttype is null or cp.[type] = @tgttype; SELECT n.* FROM @NavigationProps as n WHERE @tgttype is null or n.[type] = @tgttype; --SELECT * FROM @AssociationSets; with tt as ( --SELECT [tablename] FROM @EntityTypes --UNION SELECT [tablename] FROM @ComplexProps as cp where @tgttype is null or cp.[type] = @tgttype UNION SELECT [tablename] FROM @NavigationProps as n WHERE @tgttype is null or n.[type] = @tgttype UNION SELECT [tablename] = [countertable] FROM @NavigationProps as n WHERE @tgttype is null or n.[type] = @tgttype ) SELECT DISTINCT [tablename] from tt where not exists(SELECT * FROM @EntityTypes as et where et.tablename = tt.[tablename] AND (@tgttype is null or et.name = @tgttype)); END ELSE IF @info = 'tabledef' BEGIN DECLARE @types TABLE ([edm] varchar(100), [sql] varchar(50)); INSERT INTO @types VALUES ('Edm.Boolean', 'bit'), ('Edm.DateTime', 'DateTime'), ('Edm.Decimal', 'decimal'), ('Edm.Double', 'float'), ('Edm.Int32', 'int'), ('Edm.Int64', 'bigint'), ('Edm.String', 'varchar(255)'); END END GO ALTER AUTHORIZATION ON [dbo].[mfr__getSchema] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__#customvalues] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__#customvalues] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__#customvalues]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM [' + @tblname + ']'; INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; --WITH tmp as ( -- SELECT *, ROW_NUMBER() OVER (PARTITION BY [id],[Property] ORDER BY [version] DESC) as '#' FROM @tmp --), SOURCE as ( -- SELECT * FROM tmp WHERE [#] = 1 --) MERGE [dbo].[mfr__#customvalues] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] AND TARGET.[EntityID] = SOURCE.[EntityID] AND TARGET.[Property] = SOURCE.[Property] AND TARGET.[Meta] = SOURCE.[Meta] WHEN MATCHED THEN UPDATE SET [Value] = SOURCE.[Value] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[EntityID] ,[Property] ,[Meta] ,[Value]) VALUES (SOURCE.[Id] ,SOURCE.[EntityID] ,SOURCE.[Property] ,SOURCE.[Meta] ,SOURCE.[Value]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__#customvalues] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__#locations] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__#locations] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__#locations]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM [' + @tblname + ']'; INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; WITH tmp as ( SELECT *, ROW_NUMBER() OVER (PARTITION BY [id],[Property] ORDER BY [version] DESC) as '#' FROM @tmp ), SOURCE as ( SELECT * FROM tmp WHERE [#] = 1 ) MERGE [dbo].[mfr__#locations] as TARGET USING SOURCE ON TARGET.[Id] = SOURCE.[Id] AND TARGET.[Property] = SOURCE.[Property] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[EntityId] = SOURCE.[EntityId] ,[Property] = SOURCE.[Property] ,[Version] = SOURCE.[Version] ,[AddressString] = SOURCE.[AddressString] ,[Postal] = SOURCE.[Postal] ,[City] = SOURCE.[City] ,[State] = SOURCE.[State] ,[Country] = SOURCE.[Country] ,[Longitude] = SOURCE.[Longitude] ,[Latitude] = SOURCE.[Latitude] ,[IsValidLocation] = SOURCE.[IsValidLocation] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[EntityId] ,[Property] ,[Version] ,[AddressString] ,[Postal] ,[City] ,[State] ,[Country] ,[Longitude] ,[Latitude] ,[IsValidLocation]) VALUES (SOURCE.[Id] ,SOURCE.[EntityId] ,SOURCE.[Property] ,SOURCE.[Version] ,SOURCE.[AddressString] ,SOURCE.[Postal] ,SOURCE.[City] ,SOURCE.[State] ,SOURCE.[Country] ,SOURCE.[Longitude] ,SOURCE.[Latitude] ,SOURCE.[IsValidLocation]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__#locations] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__*PartnerSet] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__*PartnerSet] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__*PartnerSet]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM [' + @tblname + ']'; INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__*PartnerSet] as TARGET USING @tmp as SOURCE ON TARGET.[Property] = SOURCE.[Property] AND TARGET.[PartnerType] = SOURCE.[PartnerType] AND TARGET.[PartnerId] = SOURCE.[PartnerId] AND TARGET.[EntityId] = SOURCE.[EntityId] WHEN MATCHED THEN UPDATE SET [Property] = SOURCE.[Property] ,[PartnerType] = SOURCE.[PartnerType] ,[PartnerId] = SOURCE.[PartnerId] ,[EntityId] = SOURCE.[EntityId] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Property] ,[PartnerType] ,[PartnerId] ,[EntityId]) VALUES (SOURCE.[Property] ,SOURCE.[PartnerType] ,SOURCE.[PartnerId] ,SOURCE.[EntityId]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__*PartnerSet] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__appointments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__appointments] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__appointments]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__appointments] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] ) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[State] = SOURCE.[State] ,[Type] = SOURCE.[Type] ,[EndDateTime] = SOURCE.[EndDateTime] ,[StartDateTime] = SOURCE.[StartDateTime] ,[DrivingDistanceFrom] = SOURCE.[DrivingDistanceFrom] ,[DrivingDistanceTo] = SOURCE.[DrivingDistanceTo] ,[WasReadOnClientSide] = SOURCE.[WasReadOnClientSide] ,[ContactIds] = SOURCE.[ContactIds] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[ContactId] = SOURCE.[ContactId] ,[Note] = SOURCE.[Note] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[State] ,[Type] ,[EndDateTime] ,[StartDateTime] ,[DrivingDistanceFrom] ,[DrivingDistanceTo] ,[WasReadOnClientSide] ,[ContactIds] ,[ServiceRequestId] ,[ContactId] ,[Note]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[State] ,SOURCE.[Type] ,SOURCE.[EndDateTime] ,SOURCE.[StartDateTime] ,SOURCE.[DrivingDistanceFrom] ,SOURCE.[DrivingDistanceTo] ,SOURCE.[WasReadOnClientSide] ,SOURCE.[ContactIds] ,SOURCE.[ServiceRequestId] ,SOURCE.[ContactId] ,SOURCE.[Note]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__appointments] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__attachments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__attachments] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__attachments]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__attachments] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[URI] = SOURCE.[URI] ,[StepId] = SOURCE.[StepId] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[URI] ,[StepId]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[URI] ,SOURCE.[StepId]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__attachments] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__comments] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__comments] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__comments]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__comments] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateOfCreation] <= SOURCE.[DateOfCreation]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[DateOfCreation] = SOURCE.[DateOfCreation] ,[IsInternal] = SOURCE.[IsInternal] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[CompanyId] = SOURCE.[CompanyId] ,[Content] = SOURCE.[Content] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[DateOfCreation] ,[IsInternal] ,[ServiceRequestId] ,[CompanyId] ,[Content]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[DateOfCreation] ,SOURCE.[IsInternal] ,SOURCE.[ServiceRequestId] ,SOURCE.[CompanyId] ,SOURCE.[Content]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__comments] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__companies] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__companies] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); DECLARE @tmp [dbo].[mfr__tt__companies]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; IF @referencetable = 'mfr__companies' BEGIN DELETE p OUTput deleted.*, @now INTO [dbo].[mfr__d_*PartnerSet] FROM [dbo].[mfr__*PartnerSet] as p WHERE p.Property like 'Company[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = p.[EntityId]); DELETE cv OUTput deleted.*, @now INTO [dbo].[mfr__d_#customvalues] FROM [dbo].[mfr__#customvalues] as cv WHERE cv.Property like 'Company[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = cv.[EntityId]); DELETE lc OUTPUT deleted.*, @now INTO [dbo].[mfr__d_#locations] FROM [dbo].[mfr__#locations] as lc WHERE lc.Property like 'Company[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = lc.[EntityId]); DELETE cm OUTPUT deleted.*, @now INTO [dbo].[mfr__d_comments] FROM [dbo].[mfr__comments] as cm WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = cm.[CompanyId] AND ISNULL(cm.[ServiceRequestId],0) = 0); END MERGE [dbo].[mfr__companies] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Location#ID] = SOURCE.[Location#ID] ,[Version] = SOURCE.[Version] ,[IsPhysicalPerson] = SOURCE.[IsPhysicalPerson] ,[IsOwner] = SOURCE.[IsOwner] ,[IsEmailInvoicingActive] = SOURCE.[IsEmailInvoicingActive] ,[IsSupplier] = SOURCE.[IsSupplier] ,[MappingId] = SOURCE.[MappingId] ,[ExternalId] = SOURCE.[ExternalId] ,[Name] = SOURCE.[Name] ,[Note] = SOURCE.[Note] ,[SupportTelephone] = SOURCE.[SupportTelephone] ,[SupportFax] = SOURCE.[SupportFax] ,[SupportMail] = SOURCE.[SupportMail] ,[QuickSearch] = SOURCE.[QuickSearch] ,[DateModified] = SOURCE.[DateModified] ,[CustomValues] = SOURCE.[CustomValues] ,[MainContactId] = SOURCE.[MainContactId] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[Location#ID] ,[Version] ,[IsPhysicalPerson] ,[IsOwner] ,[IsEmailInvoicingActive] ,[IsSupplier] ,[MappingId] ,[ExternalId] ,[Name] ,[Note] ,[SupportTelephone] ,[SupportFax] ,[SupportMail] ,[QuickSearch] ,[DateModified] ,[CustomValues] ,[MainContactId]) VALUES (SOURCE.[Id] ,SOURCE.[Location#ID] ,SOURCE.[Version] ,SOURCE.[IsPhysicalPerson] ,SOURCE.[IsOwner] ,SOURCE.[IsEmailInvoicingActive] ,SOURCE.[IsSupplier] ,SOURCE.[MappingId] ,SOURCE.[ExternalId] ,SOURCE.[Name] ,SOURCE.[Note] ,SOURCE.[SupportTelephone] ,SOURCE.[SupportFax] ,SOURCE.[SupportMail] ,SOURCE.[QuickSearch] ,SOURCE.[DateModified] ,SOURCE.[CustomValues] ,SOURCE.[MainContactId]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__companies] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__contacts] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__contacts] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__contacts]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__contacts] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[CustomValues] = SOURCE.[CustomValues] ,[FirstName] = SOURCE.[FirstName] ,[LastName] = SOURCE.[LastName] ,[Email] = SOURCE.[Email] ,[JobTitle] = SOURCE.[JobTitle] ,[MobilePhone] = SOURCE.[MobilePhone] ,[Telephone] = SOURCE.[Telephone] ,[Fax] = SOURCE.[Fax] ,[Note] = SOURCE.[Note] ,[DateModified] = SOURCE.[DateModified] ,[Version] = SOURCE.[Version] ,[CompanyId] = SOURCE.[CompanyId] ,[IsUser] = SOURCE.[IsUser] ,[ExternalId] = SOURCE.[ExternalId] ,[Gender] = SOURCE.[Gender] ,[UserId] = SOURCE.[UserId] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[CustomValues] ,[FirstName] ,[LastName] ,[Email] ,[JobTitle] ,[MobilePhone] ,[Telephone] ,[Fax] ,[Note] ,[DateModified] ,[Version] ,[CompanyId] ,[IsUser] ,[ExternalId] ,[Gender] ,[UserId]) VALUES (SOURCE.[Id] ,SOURCE.[CustomValues] ,SOURCE.[FirstName] ,SOURCE.[LastName] ,SOURCE.[Email] ,SOURCE.[JobTitle] ,SOURCE.[MobilePhone] ,SOURCE.[Telephone] ,SOURCE.[Fax] ,SOURCE.[Note] ,SOURCE.[DateModified] ,SOURCE.[Version] ,SOURCE.[CompanyId] ,SOURCE.[IsUser] ,SOURCE.[ExternalId] ,SOURCE.[Gender] ,SOURCE.[UserId]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__contacts] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__costcenters] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__costcenters] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__costcenters]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__costcenters] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[Name]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Name]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__costcenters] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__documents] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__documents] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__documents]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__documents] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified] ) THEN UPDATE SET [Id] = SOURCE.[Id] ,[CustomValues] = SOURCE.[CustomValues] ,[Version] = SOURCE.[Version] ,[State] = SOURCE.[State] ,[ExternalId] = SOURCE.[ExternalId] ,[URI] = SOURCE.[URI] ,[IsGlobal] = SOURCE.[IsGlobal] ,[StartDateTime] = SOURCE.[StartDateTime] ,[EndDateTime] = SOURCE.[EndDateTime] ,[FileName] = SOURCE.[FileName] ,[DateModified] = SOURCE.[DateModified] ,[UploadDate] = SOURCE.[UploadDate] ,[IsLink] = SOURCE.[IsLink] ,[ContentType] = SOURCE.[ContentType] ,[HTMLCode] = SOURCE.[HTMLCode] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[Note] = SOURCE.[Note] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[CustomValues] ,[Version] ,[State] ,[ExternalId] ,[URI] ,[IsGlobal] ,[StartDateTime] ,[EndDateTime] ,[FileName] ,[DateModified] ,[UploadDate] ,[IsLink] ,[ContentType] ,[HTMLCode] ,[ServiceRequestId] ,[Note]) VALUES (SOURCE.[Id] ,SOURCE.[CustomValues] ,SOURCE.[Version] ,SOURCE.[State] ,SOURCE.[ExternalId] ,SOURCE.[URI] ,SOURCE.[IsGlobal] ,SOURCE.[StartDateTime] ,SOURCE.[EndDateTime] ,SOURCE.[FileName] ,SOURCE.[DateModified] ,SOURCE.[UploadDate] ,SOURCE.[IsLink] ,SOURCE.[ContentType] ,SOURCE.[HTMLCode] ,SOURCE.[ServiceRequestId] ,SOURCE.[Note]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__documents] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__invoices] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__invoices] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__invoices]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__invoices] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateOfCreation] <= SOURCE.[DateOfCreation] ) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[DateOfCreation] = SOURCE.[DateOfCreation] ,[URI] = SOURCE.[URI] ,[DocumentName] = SOURCE.[DocumentName] ,[ReportDefinitionCode] = SOURCE.[ReportDefinitionCode] ,[FileType] = SOURCE.[FileType] ,[InvoiceBalance] = SOURCE.[InvoiceBalance] ,[InvoiceBalanceNetto] = SOURCE.[InvoiceBalanceNetto] ,[WageBalanceNet] = SOURCE.[WageBalanceNet] ,[DatePayed] = SOURCE.[DatePayed] ,[InvoiceId] = SOURCE.[InvoiceId] ,[DueDate] = SOURCE.[DueDate] ,[WithoutVAT] = SOURCE.[WithoutVAT] ,[Skonto] = SOURCE.[Skonto] ,[PartialPayment] = SOURCE.[PartialPayment] ,[InvoiceState] = SOURCE.[InvoiceState] ,[Note] = SOURCE.[Note] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[DateOfCreation] ,[URI] ,[DocumentName] ,[ReportDefinitionCode] ,[FileType] ,[InvoiceBalance] ,[InvoiceBalanceNetto] ,[WageBalanceNet] ,[DatePayed] ,[InvoiceId] ,[DueDate] ,[WithoutVAT] ,[Skonto] ,[PartialPayment] ,[InvoiceState] ,[Note] ,[file_guid]) VALUES ( SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[DateOfCreation] ,SOURCE.[URI] ,SOURCE.[DocumentName] ,SOURCE.[ReportDefinitionCode] ,SOURCE.[FileType] ,SOURCE.[InvoiceBalance] ,SOURCE.[InvoiceBalanceNetto] ,SOURCE.[WageBalanceNet] ,SOURCE.[DatePayed] ,SOURCE.[InvoiceId] ,SOURCE.[DueDate] ,SOURCE.[WithoutVAT] ,SOURCE.[Skonto] ,SOURCE.[PartialPayment] ,SOURCE.[InvoiceState] ,SOURCE.[Note] ,newid()); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__invoices] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__items] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__items] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__items]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__items] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[QuantityHours] = SOURCE.[QuantityHours] ,[PlannedQuantityHours] = SOURCE.[PlannedQuantityHours] ,[ItemTypeId] = SOURCE.[ItemTypeId] ,[ItemNumber] = SOURCE.[ItemNumber] ,[TrackingId] = SOURCE.[TrackingId] ,[Manufacture] = SOURCE.[Manufacture] ,[Price] = SOURCE.[Price] ,[Costs] = SOURCE.[Costs] ,[NameOrNumber] = SOURCE.[NameOrNumber] ,[CustomValues] = SOURCE.[CustomValues] ,[Note] = SOURCE.[Note] ,[ExternalId] = SOURCE.[ExternalId] ,[Discount] = SOURCE.[Discount] ,[VAT] = SOURCE.[VAT] ,[IsManual] = SOURCE.[IsManual] ,[SortOrder] = SOURCE.[SortOrder] ,[Type] = SOURCE.[Type] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[ServiceObjectId] = SOURCE.[ServiceObjectId] ,[CreatorId] = SOURCE.[CreatorId] ,[UnitId] = SOURCE.[UnitId] ,[UnitString] = SOURCE.[UnitString] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[Version] ,[QuantityHours] ,[PlannedQuantityHours] ,[ItemTypeId] ,[ItemNumber] ,[TrackingId] ,[Manufacture] ,[Price] ,[Costs] ,[NameOrNumber] ,[CustomValues] ,[Note] ,[ExternalId] ,[Discount] ,[VAT] ,[IsManual] ,[SortOrder] ,[Type] ,[ServiceRequestId] ,[ServiceObjectId] ,[CreatorId] ,[UnitId] ,[UnitString]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[QuantityHours] ,SOURCE.[PlannedQuantityHours] ,SOURCE.[ItemTypeId] ,SOURCE.[ItemNumber] ,SOURCE.[TrackingId] ,SOURCE.[Manufacture] ,SOURCE.[Price] ,SOURCE.[Costs] ,SOURCE.[NameOrNumber] ,SOURCE.[CustomValues] ,SOURCE.[Note] ,SOURCE.[ExternalId] ,SOURCE.[Discount] ,SOURCE.[VAT] ,SOURCE.[IsManual] ,SOURCE.[SortOrder] ,SOURCE.[Type] ,SOURCE.[ServiceRequestId] ,SOURCE.[ServiceObjectId] ,SOURCE.[CreatorId] ,SOURCE.[UnitId] ,SOURCE.[UnitString]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__items] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__itemtypes] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__itemtypes] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__itemtypes]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__itemtypes] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified] ) THEN UPDATE SET [Id] = SOURCE.[Id] ,[CustomValues] = SOURCE.[CustomValues] ,[Version] = SOURCE.[Version] ,[Costs] = SOURCE.[Costs] ,[Description] = SOURCE.[Description] ,[ListPrice] = SOURCE.[ListPrice] ,[Manufacture] = SOURCE.[Manufacture] ,[ExternalId] = SOURCE.[ExternalId] ,[ItemNumber] = SOURCE.[ItemNumber] ,[NameOrNumber] = SOURCE.[NameOrNumber] ,[GlobalTradeItemNr] = SOURCE.[GlobalTradeItemNr] ,[Type] = SOURCE.[Type] ,[Price] = SOURCE.[Price] ,[VAT] = SOURCE.[VAT] ,[IsPortalOnly] = SOURCE.[IsPortalOnly] ,[Discount] = SOURCE.[Discount] ,[DateModified] = SOURCE.[DateModified] ,[IsDiscontinued] = SOURCE.[IsDiscontinued] ,[IsWarehouse] = SOURCE.[IsWarehouse] ,[UnitId] = SOURCE.[UnitId] ,[UnitString] = SOURCE.[UnitString] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[CustomValues] ,[Version] ,[Costs] ,[Description] ,[ListPrice] ,[Manufacture] ,[ExternalId] ,[ItemNumber] ,[NameOrNumber] ,[GlobalTradeItemNr] ,[Type] ,[Price] ,[VAT] ,[IsPortalOnly] ,[Discount] ,[DateModified] ,[IsDiscontinued] ,[IsWarehouse] ,[UnitId] ,[UnitString]) VALUES (SOURCE.[Id] ,SOURCE.[CustomValues] ,SOURCE.[Version] ,SOURCE.[Costs] ,SOURCE.[Description] ,SOURCE.[ListPrice] ,SOURCE.[Manufacture] ,SOURCE.[ExternalId] ,SOURCE.[ItemNumber] ,SOURCE.[NameOrNumber] ,SOURCE.[GlobalTradeItemNr] ,SOURCE.[Type] ,SOURCE.[Price] ,SOURCE.[VAT] ,SOURCE.[IsPortalOnly] ,SOURCE.[Discount] ,SOURCE.[DateModified] ,SOURCE.[IsDiscontinued] ,SOURCE.[IsWarehouse] ,SOURCE.[UnitId] ,SOURCE.[UnitString]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__itemtypes] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__itemunits] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__itemunits] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__itemunits]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__itemunits] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[Name]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Name]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__itemunits] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__products] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__products] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__products]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__products] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] ,[SubKey] = SOURCE.[SubKey] ,[Description] = SOURCE.[Description] ,[DateModified] = SOURCE.[DateModified] ,[MappingId] = SOURCE.[MappingId] ,[CustomValueStepTemplateId] = SOURCE.[CustomValueStepTemplateId] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[Version] ,[Name] ,[SubKey] ,[Description] ,[DateModified] ,[MappingId] ,[CustomValueStepTemplateId]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Name] ,SOURCE.[SubKey] ,SOURCE.[Description] ,SOURCE.[DateModified] ,SOURCE.[MappingId] ,SOURCE.[CustomValueStepTemplateId]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__products] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__qualifications] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__qualifications] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__qualifications]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__qualifications] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[Name]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Name]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__qualifications] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__reports] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__reports] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__reports]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__reports] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateOfCreation] <= SOURCE.[DateOfCreation] ) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[DateOfCreation] = SOURCE.[DateOfCreation] ,[URI] = SOURCE.[URI] ,[DocumentName] = SOURCE.[DocumentName] ,[FileTypeString] = SOURCE.[FileTypeString] ,[ReportDefinitionCode] = SOURCE.[ReportDefinitionCode] ,[ServiceObjectId] = SOURCE.[ServiceObjectId] ,[CanBeDeleted] = SOURCE.[CanBeDeleted] ,[InvoiceBalance] = SOURCE.[InvoiceBalance] ,[InvoiceId] = SOURCE.[InvoiceId] ,[DueDate] = SOURCE.[DueDate] ,[IsPayed] = SOURCE.[IsPayed] ,[IsInvoice] = SOURCE.[IsInvoice] ,[IsCanceled] = SOURCE.[IsCanceled] ,[CustomValues] = SOURCE.[CustomValues] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[DateOfCreation] ,[URI] ,[DocumentName] ,[FileTypeString] ,[ReportDefinitionCode] ,[ServiceObjectId] ,[CanBeDeleted] ,[InvoiceBalance] ,[InvoiceId] ,[DueDate] ,[IsPayed] ,[IsInvoice] ,[IsCanceled] ,[CustomValues]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[DateOfCreation] ,SOURCE.[URI] ,SOURCE.[DocumentName] ,SOURCE.[FileTypeString] ,SOURCE.[ReportDefinitionCode] ,SOURCE.[ServiceObjectId] ,SOURCE.[CanBeDeleted] ,SOURCE.[InvoiceBalance] ,SOURCE.[InvoiceId] ,SOURCE.[DueDate] ,SOURCE.[IsPayed] ,SOURCE.[IsInvoice] ,SOURCE.[IsCanceled] ,SOURCE.[CustomValues]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__reports] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__serviceobjects] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__serviceobjects] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); DECLARE @tmp [dbo].[mfr__tt__serviceobjects]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; IF @referencetable = 'mfr__serviceobjects' BEGIN DELETE p OUTput deleted.*, @now INTO [dbo].[mfr__d_*PartnerSet] FROM [dbo].[mfr__*PartnerSet] as p WHERE p.Property like 'ServiceObject[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = p.[EntityId]); DELETE cv OUTput deleted.*, @now INTO [dbo].[mfr__d_#customvalues] FROM [dbo].[mfr__#customvalues] as cv WHERE cv.Property like 'ServiceObject[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = cv.[EntityId]); DELETE lc OUTPUT deleted.*, @now INTO [dbo].[mfr__d_#locations] FROM [dbo].[mfr__#locations] as lc WHERE lc.Property like 'ServiceObject[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = lc.[EntityId]); DELETE itm OUTPUT deleted.*, @now INTO [dbo].[mfr__d_items] FROM [dbo].[mfr__items] as itm WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = itm.[ServiceObjectId] and ISNULL(itm.[ServiceRequestId],0) = 0); END MERGE [dbo].[mfr__serviceobjects] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Location#ID] = SOURCE.[Location#ID] ,[Name] = SOURCE.[Name] ,[Note] = SOURCE.[Note] ,[CustomValues] = SOURCE.[CustomValues] ,[DateModified] = SOURCE.[DateModified] ,[ExternalId] = SOURCE.[ExternalId] ,[MappingId] = SOURCE.[MappingId] ,[QuickSearch] = SOURCE.[QuickSearch] ,[Version] = SOURCE.[Version] ,[CreateGeoLocation] = SOURCE.[CreateGeoLocation] ,[IsWarehouse] = SOURCE.[IsWarehouse] ,[ParentServiceObjectId] = SOURCE.[ParentServiceObjectId] ,[CompanyId] = SOURCE.[CompanyId] ,[ProductId] = SOURCE.[ProductId] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[Location#ID] ,[Name] ,[Note] ,[CustomValues] ,[DateModified] ,[ExternalId] ,[MappingId] ,[QuickSearch] ,[Version] ,[CreateGeoLocation] ,[IsWarehouse] ,[ParentServiceObjectId] ,[CompanyId] ,[ProductId]) VALUES (SOURCE.[Id] ,SOURCE.[Location#ID] ,SOURCE.[Name] ,SOURCE.[Note] ,SOURCE.[CustomValues] ,SOURCE.[DateModified] ,SOURCE.[ExternalId] ,SOURCE.[MappingId] ,SOURCE.[QuickSearch] ,SOURCE.[Version] ,SOURCE.[CreateGeoLocation] ,SOURCE.[IsWarehouse] ,SOURCE.[ParentServiceObjectId] ,SOURCE.[CompanyId] ,SOURCE.[ProductId]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__serviceobjects] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__servicerequests] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__servicerequests] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; BEGIN TRY DECLARE @now datetime = GETUTCDATE(); DECLARE @tmp [dbo].[mfr__tt__servicerequests]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname; INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; BEGIN TRANSACTION; IF @referencetable = 'mfr__servicerequests' BEGIN DELETE p OUTput deleted.*, @now INTO [dbo].[mfr__d_*PartnerSet] FROM [dbo].[mfr__*PartnerSet] as p WHERE p.Property like 'ServiceRequest[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = p.[EntityId]); DELETE cv OUTput deleted.*, @now INTO [dbo].[mfr__d_#customvalues] FROM [dbo].[mfr__#customvalues] as cv WHERE cv.Property like 'ServiceRequest[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = cv.[EntityId]); DELETE lc OUTPUT deleted.*, @now INTO [dbo].[mfr__d_#locations] FROM [dbo].[mfr__#locations] as lc WHERE lc.Property like 'ServiceRequest[:]%' AND EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = lc.[EntityId]); DELETE stp OUTPUT deleted.*, @now INTO [dbo].[mfr__d_steps] FROM [dbo].[mfr__steps] as stp WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = stp.[ServiceRequestId] and ISNULL(stp.[StepListTemplateId],0) = 0); DELETE app OUTPUT deleted.*, @now INTO [dbo].[mfr__d_appointments] FROM [dbo].[mfr__appointments] as app WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = app.[ServiceRequestId]); DELETE itm OUTPUT deleted.*, @now INTO [dbo].[mfr__d_items] FROM [dbo].[mfr__items] as itm WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = itm.[ServiceRequestId] and ISNULL(itm.[ServiceobjectId],0) = 0); DELETE te OUTPUT deleted.*, @now INTO [dbo].[mfr__d_timeevents] FROM [dbo].[mfr__timeevents] as te WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = te.[ServiceRequestId]); DELETE sm OUTPUT deleted.*, @now INTO [dbo].[mfr__d_stockmovements] FROM [dbo].[mfr__stockmovements] as sm WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = sm.[ServiceRequestId]); DELETE cm OUTPUT deleted.*, @now INTO [dbo].[mfr__d_comments] FROM [dbo].[mfr__comments] as cm WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = cm.[ServiceRequestId] AND ISNULL(cm.[CompanyId],0) = 0); END MERGE [dbo].[mfr__servicerequests] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified] OR TARGET.[DateOfCreation] <= SOURCE.[DateOfCreation] ) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Name] = SOURCE.[Name] ,[ExternalId] = SOURCE.[ExternalId] ,[InvoiceId] = SOURCE.[InvoiceId] ,[ClosedAt] = SOURCE.[ClosedAt] ,[ReleasedAt] = SOURCE.[ReleasedAt] ,[WorkDoneAt] = SOURCE.[WorkDoneAt] ,[TargetTimeInMinutes] = SOURCE.[TargetTimeInMinutes] ,[DateModified] = SOURCE.[DateModified] ,[DateOfCreation] = SOURCE.[DateOfCreation] ,[DueDateRangeStart] = SOURCE.[DueDateRangeStart] ,[DueDateRangeEnd] = SOURCE.[DueDateRangeEnd] ,[PortalLink] = SOURCE.[PortalLink] ,[CostCenterId] = SOURCE.[CostCenterId] ,[Description] = SOURCE.[Description] ,[State] = SOURCE.[State] ,[CustomValues] = SOURCE.[CustomValues] ,[CurrentOwnerId] = SOURCE.[CurrentOwnerId] ,[CustomerId] = SOURCE.[CustomerId] ,[ParentServiceRequestId] = SOURCE.[ParentServiceRequestId] ,[Location#ID] = SOURCE.[Location#ID] ,[Version] = SOURCE.[Version] ,[IsTemplate] = SOURCE.[IsTemplate] ,[IsTemplateMobile] = SOURCE.[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] = SOURCE.[CreateFromServiceRequestTemplateId] ,[Type] = SOURCE.[Type] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Name] ,[ExternalId] ,[InvoiceId] ,[ClosedAt] ,[ReleasedAt] ,[WorkDoneAt] ,[TargetTimeInMinutes] ,[DateModified] ,[DateOfCreation] ,[DueDateRangeStart] ,[DueDateRangeEnd] ,[PortalLink] ,[CostCenterId] ,[Description] ,[State] ,[CustomValues] ,[CurrentOwnerId] ,[CustomerId] ,[ParentServiceRequestId] ,[Location#ID] ,[Version] ,[IsTemplate] ,[IsTemplateMobile] ,[CreateFromServiceRequestTemplateId] ,[Type]) VALUES (SOURCE.[Id] ,SOURCE.[Name] ,SOURCE.[ExternalId] ,SOURCE.[InvoiceId] ,SOURCE.[ClosedAt] ,SOURCE.[ReleasedAt] ,SOURCE.[WorkDoneAt] ,SOURCE.[TargetTimeInMinutes] ,SOURCE.[DateModified] ,SOURCE.[DateOfCreation] ,SOURCE.[DueDateRangeStart] ,SOURCE.[DueDateRangeEnd] ,SOURCE.[PortalLink] ,SOURCE.[CostCenterId] ,SOURCE.[Description] ,SOURCE.[State] ,SOURCE.[CustomValues] ,SOURCE.[CurrentOwnerId] ,SOURCE.[CustomerId] ,SOURCE.[ParentServiceRequestId] ,SOURCE.[Location#ID] ,SOURCE.[Version] ,SOURCE.[IsTemplate] ,SOURCE.[IsTemplateMobile] ,SOURCE.[CreateFromServiceRequestTemplateId] ,SOURCE.[Type]); COMMIT TRANSACTION; END TRY BEGIN CATCH INSERT INTO dbo.[fds__admin_dberrors] VALUES (SUSER_SNAME(), ERROR_NUMBER(), ERROR_STATE(), ERROR_SEVERITY(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_MESSAGE(), GETDATE()); -- Transaction uncommittable --IF (XACT_STATE()) = -1 ROLLBACK TRANSACTION; -- Transaction committable --IF (XACT_STATE()) = 1 --COMMIT TRANSACTION; DECLARE @Message varchar(MAX) = ERROR_MESSAGE(), @Severity int = ERROR_SEVERITY(), @State smallint = ERROR_STATE(); RAISERROR (@Message, @Severity, @State); END CATCH; END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__servicerequests] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__steplisttemplateinstances] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__steplisttemplateinstances] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__steplisttemplateinstances]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__steplisttemplateinstances] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[TemplateId] = SOURCE.[TemplateId] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[Name] ,[ServiceRequestId] ,[TemplateId]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Name] ,SOURCE.[ServiceRequestId] ,SOURCE.[TemplateId]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__steplisttemplateinstances] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__steplisttemplates] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__steplisttemplates] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); DECLARE @tmp [dbo].[mfr__tt__steplisttemplates]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; IF @referencetable = 'mfr__steplisttemplates' BEGIN DELETE stp OUTPUT deleted.*, @now INTO [dbo].[mfr__d_steps] FROM [dbo].[mfr__steps] as stp WHERE EXISTS (SELECT * FROM @tmp as tmp where tmp.[id] = stp.[StepListTemplateId] and ISNULL(stp.[ServiceRequestId],0) = 0); END MERGE [dbo].[mfr__steplisttemplates] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] ,[MappingId] = SOURCE.[MappingId] ,[DateModified] = SOURCE.[DateModified] ,[IsReleased] = SOURCE.[IsReleased] ,[IsDurable] = SOURCE.[IsDurable] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[Name] ,[MappingId] ,[DateModified] ,[IsReleased] ,[IsDurable]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Name] ,SOURCE.[MappingId] ,SOURCE.[DateModified] ,SOURCE.[IsReleased] ,SOURCE.[IsDurable]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__steplisttemplates] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__steps] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__steps] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @now datetime = GETUTCDATE(); DECLARE @tmp [dbo].[mfr__tt__steps]; DECLARE @ARCHIVE TABLE( [ActionType] varchar(25), [Id] [bigint] NULL, [MobileId] [bigint] NULL, [Version] [int] NULL, [Name] [nvarchar](255) NULL, [IsDone] [bit] NULL, [HasError] [bit] NULL, [TrackingId] [nvarchar](255) NULL, [Type] [nvarchar](255) NULL, [SortOrder] [int] NULL, [Data] [nvarchar](max) NULL, [DateModifiedOffline] [datetime] NULL, [ServiceRequestId] [bigint] NULL, [Description] [nvarchar](max) NULL, [Comment] [nvarchar](max) NULL, [InternalComment] [nvarchar](max) NULL, [ServiceObjectId] [bigint] NULL, [StepListTemplateId] [bigint] NULL, [ParentId] [bigint] NULL ); DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; DECLARE @olist TABLE ( [id] bigint ); DECLARE @check_reference as varchar(5) = ''; IF ISNULL(@referencetable,'') = 'mfr__servicerequests' BEGIN SET @check_reference = 'srq'; INSERT INTO @olist SELECT DISTINCT [ServiceRequestId] FROM @tmp WHERE ISNULL([ServiceRequestId],0) <> 0; END IF ISNULL(@referencetable,'') = 'mfr__steplisttemplates' BEGIN SET @check_reference = 'slt'; INSERT INTO @olist SELECT DISTINCT [StepListTemplateId] FROM @tmp WHERE ISNULL([StepListTemplateId],0) <> 0; END MERGE [dbo].[mfr__steps] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[MobileId] = SOURCE.[MobileId] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] ,[IsDone] = SOURCE.[IsDone] ,[HasError] = SOURCE.[HasError] ,[TrackingId] = SOURCE.[TrackingId] ,[Type] = SOURCE.[Type] ,[SortOrder] = SOURCE.[SortOrder] ,[Data] = SOURCE.[Data] ,[DateModifiedOffline] = SOURCE.[DateModifiedOffline] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[Description] = SOURCE.[Description] ,[Comment] = SOURCE.[Comment] ,[InternalComment] = SOURCE.[InternalComment] ,[ServiceObjectId] = SOURCE.[ServiceObjectId] ,[StepListTemplateId] = SOURCE.[StepListTemplateId] ,[ParentId] = SOURCE.[ParentId] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[MobileId] ,[Version] ,[Name] ,[IsDone] ,[HasError] ,[TrackingId] ,[Type] ,[SortOrder] ,[Data] ,[DateModifiedOffline] ,[ServiceRequestId] ,[Description] ,[Comment] ,[InternalComment] ,[ServiceObjectId] ,[StepListTemplateId] ,[ParentId]) VALUES (SOURCE.[Id] ,SOURCE.[MobileId] ,SOURCE.[Version] ,SOURCE.[Name] ,SOURCE.[IsDone] ,SOURCE.[HasError] ,SOURCE.[TrackingId] ,SOURCE.[Type] ,SOURCE.[SortOrder] ,SOURCE.[Data] ,SOURCE.[DateModifiedOffline] ,SOURCE.[ServiceRequestId] ,SOURCE.[Description] ,SOURCE.[Comment] ,SOURCE.[InternalComment] ,SOURCE.[ServiceObjectId] ,SOURCE.[StepListTemplateId] ,SOURCE.[ParentId]) WHEN NOT MATCHED BY SOURCE AND (CASE WHEN @check_reference = 'srq' AND EXISTS (SELECT * FROM @olist as ol where ol.[id] = TARGET.[ServiceRequestId]) THEN 1 WHEN @check_reference = 'slt' AND EXISTS (SELECT * FROM @olist as ol where ol.[id] = TARGET.[StepListTemplateId]) THEN 1 ELSE 0 END) = 1 THEN DELETE OUTPUT $action, deleted.* INTO @ARCHIVE; INSERT INTO [dbo].[mfr__d_steps] SELECT [Id] ,[MobileId] ,[Version] ,[Name] ,[IsDone] ,[HasError] ,[TrackingId] ,[Type] ,[SortOrder] ,[Data] ,[DateModifiedOffline] ,[ServiceRequestId] ,[Description] ,[Comment] ,[InternalComment] ,[ServiceObjectId] ,[StepListTemplateId] ,[ParentId] ,[DateDeleted] = @now FROM @ARCHIVE WHERE [ActionType] IN ( 'DELETE', 'UPDATE' ); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__steps] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__stockmovements] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__stockmovements] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__stockmovements]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__stockmovements] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified] OR TARGET.[DateOfCreation] <= SOURCE.[DateOfCreation] ) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Amount] = SOURCE.[Amount] ,[AmountReceived] = SOURCE.[AmountReceived] ,[ExternalId] = SOURCE.[ExternalId] ,[ItemId] = SOURCE.[ItemId] ,[ItemTypeId] = SOURCE.[ItemTypeId] ,[StockMovementType] = SOURCE.[StockMovementType] ,[State] = SOURCE.[State] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[WarehouseId] = SOURCE.[WarehouseId] ,[DateOfCreation] = SOURCE.[DateOfCreation] ,[DateModified] = SOURCE.[DateModified] ,[TargetDate] = SOURCE.[TargetDate] ,[CreatedById] = SOURCE.[CreatedById] ,[ConfirmedById] = SOURCE.[ConfirmedById] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[Amount] ,[AmountReceived] ,[ExternalId] ,[ItemId] ,[ItemTypeId] ,[StockMovementType] ,[State] ,[ServiceRequestId] ,[WarehouseId] ,[DateOfCreation] ,[DateModified] ,[TargetDate] ,[CreatedById] ,[ConfirmedById]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Amount] ,SOURCE.[AmountReceived] ,SOURCE.[ExternalId] ,SOURCE.[ItemId] ,SOURCE.[ItemTypeId] ,SOURCE.[StockMovementType] ,SOURCE.[State] ,SOURCE.[ServiceRequestId] ,SOURCE.[WarehouseId] ,SOURCE.[DateOfCreation] ,SOURCE.[DateModified] ,SOURCE.[TargetDate] ,SOURCE.[CreatedById] ,SOURCE.[ConfirmedById]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__stockmovements] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__tags] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__tags] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__tags]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; WITH tmp as ( SELECT *, ROW_NUMBER() OVER (PARTITION BY [id] ORDER BY [version] DESC) as '#' FROM @tmp ), SOURCE as ( SELECT * FROM tmp WHERE [#] = 1 ) MERGE [dbo].[mfr__tags] as TARGET USING SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[Name] = SOURCE.[Name] ,[ColorDefinition] = SOURCE.[ColorDefinition] ,[Type] = SOURCE.[Type] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[Version] ,[Name] ,[ColorDefinition] ,[Type]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[Name] ,SOURCE.[ColorDefinition] ,SOURCE.[Type]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__tags] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__timeevents] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__timeevents] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; DECLARE @tmp [dbo].[mfr__tt__timeevents]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; MERGE [dbo].[mfr__timeevents] as TARGET USING @tmp as SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[DateModified] <= SOURCE.[DateModified]) THEN UPDATE SET [Id] = SOURCE.[Id] ,[Version] = SOURCE.[Version] ,[State] = SOURCE.[State] ,[IsApproved] = SOURCE.[IsApproved] ,[TimeEventType] = SOURCE.[TimeEventType] ,[ExternalId] = SOURCE.[ExternalId] ,[DateModified] = SOURCE.[DateModified] ,[StartDateTime] = SOURCE.[StartDateTime] ,[EndDateTime] = SOURCE.[EndDateTime] ,[ProposedDrivingDistance] = SOURCE.[ProposedDrivingDistance] ,[ContactId] = SOURCE.[ContactId] ,[ServiceRequestId] = SOURCE.[ServiceRequestId] ,[Description] = SOURCE.[Description] WHEN NOT MATCHED BY TARGET THEN INSERT ([Id] ,[Version] ,[State] ,[IsApproved] ,[TimeEventType] ,[ExternalId] ,[DateModified] ,[StartDateTime] ,[EndDateTime] ,[ProposedDrivingDistance] ,[ContactId] ,[ServiceRequestId] ,[Description]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[State] ,SOURCE.[IsApproved] ,SOURCE.[TimeEventType] ,SOURCE.[ExternalId] ,SOURCE.[DateModified] ,SOURCE.[StartDateTime] ,SOURCE.[EndDateTime] ,SOURCE.[ProposedDrivingDistance] ,SOURCE.[ContactId] ,SOURCE.[ServiceRequestId] ,SOURCE.[Description]); END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__timeevents] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[mfr__updt__users] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[mfr__updt__users] @tblname as nvarchar(50) , @referencetable nvarchar(50) , @tgtid bigint AS BEGIN SET NOCOUNT ON; BEGIN TRY DECLARE @now datetime = GETUTCDATE(); DECLARE @tmp [dbo].[mfr__tt__users]; DECLARE @tmp_cmd nvarchar(1000) = N'SELECT DISTINCT * FROM ' + @tblname; INSERT INTO @tmp EXECUTE [sp_executesql] @tmp_cmd; BEGIN TRANSACTION; with SOURCE1 as( SELECT *, [op] = ROW_NUMBER() OVER (PARTITION BY [id] order by [version] desc, [lastlogindate] desc) FROM @tmp ), SOURCE as( SELECT * from SOURCE1 where [op] = 1 ) MERGE [dbo].[mfr__users] as TARGET USING SOURCE ON TARGET.[Id] = SOURCE.[Id] WHEN MATCHED AND (TARGET.[Version] <= SOURCE.[Version] OR TARGET.[CreationDate] <= SOURCE.[CreationDate]) THEN UPDATE SET [Version] = SOURCE.[Version] ,[UserName] = SOURCE.[UserName] ,[IsSystem] = SOURCE.[IsSystem] ,[CreationDate] = SOURCE.[CreationDate] ,[IsApproved] = SOURCE.[IsApproved] ,[ContactId] = SOURCE.[ContactId] ,[PreferedLanguage] = SOURCE.[PreferedLanguage] ,[EmailChannelEnabled] = SOURCE.[EmailChannelEnabled] ,[HasFullScreenPreference] = SOURCE.[HasFullScreenPreference] ,[TimeZone] = SOURCE.[TimeZone] ,[PreferedCulture] = SOURCE.[PreferedCulture] ,[IsActive] = SOURCE.[IsActive] ,[IsMobile] = SOURCE.[IsMobile] ,[LastLoginDate] = SOURCE.[LastLoginDate] ,[UserGuideProgress] = SOURCE.[UserGuideProgress] ,[DashboardSettings] = SOURCE.[DashboardSettings] WHEN NOT MATCHED BY TARGET THEN INSERT ( [Id] ,[Version] ,[UserName] ,[IsSystem] ,[CreationDate] ,[IsApproved] ,[ContactId] ,[PreferedLanguage] ,[EmailChannelEnabled] ,[HasFullScreenPreference] ,[TimeZone] ,[PreferedCulture] ,[IsActive] ,[IsMobile] ,[LastLoginDate] ,[UserGuideProgress] ,[DashboardSettings]) VALUES (SOURCE.[Id] ,SOURCE.[Version] ,SOURCE.[UserName] ,SOURCE.[IsSystem] ,SOURCE.[CreationDate] ,SOURCE.[IsApproved] ,SOURCE.[ContactId] ,SOURCE.[PreferedLanguage] ,SOURCE.[EmailChannelEnabled] ,SOURCE.[HasFullScreenPreference] ,SOURCE.[TimeZone] ,SOURCE.[PreferedCulture] ,SOURCE.[IsActive] ,SOURCE.[IsMobile] ,SOURCE.[LastLoginDate] ,SOURCE.[UserGuideProgress] ,SOURCE.[DashboardSettings]); COMMIT TRANSACTION; END TRY BEGIN CATCH INSERT INTO dbo.[fds__admin_dberrors] VALUES (SUSER_SNAME(), ERROR_NUMBER(), ERROR_STATE(), ERROR_SEVERITY(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_MESSAGE(), GETDATE()); -- Transaction uncommittable --IF (XACT_STATE()) = -1 ROLLBACK TRANSACTION; -- Transaction committable --IF (XACT_STATE()) = 1 --COMMIT TRANSACTION; DECLARE @Message varchar(MAX) = ERROR_MESSAGE(), @Severity int = ERROR_SEVERITY(), @State smallint = ERROR_STATE(); RAISERROR (@Message, @Severity, @State); END CATCH; END GO ALTER AUTHORIZATION ON [dbo].[mfr__updt__users] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_admin_createUserAccount] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_admin_createUserAccount] @name nvarchar(255) ,@email varchar(255) ,@mobile varchar(50) ,@password nvarchar(20) ,@enc_key uniqueidentifier AS BEGIN SET NOCOUNT ON; DECLARE @utcnow datetime = GETUTCDATE(); INSERT INTO [dbo].[ocms_useraccounts] ([useraccount_id] ,[name_enc] ,[email_enc] ,[mobile_enc] ,[password_enc] ,[UserDisabled] ,[DateDisabled] ,[UserCreated] ,[DateCreated] ,[UserModified] ,[DateModified] ,[UserDeleted] ,[DateDeleted]) OUTPUT inserted.[useraccount_id] VALUES ([dbo].[ocms_fn_useraccount_id] () ,ENCRYPTBYKEY(@enc_key, @name) ,ENCRYPTBYKEY(@enc_key, @email) ,ENCRYPTBYKEY(@enc_key, @mobile) ,CASE WHEN @password is null then null ELSE ENCRYPTBYKEY(@enc_key, @password) END ,NULL --[UserDisabled] ,NULL --[DateDisabled] ,'sa' ,@utcnow ,'sa' ,@utcnow ,NULL ,NULL); END GO ALTER AUTHORIZATION ON [dbo].[ocms_admin_createUserAccount] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_admin_debug_log] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Dr. Stefan Ott -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_admin_debug_log] @machine varchar(50) ,@error varchar(2000) ,@exception varchar(max) ,@procedure varchar(255) ,@authuser varchar(25) ,@data nvarchar(max) ,@isdebug bit AS BEGIN SET NOCOUNT ON; INSERT INTO [dbo].[ocms_debug] ([machine] ,[error] ,[exception] ,[procedure] ,[authuser] ,[data] ,[isdebug]) VALUES ( @machine ,@error ,@exception ,@procedure ,@authuser ,@data ,@isdebug ); END GO ALTER AUTHORIZATION ON [dbo].[ocms_admin_debug_log] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_cleanups] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_cleanups] AS BEGIN SET NOCOUNT ON; /* UPDATE Template Property Numbering */ with tpo as ( select * , ROW_NUMBER() OVER (PARTITION BY ocms_tid ORDER BY [order], ocms_tpid) as 'tpo' from [dbo].[ocms_template_properties] ) update tp SET tp.[order] = tpo.[tpo] From [dbo].[ocms_template_properties] as tp JOIN tpo ON tp.[ocms_tpid] = tpo.[ocms_tpid]; /* UPDATE ITEM NUMBERING */ with ino as ( select * , ROW_NUMBER() OVER (PARTITION BY [parent_iid] ORDER BY [order], [ocms_iid]) as 'itmo' -- 999 for any new from [dbo].[ocms_items] ) update i SET i.[order] = ino.[itmo] From [dbo].[ocms_items] as i JOIN ino ON i.[ocms_iid] = ino.[ocms_iid] WHERE i.[order] >= 0 and i.[parent_iid] is not null END GO ALTER AUTHORIZATION ON [dbo].[ocms_cleanups] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_cloneItem] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_cloneItem] @old_ocms_iid bigint ,@new_parent_iid bigint AS BEGIN SET NOCOUNT ON; IF EXISTS (SELECT * from [dbo].[ocms_items] as i where i.[ocms_iid] = @old_ocms_iid) AND EXISTS (SELECT * from [dbo].[ocms_items] as i where i.[ocms_iid] = @new_parent_iid) BEGIN DECLARE @NEW TABLE ([ocms_iid] bigint, [old_ocms_pid] bigint); INSERT INTO [dbo].[ocms_items] ([parent_iid] ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order] ,[DateCreated] ,[DateModified]) OUTPUT inserted.[ocms_iid], inserted.[ocms_pid] INTO @new SELECT @new_parent_iid ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order] ,GETUTCDATE() ,GETUTCDATE() FROM [dbo].[ocms_items] as i WHERE [ocms_iid] = @old_ocms_iid; DECLARE @new_ocms_iid bigint, @old_ocms_pid bigint; SELECT TOP(1) @new_ocms_iid = [ocms_iid], @old_ocms_pid = [old_ocms_pid] FROM @NEW; IF NOT EXISTS (SELECT pn.* from [dbo].[ocms_properties] as pn JOIN [dbo].[ocms_properties] as po ON pn.[key] = po.[key] and pn.[locale] = po.[locale] WHERE pn.[ocms_iid] = @new_parent_iid AND po.[ocms_pid] = @old_ocms_pid) BEGIN DECLARE @newprop [dbo].[ocms_type_properties_base]; DECLARE @property_key varchar(50), @locale varchar(5), @new_ocms_pid bigint; SELECT TOP(1) @property_key = [key], @locale = [locale] FROM [dbo].[ocms_properties] as p WHERE [ocms_pid] = @old_ocms_pid; IF ISNULL(@property_key, '') <> '' BEGIN INSERT INTO @newprop VALUES(@new_parent_iid, @property_key, '', @locale); EXECUTE [dbo].[ocms_merge_properties] @newprop; --makes sure is ok with template END SELECT TOP(1) @new_ocms_pid = [ocms_pid] FROM [dbo].[ocms_properties] WHERE [ocms_iid] = @new_parent_iid AND [key] = @property_key; UPDATE [dbo].[ocms_items] SET [ocms_pid] = @new_ocms_pid ,[DateModified] = GETUTCDATE() WHERE [ocms_iid] = @new_ocms_iid; END IF @new_ocms_iid is not null BEGIN INSERT INTO [dbo].[ocms_properties] ([ocms_iid] ,[key] ,[value] ,[locale] ,[DateCreated] ,[DateModified] ) SELECT @new_ocms_iid ,[key] ,[value] ,[locale] ,GETUTCDATE() ,GETUTCDATE() FROM [dbo].[ocms_properties] WHERE [ocms_iid] = @old_ocms_iid; END END END GO ALTER AUTHORIZATION ON [dbo].[ocms_cloneItem] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_createPropertyItem] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_createPropertyItem] @name nvarchar(255), @parent_iid bigint, @ocms_pid bigint, @property_key varchar(50), @template_id bigint, @locale varchar(5) AS BEGIN SET NOCOUNT ON; DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); IF ISNULL(@name, '') = '' THROW 61010, 'name missing', 1; IF EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [name] = @name) THROW 61010, 'name already exists', 1; IF NOT EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [ocms_iid] = @parent_iid) THROW 61010, 'parent does not exist', 1; IF NOT EXISTS (SELECT * FROM [dbo].[ocms_templates] WHERE [ocms_tid] = @template_id) THROW 61010, 'template does not exist', 1; IF NOT EXISTS (SELECT * FROM [dbo].[ocms_properties] WHERE [ocms_iid] = @parent_iid AND ([ocms_pid] = @ocms_pid OR (@ocms_pid is null AND [key] = @property_key))) BEGIN DECLARE @newprop [dbo].[ocms_type_properties_base]; INSERT INTO @newprop VALUES(@parent_iid, @property_key, '', @locale); EXECUTE [dbo].[ocms_merge_properties] @newprop; --makes sure is ok with template END SELECT TOP(1) @ocms_pid = [ocms_pid] FROM [dbo].[ocms_properties] WHERE [ocms_iid] = @parent_iid AND ([ocms_pid] = @ocms_pid OR (@ocms_pid is null AND [key] = @property_key)); --get last ocms_iid DECLARE @lastiid int = ISNULL ( (SELECT MAX(ISNULL(p.[ocms_iid], ap.[ocms_iid])) FROM [dbo].[ocms_items] as p FULL OUTER JOIN [ocms_archive__items] as ap on p.[ocms_iid] = ap.[ocms_iid]) ,0); IF NOT EXISTS (SELECT * FROM [dbo].[ocms_properties] WHERE [ocms_iid] = @parent_iid AND [ocms_pid] = @ocms_pid) THROW 61010, 'parent''s property does not exist', 1; IF @site is not null BEGIN MERGE [dbo].[ocms_items] as TARGET USING (VALUES( @parent_iid ,@ocms_pid ,@name ,0 ,@template_id ,0 ,999 -- append always )) as SOURCE ([parent_iid] ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order]) ON TARGET.[name] = SOURCE.[name] WHEN NOT MATCHED BY TARGET THEN INSERT ([ocms_iid] ,[parent_iid] ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order] ,[DateCreated] ,[DateModified]) VALUES( @lastiid + 1, SOURCE.[parent_iid], SOURCE.[ocms_pid], SOURCE.[name], SOURCE.[view], SOURCE.[template_id], SOURCE.[hide], SOURCE.[order], GETUTCDATE(), GETUTCDATE()) OUTPUT inserted.[ocms_iid]; END END GO ALTER AUTHORIZATION ON [dbo].[ocms_createPropertyItem] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_createView] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_createView] @name nvarchar(255), @parent_iid bigint AS BEGIN SET NOCOUNT ON; DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); DECLARE @template_id bigint = (SELECT TOP(1) [ocms_tid] FROM [dbo].[ocms_templates] as t WHERE t.[name] = 'view'); IF ISNULL(@name, '') = '' THROW 61010, 'name missing', 1; IF EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [name] = @name) THROW 61110, 'name already exists', 1; IF @site is null THROW 61110, 'site does not exist', 1; SELECT @parent_iid = [ocms_iid] FROM [dbo].[ocms_items] as i WHERE [ocms_iid] = @parent_iid AND (i.[parent_iid] is null OR i.[view] = 1); --apply site as fallback SET @parent_iid = ISNULL(@parent_iid, @site); --get last ocms_iid DECLARE @lastiid int = ISNULL ( (SELECT MAX(ISNULL(p.[ocms_iid], ap.[ocms_iid])) FROM [dbo].[ocms_items] as p FULL OUTER JOIN [ocms_archive__items] as ap on p.[ocms_iid] = ap.[ocms_iid]) ,0); -- get locales setting DECLARE @locales TABLE([locale] varchar(5), [order] int); INSERT INTO @locales SELECT * FROM [dbo].[ocms_locales](); -- add item DECLARE @output TABLE([ocms_iid] bigint); DECLARE @ocms_iid bigint; MERGE [dbo].[ocms_items] as TARGET USING (VALUES( @site ,NULL ,@name ,1 ,@template_id ,0 ,999 -- append always )) as SOURCE ([parent_iid] ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order]) ON TARGET.[name] = SOURCE.[name] WHEN NOT MATCHED BY TARGET THEN INSERT ([ocms_iid] ,[parent_iid] ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order] ,[DateCreated] ,[DateModified]) VALUES(@lastiid + 1, SOURCE.[parent_iid], SOURCE.[ocms_pid], SOURCE.[name], SOURCE.[view], SOURCE.[template_id], SOURCE.[hide], SOURCE.[order], GETUTCDATE(), GETUTCDATE()) OUTPUT inserted.[ocms_iid] INTO @output; SELECT TOP(1) @ocms_iid = [ocms_iid] FROM @output; -- add navigation -- update nav table UPDATE n SET n.[parent_iid] = i.[parent_iid] FROM [dbo].[ocms_navigation] as n JOIN [ocms_items] as i ON n.[ocms_iid] = i.[ocms_iid]; DECLARE @newnav [dbo].[ocms_type_navigation_base]; DECLARE @suffix int = 0; INSERT INTO @newnav SELECT @ocms_iid, [locale], @name + '_' + [locale] FROM @locales as l WHERE l.[locale] <> '*'; WHILE EXISTS (SELECT * FROM [dbo].[ocms_navigation] as cn JOIN @newnav as nn ON cn.[parent_iid] = @parent_iid AND cn.[alias] = nn.[alias]) BEGIN SET @suffix = @suffix + 1; UPDATE @newnav SET [alias] = @name + '_' + [locale] + CAST(@suffix as varchar(3)); END EXECUTE [dbo].[ocms_merge_navigation] @newnav; --output SELECT @ocms_iid; END GO ALTER AUTHORIZATION ON [dbo].[ocms_createView] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_deleteItem] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_deleteItem] @ocms_iid bigint AS BEGIN SET NOCOUNT ON; DECLARE @children TABLE([ocms_iid] bigint, [parent_iid] bigint); with cte as ( select [ocms_iid], [parent_iid] from [ocms_items] as i WHERE i.[parent_iid] = @ocms_iid --only children and below UNION ALL select i.[ocms_iid], i.[parent_iid] from [ocms_items] as i JOIN cte on cte.ocms_iid = i.[parent_iid] ) insert into @children select * from cte; --first delete childrens properties, bc else the foreign key constraint will prevent to continue */ DELETE p OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__properties] FROM [dbo].[ocms_properties] as p WHERE p.[ocms_iid] in (SELECT c.[ocms_iid] FROM @children as c); -- only children's as selected at beginning / DELETE i OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__items] FROM [ocms_items] as i WHERE i.[ocms_iid] in (SELECT c.[ocms_iid] FROM @children as c);; -- only children as selected at beginning / DELETE p OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__properties] FROM [dbo].[ocms_properties] as p WHERE p.[ocms_iid] = @ocms_iid; -- only children's as selected at beginning / DELETE FROM [ocms_items] OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__items] WHERE [ocms_iid] = @ocms_iid; SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_archive__items] WHERE [ocms_iid] = @ocms_iid; END GO ALTER AUTHORIZATION ON [dbo].[ocms_deleteItem] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_getAvailableTemplates] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_getAvailableTemplates] @ocms_iid bigint ,@ocms_pid bigint ,@property_key varchar(50) AS BEGIN SET NOCOUNT ON; IF NOT EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [ocms_iid] = @ocms_iid) THROW 61010, 'item does not exist', 1; DECLARE @TP TABLE( [ocms_tpid] [bigint] NOT NULL, [ocms_pid] [bigint], [condition] [varchar](max) NULL ); INSERT INTO @TP SELECT tp.[ocms_tpid], p.[ocms_pid], tp.[condition] FROM [dbo].[ocms_items] as i JOIN [dbo].[ocms_templates] as t on i.[template_id] = t.[ocms_tid] JOIN [dbo].[ocms_template_properties] as tp ON t.[ocms_tid] = tp.[ocms_tid] AND tp.[type] = 'array' LEFT JOIN [dbo].[ocms_properties] as p ON i.[ocms_iid] = p.[ocms_iid] AND p.[key] = tp.[key] WHERE i.[ocms_iid] = @ocms_iid AND (p.[ocms_pid] = @ocms_pid OR (@ocms_pid is null AND tp.[key] = @property_key)) AND tp.[type] = 'array'; IF NOT EXISTS (SELECT * FROM @TP) THROW 61010, 'items''s property type is not array', 1; DECLARE @condition varchar(max); SET @condition = ISNULL((SELECT TOP(1) [condition] FROM @TP), ''); DECLARE @TIDS TABLE ([ocms_tid] bigint); IF LEFT(@condition, 1) = '{' AND RIGHT(@condition, 1) = '}' BEGIN INSERT INTO @TIDS SELECT RTRIM(LTRIM(value)) FROM string_split(SUBSTRING(@condition,2,LEN(@condition) - 2), ','); END ELSE IF @condition <> '' BEGIN INSERT INTO @TIDS SELECT [ocms_tid] FROM [ocms_templates] WHERE [name] like @condition; END --output SELECT t.[ocms_tid],t.[name] FROM [dbo].[ocms_templates] as t JOIN @TIDS as tids ON t.[ocms_tid] = tids.ocms_tid; --select STUFF( -- (SELECT ',' + [name] as [text()] -- FROM [dbo].[ocms_templates] -- WHERE name like 'section%' -- FOR XML PATH, TYPE).value(N'.[1]', N'nvarchar(max)') -- ,1,1,'') END GO ALTER AUTHORIZATION ON [dbo].[ocms_getAvailableTemplates] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_getFullTree] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_getFullTree] @locale varchar(5) AS BEGIN /* FULL TREE is only intended for OCMS admin portal Hidden items will be shown ! */ SET NOCOUNT ON; -- get basics DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); IF @site is null THROW 61110, 'site does not exist', 1; --get locales DECLARE @locales TABLE([locale] varchar(5), [order] int); INSERT INTO @locales SELECT * FROM [dbo].[ocms_locales](); -- calculate tree and paths DECLARE @itemtree TABLE( [ocms_iid] [bigint] NOT NULL, [parent_iid] [bigint] NULL, [ocms_pid] [bigint] NULL, [name] [nvarchar](255) NULL, [view] [bit] NOT NULL, [template_id] [bigint] NULL, [hide] [bit] NOT NULL, [order] [int] NOT NULL, [DateCreated] datetime null, [DateModified] datetime null, [level] int, [new_order] int ); WITH cteLevels as ( SELECT t.* , cast(0 as int) as [level] FROM [dbo].[ocms_items] t WHERE t.[ocms_iid] = @site UNION ALL SELECT t.* , CAST(c.[level] + 1 as int) as [level] FROM [dbo].[ocms_items] t inner JOIN cteLevels c on t.[parent_iid] = c.[ocms_iid] ) INSERT INTO @itemtree SELECT t.* , ROW_NUMBER() OVER (PARTITION BY [parent_iid] ORDER BY [order], [ocms_iid]) as [new_order] FROM cteLevels as t; --WHERE [hide] = 0; -- output site properties WITH SP As ( SELECT p.* , ROW_NUMBER() OVER (PARTITION BY p.[ocms_iid], p.[key] ORDER BY CAST((CASE WHEN p.[locale] = '*' THEN 1 ELSE 0 END) as int)) as 'rwi' FROM @itemtree as it JOIN [dbo].[ocms_properties] as p ON it.[ocms_iid] = p.[ocms_iid] WHERE it.[level] = 0 --site AND (p.[locale] = @locale OR p.[locale] = '*') ) SELECT it.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @itemtree as it FULL OUTER JOIN [dbo].[ocms_template_properties] as tp ON it.[template_id] = tp.[ocms_tid] FULL OUTER JOIN SP as p ON p.[ocms_iid] = it.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) AND p.[rwi] = 1 -- only the right language or fallback WHERE it.[level] = 0; -- output locales SELECT * FROM @locales; -- output children SELECT it.* ,p.[key] as 'property_key' ,p.[locale] as 'property_locale' ,tpl.[name] as 'template_name' ,ROW_NUMBER() OVER (PARTITION BY it.[parent_iid] ORDER BY IIF(it.[view] = 1, 0, 1), it.[ocms_pid], it.[ORDER], it.[ocms_iid]) as 'item_order' FROM @itemtree as it LEFT JOIN [dbo].[ocms_templates] as tpl on it.[template_id] = tpl.[ocms_tid] LEFT JOIN [dbo].[ocms_properties] as p on it.[ocms_pid] = p.[ocms_pid]; --only arrays -- output childrens' properties ONLY arrays SELECT it.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,p.locale ,tp.[type] FROM @itemtree as it JOIN [dbo].[ocms_template_properties] as tp ON it.[template_id] = tp.[ocms_tid] FULL OUTER JOIN [dbo].[ocms_properties] as p ON p.[ocms_iid] = it.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) WHERE ISNULL(ISNULL(tp.[key], p.[key]),'') <> '' AND tp.[type] = 'array'; END GO ALTER AUTHORIZATION ON [dbo].[ocms_getFullTree] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_getItem] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_getItem] @ocms_iid bigint AS BEGIN SET NOCOUNT ON; -- get basics DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); IF @site is null THROW 61110, 'site does not exist', 1; --get locales DECLARE @locales TABLE([locale] varchar(5), [order] int); INSERT INTO @locales SELECT * FROM [dbo].[ocms_locales](); -- get viewtree and paths DECLARE @viewtree [dbo].[ocms_type_viewtree_full]; INSERT INTO @viewtree SELECT * FROM [dbo].[ocms_getFullViewTree](null, null) -- get full with all languages WHERE [ocms_iid] = @ocms_iid; -- only selected view --get itemtree DECLARE @itemtree [dbo].[ocms_type_itemtree]; INSERT INTO @itemtree SELECT * FROM [dbo].[ocms_getFullItemTree](@ocms_iid, 1); /*-----------------------------------------------------------------------------------------------------------------------------------------------------*/ -- output site properties SELECT t.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @itemtree as t FULL OUTER JOIN [dbo].[ocms_template_properties] as tp ON t.[template_id] = tp.[ocms_tid] FULL OUTER JOIN [dbo].[ocms_properties] as p ON p.[ocms_iid] = t.[ocms_iid] AND p.[value] is not null AND (tp.[key] = p.[key] OR tp.[key] is null) WHERE t.[level] = 0; -- output locales SELECT * FROM @locales; -- output item SELECT TOP(1) it.* ,p.[key] as 'property_key' ,p.[locale] as 'property_locale' ,tpl.[name] as 'template_name' ,ROW_NUMBER() OVER (PARTITION BY it.[parent_iid], it.[ocms_pid] ORDER BY it.[ORDER], it.[ocms_iid]) as 'item_order' FROM @itemtree as it --not necessary a view LEFT JOIN [dbo].[ocms_templates] as tpl on it.[template_id] = tpl.[ocms_tid] LEFT JOIN [dbo].[ocms_properties] as p on it.[ocms_pid] = p.ocms_pid and p.[value] is not null WHERE it.[ocms_iid] = @ocms_iid; -- item in focus -- output children SELECT it.* ,p.[key] as 'property_key' ,p.[locale] as 'property_locale' ,tpl.[name] as 'template_name' ,ROW_NUMBER() OVER (PARTITION BY it.[parent_iid], it.[ocms_pid] ORDER BY it.[ORDER], it.[ocms_iid]) as 'item_order' FROM @itemtree as it LEFT JOIN [dbo].[ocms_templates] as tpl on it.[template_id] = tpl.[ocms_tid] LEFT JOIN [dbo].[ocms_properties] as p on it.[ocms_pid] = p.ocms_pid and p.[value] is not null WHERE it.[ocms_iid] <> @ocms_iid AND it.[sub] = 1; -- output items properties WITH tp as ( SELECT tp_.*, ROW_NUMBER() OVER (ORDER BY tp_.[order], tp_.[ocms_tpid], tp_.[key]) as 'tpo', l.locale, l.[order] as [locorder] FROM [dbo].[ocms_template_properties] as tp_ CROSS JOIN @locales as l -- incl. fallback locale '*' ) SELECT it.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.locale ,tp.[type] ,tp.[mandatory] ,IIF(tp.[type] <> 'array', tp.[condition], '') as [condition] ,ROW_NUMBER() OVER (ORDER BY it.[ocms_iid], tp.[tpo], p.[ocms_pid]) as [order] FROM @itemtree as it JOIN tp ON it.[template_id] = tp.[ocms_tid] FULL OUTER JOIN [dbo].[ocms_properties] as p ON p.[ocms_iid] = it.[ocms_iid] AND p.[value] is not null AND (tp.[key] = p.[key] OR tp.[key] is null) AND p.[locale] = tp.[locale] WHERE ISNULL(ISNULL(tp.[key], p.[key]),'') <> '' AND it.[ocms_iid] = @ocms_iid; -- output items navs WITH nav as ( select [ocms_iid], [locale], [alias] from [dbo].[ocms_navigation] as n WHERE ISNULL(n.[alias], '') <> '' AND n.[locale] <> '*' UNION SELECT i.[ocms_iid], l.[locale], i.[name] FROM [dbo].[ocms_items] as i CROSS JOIN @locales as l WHERE i.[parent_iid] = @site AND i.[name] = 'index' and l.[locale] <> '*' )SELECT l.[locale] ,n.[alias] ,vt.[path] FROM @viewtree as vt CROSS JOIN @locales as l LEFT JOIN nav as n ON vt.[ocms_iid] = n.[ocms_iid] AND l.[locale] = n.[locale] WHERE vt.[ocms_iid] = @ocms_iid AND l.[locale] <> '*'; END GO ALTER AUTHORIZATION ON [dbo].[ocms_getItem] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_getItem_byName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_getItem_byName] @name nvarchar(255) AS BEGIN SET NOCOUNT ON; DECLARE @ocms_iid bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE [name] = @name); EXECUTE [dbo].[ocms_getItem] @ocms_iid; END GO ALTER AUTHORIZATION ON [dbo].[ocms_getItem_byName] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_getView] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_getView] @view_path varchar(255) ,@locale varchar(5) OUTPUT AS BEGIN SET NOCOUNT ON; IF ISNULL(@locale, '') = '' SET @locale = 'de'; -- fallback IF ISNULL(@view_path, '') = '' SET @view_path = 'index'; -- get basics DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); IF @site is null THROW 61110, 'site does not exist', 1; --get locales DECLARE @locales TABLE([locale] varchar(5), [order] int); INSERT INTO @locales SELECT * FROM [dbo].[ocms_locales](); -- get viewtree and paths DECLARE @view_iid bigint = null, @view_level int, @view_name nvarchar(255), @view_is_hidden bit; DECLARE @viewtree [dbo].[ocms_type_viewtree_full]; INSERT INTO @viewtree SELECT * FROM [dbo].[ocms_getFullViewTree](@view_path, null); -- any locale to be able to determine language from path SELECT TOP(1) @view_iid = it.[ocms_iid] , @view_level = it.[level] , @locale = it.[locale] -- will override the selected language , @view_name = it.[name] , @view_is_hidden = it.[hide] FROM @viewtree as it ORDER BY (CASE WHEN [focus] = 1 AND [locale] = @locale THEN 0 WHEN [focus] = 1 THEN 1 ELSE 2 END) ASC; --get itemtree DECLARE @itemtree [dbo].[ocms_type_itemtree]; INSERT INTO @itemtree SELECT * FROM [dbo].[ocms_getFullItemTree](@view_iid, @view_is_hidden); -- items are not localized --get properties DECLARE @PROP TABLE( [ocms_pid] [bigint] NOT NULL, [ocms_iid] [bigint] NOT NULL, [key] [varchar](50) NULL, [value] [nvarchar](max) NOT NULL, [DateModified] [datetime] NULL ); WITH SP As ( SELECT p.* ,it.[focus] ,it.[level] , ROW_NUMBER() OVER (PARTITION BY p.[ocms_iid], p.[key] ORDER BY CAST((CASE WHEN p.[locale] = '*' THEN 1 ELSE 0 END) as int)) as 'rwi' FROM @itemtree as it JOIN [dbo].[ocms_properties] as p ON it.[ocms_iid] = p.[ocms_iid] WHERE (it.[level] = 0 --site OR it.[sub] = 1 OR it.[sitepropsub] = 1 OR it.[focus] = 1 OR it.[parent_iid] = @site) -- or itms below selected AND (p.[locale] = @locale OR p.[locale] = '*') ) INSERT INTO @PROP SELECT [ocms_pid],[ocms_iid],[key],[value],[DateModified] FROM SP WHERE rwi = 1; DECLARE @translations TABLE ( [ocms_tln] [bigint] NOT NULL, [context_typ] [nvarchar](15) NOT NULL, [context] [bigint] NULL, [value] [nvarchar](255) NOT NULL, [translation] [nvarchar](255) NOT NULL, [locale] [varchar](5) NOT NULL ); /* outputs *********************************************************************************************************************************************************/ -- output nav SELECT vt.[ocms_iid] ,[parent_iid] ,vt.[ocms_pid] ,[name] ,ISNULL(p.[value], vt.[name]) as [title] ,[view] ,[template_id] ,[hide] ,[new_order] as [order] , [path], [level], [sub], [focus], [nav] FROM @viewtree as vt -- vt must be filtered by locale LEFT JOIN [dbo].[ocms_properties] as p ON vt.[ocms_iid] = p.[ocms_iid] AND p.[key] = 'title' AND p.[locale] = vt.[locale] -- ! localized WHERE [nav] = 1 AND vt.[locale] = @locale; -- output site properties SELECT vt.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @viewtree as vt -- site is part if viewtree // -- vt must be filtered by locale FULL OUTER JOIN [dbo].[ocms_template_properties] as tp ON vt.[template_id] = tp.[ocms_tid] FULL OUTER JOIN @PROP as p ON p.[ocms_iid] = vt.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) -- properties are ! localized, but already filtered for @PROP WHERE vt.[ocms_iid] = @site AND vt.[locale] = @locale UNION SELECT NULL as [ocms_iid] ,NULL as [ocms_pid] ,'DateModified' as [key] ,FORMAT((SELECT MAX([DateModified]) FROM @PROP),'yyyy-MM-ddTHH:mm:ssZ') as [value] ,'string'; INSERT INTO @translations SELECT * from [dbo].[ocms_translations] as TL WHERE TL.[context_typ] = 'site' AND TL.[locale] = @locale; -- output locales WITH pd as (SELECT DISTINCT [ocms_iid], [path], [locale] FROM @viewtree WHERE [ocms_iid] = @view_iid) SELECT pd.* , CAST(IIF(l.[locale] = @locale, 1, 0) as bit) as 'active' FROM @locales as l JOIN pd ON l.[locale] = pd.[locale] WHERE l.[locale] <> '*'; -- output view properties SELECT vt.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @viewtree as vt -- vt must be filtered by locale FULL OUTER JOIN [dbo].[ocms_template_properties] as tp ON vt.[template_id] = tp.[ocms_tid] FULL OUTER JOIN @PROP as p ON p.[ocms_iid] = vt.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) -- properties are ! localized, but already filtered for @PROP WHERE vt.[focus] = 1 AND ISNULL(ISNULL(tp.[key], p.[key]),'') <> '' AND vt.[locale] = @locale; INSERT INTO @translations SELECT * from [dbo].[ocms_translations] as TL WHERE TL.[context] = @view_iid AND TL.[locale] = @locale; --context = 'view' and all other context_types -- output children SELECT it.* ,tpl.[partial_view] ,tpl.[name] as [template_name] ,ROW_NUMBER() OVER (PARTITION BY it.[parent_iid], it.[ocms_pid] ORDER BY it.[ORDER], it.[ocms_iid]) as 'item_order' FROM @itemtree as it -- items are not localized LEFT JOIN [dbo].[ocms_templates] as tpl on it.[template_id] = tpl.[ocms_tid] WHERE [sub] = 1 OR [sitepropsub] = 1 OR it.[parent_iid] = @site; --to include also site relevant children INSERT INTO @translations SELECT TL.* from @itemtree as it JOIN [dbo].[ocms_translations] as TL ON TL.[context_typ] = 'template' AND TL.[context] = it.[template_id] AND TL.[locale] = @locale; -- output childrens' properties SELECT it.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @itemtree as it -- items are not localized JOIN [dbo].[ocms_template_properties] as tp ON it.[template_id] = tp.[ocms_tid] -- properties are ! localized, but already filtered for @PROP FULL OUTER JOIN @PROP as p ON p.[ocms_iid] = it.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) WHERE ([sub] = 1 OR [sitepropsub] = 1 OR it.[parent_iid] = @site) AND [focus] = 0 AND ISNULL(ISNULL(tp.[key], p.[key]),'') <> ''; --output translations SELECT DISTINCT * FROM @translations; --output breadcrumbs WITH vws as( SELECT vt.[ocms_iid], [parent_iid], ISNULL(p.[value], vt.[name]) as [title], [path] FROM @viewtree as vt -- vt must be filtered by locale LEFT JOIN [dbo].[ocms_properties] as p ON vt.[ocms_iid] = p.[ocms_iid] AND p.[key] = 'title' AND p.[locale] = vt.[locale] -- ! localized ) , cte as ( SELECT vws.*, [title] as [breadcrumb], 0 as [level] FROM vws WHERE vws.[ocms_iid] = @view_iid UNION ALL SELECT vws.*, ( vws.[title] + ' > ' + cte.[breadcrumb]) as [breadcrumb] , [level] + 1 as [level] FROM vws JOIN cte ON vws.[ocms_iid] = cte.[parent_iid] ) select [title] , [path] , CASE WHEN [level] = 0 THEN (SELECT TOP(1) [breadcrumb] FROM cte as cte1 ORDER BY [level] DESC) ELSE NULL END as [breadcrumb] , ROW_NUMBER() OVER (ORDER BY [level] DESC) as [order] FROM cte; END GO ALTER AUTHORIZATION ON [dbo].[ocms_getView] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_getView_byName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_getView_byName] @name nvarchar(255) ,@locale varchar(5) ,@include_hidden bit AS BEGIN SET NOCOUNT ON; IF ISNULL(@locale, '') = '' SET @locale = 'de'; -- fallback DECLARE @view_path varchar(255) = 'index'; -- get basics DECLARE @site bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE i.[parent_iid] is null); IF @site is null THROW 61110, 'site does not exist', 1; --get locales DECLARE @locales TABLE([locale] varchar(5), [order] int); INSERT INTO @locales SELECT * FROM [dbo].[ocms_locales](); -- get viewtree and paths DECLARE @view_iid bigint = null, @view_level int, @view_name nvarchar(255); DECLARE @viewtree [dbo].[ocms_type_viewtree_full]; INSERT INTO @viewtree SELECT * FROM [dbo].[ocms_getFullViewTree](@view_path, null); -- any locale to be able to determine language from path DECLARE @tgt_ocms_iid bigint = (SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_items] as i WHERE [name] = @name and (i.[hide] = 0 OR @include_hidden = 1)); SELECT TOP(1) @view_iid = it.[ocms_iid] , @view_level = it.[level] , @locale = it.[locale] -- will override the selected language , @view_name = it.[name] FROM @viewtree as it WHERE it.[ocms_iid] = @tgt_ocms_iid ORDER BY (CASE WHEN [focus] = 1 AND [locale] = @locale THEN 0 WHEN [focus] = 1 THEN 1 ELSE 2 END) ASC; --get itemtree DECLARE @itemtree [dbo].[ocms_type_itemtree]; INSERT INTO @itemtree SELECT * FROM [dbo].[ocms_getFullItemTree](@view_iid, @include_hidden); -- items are not localized --get properties DECLARE @PROP TABLE( [ocms_pid] [bigint] NOT NULL, [ocms_iid] [bigint] NOT NULL, [key] [varchar](50) NULL, [value] [nvarchar](max) NOT NULL, [DateModified] [datetime] NULL ); WITH SP As ( SELECT p.* ,it.[focus] ,it.[level] , ROW_NUMBER() OVER (PARTITION BY p.[ocms_iid], p.[key] ORDER BY CAST((CASE WHEN p.[locale] = '*' THEN 1 ELSE 0 END) as int)) as 'rwi' FROM @itemtree as it JOIN [dbo].[ocms_properties] as p ON it.[ocms_iid] = p.[ocms_iid] WHERE (it.[level] = 0 --site OR it.[sub] = 1 OR it.[sitepropsub] = 1 OR it.[focus] = 1 OR it.[parent_iid] = @site) -- or itms below selected AND (p.[locale] = @locale OR p.[locale] = '*') ) INSERT INTO @PROP SELECT [ocms_pid],[ocms_iid],[key],[value],[DateModified] FROM SP WHERE rwi = 1; DECLARE @translations TABLE ( [ocms_tln] [bigint] NOT NULL, [context_typ] [nvarchar](15) NOT NULL, [context] [bigint] NULL, [value] [nvarchar](255) NOT NULL, [translation] [nvarchar](255) NOT NULL, [locale] [varchar](5) NOT NULL ); /* outputs *********************************************************************************************************************************************************/ -- output nav SELECT vt.[ocms_iid] ,[parent_iid] ,vt.[ocms_pid] ,[name] ,ISNULL(p.[value], vt.[name]) as [title] ,[view] ,[template_id] ,[hide] ,[new_order] as [order] , [path], [level], [sub], [focus], [nav] FROM @viewtree as vt -- vt must be filtered by locale LEFT JOIN [dbo].[ocms_properties] as p ON vt.[ocms_iid] = p.[ocms_iid] AND p.[key] = 'title' AND p.[locale] = vt.[locale] -- ! localized WHERE [nav] = 1 AND vt.[locale] = @locale; -- output site properties SELECT vt.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @viewtree as vt -- site is part if viewtree // -- vt must be filtered by locale FULL OUTER JOIN [dbo].[ocms_template_properties] as tp ON vt.[template_id] = tp.[ocms_tid] FULL OUTER JOIN @PROP as p ON p.[ocms_iid] = vt.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) -- properties are ! localized, but already filtered for @PROP WHERE vt.[ocms_iid] = @site AND vt.[locale] = @locale UNION SELECT NULL as [ocms_iid] ,NULL as [ocms_pid] ,'DateModified' as [key] ,FORMAT((SELECT MAX([DateModified]) FROM @PROP),'yyyy-MM-ddTHH:mm:ssZ') as [value] ,'string'; INSERT INTO @translations SELECT * from [dbo].[ocms_translations] as TL WHERE TL.[context_typ] = 'site' AND TL.[locale] = @locale; -- output locales WITH pd as (SELECT DISTINCT [ocms_iid], [path], [locale] FROM @viewtree WHERE [ocms_iid] = @view_iid) SELECT pd.* , CAST(IIF(l.[locale] = @locale, 1, 0) as bit) as 'active' FROM @locales as l JOIN pd ON l.[locale] = pd.[locale] WHERE l.[locale] <> '*'; -- output view properties SELECT vt.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @viewtree as vt -- vt must be filtered by locale FULL OUTER JOIN [dbo].[ocms_template_properties] as tp ON vt.[template_id] = tp.[ocms_tid] FULL OUTER JOIN @PROP as p ON p.[ocms_iid] = vt.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) -- properties are ! localized, but already filtered for @PROP WHERE vt.[focus] = 1 AND ISNULL(ISNULL(tp.[key], p.[key]),'') <> '' AND vt.[locale] = @locale; INSERT INTO @translations SELECT * from [dbo].[ocms_translations] as TL WHERE TL.[context] = @view_iid AND TL.[locale] = @locale; --context = 'view' and all other context_types -- output children SELECT it.* ,tpl.[partial_view] ,tpl.[name] as [template_name] ,ROW_NUMBER() OVER (PARTITION BY it.[parent_iid], it.[ocms_pid] ORDER BY it.[ORDER], it.[ocms_iid]) as 'item_order' FROM @itemtree as it -- items are not localized LEFT JOIN [dbo].[ocms_templates] as tpl on it.[template_id] = tpl.[ocms_tid] WHERE [sub] = 1 OR [sitepropsub] = 1 OR it.[parent_iid] = @site; --to include also site relevant children INSERT INTO @translations SELECT TL.* from @itemtree as it JOIN [dbo].[ocms_translations] as TL ON TL.[context_typ] = 'template' AND TL.[context] = it.[template_id] AND TL.[locale] = @locale; -- output childrens' properties SELECT it.[ocms_iid] ,p.[ocms_pid] ,ISNULL(tp.[key], p.[key]) as [key] ,IIF(ISNULL(tp.[mandatory],0) = 0, p.[value], ISNULL(p.[value],'')) as [value] ,tp.[type] FROM @itemtree as it -- items are not localized JOIN [dbo].[ocms_template_properties] as tp ON it.[template_id] = tp.[ocms_tid] -- properties are ! localized, but already filtered for @PROP FULL OUTER JOIN @PROP as p ON p.[ocms_iid] = it.[ocms_iid] AND (tp.[key] = p.[key] OR tp.[key] is null) WHERE ([sub] = 1 OR [sitepropsub] = 1 OR it.[parent_iid] = @site) AND [focus] = 0 AND ISNULL(ISNULL(tp.[key], p.[key]),'') <> ''; --output translations SELECT DISTINCT * FROM @translations; --output breadcrumbs WITH vws as( SELECT vt.[ocms_iid], [parent_iid], ISNULL(p.[value], vt.[name]) as [title], [path] FROM @viewtree as vt -- vt must be filtered by locale LEFT JOIN [dbo].[ocms_properties] as p ON vt.[ocms_iid] = p.[ocms_iid] AND p.[key] = 'title' AND p.[locale] = vt.[locale] -- ! localized ) , cte as ( SELECT vws.*, [title] as [breadcrumb], 0 as [level] FROM vws WHERE vws.[ocms_iid] = @view_iid UNION ALL SELECT vws.*, ( vws.[title] + ' > ' + cte.[breadcrumb]) as [breadcrumb] , [level] + 1 as [level] FROM vws JOIN cte ON vws.[ocms_iid] = cte.[parent_iid] ) select [title] , [path] , CASE WHEN [level] = 0 THEN (SELECT TOP(1) [breadcrumb] FROM cte as cte1 ORDER BY [level] DESC) ELSE NULL END as [breadcrumb] , ROW_NUMBER() OVER (ORDER BY [level] DESC) as [order] FROM cte; END GO ALTER AUTHORIZATION ON [dbo].[ocms_getView_byName] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_merge_navigation] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_merge_navigation] @newnav [dbo].[ocms_type_navigation_base] READONLY AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- update nav table UPDATE n SET n.[parent_iid] = i.[parent_iid] FROM [dbo].[ocms_navigation] as n JOIN [ocms_items] as i ON n.[ocms_iid] = i.[ocms_iid]; -- merge nav WITH np as ( -- make sure nav are allowed by locales and path constraints SELECT n.* ,i.[parent_iid] FROM @newnav as n JOIN [dbo].[ocms_items] as i ON n.[ocms_iid] = i.[ocms_iid] AND [view] = 1 FULL OUTER JOIN [dbo].[ocms_locales]() as l on n.[locale] = l.[locale] AND l.[locale] <> '*' WHERE NOT EXISTS (SELECT * FROM [dbo].[ocms_navigation] as cn WHERE cn.[parent_iid] = i.[parent_iid] AND cn.[alias] = n.[alias] AND [cn].[ocms_iid] <> n.[ocms_iid]) AND i.[name] <> 'index' -- nav not allowed for index AND n.[alias] not in ('index') -- keyword index not allowed ) MERGE [dbo].[ocms_navigation] as TARGET USING np as SOURCE ON TARGET.[locale] = SOURCE.[locale] AND TARGET.[ocms_iid] = SOURCE.[ocms_iid] WHEN MATCHED AND SOURCE.[alias] is null THEN DELETE WHEN MATCHED THEN UPDATE SET [alias] = LOWER(SOURCE.[alias]) WHEN NOT MATCHED BY TARGET THEN INSERT ([ocms_iid], [locale], [alias]) VALUES (SOURCE.[ocms_iid], SOURCE.[locale], LOWER(SOURCE.[alias])); END GO ALTER AUTHORIZATION ON [dbo].[ocms_merge_navigation] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_merge_properties] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_merge_properties] @newprop [dbo].[ocms_type_properties_base] READONLY AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @lastpid int = ISNULL ( (SELECT MAX(ISNULL(p.[ocms_pid], ap.[ocms_pid])) FROM [dbo].[ocms_properties] as p FULL OUTER JOIN [ocms_archive__properties] as ap on p.[ocms_pid] = ap.[ocms_pid]) ,0); WITH np as ( -- make sure properties are allowed by templates SELECT [pid] = isnull(pp.[ocms_pid], ROW_NUMBER() OVER (PARTITION BY pp.[ocms_pid] order BY tp.[ocms_tpid], n.[key]) + @lastpid) ,n.* ,tp.[type] FROM @newprop as n JOIN [dbo].[ocms_items] as i ON n.[ocms_iid] = i.[ocms_iid] JOIN [dbo].[ocms_templates] as t ON i.[template_id] = t.[ocms_tid] JOIN [dbo].[ocms_template_properties] as tp ON t.[ocms_tid] = tp.[ocms_tid] AND n.[key] = tp.[key] LEFT JOIN [dbo].[ocms_properties] as pp ON pp.[key] = n.[key] and pp.[locale] = n.[locale] AND pp.[ocms_iid] = n.[ocms_iid] ) MERGE [dbo].[ocms_properties] as TARGET USING np as SOURCE ON TARGET.[key] = SOURCE.[key] and TARGET.[locale] = SOURCE.[locale] AND TARGET.[ocms_iid] = SOURCE.[ocms_iid] WHEN MATCHED AND ISNULL(SOURCE.[value], '') = '' AND SOURCE.[type] <> 'array' THEN DELETE WHEN MATCHED AND TARGET.[Value] <> SOURCE.[value] THEN UPDATE SET [value] = SOURCE.[value], [DateModified] = GETUTCDATE() WHEN NOT MATCHED BY TARGET THEN INSERT ([ocms_pid], [ocms_iid], [key], [value], [locale], [DateCreated], [DateModified]) VALUES (SOURCE.[pid], SOURCE.[ocms_iid], SOURCE.[key], SOURCE.[value], SOURCE.[locale], GETUTCDATE(), GETUTCDATE()) OUTPUT ISNULL(inserted.[ocms_pid], deleted.[ocms_pid]), $action, inserted.[ocms_iid], inserted.[key], inserted.[value], inserted.[locale], inserted.[DateCreated], inserted.[DateModified], NULL, NULL, deleted.[ocms_iid], deleted.[key], deleted.[value], deleted.[locale], deleted.[DateCreated], deleted.[DateModified], NULL, NULL INTO [dbo].[ocms_log__properties] ; END GO ALTER AUTHORIZATION ON [dbo].[ocms_merge_properties] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_recoverItem] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_recoverItem] @ocms_iid bigint AS BEGIN SET NOCOUNT ON; SET IDENTITY_INSERT [dbo].[ocms_items] ON; insert into ocms_items ([ocms_iid] ,[parent_iid] ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order] ,[DateCreated] ,[DateModified]) select [ocms_iid] ,[parent_iid] ,[ocms_pid] ,[name] ,[view] ,[template_id] ,[hide] ,[order] ,[DateCreated] ,[DateModified] from ocms_archive__items where ocms_iid = @ocms_iid SET IDENTITY_INSERT [dbo].[ocms_items] OFF; SET IDENTITY_INSERT [dbo].[ocms_properties] ON; insert into ocms_properties ([ocms_pid] ,[ocms_iid] ,[key] ,[value] ,[locale] ,[DateCreated] ,[DateModified]) select [ocms_pid] ,[ocms_iid] ,[key] ,[value] ,[locale] ,[DateCreated] ,[DateModified] from ocms_archive__properties where ocms_iid = @ocms_iid SET IDENTITY_INSERT [dbo].[ocms_properties] OFF; END GO ALTER AUTHORIZATION ON [dbo].[ocms_recoverItem] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_setItemName] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_setItemName] @ocms_iid bigint, @name nvarchar(255) AS BEGIN SET NOCOUNT ON; IF NOT EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [ocms_iid] = @ocms_iid) THROW 61110, 'item does not exist', 1; IF EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [ocms_iid] = @ocms_iid AND [name] = 'index') THROW 61110, 'index cannot be renamed', 1; IF ISNULL(@name, '') = '' THROW 61010, 'name missing', 1; IF EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [name] = @name AND [ocms_iid] <> @ocms_iid) THROW 61110, 'name already exists', 1; DECLARE @OUTPUT TABLE ([ocms_iid] bigint, [name] nvarchar(255)); UPDATE i SET [name] = @name ,[DateModified] = GETUTCDATE() OUTPUT inserted.[ocms_iid], inserted.[name] INTO @OUTPUT FROM [dbo].[ocms_items] as i WHERE i.[ocms_iid] = @ocms_iid; SELECT TOP(1) * FROM @OUTPUT; END GO ALTER AUTHORIZATION ON [dbo].[ocms_setItemName] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_setItemOrder] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_setItemOrder] @ocms_iid_csv varchar(2000) AS BEGIN SET NOCOUNT ON; DECLARE @neworder TABLE([ocms_iid] bigint, [order] int); DECLARE @c char(1) = ','; --delimiter INSERT INTO @neworder SELECT value, idx = ROW_NUMBER() OVER (ORDER BY CHARINDEX(@c + value + @c, @c + @ocms_iid_csv + @c)) FROM STRING_SPLIT(@ocms_iid_csv, ','); DECLARE @parents TABLE([parent_iid] bigint); INSERT INTO @parents SELECT DISTINCT [parent_iid] FROM [dbo].[ocms_items] as i JOIN @neworder as no ON i.[ocms_iid] = no.[ocms_iid] WHERE i.[parent_iid] is not null; select * from @parents IF (SELECT COUNT(*) FROM @parents) <> 1 THROW 61010, 'order can only be set for exact one parent', 1; DECLARE @parent_iid bigint = (SELECT TOP(1) [parent_iid] FROM @parents); UPDATE i SET [order] = ISNULL(no.[order], 999) OUTPUT inserted.[ocms_iid], inserted.[order] FROM [dbo].[ocms_items] as i LEFT JOIN @neworder as no ON i.[ocms_iid] = no.[ocms_iid] WHERE i.[parent_iid] = @parent_iid; END GO ALTER AUTHORIZATION ON [dbo].[ocms_setItemOrder] TO SCHEMA OWNER GO /****** Object: StoredProcedure [dbo].[ocms_setViewItem_HiddenStatus] Script Date: 13/10/2022 21:16:40 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_setViewItem_HiddenStatus] @ocms_iid bigint, @hidden bit AS BEGIN SET NOCOUNT ON; IF NOT EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [ocms_iid] = @ocms_iid) THROW 61110, 'item does not exist', 1; IF NOT EXISTS (SELECT * FROM [dbo].[ocms_items] WHERE [ocms_iid] = @ocms_iid AND [view] = 1) THROW 61110, 'item is not a view', 1; DECLARE @OUTPUT TABLE ([ocms_iid] bigint, [name] nvarchar(255), [hide] bit); UPDATE i SET i.[hide] = @hidden OUTPUT inserted.[ocms_iid], inserted.[name], inserted.[hide] INTO @OUTPUT FROM [dbo].[ocms_items] as i WHERE i.[ocms_iid] = @ocms_iid AND [view] = 1; SELECT TOP(1) * FROM @OUTPUT; END GO ALTER AUTHORIZATION ON [dbo].[ocms_setViewItem_HiddenStatus] TO SCHEMA OWNER GO USE [master] GO ALTER DATABASE [site_fuchs] SET READ_WRITE GO