diff --git a/.gitignore b/.gitignore index a510a17..c918eb9 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,10 @@ bin/ obj/ +# SSDT / SQL database project caches (regenerated) +*.dbmdl +*.jfm + # NuGet packages/ *.nupkg diff --git a/Fuchs_Database/FuchsDatabase.slnx b/Fuchs_Database/FuchsDatabase.slnx new file mode 100644 index 0000000..ce275a3 --- /dev/null +++ b/Fuchs_Database/FuchsDatabase.slnx @@ -0,0 +1,6 @@ + + + + + + diff --git a/Fuchs_Database/FuchsDatabase.sqlproj b/Fuchs_Database/FuchsDatabase.sqlproj new file mode 100644 index 0000000..b9fbe26 --- /dev/null +++ b/Fuchs_Database/FuchsDatabase.sqlproj @@ -0,0 +1,424 @@ + + + + Debug + AnyCPU + FuchsDatabase + 2.0 + 4.1 + {c062672e-866d-4c74-b6de-8d660a42e885} + Microsoft.Data.Tools.Schema.Sql.Sql170DatabaseSchemaProvider + Database + + + FuchsDatabase + FuchsDatabase + 1033, CI + BySchemaAndSchemaType + True + v4.7.2 + CS + Properties + False + True + True + + + bin\Release\ + $(MSBuildProjectName).sql + False + pdbonly + true + false + true + prompt + 4 + + + bin\Debug\ + $(MSBuildProjectName).sql + false + true + full + false + true + true + prompt + 4 + + + 11.0 + + True + 11.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Fuchs_Database/Security/fds_rwe.sql b/Fuchs_Database/Security/fds_rwe.sql new file mode 100644 index 0000000..6a2b978 --- /dev/null +++ b/Fuchs_Database/Security/fds_rwe.sql @@ -0,0 +1,7 @@ +CREATE ROLE [fds_rwe] + AUTHORIZATION [dbo]; + + +GO +ALTER ROLE [fds_rwe] ADD MEMBER [fuchs_fds]; + diff --git a/Fuchs_Database/Security/fuchs_enc_1.sql b/Fuchs_Database/Security/fuchs_enc_1.sql new file mode 100644 index 0000000..eee1734 --- /dev/null +++ b/Fuchs_Database/Security/fuchs_enc_1.sql @@ -0,0 +1,15 @@ +CREATE SYMMETRIC KEY [fuchs_enc_1] + AUTHORIZATION [dbo] + WITH ALGORITHM = AES_256 + ENCRYPTION BY PASSWORD = N'lwppdri?q{jdzus&bkuaheklmsFT7_&#$!~ + + 10 + + + Data Source=MSSQL4.NBG4.DOMAINXYZ.DE,10439;Initial Catalog=site_fuchs;Persist Security Info=False;User ID=ott1;Pooling=False;Multiple Active Result Sets=False;Connect Timeout=60;Encrypt=True;Trust Server Certificate=True;Command Timeout=0 + + + + + {c062672e-866d-4c74-b6de-8d660a42e885} + FuchsDatabase + + + + + + Version + 1 + + + + + PlanGenerationType + SqlDeploymentOptions + + + AllowExistingModelErrors + False + + + AllowIncompatiblePlatform + False + + + AllowTableRecreation + True + + + BackupDatabaseBeforeChanges + False + + + IgnoreIndexesStatisticsOnEnclaveEnabledColumns + False + + + BlockOnPossibleDataLoss + True + + + BlockWhenDriftDetected + False + + + CompareUsingTargetCollation + False + + + CommentOutSetVarDeclarations + False + + + CreateNewDatabase + False + + + DeployDatabaseInSingleUserMode + False + + + DisableAndReenableDdlTriggers + True + + + DisableIndexesForDataPhase + True + + + DisableParallelismForEnablingIndexes + False + + + DoNotAlterChangeDataCaptureObjects + True + + + DoNotAlterReplicatedObjects + True + + + DropConstraintsNotInSource + True + + + DropDmlTriggersNotInSource + True + + + DropExtendedPropertiesNotInSource + True + + + DropIndexesNotInSource + True + + + DropPermissionsNotInSource + False + + + DropObjectsNotInSource + True + + + DropRoleMembersNotInSource + False + + + DropStatisticsNotInSource + True + + + GenerateSmartDefaults + False + + + HashObjectNamesInLogs + False + + + IgnoreDdlTriggerOrder + False + + + IgnoreDdlTriggerState + False + + + IgnoreObjectPlacementOnPartitionScheme + True + + + IgnoreAuthorizer + False + + + IgnoreDefaultSchema + False + + + IgnoreRouteLifetime + True + + + IgnoreCryptographicProviderFilePath + True + + + IgnoreComments + False + + + IgnoreWhitespace + True + + + IgnoreKeywordCasing + True + + + IgnoreSemicolonBetweenStatements + True + + + IgnorePartitionSchemes + False + + + IgnorePreDeployScript + False + + + IgnorePostDeployScript + False + + + IgnoreTablePartitionOptions + False + + + IgnoreWithNocheckOnCheckConstraints + False + + + IgnoreWithNocheckOnForeignKeys + False + + + IgnoreIdentitySeed + False + + + IgnoreIncrement + False + + + IgnoreFillFactor + True + + + IgnoreIndexPadding + True + + + IgnoreColumnCollation + False + + + IgnoreColumnOrder + False + + + IgnoreLockHintsOnIndexes + False + + + IgnoreTableOptions + False + + + IgnoreIndexOptions + False + + + IgnoreDmlTriggerOrder + False + + + IgnoreDmlTriggerState + False + + + IgnoreAnsiNulls + True + + + IgnoreQuotedIdentifiers + True + + + IgnoreUserSettingsObjects + False + + + IgnoreFilegroupPlacement + True + + + IgnoreFullTextCatalogFilePath + True + + + IgnoreFileAndLogFilePath + True + + + IgnoreLoginSids + True + + + IgnoreNotForReplication + False + + + IgnoreFileSize + True + + + IgnoreSensitivityClassifications + False + + + AllowUnsafeRowLevelSecurityDataMovement + False + + + IncludeCompositeObjects + False + + + IncludeTransactionalScripts + False + + + IsAlwaysEncryptedParameterizationEnabled + False + + + NoAlterStatementsToChangeCLRTypes + False + + + PopulateFilesOnFileGroups + True + + + PreserveIdentityLastValues + False + + + RegisterDataTierApplication + False + + + PerformIndexOperationsOnline + False + + + RebuildIndexesOfflineForDataPhase + False + + + RestoreSequenceCurrentValue + True + + + ScriptDatabaseCollation + False + + + ScriptDatabaseCompatibility + False + + + ScriptDatabaseOptions + False + + + ScriptDeployStateChecks + False + + + ScriptFileSize + False + + + ScriptNewConstraintValidation + True + + + ScriptRefreshModule + True + + + TargetDatabaseName + FuchsDatabase + + + TargetConnectionString + Integrated Security=True;Pooling=False;Connect Timeout=30 + + + TreatVerificationErrorsAsWarnings + False + + + UnmodifiableObjectWarnings + True + + + VerifyCollationCompatibility + True + + + VerifyDeployment + True + + + RunDeploymentPlanExecutors + False + + + AllowDropBlockingAssemblies + False + + + DoNotEvaluateSqlCmdVariables + True + + + DoNotDropAggregates + False + + + DoNotDropApplicationRoles + False + + + DoNotDropAssemblies + False + + + DoNotDropAsymmetricKeys + False + + + DoNotDropAudits + False + + + DoNotDropBrokerPriorities + False + + + DoNotDropCertificates + False + + + DoNotDropClrUserDefinedTypes + False + + + DoNotDropColumnEncryptionKeys + False + + + DoNotDropColumnMasterKeys + False + + + DoNotDropContracts + False + + + DoNotDropCredentials + False + + + DoNotDropDatabaseScopedCredentials + False + + + DoNotDropCryptographicProviders + False + + + DoNotDropDatabaseAuditSpecifications + False + + + DoNotDropDatabaseRoles + False + + + DoNotDropDatabaseTriggers + False + + + IgnoreDatabaseWorkloadGroups + False + + + DoNotDropDatabaseWorkloadGroups + False + + + IgnoreWorkloadClassifiers + False + + + DoNotDropWorkloadClassifiers + False + + + DoNotDropDefaults + False + + + DoNotDropEndpoints + False + + + DoNotDropErrorMessages + False + + + DoNotDropEventNotifications + False + + + DoNotDropEventSessions + False + + + DoNotDropExtendedProperties + False + + + DoNotDropExternalDataSources + False + + + DoNotDropExternalFileFormats + False + + + DoNotDropExternalLanguages + False + + + DoNotDropExternalLibraries + False + + + DoNotDropExternalModels + False + + + DoNotDropExternalStreamingJobs + False + + + DoNotDropExternalTables + False + + + DoNotDropExternalStreams + False + + + DoNotDropFilegroups + False + + + DoNotDropFiles + False + + + DoNotDropFileTables + False + + + DoNotDropFullTextCatalogs + False + + + DoNotDropFullTextStoplists + False + + + DoNotDropTableValuedFunctions + False + + + DoNotDropLinkedServerLogins + False + + + DoNotDropLinkedServers + False + + + DoNotDropLogins + False + + + DoNotDropMessageTypes + False + + + DoNotDropPartitionFunctions + False + + + DoNotDropPartitionSchemes + False + + + DoNotDropPermissions + False + + + DoNotDropQueues + False + + + DoNotDropRemoteServiceBindings + False + + + DoNotDropRoleMembership + False + + + DoNotDropRoutes + False + + + DoNotDropRules + False + + + DoNotDropScalarValuedFunctions + False + + + DoNotDropSearchPropertyLists + False + + + DoNotDropSecurityPolicies + False + + + DoNotDropSequences + False + + + DoNotDropServerAuditSpecifications + False + + + DoNotDropServerRoleMembership + False + + + DoNotDropServerRoles + False + + + DoNotDropServerTriggers + False + + + DoNotDropServices + False + + + DoNotDropSignatures + False + + + DoNotDropStoredProcedures + False + + + DoNotDropSymmetricKeys + False + + + DoNotDropSynonyms + False + + + DoNotDropTables + False + + + DoNotDropUserDefinedDataTypes + False + + + DoNotDropUserDefinedTableTypes + False + + + DoNotDropUsers + False + + + DoNotDropViews + False + + + DoNotDropXmlSchemaCollections + False + + + ExcludeAggregates + False + + + ExcludeApplicationRoles + False + + + ExcludeAssemblies + False + + + ExcludeAsymmetricKeys + False + + + ExcludeAudits + True + + + ExcludeBrokerPriorities + False + + + ExcludeCertificates + False + + + ExcludeClrUserDefinedTypes + False + + + ExcludeColumnEncryptionKeys + False + + + ExcludeColumnMasterKeys + False + + + ExcludeContracts + False + + + ExcludeCredentials + True + + + ExcludeDatabaseScopedCredentials + True + + + ExcludeCryptographicProviders + True + + + ExcludeDatabaseAuditSpecifications + True + + + ExcludeDatabaseRoles + False + + + ExcludeDatabaseTriggers + False + + + ExcludeDefaults + False + + + ExcludeEndpoints + True + + + ExcludeErrorMessages + True + + + ExcludeEventNotifications + False + + + ExcludeExternalDataSources + False + + + ExcludeExternalFileFormats + False + + + ExcludeExternalLanguages + False + + + ExcludeExternalLibraries + False + + + ExcludeExternalModels + False + + + ExcludeExternalStreamingJobs + False + + + ExcludeExternalTables + False + + + ExcludeExternalStreams + False + + + ExcludeEventSessions + True + + + ExcludeFilegroups + False + + + ExcludeFiles + True + + + ExcludeFileTables + False + + + ExcludeFullTextCatalogs + False + + + ExcludeFullTextStoplists + False + + + ExcludeTableValuedFunctions + False + + + ExcludeLinkedServerLogins + True + + + ExcludeLinkedServers + True + + + ExcludeLogins + True + + + ExcludeMessageTypes + False + + + ExcludePartitionFunctions + False + + + ExcludePartitionSchemes + False + + + ExcludeQueues + False + + + ExcludeRemoteServiceBindings + False + + + ExcludeRoutes + True + + + ExcludeRules + False + + + ExcludeScalarValuedFunctions + False + + + ExcludeSearchPropertyLists + False + + + ExcludeSecurityPolicies + False + + + ExcludeSequences + False + + + ExcludeServerAuditSpecifications + True + + + ExcludeServerRoleMembership + True + + + ExcludeServerRoles + True + + + ExcludeServerTriggers + True + + + ExcludeServices + False + + + ExcludeSignatures + False + + + ExcludeStoredProcedures + False + + + ExcludeSymmetricKeys + False + + + ExcludeSynonyms + False + + + ExcludeTables + False + + + ExcludeUserDefinedDataTypes + False + + + ExcludeUserDefinedTableTypes + False + + + ExcludeUsers + False + + + ExcludeViews + False + + + ExcludeXmlSchemaCollections + False + + + AllowExternalLibraryPaths + False + + + AllowExternalLanguagePaths + False + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlServerDdlTrigger + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlRoute + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlLinkedServerLogin + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlEndpoint + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlErrorMessage + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlFile + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlLogin + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlLinkedServer + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlCredential + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlDatabaseCredential + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlDatabaseEncryptionKey + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlMasterKey + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlDatabaseAuditSpecification + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlServerAudit + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlServerAuditSpecification + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlCryptographicProvider + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlUserDefinedServerRole + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlEventSession + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlDatabaseOptions + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlEventNotification + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlServerRoleMembership + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlDatabaseEventSession + ExcludedType + + + Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlAssemblyFile + ExcludedType + + + + + 2 + 100 + Equals_Objects,Not_Supported_Deploy + + + + dbo + 2023-10-06 10-15 fds__invoice_details + + + dbo + 2023-10-06 10-15 fds__invoice_items + + + dbo + 2023-10-06 10-15 fds__invoice_servicerequests + + + dbo + 2023-10-12 1709 fds__bankingtransactions + + + dbo + 2023-10-12 1709 fds__bankingtransactions_assigns + + + dbo + 2023-10-12 1709 fds__bankingtransactions_settings + + + dbo + 2024-02-22_fds__invoices + + + dbo + 2024-03-14__fds__invoices + + + dbo + 2024-04-29__fds__invoices + + + dbo + 2024-05-15 fds__invoices + + + dbo + 2024-07-29 1718 fds__invoice_servicerequests + + + dbo + 2024-11-13 fds__invoice_items + + + dbo + 2024-11-13 fds__invoices + + + dbo + 2024-11-16 fds__invoice_items + + + dbo + 2024-11-16 fds__invoices + + + dbo + 2025-12-03 0928 fds__invoice_items + + + dbo + 2025-12-03 0928 fds__invoices + + + dbo + 2025-12-18_1429__fds__invoice_items + + + dbo + 2025-12-18_1429__fds__invoices + + + dbo + 2026-01-08_1032 fds__invoice_details + + + dbo + 2026-01-08_1032 fds__invoice_items + + + dbo + 2026-01-08_1032 fds__invoices + + + dbo + 2026-01-28_1600 fds__invoice_details + + + dbo + 2026-01-28_1600 fds__invoice_items + + + dbo + 2026-01-28_1600 fds__invoices + + + dbo + 2026-01-28_1832 fds__invoice_details + + + dbo + 2026-01-28_1832 fds__invoice_items + + + dbo + 2026-01-28_1832 fds__invoices + + + dbo + 2026-03-02_1943 fds__invoice_details + + + dbo + 2026-03-02_1943 fds__invoice_items + + + dbo + 2026-03-02_1943 fds__invoices + + + dbo + 2026-04-21_1058 fds__invoice_details + + + dbo + 2026-04-21_1058 fds__invoice_items + + + dbo + 2026-04-21_1058 fds__invoices + + + dbo + 2026-05-18_1019 fds__invoice_details + + + dbo + 2026-05-18_1019 fds__invoice_items + + + dbo + 2026-05-18_1019 fds__invoices + + + dbo + bs_05d0e2b7c9124ec7bbcd613915ccfb88 + + + dbo + bs_31ca83d0030b4669b67a46728b4b439e + + + dbo + bs_5310baa29e8d40c99a1f991964b8f141 + + + dbo + bs_6188db7e852744658933d3a04f23e849 + + + dbo + bs_ea44799b83844adcb5e634cb845786e9 + + + dbo + email_list_2020 + + + dbo + email_list_2021 + + + dbo + t_8btst_mfr__steps + + + dbo + t_tqrcd_mfr__reports + + + dbo + t_ves6u_mfr__servicerequests + + + dbo + t_wo9hi_mfr__reports + + + dbo + ocms_archive__items + + + dbo + ocms_archive__properties + + + dbo + ocms_changelog + + + dbo + ocms_debug + + + dbo + ocms_items + + + dbo + ocms_items + ocms_items__ix0 + + + dbo + ocms_items + ocms_items__ix1 + + + dbo + ocms_log__properties + + + dbo + ocms_navigation + + + dbo + ocms_navigation + ocms_navigation__ix1 + + + dbo + ocms_properties + + + dbo + ocms_settings + + + dbo + ocms_template_properties + + + dbo + ocms_template_properties + ocms_template_properties__ix1 + + + dbo + ocms_templates + + + dbo + ocms_templates + ocms_templates__ix1 + + + dbo + ocms_translations + + + dbo + ocms_useraccounts + + + dbo + ocms_useraccounts + ocms_useraccounts__ix1 + + + dbo + ocms_admin_createUserAccount + + + dbo + ocms_admin_debug_log + + + dbo + ocms_cleanups + + + dbo + ocms_cloneItem + + + dbo + ocms_createPropertyItem + + + dbo + ocms_createView + + + dbo + ocms_deleteItem + + + dbo + ocms_getAvailableTemplates + + + dbo + ocms_getFullTree + + + dbo + ocms_getItem + + + dbo + ocms_getItem_byName + + + dbo + ocms_getView + + + dbo + ocms_getView_byName + + + dbo + ocms_merge_navigation + + + dbo + ocms_merge_properties + + + dbo + ocms_recoverItem + + + dbo + ocms_setItemName + + + dbo + ocms_setItemOrder + + + dbo + ocms_setViewItem_HiddenStatus + + + dbo + ocms_admin_getConfig + + + dbo + ocms_admin_authenticate + + + dbo + ocms_admin_getUserAccount + + + dbo + ocms_getFullItemTree + + + dbo + ocms_getFullViewTree + + + dbo + ocms_locales + + + dbo + ocms_admin_checkUserExists + + + dbo + ocms_currentaccount + + + dbo + ocms_currentuser + + + dbo + ocms_fn_generatePassword + + + dbo + ocms_fn_link_csv + + + dbo + ocms_fn_randbetween + + + dbo + ocms_fn_useraccount_id + + + dbo + ocms_type_itemtree + + + dbo + ocms_type_navigation_base + + + dbo + ocms_type_properties_base + + + dbo + ocms_type_viewtree_full + + + ocms_rwe + + + + + ocms_rwe + + + + ocms_enc_1 + + + Grant.Control.SymmetricKey + ocms_rwe + dbo + ocms_enc_1 + + + \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/AddBusinessDays.sql b/Fuchs_Database/dbo/Functions/AddBusinessDays.sql new file mode 100644 index 0000000..6250e5a --- /dev/null +++ b/Fuchs_Database/dbo/Functions/AddBusinessDays.sql @@ -0,0 +1,9 @@ +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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/backup__fds__fn_InvoiceIdByName.sql b/Fuchs_Database/dbo/Functions/backup__fds__fn_InvoiceIdByName.sql new file mode 100644 index 0000000..c975352 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/backup__fds__fn_InvoiceIdByName.sql @@ -0,0 +1,27 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/backup__fds__fn_bankingtransactions.sql b/Fuchs_Database/dbo/Functions/backup__fds__fn_bankingtransactions.sql new file mode 100644 index 0000000..b7bf5d6 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/backup__fds__fn_bankingtransactions.sql @@ -0,0 +1,83 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/backup__fds__fn_invoice_customerid.sql b/Fuchs_Database/dbo/Functions/backup__fds__fn_invoice_customerid.sql new file mode 100644 index 0000000..2ab19dc --- /dev/null +++ b/Fuchs_Database/dbo/Functions/backup__fds__fn_invoice_customerid.sql @@ -0,0 +1,26 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/backup__fds__fn_unpaidInvoices.sql b/Fuchs_Database/dbo/Functions/backup__fds__fn_unpaidInvoices.sql new file mode 100644 index 0000000..0c5739f --- /dev/null +++ b/Fuchs_Database/dbo/Functions/backup__fds__fn_unpaidInvoices.sql @@ -0,0 +1,48 @@ +-- ============================================= +-- 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 +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/backup__fds__getInvoiceTreeIds.sql b/Fuchs_Database/dbo/Functions/backup__fds__getInvoiceTreeIds.sql new file mode 100644 index 0000000..3bce719 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/backup__fds__getInvoiceTreeIds.sql @@ -0,0 +1,33 @@ + +-- ============================================= +-- 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 +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/backup__fds__r_getBalanceThisMonth.sql b/Fuchs_Database/dbo/Functions/backup__fds__r_getBalanceThisMonth.sql new file mode 100644 index 0000000..82ec521 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/backup__fds__r_getBalanceThisMonth.sql @@ -0,0 +1,42 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/bo_val.sql b/Fuchs_Database/dbo/Functions/bo_val.sql new file mode 100644 index 0000000..68b9f4d --- /dev/null +++ b/Fuchs_Database/dbo/Functions/bo_val.sql @@ -0,0 +1,22 @@ +-- ============================================= +-- 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(10,2) +AS +BEGIN + DECLARE @Ret numeric(10,2) + + SET @RET = [dbo].[net_val](@price, @quantityhours, @discount) * (1 + (ISNULL(@vat, 19.0) * 0.01)); + + RETURN @RET; + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/date_add.sql b/Fuchs_Database/dbo/Functions/date_add.sql new file mode 100644 index 0000000..8faa2b1 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/date_add.sql @@ -0,0 +1,58 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/date_addcustom.sql b/Fuchs_Database/dbo/Functions/date_addcustom.sql new file mode 100644 index 0000000..c99e92f --- /dev/null +++ b/Fuchs_Database/dbo/Functions/date_addcustom.sql @@ -0,0 +1,27 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/date_monthend.sql b/Fuchs_Database/dbo/Functions/date_monthend.sql new file mode 100644 index 0000000..7ee60c6 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/date_monthend.sql @@ -0,0 +1,18 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/date_monthfirst.sql b/Fuchs_Database/dbo/Functions/date_monthfirst.sql new file mode 100644 index 0000000..be8e384 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/date_monthfirst.sql @@ -0,0 +1,18 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/date_nextFirst.sql b/Fuchs_Database/dbo/Functions/date_nextFirst.sql new file mode 100644 index 0000000..7dbd282 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/date_nextFirst.sql @@ -0,0 +1,29 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/date_weekend.sql b/Fuchs_Database/dbo/Functions/date_weekend.sql new file mode 100644 index 0000000..d4e662f --- /dev/null +++ b/Fuchs_Database/dbo/Functions/date_weekend.sql @@ -0,0 +1,17 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/date_weekfirst.sql b/Fuchs_Database/dbo/Functions/date_weekfirst.sql new file mode 100644 index 0000000..41bd5dc --- /dev/null +++ b/Fuchs_Database/dbo/Functions/date_weekfirst.sql @@ -0,0 +1,19 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__admin_reminderSettings.sql b/Fuchs_Database/dbo/Functions/fds__admin_reminderSettings.sql new file mode 100644 index 0000000..8ef7049 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__admin_reminderSettings.sql @@ -0,0 +1,18 @@ +-- ============================================= +-- 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) +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_DocumentName.sql b/Fuchs_Database/dbo/Functions/fds__fn_DocumentName.sql new file mode 100644 index 0000000..a589098 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_DocumentName.sql @@ -0,0 +1,28 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_IntermediateIsAllocatedToOther.sql b/Fuchs_Database/dbo/Functions/fds__fn_IntermediateIsAllocatedToOther.sql new file mode 100644 index 0000000..df58125 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_IntermediateIsAllocatedToOther.sql @@ -0,0 +1,22 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_InvoiceIDs_mfr.sql b/Fuchs_Database/dbo/Functions/fds__fn_InvoiceIDs_mfr.sql new file mode 100644 index 0000000..7ca2751 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_InvoiceIDs_mfr.sql @@ -0,0 +1,30 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_InvoiceIdByName.sql b/Fuchs_Database/dbo/Functions/fds__fn_InvoiceIdByName.sql new file mode 100644 index 0000000..eda1bcf --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_InvoiceIdByName.sql @@ -0,0 +1,21 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_InvoicePaymentAmount.sql b/Fuchs_Database/dbo/Functions/fds__fn_InvoicePaymentAmount.sql new file mode 100644 index 0000000..4e66286 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_InvoicePaymentAmount.sql @@ -0,0 +1,30 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_InvoicePaymentAmount_full.sql b/Fuchs_Database/dbo/Functions/fds__fn_InvoicePaymentAmount_full.sql new file mode 100644 index 0000000..76e12ed --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_InvoicePaymentAmount_full.sql @@ -0,0 +1,37 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_ReminderDocumentName.sql b/Fuchs_Database/dbo/Functions/fds__fn_ReminderDocumentName.sql new file mode 100644 index 0000000..debd677 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_ReminderDocumentName.sql @@ -0,0 +1,30 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_bankingtransaction_id.sql b/Fuchs_Database/dbo/Functions/fds__fn_bankingtransaction_id.sql new file mode 100644 index 0000000..f96dd97 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_bankingtransaction_id.sql @@ -0,0 +1,23 @@ + + + + + + + + + +CREATE FUNCTION [dbo].[fds__fn_bankingtransaction_id] ( +) +RETURNS varchar(10) +AS +BEGIN + DECLARE @NewAccount varchar(7) = [dbo].[ocms_fn_generatePassword] (8,0,1,0); + + WHILE EXISTS( SELECT * FROM [dbo].[fds__bankingtransactions] WITH (SERIALIZABLE) WHERE [taID] = @NewAccount) + BEGIN + SET @NewAccount = [dbo].[ocms_fn_generatePassword] (8,0,1,0); + END + + RETURN @NewAccount; +END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_bankingtransactions.sql b/Fuchs_Database/dbo/Functions/fds__fn_bankingtransactions.sql new file mode 100644 index 0000000..d16ffdb --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_bankingtransactions.sql @@ -0,0 +1,88 @@ +-- ============================================= +-- 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 +( + [taID] varchar(10) + ,[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 [taID],[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.[taID], [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.[taID] = bs.[taID] + WHERE bs.assigned_invoice_id is not null + ), bs1 as ( + SELECT * FROM bs0manu + UNION + SELECT bs.[taID], [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.[taID] = bs.[taID] + WHERE bs.auto_invoice_id is not null + and bt.[taID] NOT IN (SELECT [taID] FROM bs0manu) + ), bs as ( + SELECT [taID], [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 [taID], [invid] + ) + INSERT INTO @bankingtransactions + SELECT + bt.[taID] + ,[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.[taID] = bs.[taID] + LEFT JOIN [dbo].[fds__bankingtransactions_settings] as bs2 ON bt.[taID] = bs2.[taID] + LEFT JOIN [dbo].[fds__invoices] as fi on bs.[invid] = fi.[id] AND fi.[DateFinalized] BETWEEN @invoice_startdate AND @invoice_enddate + + RETURN +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_bankingtransactions_perInvoice.sql b/Fuchs_Database/dbo/Functions/fds__fn_bankingtransactions_perInvoice.sql new file mode 100644 index 0000000..30f2919 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_bankingtransactions_perInvoice.sql @@ -0,0 +1,35 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_combineAddress.sql b/Fuchs_Database/dbo/Functions/fds__fn_combineAddress.sql new file mode 100644 index 0000000..9ac958a --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_combineAddress.sql @@ -0,0 +1,27 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_creanupTransactionInfo.sql b/Fuchs_Database/dbo/Functions/fds__fn_creanupTransactionInfo.sql new file mode 100644 index 0000000..5ea9c94 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_creanupTransactionInfo.sql @@ -0,0 +1,19 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_invoice-srq_id.sql b/Fuchs_Database/dbo/Functions/fds__fn_invoice-srq_id.sql new file mode 100644 index 0000000..05b3f36 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_invoice-srq_id.sql @@ -0,0 +1,22 @@ + + + + + + + + +CREATE FUNCTION [dbo].[fds__fn_invoice-srq_id] ( +) +RETURNS varchar(10) +AS +BEGIN + DECLARE @NewID varchar(7) = [dbo].[ocms_fn_generatePassword] (7,0,1,0); + + WHILE EXISTS( SELECT * FROM [dbo].[fds__invoice_servicerequests] WITH (SERIALIZABLE) WHERE [id] = @NewID) + BEGIN + SET @NewID = [dbo].[ocms_fn_generatePassword] (7,0,1,0); + END + + RETURN @NewID; +END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_invoice_customerid.sql b/Fuchs_Database/dbo/Functions/fds__fn_invoice_customerid.sql new file mode 100644 index 0000000..222cd79 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_invoice_customerid.sql @@ -0,0 +1,19 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_invoice_id.sql b/Fuchs_Database/dbo/Functions/fds__fn_invoice_id.sql new file mode 100644 index 0000000..a2892b4 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_invoice_id.sql @@ -0,0 +1,22 @@ + + + + + + + + +CREATE FUNCTION [dbo].[fds__fn_invoice_id] ( +) +RETURNS varchar(10) +AS +BEGIN + DECLARE @NewAccount varchar(5) = [dbo].[ocms_fn_generatePassword] (8,0,1,0); + + WHILE EXISTS( SELECT * FROM [dbo].[fds__invoices] WITH (SERIALIZABLE) WHERE [id] = @NewAccount) + BEGIN + SET @NewAccount = [dbo].[ocms_fn_generatePassword] (8,0,1,0); + END + + RETURN @NewAccount; +END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_isInvoiceCancelled.sql b/Fuchs_Database/dbo/Functions/fds__fn_isInvoiceCancelled.sql new file mode 100644 index 0000000..607e168 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_isInvoiceCancelled.sql @@ -0,0 +1,28 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_reminder_id.sql b/Fuchs_Database/dbo/Functions/fds__fn_reminder_id.sql new file mode 100644 index 0000000..33e107a --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_reminder_id.sql @@ -0,0 +1,22 @@ + + + + + + + + +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; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_requestsforinvoice.sql b/Fuchs_Database/dbo/Functions/fds__fn_requestsforinvoice.sql new file mode 100644 index 0000000..4682dbd --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_requestsforinvoice.sql @@ -0,0 +1,26 @@ +-- ============================================= +-- 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]) +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_unpaidInvoices.sql b/Fuchs_Database/dbo/Functions/fds__fn_unpaidInvoices.sql new file mode 100644 index 0000000..b417fd8 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_unpaidInvoices.sql @@ -0,0 +1,33 @@ +-- ============================================= +-- 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 +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__fn_vatfrombalances.sql b/Fuchs_Database/dbo/Functions/fds__fn_vatfrombalances.sql new file mode 100644 index 0000000..6bbd7e4 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__fn_vatfrombalances.sql @@ -0,0 +1,18 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getCompanyAddress.sql b/Fuchs_Database/dbo/Functions/fds__getCompanyAddress.sql new file mode 100644 index 0000000..43ed6e4 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getCompanyAddress.sql @@ -0,0 +1,36 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getCompanyContacts.sql b/Fuchs_Database/dbo/Functions/fds__getCompanyContacts.sql new file mode 100644 index 0000000..5d31b1e --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getCompanyContacts.sql @@ -0,0 +1,31 @@ +-- ============================================= +-- 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 + +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getCompanyEmail.sql b/Fuchs_Database/dbo/Functions/fds__getCompanyEmail.sql new file mode 100644 index 0000000..cd451f0 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getCompanyEmail.sql @@ -0,0 +1,16 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getCompanyName.sql b/Fuchs_Database/dbo/Functions/fds__getCompanyName.sql new file mode 100644 index 0000000..a43b01f --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getCompanyName.sql @@ -0,0 +1,20 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getCompanyNameAddress.sql b/Fuchs_Database/dbo/Functions/fds__getCompanyNameAddress.sql new file mode 100644 index 0000000..f70e1e9 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getCompanyNameAddress.sql @@ -0,0 +1,36 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getCompanysContacts.sql b/Fuchs_Database/dbo/Functions/fds__getCompanysContacts.sql new file mode 100644 index 0000000..045b421 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getCompanysContacts.sql @@ -0,0 +1,36 @@ +-- ============================================= +-- 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] + +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getInvoiceCredits.sql b/Fuchs_Database/dbo/Functions/fds__getInvoiceCredits.sql new file mode 100644 index 0000000..c0bde9f --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getInvoiceCredits.sql @@ -0,0 +1,129 @@ + +CREATE function [dbo].[fds__getInvoiceCredits] +( + @startdate date + ,@enddate date +) +RETURNS TABLE +AS +RETURN +( + with b0 as ( + SELECT [taID] + --,[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 + [taID] + , [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 +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getInvoiceTreeIds.sql b/Fuchs_Database/dbo/Functions/fds__getInvoiceTreeIds.sql new file mode 100644 index 0000000..ae1736d --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getInvoiceTreeIds.sql @@ -0,0 +1,23 @@ + +-- ============================================= +-- 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 +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getRequestTreeIds.sql b/Fuchs_Database/dbo/Functions/fds__getRequestTreeIds.sql new file mode 100644 index 0000000..b403597 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getRequestTreeIds.sql @@ -0,0 +1,18 @@ +-- ============================================= +-- 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 +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getUpdateableRequests.sql b/Fuchs_Database/dbo/Functions/fds__getUpdateableRequests.sql new file mode 100644 index 0000000..369ac77 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getUpdateableRequests.sql @@ -0,0 +1,115 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__getUpdateableTables.sql b/Fuchs_Database/dbo/Functions/fds__getUpdateableTables.sql new file mode 100644 index 0000000..052aa51 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__getUpdateableTables.sql @@ -0,0 +1,114 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__newInvoiceId.sql b/Fuchs_Database/dbo/Functions/fds__newInvoiceId.sql new file mode 100644 index 0000000..96d8b4d --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__newInvoiceId.sql @@ -0,0 +1,19 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__r_getBalanceThisMonth.sql b/Fuchs_Database/dbo/Functions/fds__r_getBalanceThisMonth.sql new file mode 100644 index 0000000..8a21d5c --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__r_getBalanceThisMonth.sql @@ -0,0 +1,33 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fds__updateNeed.sql b/Fuchs_Database/dbo/Functions/fds__updateNeed.sql new file mode 100644 index 0000000..0f98931 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fds__updateNeed.sql @@ -0,0 +1,25 @@ +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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_authenticate.sql b/Fuchs_Database/dbo/Functions/fis_admin_authenticate.sql new file mode 100644 index 0000000..afe4350 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_authenticate.sql @@ -0,0 +1,33 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_authenticate_byID.sql b/Fuchs_Database/dbo/Functions/fis_admin_authenticate_byID.sql new file mode 100644 index 0000000..fdbe73e --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_authenticate_byID.sql @@ -0,0 +1,34 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_checkUserExists.sql b/Fuchs_Database/dbo/Functions/fis_admin_checkUserExists.sql new file mode 100644 index 0000000..50f7f8b --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_checkUserExists.sql @@ -0,0 +1,20 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount.sql new file mode 100644 index 0000000..b409a59 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount.sql @@ -0,0 +1,55 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserAccountList.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccountList.sql new file mode 100644 index 0000000..e025aeb --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccountList.sql @@ -0,0 +1,65 @@ + + + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount_Namelist.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount_Namelist.sql new file mode 100644 index 0000000..2f69c38 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount_Namelist.sql @@ -0,0 +1,36 @@ + + + + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount_byemail.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount_byemail.sql new file mode 100644 index 0000000..7c09c56 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserAccount_byemail.sql @@ -0,0 +1,66 @@ + + + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserAddressForm.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserAddressForm.sql new file mode 100644 index 0000000..6e75842 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserAddressForm.sql @@ -0,0 +1,33 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserAuth.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserAuth.sql new file mode 100644 index 0000000..b49ca50 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserAuth.sql @@ -0,0 +1,23 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserEmail_byID.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserEmail_byID.sql new file mode 100644 index 0000000..9617f50 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserEmail_byID.sql @@ -0,0 +1,24 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserGroupList.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserGroupList.sql new file mode 100644 index 0000000..71c0bd4 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserGroupList.sql @@ -0,0 +1,33 @@ + + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserName.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserName.sql new file mode 100644 index 0000000..0d68873 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserName.sql @@ -0,0 +1,27 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserName_byID.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserName_byID.sql new file mode 100644 index 0000000..9202a6e --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserName_byID.sql @@ -0,0 +1,23 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserName_rev.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserName_rev.sql new file mode 100644 index 0000000..b2dcc9f --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserName_rev.sql @@ -0,0 +1,28 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserName_rev_byID.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserName_rev_byID.sql new file mode 100644 index 0000000..3a5724d --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserName_rev_byID.sql @@ -0,0 +1,24 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_getUserSetting.sql b/Fuchs_Database/dbo/Functions/fis_admin_getUserSetting.sql new file mode 100644 index 0000000..857c127 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_getUserSetting.sql @@ -0,0 +1,26 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_admin_testGroupMembership.sql b/Fuchs_Database/dbo/Functions/fis_admin_testGroupMembership.sql new file mode 100644 index 0000000..3c3bc99 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_admin_testGroupMembership.sql @@ -0,0 +1,29 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_fn_id.sql b/Fuchs_Database/dbo/Functions/fis_fn_id.sql new file mode 100644 index 0000000..4c5ac55 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_fn_id.sql @@ -0,0 +1,43 @@ + + + + + + + +CREATE FUNCTION [dbo].[fis_fn_id] ( + @table varchar(50) +) +RETURNS varchar(50) +AS +BEGIN + DECLARE @NewAccount varchar(10) = null; + SET @table = ISNULL(@table, ''); + + IF @table = 'fis_usergroups' + BEGIN + SELECT @NewAccount = [dbo].[ocms_fn_generatePassword] (5,0,1,0); + WHILE EXISTS( SELECT 0 FROM [dbo].[fis_usergroups] WITH (SERIALIZABLE) WHERE [usergroup_id] = @NewAccount) + BEGIN + SET @NewAccount = [dbo].[ocms_fn_generatePassword] (5,0,1,0); + END + END + ELSE IF @table = 'tmp__fds__invoice_servicerequests' + BEGIN + SELECT @NewAccount = [dbo].[ocms_fn_generatePassword] (7,0,1,0); + WHILE EXISTS( SELECT 0 FROM [dbo].[tmp__fds__invoice_servicerequests] WITH (SERIALIZABLE) WHERE [InvRqId] = @NewAccount) + BEGIN + SET @NewAccount = [dbo].[ocms_fn_generatePassword] (7,0,1,0); + END + END + ELSE IF @table = 'tmp__fds__bankingtransactions' + BEGIN + SELECT @NewAccount = [dbo].[ocms_fn_generatePassword] (7,0,1,0); + WHILE EXISTS( SELECT 0 FROM [dbo].[tmp__fds__bankingtransactions] WITH (SERIALIZABLE) WHERE [taID] = @NewAccount) + BEGIN + SET @NewAccount = [dbo].[ocms_fn_generatePassword] (7,0,1,0); + END + END + + RETURN ISNULL(@NewAccount, [dbo].[ocms_fn_generatePassword] (10,0,1,0)); +END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_fn_useraccount_id.sql b/Fuchs_Database/dbo/Functions/fis_fn_useraccount_id.sql new file mode 100644 index 0000000..5d8184b --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_fn_useraccount_id.sql @@ -0,0 +1,20 @@ + + + + + + +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; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_getModuleAuth.sql b/Fuchs_Database/dbo/Functions/fis_getModuleAuth.sql new file mode 100644 index 0000000..cfe6070 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_getModuleAuth.sql @@ -0,0 +1,64 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_getModuleAuthList.sql b/Fuchs_Database/dbo/Functions/fis_getModuleAuthList.sql new file mode 100644 index 0000000..69335bc --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_getModuleAuthList.sql @@ -0,0 +1,20 @@ +-- ============================================= +-- 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]) <> '' +) \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/fis_getONEPersonWidgets.sql b/Fuchs_Database/dbo/Functions/fis_getONEPersonWidgets.sql new file mode 100644 index 0000000..b64e299 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/fis_getONEPersonWidgets.sql @@ -0,0 +1,49 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/json_compareObjectArrays.sql b/Fuchs_Database/dbo/Functions/json_compareObjectArrays.sql new file mode 100644 index 0000000..16d2433 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/json_compareObjectArrays.sql @@ -0,0 +1,154 @@ + +CREATE FUNCTION [dbo].[json_compareObjectArrays] (@SourceJSON NVARCHAR(MAX), @TargetJSON NVARCHAR(MAX), @uniquekey varchar(50) ) +/** + Summary: + This function 'diffs' a source JSON document with a target JSON document and produces an + analysis of which properties are missing in either the source or target, or the values + of these properties that are different. It reports on the properties and values for + both source and target as well as the path that references that scalar value. The + path reference to the object's parent is exposed in the result to enable a query to + reference the value of any other object in the parent that is needed. + Author: Phil Factor + based on Author: Phil Factor (06/07/2020) + Date: 06/30/2023 + + Returns: > + equal: 1 = equal, 0 not equal + SideIndicator: ( == equal, <- not in target, -> not in source, <> not equal ) + uid: + parent: + path: the JSON path used by the SQL JSON functions + key: the key field without the path + SourceValue: the value IN the SOURCE JSON document + TargetValue: the value IN the TARGET JSON document + +**/ +RETURNS @returntable TABLE + ( + [equal] [bit], + [SideIndicator] CHAR(2), -- == means equal, <- means not in target, -> means not in source, <> means not equal + [UID] varchar(100), + [parent] VARCHAR(2000), -- the parent object + [path] VARCHAR(2000), -- the JSON path used by the SQL JSON functions + [key] VARCHAR(255), -- the key field without the path + [SourceValue] NVARCHAR(max), -- the value IN the SOURCE JSON document + [TargetValue] NVARCHAR(max) -- the value IN the TARGET JSON document + ) +AS + BEGIN + + IF (IsJson(ISNULL(@SourceJSON, '{}')) = 1 AND IsJson(ISNULL(@TargetJSON, '{}')) = 1) --don't try anything if either json is invalid + BEGIN + DECLARE @map TABLE --these contain all properties or array elements with scalar values + ( + iteration INT, --the number of times that more arrays or objects were found + SourceOrTarget CHAR(1), --is this the source 's' OR the target 't' + [UID] varchar(100), + [mparent] VARCHAR(2000), --the parent object + [mPath] VARCHAR(2000), -- the JSON path to the key/value pair or array element + [mOPath] NVARCHAR(2000), + [mKey] VARCHAR(255), --the key to the property + [mValue] NVARCHAR(MAX),-- the value + [mType] INT --the type of value it is + ); + DECLARE @objects TABLE --this contains all the properties with arrays and objects + ( + iteration INT, + SourceOrTarget CHAR(1), + [UID] varchar(100), + [oParent] VARCHAR(2000), + [oPath] VARCHAR(2000), + [oOPath] VARCHAR(2000), + [oKey] NVARCHAR(2000), + [oValue] NVARCHAR(MAX), + [oType] INT + ); + DECLARE @depth INT = 1; --we start in shallow water + DECLARE @HowManyObjectsNext INT = 1, @SourceType INT, @TargetType INT; + + SELECT --firstly, we try to work out if the source is an array or object + @SourceType = + CASE IsNumeric((SELECT TOP 1 [key] FROM OpenJson(@SourceJSON))) + WHEN 1 THEN 4 ELSE 5 END, + @TargetType= --and if the target is an array or object + CASE IsNumeric((SELECT TOP 1 [key] FROM OpenJson(@TargetJSON))) + WHEN 1 THEN 4 ELSE 5 END + --now we insert the base objects or arrays into the object table + INSERT INTO @objects (iteration, SourceOrTarget, [oParent], [oPath], [oOPath], [oKey], [oValue], [oType]) + SELECT 0, 's' AS SourceOrTarget,'' AS [oParent], [oPath] = '$', [oOPath] = '$', [oKey] = '', @SourceJSON, @SourceType; + INSERT INTO @objects (iteration, SourceOrTarget, [oParent], [oPath], [oOPath], [oKey], [oValue], [oType]) + SELECT 0, 't' AS SourceOrTarget, '' AS [oParent], [oPath] = '$', [oOPath] = '$', [oKey] = '', @TargetJSON, @TargetType; + + --we now set the depth and how many objects are in the next iteration + SELECT @depth = 0, @HowManyObjectsNext = 2; + + WHILE @HowManyObjectsNext > 0 AND @depth < 2 + BEGIN + INSERT INTO @map --get the scalar values into the @map table + (iteration, SourceOrTarget, [UID], [mParent], [mPath], [mOPath], [mKey], [mValue], [mType]) + SELECT -- + [iteration] = o.[iteration] + 1 + , SourceOrTarget + , [UID] = [UID] + , [mParent] = [oPath] + , [mPath] = [oPath] + CASE [otype] WHEN 4 THEN '[' + [Key] + ']' ELSE '.' + [key] END + , [mOPath] = [oOPath] + CASE [otype] WHEN 4 THEN '[' + [Key] + ']' ELSE '.' + [key] END + , [mkey] = [key] + , [mvalue] = [value] + , [mtype] = [type] + FROM @objects AS o + CROSS APPLY OpenJson([oValue]) as j + WHERE j.[type] IN (0, 1, 2, 3) AND o.[iteration] = @depth; + + --now we do the same for the objects and arrays + INSERT INTO @objects (iteration, SourceOrTarget, [UID], [oParent], [oPath], [oOPath], [oKey], [oValue], [oType]) + SELECT + [iteration] = o.[iteration] + 1 + , [SourceOrTarget] = SourceOrTarget + , [UID] = JSON_VALUE(j.[Value], '$.' + @uniquekey) + , [oParent] = [oPath] + , [oPath] = [oPath] + CASE [oType] WHEN 4 THEN '[' + JSON_VALUE(j.[Value], '$.' + @uniquekey) + ']' ELSE '.' + [key] END + , [oOPath] = [oOPath] + CASE [oType] WHEN 4 THEN '[' + j.[key] + ']' ELSE '.' + j.[key] END + , [oKey] = [key] + , [oValue] = [value] + , [oType] = [type] + FROM @objects o + CROSS APPLY OpenJson([oValue]) as j + WHERE j.[type] IN (4,5) AND o.[iteration] = @depth; + + SELECT @HowManyObjectsNext = @@RowCount --how many objects or arrays? + SELECT @depth = @depth + 1; --and so to the next depth maybe + + END; --while + + --now we just do a full join on the columns we are comparing and work out the comparison + INSERT INTO @returntable + SELECT + --first we work out the side-indicator that summarises the comparison + [equal] = CASE WHEN src.[UID] is null OR tgt.[UID] is null THEN 0 + WHEN src.[mValue] is NULL AND tgt.[mValue] is null THEN 1 + WHEN src.[mValue] = tgt.[mValue] THEN 1 + ELSE 0 + END + , [Sideindicator] = CASE WHEN src.[UID] is null AND tgt.[UID] IS NOT null THEN '->' + WHEN src.[UID] is NOT null AND tgt.[UID] IS null THEN '<-' + WHEN src.[mValue] is NULL AND tgt.[mValue] is null THEN '==' + WHEN src.[mValue] = tgt.[mValue] THEN '==' + ELSE IIF(src.[mPath] IS NULL, '-', '<') + IIF(tgt.[mPath] IS NULL, '-', '>') + END + --these columns could be in either table + , [UID] = Coalesce(src.[UID], tgt.[UID]) + , [parent] = Coalesce(src.[mParent], tgt.[mParent]) + , [path] = Coalesce(src.[mOPath], tgt.[mOPath]) + , [key] = Coalesce(src.[mKey], tgt.[mKey]) + , [sourceValue] = src.[mValue] + , [targetValue] = tgt.[mValue] + FROM + (SELECT [UID], [mParent], [mPath], [mOPath], [mKey], [mValue] FROM @map WHERE SourceOrTarget = 's') AS src -- the source scalar literals + FULL OUTER JOIN + (SELECT [UID], [mParent], [mPath], [mOPath], [mKey], [mValue] FROM @map WHERE SourceOrTarget = 't') AS tgt --the target scalar literals + ON src.[mPath] = tgt.[mPath] + ORDER BY [path]; + END; + RETURN; + END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/json_diffObjectArrays.sql b/Fuchs_Database/dbo/Functions/json_diffObjectArrays.sql new file mode 100644 index 0000000..ce8d8cf --- /dev/null +++ b/Fuchs_Database/dbo/Functions/json_diffObjectArrays.sql @@ -0,0 +1,112 @@ + +CREATE FUNCTION [dbo].[json_diffObjectArrays] (@SourceJSON NVARCHAR(MAX), @TargetJSON NVARCHAR(MAX), @uniquekey varchar(50) ) +/** +Summary: > + This function 'diffs' a source JSON document with a target JSON document and produces an + analysis of which properties are missing in either the source or target, or the values + of these properties that are different. It reports on the properties and values for + both source and target as well as the path that references that scalar value. The + path reference to the object's parent is exposed in the result to enable a query to + reference the value of any other object in the parent that is needed. +Author: Phil Factor +Date: 06/07/2020 +Revised: + - mod: Added the parent reference to the difference report + - Date: 09/07/2020 +Database: PhilsRoutines +Examples: + - SELECT * FROM dbo.Compare_JsonObject(@TheSourceJSON, @TheTargetJSON) + WHERE SideIndicator <> '=='; + - SELECT *, Json_Value(@TheSourceJSON,TheParent+'.name') + FROM dbo.Compare_JsonObject(@TheSourceJSON, @TheTargetJSON) + WHERE SideIndicator <> '=='; +Returns: > + SideIndicator: ( == equal, <- not in target, -> not in source, <> not equal + ThePath: the JSON path used by the SQL JSON functions + TheKey: the key field without the path + TheSourceValue: the value IN the SOURCE JSON document + TheTargetValue: the value IN the TARGET JSON document + +**/ +RETURNS @returntable TABLE + ( + [equal] [bit], + [action] smallint, + [uid] varchar(100), + [diff] nvarchar(max) + ) +AS + BEGIN + + DECLARE @objects TABLE ( + [uid] varchar(100), + [json] NVARCHAR(MAX) + ) + INSERT INTO @objects ([uid], [json]) + SELECT JSON_VALUE(j.[Value], '$.' + @uniquekey), [value] + FROM OpenJson(@TargetJSON) as j + WHERE type IN (4,5); + + DECLARE @intermediate TABLE + ( + [equal] [bit], + [SideIndicator] CHAR(2), -- == means equal, <- means not in target, -> means not in source, <> means not equal + [UID] varchar(100), + [parent] VARCHAR(2000), -- the parent object + [path] VARCHAR(2000), -- the JSON path used by the SQL JSON functions + [key] VARCHAR(255), -- the key field without the path + [SourceValue] NVARCHAR(max), -- the value IN the SOURCE JSON document + [TargetValue] NVARCHAR(max) -- the value IN the TARGET JSON document + ) + INSERT INTO @intermediate + SELECT * FROM [dbo].[json_compareObjectArrays](@SourceJSON, @TargetJSON, @uniquekey); + + WITH d as( + SELECT + [UID] + , [total] = SUM(1) + , [LEFT] = SUM(IIF([sideindicator] = '<-',1,0)) + , [RIGHT] = SUM(IIF([sideindicator] = '->',1,0)) + , [inequal] = SUM(IIF(i.[equal] = 1,0,1)) + FROM @intermediate as i + GROUP BY [UID] + ) + INSERT INTO @returntable + SELECT + [equal] = IIF([inequal] = 0, 1 ,0) + , CASE WHEN [total] = [RIGHT] THEN 2 + WHEN [total] = [LEFT] THEN -1 + WHEN [inequal] > 0 THEN 1 + ELSE 0 END + , ISNULL(o.[uid], d.[UID]) + , [j] = IIF([inequal] = 0, '{}' , --( SELECT [key] = im.[theKey], [val] = im.[TheTargetValue] FROM @intermediate as im WHERE im.[UID] = d.[UID] AND im.equal = 0 FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ) + o.[json] + ) + FROM d + FULL OUTER JOIN @objects as o ON d.[UID] = o.[uid] + + DECLARE @uid varchar(100), @key varchar(100); + + DECLARE im_cursor CURSOR FOR + SELECT [uid], [key] + FROM @intermediate + WHERE [SideIndicator] in ('=='); + + OPEN im_cursor + FETCH NEXT FROM im_cursor INTO @uid, @key; + + WHILE @@FETCH_STATUS = 0 + BEGIN + UPDATE o + SET o.[diff] = JSON_MODIFY(o.[diff], '$.' + @key, null) + FROM @returntable as o + WHERE [uid] = @uid; + + FETCH NEXT FROM im_cursor INTO @uid, @key; + END + + CLOSE im_cursor ; + DEALLOCATE im_cursor; + + RETURN; + END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/mfr__schema.sql b/Fuchs_Database/dbo/Functions/mfr__schema.sql new file mode 100644 index 0000000..60161ca --- /dev/null +++ b/Fuchs_Database/dbo/Functions/mfr__schema.sql @@ -0,0 +1,1188 @@ +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE FUNCTION [dbo].[mfr__schema] +( + +) +RETURNS XML +AS +BEGIN + DECLARe @AS XML; +SET @AS = N' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + '; + + RETURN @as; + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/mfr_fn_dateSent_fromNotes.sql b/Fuchs_Database/dbo/Functions/mfr_fn_dateSent_fromNotes.sql new file mode 100644 index 0000000..284bb80 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/mfr_fn_dateSent_fromNotes.sql @@ -0,0 +1,18 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ne.sql b/Fuchs_Database/dbo/Functions/ne.sql new file mode 100644 index 0000000..a09b7ec --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ne.sql @@ -0,0 +1,77 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/net_val.sql b/Fuchs_Database/dbo/Functions/net_val.sql new file mode 100644 index 0000000..28e4b4a --- /dev/null +++ b/Fuchs_Database/dbo/Functions/net_val.sql @@ -0,0 +1,21 @@ +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE FUNCTION [dbo].[net_val] +( + @price numeric(10,3) + ,@quantityhours numeric(10,3) + ,@discount numeric(10,3) +) +RETURNS numeric(10,2) +AS +BEGIN + DECLARE @Ret numeric(10,2) + + SET @RET = ISNULL(@Price,0) * ISNULL(@quantityhours,1) * (100 - ISNULL(@discount,0)) * 0.01; + + RETURN @RET; + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_20_randomStrings.sql b/Fuchs_Database/dbo/Functions/ott_20_randomStrings.sql new file mode 100644 index 0000000..8e5297d --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_20_randomStrings.sql @@ -0,0 +1,27 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_b10.sql b/Fuchs_Database/dbo/Functions/ott_b10.sql new file mode 100644 index 0000000..651cc29 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_b10.sql @@ -0,0 +1,43 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_b26.sql b/Fuchs_Database/dbo/Functions/ott_b26.sql new file mode 100644 index 0000000..444f803 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_b26.sql @@ -0,0 +1,38 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_csv_contains.sql b/Fuchs_Database/dbo/Functions/ott_csv_contains.sql new file mode 100644 index 0000000..a696bc6 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_csv_contains.sql @@ -0,0 +1,30 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_jcontent.sql b/Fuchs_Database/dbo/Functions/ott_jcontent.sql new file mode 100644 index 0000000..2ecf1f0 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_jcontent.sql @@ -0,0 +1,36 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_jcsv_contains.sql b/Fuchs_Database/dbo/Functions/ott_jcsv_contains.sql new file mode 100644 index 0000000..c8dee5a --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_jcsv_contains.sql @@ -0,0 +1,52 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_jcsv_containskey.sql b/Fuchs_Database/dbo/Functions/ott_jcsv_containskey.sql new file mode 100644 index 0000000..59d6521 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_jcsv_containskey.sql @@ -0,0 +1,38 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_max.sql b/Fuchs_Database/dbo/Functions/ott_max.sql new file mode 100644 index 0000000..dcb7856 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_max.sql @@ -0,0 +1,28 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_max_float.sql b/Fuchs_Database/dbo/Functions/ott_max_float.sql new file mode 100644 index 0000000..9f206fd --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_max_float.sql @@ -0,0 +1,28 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_merge_csv.sql b/Fuchs_Database/dbo/Functions/ott_merge_csv.sql new file mode 100644 index 0000000..7f5e56b --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_merge_csv.sql @@ -0,0 +1,28 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_min.sql b/Fuchs_Database/dbo/Functions/ott_min.sql new file mode 100644 index 0000000..a39defe --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_min.sql @@ -0,0 +1,29 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_min_date.sql b/Fuchs_Database/dbo/Functions/ott_min_date.sql new file mode 100644 index 0000000..67a6d1c --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_min_date.sql @@ -0,0 +1,28 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_min_float.sql b/Fuchs_Database/dbo/Functions/ott_min_float.sql new file mode 100644 index 0000000..dcd3965 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_min_float.sql @@ -0,0 +1,29 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_quote.sql b/Fuchs_Database/dbo/Functions/ott_quote.sql new file mode 100644 index 0000000..266a9b3 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_quote.sql @@ -0,0 +1,19 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_quote_255.sql b/Fuchs_Database/dbo/Functions/ott_quote_255.sql new file mode 100644 index 0000000..f7ab489 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_quote_255.sql @@ -0,0 +1,19 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_random_int.sql b/Fuchs_Database/dbo/Functions/ott_random_int.sql new file mode 100644 index 0000000..a6c0247 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_random_int.sql @@ -0,0 +1,16 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/ott_remove_csv.sql b/Fuchs_Database/dbo/Functions/ott_remove_csv.sql new file mode 100644 index 0000000..9e7c06c --- /dev/null +++ b/Fuchs_Database/dbo/Functions/ott_remove_csv.sql @@ -0,0 +1,27 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/string_SplitString_ordered.sql b/Fuchs_Database/dbo/Functions/string_SplitString_ordered.sql new file mode 100644 index 0000000..966f344 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/string_SplitString_ordered.sql @@ -0,0 +1,30 @@ + +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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/strings_encodeHTML.sql b/Fuchs_Database/dbo/Functions/strings_encodeHTML.sql new file mode 100644 index 0000000..5b6b0c8 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/strings_encodeHTML.sql @@ -0,0 +1,12 @@ + +CREATE FUNCTION [dbo].[strings_encodeHTML](@inputText NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + DECLARE @encodedText NVARCHAR(MAX); + + -- Use FOR XML PATH to escape special characters + SET @encodedText = CAST((SELECT @inputText AS [p] FOR XML PATH(''), TYPE) as nvarchar(max)); + + RETURN IIF(LEN(@encodedText) < 7, '', dbo.strings_replaceSpecialCharsInHTML(SUBSTRING(@encodedText, 4, LEN(@encodedText) -7))); +END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/strings_removeLeading0.sql b/Fuchs_Database/dbo/Functions/strings_removeLeading0.sql new file mode 100644 index 0000000..f80b32e --- /dev/null +++ b/Fuchs_Database/dbo/Functions/strings_removeLeading0.sql @@ -0,0 +1,17 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/strings_removeLeading0_255.sql b/Fuchs_Database/dbo/Functions/strings_removeLeading0_255.sql new file mode 100644 index 0000000..b0d9cf3 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/strings_removeLeading0_255.sql @@ -0,0 +1,17 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/strings_replaceSpecialCharsInHTML.sql b/Fuchs_Database/dbo/Functions/strings_replaceSpecialCharsInHTML.sql new file mode 100644 index 0000000..56c0a75 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/strings_replaceSpecialCharsInHTML.sql @@ -0,0 +1,31 @@ + +CREATE FUNCTION [dbo].[strings_replaceSpecialCharsInHTML] +( + @inputHtml NVARCHAR(MAX) +) +RETURNS NVARCHAR(MAX) +AS +BEGIN + DECLARE @result NVARCHAR(MAX); + + /* the order is important !! */ + + + -- Replace ampersand ("&") with "&" + SET @inputHtml = REPLACE(@inputHtml, N'&', N'&'); + + -- Replace non-breaking space (ASCII 160) with " " + SET @inputHtml = REPLACE(@inputHtml, NCHAR(160), N' '); + + -- Replace newline with "
" + SET @inputHtml = REPLACE(@inputHtml, NCHAR(10), N'
'); + + -- Replace copyright symbol ("©") with "©" + SET @inputHtml = REPLACE(@inputHtml, NCHAR(169), N'©'); + + -- Add more replacements for other special characters as needed + + SET @result = @inputHtml; + + RETURN @result; +END; \ No newline at end of file diff --git a/Fuchs_Database/dbo/Functions/vat_val.sql b/Fuchs_Database/dbo/Functions/vat_val.sql new file mode 100644 index 0000000..244fc62 --- /dev/null +++ b/Fuchs_Database/dbo/Functions/vat_val.sql @@ -0,0 +1,22 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/_BackupAndClearInvoiceFile.sql b/Fuchs_Database/dbo/Stored Procedures/_BackupAndClearInvoiceFile.sql new file mode 100644 index 0000000..f69149e --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/_BackupAndClearInvoiceFile.sql @@ -0,0 +1,68 @@ + + +-- Example usage: EXEC dbo.usp_BackupAndClearInvoiceFile @InvoiceID = 'R2025-0057'; + +CREATE PROCEDURE [dbo].[_BackupAndClearInvoiceFile] + @InvoiceID nvarchar(25) +AS +BEGIN + SET NOCOUNT ON; + + DECLARE @invID varchar(10); + DECLARE @today datetime; + DECLARE @td nvarchar(max); + DECLARE @sql nvarchar(max) = ''; + DECLARE @ErrorMessage nvarchar(500); + + -- Get the invoice ID + SELECT TOP(1) @invID = [id] + FROM dbo.fds__invoices + WHERE InvoiceId = @InvoiceID; + + -- Check if invoice exists + IF ISNULL(@invID, '') = '' + BEGIN + SET @ErrorMessage = 'Invoice not found: ' + @InvoiceID; + PRINT @ErrorMessage; + RETURN -1; + END + + -- Generate backup table prefix with timestamp + SET @today = GETDATE(); + SET @td = FORMAT(@today, 'yyyy-MM-dd_HHmm'); + + PRINT 'Backup table prefix: ' + @td; + + BEGIN TRY + -- Build dynamic SQL for backup and update + SET @sql = @sql + N'SELECT * INTO [' + @td + ' fds__invoices] FROM dbo.fds__invoices WHERE Id = ''' + CAST(@invID as nvarchar(max)) + ''';'; + SET @sql = @sql + N'SELECT * INTO [' + @td + ' fds__invoice_items] FROM dbo.fds__invoice_items WHERE InvId = ''' + CAST(@invID as nvarchar(max)) + ''';'; + SET @sql = @sql + N'SELECT * INTO [' + @td + ' fds__invoice_details] FROM dbo.fds__invoice_details WHERE InvId = ''' + CAST(@invID as nvarchar(max)) + ''';'; + + -- Clear file column after successful backup + SET @sql = @sql + N'IF EXISTS (SELECT 1 FROM [dbo].[' + @td + ' fds__invoices]) + BEGIN + UPDATE dbo.fds__invoices SET [file] = NULL WHERE [Id] = ''' + CAST(@invID as nvarchar(max)) + '''; + END;'; + + -- Execute the dynamic SQL + EXEC sp_executesql @sql; + + PRINT 'SUCCESS: Backup created and file column cleared for Invoice: ' + @InvoiceID; + + + + Print Formatmessage('https://sanitaerfuchs.de/intranet/do/req/idoc?id=%s&create=1', @invID); + Print Formatmessage('https://sanitaerfuchs.de/intranet/do/inv/rdoc?id=%s&create=1', @invID); + + + RETURN 0; + + END TRY + BEGIN CATCH + SET @ErrorMessage = 'ERROR: ' + ERROR_MESSAGE(); + PRINT @ErrorMessage; + RETURN -1; + END CATCH + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__createCredit_simple.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__createCredit_simple.sql new file mode 100644 index 0000000..92d34c5 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__createCredit_simple.sql @@ -0,0 +1,264 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__createReminder.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__createReminder.sql new file mode 100644 index 0000000..b16b388 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__createReminder.sql @@ -0,0 +1,120 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__createStorno_simple.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__createStorno_simple.sql new file mode 100644 index 0000000..7eb58b0 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__createStorno_simple.sql @@ -0,0 +1,263 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getBankingtransfers.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getBankingtransfers.sql new file mode 100644 index 0000000..21dfadb --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getBankingtransfers.sql @@ -0,0 +1,51 @@ + +-- ============================================= +-- 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.[taID] + --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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getBankingtransfers_questionable.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getBankingtransfers_questionable.sql new file mode 100644 index 0000000..aa74767 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getBankingtransfers_questionable.sql @@ -0,0 +1,60 @@ +-- ============================================= +-- 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.[taID] + --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.[taID] = ic.[taID] AND (ISNULL(bs.[done_manually],'') <> '' OR ISNULL(bs.[assigned_invoice_id],'') <> '')) +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getDatevExports.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getDatevExports.sql new file mode 100644 index 0000000..e748ef3 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getDatevExports.sql @@ -0,0 +1,634 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvRequestItems.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvRequestItems.sql new file mode 100644 index 0000000..e5bd618 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvRequestItems.sql @@ -0,0 +1,57 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoiceReminder.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoiceReminder.sql new file mode 100644 index 0000000..f5eaad5 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoiceReminder.sql @@ -0,0 +1,43 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoices_list2.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoices_list2.sql new file mode 100644 index 0000000..a601a60 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoices_list2.sql @@ -0,0 +1,285 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoices_list_vario.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoices_list_vario.sql new file mode 100644 index 0000000..00302ac --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getInvoices_list_vario.sql @@ -0,0 +1,293 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getReminder.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getReminder.sql new file mode 100644 index 0000000..dfaeac7 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getReminder.sql @@ -0,0 +1,96 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getReportDocument.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getReportDocument.sql new file mode 100644 index 0000000..60d433e --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getReportDocument.sql @@ -0,0 +1,26 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequest_details.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequest_details.sql new file mode 100644 index 0000000..4b97694 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequest_details.sql @@ -0,0 +1,422 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequests_list.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequests_list.sql new file mode 100644 index 0000000..65d9b2c --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequests_list.sql @@ -0,0 +1,278 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequests_list2.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequests_list2.sql new file mode 100644 index 0000000..d27a3fb --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__getRequests_list2.sql @@ -0,0 +1,308 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__lookupReminders.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__lookupReminders.sql new file mode 100644 index 0000000..1230c57 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__lookupReminders.sql @@ -0,0 +1,113 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__prepReminder.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__prepReminder.sql new file mode 100644 index 0000000..4d02e9a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__prepReminder.sql @@ -0,0 +1,86 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__prepStorno_recreate.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__prepStorno_recreate.sql new file mode 100644 index 0000000..f0c473a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__prepStorno_recreate.sql @@ -0,0 +1,459 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByMonth.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByMonth.sql new file mode 100644 index 0000000..b6d92b0 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByMonth.sql @@ -0,0 +1,61 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByYearTopCustomer.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByYearTopCustomer.sql new file mode 100644 index 0000000..bf16db0 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByYearTopCustomer.sql @@ -0,0 +1,91 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByYearTopMaterial.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByYearTopMaterial.sql new file mode 100644 index 0000000..513a7dc --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceByYearTopMaterial.sql @@ -0,0 +1,90 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceTrendByMonth.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceTrendByMonth.sql new file mode 100644 index 0000000..f94b85a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceTrendByMonth.sql @@ -0,0 +1,72 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceTrendByYear.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceTrendByYear.sql new file mode 100644 index 0000000..744caf0 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__r_getBalanceTrendByYear.sql @@ -0,0 +1,71 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__setBankingtransaction_autoAssigns.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__setBankingtransaction_autoAssigns.sql new file mode 100644 index 0000000..65a504f --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__setBankingtransaction_autoAssigns.sql @@ -0,0 +1,70 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/backup__fds__setInvoicePayed.sql b/Fuchs_Database/dbo/Stored Procedures/backup__fds__setInvoicePayed.sql new file mode 100644 index 0000000..ad0d013 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/backup__fds__setInvoicePayed.sql @@ -0,0 +1,46 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__admin_getReportCatalog.sql b/Fuchs_Database/dbo/Stored Procedures/fds__admin_getReportCatalog.sql new file mode 100644 index 0000000..c2fc5e4 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__admin_getReportCatalog.sql @@ -0,0 +1,206 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__admin_logdebug.sql b/Fuchs_Database/dbo/Stored Procedures/fds__admin_logdebug.sql new file mode 100644 index 0000000..1a75a50 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__admin_logdebug.sql @@ -0,0 +1,30 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__admin_removeconflicttables.sql b/Fuchs_Database/dbo/Stored Procedures/fds__admin_removeconflicttables.sql new file mode 100644 index 0000000..9d90aab --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__admin_removeconflicttables.sql @@ -0,0 +1,40 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__admin_updateconflicttables.sql b/Fuchs_Database/dbo/Stored Procedures/fds__admin_updateconflicttables.sql new file mode 100644 index 0000000..9bc8f7f --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__admin_updateconflicttables.sql @@ -0,0 +1,41 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__createCredit_simple.sql b/Fuchs_Database/dbo/Stored Procedures/fds__createCredit_simple.sql new file mode 100644 index 0000000..26fd9a4 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__createCredit_simple.sql @@ -0,0 +1,183 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice.sql b/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice.sql new file mode 100644 index 0000000..94fc72b --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice.sql @@ -0,0 +1,170 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice_Details.sql b/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice_Details.sql new file mode 100644 index 0000000..91f1204 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice_Details.sql @@ -0,0 +1,38 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice_ServiceRequest.sql b/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice_ServiceRequest.sql new file mode 100644 index 0000000..634f7d6 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__createInvoice_ServiceRequest.sql @@ -0,0 +1,29 @@ +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; + + DECLARE @InvRqId varchar(10) = [dbo].[fds__fn_invoice-srq_id](); + + INSERT INTO [dbo].[fds__invoice_servicerequests] + ([Id] + ,[InvId] + ,[mfr__servicerequest] + ,[title] + ,[value_net] + ,[SortOrder]) + OUTPUT inserted.* + VALUES + (@InvRqId + ,@InvId + ,@mfr__servicerequest + ,@title + ,@value_net + ,@SortOrder); + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__createReminder.sql b/Fuchs_Database/dbo/Stored Procedures/fds__createReminder.sql new file mode 100644 index 0000000..c3618b4 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__createReminder.sql @@ -0,0 +1,107 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__createStorno_copy.sql b/Fuchs_Database/dbo/Stored Procedures/fds__createStorno_copy.sql new file mode 100644 index 0000000..f5c74c2 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__createStorno_copy.sql @@ -0,0 +1,247 @@ + + +-- ============================================= +-- 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, '')); + + BEGIN TRANSACTION; + + 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 + [Id] = [dbo].[fds__fn_invoice-srq_id]() + ,[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] + ([Id] + ,[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; + + COMMIT TRANSACTION; + + + EXECUTE [dbo].[fds__getInvoice] @newid, @authuser; + + + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__createStorno_simple.sql b/Fuchs_Database/dbo/Stored Procedures/fds__createStorno_simple.sql new file mode 100644 index 0000000..b8a491b --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__createStorno_simple.sql @@ -0,0 +1,191 @@ + + +-- ============================================= +-- 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] + ([Id] + ,[InvId] + ,[mfr__servicerequest] + ,[title] + ,[value_net] + ,[SortOrder]) + OUTPUT + inserted.* INTO @inv_srq + SELECT TOP(1) + [dbo].[fds__fn_invoice-srq_id]() + ,[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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__fn_getMFRInvoicesWithoutfiles.sql b/Fuchs_Database/dbo/Stored Procedures/fds__fn_getMFRInvoicesWithoutfiles.sql new file mode 100644 index 0000000..816a51a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__fn_getMFRInvoicesWithoutfiles.sql @@ -0,0 +1,14 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_list.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_list.sql new file mode 100644 index 0000000..b0806b1 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_list.sql @@ -0,0 +1,71 @@ + +-- ============================================= +-- 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.[taID] + --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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_list2.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_list2.sql new file mode 100644 index 0000000..0de8601 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_list2.sql @@ -0,0 +1,86 @@ + +-- ============================================= +-- 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.[taID] + --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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_questionable.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_questionable.sql new file mode 100644 index 0000000..d935289 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getBankingtransfers_questionable.sql @@ -0,0 +1,81 @@ +-- ============================================= +-- 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.[taID] + 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.[taID] + --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.[taID] = bts.[taID] + --LEFT JOIN [dbo].[fds__getInvoiceCredits] (null, null) as ic ON ic.[taID] = bt.[taID] + --LEFT JOIN inv on inv.[InvoiceId] = ic.[invoiceid] + LEFT JOIN inv on inv.[taID] = bt.[taID] + 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getDatevExports.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getDatevExports.sql new file mode 100644 index 0000000..2f64508 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getDatevExports.sql @@ -0,0 +1,555 @@ + +-- ============================================= +-- 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), [name] varchar(100), [vat] numeric(5,2)); + insert into @contraaccounts + SELECT [account] = [key], [name] = [value], [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 [dbo].[fds__invoice_details] as d on iv.[Id] = d.[InvId] + LEFT JOIN sc on iv.[id] = sc.[invoice.Id] + LEFT JOIN @contraaccounts as ca ON (CASE WHEN d.InvoiceOptions like '%§13b%' and RIGHT(ca.[name], 3) = '13b' then 1 WHEN d.InvoiceOptions like '%§13b%' THEN 0 when ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] THEN 1 ELSE 0 END) = 1 + 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getFDSDocument.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getFDSDocument.sql new file mode 100644 index 0000000..9217ccd --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getFDSDocument.sql @@ -0,0 +1,31 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getInvPayments.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getInvPayments.sql new file mode 100644 index 0000000..f28a3ab --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getInvPayments.sql @@ -0,0 +1,49 @@ +-- ============================================= +-- 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.[taID], [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.[taID], [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 [taID], [invid], manu = CAST(MAX(CAST([manu] as int)) as bit) + from bs1 + GROUP BY [taID], [invid] + ) + SELECT + bs.[taID] + , [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.[taID] = bs.[taID]; +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getInvRequestItems.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getInvRequestItems.sql new file mode 100644 index 0000000..ca3452c --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getInvRequestItems.sql @@ -0,0 +1,53 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getInvoice.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoice.sql new file mode 100644 index 0000000..68b0bc3 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoice.sql @@ -0,0 +1,108 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getInvoiceReminder.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoiceReminder.sql new file mode 100644 index 0000000..e895e20 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoiceReminder.sql @@ -0,0 +1,34 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list.sql new file mode 100644 index 0000000..bd6cd9a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list.sql @@ -0,0 +1,152 @@ + +-- ============================================= +-- 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], [name] = [value], [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 [dbo].[fds__invoice_details] as d on iv.[Id] = d.[InvId] + 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 (CASE WHEN d.InvoiceOptions like '%§13b%' and RIGHT(ca.[name], 3) = '13b' then 1 WHEN d.InvoiceOptions like '%§13b%' THEN 0 when ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] THEN 1 ELSE 0 END) = 1 + 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list2.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list2.sql new file mode 100644 index 0000000..8a89422 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list2.sql @@ -0,0 +1,193 @@ + + +-- ============================================= +-- 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], [name] = [value], [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] + ,[13b] = CAST( CASE WHEN d.InvoiceOptions like '%§13b%' THEN 1 ELSE 0 END as bit) + from [dbo].[fds__invoices] as iv + LEFT JOIN [dbo].[fds__invoice_details] as d on iv.[Id] = d.[InvId] + 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 (CASE WHEN d.InvoiceOptions like '%§13b%' and RIGHT(ca.[name], 3) = '13b' then 1 WHEN d.InvoiceOptions like '%§13b%' THEN 0 when ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] THEN 1 ELSE 0 END) = 1 + 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list_vario.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list_vario.sql new file mode 100644 index 0000000..0b1978e --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getInvoices_list_vario.sql @@ -0,0 +1,188 @@ + +-- ============================================= +-- 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], [name] = [value], [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 [dbo].[fds__invoice_details] as d on iv.[Id] = d.[InvId] + 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 (CASE WHEN d.InvoiceOptions like '%§13b%' and RIGHT(ca.[name], 3) = '13b' then 1 WHEN d.InvoiceOptions like '%§13b%' THEN 0 when ISNULL(iv.[InvoiceVAT_1], 19.0) = ca.[vat] THEN 1 ELSE 0 END) = 1 + 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getReminder.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getReminder.sql new file mode 100644 index 0000000..3d726f0 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getReminder.sql @@ -0,0 +1,79 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getReportDocument.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getReportDocument.sql new file mode 100644 index 0000000..8f92b85 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getReportDocument.sql @@ -0,0 +1,23 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getRequest_details.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getRequest_details.sql new file mode 100644 index 0000000..e909bed --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getRequest_details.sql @@ -0,0 +1,399 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getRequests_list.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getRequests_list.sql new file mode 100644 index 0000000..aa756d3 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getRequests_list.sql @@ -0,0 +1,271 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__getRequests_list2.sql b/Fuchs_Database/dbo/Stored Procedures/fds__getRequests_list2.sql new file mode 100644 index 0000000..d690e60 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__getRequests_list2.sql @@ -0,0 +1,301 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__logEmail.sql b/Fuchs_Database/dbo/Stored Procedures/fds__logEmail.sql new file mode 100644 index 0000000..0064ea8 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__logEmail.sql @@ -0,0 +1,34 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__lookupReminders.sql b/Fuchs_Database/dbo/Stored Procedures/fds__lookupReminders.sql new file mode 100644 index 0000000..1b03d4f --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__lookupReminders.sql @@ -0,0 +1,113 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__maint__updateCancelledStatus.sql b/Fuchs_Database/dbo/Stored Procedures/fds__maint__updateCancelledStatus.sql new file mode 100644 index 0000000..8b318c0 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__maint__updateCancelledStatus.sql @@ -0,0 +1,41 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__merge_bankingtransactions.sql b/Fuchs_Database/dbo/Stored Procedures/fds__merge_bankingtransactions.sql new file mode 100644 index 0000000..6f1b07d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__merge_bankingtransactions.sql @@ -0,0 +1,120 @@ +-- ============================================= +-- 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 + ([taID] + ,[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 + ( [dbo].[fds__fn_bankingtransaction_id]() + , 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 [valuedate]) as [order] + FROM [dbo].[fds__bankingtransactions] + ) + DELETE FROM b where [order] > 1; + + + --Process transactions and assignments + + EXECUTE [dbo].[fds__setBankingtransaction_autoAssigns]; + EXECUTE [dbo].[fds__setInvoicePaymentStatus_auto]; + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__prepInvoice.sql b/Fuchs_Database/dbo/Stored Procedures/fds__prepInvoice.sql new file mode 100644 index 0000000..82dae8d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__prepInvoice.sql @@ -0,0 +1,470 @@ + +-- ============================================= +-- 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(10,2)) + --, [bo_val] = CAST( ((ISNULL([Price],0) * ISNULL([quantityhours],1)) - ISNULL([discount],0)) * (1 + (ISNULL(vat.[vat], 19.0) * 0.01)) as numeric(10,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(10,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(10,2)) + , [bo_val] = CAST( 1000.0 * 1.19 as numeric(10,2)) + , [vat] = FORMAT( 19.0, '#0.0','de') + '%' + , [vat_val] = CAST( 1000.0 * 0.19 as numeric(10,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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__prepReminder.sql b/Fuchs_Database/dbo/Stored Procedures/fds__prepReminder.sql new file mode 100644 index 0000000..dd356e1 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__prepReminder.sql @@ -0,0 +1,58 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__prepStorno_recreate.sql b/Fuchs_Database/dbo/Stored Procedures/fds__prepStorno_recreate.sql new file mode 100644 index 0000000..995934b --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__prepStorno_recreate.sql @@ -0,0 +1,462 @@ + + +-- ============================================= +-- 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 **/ + + + --admin + + 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; + + + --servicerequests + + SELECT + * + ,[order] = ROW_NUMBER() OVER (ORDER BY [baseorder]) + FROM @SReq; + + + + --items + + 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByMonth.sql b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByMonth.sql new file mode 100644 index 0000000..2538e91 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByMonth.sql @@ -0,0 +1,53 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByYearTopCustomer.sql b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByYearTopCustomer.sql new file mode 100644 index 0000000..2bf8960 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByYearTopCustomer.sql @@ -0,0 +1,72 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByYearTopMaterial.sql b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByYearTopMaterial.sql new file mode 100644 index 0000000..1dc599b --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceByYearTopMaterial.sql @@ -0,0 +1,72 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceTrendByMonth.sql b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceTrendByMonth.sql new file mode 100644 index 0000000..23023a4 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceTrendByMonth.sql @@ -0,0 +1,64 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceTrendByYear.sql b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceTrendByYear.sql new file mode 100644 index 0000000..b26bc23 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__r_getBalanceTrendByYear.sql @@ -0,0 +1,63 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice.sql b/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice.sql new file mode 100644 index 0000000..565b65e --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice.sql @@ -0,0 +1,53 @@ +-- ============================================= +-- 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 , ''); + + + BEGIN TRANSACTION + + DECLARE @out TABLE([InvId] varchar(10), [json] nvarchar(max)); + + INSERT INTO [dbo].[fds__removed] ([Id], [json],[dateDeleted_utc]) + OUTPUT inserted.[Id], inserted.[json] + Into @out + SELECT [Id] + , [json] = ( + SELECT + [invoice] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoices] where [Id] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)) + , [items] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoice_items] where [invId] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)) + , [servicerequests] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoice_servicerequests] where [invId] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)) + , [details] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoice_details] where [invId] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)) + FROM (VALUES([Id])) as Inv ([InvId]) + FOR JSON PATH, WITHOUT_ARRAY_WRAPPER + ) + , [dateDeleted_utc] = GETUTCDATE() + FROM [dbo].[fds__invoices] WHERE [Id] = @Id AND @Id is not null AND [isFinal] = 0 AND [IsSent] = 0 + ; + + IF EXISTS(SELECT 0 FROM @out CROSS APPLY OPENJSON([json]) where [key] = 'invoice') + BEGIN + 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 + + COMMIT TRANSACTION; + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice_Items.sql b/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice_Items.sql new file mode 100644 index 0000000..afc2764 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice_Items.sql @@ -0,0 +1,18 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice_ServiceRequests.sql b/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice_ServiceRequests.sql new file mode 100644 index 0000000..a171994 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__remInvoice_ServiceRequests.sql @@ -0,0 +1,18 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_assignToIvoice.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_assignToIvoice.sql new file mode 100644 index 0000000..52bffeb --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_assignToIvoice.sql @@ -0,0 +1,52 @@ + + +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE PROCEDURE [dbo].[fds__setBankingtransaction_assignToIvoice] + @taID varchar(10) + ,@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: ' + @taID + ', invoice_id: ' + @invoice_id)); + + + DECLARE @now datetime = GETUTCDATE(); + DECLARE @today date = @now; + + DECLARE @OUT TABLE([uid] varchar(10), [assigned_invoice_id] varchar(25)); + + MERGE [dbo].[fds__bankingtransactions_settings] as TARGET + USING (SELECT TOP(1) * FROM [dbo].[fds__bankingtransactions] as b WHERE b.[taID] = @taID) as SOURCE ON TARGET.[taID] = SOURCE.[taID] + 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 ([taID],[assigned_invoice_id]) VALUES (SOURCE.[taID], @invoice_id) + OUTPUT inserted.[taID], 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_autoAssigns.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_autoAssigns.sql new file mode 100644 index 0000000..a06642c --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_autoAssigns.sql @@ -0,0 +1,72 @@ +-- ============================================= +-- 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([taID] varchar(10), [auto_invoice_id] varchar(255)); + + + with + icr as ( + SELECT * FROM [dbo].[fds__getInvoiceCredits] (null, null) + ), ic as ( + SELECT + icr.[taID] + , 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 [taID] = ic.[taID] + , [amount] = SUM(ISNULL(ic.[amount], 0.0)) + , [InvID_csv] = STRING_AGG(ic.[InvID], ',') + from ic + WHERE ic.[InvID] is not null + GROUP BY ic.[taID] + ) + --select * from ic2 + MERGE [dbo].[fds__bankingtransactions_settings] as TARGET + USING ic2 as SOURCE ON TARGET.[taID] = SOURCE.[taID] + WHEN NOT MATCHED BY TARGET THEN + INSERT + ([taID] + ,[auto_invoice_id]) + VALUES + (SOURCE.[taID] + ,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.[taID], inserted.[auto_invoice_id] + INTO @out; + + + WITH SOURCE as ( + SELECT [taID], [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.[taID] = SOURCE.[taID] AND TARGET.[invoice_id] = SOURCE.[invoice_id] + WHEN NOT MATCHED BY TARGET THEN + INSERT ([taID], [invoice_id], [auto]) VALUES (SOURCE.[taID], SOURCE.[invoice_id], SOURCE.[auto]) + WHEN NOT MATCHED BY SOURCE AND EXISTS (SELECT NULL FROM @out as o WHERE o.[taID] = TARGET.[taID]) THEN + DELETE; + + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_done.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_done.sql new file mode 100644 index 0000000..9662086 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setBankingtransaction_done.sql @@ -0,0 +1,40 @@ + +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE PROCEDURE [dbo].[fds__setBankingtransaction_done] + @taID varchar(100) + ,@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([taID] varchar(10), [done_manually] varchar(25)); + + MERGE [dbo].[fds__bankingtransactions_settings] as TARGET + USING (SELECT TOP(1) * FROM [dbo].[fds__bankingtransactions] as b WHERE b.[taID] = @taID) as SOURCE ON TARGET.[taID] = SOURCE.[taID] + WHEN MATCHED THEN + UPDATE SET [done_manually] = FORMAT(@now, 'yyyy-MM-dd HH:mm:ss') + ';' + @authuser + WHEN NOT MATCHED BY TARGET THEN + INSERT ([taID],[done_manually]) VALUES (SOURCE.[taID], FORMAT(@now, 'yyyy-MM-dd HH:mm:ss') + ';' + @authuser) + OUTPUT inserted.[taID], 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoice.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoice.sql new file mode 100644 index 0000000..e979248 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoice.sql @@ -0,0 +1,180 @@ +-- ============================================= +-- 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') + ,REPLACE(REPLACE(REPLACE(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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceCancelled__deprecated.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceCancelled__deprecated.sql new file mode 100644 index 0000000..1c4d3cb --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceCancelled__deprecated.sql @@ -0,0 +1,22 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceFile.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceFile.sql new file mode 100644 index 0000000..d09064d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceFile.sql @@ -0,0 +1,25 @@ +-- ============================================= +-- 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) + , [InvoiceTitle] = REPLACE(REPLACE(REPLACE([InvoiceTitle], ' ',''),'

', ''),'

','') + , [DocumentName] = REPLACE(REPLACE(REPLACE(([dbo].[fds__fn_DocumentName]([InvoiceId],REPLACE(REPLACE(REPLACE([InvoiceType], ' ',''),'

', ''),'

',''),[InvoiceTitle],[DateFinalized])), ' ',''),'

', ''),'

','') + OUTPUT inserted.[Id] + WHERE [Id] = @Id AND @Id is not null and [file] is null; + +END \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceFinal.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceFinal.sql new file mode 100644 index 0000000..8bdc449 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceFinal.sql @@ -0,0 +1,66 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePayed.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePayed.sql new file mode 100644 index 0000000..c8db03d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePayed.sql @@ -0,0 +1,25 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePaymentStatus_auto.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePaymentStatus_auto.sql new file mode 100644 index 0000000..cb447f1 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePaymentStatus_auto.sql @@ -0,0 +1,51 @@ +-- ============================================= +-- 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.[taID] + , 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.[taID] = bs.[taID] + 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 [taID] = ic.[taID] + , [amount] = SUM(ISNULL(ic.[amount], 0.0)) + , ic.[invoiceid] + , ic.[InvID] + , ic.[auto] + from ic + WHERE ic.[invoiceid] is not null + GROUP BY ic.[taID], 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePaymentStatus_auto_single.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePaymentStatus_auto_single.sql new file mode 100644 index 0000000..e40b713 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoicePaymentStatus_auto_single.sql @@ -0,0 +1,51 @@ +-- ============================================= +-- 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.[taID] + , 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.[taID] = bs.[taID] + 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.[taID] + , [amount] = SUM(ISNULL(ic.[amount], 0.0)) + , ic.[invoiceid] + , ic.[InvID] + , ic.[auto] + from ic + WHERE ic.[invoiceid] is not null + GROUP BY ic.[taID], 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceSent.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceSent.sql new file mode 100644 index 0000000..ed4424a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceSent.sql @@ -0,0 +1,19 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceUNPayed.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceUNPayed.sql new file mode 100644 index 0000000..f3f626a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setInvoiceUNPayed.sql @@ -0,0 +1,37 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setMFRInvoiceFile.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setMFRInvoiceFile.sql new file mode 100644 index 0000000..d9e1467 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setMFRInvoiceFile.sql @@ -0,0 +1,30 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setReminderFile.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setReminderFile.sql new file mode 100644 index 0000000..7c5e311 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setReminderFile.sql @@ -0,0 +1,21 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setReminderFinal.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setReminderFinal.sql new file mode 100644 index 0000000..dbde3fa --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setReminderFinal.sql @@ -0,0 +1,35 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setReminderSent.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setReminderSent.sql new file mode 100644 index 0000000..f818ff5 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setReminderSent.sql @@ -0,0 +1,20 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setReportVAT.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setReportVAT.sql new file mode 100644 index 0000000..1ea1438 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setReportVAT.sql @@ -0,0 +1,27 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__setStatus.sql b/Fuchs_Database/dbo/Stored Procedures/fds__setStatus.sql new file mode 100644 index 0000000..373d92e --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__setStatus.sql @@ -0,0 +1,29 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fds__toggleRequestHidden.sql b/Fuchs_Database/dbo/Stored Procedures/fds__toggleRequestHidden.sql new file mode 100644 index 0000000..0a3f89d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fds__toggleRequestHidden.sql @@ -0,0 +1,28 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_addGroupMember.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_addGroupMember.sql new file mode 100644 index 0000000..b816fe4 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_addGroupMember.sql @@ -0,0 +1,37 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_createUserAccount.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_createUserAccount.sql new file mode 100644 index 0000000..5d2c7f0 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_createUserAccount.sql @@ -0,0 +1,60 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_debug.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_debug.sql new file mode 100644 index 0000000..94f70d3 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_debug.sql @@ -0,0 +1,53 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_delUserAccount.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_delUserAccount.sql new file mode 100644 index 0000000..2febd1b --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_delUserAccount.sql @@ -0,0 +1,29 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_delUserGroup.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_delUserGroup.sql new file mode 100644 index 0000000..a83e585 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_delUserGroup.sql @@ -0,0 +1,29 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_remGroupMember.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_remGroupMember.sql new file mode 100644 index 0000000..13e8462 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_remGroupMember.sql @@ -0,0 +1,30 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_resetUserPassword.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_resetUserPassword.sql new file mode 100644 index 0000000..84f05b5 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_resetUserPassword.sql @@ -0,0 +1,36 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_setNewPassword.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setNewPassword.sql new file mode 100644 index 0000000..38e5c9f --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setNewPassword.sql @@ -0,0 +1,42 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserAccount.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserAccount.sql new file mode 100644 index 0000000..ebc564e --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserAccount.sql @@ -0,0 +1,106 @@ + + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserAccount_activeStatus.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserAccount_activeStatus.sql new file mode 100644 index 0000000..978d6b3 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserAccount_activeStatus.sql @@ -0,0 +1,48 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserGroup.sql b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserGroup.sql new file mode 100644 index 0000000..9c32074 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_admin_setUserGroup.sql @@ -0,0 +1,61 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_widgets_getCache.sql b/Fuchs_Database/dbo/Stored Procedures/fis_widgets_getCache.sql new file mode 100644 index 0000000..62944ea --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_widgets_getCache.sql @@ -0,0 +1,35 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fis_widgets_setCache.sql b/Fuchs_Database/dbo/Stored Procedures/fis_widgets_setCache.sql new file mode 100644 index 0000000..d2d3f36 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fis_widgets_setCache.sql @@ -0,0 +1,30 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getNext.sql b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getNext.sql new file mode 100644 index 0000000..2096081 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getNext.sql @@ -0,0 +1,160 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getPrev.sql b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getPrev.sql new file mode 100644 index 0000000..3ac5783 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getPrev.sql @@ -0,0 +1,157 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getSummary.sql b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getSummary.sql new file mode 100644 index 0000000..1ddcc84 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_getSummary.sql @@ -0,0 +1,157 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_submit.sql b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_submit.sql new file mode 100644 index 0000000..2a4c37f --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/fuchs_planner_submit.sql @@ -0,0 +1,21 @@ + + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__getSchema.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__getSchema.sql new file mode 100644 index 0000000..9525c45 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__getSchema.sql @@ -0,0 +1,170 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__#customvalues.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__#customvalues.sql new file mode 100644 index 0000000..82e8d7a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__#customvalues.sql @@ -0,0 +1,46 @@ + +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__#locations.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__#locations.sql new file mode 100644 index 0000000..af324f7 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__#locations.sql @@ -0,0 +1,67 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt___PartnerSet.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt___PartnerSet.sql new file mode 100644 index 0000000..4f2d5fc --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt___PartnerSet.sql @@ -0,0 +1,43 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__appointments.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__appointments.sql new file mode 100644 index 0000000..9cad13d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__appointments.sql @@ -0,0 +1,66 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__attachments.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__attachments.sql new file mode 100644 index 0000000..47cac02 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__attachments.sql @@ -0,0 +1,39 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__comments.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__comments.sql new file mode 100644 index 0000000..88b654b --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__comments.sql @@ -0,0 +1,48 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__companies.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__companies.sql new file mode 100644 index 0000000..965d0df --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__companies.sql @@ -0,0 +1,102 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__contacts.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__contacts.sql new file mode 100644 index 0000000..041ed52 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__contacts.sql @@ -0,0 +1,78 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__costcenters.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__costcenters.sql new file mode 100644 index 0000000..82e637d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__costcenters.sql @@ -0,0 +1,36 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__documents.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__documents.sql new file mode 100644 index 0000000..9aea05f --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__documents.sql @@ -0,0 +1,78 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__invoices.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__invoices.sql new file mode 100644 index 0000000..070e4f1 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__invoices.sql @@ -0,0 +1,83 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__items.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__items.sql new file mode 100644 index 0000000..b65f660 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__items.sql @@ -0,0 +1,99 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__itemtypes.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__itemtypes.sql new file mode 100644 index 0000000..9dcd48a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__itemtypes.sql @@ -0,0 +1,90 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__itemunits.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__itemunits.sql new file mode 100644 index 0000000..57c586e --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__itemunits.sql @@ -0,0 +1,36 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__products.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__products.sql new file mode 100644 index 0000000..41e560f --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__products.sql @@ -0,0 +1,51 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__qualifications.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__qualifications.sql new file mode 100644 index 0000000..7ec320a --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__qualifications.sql @@ -0,0 +1,36 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__reports.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__reports.sql new file mode 100644 index 0000000..9829bb5 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__reports.sql @@ -0,0 +1,75 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__serviceobjects.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__serviceobjects.sql new file mode 100644 index 0000000..5dffeb8 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__serviceobjects.sql @@ -0,0 +1,93 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__servicerequests.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__servicerequests.sql new file mode 100644 index 0000000..0816004 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__servicerequests.sql @@ -0,0 +1,170 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steplisttemplateinstances.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steplisttemplateinstances.sql new file mode 100644 index 0000000..1430214 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steplisttemplateinstances.sql @@ -0,0 +1,42 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steplisttemplates.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steplisttemplates.sql new file mode 100644 index 0000000..eff731b --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steplisttemplates.sql @@ -0,0 +1,59 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steps.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steps.sql new file mode 100644 index 0000000..3502e29 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__steps.sql @@ -0,0 +1,149 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__stockmovements.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__stockmovements.sql new file mode 100644 index 0000000..ce64d68 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__stockmovements.sql @@ -0,0 +1,75 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__tags.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__tags.sql new file mode 100644 index 0000000..8307e4d --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__tags.sql @@ -0,0 +1,46 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__timeevents.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__timeevents.sql new file mode 100644 index 0000000..92d43aa --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__timeevents.sql @@ -0,0 +1,66 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Stored Procedures/mfr__updt__users.sql b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__users.sql new file mode 100644 index 0000000..e38f3c8 --- /dev/null +++ b/Fuchs_Database/dbo/Stored Procedures/mfr__updt__users.sql @@ -0,0 +1,109 @@ +-- ============================================= +-- 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 \ No newline at end of file diff --git a/Fuchs_Database/dbo/Tables/fds__admin_activity.sql b/Fuchs_Database/dbo/Tables/fds__admin_activity.sql new file mode 100644 index 0000000..e5ebf9d --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__admin_activity.sql @@ -0,0 +1,9 @@ +CREATE TABLE [dbo].[fds__admin_activity] ( + [uid] BIGINT IDENTITY (1, 1) NOT NULL, + [timestamp] DATETIME CONSTRAINT [DF_fds__admin_activity_timestamp] DEFAULT (getutcdate()) NOT NULL, + [activity] VARCHAR (50) NOT NULL, + [authuser] VARCHAR (10) NULL, + [info] VARCHAR (1000) NULL, + [data] NVARCHAR (MAX) NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fds__admin_dberrors.sql b/Fuchs_Database/dbo/Tables/fds__admin_dberrors.sql new file mode 100644 index 0000000..b0b8da2 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__admin_dberrors.sql @@ -0,0 +1,12 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/fds__admin_reportcatalog.sql b/Fuchs_Database/dbo/Tables/fds__admin_reportcatalog.sql new file mode 100644 index 0000000..8ec1a9e --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__admin_reportcatalog.sql @@ -0,0 +1,17 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/fds__admin_settings.sql b/Fuchs_Database/dbo/Tables/fds__admin_settings.sql new file mode 100644 index 0000000..677fd81 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__admin_settings.sql @@ -0,0 +1,9 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__bankingtransactions.sql b/Fuchs_Database/dbo/Tables/fds__bankingtransactions.sql new file mode 100644 index 0000000..6a55b3f --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__bankingtransactions.sql @@ -0,0 +1,37 @@ +CREATE TABLE [dbo].[fds__bankingtransactions] ( + [taID] VARCHAR (10) 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, + CONSTRAINT [PK_fds__bankingtransactions] PRIMARY KEY CLUSTERED ([taID] ASC) +); + + +GO +CREATE NONCLUSTERED INDEX [fds__bankingtransactions__ix1] + ON [dbo].[fds__bankingtransactions]([taID] ASC) + INCLUDE([Amount]); + diff --git a/Fuchs_Database/dbo/Tables/fds__bankingtransactions_assigns.sql b/Fuchs_Database/dbo/Tables/fds__bankingtransactions_assigns.sql new file mode 100644 index 0000000..23d66e0 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__bankingtransactions_assigns.sql @@ -0,0 +1,6 @@ +CREATE TABLE [dbo].[fds__bankingtransactions_assigns] ( + [taID] VARCHAR (10) NOT NULL, + [invoice_id] VARCHAR (15) NULL, + [auto] BIT NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fds__bankingtransactions_settings.sql b/Fuchs_Database/dbo/Tables/fds__bankingtransactions_settings.sql new file mode 100644 index 0000000..1b6c2ff --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__bankingtransactions_settings.sql @@ -0,0 +1,7 @@ +CREATE TABLE [dbo].[fds__bankingtransactions_settings] ( + [taID] VARCHAR (10) NOT NULL, + [done_manually] VARCHAR (25) NULL, + [assigned_invoice_id] VARCHAR (255) NULL, + [auto_invoice_id] VARCHAR (255) NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fds__custom_invoiceinfo.sql b/Fuchs_Database/dbo/Tables/fds__custom_invoiceinfo.sql new file mode 100644 index 0000000..6831e98 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__custom_invoiceinfo.sql @@ -0,0 +1,8 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__custom_servicerequest.sql b/Fuchs_Database/dbo/Tables/fds__custom_servicerequest.sql new file mode 100644 index 0000000..aa1067e --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__custom_servicerequest.sql @@ -0,0 +1,6 @@ +CREATE TABLE [dbo].[fds__custom_servicerequest] ( + [EntityId] BIGINT NOT NULL, + [hidden] BIT NOT NULL, + CONSTRAINT [PK_fds__custom_servicerequest] PRIMARY KEY CLUSTERED ([EntityId] ASC) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__custom_vat.sql b/Fuchs_Database/dbo/Tables/fds__custom_vat.sql new file mode 100644 index 0000000..099135d --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__custom_vat.sql @@ -0,0 +1,8 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__debuglog.sql b/Fuchs_Database/dbo/Tables/fds__debuglog.sql new file mode 100644 index 0000000..8a1b197 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__debuglog.sql @@ -0,0 +1,9 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/fds__emaillog.sql b/Fuchs_Database/dbo/Tables/fds__emaillog.sql new file mode 100644 index 0000000..9de0f38 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__emaillog.sql @@ -0,0 +1,11 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__invoice_details.sql b/Fuchs_Database/dbo/Tables/fds__invoice_details.sql new file mode 100644 index 0000000..42f87d5 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__invoice_details.sql @@ -0,0 +1,11 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__invoice_items.sql b/Fuchs_Database/dbo/Tables/fds__invoice_items.sql new file mode 100644 index 0000000..2d9c116 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__invoice_items.sql @@ -0,0 +1,23 @@ +CREATE TABLE [dbo].[fds__invoice_items] ( + [Id] BIGINT IDENTITY (1, 1) NOT NULL, + [InvId] VARCHAR (10) NOT NULL, + [InvRqId] VARCHAR (10) 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 +); + + +GO +CREATE NONCLUSTERED INDEX [fds__invoice_items__ix1] + ON [dbo].[fds__invoice_items]([InvId] ASC); + diff --git a/Fuchs_Database/dbo/Tables/fds__invoice_servicerequests.sql b/Fuchs_Database/dbo/Tables/fds__invoice_servicerequests.sql new file mode 100644 index 0000000..5d3a67b --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__invoice_servicerequests.sql @@ -0,0 +1,15 @@ +CREATE TABLE [dbo].[fds__invoice_servicerequests] ( + [Id] VARCHAR (10) 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, + CONSTRAINT [PK_fds__invoice_servicerequests] PRIMARY KEY CLUSTERED ([Id] ASC) +); + + +GO +CREATE NONCLUSTERED INDEX [fds__invoice_servicerequests__ix1] + ON [dbo].[fds__invoice_servicerequests]([mfr__servicerequest] ASC); + diff --git a/Fuchs_Database/dbo/Tables/fds__invoices.sql b/Fuchs_Database/dbo/Tables/fds__invoices.sql new file mode 100644 index 0000000..26fefab --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__invoices.sql @@ -0,0 +1,50 @@ +CREATE TABLE [dbo].[fds__invoices] ( + [Id] VARCHAR (10) NOT NULL, + [Version] INT CONSTRAINT [DF_fds__invoices_Version] DEFAULT ((0)) NOT NULL, + [InvoiceId] NVARCHAR (25) NULL, + [InvoiceType] CHAR (1) NOT NULL, + [InvoiceTitle] VARCHAR (100) CONSTRAINT [DF_fds__invoices_InvoiceTitle] DEFAULT ('Rechnung') 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 CONSTRAINT [DF_fds__invoices_IsPayed] DEFAULT ((0)) NOT NULL, + [IsSent] BIT CONSTRAINT [DF_fds__invoices_IsSent] DEFAULT ((0)) 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 CONSTRAINT [DF_fds__invoices_external] DEFAULT ((0)) NULL, + [file] VARBINARY (MAX) NULL, + [file_guid] UNIQUEIDENTIFIER CONSTRAINT [DF_fds__invoices_file_guid] DEFAULT (newid()) NOT NULL, + CONSTRAINT [PK_fds__invoices] PRIMARY KEY CLUSTERED ([Id] ASC) +); + + +GO +CREATE NONCLUSTERED INDEX [fds__invoices__ix1] + ON [dbo].[fds__invoices]([IsFinal] ASC, [InvoiceBalance] ASC) + INCLUDE([IsPayed], [IsCanceled], [DateFinalized]); + diff --git a/Fuchs_Database/dbo/Tables/fds__log.sql b/Fuchs_Database/dbo/Tables/fds__log.sql new file mode 100644 index 0000000..3ab202a --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__log.sql @@ -0,0 +1,8 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/fds__mfr_invoicefiles.sql b/Fuchs_Database/dbo/Tables/fds__mfr_invoicefiles.sql new file mode 100644 index 0000000..04d2f22 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__mfr_invoicefiles.sql @@ -0,0 +1,6 @@ +CREATE TABLE [dbo].[fds__mfr_invoicefiles] ( + [Id] BIGINT NOT NULL, + [filename] VARCHAR (100) NOT NULL, + [file] VARBINARY (MAX) NOT NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fds__mfr_updaterequests.sql b/Fuchs_Database/dbo/Tables/fds__mfr_updaterequests.sql new file mode 100644 index 0000000..6690cf6 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__mfr_updaterequests.sql @@ -0,0 +1,6 @@ +CREATE TABLE [dbo].[fds__mfr_updaterequests] ( + [entity_name] VARCHAR (255) NOT NULL, + [Id] BIGINT NOT NULL, + [date_requested] DATETIME CONSTRAINT [DF_fds__mfr_updaterequests_date_requested] DEFAULT (getutcdate()) NOT NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fds__payments.sql b/Fuchs_Database/dbo/Tables/fds__payments.sql new file mode 100644 index 0000000..dbc7a5b --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__payments.sql @@ -0,0 +1,16 @@ +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) CONSTRAINT [DF_fds__payments_IsAllocated] DEFAULT ((0)) 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) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__reminder.sql b/Fuchs_Database/dbo/Tables/fds__reminder.sql new file mode 100644 index 0000000..7c3a3f5 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__reminder.sql @@ -0,0 +1,29 @@ +CREATE TABLE [dbo].[fds__reminder] ( + [Id] VARCHAR (10) NOT NULL, + [Version] INT CONSTRAINT [DF_fds__reminder_Version] DEFAULT ((0)) 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 CONSTRAINT [DF_fds__reminder_IsSent] DEFAULT ((0)) 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) +); + diff --git a/Fuchs_Database/dbo/Tables/fds__removed.sql b/Fuchs_Database/dbo/Tables/fds__removed.sql new file mode 100644 index 0000000..4774b55 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__removed.sql @@ -0,0 +1,6 @@ +CREATE TABLE [dbo].[fds__removed] ( + [Id] VARCHAR (10) NULL, + [json] NVARCHAR (MAX) NULL, + [DateDeleted_utc] DATETIME NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fds__status.sql b/Fuchs_Database/dbo/Tables/fds__status.sql new file mode 100644 index 0000000..bbd7e08 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fds__status.sql @@ -0,0 +1,7 @@ +CREATE TABLE [dbo].[fds__status] ( + [table] VARCHAR (50) NOT NULL, + [action] VARCHAR (50) NOT NULL, + [timestamp] DATETIME NOT NULL, + [setid] VARCHAR (10) NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fis_admin_debuglog.sql b/Fuchs_Database/dbo/Tables/fis_admin_debuglog.sql new file mode 100644 index 0000000..fd6d8ed --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_admin_debuglog.sql @@ -0,0 +1,18 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fis_module_auth.sql b/Fuchs_Database/dbo/Tables/fis_module_auth.sql new file mode 100644 index 0000000..fbd91a3 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_module_auth.sql @@ -0,0 +1,10 @@ +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 CONSTRAINT [DF_fis_module_auth_auth] DEFAULT ((1)) NOT NULL, + CONSTRAINT [PK_fis_module_auth] PRIMARY KEY CLUSTERED ([id] ASC) +); + diff --git a/Fuchs_Database/dbo/Tables/fis_useraccounts.sql b/Fuchs_Database/dbo/Tables/fis_useraccounts.sql new file mode 100644 index 0000000..73a10fb --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_useraccounts.sql @@ -0,0 +1,21 @@ +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) CONSTRAINT [DF_fis_useraccounts_language] DEFAULT ('de') NULL, + [UserDisabled] VARCHAR (36) NULL, + [DateDisabled] DATETIME NULL, + [UserCreated] VARCHAR (36) NOT NULL, + [DateCreated] DATETIME CONSTRAINT [DF_fis_useraccounts_DateCreated] DEFAULT (getutcdate()) NOT NULL, + [UserModified] VARCHAR (36) NULL, + [DateModified] DATETIME CONSTRAINT [DF_fis_useraccounts_DateModified] DEFAULT (getutcdate()) NOT NULL, + [UserDeleted] VARCHAR (36) NULL, + [DateDeleted] DATETIME NULL, + CONSTRAINT [PK_fis_useraccounts] PRIMARY KEY CLUSTERED ([useraccount_id] ASC) +); + diff --git a/Fuchs_Database/dbo/Tables/fis_useraccounts_settings.sql b/Fuchs_Database/dbo/Tables/fis_useraccounts_settings.sql new file mode 100644 index 0000000..f65f95f --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_useraccounts_settings.sql @@ -0,0 +1,10 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fis_usergroups.sql b/Fuchs_Database/dbo/Tables/fis_usergroups.sql new file mode 100644 index 0000000..03cb8be --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_usergroups.sql @@ -0,0 +1,12 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/fis_usergroups_members.sql b/Fuchs_Database/dbo/Tables/fis_usergroups_members.sql new file mode 100644 index 0000000..d7e086f --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_usergroups_members.sql @@ -0,0 +1,10 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/fis_widget_subscriptions.sql b/Fuchs_Database/dbo/Tables/fis_widget_subscriptions.sql new file mode 100644 index 0000000..eb024ef --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_widget_subscriptions.sql @@ -0,0 +1,11 @@ +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 CONSTRAINT [DF_fis_widget_subscriptions_display_order] DEFAULT ((0)) NOT NULL, + [DateCreated] DATETIME CONSTRAINT [DF_fis_widget_subscriptions_DateCreated] DEFAULT (getutcdate()) NOT NULL, + [UserCreated] VARCHAR (36) CONSTRAINT [DF_fis_widget_subscriptions_UserCreated] DEFAULT ('') NOT NULL, + CONSTRAINT [PK_fis_widget_subscriptions] PRIMARY KEY CLUSTERED ([uid] ASC) +); + diff --git a/Fuchs_Database/dbo/Tables/fis_widgets.sql b/Fuchs_Database/dbo/Tables/fis_widgets.sql new file mode 100644 index 0000000..d55b007 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_widgets.sql @@ -0,0 +1,23 @@ +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 CONSTRAINT [DF_fis_widgets_visible] DEFAULT ((1)) NOT NULL, + [auth_module] VARCHAR (50) NULL, + [rendering_options] NVARCHAR (255) NULL, + [server_options] NVARCHAR (2000) NULL, + [daycache] BIT CONSTRAINT [DF_fis_widgets_daychache] DEFAULT ((0)) NOT NULL, + [personalized] BIT CONSTRAINT [DF_fis_widgets_personalized] DEFAULT ((0)) NOT NULL, + [safemode] BIT CONSTRAINT [DF_fis_widgets_safemode] DEFAULT ((0)) NOT NULL, + [variables] VARCHAR (1000) NULL, + CONSTRAINT [PK_fis_widgets] PRIMARY KEY CLUSTERED ([short_name] ASC) +); + diff --git a/Fuchs_Database/dbo/Tables/fis_widgets_cache.sql b/Fuchs_Database/dbo/Tables/fis_widgets_cache.sql new file mode 100644 index 0000000..dd7667f --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fis_widgets_cache.sql @@ -0,0 +1,8 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/fuchs_debug.sql b/Fuchs_Database/dbo/Tables/fuchs_debug.sql new file mode 100644 index 0000000..3a28b17 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fuchs_debug.sql @@ -0,0 +1,8 @@ +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 CONSTRAINT [DF_fuchs_debug_date] DEFAULT (getutcdate()) NOT NULL +); + diff --git a/Fuchs_Database/dbo/Tables/fuchs_planner.sql b/Fuchs_Database/dbo/Tables/fuchs_planner.sql new file mode 100644 index 0000000..2d69230 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fuchs_planner.sql @@ -0,0 +1,9 @@ +CREATE TABLE [dbo].[fuchs_planner] ( + [planner_id] TINYINT NOT NULL, + [shortname] VARCHAR (10) NOT NULL, + [name] VARCHAR (100) NULL, + [description] VARCHAR (2000) NULL, + [active] BIT CONSTRAINT [DF_fuchs_planner_active] DEFAULT ((1)) NOT NULL, + CONSTRAINT [PK_fuchs_planner] PRIMARY KEY CLUSTERED ([planner_id] ASC) +); + diff --git a/Fuchs_Database/dbo/Tables/fuchs_planner_groups.sql b/Fuchs_Database/dbo/Tables/fuchs_planner_groups.sql new file mode 100644 index 0000000..2912ea2 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fuchs_planner_groups.sql @@ -0,0 +1,23 @@ +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 CONSTRAINT [DF_fuchs_planner_groups_order] DEFAULT ((0)) 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 CONSTRAINT [DF_fuchs_planner_groups_final] DEFAULT ((0)) NOT NULL, + [hide] BIT CONSTRAINT [DF_fuchs_planner_groups_hide] DEFAULT ((0)) NOT NULL, + CONSTRAINT [PK_fuchs_planner_groups] PRIMARY KEY CLUSTERED ([group_id] ASC), + CONSTRAINT [FK_fuchs_planner_groups_fuchs_planner] FOREIGN KEY ([planner_id]) REFERENCES [dbo].[fuchs_planner] ([planner_id]), + CONSTRAINT [FK_fuchs_planner_groups_fuchs_planner_groups] FOREIGN KEY ([group_id]) REFERENCES [dbo].[fuchs_planner_groups] ([group_id]) +); + + +GO +CREATE UNIQUE NONCLUSTERED INDEX [IX_fuchs_planner_groups] + ON [dbo].[fuchs_planner_groups]([planner_id] ASC, [sequence_order] ASC); + diff --git a/Fuchs_Database/dbo/Tables/fuchs_planner_options.sql b/Fuchs_Database/dbo/Tables/fuchs_planner_options.sql new file mode 100644 index 0000000..3206b5e --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fuchs_planner_options.sql @@ -0,0 +1,24 @@ +CREATE TABLE [dbo].[fuchs_planner_options] ( + [option_id] INT 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 CONSTRAINT [DF_Table_1_item_oder] DEFAULT ((0)) 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 CONSTRAINT [DF_fuchs_planner_options_hide] DEFAULT ((0)) NOT NULL, + CONSTRAINT [PK_fuchs_planner_options] PRIMARY KEY CLUSTERED ([option_id] ASC), + CONSTRAINT [FK_fuchs_planner_options_fuchs_planner] FOREIGN KEY ([planner_id]) REFERENCES [dbo].[fuchs_planner] ([planner_id]), + CONSTRAINT [FK_fuchs_planner_options_fuchs_planner_groups] FOREIGN KEY ([group_id]) REFERENCES [dbo].[fuchs_planner_groups] ([group_id]) +); + + +GO +CREATE UNIQUE NONCLUSTERED INDEX [IX_fuchs_planner_options] + ON [dbo].[fuchs_planner_options]([planner_id] ASC, [group_id] ASC, [option_order] ASC); + diff --git a/Fuchs_Database/dbo/Tables/fuchs_planner_traffic.sql b/Fuchs_Database/dbo/Tables/fuchs_planner_traffic.sql new file mode 100644 index 0000000..da43633 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/fuchs_planner_traffic.sql @@ -0,0 +1,21 @@ +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 CONSTRAINT [DF_fuchs_planner_traffic_DateSubmitted] DEFAULT (getutcdate()) NOT NULL, + CONSTRAINT [PK_fuchs_planner_traffic] PRIMARY KEY CLUSTERED ([uid] ASC) +); + + +GO +CREATE NONCLUSTERED INDEX [fuchs_planner_traffic__ix2] + ON [dbo].[fuchs_planner_traffic]([planner_id] ASC, [sessionid] ASC) + INCLUDE([group_code], [DateSubmitted]); + + +GO +CREATE NONCLUSTERED INDEX [fuchs_planner_traffic__ix1] + ON [dbo].[fuchs_planner_traffic]([sessionid] ASC); + diff --git a/Fuchs_Database/dbo/Tables/mfr__#customvalues.sql b/Fuchs_Database/dbo/Tables/mfr__#customvalues.sql new file mode 100644 index 0000000..fb843e5 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__#customvalues.sql @@ -0,0 +1,8 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__#locations.sql b/Fuchs_Database/dbo/Tables/mfr__#locations.sql new file mode 100644 index 0000000..22fe226 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__#locations.sql @@ -0,0 +1,27 @@ +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 +); + + +GO +CREATE NONCLUSTERED INDEX [mfr__#locations__ix2] + ON [dbo].[mfr__#locations]([Id] ASC) + INCLUDE([AddressString], [Postal], [City], [State], [Country], [Longitude], [Latitude]); + + +GO +CREATE NONCLUSTERED INDEX [mfr__#locations__ix1] + ON [dbo].[mfr__#locations]([EntityId] ASC, [Property] ASC) + INCLUDE([AddressString], [Postal], [City], [Country]); + diff --git a/Fuchs_Database/dbo/Tables/mfr___PartnerSet.sql b/Fuchs_Database/dbo/Tables/mfr___PartnerSet.sql new file mode 100644 index 0000000..6bdfb1e --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr___PartnerSet.sql @@ -0,0 +1,25 @@ +CREATE TABLE [dbo].[mfr__*PartnerSet] ( + [Property] VARCHAR (50) NOT NULL, + [PartnerType] VARCHAR (25) NOT NULL, + [PartnerId] BIGINT NOT NULL, + [EntityId] BIGINT NOT NULL +); + + +GO +CREATE NONCLUSTERED INDEX [mfr__*PartnerSet__ix3] + ON [dbo].[mfr__*PartnerSet]([Property] ASC, [PartnerId] ASC) + INCLUDE([EntityId]); + + +GO +CREATE NONCLUSTERED INDEX [mfr__*PartnerSet__ix2] + ON [dbo].[mfr__*PartnerSet]([EntityId] ASC, [Property] ASC) + INCLUDE([PartnerId]); + + +GO +CREATE NONCLUSTERED INDEX [mfr__*PartnerSet__ix1] + ON [dbo].[mfr__*PartnerSet]([Property] ASC) + INCLUDE([PartnerId], [EntityId]); + diff --git a/Fuchs_Database/dbo/Tables/mfr__appointments.sql b/Fuchs_Database/dbo/Tables/mfr__appointments.sql new file mode 100644 index 0000000..fbb47f7 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__appointments.sql @@ -0,0 +1,29 @@ +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) +); + + +GO +CREATE NONCLUSTERED INDEX [mfr__appointments__ix2] + ON [dbo].[mfr__appointments]([State] ASC, [ServiceRequestId] ASC) + INCLUDE([EndDateTime], [StartDateTime]); + + +GO +CREATE NONCLUSTERED INDEX [mfr__appointments__ix1] + ON [dbo].[mfr__appointments]([State] ASC) + INCLUDE([EndDateTime], [StartDateTime], [ServiceRequestId]); + diff --git a/Fuchs_Database/dbo/Tables/mfr__attachments.sql b/Fuchs_Database/dbo/Tables/mfr__attachments.sql new file mode 100644 index 0000000..4d574ad --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__attachments.sql @@ -0,0 +1,8 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__comments.sql b/Fuchs_Database/dbo/Tables/mfr__comments.sql new file mode 100644 index 0000000..9583ee9 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__comments.sql @@ -0,0 +1,11 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__companies.sql b/Fuchs_Database/dbo/Tables/mfr__companies.sql new file mode 100644 index 0000000..5d83872 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__companies.sql @@ -0,0 +1,22 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__contacts.sql b/Fuchs_Database/dbo/Tables/mfr__contacts.sql new file mode 100644 index 0000000..693a399 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__contacts.sql @@ -0,0 +1,27 @@ +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) +); + + +GO +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]); + diff --git a/Fuchs_Database/dbo/Tables/mfr__costcenters.sql b/Fuchs_Database/dbo/Tables/mfr__costcenters.sql new file mode 100644 index 0000000..f2f2afa --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__costcenters.sql @@ -0,0 +1,7 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_#customvalues.sql b/Fuchs_Database/dbo/Tables/mfr__d_#customvalues.sql new file mode 100644 index 0000000..17ba91a --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_#customvalues.sql @@ -0,0 +1,9 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_#locations.sql b/Fuchs_Database/dbo/Tables/mfr__d_#locations.sql new file mode 100644 index 0000000..e73df2e --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_#locations.sql @@ -0,0 +1,16 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d__PartnerSet.sql b/Fuchs_Database/dbo/Tables/mfr__d__PartnerSet.sql new file mode 100644 index 0000000..f270dbf --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d__PartnerSet.sql @@ -0,0 +1,8 @@ +CREATE TABLE [dbo].[mfr__d_*PartnerSet] ( + [Property] VARCHAR (50) NULL, + [PartnerType] VARCHAR (25) NULL, + [PartnerId] BIGINT NULL, + [EntityId] BIGINT NULL, + [DateDeleted] DATETIME NULL +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_appointments.sql b/Fuchs_Database/dbo/Tables/mfr__d_appointments.sql new file mode 100644 index 0000000..0a42196 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_appointments.sql @@ -0,0 +1,17 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_comments.sql b/Fuchs_Database/dbo/Tables/mfr__d_comments.sql new file mode 100644 index 0000000..19633dd --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_comments.sql @@ -0,0 +1,11 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_items.sql b/Fuchs_Database/dbo/Tables/mfr__d_items.sql new file mode 100644 index 0000000..08adace --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_items.sql @@ -0,0 +1,28 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_steps.sql b/Fuchs_Database/dbo/Tables/mfr__d_steps.sql new file mode 100644 index 0000000..e416e4f --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_steps.sql @@ -0,0 +1,22 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_stockmovements.sql b/Fuchs_Database/dbo/Tables/mfr__d_stockmovements.sql new file mode 100644 index 0000000..844d13f --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_stockmovements.sql @@ -0,0 +1,20 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__d_timeevents.sql b/Fuchs_Database/dbo/Tables/mfr__d_timeevents.sql new file mode 100644 index 0000000..3e657f2 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__d_timeevents.sql @@ -0,0 +1,17 @@ +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 +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__documents.sql b/Fuchs_Database/dbo/Tables/mfr__documents.sql new file mode 100644 index 0000000..a8a4841 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__documents.sql @@ -0,0 +1,21 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__invoices.sql b/Fuchs_Database/dbo/Tables/mfr__invoices.sql new file mode 100644 index 0000000..91f0ec1 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__invoices.sql @@ -0,0 +1,27 @@ +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 CONSTRAINT [DF_mfr__invoices_file_guid] DEFAULT (newid()) NULL +); + + +GO +CREATE NONCLUSTERED INDEX [mfr__invoices__ix1] + ON [dbo].[mfr__invoices]([Id] ASC, [InvoiceId] ASC); + diff --git a/Fuchs_Database/dbo/Tables/mfr__items.sql b/Fuchs_Database/dbo/Tables/mfr__items.sql new file mode 100644 index 0000000..0c092b9 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__items.sql @@ -0,0 +1,34 @@ +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) +); + + +GO +CREATE NONCLUSTERED INDEX [mfr__items__ix1] + ON [dbo].[mfr__items]([ServiceRequestId] ASC) + INCLUDE([QuantityHours], [Price]); + diff --git a/Fuchs_Database/dbo/Tables/mfr__itemtypes.sql b/Fuchs_Database/dbo/Tables/mfr__itemtypes.sql new file mode 100644 index 0000000..dbcbf53 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__itemtypes.sql @@ -0,0 +1,25 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__itemunits.sql b/Fuchs_Database/dbo/Tables/mfr__itemunits.sql new file mode 100644 index 0000000..2592454 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__itemunits.sql @@ -0,0 +1,7 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__products.sql b/Fuchs_Database/dbo/Tables/mfr__products.sql new file mode 100644 index 0000000..8d19f39 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__products.sql @@ -0,0 +1,12 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__qualifications.sql b/Fuchs_Database/dbo/Tables/mfr__qualifications.sql new file mode 100644 index 0000000..14daaec --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__qualifications.sql @@ -0,0 +1,7 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__reports.sql b/Fuchs_Database/dbo/Tables/mfr__reports.sql new file mode 100644 index 0000000..95d990d --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__reports.sql @@ -0,0 +1,20 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__serviceobjects.sql b/Fuchs_Database/dbo/Tables/mfr__serviceobjects.sql new file mode 100644 index 0000000..38915e0 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__serviceobjects.sql @@ -0,0 +1,19 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__servicerequests.sql b/Fuchs_Database/dbo/Tables/mfr__servicerequests.sql new file mode 100644 index 0000000..9061022 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__servicerequests.sql @@ -0,0 +1,36 @@ +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) +); + + +GO +CREATE NONCLUSTERED INDEX [mfr__servicerequests__ix1] + ON [dbo].[mfr__servicerequests]([InvoiceId] ASC) + INCLUDE([Name], [DateOfCreation], [CustomerId]); + diff --git a/Fuchs_Database/dbo/Tables/mfr__steplisttemplateinstances.sql b/Fuchs_Database/dbo/Tables/mfr__steplisttemplateinstances.sql new file mode 100644 index 0000000..bf31715 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__steplisttemplateinstances.sql @@ -0,0 +1,9 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__steplisttemplates.sql b/Fuchs_Database/dbo/Tables/mfr__steplisttemplates.sql new file mode 100644 index 0000000..263a7db --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__steplisttemplates.sql @@ -0,0 +1,11 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__steps.sql b/Fuchs_Database/dbo/Tables/mfr__steps.sql new file mode 100644 index 0000000..c5cb25d --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__steps.sql @@ -0,0 +1,28 @@ +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) +); + + +GO +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]); + diff --git a/Fuchs_Database/dbo/Tables/mfr__stockmovements.sql b/Fuchs_Database/dbo/Tables/mfr__stockmovements.sql new file mode 100644 index 0000000..cf360d4 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__stockmovements.sql @@ -0,0 +1,20 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__tags.sql b/Fuchs_Database/dbo/Tables/mfr__tags.sql new file mode 100644 index 0000000..d6d8a96 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__tags.sql @@ -0,0 +1,9 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__timeevents.sql b/Fuchs_Database/dbo/Tables/mfr__timeevents.sql new file mode 100644 index 0000000..9425fc7 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__timeevents.sql @@ -0,0 +1,17 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__users.sql b/Fuchs_Database/dbo/Tables/mfr__users.sql new file mode 100644 index 0000000..7553f97 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__users.sql @@ -0,0 +1,21 @@ +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) +); + diff --git a/Fuchs_Database/dbo/Tables/mfr__xl__servicerequests.sql b/Fuchs_Database/dbo/Tables/mfr__xl__servicerequests.sql new file mode 100644 index 0000000..722ab83 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/mfr__xl__servicerequests.sql @@ -0,0 +1,5 @@ +CREATE TABLE [dbo].[mfr__xl__servicerequests] ( + [servicerequest_id] BIGINT NOT NULL, + [invoice_id] BIGINT NOT NULL +); + diff --git a/Fuchs_Database/dbo/Tables/tmp__fds__bankingtransactions.sql b/Fuchs_Database/dbo/Tables/tmp__fds__bankingtransactions.sql new file mode 100644 index 0000000..24a10a4 --- /dev/null +++ b/Fuchs_Database/dbo/Tables/tmp__fds__bankingtransactions.sql @@ -0,0 +1,36 @@ +CREATE TABLE [dbo].[tmp__fds__bankingtransactions] ( + [uid] BIGINT NOT NULL, + [taID] VARCHAR (10) 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 +); + + +GO +CREATE UNIQUE NONCLUSTERED INDEX [IX_tmp__fds__bankingtransactions] + ON [dbo].[tmp__fds__bankingtransactions]([taID] ASC); + diff --git a/Fuchs_Database/dbo/Tables/tmp__fds__invoice_servicerequests.sql b/Fuchs_Database/dbo/Tables/tmp__fds__invoice_servicerequests.sql new file mode 100644 index 0000000..3ecf2ef --- /dev/null +++ b/Fuchs_Database/dbo/Tables/tmp__fds__invoice_servicerequests.sql @@ -0,0 +1,15 @@ +CREATE TABLE [dbo].[tmp__fds__invoice_servicerequests] ( + [Id] BIGINT NOT NULL, + [InvRqId] VARCHAR (10) 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 +); + + +GO +CREATE UNIQUE NONCLUSTERED INDEX [IX_tmp__fds__invoice_servicerequests] + ON [dbo].[tmp__fds__invoice_servicerequests]([InvRqId] ASC); + diff --git a/Fuchs_Database/dbo/User Defined Types/datetime_utc.sql b/Fuchs_Database/dbo/User Defined Types/datetime_utc.sql new file mode 100644 index 0000000..0a182c3 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/datetime_utc.sql @@ -0,0 +1,3 @@ +CREATE TYPE [dbo].[datetime_utc] + FROM DATETIME NULL; + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__admin_ReportAdminTable.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__admin_ReportAdminTable.sql new file mode 100644 index 0000000..d31eab8 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__admin_ReportAdminTable.sql @@ -0,0 +1,12 @@ +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)); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__bankingtransactions.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__bankingtransactions.sql new file mode 100644 index 0000000..b803362 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__bankingtransactions.sql @@ -0,0 +1,28 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__idlist.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__idlist.sql new file mode 100644 index 0000000..39abed3 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__idlist.sql @@ -0,0 +1,3 @@ +CREATE TYPE [dbo].[fds__tt__idlist] AS TABLE ( + [Id] BIGINT NULL); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__idlist_vchar.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__idlist_vchar.sql new file mode 100644 index 0000000..d2be966 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__idlist_vchar.sql @@ -0,0 +1,3 @@ +CREATE TYPE [dbo].[fds__tt__idlist_vchar] AS TABLE ( + [Id] VARCHAR (15) NULL); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_base.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_base.sql new file mode 100644 index 0000000..56bfcf7 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_base.sql @@ -0,0 +1,48 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_core.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_core.sql new file mode 100644 index 0000000..6e53ac6 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_core.sql @@ -0,0 +1,39 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_items.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_items.sql new file mode 100644 index 0000000..93a2202 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_items.sql @@ -0,0 +1,17 @@ +CREATE TYPE [dbo].[fds__tt__invoice_items] AS TABLE ( + [Id] BIGINT NULL, + [InvId] VARCHAR (10) NULL, + [InvRqId] VARCHAR (10) 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); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_servicerequests.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_servicerequests.sql new file mode 100644 index 0000000..17f379d --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__invoice_servicerequests.sql @@ -0,0 +1,8 @@ +CREATE TYPE [dbo].[fds__tt__invoice_servicerequests] AS TABLE ( + [Id] VARCHAR (10) NULL, + [InvId] VARCHAR (10) NULL, + [mfr__servicerequest] BIGINT NULL, + [title] NVARCHAR (MAX) NULL, + [value_net] NUMERIC (10, 2) NULL, + [SortOrder] TINYINT NULL); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__mfr_items.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__mfr_items.sql new file mode 100644 index 0000000..a4400fa --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__mfr_items.sql @@ -0,0 +1,28 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__mfr_steps.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__mfr_steps.sql new file mode 100644 index 0000000..de6cd1d --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__mfr_steps.sql @@ -0,0 +1,22 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/fds__tt__reminder_core.sql b/Fuchs_Database/dbo/User Defined Types/fds__tt__reminder_core.sql new file mode 100644 index 0000000..f045a48 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/fds__tt__reminder_core.sql @@ -0,0 +1,27 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/hash_256.sql b/Fuchs_Database/dbo/User Defined Types/hash_256.sql new file mode 100644 index 0000000..a8d44bc --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/hash_256.sql @@ -0,0 +1,3 @@ +CREATE TYPE [dbo].[hash_256] + FROM BINARY (32) NOT NULL; + diff --git a/Fuchs_Database/dbo/User Defined Types/json_data_maxU.sql b/Fuchs_Database/dbo/User Defined Types/json_data_maxU.sql new file mode 100644 index 0000000..6c0b4b9 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/json_data_maxU.sql @@ -0,0 +1,3 @@ +CREATE TYPE [dbo].[json_data_maxU] + FROM NVARCHAR (MAX) NULL; + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__#customvalues.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__#customvalues.sql new file mode 100644 index 0000000..0636471 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__#customvalues.sql @@ -0,0 +1,8 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__#locations.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__#locations.sql new file mode 100644 index 0000000..58d537f --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__#locations.sql @@ -0,0 +1,15 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt___PartnerSet.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt___PartnerSet.sql new file mode 100644 index 0000000..f070d83 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt___PartnerSet.sql @@ -0,0 +1,7 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__appointments.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__appointments.sql new file mode 100644 index 0000000..eed7307 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__appointments.sql @@ -0,0 +1,16 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__attachments.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__attachments.sql new file mode 100644 index 0000000..2bee177 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__attachments.sql @@ -0,0 +1,7 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__comments.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__comments.sql new file mode 100644 index 0000000..764a273 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__comments.sql @@ -0,0 +1,10 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__companies.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__companies.sql new file mode 100644 index 0000000..974033e --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__companies.sql @@ -0,0 +1,21 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__contacts.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__contacts.sql new file mode 100644 index 0000000..7b1742c --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__contacts.sql @@ -0,0 +1,20 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__costcenters.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__costcenters.sql new file mode 100644 index 0000000..b873391 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__costcenters.sql @@ -0,0 +1,6 @@ +CREATE TYPE [dbo].[mfr__tt__costcenters] AS TABLE ( + [setid] VARCHAR (5) NULL, + [Id] BIGINT NOT NULL, + [Version] INT NOT NULL, + [Name] NVARCHAR (255) NULL); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__documents.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__documents.sql new file mode 100644 index 0000000..5c3b1f4 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__documents.sql @@ -0,0 +1,20 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__invoices.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__invoices.sql new file mode 100644 index 0000000..94a3968 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__invoices.sql @@ -0,0 +1,22 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__items.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__items.sql new file mode 100644 index 0000000..3e23d3b --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__items.sql @@ -0,0 +1,27 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__itemtypes.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__itemtypes.sql new file mode 100644 index 0000000..320c61c --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__itemtypes.sql @@ -0,0 +1,24 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__itemunits.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__itemunits.sql new file mode 100644 index 0000000..7032358 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__itemunits.sql @@ -0,0 +1,6 @@ +CREATE TYPE [dbo].[mfr__tt__itemunits] AS TABLE ( + [setid] VARCHAR (5) NULL, + [Id] BIGINT NOT NULL, + [Version] INT NOT NULL, + [Name] NVARCHAR (255) NULL); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__products.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__products.sql new file mode 100644 index 0000000..ce3322c --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__products.sql @@ -0,0 +1,11 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__qualifications.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__qualifications.sql new file mode 100644 index 0000000..a7cc39e --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__qualifications.sql @@ -0,0 +1,6 @@ +CREATE TYPE [dbo].[mfr__tt__qualifications] AS TABLE ( + [setid] VARCHAR (5) NULL, + [Id] BIGINT NOT NULL, + [Version] INT NOT NULL, + [Name] NVARCHAR (255) NULL); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__reports.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__reports.sql new file mode 100644 index 0000000..18723dc --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__reports.sql @@ -0,0 +1,19 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__serviceobjects.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__serviceobjects.sql new file mode 100644 index 0000000..3ae24d5 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__serviceobjects.sql @@ -0,0 +1,18 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__servicerequests.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__servicerequests.sql new file mode 100644 index 0000000..5b98f25 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__servicerequests.sql @@ -0,0 +1,29 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__steplisttemplateinstances.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__steplisttemplateinstances.sql new file mode 100644 index 0000000..3735668 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__steplisttemplateinstances.sql @@ -0,0 +1,8 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__steplisttemplates.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__steplisttemplates.sql new file mode 100644 index 0000000..904b81a --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__steplisttemplates.sql @@ -0,0 +1,10 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__steps.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__steps.sql new file mode 100644 index 0000000..6853171 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__steps.sql @@ -0,0 +1,21 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__stockmovements.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__stockmovements.sql new file mode 100644 index 0000000..c210f13 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__stockmovements.sql @@ -0,0 +1,19 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__tags.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__tags.sql new file mode 100644 index 0000000..eac0587 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__tags.sql @@ -0,0 +1,8 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__timeevents.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__timeevents.sql new file mode 100644 index 0000000..f742526 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__timeevents.sql @@ -0,0 +1,16 @@ +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); + diff --git a/Fuchs_Database/dbo/User Defined Types/mfr__tt__users.sql b/Fuchs_Database/dbo/User Defined Types/mfr__tt__users.sql new file mode 100644 index 0000000..1b00b86 --- /dev/null +++ b/Fuchs_Database/dbo/User Defined Types/mfr__tt__users.sql @@ -0,0 +1,20 @@ +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); + diff --git a/Fuchs_Database/dbo/Views/ocms_fn_rand.sql b/Fuchs_Database/dbo/Views/ocms_fn_rand.sql new file mode 100644 index 0000000..fdc736e --- /dev/null +++ b/Fuchs_Database/dbo/Views/ocms_fn_rand.sql @@ -0,0 +1,4 @@ + +CREATE VIEW [dbo].[ocms_fn_rand] +AS + select rand(Cast(newid() as varbinary)) as rn \ No newline at end of file