diff --git a/GeneticsCore/resources/schemas/dbscripts/postgresql/geneticscore-17.10-17.11.sql b/GeneticsCore/resources/schemas/dbscripts/postgresql/geneticscore-17.10-17.11.sql new file mode 100644 index 000000000..f3a6a3455 --- /dev/null +++ b/GeneticsCore/resources/schemas/dbscripts/postgresql/geneticscore-17.10-17.11.sql @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +CREATE TABLE geneticscore.taqman_probes ( + rowid serial, + probe varchar(100), + target varchar(1000), + + container ENTITYID, + created TIMESTAMP, + createdby USERID, + modified TIMESTAMP, + modifiedby USERID, + + CONSTRAINT PK_taqman_probes PRIMARY KEY (rowid) +); + +CREATE TABLE geneticscore.test_significance ( + rowid serial, + probe varchar(100), + genotype varchar(100), + label varchar(1000), + comment varchar(4000), + + container ENTITYID, + created TIMESTAMP, + createdby USERID, + modified TIMESTAMP, + modifiedby USERID, + + CONSTRAINT PK_test_significance PRIMARY KEY (rowid) +); \ No newline at end of file diff --git a/GeneticsCore/resources/schemas/dbscripts/sqlserver/geneticscore-17.10-17.11.sql b/GeneticsCore/resources/schemas/dbscripts/sqlserver/geneticscore-17.10-17.11.sql new file mode 100644 index 000000000..1dd7283be --- /dev/null +++ b/GeneticsCore/resources/schemas/dbscripts/sqlserver/geneticscore-17.10-17.11.sql @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +CREATE TABLE geneticscore.taqman_probes ( + rowid int identity(1,1), + probe varchar(100), + target varchar(1000), + + container ENTITYID, + created DATETIME, + createdby USERID, + modified DATETIME, + modifiedby USERID, + + CONSTRAINT PK_taqman_probes PRIMARY KEY (rowid) +); + +CREATE TABLE geneticscore.test_significance ( + rowid int identity(1,1), + probe varchar(100), + genotype varchar(100), + label varchar(1000), + comment varchar(4000), + + container ENTITYID, + created DATETIME, + createdby USERID, + modified DATETIME, + modifiedby USERID, + + CONSTRAINT PK_test_significance PRIMARY KEY (rowid) +); \ No newline at end of file diff --git a/GeneticsCore/resources/schemas/geneticscore.xml b/GeneticsCore/resources/schemas/geneticscore.xml index a5a4c1309..1de9bde1c 100644 --- a/GeneticsCore/resources/schemas/geneticscore.xml +++ b/GeneticsCore/resources/schemas/geneticscore.xml @@ -58,6 +58,74 @@ + + + + + org.labkey.ldk.query.DefaultTableCustomizer + Taqman Probes + rowId + + + Row Id + + + + + + + + + Folder + + + + + + + + + + + + + + + + + org.labkey.ldk.query.DefaultTableCustomizer + Genetic Test Significance + rowId + + + Row Id + + + + + + + + + + + + + + + Folder + + + + + + + + + + + + diff --git a/GeneticsCore/src/org/labkey/GeneticsCore/GeneticsCoreModule.java b/GeneticsCore/src/org/labkey/GeneticsCore/GeneticsCoreModule.java index e108e5ba4..ad2afdfca 100644 --- a/GeneticsCore/src/org/labkey/GeneticsCore/GeneticsCoreModule.java +++ b/GeneticsCore/src/org/labkey/GeneticsCore/GeneticsCoreModule.java @@ -39,7 +39,7 @@ public String getName() @Override public @Nullable Double getSchemaVersion() { - return 17.10; + return 17.11; } @Override diff --git a/GeneticsCore/src/org/labkey/GeneticsCore/notification/GeneticsCoreNotification.java b/GeneticsCore/src/org/labkey/GeneticsCore/notification/GeneticsCoreNotification.java index 93663dff3..9639c1db1 100644 --- a/GeneticsCore/src/org/labkey/GeneticsCore/notification/GeneticsCoreNotification.java +++ b/GeneticsCore/src/org/labkey/GeneticsCore/notification/GeneticsCoreNotification.java @@ -106,6 +106,7 @@ public String getMessageBodyHTML(Container c, User u) getParentageFreezerSamplesNotFlagged(c, u, msg); getParentageConflicts(c, u, msg); + getAncestryConflicts(c, u, msg); return msg.toString(); } @@ -157,6 +158,18 @@ public void getParentageConflicts(Container c, User u, StringBuilder msg) } } + public void getAncestryConflicts(Container c, User u, StringBuilder msg) + { + TableInfo ti = QueryService.get().getUserSchema(u, c, "study").getTable("geneticAncestryConflicts"); + TableSelector ts = new TableSelector(ti, PageFlowUtil.set("Id")); + long count = ts.getRowCount(); + if (count > 0) + { + ActionURL url = QueryService.get().urlFor(u, c, QueryAction.executeQuery, "study", "geneticAncestryConflicts"); + msg.append("WARNING: There are " + count + " animals with duplicate or conflicting genetic ancestry calls.

Click here to view these animals


"); + } + } + public void getActiveExclusions(Container c, User u, StringBuilder msg, String flag, int interval) { SimpleFilter filter = new SimpleFilter(); diff --git a/ONPRC_EHR_ComplianceDB/module.properties b/ONPRC_EHR_ComplianceDB/module.properties new file mode 100644 index 000000000..7d66f2b70 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/module.properties @@ -0,0 +1,3 @@ +Name: ONPRC_EHR_ComplianceDB +ModuleClass: org.labkey.api.module.SimpleModule +ModuleDependencies: EHR_ComplianceDB \ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/Measles45DayAlert.query.xml b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/Measles45DayAlert.query.xml new file mode 100644 index 000000000..dd4d22255 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/Measles45DayAlert.query.xml @@ -0,0 +1,49 @@ + + + + + Measles 45 Day Overdue Report + + + true + + ehr_compliancedb + employees + employeeId + + + + Requirement Name + + ehr_compliancedb + requirements + requirementName + + ALWAYS_OFF + + + + + + + + + E3170D + + + + + + FBEC5D + + + + + Is Required? + ALWAYS_OFF + + +
+
+
+
diff --git a/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/Measles45DayAlert.sql b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/Measles45DayAlert.sql new file mode 100644 index 000000000..ee9aeb1de --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/Measles45DayAlert.sql @@ -0,0 +1,47 @@ +SELECT + emp.employeeid, + emp.Name, + emp.email, + emp.unit, + emp.category, + emp.location, + emp.majorudds, + emp.notes, + emp.requirementname, + --c.date, + Case + When (c.requirementname is null) Then emp.date + When (c.requirementname is not null) Then c.date + ELSE '' + End AS DateCompleted, + emp.comment, + emp.trainer, + Case + When (c.requirementname is null) Then TIMESTAMPDIFF('SQL_TSI_DAY', emp.date, now()) + When (c.requirementname is not null) Then '-1' + ELSE '' + End as DaysOverDue + FROM ehr_compliancedb.completiondates c + RIGHT JOIN ( + SELECT + c1.employeeid, + emp.email, + emp.Firstname + ' ' + emp.Lastname as Name, + emp.unit, + emp.category, + emp.location, + emp.majorudds, + emp.notes, + emp.isActive, + c1.requirementname, + c1.date, + c1.result, + c1.comment, + c1.trainer + FROM ehr_compliancedb.completiondates c1, ehr_compliancedb.employees emp + Where c1.employeeid = emp.employeeid + And c1.requirementname like 'Occupational Health - Measles Compliant - Initial' + And emp.endDate is null + ) emp + ON c.employeeid = emp.employeeid + And c.requirementname like 'Occupational Health - Measles Compliant' \ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/employees.query.xml b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/employees.query.xml new file mode 100644 index 000000000..4815c6bae --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/employees.query.xml @@ -0,0 +1,30 @@ + + + + + Employees + + + Host + + + + + + + + + + + + + + + + + + +
+
+
+
\ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/employees/.qview.xml b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/employees/.qview.xml new file mode 100644 index 000000000..d65d71743 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/employees/.qview.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/requirements.query.xml b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/requirements.query.xml new file mode 100644 index 000000000..64d4ad8ff --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/requirements.query.xml @@ -0,0 +1,23 @@ + + + + + Requirements + + + + + + + + + + + + + + +
+
+
+
\ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/requirements/.qview.xml b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/requirements/.qview.xml new file mode 100644 index 000000000..17d0f4476 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/queries/EHR_ComplianceDB/requirements/.qview.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/views/begin.html b/ONPRC_EHR_ComplianceDB/resources/views/begin.html new file mode 100644 index 000000000..620e2c538 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/views/begin.html @@ -0,0 +1,75 @@ + \ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/views/begin.view.xml b/ONPRC_EHR_ComplianceDB/resources/views/begin.view.xml new file mode 100644 index 000000000..a01fb3cf0 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/views/begin.view.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/views/begin.webpart.xml b/ONPRC_EHR_ComplianceDB/resources/views/begin.webpart.xml new file mode 100644 index 000000000..bd3430562 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/views/begin.webpart.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/views/printableComplianceReports.html b/ONPRC_EHR_ComplianceDB/resources/views/printableComplianceReports.html new file mode 100644 index 000000000..c286dec8d --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/views/printableComplianceReports.html @@ -0,0 +1,267 @@ + \ No newline at end of file diff --git a/ONPRC_EHR_ComplianceDB/resources/views/printableComplianceReports.view.xml b/ONPRC_EHR_ComplianceDB/resources/views/printableComplianceReports.view.xml new file mode 100644 index 000000000..171801594 --- /dev/null +++ b/ONPRC_EHR_ComplianceDB/resources/views/printableComplianceReports.view.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/extscheduler/build.gradle b/extscheduler/build.gradle index 954e555da..87d0fad55 100644 --- a/extscheduler/build.gradle +++ b/extscheduler/build.gradle @@ -2,4 +2,5 @@ import org.labkey.gradle.util.BuildUtils; dependencies { BuildUtils.addLabKeyDependency(project: project, config: "implementation", depProjectPath: ":server:modules:LabDevKitModules:LDK", depProjectConfig: "apiJarFile") + BuildUtils.addLabKeyDependency(project: project, config: "modules", depProjectPath: ":server:modules:LabDevKitModules:LDK", depProjectConfig: 'published', depExtension: 'module') } diff --git a/extscheduler/module.properties b/extscheduler/module.properties index a4145fb74..446b2b018 100644 --- a/extscheduler/module.properties +++ b/extscheduler/module.properties @@ -1,5 +1,6 @@ Name: extscheduler ModuleClass: org.labkey.extscheduler.ExtSchedulerModule +ModuleDependencies: LDK SupportedDatabases: mssql RequiredServerVersion: 15.2 ManageVersion: false \ No newline at end of file diff --git a/extscheduler/resources/module.xml b/extscheduler/resources/module.xml index 6f39e879a..c67e137ca 100644 --- a/extscheduler/resources/module.xml +++ b/extscheduler/resources/module.xml @@ -2,10 +2,45 @@ The group name to be used for the set of users to display in the Scheduler app UserId combobox for creating new events. + true true ADMIN + + + Length in minutes for event period when creating a new event. + true + true + 30 + + ADMIN + + + + + A comma separated list of column names to display for the EventForm.js file. Column Names(Name,ResourceId,UserId,Alias,Quantity,Comments,StartDate,EndDate) + true + true + Name,ResourceId,UserId,Alias,Quantity,Comments,StartDate,EndDate + + ADMIN + + + + + Set as true to allow for calendar events to overlap for a given resource. Defaults to false when blank. + true + select + + + true + false + + ADMIN + + diff --git a/extscheduler/resources/queries/extscheduler/SchedulerAliases.sql b/extscheduler/resources/queries/extscheduler/SchedulerAliases.sql new file mode 100644 index 000000000..a15512491 --- /dev/null +++ b/extscheduler/resources/queries/extscheduler/SchedulerAliases.sql @@ -0,0 +1,10 @@ +SELECT +a.ResourceId, +a.Name, +a.StartDate, +a.EndDate, +a.UserId, +a.Alias +FROM Events a +WHERE a.alias NOT IN (Select b.alias FROM Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer_Public')}.onprc_billing_public.aliases b) +--AND a.alias IS NOT NULL \ No newline at end of file diff --git a/extscheduler/resources/queries/extscheduler/SchedulerAliases/.qview.xml b/extscheduler/resources/queries/extscheduler/SchedulerAliases/.qview.xml new file mode 100644 index 000000000..f5134953c --- /dev/null +++ b/extscheduler/resources/queries/extscheduler/SchedulerAliases/.qview.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.28-15.29.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.28-15.29.sql new file mode 100644 index 000000000..4ae71d86e --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.28-15.29.sql @@ -0,0 +1 @@ +ALTER TABLE extscheduler.Events ADD Quantity INT; \ No newline at end of file diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.29-15.30.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.29-15.30.sql new file mode 100644 index 000000000..6fc9496ad --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.29-15.30.sql @@ -0,0 +1 @@ +ALTER TABLE extscheduler.Events ADD Comments VARCHAR(255); \ No newline at end of file diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.30-15.31.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.30-15.31.sql new file mode 100644 index 000000000..048fef129 --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-15.30-15.31.sql @@ -0,0 +1,21 @@ + +ALTER TRIGGER extscheduler.TR_OverlappingDateRanges ON extscheduler.Events FOR INSERT, UPDATE AS +BEGIN + IF EXISTS( + SELECT 1 FROM extscheduler.events R + LEFT JOIN ( + SELECT ObjectId, Value FROM prop.Properties + JOIN prop.PropertySets ON PropertySets."Set" = Properties."Set" + WHERE Name = 'ExtSchedulerAllowEventOverlap' + ) P ON R.Container = P.ObjectId + INNER JOIN inserted I + ON (P.Value IS NULL OR P.Value = 'false') AND ( + (R.Container = I.Container AND R.ResourceId = I.ResourceId AND R.StartDate < I.EndDate AND I.StartDate < R.EndDate) + AND NOT (R.Id = I.Id) + ) + ) + BEGIN + RAISERROR('Start/End date ranges may not overlap for the same resource.', 16, 1) + ROLLBACK + END +END \ No newline at end of file diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.02-20.03.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.02-20.03.sql new file mode 100644 index 000000000..ae7232d34 --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.02-20.03.sql @@ -0,0 +1,7 @@ +/* +Created: 2020-05-07 +Created by jonesga +Purpose: Update of Comments field of scheduler per user request + +*/ +ALTER TABLE extscheduler.Events ALTER COLUMN Comments NVARCHAR(4000); \ No newline at end of file diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.502-20.503.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.502-20.503.sql new file mode 100644 index 000000000..5a35390bb --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.502-20.503.sql @@ -0,0 +1,48 @@ +/* +Created: 2020-05-07 +Created by jonesga +Purpose: Dataset to mimic DateRange from Labkey for SCheduler actionin SQL + +*/ +DROP TABLE IF EXISTS extScheduler.DateParts +GO +CREATE TABLE extScheduler.dateParts +(date datetime, +dateOnly datetime, +DayOfYear int, +DayofMonth int, +DayofWeek int, +DayName varchar(20), + +WeekofMonth int, +WeekofYear int, + Month int, + year int) + +Go + +Insert into extScheduler.DateParts + (Date, + dateonly, + DayOfYear, + DayofMonth, + DayofWeek, + DayName, + WeekofMonth, + WeekofYear, + Month, + year) +Select + + i.NDate, + CAST(i.Ndate as date) as dateOnly, + cast(datepart(dy,i.Ndate) as integer) as DayOfYear, + cast(datepart(dd,i.Ndate) as integer) as DayOfMonth, + cast(datepart(dw,i.Ndate) as integer) as DayOfWeek, + cast(dateName(dd,i.Ndate) as VarChar(20)) as DayName, + (cast(datepart(dd,i.Ndate) as integer)/ 7) as WeekofMonth, + cast(datepart(wk,i.Ndate) as integer) as WeekofYear, + cast(datepart(mm,i.Ndate) as integer) as Month, + cast(datepart(yyyy,i.Ndate) as integer) as Year +FROM (SELECT DateAdd(dd, i.value, '5/1/2020') as NDate FROM ldk.integers i)i +Where i.nDate <= '4/20/2021' \ No newline at end of file diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.503-20.504.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.503-20.504.sql new file mode 100644 index 000000000..d5968507b --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.503-20.504.sql @@ -0,0 +1,55 @@ +-- ================================================ +-- Template generated from Template Explorer using: +-- Create Procedure (New Menu).SQL +-- +-- Use the Specify Values for Template Parameters +-- command (Ctrl-Shift-M) to fill in the parameter +-- values below. +-- +-- This block of comments will not be included in +-- the definition of the procedure. +-- ================================================ +-- ============================================= +-- Author: jonesga@ohsu.edu +-- Create date: 2020-05-13 +-- Description: PRocedure to Block out Scheduling for Covid19 testing for 3:30 to 7 PM on Monday and Friday +-- ============================================= + +DROP PROCEDURE IF EXISTS extscheduler.extBlockOutEvening +GO +CREATE PROCEDURE extscheduler.extBlockOutEvening + -- Add the parameters for the stored procedure here + @Month INTEGER, @ResourceID INTEGER +AS +BEGIN + + INSERT INTO [extscheduler].[Events] + ([ResourceId] + ,[Name] + ,[StartDate] + ,[EndDate] + ,[UserId] + ,[Container] + ,[CreatedBy] + ,[Created] + ,[Quantity] + ,[Comments]) + + SELECT @ResourceID + ,'No Covid-19 Testing' + ,DateAdd(hh,1530,c.date) as StartDate + ,DateAdd(hh,19,c.date) as EndDate + ,1003 + ,'5C3C9FF8-6BCF-1038-930A-7D62F3A605B4' + ,1003 + ,GetDate() + ,1 + ,'Insert by ISE' + FROM [Labkey].[extscheduler].[dateParts] c + where c.dayofWeek in (2,6) and c.Month = @Month +--Days of Week start with Sunday + + + +END +GO diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.504-20.505.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.504-20.505.sql new file mode 100644 index 000000000..478b46583 --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.504-20.505.sql @@ -0,0 +1,55 @@ +/****** Object: StoredProcedure [extscheduler].[extBlockOutMorning] Script Date: 5/13/2020 6:10:00 AM ******/ +-- ================================================ +-- Template generated from Template Explorer using: +-- Create Procedure (New Menu).SQL +-- +-- Use the Specify Values for Template Parameters +-- command (Ctrl-Shift-M) to fill in the parameter +-- values below. +-- +-- This block of comments will not be included in +-- the definition of the procedure. +-- ================================================ +-- ============================================= +-- Author: jonesga@ohsu.edu +-- Create date: 2020-05-13 +-- Description: PRocedure to Block out Scheduling for Covid19 testing for 7 to 8 on Monday and Friday +-- ============================================= +DROP PROCEDURE IF EXISTS [extscheduler].[extBlockOutMorning] +GO + +CREATE PROCEDURE [extscheduler].[extBlockOutMorning] + -- Add the parameters for the stored procedure here + @Month INTEGER, @ResourceID INTEGER +AS +BEGIN + + INSERT INTO [extscheduler].[Events] + ([ResourceId] + ,[Name] + ,[StartDate] + ,[EndDate] + ,[UserId] + ,[Container] + ,[CreatedBy] + ,[Created] + ,[Quantity] + ,[Comments]) + + SELECT @ResourceID + ,'No Covid-19 Testing' + ,DateAdd(hh,7,c.date) as StartDate + ,DateAdd(hh,8,c.date) as EndDate + ,1003 + ,'5C3C9FF8-6BCF-1038-930A-7D62F3A605B4' + ,1003 + ,GetDate() + ,1 + ,'Insert by ISE' + FROM [Labkey].[extscheduler].[dateParts] c + where c.dayofWeek in (2,6) and c.Month = @Month +--Days of Week start with Sunday + + + +END diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.505-20.506.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.505-20.506.sql new file mode 100644 index 000000000..370417a83 --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.505-20.506.sql @@ -0,0 +1,55 @@ +-- /****** Object: StoredProcedure [extscheduler].[extBlockOutDays] Script Date: 5/13/2020 6:12:06 AM ******/ +-- ================================================ +-- Template generated from Template Explorer using: +-- Create Procedure (New Menu).SQL +-- +-- Use the Specify Values for Template Parameters +-- command (Ctrl-Shift-M) to fill in the parameter +-- values below. +-- +-- This block of comments will not be included in +-- the definition of the procedure. +-- ================================================ +-- ============================================= +-- Author: jonesga@ohsu.edu +-- Create date: 2020-05-13 +-- Description: PRocedure to Block out Scheduling for Covid19 testing for all days except Monday and Friday +-- ============================================= +DROP PROCEDURE IF EXISTS [extscheduler].[extBlockOutDays] +GO + +CREATE PROCEDURE [extscheduler].[extBlockOutDays] + -- Add the parameters for the stored procedure here + @Month INTEGER, @ResourceID INTEGER +AS +BEGIN + + INSERT INTO [extscheduler].[Events] + ([ResourceId] + ,[Name] + ,[StartDate] + ,[EndDate] + ,[UserId] + ,[Container] + ,[CreatedBy] + ,[Created] + ,[Quantity] + ,[Comments]) + + SELECT @ResourceID + ,'No Covid-19 Testing' + ,DateAdd(hh,7,c.date) as StartDate + ,DateAdd(hh,19,c.date) as EndDate + ,1003 + ,'5C3C9FF8-6BCF-1038-930A-7D62F3A605B4' + ,1003 + ,GetDate() + ,1 + ,'Insert by ISE' + FROM [Labkey].[extscheduler].[dateParts] c + where c.dayofWeek in (1,3,4,5,7) and c.Month = @Month +--Days of Week start with Sunday + + + +END diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.601-20.602.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.601-20.602.sql new file mode 100644 index 000000000..338d08fb8 --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.601-20.602.sql @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2003-2005 Fred Hutchinson Cancer Research Center + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * Created 2020-06-09 + * Created by jonesga + * Purpose - View joining Scheduler Resources, Events and the User Data + */ + + +DROP VIEW IF EXISTS extScheduler.vw_Covid19Research +GO + +CREATE VIEW extScheduler.vw_Covid19Research AS +SELECT extscheduler.Events.Id AS SChedulerID, extscheduler.Events.ResourceId, extscheduler.Resources.Name AS ResourceName, extscheduler.Events.Name, extscheduler.Events.StartDate, extscheduler.Events.UserId, + extscheduler.Events.CreatedBy, extscheduler.Events.Created, extscheduler.Events.Quantity, core.UsersData.IM AS EmployeeID +FROM extscheduler.Events LEFT OUTER JOIN + core.UsersData ON extscheduler.Events.UserId = core.UsersData.UserId LEFT OUTER JOIN + extscheduler.Resources ON extscheduler.Events.ResourceId = extscheduler.Resources.Id +WHERE (extscheduler.Events.ResourceId = 67) diff --git a/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.602-20.603.sql b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.602-20.603.sql new file mode 100644 index 000000000..8650874c6 --- /dev/null +++ b/extscheduler/resources/schemas/dbscripts/sqlserver/extscheduler-20.602-20.603.sql @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2003-2005 Fred Hutchinson Cancer Research Center + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * Created 2020-06-09 + * Created by jonesga + * Purpose - View joining Scheduler Resources, Events and the User Data + */ + +DROP VIEW IF EXISTS extScheduler.vw_Covid19DCMSchedule +GO + +CREATE VIEW extScheduler.vw_Covid19DCMSchedule AS +SELECT extscheduler.Events.Id AS SChedulerID, extscheduler.Events.ResourceId, extscheduler.Resources.Name AS ResourceName, extscheduler.Events.Name, extscheduler.Events.StartDate, extscheduler.Events.UserId, + extscheduler.Events.CreatedBy, extscheduler.Events.Created, extscheduler.Events.Quantity, core.UsersData.IM AS EmployeeID + FROM extscheduler.Events LEFT OUTER JOIN + core.UsersData ON extscheduler.Events.UserId = core.UsersData.UserId LEFT OUTER JOIN + extscheduler.Resources ON extscheduler.Events.ResourceId = extscheduler.Resources.Id + WHERE (extscheduler.Resources.Name LIKE 'DCM%') diff --git a/extscheduler/resources/schemas/extscheduler.xml b/extscheduler/resources/schemas/extscheduler.xml index 6db905b6e..2a009cc23 100644 --- a/extscheduler/resources/schemas/extscheduler.xml +++ b/extscheduler/resources/schemas/extscheduler.xml @@ -52,6 +52,8 @@ + + User @@ -96,5 +98,46 @@ - + + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
\ No newline at end of file diff --git a/extscheduler/resources/views/weeklyTest.html b/extscheduler/resources/views/weeklyTest.html index 332e0a906..7d98e834d 100644 --- a/extscheduler/resources/views/weeklyTest.html +++ b/extscheduler/resources/views/weeklyTest.html @@ -80,7 +80,7 @@ LABKEY.Query.selectRows({ schemaName: 'extscheduler', queryName: 'Events', - columns: 'Id,ResourceId,Name,StartDate,EndDate,UserId,Alias,Owner', + columns: 'Id,ResourceId,Name,StartDate,EndDate,UserId,Alias,Owner,Comments,Quantity', success: function(data){ // need to convert the date fields from a string to JS Date object diff --git a/extscheduler/resources/web/extscheduler/App/view/EventForm.js b/extscheduler/resources/web/extscheduler/App/view/EventForm.js index 23e33cb32..56e0ac4dd 100644 --- a/extscheduler/resources/web/extscheduler/App/view/EventForm.js +++ b/extscheduler/resources/web/extscheduler/App/view/EventForm.js @@ -13,8 +13,14 @@ Ext.define('App.view.EventForm', { editable : false, scheduler : null, + eventPeriodLength: 30, + initComponent: function() { + var context = LABKEY.getModuleContext('extscheduler'); + this.eventPeriodLength = parseInt(context['ExtSchedulerEventPeriodLength']); + this.eventFormColumns = context['ExtSchedulerEventFormColumns'].split(','); + this.items = [ //{ // xtype : 'textfield', @@ -22,6 +28,7 @@ Ext.define('App.view.EventForm', { // name : 'Name', // reference : 'eventNameField', // allowBlank : !this.editable, + // hidden : this.eventFormColumns.indexOf('Name') === -1, // bind : { // value : '{eventRecord.Name}', // readOnly : !this.editable @@ -33,9 +40,11 @@ Ext.define('App.view.EventForm', { name : 'ResourceId', reference : 'eventResourceField', allowBlank : !this.editable, + hidden : this.eventFormColumns.indexOf('ResourceId') === -1, bind : { value : '{eventRecord.ResourceId}', readOnly : !this.editable + } }, { @@ -49,25 +58,68 @@ Ext.define('App.view.EventForm', { editable : false, typeAhead : true, allowBlank : !this.editable, + hidden : this.eventFormColumns.indexOf('UserId') === -1, bind : { value : '{eventRecord.UserId}', readOnly : !this.editable } }, - // { - // xtype : 'textfield', - // fieldLabel : 'Alias', - // name : 'Alias', - // reference : 'eventAliasField', - // allowBlank : !this.editable, - // bind : { - // value : '{eventRecord.Alias}', - // readOnly : !this.editable - // } - // }, + { + xtype : 'textfield', + fieldLabel : 'Alias', + name : 'Alias', + reference : 'eventAliasField', + //allowBlank : !this.editable, + allowBlank: true, + hidden : this.eventFormColumns.indexOf('Alias') === -1, + bind : { + value : '{eventRecord.Alias}', + readOnly : !this.editable + } + }, + { + xtype : 'numberfield', + fieldLabel : 'Quantity', + name : 'Quantity', + value : 1, + minValue: 1, + allowDecimals : false, + reference : 'eventQuantityField', + allowBlank : !this.editable, + hidden : this.eventFormColumns.indexOf('Quantity') === -1, + bind : { + value : '{eventRecord.Quantity}', + readOnly : !this.editable + } + }, + { + xtype : 'textarea', + labelAlign: 'top', + width: 320, + height: 200, + fieldLabel : 'Comments', + name : 'Comments', + reference : 'eventCommentsField', + style: 'margin-top: 20px;', + allowBlank : true, + hidden : this.eventFormColumns.indexOf('Comments') === -1, + bind : { + value : '{eventRecord.Comments}', + readOnly : !this.editable + } + /* xtype: 'textarea', + labelAlign: 'top', + width: 500, + height: 200, + fieldLabel: 'Question/Comment', + name: 'comment', + style: 'margin-top: 20px;', + allowBlank: false + */ }, { xtype : 'fieldcontainer', layout : 'hbox', + hidden : this.eventFormColumns.indexOf('StartDate') === -1, items : [ this.getStartDateField(), this.getStartTimeField() @@ -76,6 +128,7 @@ Ext.define('App.view.EventForm', { { xtype : 'fieldcontainer', layout : 'hbox', + hidden : this.eventFormColumns.indexOf('EndDate') === -1, items : [ this.getEndDateField(), this.getEndTimeField() @@ -187,7 +240,7 @@ Ext.define('App.view.EventForm', { width : 90, name : 'StartTime', format : 'H:i', - increment : 30, + increment : this.eventPeriodLength, allowBlank : !this.editable, bind : { minValue : '{defaultMinTime}', @@ -200,7 +253,7 @@ Ext.define('App.view.EventForm', { this.startTimeField.on('change', function(timefield, newValue){ if (this.getEndTimeField().getValue() == null) - this.getEndTimeField().setValue(new Date(newValue.getTime() + (30*60*1000))); + this.getEndTimeField().setValue(new Date(newValue.getTime() + (this.eventPeriodLength*60*1000))); this.ensureEndTimeAfterStart(); }, this); @@ -245,7 +298,7 @@ Ext.define('App.view.EventForm', { name : 'EndTime', width : 90, format : 'H:i', - increment : 30, + increment : this.eventPeriodLength, allowBlank : !this.editable, bind : { minValue : '{minEndTime}', @@ -274,7 +327,7 @@ Ext.define('App.view.EventForm', { if (allNonNull && startDate.getTime() == endDate.getTime()) { - var d = new Date(startTime.getTime() + (30*60*1000)); + var d = new Date(startTime.getTime() + (this.eventPeriodLength*60*1000)); this.getEndTimeField().setMinValue(d); if (startTime.getTime() >= endTime.getTime()) diff --git a/extscheduler/resources/web/extscheduler/App/view/Scheduler.js b/extscheduler/resources/web/extscheduler/App/view/Scheduler.js index d06ceb5fb..3cf7c3587 100644 --- a/extscheduler/resources/web/extscheduler/App/view/Scheduler.js +++ b/extscheduler/resources/web/extscheduler/App/view/Scheduler.js @@ -17,6 +17,7 @@ Ext.define('App.view.Scheduler', { eventResizeHandles : 'none', eventBodyTemplate :'{Name:htmlEncode}
{ResourceName:htmlEncode}
{UserDisplayName:htmlEncode}', snapToIncrement : true, + allowOverlap : true, highlightCurrentTime : true, calendarTimeAxisCfg : { height : 30 diff --git a/extscheduler/src/org/labkey/extscheduler/ExtSchedulerModule.java b/extscheduler/src/org/labkey/extscheduler/ExtSchedulerModule.java index 2762d398d..4fc480344 100644 --- a/extscheduler/src/org/labkey/extscheduler/ExtSchedulerModule.java +++ b/extscheduler/src/org/labkey/extscheduler/ExtSchedulerModule.java @@ -1,3 +1,4 @@ +//update to add new data set package org.labkey.extscheduler; import org.jetbrains.annotations.NotNull; @@ -26,7 +27,7 @@ public String getName() @Override public @Nullable Double getSchemaVersion() { - return 15.28; + return 20.603; } @Override diff --git a/extscheduler/src/org/labkey/extscheduler/query/EventsTable.java b/extscheduler/src/org/labkey/extscheduler/query/EventsTable.java index df1fb2618..d4cdca344 100644 --- a/extscheduler/src/org/labkey/extscheduler/query/EventsTable.java +++ b/extscheduler/src/org/labkey/extscheduler/query/EventsTable.java @@ -39,7 +39,9 @@ public EventsTable(TableInfo table, ExtSchedulerQuerySchema schema, ContainerFil wrapAllColumns(true); SqlDialect dialect = getSchema().getSqlDialect(); - SQLFragment isOwnerSQL = new SQLFragment("CASE WHEN "+ ExprColumn.STR_TABLE_ALIAS +".UserId = ? OR " + ExprColumn.STR_TABLE_ALIAS +".CreatedBy = ? THEN " + +// Modified: 6-19-2020 R.Blasa Allow future events to be displayed + SQLFragment isOwnerSQL = new SQLFragment("CASE WHEN " + ExprColumn.STR_TABLE_ALIAS + ".StartDate >= {fn now()} AND (" + ExprColumn.STR_TABLE_ALIAS +".UserId = ? OR " + ExprColumn.STR_TABLE_ALIAS +".CreatedBy = ? ) THEN " + dialect.getBooleanTRUE() + " ELSE " + dialect.getBooleanFALSE() + " END"); isOwnerSQL.add(schema.getUser().getUserId()); isOwnerSQL.add(schema.getUser().getUserId()); @@ -51,12 +53,10 @@ public EventsTable(TableInfo table, ExtSchedulerQuerySchema schema, ContainerFil // disable bulk import for all users setImportURL(AbstractTableInfo.LINK_DISABLER); - // only allow admins to see insert new button and edit links - if (!getContainer().hasPermission(schema.getUser(), AdminPermission.class)) - { - setInsertURL(AbstractTableInfo.LINK_DISABLER); - setUpdateURL(AbstractTableInfo.LINK_DISABLER); - } + +// Added: 6-15-2020 R.Blasa allowed delete option +// setDeleteURL(AbstractTableInfo.LINK_DISABLER); + } @Override diff --git a/mergesync/resources/scripts/mergesync/mergesync.js b/mergesync/resources/scripts/mergesync/mergesync.js index ff7feec7e..1b7fe4d1a 100644 --- a/mergesync/resources/scripts/mergesync/mergesync.js +++ b/mergesync/resources/scripts/mergesync/mergesync.js @@ -7,7 +7,7 @@ var console = require("console"); var LABKEY = require("labkey"); exports.init = function(EHR){ - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.COMPLETE, 'study', 'Clinpath Runs', function(event, errors, helper){ + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.COMPLETE, 'study', 'clinpathruns', function(event, errors, helper){ var rows = helper.getRows(); if (helper.getEvent() == 'insert' && rows.length && !helper.isValidateOnly()){ var toSync = []; @@ -37,7 +37,7 @@ exports.init = function(EHR){ } }); - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_DELETE, 'study', 'Clinpath Runs', function(helper, errors, row) { + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_DELETE, 'study', 'clinpathruns', function(helper, errors, row) { if (row.objectid){ var mergeHelper = new org.labkey.mergesync.RequestSyncHelper(LABKEY.Security.currentUser.id, LABKEY.Security.currentContainer.id); mergeHelper.deleteSyncRecords(row.objectid); diff --git a/onprc_billing/resources/module.xml b/onprc_billing/resources/module.xml index 2914ffc45..77d3ab93f 100644 --- a/onprc_billing/resources/module.xml +++ b/onprc_billing/resources/module.xml @@ -7,6 +7,14 @@ ADMIN + + true + The is the path to the container holding billing data made accessible for the non-finance users. Use of slashes is very important - it should be in the format '/myProject/ehr' + /onprc/admin/finance/public + + ADMIN + + true The is the path to the issue tracker used by the Finance group. Use of slashes is very important - it should be in the format '/myProject/ehr' diff --git a/onprc_billing/resources/queries/onprc_billing/ActiveAlias_2020.query.xml b/onprc_billing/resources/queries/onprc_billing/ActiveAlias_2020.query.xml new file mode 100644 index 000000000..901c93b55 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/ActiveAlias_2020.query.xml @@ -0,0 +1,71 @@ + + + + + Active Aliases ONPRC + + + + + + + OGA Award Nummber + + + + + + + + + MM-dd-yyyy + + + MM-dd-yyyy + + + + + onprc_billing + investigators + employeeID + InvestigatorID + + + + + + onprc_billing + fiscalAuthorities + employeeid + rowID + + + + 0.00 + + + + + MM-dd-yyyy + + + + + + + +
+
+
+
diff --git a/onprc_billing/resources/queries/onprc_billing/Activealias_2020.sql b/onprc_billing/resources/queries/onprc_billing/Activealias_2020.sql new file mode 100644 index 000000000..6558c1da5 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/Activealias_2020.sql @@ -0,0 +1,39 @@ +SELECT a.alias, + a.category, + a.aliasEnabled, + a.projectNumber, + a.grantNumber as OGAAwardNumber, + a.agencyAwardNumber, + a.investigatorId, + a.investigatorName, + a.fiscalAuthority, + a.fiscalAuthorityName, + a.budgetStartDate, + a.budgetEndDate, + a.faRate, + a.faSchedule, + a.projectTitle, + a.projectDescription, + a.projectStatus, + a.aliasType, + a.container, + a.dateDisabled, + a.Comments, + a.PPQNumber, + a.PPQDate, + a.ApplicationTypeDescription, + a.AwardStatus, + a.AwardID, + a.ApplicationType, + a.ProjectID, + a.ActivityType, + a.AwardNumber, + a.AwardSuffix, + a.ADFMEmpNum, + a.ADFMFullName, + a.ActivityTypeDescription, + a.FUndingSourceNumber, + a.FUndingSourceName, + a.Org +FROM aliases a +where aliasEnabled = 'y' \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/LeaseFeeDefinitionUnitCost.sql b/onprc_billing/resources/queries/onprc_billing/LeaseFeeDefinitionUnitCost.sql new file mode 100644 index 000000000..405a9f349 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/LeaseFeeDefinitionUnitCost.sql @@ -0,0 +1,22 @@ +PARAMETERS(chargeDate TIMESTAMP DEFAULT '1/1/2019') + +SELECT lf.rowId, +--lf.minAge, +--lf.maxAge, +--lf.assignCondition, +--lf.releaseCondition, +lf.chargeId, +lf.chargeid.rowId as lfRowID, +cr.chargeid.rowid as CRRowID, +cr.unitcost, +lf.chargeunit, +lf.active, +lf.startDate as lfstartdate, +cr.startDate as CRStartdate, +lf.endDate as lfenddate, +cr.enddate as crEndDate +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeDefinition lf + join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.chargeRates cr + on lf.chargeID.rowid = cr.chargeID.rowid --and lf.startdate >= cr.startDate and lf.enddate <= cr.enddate) +where ((lf.startdate <= chargedate and lf.enddate >= chargedate) + and (cr.startdate <=Chargedate and cr.enddate >= chargedate)) \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/LeaseFeeRates_Final.sql b/onprc_billing/resources/queries/onprc_billing/LeaseFeeRates_Final.sql new file mode 100644 index 000000000..159f2d300 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/LeaseFeeRates_Final.sql @@ -0,0 +1,95 @@ +--2020/02/12 build + +SELECT r.Id, +r.date as BillingDate, +r.enddate as ReleaseDate, +r.CenterProject, +r.AliasAtTime, + +--r.ageinyears, +--r.AgeGroup, +r.projectedReleaseCondition, +r.assignCondition, +r.releaseCondition, +r.releaseType, +r.AgeAtAssignment as AgeAtTime, +r.item as ChargeName, +r.ServiceCenter, +Case + When r.item = 'Lease Fee Adjustment' then a.leaseCharge1.name + else null + end as OriginalLeaseType, +r.revisedChargeID as FinalLeaseType, +r.AssignmentType as ChargeCategory, +r.CalculatedRate as UnitCost, +cr.unitCost as NIHRate, +--r.DayLease, + +--case statement when dayeleaselength > 0 then dayleasr leanth else 1 as quantity +case + when r.DayLeaseLength> 0 then r.dayleaseLength + when r.researchowned = 'Yes' then 0 + when d.birthType = 'Born to Resource Dam' then 0 + Else 1 + End as Quantity, +--Credit Alias Need to +r.MultipleAssignments, +--r.date, +r.projectedRelease, +r.datefinalized, +--r.releaseCondition, +--r.releaseType, +r.remark, +r.alias, +r.ChargeID, +--r.Item, +r.exemptionRate, +r.Multiplier, +r.subsidy, + +--r.revisedChargeID, +r.revisedSubsidy, +r.leasetype, +r.ResearchOwned, +r.farate, +r.removesubsidy, +r.canRaiseFA, +r.BirthAssignment, +r.BirthType, +case + When d.creditResource is not Null then d.creditResource + Else 'p51' + End as CreditTo, +Case +When d.creditResource is not Null then d.creditTo + else ca.account + End as CreditAccount, +case + WHen r.releaseType = 'No Charge' then 0 + when r.researchOwned = 'Yes' then 0 + when r.DayLeaseLength > 0 and r.daylease = 'yes' then (r.dayleaseLength * r.CalculatedRate) + when r.revisedrate is not null and r.revisedrate > r.CalculatedRate then (r.revisedRate - r.CalculatedRate) + when r.revisedrate is not null and r.revisedrate < r.CalculatedRate then (r.CalculatedRate - r.RevisedRate) + + Else (1 * r.CalculatedRate) + End as TotalCost, +r.revisedRate + + +--Fields to Add +--Is Exemption +--Is Non Standard Rate +--Ie Manually Entered +--Is Adjustment/Reversal +---Missing Alias +--Alias Accepting Charges +--Expired Alias +-->45 Days Olde +--Is Assigned at Tom +--IS Assigned to Protocol at Time + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeRates_2020 r + left outer join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeReleaseAdjustment a on a.id = r.id + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.chargeRates cr on r.chargeID = cr.chargeID and (cr.startDate <= r.date and cr.enddate >= r.date or cr.enddate is null) + left outer join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.creditAccount ca on ca.chargeID = r.chargeID and (r.Date > ca.startDate and r.Date <= ca.enddate) + Left outer join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.LeaseFee_Demographics d on r.id = d.id and r.date = d.date and r.project = d.project \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/LeaseFeeReleaseAdjustment.sql b/onprc_billing/resources/queries/onprc_billing/LeaseFeeReleaseAdjustment.sql new file mode 100644 index 000000000..a55bc8e42 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/LeaseFeeReleaseAdjustment.sql @@ -0,0 +1,96 @@ +--Update to full path Source +PARAMETERS (StartDate TIMESTAMP, EndDate TIMESTAMP) + +SELECT +a.id, +case + When a.enddate < a.dateFinalized then a.dateFinalized + Else a.enddate + End as date, +--a.date, +a.project, +a.project.project as projectID, +a.project.account as alias, +a.project.account.farate as faRate, +a.project.account.aliastype.removesubsidy as removeSubsidy, +a.project.account.aliastype.canRaiseFA as CanRaiseFA, +a.project.account.investigatorID, +a.project.account.fiscalAuthorityName as FANAme, +a.date as assignmentStart, +a.enddate, +a.projectedReleaseCondition, +a.releaseCondition, +a.assignCondition, +a.releaseType, +a.ageAtTime.AgeAtTimeYearsRounded as ageAtTime, +a5.id as ESPFAnimal, +'Lease Fees' as category, +--////This selectes the charge ID to be used +(SELECT max(rowid) as rowid FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.chargeableItems ci WHERE ci.name = javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.LEASE_FEE_ADJUSTMENT') and ci.active = true) as chargeId, +CASE + when (fl.id Is Not Null) then 0 + when (d.researchOwned = 'yes') then 0 + else 1 + end as quantity, +lf2.chargeId as leaseCharge1, +lf.chargeId as leaseCharge2, +a.objectid as sourceRecord, +'Adjustment - Automatic' as chargeCategory, +'Y' as isAdjustment, +Case + When a.id in (Select f.id from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.flags f where (f.id = a.id and f.flag.value = 'PI Purchased NHP' and f.enddate is Null)) then 'yes' + else 'No' + End as ResearchOwned, +a.datefinalized, +a.enddatefinalized + + +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeDefinition lf + ON (lf.assignCondition = a.assignCondition + AND lf.releaseCondition = a.releaseCondition + AND (a.ageAtTime.AgeAtTimeYearsRounded >= lf.minAge OR lf.minAge IS NULL) + AND (a.ageAtTime.AgeAtTimeYearsRounded < lf.maxAge OR lf.maxAge IS NULL) + and (a.date >=lf.startDate + and a.date <= lf.endDate) + ) + +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeDefinition lf2 + ON (lf2.assignCondition = a.assignCondition + AND lf2.releaseCondition = a.projectedReleaseCondition + AND (a.ageAtTime.AgeAtTimeYearsRounded >= lf2.minAge OR lf2.minAge IS NULL) + AND (a.ageAtTime.AgeAtTimeYearsRounded < lf2.maxAge OR lf2.maxAge IS NULL) + and (a.date >=lf2.startDate + and a.date <= lf2.endDate) + ) + +--find overlapping TMB at date of assignment + LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a2 ON ( + a.id = a2.id AND a.project != a2.project + AND a2.dateOnly <= a.dateOnly + AND a2.endDateCoalesced >= a.dateOnly + AND a2.project.name = javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.TMB_PROJECT') + ) +LEFt join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.assignment_U42ESPF a5 on + ( a.id = a5.id and a.project !=a5.project + and a5.project = 1107 + and a5.dateonly <=a.dateOnly + AND a5.endDateCoalesced >= a.dateOnly) + +--adds the reasearch owned animal exemption +Left JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.flags fl on + (a.id = fl.id + and fl.flag.code = 4034 + and (a.date >= fl.date and a.date <=COALESCE(fl.enddate,Now()) )) + +LEFt join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFee_demographics d + on a.id = d.id + +WHERE a.releaseCondition != a.projectedReleaseCondition +and (A.id != A5.id or A5.id is Null) +AND (a.enddatefinalized is not null) +and (a.enddateFinalized >= startDate and a.enddateFinalized <= enddate) +AND a.qcstate.publicdata = true +and lf.chargeID is not null +--AND lf.active = true +AND a2.id IS NULL and a.participantID not like '[a-z]%' \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/LeaseFee_Demographics.sql b/onprc_billing/resources/queries/onprc_billing/LeaseFee_Demographics.sql new file mode 100644 index 000000000..06c95cdfe --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/LeaseFee_Demographics.sql @@ -0,0 +1,121 @@ +/*-objectives are +IDentify Research versus resource assignments +Identify infant assignments (determine if Born to resource Mom) +2018-12-21 Added the folllowing to the mix +PI Purchased NHP is code in studyflags to look for +Need to determine if this is a day lease +Add Column for Credit To +Lease Type - Reqds from the query for leases and populates the lease sequnce to use +??Is there a benefit to having a query that reads lease charges from the\ +Update of File 2020-01-10 insured that all files use the subsistue page +*/ +--Update to resolve path issues +PARAMETERS(StartDate TIMESTAMP, EndDate TIMESTAMP) + +SELECT distinct a.Id, +Case + When a.id in (Select f.id from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.flags f where (f.id = a.id and f.flag.value = 'PI Purchased NHP' and f.enddate is Null)) then 'yes' + else 'No' + End as ResearchOwned, +a.project, +a.project.account as ProjectAlias, + +--determine age at time of assignment +a.ageAtTime.AgeAtTime as AgeAtAssignment, +a.id.age.ageinyears, +Case when a.ageAtTime.AgeAtTime <1 then 'infant' + Else 'adult' + End as AgeGroup, +Case when Cast(a.date as Date) = cast(d.date as date) then 'yes' + Else 'no' + End as BirthAssignment, +Case + when t.id is not null and t.tmbDamStatus <> 'Dam TMB Only' then 'TMB Infant with Dam' + when t.id is not null and t.tmbDamStatus = 'Dam TMB Only' then 'TMB Birth Dam Not on Research Project' + --when ( Cast(a.date as Date) = Cast(a.id.birth.date as Date) and t.id is not null) and a.project != t.DamAssignment then 'TMB Birth Dam Not on Research Project' + when (d.use_Category is null and Cast(a.date as Date) = cast(d.date as date)) then 'NonResourceBirth' + when (d.use_Category is not Null and Cast(a.date as Date) = cast(d.date as date)) then 'Born to Resource Dam' + else 'Non Birth Assignment' + End as BirthType, + +Case + --When da.id + when ( a.date = a.id.birth.date and t.id is not null) then 'TMB Birth' + + when a.project.use_category = 'Research' then 'Research' + Else a.project.use_category +end +as AssignmentType, +--determine if day lease - +Case + WHen a.assigncondition <> a.projectedReleaseCondition then 'No' + WHen a.assigncondition <> a.ReleaseCondition then 'No' + When (TimestampDiff('SQL_TSI_DAY',a.date,a.enddate) < 15 and TimestampDiff('SQL_TSI_DAY',a.date,a.enddate) >= 0) then 'Yes' + When TimestampDiff('SQL_TSI_DAY',a.date,a.projectedRelease) < 0 then 'Bad Date Entry' + When TimestampDiff('SQL_TSI_DAY',a.date,a.projectedRelease) < 15 then 'Yes' + When a.projectedRelease is null then 'No Defined Projected Release Date' + Else 'No' +End as DayLease, + +--build in to handle bad code +Case + WHen a.assigncondition <> a.projectedReleaseCondition then 1 + WHen a.assigncondition <> a.ReleaseCondition then 1 + when a.enddate is not null and TimestampDiff('SQL_TSI_DAY',a.date,a.enddate) < 15 then TimestampDiff('SQL_TSI_DAY',a.date,a.enddate) + when a.projectedRelease is not null and TimestampDiff('SQL_TSI_DAY',a.date,a.projectedRelease) < 15 and TimestampDiff('SQL_TSI_DAY',a.date,a.projectedRelease) >=0 then TimestampDiff('SQL_TSI_DAY',a.date,a.projectedRelease) + Else Null + End as DayLeaseLength, + +--need to determine if this is a dual assignment so we can tag who receives the credit + +Case + When da.project is not null then 'Dual Assigned' + +End as MultipleAssignments, + --(Select a2.project.name from study.assignment a2 where (a2.id = a.id and a.project <> a2.project and a2.enddate is null and a2.date <= a.date)) as DualAssignment, +---Case + -- When (da.project is not null and da.projectCategory = 'Resource') and da.dualassignment = a.project then da.project.name + -- else null + da.projectName as CreditResource, + da.projectAccount as CreditTo, +--Case +-- When (da.project is not null and da.projectCategory = 'Resource') and da.dualassignment = a.project then da.project.account +-- else null + -- da.projectAccount as CreditTo, + + + +a.date, +a.project.project as projectID, +a.projectedRelease, +a.enddate, +a.datefinalized, +a.assignCondition, +a.projectedReleaseCondition, +a.releaseCondition, +a.releaseType, +a.remark, +a.project.account As alias, +a.project.account.farate, +a.project.account.aliasType.removesubsidy, +a.project.account.aliasType.canRaiseFA + + +--This looks at situations where an animal is being dual assigned and credits the correct resource +--Case + + + +--End as CreditTo, + + +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a +left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.tmbBirth t on a.id = t.id +left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.birth_resourceDam d on a.id = d.id +--left outer join study.tmbdam t on t.id = a.id.birth.dam +Left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.dualassigned da on da.id = a.id and (da.dualassignment = a.project.project + and (da.enddate is null or da.enddate >= a.date) and (da.dualenddate is null or da.Dualenddate >= a.date)) +Left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.tmbDam tmb on tmb.id = a.id and (tmb.date <= a.date and tmb.enddate >= a.date or tmb.endDate is Null) +where a.datefinalized >= startDate and (a.datefinalized <= enddate or a.enddate is null) + +and a.id not like '[a-z]%' \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/LeaseFee_LeaseType.sql b/onprc_billing/resources/queries/onprc_billing/LeaseFee_LeaseType.sql new file mode 100644 index 000000000..3876e2a8d --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/LeaseFee_LeaseType.sql @@ -0,0 +1,109 @@ + +SELECT +l.id, +l.researchOwned, +l.project, +l.alias, +l.ageatAssignment, +l.ageinYears, +l.AgeGroup, +l.BirthAssignment, +l.BirthType, +l.AssignmentType, +l.daylease, +Case + when l.dayleaseLength = 0 then 1 + else l.dayLeaseLength + end as DayLeaseLength, +l.multipleAssignments, +l.CreditResource, +l.creditTo, +l.date as AssignmentDate, +l.projectid, +l.projectedRelease, +l.enddate as ReleaseDate, +l.dateFinalized, +l.assignCondition, +l.projectedReleaseCondition, +l.releaseCondition, +l.releaseType, +l.remark, +l.faRate, +l.removesubsidy, +l.canRaiseFA, + +--this provides the recorded dam for the NHP assocatied to the assignment +b.dam, +da.project as DualAssigned, +Case +--Research Owned Animal + When l.researchowned = 'yes' then 'researchOwned' +--Adult Research Assignment P51 Animal (animal unassigned and adult) +----**Dual Assigned Obese JMac Control Infant Lease + When l.id.age.ageinyears < 3 and da.projectname = '0622-01'and (l.id !=r.id or r.id is null) then 'Obese JMac Control Infant' +----**Dual Assigned Obese JMac WSD Infant Lease + When l.id.age.ageinyears < 3 and da.projectname = '0622-01'and l.id =r.id then 'Obese JMac WSD Infant' + --Adult Day Lease Condition Change for Research Assigned Adults - remove Age restriction + When (l.id.age.ageinyears > 1 and l.dayLease = 'yes' and l.assignCondition = l.projectedReleaseCondition) and (da.projectname != '0833' or da.projectname is Null ) then 'Day Lease Research Assignment P51 NHP NC' + --Adult Day L:ease No Condition Change + When (l.id.age.ageinyears > 1 and l.dayLease = 'yes' and l.assignCondition != l.projectedReleaseCondition) and (da.projectname != '0833' or da.projectname is Null) then 'Day Lease Research Assignment P51 NHP Condition Change' +--Dual assigned ESPF using different Chared Code +-- When da.projectName = '0492-03' then 'DualAssignedESPF' +--Dual assigned TMB Male on Day Lease + When l.agegroup = 'Adult' and da.projectname = '0300' and l.dayLease = 'yes' then 'TMB Adult Day Lease' +--Dual assigned Obese Male Day Lease + When l.agegroup = 'Adult' and da.projectname = '0833' and l.dayLease = 'yes' then 'OBESE Adult Day Lease' +--Full LEase P51 adult + When l.id.age.ageinyears > 1 and l.daylease <> 'yes' and (da.projectname <> '0833' or da.projectName is Null) then 'Research Assignment P51 Adult' +--**Dual Assigned TMB-Dam Assigned Use lease_TMB as Process -------------------------------------------------------------------------------------------------------- +-- For No charge Dam is Dual assigned to TMB and to the Project and Infant is assigned to the Project - THe lease for infant is built into the TMB Lease of the Dam + WHEN L.Birthtype = 'TMBResearchAssignment' then 'TMB No Charge' +--**Dual Assigned TMB Dam Not Assigned ---------------------------------------------------------------------------------------------------------------------------- +-- For this the INfant and Dam are not assigned to the same project and the dam is assigned to TMB + WHEN L.Birthtype = 'TMB DAm Not Assigned' then 'TMB Full P 51 Rate Lease' +--Infant born to Resource Dam + When l.birthType = 'Born to Resource Dam' then l.birthType +--handle Birth to resource and research at birth --handle it +/*********Dual Assigned ESPFTMB Birth */ + When da.projectName = '0492-03' then 'DualAssignedESPF' +----Dual Assigned Obese JMac Infant or Dam Day Lease = No condition Code CHanges - if change full lease + When da.projectname = '0622-01' and l.daylease = 'yes' then 'Obese 0622-01 Day Lease' +----**Dual Assigned Obese JMac Control Infant Lease + When l.id.age.ageinyears < 3 and da.projectname = '0622-01'and l.id !=r.id then 'Obese JMac Control Infant' +----**Dual Assigned Obese JMac WSD Infant Lease + When l.id.age.ageinyears < 3 and da.projectname = '0622-01'and l.id =r.id then 'Obese JMac WSD Infant' +----**Dual Assigned Obese Adult Day Lease + When l.agegroup = 'adult' and da.projectname = '0833' and l.daylease = 'yes' then 'OBESE Adult Day Lease' +----**Dual Assigned Obese Adult Male Lease + When l.agegroup = 'adult' and da.projectname = '0833' and l.daylease = 'no' and Cast(l.projectedReleaseCondition as Varchar(20)) != 'Terminal' then 'OBESE Adult Male Lease' +----Dual Assigned Obese Adult Male Terminal Lease + When l.agegroup = 'adult' and da.projectname = '0833' and l.daylease = 'no' and Cast(l.projectedReleaseCondition as Varchar(20)) = 'Terminal' then 'OBESE Adult Terminal Leasel' +--when Adult Animal Assigned to Research project + when l.agegroup = 'adult' and da.project ='0300' then 'Aninal Lease Fee -TMB' +--Infant Research Assignment P51 Animal Day Lease ------------------------------------------------------------------------------------------------------- + When l.id.age.ageinyears < 1 and l.daylease = 'yes' then 'Day Lease Research Assignment P51 Infant' +--Infant Research Assignment P51 Animal------------------------------------------------------------------------------------------------------- + When l.ageatAssignment < 1 then 'Research Assignment P51 Infant' +Else 'UnDeteremined' +End As LeaseType, + +/*Case +--Dual Assigned 0492-02 + When da.projectname = '0492-02' then 'Dual Assigned U42' +--Dual Assigned 0492-45 + When da.projectname = '0492-45' then 'Dual Assigned JMR' +--Dual Assigned 0689 + When da.projectname = '0689' then 'Dual Assigned IDR Orphanage' +--Dual Assigned 0456 + When da.projectname = '0456' then 'Dual Assigned Aging' +When da.projectName = '0492-03' then 'DualAssignedESPF' +else 'P-51' +ENd as CreditTo, +*/ + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leasefee_demographics l + left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.birth b on l.id = b.id + left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.lease_ObeseInfant_HFDDam R on l.id = r.id + Left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.dualassigned da on da.id = l.id and (da.dualassignment = l.project + and (da.enddate is null or da.enddate > l.date) and (da.dualenddate is null or Dualenddate > l.date)) +where l.researchowned = 'no' \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/LeaseFee_UnitCost_RateCalc.sql b/onprc_billing/resources/queries/onprc_billing/LeaseFee_UnitCost_RateCalc.sql new file mode 100644 index 000000000..7958e085b --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/LeaseFee_UnitCost_RateCalc.sql @@ -0,0 +1,73 @@ +--Corrested Issue with Adjustments and loading into Test + +SELECT d.Id, + r.leasetype, + d.ResearchOwned, + d.project, --integer + d.ProjectAlias, + d.AgeAtAssignment, + d.ageinyears, + d.AgeGroup, + d.BirthAssignment, + d.BirthType, + d.AssignmentType, + d.DayLease, + d.DayLeaseLength, --integer + d.MultipleAssignments, + d.date, + d.projectedRelease, + d.enddate, + d.datefinalized, + d.assignCondition, --integer + d.projectedReleaseCondition, --integer + d.releaseCondition, --integer + d.releaseType, + d.remark, + d.alias, + d.farate, + d.removesubsidy, + d.canRaiseFA, + r.ChargeID, --integer + RateCalc(d.alias,r.chargeID,d.project,d.Date,d.farate) as CalculatedRate, + r.revisedChargeID + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leasefee_rateData r join + Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.LeaseFee_Demographics d on r.id = d.id and r.assignmentdate = d.date and r.projectid = d.project + join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leasefee_LeaseType t on d.id = t.id and t.assignmentdate = d.date and t.project = d.project + + +union + +select + a.id, + 'automatic_adjustment' as AssignmentType, + '' as researchOwned, + a.projectID, --intege + a.alias, + a.ageattime, + 1 as ageinYears, --need to run function to return years + '' as agegroup, + '' as BirthAssignment, + '' as BirthType, + 'automatic_adjustment' as AssignmentTypeNA, + '' as DayLease, + '' as DayLeaseLength, --integer + '' as MultipleAssignments, + a.date, + a.enddate as projectedrelease, + a.enddate, + a.datefinalized, + a.assignCondition, --0integer + a.projectedReleaseCondition, --integer + a.releaseCondition,--integer + a.releasetype, + '' as remark, + a.alias as alias2, + a.faRate as farate, + a.removeSubsidy as removesubsidy, + a.canRaiseFA as canRaiseFA, + a.leaseCharge1, --integer + RateCalc(a.alias,a.leasecharge2,a.projectID, a.date,a.farate) as RevisedRate, + a.leaseCharge2 + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.LeaseFeeReleaseAdjustment a \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/MiscChargesNotBilled_Virology.sql b/onprc_billing/resources/queries/onprc_billing/MiscChargesNotBilled_Virology.sql new file mode 100644 index 000000000..3280c65e3 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/MiscChargesNotBilled_Virology.sql @@ -0,0 +1,49 @@ +--New query as source of Misc CHarges Not yet billing will replace needed items in Test and Production +SELECT d.Id, +d.date, +d.billingDate, +d.project, +d.account as ChargeTo, +d.chargetype as CreditTo, +d.creditAccount, +d.creditAccountType, +d.investigatorId, +d.chargeId, +d.category, +d.item, +d.unitCost, +m.unitCost as nihRate, +d.quantity, +Sum(d.unitCost * d.quantity) as TOtalCharges, +d.chargeCategory, +d.comment, + +d.invoiceId, +d.created, +d.createdby, +m.taskId +FROM MiscChargeswithRates d join MiscCharges m on d.taskId = m.taskId and d.sourceRecord = m.objectID +where d.invoiceID is null and d.category = 'Virology' +Group by +d.Id, +d.date, +d.billingDate, +d.project, +d.account, +d.chargetype, +d.creditAccount, +d.creditAccountType, +d.investigatorId, +d.chargeId, +d.category, +d.item, +d.unitCost, +m.unitCost, +d.quantity, +d.chargeCategory, +d.comment, + +d.invoiceId, +d.created, +d.createdby, +m.taskId \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/aliases/.qview.xml b/onprc_billing/resources/queries/onprc_billing/aliases/.qview.xml index 5b16c9251..4b9701c0a 100644 --- a/onprc_billing/resources/queries/onprc_billing/aliases/.qview.xml +++ b/onprc_billing/resources/queries/onprc_billing/aliases/.qview.xml @@ -4,10 +4,12 @@ - + + + @@ -15,8 +17,18 @@ + + + + + + + + + + \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/assignment_ObeseResource.sql b/onprc_billing/resources/queries/onprc_billing/assignment_ObeseResource.sql new file mode 100644 index 000000000..91379f5aa --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/assignment_ObeseResource.sql @@ -0,0 +1,6 @@ +SELECT a.Id, + a.project, + a.dateOnly, + a.endDateCoalesced +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a +where a.enddate is Null and a.project.use_category like '%obese%' \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/assignment_U42ESPF.sql b/onprc_billing/resources/queries/onprc_billing/assignment_U42ESPF.sql new file mode 100644 index 000000000..2666909cd --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/assignment_U42ESPF.sql @@ -0,0 +1,8 @@ + +SELECT a.Id, +a.project, +a.project.use_category, +a.dateOnly, +a.endDateCoalesced +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a +where a.enddate is Null and a.project.use_category like '%ESPF%' \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/clinPathRun_ExemptCharges.sql b/onprc_billing/resources/queries/onprc_billing/clinPathRun_ExemptCharges.sql new file mode 100644 index 000000000..c71079dd5 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/clinPathRun_ExemptCharges.sql @@ -0,0 +1,25 @@ +SELECT c.Id, +c.date, +c.project, +c.servicerequested, +c.chargetype, +c.sampletype, +c.tissue, +c.collectionMethod, +c.method, +c.remark, +c.type, +c.instructions, +c.units, +c.taskid, +c.performedby, +c.requestid, +c.history, +c.isAssignedAtTime, +c.isAssignedToProtocolAtTime, +c.enteredSinceVetReview, +c.QCState, +c.objectID as sourceRecord, +c.datefinalized as billingDate +FROM study.clinpathRuns c left outer join Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.lists.Labfee_NoChargeProjects p on c.project.DisplayName = p.project +where (p.dateDisabled is null and p.project is Null) \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/grantProjects/.qview.xml b/onprc_billing/resources/queries/onprc_billing/grantProjects/.qview.xml index 48406378c..0f86249c4 100644 --- a/onprc_billing/resources/queries/onprc_billing/grantProjects/.qview.xml +++ b/onprc_billing/resources/queries/onprc_billing/grantProjects/.qview.xml @@ -1,7 +1,6 @@ - diff --git a/onprc_billing/resources/queries/onprc_billing/invoiceditems.query.xml b/onprc_billing/resources/queries/onprc_billing/invoiceditems.query.xml new file mode 100644 index 000000000..600842dde --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/invoiceditems.query.xml @@ -0,0 +1,185 @@ + + + + + Invoiced Items + + + + Row Id + true + + + Invoice + + + onprc_billing + invoiceRuns + objectid + rowid + + + + Transaction Number + + + Invoice Date + true + + + http://cpas.labkey.com/Study#ParticipantId + + + Transaction Date + Date + + + Item + + + Item Code + A code used to refer to identify this item, which is primarily used when exporting or communicating with external billing systems + + + Category + + onprc_billing + chargeableItemCategories + category + category + + + + Service Center + + + Project + + + Debited Alias + + + Credited Alias + + + FAID + + onprc_billing + fiscalAuthorities + rowid + lastName + + + + + + + Last Name + + + First Name + + + Department + true + + + Mail Code + true + + + Contact Phone + true + + + true + + + Cage Id + true + + + Key + true + true + false + false + + + Quantity + + + Unit Cost + $###,##0.00 + + + Total Cost + $###,##0.00 + + + Is Credit? + true + + + Rate Id + true + + + Exception Id + true + + + Credit Account Id + true + + + Comment + + + Transaction Type + true + + + + Charge Source Clin Path + + /ONPRC/EHR + study + ClinPathRuns + objectId + SampleID + + + + + true + + + Issue # + true + + + Charge Category + + + Billing Id + true + + + Invoice Number + true + + + true + + + + Date + + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/labworkFeeDefinition.query.xml b/onprc_billing/resources/queries/onprc_billing/labworkFeeDefinition.query.xml new file mode 100644 index 000000000..8061a69f0 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/labworkFeeDefinition.query.xml @@ -0,0 +1,59 @@ + + + + + Labwork Charges + + + + Row Id + + + Service/Panel Name + false + + /ONPRC/EHR + ehr_lookups + labwork_services + servicename + + + + Charge Type + true + true + + /ONPRC/EHR + ehr_lookups + labworkChargeType + value + + + + Charge Id + false + + + Is Active? + true + + + Start Date + false + Date + + + End Date + false + Date + + + + + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/labworkFeeRates.sql b/onprc_billing/resources/queries/onprc_billing/labworkFeeRates.sql index 29f8d8f5c..32638da14 100644 --- a/onprc_billing/resources/queries/onprc_billing/labworkFeeRates.sql +++ b/onprc_billing/resources/queries/onprc_billing/labworkFeeRates.sql @@ -38,15 +38,23 @@ SELECT WHEN (alias.category IS NOT NULL AND alias.category != 'OGA') THEN cr.unitCost --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null + --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + --WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN + ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate)))) ELSE 1 END)) + --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) + --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + --WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)))/(1+ alias.faRate)) ELSE 1 END)) + --the NIH rate ELSE cr.unitCost END AS DOUBLE), 2) as unitCost, + cr.unitCost as nihRate, 1 as quantity, COALESCE(cu.account, cast(ce.account as varchar(100))) as creditAccount, @@ -170,7 +178,12 @@ SELECT mc.item, mc.category, - mc.unitcost, + case + When mc.project.displayName in (Select project from Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.lists.LabFee_NoChargeProjects where enddate is null) + then 0 + else mc.unitcost + End as unitCost, + -- mc.unitcost, mc.nihRate, mc.quantity, @@ -198,5 +211,7 @@ SELECT mc.currentActiveAlias FROM onprc_billing.miscChargesFeeRateData mc +--left outer join "/ONPRC/ADMIN/FINANCE".lists.LabFee_NoChargeProjects nc on (mc.project.displayName = nc.project and nc.DateDisabled is null) + WHERE cast(mc.billingDate as date) >= CAST(StartDate as date) AND cast(mc.billingDate as date) <= CAST(EndDate as date) -AND mc.category = 'Clinical Lab Test' \ No newline at end of file +AND mc.category = 'Clinical Lab Test' --and nc.project is null \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/labworkFees.sql b/onprc_billing/resources/queries/onprc_billing/labworkFees.sql index 487ebcd57..b1c222f8a 100644 --- a/onprc_billing/resources/queries/onprc_billing/labworkFees.sql +++ b/onprc_billing/resources/queries/onprc_billing/labworkFees.sql @@ -1,28 +1,20 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - */ ---this query displays all animals co-housed with each housing record ---to be considered co-housed, they only need to overlap by any period of time - PARAMETERS(StartDate TIMESTAMP, EndDate TIMESTAMP) SELECT e.Id, e.date, - e.datefinalized as billingDate, + e.billingDate, e.project, e.servicerequested, p.chargeId, - e.objectid as sourceRecord, + e.sourceRecord, null as chargeCategory, e.taskid -FROM study.clinpathRuns e +FROM onprc_billing.clinPathRun_ExemptCharges e JOIN onprc_billing.labworkFeeDefinition p ON (p.servicename = e.servicerequested AND p.active = true) -WHERE CAST(e.datefinalized as date) >= CAST(StartDate as date) AND CAST(e.datefinalized as date) <= CAST(EndDate as date) +WHERE CAST(e.billingdate as date) >= CAST(StartDate as date) AND CAST(e.billingdate as date) <= CAST(EndDate as date) AND (e.chargetype not in ('Not Billable', 'No Charge', 'Research Staff') or e.chargetype is null) AND e.qcstate.publicdata = true @@ -31,18 +23,18 @@ UNION ALL --for any service sent to an outside lab, we have 1 processing charge per distinct sample SELECT e.Id, - e.dateOnly, - e.datefinalized as billingDate, + e.date, + e.billingDate, e.project, group_concat(e.servicerequested) as servicerequested, - (SELECT c.rowid FROM onprc_billing_public.chargeableItems c WHERE c.name = 'Lab Processing Fee') as chargeId, + (SELECT c.rowid FROM onprc_billing_public.chargeableItems c WHERE c.name = 'Lab Processing Fee') as chargeId, null as sourceRecord, null as chargeCategory, e.taskid -FROM study.clinpathRuns e -WHERE CAST(e.datefinalized as date) >= CAST(StartDate as date) AND CAST(e.datefinalized as date) <= CAST(EndDate as date) +FROM onprc_billing.clinPathRun_ExemptCharges e +WHERE CAST(e.billingDate as date) >= CAST(StartDate as date) AND CAST(e.billingDate as date) <= CAST(EndDate as date) AND e.qcstate.publicdata = true AND (e.chargetype not in ('Not Billable', 'No Charge', 'Research Staff') or e.chargetype is null) AND e.servicerequested.outsidelab = true -GROUP BY e.Id, e.dateOnly, e.datefinalized, e.project, e.tissue, e.taskid \ No newline at end of file +GROUP BY e.Id, e.date, e.billingdate, e.project, e.tissue, e.taskid \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/leaseFeeRates.sql b/onprc_billing/resources/queries/onprc_billing/leaseFeeRates.sql index 85a2d9540..ffabcf77b 100644 --- a/onprc_billing/resources/queries/onprc_billing/leaseFeeRates.sql +++ b/onprc_billing/resources/queries/onprc_billing/leaseFeeRates.sql @@ -1,3 +1,4 @@ + /* * Copyright (c) 2013 LabKey Corporation * @@ -114,11 +115,11 @@ SELECT --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate)))) ELSE 1 END)) --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) - --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + --raise F&A on ly + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)))/(1+ alias.faRate)) ELSE 1 END)) --the NIH rate ELSE cr.unitCost END AS DOUBLE) as unitCost1, @@ -138,11 +139,11 @@ SELECT --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr2.unitCost / (1 - COALESCE(cr2.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr2.unitCost / (1 - COALESCE(cr2.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate))) ELSE 1 END)) --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr2.unitCost / (1 - COALESCE(cr2.subsidy, 0))) --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr2.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr2.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate))) ELSE 1 END)) --the NIH rate ELSE cr2.unitCost END AS DOUBLE) as unitCost2, @@ -162,11 +163,11 @@ SELECT --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr3.unitCost / (1 - COALESCE(cr3.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr3.unitCost / (1 - COALESCE(cr3.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / ( 1 + alias.faRate))) ELSE 1 END)) --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr3.unitCost / (1 - COALESCE(cr3.subsidy, 0))) --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr3.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr3.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate))) ELSE 1 END)) --the NIH rate ELSE cr3.unitCost END AS DOUBLE) as unitCost3, diff --git a/onprc_billing/resources/queries/onprc_billing/leaseFeeRates_2020.sql b/onprc_billing/resources/queries/onprc_billing/leaseFeeRates_2020.sql new file mode 100644 index 000000000..b789728c6 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/leaseFeeRates_2020.sql @@ -0,0 +1,152 @@ +--Corrested Issue with Adjustments and loading into Test +--20200111 - changed source from rate data to a passthru with a lookup of rate name and unit cost + +SELECT d.Id, + r.leasetype, + d.ResearchOwned, + d.project, --integer + d.project.name as CenterProject, + r.AliasAtTime, + d.AgeAtAssignment, + d.ageinyears, + d.AgeGroup, + d.BirthAssignment, + d.BirthType, + d.AssignmentType, + d.DayLease, + d.DayLeaseLength, --integer + d.MultipleAssignments, + d.CreditResource as dualassignment, + null as creditto, + d.date, + d.projectedRelease, + d.enddate, + d.datefinalized, + d.assignCondition, --integer + d.projectedReleaseCondition, --integer + d.releaseCondition, --integer + d.releaseType, + d.remark, + d.alias, + d.farate, + d.removesubsidy, + d.canRaiseFA, + r.ChargeID, --integer + i.Name as Item, + i.DepartmentCode as ServiceCenter, + r.exemptionRate, + r.Multiplier, + r.subsidy, + RateCalc(r.AliasAtTime,r.chargeID,d.project,d.Date,.4) as CalculatedRate, + null as revisedRate, + r.revisedChargeID, + r.revisedSubsidy + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leasefee_rateChargeItem r join + Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.LeaseFee_Demographics d on r.id = d.id and r.assignmentdate = d.date and r.projectid = d.project + join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leasefee_LeaseType t on d.id = t.id and t.assignmentdate = d.date and t.project = d.project + join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.chargeableItems i on i.rowID = r.chargeID + +union + +select + a.id, + 'automatic_adjustment' as AssignmentType, + a.researchowned, + a.projectID, --intege + a.project.name as CenterProject, + a.alias, + a.ageattime, + 1 as ageinYears, --need to run function to return years + '' as agegroup, + '' as BirthAssignment, + '' as BirthType, + 'automatic_adjustment' as AssignmentTypeNA, + '' as DayLease, + '' as DayLeaseLength, --integer + '' as MultipleAssignments, + null as dualassignment, + null as creditto, + a.date, + a.enddate as projectedrelease, + a.enddate, + a.datefinalized, + a.assignCondition, --0integer + a.projectedReleaseCondition, --integer + a.releaseCondition,--integer + a.releasetype, + '' as remark, + a.alias as alias2, + a.faRate as farate, + a.removeSubsidy as removesubsidy, + a.canRaiseFA as canRaiseFA, + a.leaseCharge1, --integer + ii.name as Item, + ii.DepartmentCode as ServiceCenter, + null as exemptionRate, + null as Multiplier, + null as subsidy, + RateCalc(a.alias,a.leasecharge1,a.projectID, a.date,a.farate) as CalculatedRate, + RateCalc(a.alias,a.leasecharge2,a.projectID, a.date,a.farate) as RevisedRate, + a.leaseCharge2, + null as RevisedSubsidy + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.LeaseFeeReleaseAdjustment a +join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.chargeableItems ii on ii.rowID = a.chargeID + + +Union + + + +Select + r.id, + 'Misc Charge', + null as researchOwned, + r.project, + r.project.name as CenterProject, + r.account.alias, + null as ageatTime, + null as ageInYears, + null as AgeGroup, + null as BirthAssignment, + null as BirthType, + case + When r.chargeCategory is not Null then r.chargeCategory + Else 'Misc Charge' + End as AssignmentTypeNA, + null as DayLease, + null as DayLeaseLength, --integer + null as MultipleAssignments, + null as dualassignment, + null as creditto, + r.date, + null as projectedrelease, + null as enddate, + null as datefinalized, + null as assignCondition, --0integer + null as projectedReleaseCondition, --integer + null as releaseCondition,--integer + null as releasetype, + r.comment as remark, + null as alias2, + null as farate, + null as removesubsidy, + null as canRaiseFA, + r.chargeID, --integer + r.chargeID.Name as Item, + r.serviceCenter as ServiceCenter, + null as exemptionRate, + Null as Multiplier, + null as Subsidy, + + r.rateCalc, + null as RevisedRate, + null as rate2, + null as RevisedSubsidy + + + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.miscChargesWithRates r +WHERE cast(r.billingDate as date) >= CAST(StartDate as date) AND cast(r.billingDate as date) <= CAST(EndDate as date) +AND r.category IN ('Lease Fees', 'Lease Setup Fee', 'Lease Setup Fees') diff --git a/onprc_billing/resources/queries/onprc_billing/leaseFeeRates_Final.query.xml b/onprc_billing/resources/queries/onprc_billing/leaseFeeRates_Final.query.xml new file mode 100644 index 000000000..c1be7a883 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/leaseFeeRates_Final.query.xml @@ -0,0 +1,151 @@ + + + + + Lease Fee Charges + + + + + ehr + project + project + + + + + onprc_billing_public + aliases + alias + + + + Investigator + true + + onprc_ehr + investigators + rowid + lastName + + + + + ehr + tasks + taskid + rowid + + + + Charge + + onprc_billing_public + chargeableItems + rowid + + + + + onprc_billing_public + chargeableItems + rowid + + + + + onprc_billing_public + chargeableItems + rowid + + + + Is Rate Exemption? + + + Unit Cost + $###,##0.00 + + + Total Cost + $###,##0.00 + + + Credit Alias + + + true + + + true + + + true + + + Lacks Unit Cost? + true + + + Rate Id + true + /query/executeQuery.view?schemaName=onprc_billing&query.queryName=chargeRates&query.rowid~eq=${rateid} + + + Exemption Id + true + /query/executeQuery.view?schemaName=onprc_billing&query.queryName=chargeRateExemptions&query.rowid~eq=${exemptionId} + + + true + + + Is Manually Entered? + + + Is Adjustment/Reversal? + + + Missing Alias? + + + Missing FAID? + + + Expired Alias? + + + Alias Accepting Charges? + + + >45 Days Old? + + + Unit Cost, Based On Projected Release + true + + + NIH Rate, Based On Projected Release + true + + + Adjustment Unit Cost, Based On Projected Release + true + + + Adjustment NIH Rate, Based On Projected Release + true + + + Adjustment Unit Cost, Based On Actual Release + true + + + Adjustment NIH Rate, Based On Actual Release + true + + +
+
+
+
\ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/leaseFee_RateReview.sql b/onprc_billing/resources/queries/onprc_billing/leaseFee_RateReview.sql new file mode 100644 index 000000000..da8b30591 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/leaseFee_RateReview.sql @@ -0,0 +1,55 @@ +SELECT r.id, +r.CenterProject, +r.ProjectID, +r.CurrentAlias, +r.AliasAtTime, +r.RemoveSubsidy, +r.leasetype, +r.assignmentdate, +r.code, +r.ProjectedReleaseCode, +r.AssignmentAge, +r.chargeId, +r.subsidy, +r.ChargeItem, +r.unitCost, +r.multiplier, +r.ExemptionRate, +r.RevisedChargeID, +r.RevisedItem, +r.RevisedSubsidy, +r.RevisedUnitCost, +Case + when r.ExemptionRate is not null then ('Exemption Rate: ' || CAST(r.ExemptionRate AS varchar(100))) + When r.multiplier is not null THEN ('Multiplier: ' || CAST(r.multiplier AS varchar(100))) + Else Null +End as isExemption, +--Is Non Standard Rate Looks to see if +--Ie Manually Entered +--Is Adjustment/Reversal + +---Missing Alias +Case When r.aliasAtTime is Null then 'y' + else 'n' + End As Missingalias, +--Alias Accepting Charges +CASE + WHEN a.aliasEnabled IS NULL THEN 'N' + WHEN a.aliasEnabled != 'Y' THEN 'N' + ELSE null + END as isAcceptingCharges, +--Expired Alias + CASE + WHEN (a.budgetStartDate IS NOT NULL AND CAST(a.budgetStartDate as date) > CAST(r.assignmentdate as date)) THEN 'Prior To Budget Start' + WHEN (a.budgetEndDate IS NOT NULL AND Cast(a.budgetEndDate as date ) < CAST(r.assignmentdate as date)) THEN 'After Budget End' + WHEN (a.projectStatus IS NOT NULL AND a.projectStatus != 'ACTIVE' AND a.projectStatus != 'No Cost Ext' AND a.projectStatus != 'Partial Setup') THEN 'Grant Project Not Active' + ELSE null + END as isExpiredAccount, +-->45 Days Olde +CASE WHEN (TIMESTAMPDIFF('SQL_TSI_DAY', r.assignmentDate, curdate()) > 45) THEN 'Y' ELSE null END as isOldCharge, +--Is Assigned at Time +--IS Assigned to Protocol at Time + + +FROM leasefee_rateChargeItem r + Left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.aliases a on r.aliasatTime = a.alias \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/leaseFees.sql b/onprc_billing/resources/queries/onprc_billing/leaseFees.sql index 60486916f..956b946a8 100644 --- a/onprc_billing/resources/queries/onprc_billing/leaseFees.sql +++ b/onprc_billing/resources/queries/onprc_billing/leaseFees.sql @@ -2,7 +2,9 @@ PARAMETERS(StartDate TIMESTAMP, EndDate TIMESTAMP) SELECT a.id, +--This shoould compare finalized to assignent date which is date a.date, + a.project, a.date as assignmentStart, a.enddate, @@ -10,19 +12,74 @@ a.projectedReleaseCondition, a.releaseCondition, a.assignCondition, a.releaseType, +a5.id as ESPFAnimal, a.ageAtTime.AgeAtTimeYearsRounded as ageAtTime, 'Lease Fees' as category, + +--determine if the animal is assigned to U42 ESPF + + CASE +-- Determine if the animal is currently a n Obese Animal +-- Deermines if the animal is part of 0833 +-- TODO Need to change the Day lease to release date instead of projected release date +When a5.id is not Null + then '5348' + -- then (Select c.rowid from chargeableItems c where c.itemCode = '1077') +-- remove setup fee from Day Leases + When (a3.id IS NOT NULL + and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)<= 14 AND a.enddate IS NULL)) + AND a.assignCondition = a.projectedreleasecondition + then (Select c.rowid from chargeableItems c where c.itemCode = 'ONR01') + --short term obese lease + When (a3.id is Not Null + and ((TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease) > 14) + and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)< 90)) + AND a.assignCondition = a.projectedreleasecondition + AND a.enddate IS NULL) + then (Select c.rowid from Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.onprc_billing.chargeableItems c where c.itemCode = 'ONR24') + --obese long term terminal assignment + When (a3.Id is not Null AND ((TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) > 90 ) AND a.enddate is NULL and a.projectedReleaseCondition = 206) + then (Select c.rowid from Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.onprc_billing.chargeableItems c where c.itemCode = 'ONR45') + --obese long term + When (a3.id Is Not NUll + and ((TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)> 90 ) AND a.enddate IS NULL)) + then (Select c.rowid from Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.onprc_billing.chargeableItems c where c.itemCode = 'ONR25') + +--Infant/Dam Day Lease + + When (a4.id is not null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) <=14 and a.endDate is null and a.ageAtTime.AgeAtTimeYearsRounded < 1 + and a.remark like '%Diet%') + then (Select c.rowid from Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.onprc_billing.chargeableItems c where c.itemCode = 'ONR40') + When (a4.id is not null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) <=14 and a.endDate is null and a.ageAtTime.AgeAtTimeYearsRounded < 1 + and a.remark like 'Control%') + then (Select c.rowid from Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.onprc_billing.chargeableItems c where c.itemCode = 'ONR41') + When (a4.id is not null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) <=14 and a.endDate is null and a.ageAtTime.AgeAtTimeYearsRounded < 1) + then (Select c.rowid from Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer')}.onprc_billing.chargeableItems c where c.itemCode = 'ONR44') + WHEN (a.duration <= CAST(javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.DAY_LEASE_MAX_DURATION') as INTEGER) AND a.enddate IS NOT NULL AND a.assignCondition = a.releaseCondition) THEN (SELECT rowid FROM onprc_billing_public.chargeableItems ci WHERE ci.active = true AND ci.name = javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.DAY_LEASE_NAME')) WHEN (a.duration <= CAST(javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.DAY_LEASE_MAX_DURATION') as INTEGER) AND a.enddate IS NOT NULL AND a.assignCondition = a.releaseCondition) THEN (SELECT rowid FROM onprc_billing_public.chargeableItems ci WHERE ci.active = true AND ci.name = javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.DAY_LEASE_NAME')) WHEN a2.id IS NOT NULL THEN (SELECT rowid FROM onprc_billing_public.chargeableItems ci WHERE (ci.startDate <= a.date and ci.endDate >= a.date) AND ci.name = javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.TMB_LEASE_NAME')) ELSE lf.chargeId END as chargeId, --special case one-day lease rates. note: if enddate is null, these cannot be a one-day lease CASE - WHEN (Select Count(*) from study.birth b - left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a1 on b.id = a.id and a.date = b.dateOnly and a.project.use_category in ('Center Resource','U42','U24') - left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a2 on b.dam = a2.id and a2.project.use_category in ('Center Resource','U42','U24') and (a2.date <= b.dateOnly and a2.endDate >=b.dateOnly or a2.enddate is Null) + WHen a3.id is not Null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) >14 Then 1 + WHen a4.id is not Null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) >14 Then 1 + WHen a3.id is not Null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) <=14 Then (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) + WHen a4.id is not Null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) <=14 Then (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) + WHen a4.id is not Null and (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) >14 Then (TIMESTAMPDIFF('SQL_TSI_Day',a.date,a.projectedRelease)) +--this looks for TMB INfant and sets count to 0. Based on Mom being TMB + + WHEN (Select Count(*) from study.birth b + left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a1 on b.id = a.id and a.date = b.dateOnly + left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a2 on b.dam = a2.id and a2.project = 559 and (a2.date <= b.dateOnly and a2.endDate >=b.dateOnly or a2.enddate is Null) + where b.id = a.id and a1.project.protocol != a2.project.protocol) > 0 THEN 0 +--infdants born to resource dams + WHEN (Select Count(*) from study.birth b + left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a1 on b.id = a.id and a.date = b.dateOnly and a.project.use_category in ('Center Resource','U42','U24') + left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a2 on b.dam = a2.id and a2.project.use_category in ('Center Resource','U42','U24') and (a2.date <= b.dateOnly and a2.endDate >=b.dateOnly or a2.enddate is Null) where b.id = a.id and a1.project.protocol = a2.project.protocol) > 0 THEN 0 + WHEN (a.duration = 0 AND a.enddate IS NOT NULL AND a.assignCondition = a.releaseCondition) THEN 1 WHEN (fl.id Is Not Null) THEN 0 --This will check for infants born to resource moms and will not charge @@ -37,7 +94,6 @@ null as chargeCategory, null as isAdjustment, a.datefinalized, a.enddatefinalized - FROM study.assignment a --find overlapping TMB at date of assignment @@ -48,19 +104,50 @@ LEFT JOIN study.assignment a2 ON ( AND a2.project.name = javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.TMB_PROJECT') ) + +--Obese 0833 animals id 1609 +LEFT join onprc_billing.assignment_ObeseResource a3 on + ( a.id = a3.id and a.project !=a3.project + and a3.project = 1609 + and a3.dateonly <=a.dateOnly + AND a3.endDateCoalesced >= a.dateOnly) + +--Obese 0622-01 animals id 1082 +LEFT join onprc_billing.assignment_ObeseResource a4 on + ( a.id = a4.id and a.project !=a4.project + and a4.project = 1082 + and a4.dateonly <=a.dateOnly + AND a4.endDateCoalesced >= a.dateOnly) + + + + + +--espf animals being dual assigned +LEFT join assignment_U42ESPF a5 on + ( a.id = a5.id and a.project !=a5.project + and a5.project = 1107 + and a5.dateonly <=a.dateOnly + AND a5.endDateCoalesced >= a.dateOnly) + LEFT JOIN onprc_billing.leaseFeeDefinition lf ON ( - lf.assignCondition = a.assignCondition - AND lf.releaseCondition = a.projectedReleaseCondition - AND (a.ageAtTime.AgeAtTimeYearsRounded >= lf.minAge OR lf.minAge IS NULL) - AND (a.ageAtTime.AgeAtTimeYearsRounded < lf.maxAge OR lf.maxAge IS NULL) - AND lf.active = true + a3.Id is null and a4.id is Null and a5.id is Null And + lf.assignCondition = a.assignCondition + AND lf.releaseCondition = a.projectedReleaseCondition + AND (a.ageAtTime.AgeAtTimeYearsRounded >= lf.minAge OR lf.minAge IS NULL) + AND (a.ageAtTime.AgeAtTimeYearsRounded < lf.maxAge OR lf.maxAge IS NULL) + AND lf.active = true ) + + + --adds the reasearch owned animal exemption -Left JOIN study.flags fl on +LEFT JOIN study.flags fl on (a.id = fl.id and fl.flag.code = 4034 and (a.date >= fl.date and a.date <=COALESCE(fl.enddate,Now()) )) + WHERE CAST(a.datefinalized AS DATE) >= CAST(STARTDATE as DATE) AND CAST(a.datefinalized AS DATE) <= CAST(ENDDATE as DATE) AND a.qcstate.publicdata = true --and a.participantID.demographics.species.common not in ('Rabbit','Guinea Pigs') @@ -78,6 +165,7 @@ SELECT a.assignCondition, a.releaseType, a.ageAtTime.AgeAtTimeYearsRounded as ageAtTime, + ' ' as ESPFAnimal, 'Lease Setup Fees' as category, (SELECT rowid FROM onprc_billing_public.chargeableItems ci WHERE ci.active = true AND ci.name = javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.LEASE_SETUP_FEES')) as chargeId, 1 as quantity, @@ -94,7 +182,7 @@ FROM study.assignment a WHERE CAST(a.datefinalized AS DATE) >= CAST(STARTDATE as DATE) AND CAST(a.datefinalized AS DATE) <= CAST(ENDDATE as DATE) AND a.qcstate.publicdata = true --only charge setup fee for leases >24H. note: duration assumes today as end, so exclude null enddates -AND (a.duration > CAST(javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.DAY_LEASE_MAX_DURATION') as INTEGER) OR a.assignCondition != a.releaseCondition OR a.enddate IS NULL) +AND ((a.duration > CAST(javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.DAY_LEASE_MAX_DURATION') as INTEGER)) OR ( a.assignCondition != a.releaseCondition AND a.enddate IS NULL)) and a.id.demographics.species Not IN ('Rabbit','Guinea Pigs') --add released animals that need adjustments @@ -102,7 +190,11 @@ UNION ALL SELECT a.id, -a.enddate as date, --use enddate as the transaction date for this charge +case + When a.enddate < a.dateFinalized then a.dateFinalized + Else a.enddate + End as date, +--a.date, a.project, a.date as assignmentStart, a.enddate, @@ -111,7 +203,9 @@ a.releaseCondition, a.assignCondition, a.releaseType, a.ageAtTime.AgeAtTimeYearsRounded as ageAtTime, +a5.id as ESPFAnimal, 'Lease Fees' as category, +--////This selectes the charge ID to be used (SELECT max(rowid) as rowid FROM onprc_billing_public.chargeableItems ci WHERE ci.name = javaConstant('org.labkey.onprc_billing.ONPRC_BillingManager.LEASE_FEE_ADJUSTMENT') and ci.active = true) as chargeId, CASE when (fl.id Is Not Null) then 0 @@ -147,16 +241,21 @@ LEFT JOIN onprc_billing.leaseFeeDefinition lf2 AND a2.dateOnly <= a.dateOnly AND a2.endDateCoalesced >= a.dateOnly AND a2.project.name = javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.TMB_PROJECT') - - ) +LEFT join assignment_U42ESPF a5 on + ( a.id = a5.id and a.project !=a5.project + and a5.project = 1107 + and a5.dateonly <=a.dateOnly + AND a5.endDateCoalesced >= a.dateOnly) + --adds the reasearch owned animal exemption -Left JOIN study.flags fl on +LEFT JOIN study.flags fl on (a.id = fl.id and fl.flag.code = 4034 and (a.date >= fl.date and a.date <=COALESCE(fl.enddate,Now()) )) WHERE a.releaseCondition != a.projectedReleaseCondition +and (A.id != A5.id or A5.id is Null) AND a.enddatefinalized is not null AND CAST(a.enddatefinalized AS DATE) >= CAST(STARTDATE AS DATE) AND CAST(a.enddatefinalized AS DATE) <= CAST(EndDate as DATE) AND a.qcstate.publicdata = true AND lf.active = true -AND a2.id IS NULL and a.participantID not like '[a-z]%' \ No newline at end of file +AND a2.id IS NULL and a.participantID not like '[a-z]%' diff --git a/onprc_billing/resources/queries/onprc_billing/lease_ObeseInfant_HFDDam.sql b/onprc_billing/resources/queries/onprc_billing/lease_ObeseInfant_HFDDam.sql new file mode 100644 index 000000000..d5f9497f9 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/lease_ObeseInfant_HFDDam.sql @@ -0,0 +1,9 @@ +SELECT b.Id, +b.date, +b.date_type, +b.birth_condition, +b.room, +b.cage, +b.dam + +FROM study.birth b join study.flags s on b.dam = s.id and s.flag.value = 'JMac Obese HFD' and s.enddate is null \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/lease_dayLeaseAdult.sql b/onprc_billing/resources/queries/onprc_billing/lease_dayLeaseAdult.sql new file mode 100644 index 000000000..3ac4a55ae --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/lease_dayLeaseAdult.sql @@ -0,0 +1,19 @@ +Select +a.id, +a.date, +a.enddate, +a.projectedrelease, +a.assigncondition, +a.projectedReleaseCondition, +TimeStampDiff('SQL_TSI_Day',a.date,a.projectedRelease) as LengthofLEase, +Case + When a.assigncondition = a.projectedReleaseCondition then 'No' + When a.assigncondition != a.projectedReleaseCondition then 'Yes' + +End as DayLeaseConditionChange + + +from study.assignment a +--where a.projectedRelease is not null +where (a.projectedRelease is not null and a.projectedRelease > a.date) +--and TimeStampDiff('SQL_TSI_Day',a.date,a.projectedRelease)<=15 \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/leasefee_rateChargeItem.sql b/onprc_billing/resources/queries/onprc_billing/leasefee_rateChargeItem.sql new file mode 100644 index 000000000..19b297855 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/leasefee_rateChargeItem.sql @@ -0,0 +1,34 @@ +--20200113 Updated to look up active alias at time of assignment - Critical when dealing with Historic assignments +SELECT d.id, +d.CenterProject, +d.ProjectID, +d.alias as CurrentAlias, +h.account as AliasAtTime, +h.account.aliastype.removeSubsidy as RemoveSubsidy, +d.leasetype, +d.assignmentdate, +d.code, +d.ProjectedReleaseCode, +d.AssignmentAge, +d.chargeId, +r.chargeId.activeRate.subsidy, +r.chargeID.name as ChargeItem, +r.unitCost , +p.multiplier, +e.UnitCost as ExemptionRate, +d.RevisedChargeID, +r1.chargeID.Name AS RevisedItem, +r1.chargeID.activeRate.subsidy as RevisedSubsidy, +r1.unitCost as RevisedUnitCost, +d.quantity +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.leasefee_rateData d + --Join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.Leasefee_leaseType t on d.id = t.id + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.chargeRates r on d.chargeID = r.chargeID + and (d.assignmentdate >= r.startDate and d.assignmentdate <= r.enddate) + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.chargeRates r1 on d.RevisedchargeID = r1.chargeID and (d.assignmentdate >= r1.startDate and d.assignmentdate <= r1.enddate) + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.projectAccountHistory h on h.project = d.projectID and (d.assignmentdate >= h.startDate and d.assignmentDate <= h.enddate) +--add query for exemption item + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.chargeRateExemptions e on e.chargeID = d.chargeID and e.project = d.projectID + and (d.assignmentdate >= e.startDate and d.assignmentDate <= e.enddate) +--add project multipler + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.ProjectMultipliers p on p.account = h.account and (d.assignmentDate >= p.startDate and d.assignmentdate <= p.enddate) \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/leasefee_rateData.sql b/onprc_billing/resources/queries/onprc_billing/leasefee_rateData.sql new file mode 100644 index 000000000..f3422d8b6 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/leasefee_rateData.sql @@ -0,0 +1,52 @@ +SELECT l.id, +l.project.name as CenterProject, +l.project.project as ProjectID, +l.alias, +l.leasetype, +l.assignmentdate, +l.assignCondition.code, + +l.projectedReleaseCondition.code as ProjectedReleaseCode, +Cast(l.ageAtAssignment as Integer) as AssignmentAge, +Case + + when (l.leasetype = 'U42 Expanded SPF Lease' and l.daylease <> 'yes') then 5348 + When (l.leaseType = 'Obese 0622-01 Day Lease' and l.leasetype = lf.chargeID.name) then 5367 + When (l.leaseType = 'Obese JMac Control Infant' and l.daylease <> 'yes' and l.leasetype = lf.chargeID.name) then 5372 + When (l.leaseType = 'Obese JMac WSD Infant' and l.daylease <> 'yes' and l.leasetype = lf.chargeID.name) then 5371 + When (l.leaseType = 'OBESE Adult Male Lease' and l.daylease <> 'yes' and l.leasetype = lf.chargeID.name) then 5368 + When (l.leaseType = 'OBESE Adult Terminal Leasel' and l.daylease <> 'yes' and l.leasetype = lf.chargeID.name) then 5369 + When (l.leaseType = 'OBESE Adult Day Lease' and l.leasetype = lf.chargeID.name) then 5367 + When (l.leaseType = 'Day Lease Research Assignment P51 NHP Condition Change' and l.leasetype = lf.chargeID.name) then 9999 + When (l.leaseType = 'Day Lease Research Assignment P51 NHP NC' ) then 90 + When (l.leaseType = 'DualAssignedESPF' and l.daylease <> 'yes' and l.leasetype = lf.chargeID.name) then null + when (l.leasetype = 'Animal Lease Fee - TMB') and l.daylease <> 'yes' then 1552 + + When (l.leaseType = 'TMB Adult Day Lease' and l.leasetype = lf.chargeID.name) then 90 + When (l.leaseType = 'TMB No Charge' and l.leasetype = lf.chargeID.name) then Null + When (l.leaseType = 'TMB Full P 51 Rate Lease' and l.leasetype = lf.chargeID.name) then + (Select lf1.ChargeID from Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeDefinition lf1 + where lf1.assignCondition = l.assignCondition + AND lf1.releaseCondition = l.projectedReleaseCondition + AND (l.ageAtAssignment >= lf1.minAge OR lf1.minAge IS NULL) + AND (l.ageAtAssignment < lf1.maxAge OR lf1.maxAge IS NULL) + AND lf1.active = true) + when (l.leasetype like 'Research Assignment P51 %' and l.daylease <> 'yes') then + (Select lf2.ChargeID from Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeDefinition lf2 + where lf2.assignCondition = l.assignCondition + AND lf2.releaseCondition = l.projectedReleaseCondition + AND (l.ageAtAssignment >= lf2.minAge OR lf2.minAge IS NULL) + AND (l.ageAtAssignment < lf2.maxAge OR lf2.maxAge IS NULL) + AND lf2.active = true) + + + When (l.leaseType = 'Born to Resource Dam' ) then Null + Else Null + End as chargeID, +--lf.chargeId, +Null as RevisedChargeID, + +1 as quantity + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.leaseFee_LeaseType l left outer join + Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing.leaseFeeDefinition lf on l.leaseType = lf.chargeID.name \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/leasefee_rateFunction.sql b/onprc_billing/resources/queries/onprc_billing/leasefee_rateFunction.sql new file mode 100644 index 000000000..af90ffd4b --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/leasefee_rateFunction.sql @@ -0,0 +1,29 @@ +--PARAMETERS(A VARCHAR DEFAULT '9012221',P double DEFAULT 277, +-- c DOUBLE DEFAULT 1477, +-- s TIMESTAMP DEFAULT '1/1/2019', +-- B DOUBLE +-- ) +--2019-11-22 clean up of code onn function had a bad date select +Select +c.id, +c.CenterProject, +c.alias, +c.alias as ChargeTO, +t.creditTo, +c.projectID, +c.chargeId, +t.leasetype, +r.unitcost, +c.assignmentDate, +t.faRate, +t.removesubsidy, +t.canRaiseFA, + +RateCalc(c.alias,c.chargeID,c.projectID,c.assignmentDate,t.farate) as CalculatedRate + +FROM Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.leasefee_RateData c + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.chargeRates r + on c.chargeID = r.chargeID + left join Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_Billing.leasefee_leaseType t + on (c.id = t.id and c.projectID = t.projectID and t.assignmentDate = c.assignmentDate) +where r.startDate <= c.assignmentDate and r.enddate >= c.assignmentDate \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/miscCharges.js b/onprc_billing/resources/queries/onprc_billing/miscCharges.js index 167f8f3d0..9835b5071 100644 --- a/onprc_billing/resources/queries/onprc_billing/miscCharges.js +++ b/onprc_billing/resources/queries/onprc_billing/miscCharges.js @@ -32,20 +32,19 @@ EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Even } if (row.debitedaccount){ - row.debitedaccount = row.debitedaccount.replace(/^\s+|\s+$/g, '') + row.debitedaccount = row.debitedaccount.replace(/^\s+|\s+$/g, ''); } - if (row.creditedaccount){ - row.creditedaccount = row.creditedaccount.replace(/^\s+|\s+$/g, '') + if (row.creditedaccount) { + row.creditedaccount = row.creditedaccount.replace(/^\s+|\s+$/g, ''); } - if (row.chargeId){ - if (!row.chargeCategory && row.unitcost){ - if (!billingHelper.supportsCustomUnitCost(row.chargeId)) - { - EHR.Server.Utils.addError(scriptErrors, 'unitCost', 'This type of charge does not support a custom unit cost. You should leave this blank and it will be automatically calculated.', 'WARN'); - } - } + // if (!row.chargeCategory && row.unitcost){ + // if (!billingHelper.supportsCustomUnitCost(row.chargeId)) + // { + // EHR.Server.Utils.addError(scriptErrors, 'unitCost', 'This type of charge does not support a custom unit cost. You should leave this blank and it will be automatically calculated.', 'WARN'); + // } + // } if (!row.Id){ if (!billingHelper.supportsBlankAnimal(row.chargeId)) diff --git a/onprc_billing/resources/queries/onprc_billing/miscChargesFeeRates.query.xml b/onprc_billing/resources/queries/onprc_billing/miscChargesFeeRates.query.xml index 0e1f63588..ca62f577f 100644 --- a/onprc_billing/resources/queries/onprc_billing/miscChargesFeeRates.query.xml +++ b/onprc_billing/resources/queries/onprc_billing/miscChargesFeeRates.query.xml @@ -29,12 +29,6 @@ true - - true - - - true - true @@ -60,4 +54,4 @@ - \ No newline at end of file + diff --git a/onprc_billing/resources/queries/onprc_billing/miscChargesFees.sql b/onprc_billing/resources/queries/onprc_billing/miscChargesFees.sql index 1de149355..feac4d44d 100644 --- a/onprc_billing/resources/queries/onprc_billing/miscChargesFees.sql +++ b/onprc_billing/resources/queries/onprc_billing/miscChargesFees.sql @@ -4,6 +4,12 @@ * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 */ +/* + * Copyright (c) 2013 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + SELECT mc.Id, mc.date, @@ -12,7 +18,30 @@ SELECT mc.chargeId, mc.item, mc.quantity, - mc.unitCost, + round(CAST(CASE + --order of priority for unit cost: + --project-level exemption: pay this value + WHEN (e.unitCost IS NOT NULL) THEN e.unitCost + --project-level multiplier: multiply NIH rate by this value + WHEN (pm.multiplier IS NOT NULL AND cr.unitCost IS NOT NULL) THEN (cr.unitCost * pm.multiplier) + --if there is not a known rate, we dont know what do to + WHEN (cr.unitCost IS NULL) THEN null + --for non-OGA aliases, we always use the NIH rate + WHEN (alias.category IS NOT NULL AND alias.category != 'OGA') THEN cr.unitCost + --if we dont know the aliasType, we also dont know what do to + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND mc.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN + ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate)))) ELSE 1 END)) + + --remove subsidy only + WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) + + --raise F&A only + --WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND mc.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND mc.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)))/(1+ alias.faRate)) ELSE 1 END)) + --the NIH rate + ELSE cr.unitCost + END AS DOUBLE), 2) as unitCost, + --mc.unitCost, mc.category, mc.chargeCategory, mc.invoicedItemId, @@ -23,5 +52,40 @@ SELECT mc.sourceInvoicedItem, mc.invoiceId, mc.taskid, + mc.chargeType as chargeUnit + +FROM onprc_billing.miscCharges mc + +LEFT JOIN onprc_billing_public.chargeRates cr ON ( + CAST(mc.date AS DATE) >= CAST(cr.startDate AS DATE) AND + (CAST(mc.date AS DATE) <= cr.enddateCoalesced OR cr.enddate IS NULL) AND + mc.chargeId = cr.chargeId +) + + LEFT JOIN onprc_billing_public.chargeRateExemptions e ON ( + CAST(mc.date AS DATE) >= CAST(e.startDate AS DATE) AND + (CAST(mc.date AS DATE) <= e.enddateCoalesced OR e.enddate IS NULL) AND + mc.chargeId = e.chargeId AND + mc.project = e.project +) + +LEFT JOIN onprc_billing_public.creditAccount ce ON ( + CAST(mc.date AS DATE) >= CAST(ce.startDate AS DATE) AND + (CAST(mc.date AS DATE) <= ce.enddateCoalesced OR ce.enddate IS NULL) AND + mc.chargeId = ce.chargeId +) + +LEFT JOIN onprc_billing_public.projectAccountHistory aliasAtTime ON ( + aliasAtTime.project = mc.project AND + aliasAtTime.startDate <= cast(mc.date as date) AND + aliasAtTime.endDate >= cast(mc.date as date) +) + +LEFT JOIN onprc_billing_public.aliases alias ON ( + aliasAtTime.account = alias.alias and alias.datedisabled is null +) -FROM onprc_billing.miscCharges mc \ No newline at end of file +LEFT JOIN onprc_billing_public.projectMultipliers pm ON ( + CAST(mc.date AS DATE) >= CASt(pm.startDate AS DATE) AND + (CAST(mc.date AS DATE) <= pm.enddateCoalesced OR pm.enddate IS NULL) AND + alias.alias = pm.account) \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/miscChargesNotBilled_Virology.query.xml b/onprc_billing/resources/queries/onprc_billing/miscChargesNotBilled_Virology.query.xml new file mode 100644 index 000000000..201c282a0 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/miscChargesNotBilled_Virology.query.xml @@ -0,0 +1,123 @@ + + + + + Manually Entered Charges + + + + + ehr + project + project + + + + Alias + + onprc_billing_public + aliases + alias + + /query/executeQuery.view?schemaName=onprc_billing_public&query.queryName=aliases&query.alias~eq=${account} + + + Investigator + true + + onprc_ehr + investigators + rowid + lastName + + + + + ehr + tasks + taskid + rowid + + + + Charge + + onprc_billing_public + chargeableItems + rowid + + + + Is Rate Exemption? + + + Unit Cost + $###,##0.00 + + + Total Cost + $###,##0.00 + + + Credit Alias + + + true + + + Assigned To Project On This Date? + + + Lacks Unit Cost? + + + Rate Id + /query/executeQuery.view?schemaName=onprc_billing&query.queryName=chargeRates&query.rowid~eq=${rateid} + + + Exemption Id + /query/executeQuery.view?schemaName=onprc_billing&query.queryName=chargeRateExemptions&query.rowid~eq=${exemptionId} + + + true + + + true + + + true + true + + + Missing Alias? + + + Missing FAID? + + + Expired Alias? + + + Alias Accepting Charges? + + + Is Adjustment/Reversal? + + + true + + + Alias Differs From Project? + + + >45 Days Old? + + + Is Manually Entered? + true + + +
+
+
+
\ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/miscChargesWithRates.sql b/onprc_billing/resources/queries/onprc_billing/miscChargesWithRates.sql index f8813240b..ffe18c7fd 100644 --- a/onprc_billing/resources/queries/onprc_billing/miscChargesWithRates.sql +++ b/onprc_billing/resources/queries/onprc_billing/miscChargesWithRates.sql @@ -1,11 +1,4 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - */ - --- NOTE: this query provides the raw data used in most of billing *Rates.sql queries. The goal is to have a single implementation of the --- process to assign rates and accounts to the raw charges. +--Udpate 20200107 using fiull path for source SELECT p.Id, p.date, @@ -16,9 +9,21 @@ SELECT p.chargeId, COALESCE(p.chargetype.servicecenter, p.chargeId.departmentCode) as serviceCenter, coalesce(p.chargeId.name, p.item) as item, + p.unitCost as MCEnteredUnitCost, + case + WHen p.unitCost is NOT NULL then p.unitCost + When RateCalc(p.debitedaccount,p.chargeID,p.project,p.Date,alias.farate) Is Not Null then RateCalc(p.debitedaccount,p.chargeID,p.project,p.Date,alias.farate) + Else cr.unitcost + ENd as RateCalc, + case + WHen p.unitCost is NOT NULL then 'Misc Rate Entered' + When RateCalc(p.debitedaccount,p.chargeID,p.project,p.Date,alias.farate) Is Not Null then 'Rate Calc Function' + else 'Passed Thru to Cr UnitCost' + ENd as RateMethod, round(CAST(CASE --order of priority for unit cost: --if this row specifies a unit cost, like an adjustment, defer to that. this is unique to miscCharges + --this occurs when the rate is a vairable rate or a reversal where an negative number is entered WHEN (p.unitCost IS NOT NULL) THEN p.unitCost --project-level exemption: pay this value WHEN (e.unitCost IS NOT NULL) THEN e.unitCost @@ -30,12 +35,12 @@ SELECT WHEN (alias.category IS NOT NULL AND alias.category != 'OGA') THEN cr.unitCost --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null - --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + --remove both subsidy and raise F&A if needed + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate)))) ELSE 1 END)) --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) - --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + --raise F&A on ly + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)))/(1+ alias.faRate)) ELSE 1 END)) --the NIH rate ELSE cr.unitCost END AS DOUBLE), 2) as unitCost, @@ -87,7 +92,7 @@ SELECT WHEN (p.project IS NULL AND p.debitedaccount IS NOT NULL) THEN null --note: allow charges entered by account only WHEN p.project IS NULL THEN 'N' WHEN p.project.alwaysavailable = true THEN null - WHEN (SELECT count(*) as projects FROM study.assignment a WHERE + WHEN (SELECT count(*) as projects FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a WHERE p.Id = a.Id AND (p.project = a.project OR p.project.protocol = a.project.protocol) AND (cast(p.date AS DATE) <= a.enddateCoalesced OR a.enddate IS NULL) AND @@ -95,7 +100,7 @@ SELECT ) > 0 THEN null ELSE 'N' END as matchesProject, - (SELECT group_concat(distinct a.project.displayName, chr(10)) as projects FROM study.assignment a WHERE + (SELECT group_concat(distinct a.project.displayName, chr(10)) as projects FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a WHERE p.Id = a.Id AND (cast(p.date AS DATE) <= a.enddateCoalesced OR a.enddate IS NULL) AND cast(p.date as date) >= a.dateOnly @@ -124,44 +129,44 @@ SELECT END as accountDiffersFromProject, true as isMiscCharge -FROM onprc_billing.miscCharges p +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_billing.miscCharges p -LEFT JOIN onprc_billing_public.chargeRates cr ON ( +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.chargeRates cr ON ( CAST(p.date AS DATE) >= CAST(cr.startDate AS DATE) AND (CAST(p.date AS DATE) <= cr.enddateCoalesced OR cr.enddate IS NULL) AND p.chargeId = cr.chargeId ) -LEFT JOIN onprc_billing_public.chargeRateExemptions e ON ( +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.chargeRateExemptions e ON ( CAST(p.date AS DATE) >= CAST(e.startDate AS DATE) AND (CAST(p.date AS DATE) <= e.enddateCoalesced OR e.enddate IS NULL) AND p.chargeId = e.chargeId AND p.project = e.project ) -LEFT JOIN onprc_billing_public.creditAccount ce ON ( +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.creditAccount ce ON ( CAST(p.date AS DATE) >= CAST(ce.startDate AS DATE) AND (CAST(p.date AS DATE) <= ce.enddateCoalesced OR ce.enddate IS NULL) AND p.chargeId = ce.chargeId ) -LEFT JOIN onprc_billing_public.projectAccountHistory aliasAtTime ON ( +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.projectAccountHistory aliasAtTime ON ( aliasAtTime.project = p.project AND aliasAtTime.startDate <= cast(p.date as date) AND aliasAtTime.endDate >= cast(p.date as date) ) -LEFT JOIN onprc_billing_public.aliases alias ON ( - alias.alias = COALESCE(p.debitedaccount, aliasAtTime.account) +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.aliases alias ON ( + alias.alias = COALESCE(p.debitedaccount, aliasAtTime.account) and alias.dateDisabled is Null ) -LEFT JOIN onprc_billing_public.projectMultipliers pm ON ( +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.projectMultipliers pm ON ( CAST(p.date AS DATE) >= CASt(pm.startDate AS DATE) AND (CAST(p.date AS DATE) <= pm.enddateCoalesced OR pm.enddate IS NULL) AND alias.alias = pm.account ) -LEFT JOIN onprc_billing_public.chargeUnitAccounts cu ON ( +LEFT JOIN Site.{substitutePath moduleProperty('onprc_billing','BillingContainer')}.onprc_billing_public.chargeUnitAccounts cu ON ( p.chargetype = cu.chargetype AND cast(cu.startDate AS date) <= cast(p.date as date) AND cast(cu.endDate AS date) >= cast(p.date as date) diff --git a/onprc_billing/resources/queries/onprc_billing/perDiemFeeDefinition.query.xml b/onprc_billing/resources/queries/onprc_billing/perDiemFeeDefinition.query.xml new file mode 100644 index 000000000..d7d9cc932 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/perDiemFeeDefinition.query.xml @@ -0,0 +1,34 @@ + + + + + Per Diem Fee Definition + + + + + + + /onprc/ehr + ehr_lookups + housingTypes + rowID + + + + + /onprc/ehr + ehr_lookups + housingDefinition + rowID + + + + + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/perDiemRates.sql b/onprc_billing/resources/queries/onprc_billing/perDiemRates.sql index a49212cab..d7a74ce5a 100644 --- a/onprc_billing/resources/queries/onprc_billing/perDiemRates.sql +++ b/onprc_billing/resources/queries/onprc_billing/perDiemRates.sql @@ -47,12 +47,16 @@ SELECT --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN + ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate)))) ELSE 1 END)) + --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) + --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) - --the NIH rate + --WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)))/(1+ alias.faRate)) ELSE 1 END)) + --the NIH rate ELSE cr.unitCost END AS DOUBLE), 2) as unitCost, cr.unitCost as nihRate, diff --git a/onprc_billing/resources/queries/onprc_billing/procedureFeeDefinition.js b/onprc_billing/resources/queries/onprc_billing/procedureFeeDefinition.js index 24f61da7d..68f8a9792 100644 --- a/onprc_billing/resources/queries/onprc_billing/procedureFeeDefinition.js +++ b/onprc_billing/resources/queries/onprc_billing/procedureFeeDefinition.js @@ -16,8 +16,8 @@ EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Even if (row.assistingstaff && row.procedureid && !onprcTriggerHelper.requiresAssistingStaff(row.procedureid)){ EHR.Server.Utils.addError(scriptErrors, 'assistingstaff', 'Only surgeries support assisting staff.', 'ERROR'); } - - if (row.chargetype != 'Research Staff' && row.assistingstaff){ + //Modified: 6-9-2020 R. Blasa to allow to process Infectious Disease Resource as Charge unit + if (row.chargetype != 'Research Staff' && row.assistingstaff && row.assistingstaff != 'DCM: Surgery Services'){ EHR.Server.Utils.addError(scriptErrors, 'assistingstaff', 'This field will be ignored unless Research Staff is selected, and should be blank.', 'ERROR'); } }); diff --git a/onprc_billing/resources/queries/onprc_billing/procedureFeeRates.sql b/onprc_billing/resources/queries/onprc_billing/procedureFeeRates.sql index 41fe00395..6611b4d9b 100644 --- a/onprc_billing/resources/queries/onprc_billing/procedureFeeRates.sql +++ b/onprc_billing/resources/queries/onprc_billing/procedureFeeRates.sql @@ -41,12 +41,16 @@ SELECT --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN + ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate)))) ELSE 1 END)) + --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) + --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) - --the NIH rate + --WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)))/(1+ alias.faRate)) ELSE 1 END)) + --the NIH rate ELSE cr.unitCost END AS DOUBLE), 2) as unitCost, cr.unitCost as nihRate, @@ -204,4 +208,4 @@ SELECT FROM onprc_billing.miscChargesFeeRateData mc WHERE cast(mc.billingDate as date) >= CAST(StartDate as date) AND cast(mc.billingDate as date) <= CAST(EndDate as date) -AND mc.category IN ('Surgical Procedure', 'Clinical Procedure', 'Surgery', 'Pathology') +AND mc.category IN ('Surgical Procedure', 'Clinical Procedure', 'Surgery', 'Pathology') \ No newline at end of file diff --git a/onprc_billing/resources/queries/onprc_billing/procedureFees.sql b/onprc_billing/resources/queries/onprc_billing/procedureFees.sql index 3283a90a9..6d07f32a9 100644 --- a/onprc_billing/resources/queries/onprc_billing/procedureFees.sql +++ b/onprc_billing/resources/queries/onprc_billing/procedureFees.sql @@ -19,7 +19,6 @@ SELECT p.chargeId, e.objectid as sourceRecord, e.taskid - FROM study.encounters e JOIN onprc_billing.procedureFeeDefinition p ON ( p.procedureId = e.procedureId and @@ -48,6 +47,7 @@ SELECT max(e.objectid) as sourceRecord, e.taskid + FROM study.blood e WHERE CAST(e.datefinalized as date) >= CAST(StartDate as date) AND CAST(e.datefinalized as date) <= CAST(EndDate as date) and e.chargetype != 'No Charge' and e.chargetype != 'Research Staff' @@ -123,7 +123,6 @@ max(e.objectid) as sourceRecord, e.taskid - FROM study.drug e --join "/ONPRC/EHR".onprc_billing.medicationFeeDefinition mfd ON mfd.code = e.code .code left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr_lookups.snomed_combo_list s on s.code = e.code.code diff --git a/onprc_billing/resources/queries/onprc_billing/slaPerDiemRates.sql b/onprc_billing/resources/queries/onprc_billing/slaPerDiemRates.sql index e20ffb0bf..ae22b9ffc 100644 --- a/onprc_billing/resources/queries/onprc_billing/slaPerDiemRates.sql +++ b/onprc_billing/resources/queries/onprc_billing/slaPerDiemRates.sql @@ -40,13 +40,17 @@ SELECT WHEN (alias.category IS NOT NULL AND alias.category != 'OGA') THEN cr.unitCost --if we dont know the aliasType, we also dont know what do to WHEN (alias.aliasType.aliasType IS NULL) THEN null - --remove both subsidy and raise F&A if needed - WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + --remove both subsidy and raise F&A if needed------- Changed by Kollil on 5/19/17 + WHEN (alias.aliasType.removeSubsidy = true AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN ((cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN + ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) / (1 + alias.faRate)))) ELSE 1 END)) + --remove subsidy only WHEN (alias.aliasType.removeSubsidy = true AND alias.aliasType.canRaiseFA = false) THEN (cr.unitCost / (1 - COALESCE(cr.subsidy, 0))) + --raise F&A only - WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) - --the NIH rate + --WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN (1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE) - alias.faRate)) ELSE 1 END)) + WHEN (alias.aliasType.removeSubsidy = false AND (alias.aliasType.canRaiseFA = true AND p.chargeId.canRaiseFA = true)) THEN (cr.unitCost * (CASE WHEN (alias.faRate IS NOT NULL AND alias.faRate < CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)) THEN ((1 + (CAST(javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.BASE_SUBSIDY') AS DOUBLE)))/(1+ alias.faRate)) ELSE 1 END)) + --the NIH rate ELSE cr.unitCost END AS DOUBLE), 2) as unitCost, cr.unitCost as nihRate, @@ -55,7 +59,7 @@ SELECT cast(ce.account as varchar(200)) as creditAccount, ce.rowid as creditAccountId, - coalesce(alias.investigatorId, p.project.investigatorId) as investigatorId, + alias.investigatorId as investigatorId, CASE WHEN e.unitCost IS NOT NULL THEN 'Y' WHEN pm.multiplier IS NOT NULL THEN ('Multiplier: ' || CAST(pm.multiplier AS varchar(100))) @@ -93,7 +97,7 @@ SELECT ELSE null END as isExpiredAccount, CASE WHEN (TIMESTAMPDIFF('SQL_TSI_DAY', p.date, curdate()) > 45) THEN 'Y' ELSE null END as isOldCharge, - p.project.account as currentActiveAlias + p.project as currentActiveAlias FROM onprc_billing.slaPerDiems p diff --git a/onprc_billing/resources/queries/onprc_billing/virologyAliases.sql b/onprc_billing/resources/queries/onprc_billing/virologyAliases.sql new file mode 100644 index 000000000..ccb76df21 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/virologyAliases.sql @@ -0,0 +1,9 @@ +SELECT alias, alias + ' - ' + COALESCE(investigatorName, 'N/A') as aliasPI +FROM Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer_Public')}.onprc_billing_public.aliases +--WHERE a.projectStatus in ('Active', 'Partial Setup', 'No Cost Ext', 'Preaward') OR a.alias in ('68119000', '46050050') +--WHERE (budgetstartdate IS NOT NULL AND (budgetEndDate IS NULL OR budgetEndDate > now() )) OR alias in ('68119000', '46050050','46030010', '61247550') +--Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')} +--WHERE (budgetstartdate IS NOT NULL AND (budgetEndDate IS NULL OR budgetEndDate >= now() )) +-- including the aliases that expired 30 days ago from today's date. This provision is given to the PIs to enter the previous month charges. By Kolli on 7/6/19 +WHERE (budgetstartdate IS NOT NULL AND (budgetEndDate IS NULL OR budgetEndDate >= TIMESTAMPADD('SQL_TSI_DAY', -30, now()) )) +OR alias in (Select alias from lists.Special_Aliases Where category like 'Virology') diff --git a/onprc_billing/resources/queries/onprc_billing/virologyBillingCharges.sql b/onprc_billing/resources/queries/onprc_billing/virologyBillingCharges.sql new file mode 100644 index 000000000..cf2d9fba9 --- /dev/null +++ b/onprc_billing/resources/queries/onprc_billing/virologyBillingCharges.sql @@ -0,0 +1,4 @@ +SELECT rowid, category, activeRate.unitCost, itemCode + ' - ' + name as chargeName +FROM Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer_Public')}.onprc_billing_public.chargeableItems +WHERE category = 'Virology' +AND Active = 'true' \ No newline at end of file diff --git a/onprc_billing/resources/queries/virologyAliases.sql b/onprc_billing/resources/queries/virologyAliases.sql new file mode 100644 index 000000000..f8ec6e8ea --- /dev/null +++ b/onprc_billing/resources/queries/virologyAliases.sql @@ -0,0 +1,3 @@ +SELECT rowid,aliases.alias, aliases.alias + ' - ' + aliases.investigatorName as aliasPI +FROM aliases +WHERE projectStatus = 'Active' \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/oga_AliasCleanup2020.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/oga_AliasCleanup2020.sql new file mode 100644 index 000000000..092c240ff --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/oga_AliasCleanup2020.sql @@ -0,0 +1,76 @@ +-- This script will never run as part of an upgrade, but is being archived here + + +/****** Object: StoredProcedure [onprc_billing].[oga_AliasCleanupNew] Script Date: 1/29/2020 7:13:37 AM ******/ +CREATE PROCEDURE [onprc_billing].[oga_AliasCleanup] + + AS + BEGIN + +--This update will be used to enter date disabled for all aliases used in Invoiced Items +--This update will be used to enter date disabled for all aliases used in Invoiced Items +Update onprc_billing.aliases + Set COMMENTS = 'Found In PRoject Account History',dateDisabled = GetDate(), aliasEnabled = 'n' +Where alias in (Select Distinct Alias + + +from onprc_billing.aliases a left outer join onprc_billing.projectAccountHistory p + on a.alias = p.account + where p.account is not null and p.enddate < getDate() + and a.category != 'OHSU GL' ) --and a.projectStatus != 'Active') + + +--This update will be used to enter date disabled for all aliases used in Invoiced Items +Update onprc_billing.aliases + Set COMMENTS = 'Found In INvoiced ITem',dateDisabled = GetDate(), aliasEnabled = 'n' +Where alias in (Select Distinct Alias + + +from onprc_billing.aliases a left outer join onprc_billing.invoicedItems i + on a.alias = i.debitedaccount + where i.debitedaccount is not null + and a.category != 'OHSU GL')--and a.projectStatus != 'Active') + + +/* + + --Handles active non OGA Aliases + Update a + Set a.projectStatus = 'Active',a.comments = 'In Use - Non ONPRC Alias', a.category = 'OHSU GL' + +--Select a.Alias,p.account -- update the category to + from onprc_billing.aliases a join onprc_billing.projectAccountHistory p on p.account = a.alias + where p.enddate > = GetDate() and a.alias Not Like '9%' + +--handle inactive GL Aliases in the Dataset + Update gl + set gl.projectStatus = 'Non Active GL', gl.aliasEnabled = 'n', gl.datedisabled = GetDate(), gl.comments = 'GL Alias Not Active entered Previously' + +--Select gl.* + from onprc_billing.aliases gl left outer join onprc_billing.projectAccountHistory p on p.account = gl.alias + where gl.alias not like '9%' and (gl.comments != 'In Use - Non ONPRC Alias' or gl.comments is null) + +--Handles Expired Aliases by setting Date Disabled + Update a1 + Set a1.dateDisabled = GetDate(), comments = 'Expired Alias' +--select a1.alias,a1.budgetEndDate + from onprc_billing.aliases a1 + where a1.budgetEndDate <=GetDate() + + Update a4 + set dateDisabled = GetDate(), comments = 'Grant Closed', projectStatus = 'Grant Closed' +--Select a4.alias,s.[PROJECT STATUS],a4.projectStatus + from onprc_billing.aliases a4 left Outer join onprc_billing.ogaSynch s on Cast(a4.alias as varchar(50)) = Cast(s.[alias] as VarChar(50)) + where a4.dateDisabled is null and a4.projectstatus in ('Archived','Closed','IM PURGEd') + +--Update the existing data to add PPQ, ORG PPQ Date to Existing Aliases + + Update a10 + Set organization = s.ORG, a10.PPQCode = s.[PPQ CODE], a10.PPQDate = s.[PPQ DATE] + + + from onprc_billing.aliases a10 left Outer join onprc_billing.ogaSynch s on Cast(a10.alias as varchar(50)) = Cast(s.[alias] as VarChar(50)) + where a10.Organization is null +*/ + + END diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-0.00-12.372.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-0.00-12.372.sql new file mode 100644 index 000000000..cc8c1ab83 --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-0.00-12.372.sql @@ -0,0 +1,944 @@ +/* + * Copyright (c) 2012 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +CREATE SCHEMA onprc_billing; +GO +; + +--this table contains one row each time a billing run is performed, which gleans items to be charged from a variety of sources +--and snapshots them into invoicedItems +CREATE TABLE onprc_billing.invoiceRuns ( + rowId INT IDENTITY (1,1) NOT NULL, + date DATETIME, + dataSources varchar(1000), + runBy userid, + comment varchar(4000), + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_invoiceRuns PRIMARY KEY (rowId) +); + +--this table contains a snapshot of items actually invoiced, which will draw from many places in the animal record +CREATE TABLE onprc_billing.invoicedItems ( + rowId INT IDENTITY (1,1) NOT NULL, + id varchar(100), + date DATETIME, + debitedaccount varchar(100), + creditedaccount varchar(100), + category varchar(100), + item varchar(500), + quantity double precision, + unitcost double precision, + totalcost double precision, + chargeId int, + rateId int, + exemptionId int, + comment varchar(4000), + flag integer, + sourceRecord varchar(200), + billingId int, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_billedItems PRIMARY KEY (rowId) +); + + +--this table contains a list of all potential items that can be charged. it maps between the integer ID +--and a descriptive name. it does not contain any fee information +CREATE TABLE onprc_billing.chargableItems ( + rowId INT IDENTITY (1,1) NOT NULL, + name varchar(200), + category varchar(200), + comment varchar(4000), + active bit default 1, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_chargableItems PRIMARY KEY (rowId) +); + +--this table contains a list of the current changes for each item in onprc_billing.charges +--it will retain historic information, so we can accurately determine 'cost at the time' +CREATE TABLE onprc_billing.chargeRates ( + rowId INT IDENTITY (1,1) NOT NULL, + chargeId int, + unitcost double precision, + unit varchar(100), + startDate datetime, + endDate datetime, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_chargeRates PRIMARY KEY (rowId) +); + +--contains records of project-specific exemptions to chargeRates +CREATE TABLE onprc_billing.chargeRateExemptions ( + rowId INT IDENTITY (1,1) NOT NULL, + project int, + chargeId int, + unitcost double precision, + unit varchar(100), + startDate datetime, + endDate datetime, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_chargeRateExemptions PRIMARY KEY (rowId) +); + +--maps the account to be credited for each charged item +CREATE TABLE onprc_billing.creditAccount ( + rowId INT IDENTITY (1,1) NOT NULL, + chargeId int, + account int, + startDate datetime, + endDate datetime, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_creditAccount PRIMARY KEY (rowId) +); + +--this table contains records of misc charges that have happened that cannot otherwise be +--automatically inferred from the record +CREATE TABLE onprc_billing.miscCharges ( + rowId INT IDENTITY (1,1) NOT NULL, + id varchar(100), + date DATETIME, + project integer, + account varchar(100), + category varchar(100), + chargeId int, + descrption varchar(1000), --usually null, allow other random values to be supported + quantity double precision, + unitcost double precision, + totalcost double precision, + comment varchar(4000), + + taskid entityid, + requestid entityid, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_miscCharges PRIMARY KEY (rowId) +); + + +--this table details how to calculate lease fees, and produces a list of charges over a billing period +--no fee info is contained +CREATE TABLE onprc_billing.leaseFeeDefinition ( + rowId INT IDENTITY (1,1) NOT NULL, + minAge int, + maxAge int, + + assignCondition int, + releaseCondition int, + chargeId int, + + active bit default 1, + objectid ENTITYID, + createdBy int, + created DATETIME, + modifiedBy int, + modified DATETIME, + + CONSTRAINT PK_leaseFeeDefinition PRIMARY KEY (rowId) +); + +--this table details how to calculate lease fees, and produces a list of charges over a billing period +--no fee info is contained +CREATE TABLE onprc_billing.perDiemFeeDefinition ( + rowId INT IDENTITY (1,1) NOT NULL, + chargeId int, + housingType int, + housingDefinition int, + + startdate datetime, + releaseCondition int, + + active bit default 1, + objectid ENTITYID, + createdBy int, + created DATETIME, + modifiedBy int, + modified DATETIME, + + CONSTRAINT PK_perDiemFeeDefinition PRIMARY KEY (rowId) +); + +--creates list of all procedures that are billable +CREATE TABLE onprc_billing.clinicalFeeDefinition ( + rowId INT IDENTITY (1,1) NOT NULL, + procedureId int, + snomed varchar(100), + + active bit default 1, + objectid ENTITYID, + createdBy int, + created DATETIME, + modifiedBy int, + modified DATETIME, + + CONSTRAINT PK_clinicalFeeDefinition PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.chargeRates drop column unit; +ALTER TABLE onprc_billing.chargeRateExemptions drop column unit; + +alter table onprc_billing.leaseFeeDefinition add project int; +alter table onprc_billing.chargableItems add shortName varchar(100); + +CREATE TABLE onprc_billing.procedureFeeDefinition ( + rowid int identity(1,1), + procedureId int, + chargeType int, + chargeId int, + + active bit default 1, + objectid ENTITYID, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_procedureFeeDefinition PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.financialContacts ( + rowid int identity(1,1), + firstName varchar(100), + lastName varchar(100), + position varchar(100), + address varchar(500), + city varchar(100), + state varchar(100), + country varchar(100), + zip varchar(100), + phoneNumber varchar(100), + + active bit default 1, + objectid ENTITYID, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_financialContacts PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.grants ( + "grant" varchar(100), + investigatorId int, + title varchar(500), + startDate datetime, + endDate datetime, + fiscalAuthority int, + + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_grants PRIMARY KEY ("grant") +); + +CREATE TABLE onprc_billing.accounts ( + account varchar(100), + "grant" varchar(100), + investigator integer, + startdate datetime, + enddate datetime, + externalid varchar(200), + comment varchar(4000), + fiscalAuthority int, + tier integer, + active bit default 1, + + objectid entityid, + createdBy userid, + created datetime, + modifiedBy userid, + modified datetime, + + CONSTRAINT PK_accounts PRIMARY KEY (account) +); + +drop table onprc_billing.financialContacts; + +CREATE TABLE onprc_billing.fiscalAuthorities ( + rowid int identity(1,1), + faid varchar(100), + firstName varchar(100), + lastName varchar(100), + position varchar(100), + address varchar(500), + city varchar(100), + state varchar(100), + country varchar(100), + zip varchar(100), + phoneNumber varchar(100), + + active bit default 1, + objectid ENTITYID, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT pk_fiscalAuthorities PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.projectAccountHistory ( + rowid int identity(1,1), + project int, + account varchar(200), + startdate datetime, + enddate datetime, + objectid entityid, + createdby userid, + created datetime, + modifiedby userid, + modified datetime +); + +DROP TABLE onprc_billing.chargableItems; + +CREATE TABLE onprc_billing.chargeableItems ( + rowId INT IDENTITY (1,1) NOT NULL, + name varchar(200), + shortName varchar(100), + category varchar(200), + comment varchar(4000), + active bit default 1, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_chargeableItems PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.projectAccountHistory ADD CONSTRAINT PK_projectAccountHistory PRIMARY KEY (rowid); + +DROP TABLE onprc_billing.grants ; +GO + +CREATE TABLE onprc_billing.grants ( + grantNumber varchar(100), + investigatorId int, + title varchar(500), + startDate datetime, + endDate datetime, + fiscalAuthority int, + fundingAgency varchar(200), + grantType varchar(200), + + totalDCBudget double precision, + totalFABudget double precision, + budgetStartDate datetime, + budgetEndDate datetime, + + agencyAwardNumber varchar(200), + comment text, + + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_grants PRIMARY KEY (grantNumber) +); + + +DROP TABLE onprc_billing.accounts; + +CREATE TABLE onprc_billing.grantProjects ( + rowid int identity(1,1), + projectNumber varchar(200), + grantNumber varchar(200), + fundingAgency varchar(200), + grantType varchar(200), + agencyAwardNumber varchar(200), + investigatorId int, + alias varchar(200), + projectTitle varchar(4000), + projectDescription varchar(4000), + currentYear int, + totalYears int, + awardSuffix varchar(200), + organization varchar(200), + + awardStartDate datetime, + awardEndDate datetime, + budgetStartDate datetime, + budgetEndDate datetime, + currentDCBudget double precision, + currentFABudget double precision, + totalDCBudget double precision, + totalFABudget double precision, + + spid varchar(100), + fiscalAuthority int, + comment text, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_grantProjects PRIMARY KEY (rowid) +); + + +CREATE TABLE onprc_billing.iacucFundingSources ( + rowid int identity(1,1), + protocol varchar(200), + grantNumber varchar(200), + projectNumber varchar(200), + + startdate datetime, + enddate datetime, + + container ENTITYID NOT NULL, + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_iacucFundingSources PRIMARY KEY (rowid) +); + +alter table onprc_billing.leaseFeeDefinition drop column project; + +ALTER Table onprc_billing.invoicedItems DROP COLUMN flag; + +ALTER Table onprc_billing.invoicedItems ADD credit bit; +ALTER Table onprc_billing.invoicedItems ADD lastName varchar(100); +ALTER Table onprc_billing.invoicedItems ADD firstName varchar(100); +ALTER Table onprc_billing.invoicedItems ADD project int; +ALTER Table onprc_billing.invoicedItems ADD invoiceDate datetime; +ALTER Table onprc_billing.invoicedItems ADD invoiceNumber int; +ALTER Table onprc_billing.invoicedItems ADD transactionType varchar(10); +ALTER Table onprc_billing.invoicedItems ADD department varchar(100); +ALTER Table onprc_billing.invoicedItems ADD mailcode varchar(20); +ALTER Table onprc_billing.invoicedItems ADD contactPhone varchar(30); +ALTER Table onprc_billing.invoicedItems ADD faid int; +ALTER Table onprc_billing.invoicedItems ADD cageId int; +ALTER Table onprc_billing.invoicedItems ADD objectId entityid; + +ALTER Table onprc_billing.invoiceRuns ADD runDate datetime; + +ALTER Table onprc_billing.invoiceRuns ADD billingPeriodStart datetime; +ALTER Table onprc_billing.invoiceRuns ADD billingPeriodEnd datetime; + +ALTER Table onprc_billing.chargeableItems ADD itemCode varchar(100); +ALTER Table onprc_billing.chargeableItems ADD departmentCode varchar(100); +ALTER Table onprc_billing.invoicedItems ADD itemCode varchar(100); + +ALTER Table onprc_billing.procedureFeeDefinition DROP COLUMN chargeType; +GO +ALTER Table onprc_billing.procedureFeeDefinition ADD billedby varchar(100); + +ALTER Table onprc_billing.invoiceRuns ADD objectid entityid; + +ALTER Table onprc_billing.procedureFeeDefinition DROP COLUMN billedby; +ALTER Table onprc_billing.procedureFeeDefinition ADD chargetype varchar(100); + +ALTER TABLE onprc_billing.invoiceRuns ALTER COLUMN objectid ENTITYID NOT NULL; +GO +EXEC core.fn_dropifexists 'invoiceRuns', 'onprc_billing', 'CONSTRAINT', 'pk_invoiceRuns'; + +ALTER TABLE onprc_billing.invoiceRuns ADD CONSTRAINT pk_invoiceRuns PRIMARY KEY (objectid); + +ALTER TABLE onprc_billing.invoicedItems ADD creditAccountId int; +ALTER TABLE onprc_billing.invoicedItems ADD invoiceId entityid; + +CREATE TABLE onprc_billing.labworkFeeDefinition ( + rowid int identity(1,1), + servicename varchar(200), + chargeType int, + chargeId int, + + active bit default 1, + objectid ENTITYID, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_labworkFeeDefinition PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.invoicedItems ADD servicecenter varchar(200); + +ALTER TABLE onprc_billing.labworkFeeDefinition DROP COLUMN chargeType; +GO +ALTER TABLE onprc_billing.labworkFeeDefinition ADD chargeType varchar(100); + +ALTER TABLE onprc_billing.invoicedItems ADD transactionNumber int; + +ALTER TABLE onprc_billing.miscCharges ADD chargeType int; +ALTER TABLE onprc_billing.miscCharges ADD billingDate datetime; +ALTER TABLE onprc_billing.miscCharges ADD invoiceId entityid; +ALTER TABLE onprc_billing.miscCharges ADD description varchar(4000); +ALTER TABLE onprc_billing.miscCharges DROP COLUMN descrption; + +ALTER TABLE onprc_billing.invoicedItems DROP COLUMN transactionNumber; +GO +ALTER TABLE onprc_billing.invoicedItems ADD transactionNumber varchar(100); + +ALTER TABLE onprc_billing.miscCharges ADD objectid entityid NOT NULL; + +GO +EXEC core.fn_dropifexists 'miscCharges', 'onprc_billing', 'CONSTRAINT', 'pk_miscCharges'; + +ALTER TABLE onprc_billing.miscCharges ADD CONSTRAINT pk_miscCharges PRIMARY KEY (objectid); + +ALTER TABLE onprc_billing.miscCharges DROP COLUMN rowid; + +ALTER TABLE onprc_billing.invoiceRuns DROP COLUMN runBy; +ALTER TABLE onprc_billing.invoiceRuns DROP COLUMN date; + +ALTER TABLE onprc_billing.invoiceRuns ADD invoiceNumber varchar(200); + +ALTER TABLE onprc_billing.miscCharges ADD invoicedItemId entityid; +ALTER TABLE onprc_billing.miscCharges DROP COLUMN description; + +ALTER TABLE onprc_billing.invoicedItems ADD investigatorId int; + +ALTER TABLE onprc_billing.miscCharges ADD item varchar(500); + +CREATE TABLE onprc_billing.dataAccess ( + rowId int identity(1,1) NOT NULL, + userid int, + investigatorId int, + project int, + allData bit, + + container entityid NOT NULL, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_dataAccess PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.grantProjects ADD protocolNumber Varchar(100); +ALTER TABLE onprc_billing.grantProjects ADD projectStatus Varchar(100); +ALTER TABLE onprc_billing.grantProjects ADD aliasEnabled Varchar(100); +ALTER TABLE onprc_billing.grantProjects ADD ogaProjectId int; + +ALTER TABLE onprc_billing.grantProjects DROP COLUMN spid; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN currentDCBudget; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN currentFABudget; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN totalDCBudget; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN totalFABudget; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN awardStartDate; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN awardEndDate; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN currentYear; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN totalYears; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN awardSuffix; + +ALTER TABLE onprc_billing.grants ADD awardStatus Varchar(100); +ALTER TABLE onprc_billing.grants ADD applicationType Varchar(100); +ALTER TABLE onprc_billing.grants ADD activityType Varchar(100); + +ALTER TABLE onprc_billing.grants ADD ogaAwardId int; + +ALTER TABLE onprc_billing.fiscalAuthorities ADD employeeId varchar(100); + +ALTER TABLE onprc_billing.grants ADD rowid int identity(1,1); +ALTER TABLE onprc_billing.grants ADD container entityid; + +ALTER TABLE onprc_billing.grants DROP PK_grants; +GO +ALTER TABLE onprc_billing.grants ADD CONSTRAINT PK_grants PRIMARY KEY (rowid); +ALTER TABLE onprc_billing.grants ADD CONSTRAINT UNIQUE_grants UNIQUE (container, grantNumber); + +ALTER TABLE onprc_billing.grants DROP COLUMN totalDCBudget; +ALTER TABLE onprc_billing.grants DROP COLUMN totalFABudget; + +ALTER TABLE onprc_billing.grants ADD investigatorName varchar(200); +ALTER TABLE onprc_billing.grantProjects ADD investigatorName varchar(200); + +ALTER TABLE onprc_billing.invoiceRuns ADD status varchar(200); + +ALTER TABLE onprc_billing.miscCharges DROP COLUMN chargeType; +GO +ALTER TABLE onprc_billing.miscCharges ADD chargeType varchar(200); +ALTER TABLE onprc_billing.miscCharges ADD sourceInvoicedItem entityid; + +ALTER TABLE onprc_billing.miscCharges ADD creditaccount varchar(100); + +ALTER TABLE onprc_billing.grantProjects DROP COLUMN alias; +ALTER TABLE onprc_billing.grantProjects DROP COLUMN aliasEnabled; + +CREATE TABLE onprc_billing.aliases ( + rowid int identity(1,1), + alias varchar(200), + aliasEnabled Varchar(100), + + projectNumber varchar(200), + grantNumber varchar(200), + agencyAwardNumber varchar(200), + investigatorId int, + investigatorName varchar(200), + fiscalAuthority int, + + container ENTITYID NOT NULL, + createdBy USERID, + created datetime, + modifiedBy USERID, + modified datetime, + + CONSTRAINT PK_aliases PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_billing.miscCharges ADD debitedaccount varchar(200); +EXEC sp_rename 'onprc_billing.miscCharges.creditaccount', 'creditedaccount', 'COLUMN'; + +ALTER TABLE onprc_billing.miscCharges ADD qcstate int; + +ALTER TABLE onprc_billing.perDiemFeeDefinition ADD tier varchar(100); + +ALTER TABLE onprc_billing.aliases ADD fiscalAuthorityName varchar(200); + +ALTER TABLE onprc_billing.chargeableItems ADD allowsCustomUnitCost bit DEFAULT 0; +GO +UPDATE onprc_billing.chargeableItems SET allowsCustomUnitCost = 0; + +ALTER TABLE onprc_billing.aliases ADD category varchar(100); + +ALTER TABLE onprc_billing.miscCharges ADD parentid entityid; + +ALTER TABLE onprc_billing.perDiemFeeDefinition DROP COLUMN releaseCondition; +ALTER TABLE onprc_billing.perDiemFeeDefinition DROP COLUMN startDate; + +CREATE TABLE onprc_billing.slaPerDiemFeeDefinition ( + rowid int IDENTITY(1,1) NOT NULL, + chargeid int, + cagetype varchar(100), + cagesize varchar(100), + species varchar(100), + active bit, + objectid ENTITYID, + createdby int, + created datetime, + modifiedby int, + modified datetime, + + CONSTRAINT PK_slaPerDiemFeeDefinition PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_billing.invoicedItems ADD chargetype varchar(100); + +ALTER TABLE onprc_billing.invoicedItems ADD sourcerecord2 varchar(100); +ALTER TABLE onprc_billing.invoicedItems ADD issueId int; +ALTER TABLE onprc_billing.miscCharges ADD issueId int; + +ALTER TABLE onprc_billing.chargeRateExemptions ADD remark varchar(4000); +ALTER TABLE onprc_billing.chargeRateExemptions ADD subsidy double precision; + +CREATE TABLE onprc_billing.projectFARates ( + rowid int identity(1,1), + project int, + fa double precision, + remark varchar(4000), + startdate datetime, + enddate datetime, + + container entityid, + createdby int, + created datetime, + modifiedby int, + modified datetime +); + +ALTER TABLE onprc_billing.chargeRateExemptions DROP COLUMN subsidy; +ALTER TABLE onprc_billing.chargeRates ADD subsidy double precision; + +DROP TABLE onprc_billing.projectFARates; +ALTER TABLE onprc_billing.aliases ADD faRate double precision; +ALTER TABLE onprc_billing.aliases ADD faSchedule varchar(200); + +ALTER TABLE onprc_billing.aliases ADD budgetStartDate datetime; +ALTER TABLE onprc_billing.aliases ADD budgetEndDate datetime; + +CREATE INDEX IDX_aliases ON onprc_billing.aliases (container, alias); + +ALTER TABLE onprc_billing.invoicedItems DROP CONSTRAINT PK_billedItems; +GO +ALTER TABLE onprc_billing.invoicedItems ALTER COLUMN objectid ENTITYID NOT NULL; +GO +ALTER TABLE onprc_billing.invoicedItems ADD CONSTRAINT PK_invoicedItems PRIMARY KEY (objectid); + +CREATE TABLE onprc_billing.chargeableItemCategories ( + category varchar(100), + + CONSTRAINT PK_chargeableItemCategories PRIMARY KEY (category) +); +GO +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Animal Per Diem'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Clinical Lab Test'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Clinical Procedure'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Lease Fees'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Lease Setup Fees'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Misc. Fees'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Small Animal Per Diem'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Surgery'); +INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Time Mated Breeders'); + +CREATE TABLE onprc_billing.aliasCategories ( + category varchar(100), + + CONSTRAINT PK_aliasCategories PRIMARY KEY (category) +); +GO +INSERT INTO onprc_billing.aliasCategories (category) VALUES ('OGA'); +INSERT INTO onprc_billing.aliasCategories (category) VALUES ('Other'); +INSERT INTO onprc_billing.aliasCategories (category) VALUES ('GL'); + +ALTER TABLE onprc_billing.creditAccount ADD tempaccount varchar(100); +GO +UPDATE onprc_billing.creditAccount SET tempaccount = cast(account as varchar(100)); +ALTER TABLE onprc_billing.creditAccount DROP COLUMN account; +GO +ALTER TABLE onprc_billing.creditAccount ADD account varchar(100); +GO +UPDATE onprc_billing.creditAccount SET account = tempaccount; +ALTER TABLE onprc_billing.creditAccount DROP COLUMN tempaccount; + +ALTER TABLE onprc_billing.aliases ADD projectTitle varchar(1000); +ALTER TABLE onprc_billing.aliases ADD projectDescription varchar(1000); +ALTER TABLE onprc_billing.aliases ADD projectStatus varchar(200); + +CREATE TABLE onprc_billing.bloodDrawFeeDefinition ( + rowid int identity(1,1), + chargeType int, + chargeId int, + + active bit default 1, + objectid ENTITYID, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_bloodDrawFeeDefinition PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.bloodDrawFeeDefinition DROP COLUMN chargetype; +GO +ALTER TABLE onprc_billing.bloodDrawFeeDefinition ADD chargetype varchar(100); +ALTER TABLE onprc_billing.bloodDrawFeeDefinition ADD creditalias varchar(100); + +ALTER TABLE onprc_billing.miscCharges DROP COLUMN account; +ALTER TABLE onprc_billing.miscCharges DROP COLUMN totalcost; + +ALTER TABLE onprc_billing.aliases ADD aliasType VARCHAR(100); + +DELETE FROM onprc_billing.aliasCategories WHERE category = 'Non-Syncing'; +INSERT INTO onprc_billing.aliasCategories (category) VALUES ('Non-Syncing'); + +CREATE TABLE onprc_billing.aliasTypes ( + aliasType varchar(500) not null, + removeSubsidy bit, + canRaiseFA bit, + + createdBy integer, + created datetime, + modifiedBy integer, + modified datetime, + + CONSTRAINT PK_aliasTypes PRIMARY KEY (aliasType) +); + +CREATE TABLE onprc_billing.projectMultipliers ( + rowid int identity(1,1) not null, + project integer, + multiplier double precision, + + startdate datetime, + enddate datetime, + comment varchar(4000), + + container entityid, + createdBy integer, + created datetime, + modifiedBy integer, + modified datetime, + + CONSTRAINT PK_projectMultipliers PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_billing.chargeableItems ADD canRaiseFA bit; + +ALTER TABLE onprc_billing.miscCharges ADD formSort integer; + +CREATE TABLE onprc_billing.miscChargesType ( + category varchar(100) not null, + + CONSTRAINT PK_miscChargesType PRIMARY KEY (category) +); +GO +INSERT INTO onprc_billing.miscChargesType (category) VALUES ('Adjustment'); +INSERT INTO onprc_billing.miscChargesType (category) VALUES ('Reversal'); + +ALTER TABLE onprc_billing.miscCharges ADD chargeCategory VARCHAR(100); +GO +UPDATE onprc_billing.miscCharges SET chargeCategory = chargetype; +UPDATE onprc_billing.miscCharges SET chargetype = null; + +EXEC sp_rename 'onprc_billing.invoicedItems.chargetype', 'chargeCategory', 'COLUMN'; + +DROP TABLE onprc_billing.bloodDrawFeeDefinition; +DROP TABLE onprc_billing.clinicalFeeDefinition; + +ALTER TABLE onprc_billing.perDiemFeeDefinition ADD canChargeInfants bit default 0; +ALTER TABLE onprc_billing.procedureFeeDefinition ADD assistingStaff VARCHAR(100); + +CREATE TABLE onprc_billing.medicationFeeDefinition ( + rowid int identity(1,1), + route varchar(100), + chargeId int, + + active bit default 1, + objectid ENTITYID, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_medicationFeeDefinition PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.chargeUnits ( + chargetype varchar(100) NOT NULL, + shownInBlood bit default 0, + shownInLabwork bit default 0, + shownInMedications bit default 0, + shownInProcedures bit default 0, + + active bit default 1, + container entityid, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_chargeUnits PRIMARY KEY (chargetype) +); + +CREATE TABLE onprc_billing.chargeUnitAccounts ( + rowid int identity(1,1), + chargetype varchar(100), + account varchar(100), + startdate datetime, + enddate datetime, + + container entityid, + createdBy int, + created datetime, + modifiedBy int, + modified datetime, + + CONSTRAINT PK_chargeUnitAccounts PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_billing.chargeableItems ADD allowBlankId bit; +GO +UPDATE onprc_billing.chargeableItems SET allowBlankId = 0; + +ALTER TABLE onprc_billing.projectMultipliers ADD account varchar(100); +GO +UPDATE onprc_billing.projectMultipliers SET account = ( + SELECT max(account) FROM onprc_billing.projectAccountHistory a + WHERE a.project = projectMultipliers.project + AND a.startdate <= CURRENT_TIMESTAMP + AND a.enddate >= CURRENT_TIMESTAMP +); +GO +ALTER TABLE onprc_billing.projectMultipliers DROP COLUMN project; + +ALTER TABLE onprc_billing.chargeUnits ADD servicecenter varchar(100); + +ALTER TABLE onprc_billing.leaseFeeDefinition ADD chargeunit varchar(100); + +CREATE INDEX IDX_projectAccountHistory_project_enddate ON onprc_billing.projectAccountHistory (project, enddate); + +ALTER TABLE onprc_billing.medicationFeeDefinition ADD code VARCHAR(100); + +--Updated 1/21/2016 +--gjones +--added start and end dates to selected Finance datasets +--reset the tables + + +ALTER TABLE onprc_billing.procedureFeeDefinition ADD startDate DATETIME; +ALTER TABLE onprc_billing.procedureFeeDefinition ADD endDate DATETIME; + +ALTER TABLE onprc_billing.labWorkFeeDefinition ADD startDate DATETIME; +ALTER TABLE onprc_billing.labWorkFeeDefinition ADD endDate DATETIME; + + +ALTER TABLE onprc_billing.slaPerDiemFeeDefinition ADD startDate DATETIME; +ALTER TABLE onprc_billing.slaPerDiemFeeDefinition ADD endDate DATETIME; + +ALTER TABLE onprc_billing.leaseFeeDefinition ADD startDate DATETIME; +ALTER TABLE onprc_billing.leaseFeeDefinition ADD endDate DATETIME; +ALTER TABLE onprc_billing.chargeableItems ADD startDate DATETIME; +ALTER TABLE onprc_billing.chargeableItems ADD endDate DATETIME; + + +ALTER TABLE onprc_billing.perDiemFeeDefinition ADD startDate DATETIME; +ALTER TABLE onprc_billing.perDiemFeeDefinition ADD endDate DATETIME; + +ALTER TABLE onprc_billing.medicationFeeDefinition ADD startDate DATETIME; +ALTER TABLE onprc_billing.medicationFeeDefinition ADD endDate DATETIME; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.30-12.301.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.30-12.301.sql deleted file mode 100644 index 993c7f1d8..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.30-12.301.sql +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE SCHEMA onprc_billing; -GO -; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.301-12.302.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.301-12.302.sql deleted file mode 100644 index e6af9a41e..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.301-12.302.sql +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---this table contains one row each time a billing run is performed, which gleans items to be charged from a variety of sources ---and snapshots them into invoicedItems -CREATE TABLE onprc_billing.invoiceRuns ( - rowId INT IDENTITY (1,1) NOT NULL, - date DATETIME, - dataSources varchar(1000), - runBy userid, - comment varchar(4000), - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_invoiceRuns PRIMARY KEY (rowId) -); - ---this table contains a snapshot of items actually invoiced, which will draw from many places in the animal record -CREATE TABLE onprc_billing.invoicedItems ( - rowId INT IDENTITY (1,1) NOT NULL, - id varchar(100), - date DATETIME, - debitedaccount varchar(100), - creditedaccount varchar(100), - category varchar(100), - item varchar(500), - quantity double precision, - unitcost double precision, - totalcost double precision, - chargeId int, - rateId int, - exemptionId int, - comment varchar(4000), - flag integer, - sourceRecord varchar(200), - billingId int, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_billedItems PRIMARY KEY (rowId) -); - - ---this table contains a list of all potential items that can be charged. it maps between the integer ID ---and a descriptive name. it does not contain any fee information -CREATE TABLE onprc_billing.chargableItems ( - rowId INT IDENTITY (1,1) NOT NULL, - name varchar(200), - category varchar(200), - comment varchar(4000), - active bit default 1, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_chargableItems PRIMARY KEY (rowId) -); - ---this table contains a list of the current changes for each item in onprc_billing.charges ---it will retain historic information, so we can accurately determine 'cost at the time' -CREATE TABLE onprc_billing.chargeRates ( - rowId INT IDENTITY (1,1) NOT NULL, - chargeId int, - unitcost double precision, - unit varchar(100), - startDate datetime, - endDate datetime, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_chargeRates PRIMARY KEY (rowId) -); - ---contains records of project-specific exemptions to chargeRates -CREATE TABLE onprc_billing.chargeRateExemptions ( - rowId INT IDENTITY (1,1) NOT NULL, - project int, - chargeId int, - unitcost double precision, - unit varchar(100), - startDate datetime, - endDate datetime, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_chargeRateExemptions PRIMARY KEY (rowId) -); - ---maps the account to be credited for each charged item -CREATE TABLE onprc_billing.creditAccount ( - rowId INT IDENTITY (1,1) NOT NULL, - chargeId int, - account int, - startDate datetime, - endDate datetime, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_creditAccount PRIMARY KEY (rowId) -); - ---this table contains records of misc charges that have happened that cannot otherwise be ---automatically inferred from the record -CREATE TABLE onprc_billing.miscCharges ( - rowId INT IDENTITY (1,1) NOT NULL, - id varchar(100), - date DATETIME, - project integer, - account varchar(100), - category varchar(100), - chargeId int, - descrption varchar(1000), --usually null, allow other random values to be supported - quantity double precision, - unitcost double precision, - totalcost double precision, - comment varchar(4000), - - taskid entityid, - requestid entityid, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_miscCharges PRIMARY KEY (rowId) -); - - ---this table details how to calculate lease fees, and produces a list of charges over a billing period ---no fee info is contained -CREATE TABLE onprc_billing.leaseFeeDefinition ( - rowId INT IDENTITY (1,1) NOT NULL, - minAge int, - maxAge int, - - assignCondition int, - releaseCondition int, - chargeId int, - - active bit default 1, - objectid ENTITYID, - createdBy int, - created DATETIME, - modifiedBy int, - modified DATETIME, - - CONSTRAINT PK_leaseFeeDefinition PRIMARY KEY (rowId) -); - ---this table details how to calculate lease fees, and produces a list of charges over a billing period ---no fee info is contained -CREATE TABLE onprc_billing.perDiemFeeDefinition ( - rowId INT IDENTITY (1,1) NOT NULL, - chargeId int, - housingType int, - housingDefinition int, - - startdate datetime, - releaseCondition int, - - active bit default 1, - objectid ENTITYID, - createdBy int, - created DATETIME, - modifiedBy int, - modified DATETIME, - - CONSTRAINT PK_perDiemFeeDefinition PRIMARY KEY (rowId) -); - ---creates list of all procedures that are billable -CREATE TABLE onprc_billing.clinicalFeeDefinition ( - rowId INT IDENTITY (1,1) NOT NULL, - procedureId int, - snomed varchar(100), - - active bit default 1, - objectid ENTITYID, - createdBy int, - created DATETIME, - modifiedBy int, - modified DATETIME, - - CONSTRAINT PK_clinicalFeeDefinition PRIMARY KEY (rowId) -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.302-12.303.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.302-12.303.sql deleted file mode 100644 index acc3ebd3a..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.302-12.303.sql +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.chargeRates drop column unit; -ALTER TABLE onprc_billing.chargeRateExemptions drop column unit; - -alter table onprc_billing.leaseFeeDefinition add project int; -alter table onprc_billing.chargableItems add shortName varchar(100); - -CREATE TABLE onprc_billing.procedureFeeDefinition ( - rowid int identity(1,1), - procedureId int, - chargeType int, - chargeId int, - - active bit default 1, - objectid ENTITYID, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_procedureFeeDefinition PRIMARY KEY (rowId) -); - -CREATE TABLE onprc_billing.financialContacts ( - rowid int identity(1,1), - firstName varchar(100), - lastName varchar(100), - position varchar(100), - address varchar(500), - city varchar(100), - state varchar(100), - country varchar(100), - zip varchar(100), - phoneNumber varchar(100), - - active bit default 1, - objectid ENTITYID, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_financialContacts PRIMARY KEY (rowId) -); - -CREATE TABLE onprc_billing.grants ( - "grant" varchar(100), - investigatorId int, - title varchar(500), - startDate datetime, - endDate datetime, - fiscalAuthority int, - - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_grants PRIMARY KEY ("grant") -); - -CREATE TABLE onprc_billing.accounts ( - account varchar(100), - "grant" varchar(100), - investigator integer, - startdate datetime, - enddate datetime, - externalid varchar(200), - comment varchar(4000), - fiscalAuthority int, - tier integer, - active bit default 1, - - objectid entityid, - createdBy userid, - created datetime, - modifiedBy userid, - modified datetime, - - CONSTRAINT PK_accounts PRIMARY KEY (account) -); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.303-12.304.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.303-12.304.sql deleted file mode 100644 index 14855fc3c..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.303-12.304.sql +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -drop table onprc_billing.financialContacts; - -CREATE TABLE onprc_billing.fiscalAuthorities ( - rowid int identity(1,1), - faid varchar(100), - firstName varchar(100), - lastName varchar(100), - position varchar(100), - address varchar(500), - city varchar(100), - state varchar(100), - country varchar(100), - zip varchar(100), - phoneNumber varchar(100), - - active bit default 1, - objectid ENTITYID, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT pk_fiscalAuthorities PRIMARY KEY (rowId) -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.304-12.305.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.304-12.305.sql deleted file mode 100644 index cee1e6c21..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.304-12.305.sql +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_billing.projectAccountHistory ( - rowid int identity(1,1), - project int, - account varchar(200), - startdate datetime, - enddate datetime, - objectid entityid, - createdby userid, - created datetime, - modifiedby userid, - modified datetime -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.305-12.306.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.305-12.306.sql deleted file mode 100644 index 6aff27a47..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.305-12.306.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -DROP TABLE onprc_billing.chargableItems; - -CREATE TABLE onprc_billing.chargeableItems ( - rowId INT IDENTITY (1,1) NOT NULL, - name varchar(200), - shortName varchar(100), - category varchar(200), - comment varchar(4000), - active bit default 1, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_chargeableItems PRIMARY KEY (rowId) -); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.307-12.308.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.307-12.308.sql deleted file mode 100644 index de21103cb..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.307-12.308.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.projectAccountHistory ADD CONSTRAINT PK_projectAccountHistory PRIMARY KEY (rowid); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.309-12.310.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.309-12.310.sql deleted file mode 100644 index 8f623749c..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.309-12.310.sql +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -DROP TABLE onprc_billing.grants ; -GO - -CREATE TABLE onprc_billing.grants ( - grantNumber varchar(100), - investigatorId int, - title varchar(500), - startDate datetime, - endDate datetime, - fiscalAuthority int, - fundingAgency varchar(200), - grantType varchar(200), - - totalDCBudget double precision, - totalFABudget double precision, - budgetStartDate datetime, - budgetEndDate datetime, - - agencyAwardNumber varchar(200), - comment text, - - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_grants PRIMARY KEY (grantNumber) -); - - -DROP TABLE onprc_billing.accounts; - -CREATE TABLE onprc_billing.grantProjects ( - rowid int identity(1,1), - projectNumber varchar(200), - grantNumber varchar(200), - fundingAgency varchar(200), - grantType varchar(200), - agencyAwardNumber varchar(200), - investigatorId int, - alias varchar(200), - projectTitle varchar(4000), - projectDescription varchar(4000), - currentYear int, - totalYears int, - awardSuffix varchar(200), - organization varchar(200), - - awardStartDate datetime, - awardEndDate datetime, - budgetStartDate datetime, - budgetEndDate datetime, - currentDCBudget double precision, - currentFABudget double precision, - totalDCBudget double precision, - totalFABudget double precision, - - spid varchar(100), - fiscalAuthority int, - comment text, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_grantProjects PRIMARY KEY (rowid) -); - - -CREATE TABLE onprc_billing.iacucFundingSources ( - rowid int identity(1,1), - protocol varchar(200), - grantNumber varchar(200), - projectNumber varchar(200), - - startdate datetime, - enddate datetime, - - container ENTITYID NOT NULL, - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_iacucFundingSources PRIMARY KEY (rowid) -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.310-12.311.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.310-12.311.sql deleted file mode 100644 index 261041ce3..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.310-12.311.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -alter table onprc_billing.leaseFeeDefinition drop column project; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.315-12.316.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.315-12.316.sql deleted file mode 100644 index 98fa9b06b..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.315-12.316.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER Table onprc_billing.invoicedItems DROP COLUMN flag; - -ALTER Table onprc_billing.invoicedItems ADD credit bit; -ALTER Table onprc_billing.invoicedItems ADD lastName varchar(100); -ALTER Table onprc_billing.invoicedItems ADD firstName varchar(100); -ALTER Table onprc_billing.invoicedItems ADD project int; -ALTER Table onprc_billing.invoicedItems ADD invoiceDate datetime; -ALTER Table onprc_billing.invoicedItems ADD invoiceNumber int; -ALTER Table onprc_billing.invoicedItems ADD transactionType varchar(10); -ALTER Table onprc_billing.invoicedItems ADD department varchar(100); -ALTER Table onprc_billing.invoicedItems ADD mailcode varchar(20); -ALTER Table onprc_billing.invoicedItems ADD contactPhone varchar(30); -ALTER Table onprc_billing.invoicedItems ADD faid int; -ALTER Table onprc_billing.invoicedItems ADD cageId int; -ALTER Table onprc_billing.invoicedItems ADD objectId entityid; - -ALTER Table onprc_billing.invoiceRuns ADD runDate datetime; - \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.320-12.321.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.320-12.321.sql deleted file mode 100644 index 7ecbae027..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.320-12.321.sql +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -ALTER Table onprc_billing.procedureFeeDefinition DROP COLUMN billedby; -ALTER Table onprc_billing.procedureFeeDefinition ADD chargetype varchar(100); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.322-12.323.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.322-12.323.sql deleted file mode 100644 index 85121da22..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.322-12.323.sql +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_billing.labworkFeeDefinition ( - rowid int identity(1,1), - servicename varchar(200), - chargeType int, - chargeId int, - - active bit default 1, - objectid ENTITYID, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_labworkFeeDefinition PRIMARY KEY (rowId) -); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.323-12.324.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.323-12.324.sql deleted file mode 100644 index f7cab6658..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.323-12.324.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.invoicedItems ADD servicecenter varchar(200); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.324-12.325.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.324-12.325.sql deleted file mode 100644 index d70034fc4..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.324-12.325.sql +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.labworkFeeDefinition DROP COLUMN chargeType; -GO -ALTER TABLE onprc_billing.labworkFeeDefinition ADD chargeType varchar(100); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.325-12.326.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.325-12.326.sql deleted file mode 100644 index 67f33ab8e..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.325-12.326.sql +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.invoicedItems ADD transactionNumber int; - -ALTER TABLE onprc_billing.miscCharges ADD chargeType int; -ALTER TABLE onprc_billing.miscCharges ADD billingDate datetime; -ALTER TABLE onprc_billing.miscCharges ADD invoiceId entityid; -ALTER TABLE onprc_billing.miscCharges ADD description varchar(4000); -ALTER TABLE onprc_billing.miscCharges DROP COLUMN descrption; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.326-12.327.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.326-12.327.sql deleted file mode 100644 index dda0e6693..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.326-12.327.sql +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.invoicedItems DROP COLUMN transactionNumber; -GO -ALTER TABLE onprc_billing.invoicedItems ADD transactionNumber varchar(100); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.328-12.329.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.328-12.329.sql deleted file mode 100644 index 12301fb39..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.328-12.329.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.miscCharges DROP COLUMN rowid; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.329-12.330.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.329-12.330.sql deleted file mode 100644 index 4e28283e7..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.329-12.330.sql +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.invoiceRuns DROP COLUMN runBy; -ALTER TABLE onprc_billing.invoiceRuns DROP COLUMN date; - -ALTER TABLE onprc_billing.invoiceRuns ADD invoiceNumber varchar(200); - -ALTER TABLE onprc_billing.miscCharges ADD invoicedItemId entityid; -ALTER TABLE onprc_billing.miscCharges DROP COLUMN description; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.330-12.331.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.330-12.331.sql deleted file mode 100644 index 3b1d1ef94..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.330-12.331.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.invoicedItems ADD investigatorId int; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.331-12.332.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.331-12.332.sql deleted file mode 100644 index 77f96d97d..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.331-12.332.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.miscCharges ADD item varchar(500); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.332-12.333.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.332-12.333.sql deleted file mode 100644 index 61d75a26a..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.332-12.333.sql +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_billing.dataAccess ( - rowId int identity(1,1) NOT NULL, - userid int, - investigatorId int, - project int, - allData bit, - - container entityid NOT NULL, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_dataAccess PRIMARY KEY (rowId) -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.334-12.335.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.334-12.335.sql deleted file mode 100644 index b78231413..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.334-12.335.sql +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.grantProjects ADD protocolNumber Varchar(100); -ALTER TABLE onprc_billing.grantProjects ADD projectStatus Varchar(100); -ALTER TABLE onprc_billing.grantProjects ADD aliasEnabled Varchar(100); -ALTER TABLE onprc_billing.grantProjects ADD ogaProjectId int; - -ALTER TABLE onprc_billing.grantProjects DROP COLUMN spid; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN currentDCBudget; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN currentFABudget; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN totalDCBudget; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN totalFABudget; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN awardStartDate; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN awardEndDate; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN currentYear; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN totalYears; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN awardSuffix; - -ALTER TABLE onprc_billing.grants ADD awardStatus Varchar(100); -ALTER TABLE onprc_billing.grants ADD applicationType Varchar(100); -ALTER TABLE onprc_billing.grants ADD activityType Varchar(100); - -ALTER TABLE onprc_billing.grants ADD ogaAwardId int; - -ALTER TABLE onprc_billing.fiscalAuthorities ADD employeeId varchar(100); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.335-12.336.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.335-12.336.sql deleted file mode 100644 index 41a0f2e38..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.335-12.336.sql +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.grants ADD rowid int identity(1,1); -ALTER TABLE onprc_billing.grants ADD container entityid; - -ALTER TABLE onprc_billing.grants DROP PK_grants; -GO -ALTER TABLE onprc_billing.grants ADD CONSTRAINT PK_grants PRIMARY KEY (rowid); -ALTER TABLE onprc_billing.grants ADD CONSTRAINT UNIQUE_grants UNIQUE (container, grantNumber); - -ALTER TABLE onprc_billing.grants DROP COLUMN totalDCBudget; -ALTER TABLE onprc_billing.grants DROP COLUMN totalFABudget; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.336-12.337.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.336-12.337.sql deleted file mode 100644 index 7b07ac164..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.336-12.337.sql +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.grants ADD investigatorName varchar(200); -ALTER TABLE onprc_billing.grantProjects ADD investigatorName varchar(200); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.337-12.338.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.337-12.338.sql deleted file mode 100644 index 9a2ce21ff..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.337-12.338.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_billing.invoiceRuns ADD status varchar(200); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.338-12.339.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.338-12.339.sql deleted file mode 100644 index 43d6a3f7c..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.338-12.339.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE onprc_billing.miscCharges DROP COLUMN chargeType; -GO -ALTER TABLE onprc_billing.miscCharges ADD chargeType varchar(200); -ALTER TABLE onprc_billing.miscCharges ADD sourceInvoicedItem entityid; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.339-12.340.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.339-12.340.sql deleted file mode 100644 index 379e34c27..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.339-12.340.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_billing.miscCharges ADD creditaccount varchar(100); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.340-12.341.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.340-12.341.sql deleted file mode 100644 index 46cad766d..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.340-12.341.sql +++ /dev/null @@ -1,23 +0,0 @@ -ALTER TABLE onprc_billing.grantProjects DROP COLUMN alias; -ALTER TABLE onprc_billing.grantProjects DROP COLUMN aliasEnabled; - -CREATE TABLE onprc_billing.aliases ( - rowid int identity(1,1), - alias varchar(200), - aliasEnabled Varchar(100), - - projectNumber varchar(200), - grantNumber varchar(200), - agencyAwardNumber varchar(200), - investigatorId int, - investigatorName varchar(200), - fiscalAuthority int, - - container ENTITYID NOT NULL, - createdBy USERID, - created datetime, - modifiedBy USERID, - modified datetime, - - CONSTRAINT PK_aliases PRIMARY KEY (rowid) -); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.341-12.342.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.341-12.342.sql deleted file mode 100644 index 8919d1b73..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.341-12.342.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE onprc_billing.miscCharges ADD debitedaccount varchar(200); -EXEC sp_rename 'onprc_billing.miscCharges.creditaccount', 'creditedaccount', 'COLUMN'; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.342-12.343.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.342-12.343.sql deleted file mode 100644 index 40bf0719d..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.342-12.343.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_billing.miscCharges ADD qcstate int; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.343-12.344.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.343-12.344.sql deleted file mode 100644 index 3a27e8cee..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.343-12.344.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_billing.perDiemFeeDefinition ADD tier varchar(100); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.344-12.345.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.344-12.345.sql deleted file mode 100644 index 1675c1bba..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.344-12.345.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_billing.aliases ADD fiscalAuthorityName varchar(200); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.345-12.346.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.345-12.346.sql deleted file mode 100644 index 8b909785b..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.345-12.346.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE onprc_billing.chargeableItems ADD allowsCustomUnitCost bit DEFAULT 0; -GO -UPDATE onprc_billing.chargeableItems SET allowsCustomUnitCost = 0; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.346-12.347.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.346-12.347.sql deleted file mode 100644 index a1407b4e0..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.346-12.347.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_billing.aliases ADD category varchar(100); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.347-12.348.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.347-12.348.sql deleted file mode 100644 index b40a84c4b..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.347-12.348.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE onprc_billing.miscCharges ADD parentid entityid; - -ALTER TABLE onprc_billing.perDiemFeeDefinition DROP COLUMN releaseCondition; -ALTER TABLE onprc_billing.perDiemFeeDefinition DROP COLUMN startDate; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.348-12.349.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.348-12.349.sql deleted file mode 100644 index 17b6b3674..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.348-12.349.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE TABLE onprc_billing.slaPerDiemFeeDefinition ( - rowid int IDENTITY(1,1) NOT NULL, - chargeid int, - cagetype varchar(100), - cagesize varchar(100), - species varchar(100), - active bit, - objectid ENTITYID, - createdby int, - created datetime, - modifiedby int, - modified datetime, - - CONSTRAINT PK_slaPerDiemFeeDefinition PRIMARY KEY (rowid) -); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.349-12.350.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.349-12.350.sql deleted file mode 100644 index 5f4271667..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.349-12.350.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_billing.invoicedItems ADD chargetype varchar(100); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.350-12.351.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.350-12.351.sql deleted file mode 100644 index 6f51fd797..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.350-12.351.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE onprc_billing.invoicedItems ADD sourcerecord2 varchar(100); -ALTER TABLE onprc_billing.invoicedItems ADD issueId int; -ALTER TABLE onprc_billing.miscCharges ADD issueId int; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.351-12.352.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.351-12.352.sql deleted file mode 100644 index 85a56d43f..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.351-12.352.sql +++ /dev/null @@ -1,17 +0,0 @@ -ALTER TABLE onprc_billing.chargeRateExemptions ADD remark varchar(4000); -ALTER TABLE onprc_billing.chargeRateExemptions ADD subsidy double precision; - -CREATE TABLE onprc_billing.projectFARates ( - rowid int identity(1,1), - project int, - fa double precision, - remark varchar(4000), - startdate datetime, - enddate datetime, - - container entityid, - createdby int, - created datetime, - modifiedby int, - modified datetime -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.352-12.353.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.352-12.353.sql deleted file mode 100644 index 9a4610df7..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.352-12.353.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE onprc_billing.chargeRateExemptions DROP COLUMN subsidy; -ALTER TABLE onprc_billing.chargeRates ADD subsidy double precision; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.353-12.354.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.353-12.354.sql deleted file mode 100644 index 427aa7419..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.353-12.354.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE onprc_billing.projectFARates; -ALTER TABLE onprc_billing.aliases ADD faRate double precision; -ALTER TABLE onprc_billing.aliases ADD faSchedule varchar(200); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.354-12.355.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.354-12.355.sql deleted file mode 100644 index d3bbf9ffa..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.354-12.355.sql +++ /dev/null @@ -1,5 +0,0 @@ -ALTER TABLE onprc_billing.aliases ADD budgetStartDate datetime; -ALTER TABLE onprc_billing.aliases ADD budgetEndDate datetime; - -CREATE INDEX IDX_aliases ON onprc_billing.aliases (container, alias); - diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.355-12.356.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.355-12.356.sql deleted file mode 100644 index 08519cd62..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.355-12.356.sql +++ /dev/null @@ -1,32 +0,0 @@ -ALTER TABLE onprc_billing.invoicedItems DROP CONSTRAINT PK_billedItems; -GO -ALTER TABLE onprc_billing.invoicedItems ALTER COLUMN objectid ENTITYID NOT NULL; -GO -ALTER TABLE onprc_billing.invoicedItems ADD CONSTRAINT PK_invoicedItems PRIMARY KEY (objectid); - -CREATE TABLE onprc_billing.chargeableItemCategories ( - category varchar(100), - - CONSTRAINT PK_chargeableItemCategories PRIMARY KEY (category) -); -GO -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Animal Per Diem'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Clinical Lab Test'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Clinical Procedure'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Lease Fees'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Lease Setup Fees'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Misc. Fees'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Small Animal Per Diem'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Surgery'); -INSERT INTO onprc_billing.chargeableItemCategories (category) VALUES ('Time Mated Breeders'); - -CREATE TABLE onprc_billing.aliasCategories ( - category varchar(100), - - CONSTRAINT PK_aliasCategories PRIMARY KEY (category) -); -GO -INSERT INTO onprc_billing.aliasCategories (category) VALUES ('OGA'); -INSERT INTO onprc_billing.aliasCategories (category) VALUES ('Other'); -INSERT INTO onprc_billing.aliasCategories (category) VALUES ('GL'); - diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.356-12.357.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.356-12.357.sql deleted file mode 100644 index 8aa42c4db..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.356-12.357.sql +++ /dev/null @@ -1,9 +0,0 @@ -ALTER TABLE onprc_billing.creditAccount ADD tempaccount varchar(100); -GO -UPDATE onprc_billing.creditAccount SET tempaccount = cast(account as varchar(100)); -ALTER TABLE onprc_billing.creditAccount DROP COLUMN account; -GO -ALTER TABLE onprc_billing.creditAccount ADD account varchar(100); -GO -UPDATE onprc_billing.creditAccount SET account = tempaccount; -ALTER TABLE onprc_billing.creditAccount DROP COLUMN tempaccount; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.357-12.358.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.357-12.358.sql deleted file mode 100644 index 7db95e31d..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.357-12.358.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE onprc_billing.aliases ADD projectTitle varchar(1000); -ALTER TABLE onprc_billing.aliases ADD projectDescription varchar(1000); -ALTER TABLE onprc_billing.aliases ADD projectStatus varchar(200); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.358-12.359.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.358-12.359.sql deleted file mode 100644 index c036a5747..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.358-12.359.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE onprc_billing.bloodDrawFeeDefinition ( - rowid int identity(1,1), - chargeType int, - chargeId int, - - active bit default 1, - objectid ENTITYID, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_bloodDrawFeeDefinition PRIMARY KEY (rowId) -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.359-12.360.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.359-12.360.sql deleted file mode 100644 index 2ad00f5ce..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.359-12.360.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE onprc_billing.bloodDrawFeeDefinition DROP COLUMN chargetype; -GO -ALTER TABLE onprc_billing.bloodDrawFeeDefinition ADD chargetype varchar(100); -ALTER TABLE onprc_billing.bloodDrawFeeDefinition ADD creditalias varchar(100); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.360-12.361.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.360-12.361.sql deleted file mode 100644 index b7ba2de4b..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.360-12.361.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE onprc_billing.miscCharges DROP COLUMN account; -ALTER TABLE onprc_billing.miscCharges DROP COLUMN totalcost; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.361-12.362.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.361-12.362.sql deleted file mode 100644 index bba848f82..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.361-12.362.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE onprc_billing.aliases ADD aliasType VARCHAR(100); - -DELETE FROM onprc_billing.aliasCategories WHERE category = 'Non-Syncing'; -INSERT INTO onprc_billing.aliasCategories (category) VALUES ('Non-Syncing'); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.362-12.363.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.362-12.363.sql deleted file mode 100644 index 2d1c5a160..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.362-12.363.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE TABLE onprc_billing.aliasTypes ( - aliasType varchar(500) not null, - removeSubsidy bit, - canRaiseFA bit, - - createdBy integer, - created datetime, - modifiedBy integer, - modified datetime, - - CONSTRAINT PK_aliasTypes PRIMARY KEY (aliasType) -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.363-12.364.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.363-12.364.sql deleted file mode 100644 index 1175e0ade..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.363-12.364.sql +++ /dev/null @@ -1,19 +0,0 @@ -CREATE TABLE onprc_billing.projectMultipliers ( - rowid int identity(1,1) not null, - project integer, - multiplier double precision, - - startdate datetime, - enddate datetime, - comment varchar(4000), - - container entityid, - createdBy integer, - created datetime, - modifiedBy integer, - modified datetime, - - CONSTRAINT PK_projectMultipliers PRIMARY KEY (rowid) -); - -ALTER TABLE onprc_billing.chargeableItems ADD canRaiseFA bit; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.364-12.365.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.364-12.365.sql deleted file mode 100644 index 2635ea5e1..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.364-12.365.sql +++ /dev/null @@ -1,17 +0,0 @@ -ALTER TABLE onprc_billing.miscCharges ADD formSort integer; - -CREATE TABLE onprc_billing.miscChargesType ( - category varchar(100) not null, - - CONSTRAINT PK_miscChargesType PRIMARY KEY (category) -); -GO -INSERT INTO onprc_billing.miscChargesType (category) VALUES ('Adjustment'); -INSERT INTO onprc_billing.miscChargesType (category) VALUES ('Reversal'); - -ALTER TABLE onprc_billing.miscCharges ADD chargeCategory VARCHAR(100); -GO -UPDATE onprc_billing.miscCharges SET chargeCategory = chargetype; -UPDATE onprc_billing.miscCharges SET chargetype = null; - -EXEC sp_rename 'onprc_billing.invoicedItems.chargetype', 'chargeCategory', 'COLUMN'; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.365-12.366.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.365-12.366.sql deleted file mode 100644 index 16351513e..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.365-12.366.sql +++ /dev/null @@ -1,53 +0,0 @@ -DROP TABLE onprc_billing.bloodDrawFeeDefinition; -DROP TABLE onprc_billing.clinicalFeeDefinition; - -ALTER TABLE onprc_billing.perDiemFeeDefinition ADD canChargeInfants bit default 0; -ALTER TABLE onprc_billing.procedureFeeDefinition ADD assistingStaff VARCHAR(100); - -CREATE TABLE onprc_billing.medicationFeeDefinition ( - rowid int identity(1,1), - route varchar(100), - chargeId int, - - active bit default 1, - objectid ENTITYID, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_medicationFeeDefinition PRIMARY KEY (rowId) -); - -CREATE TABLE onprc_billing.chargeUnits ( - chargetype varchar(100) NOT NULL, - shownInBlood bit default 0, - shownInLabwork bit default 0, - shownInMedications bit default 0, - shownInProcedures bit default 0, - - active bit default 1, - container entityid, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_chargeUnits PRIMARY KEY (chargetype) -); - -CREATE TABLE onprc_billing.chargeUnitAccounts ( - rowid int identity(1,1), - chargetype varchar(100), - account varchar(100), - startdate datetime, - enddate datetime, - - container entityid, - createdBy int, - created datetime, - modifiedBy int, - modified datetime, - - CONSTRAINT PK_chargeUnitAccounts PRIMARY KEY (rowid) -); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.366-12.367.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.366-12.367.sql deleted file mode 100644 index 66cdd687e..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.366-12.367.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE onprc_billing.chargeableItems ADD allowBlankId bit; -GO -UPDATE onprc_billing.chargeableItems SET allowBlankId = 0; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.367-12.368.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.367-12.368.sql deleted file mode 100644 index fd2376fdc..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.367-12.368.sql +++ /dev/null @@ -1,10 +0,0 @@ -ALTER TABLE onprc_billing.projectMultipliers ADD account varchar(100); -GO -UPDATE onprc_billing.projectMultipliers SET account = ( - SELECT max(account) FROM onprc_billing.projectAccountHistory a - WHERE a.project = projectMultipliers.project - AND a.startdate <= CURRENT_TIMESTAMP - AND a.enddate >= CURRENT_TIMESTAMP -); -GO -ALTER TABLE onprc_billing.projectMultipliers DROP COLUMN project; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.368-12.369.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.368-12.369.sql deleted file mode 100644 index e4f5e5eaf..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.368-12.369.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE onprc_billing.chargeUnits ADD servicecenter varchar(100); - -ALTER TABLE onprc_billing.leaseFeeDefinition ADD chargeunit varchar(100); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.369-12.370.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.369-12.370.sql deleted file mode 100644 index fe48f4406..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.369-12.370.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE INDEX IDX_projectAccountHistory_project_enddate ON onprc_billing.projectAccountHistory (project, enddate); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.370-12.371.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.370-12.371.sql deleted file mode 100644 index b5615161b..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.370-12.371.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_billing.medicationFeeDefinition ADD code VARCHAR(100); \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.371-12.372.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.371-12.372.sql deleted file mode 100644 index 47fec2f15..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.371-12.372.sql +++ /dev/null @@ -1,27 +0,0 @@ ---Updated 1/21/2016 ---gjones ---added start and end dates to selected Finance datasets ---reset the tables - - -ALTER TABLE onprc_billing.procedureFeeDefinition ADD startDate DATETIME; -ALTER TABLE onprc_billing.procedureFeeDefinition ADD endDate DATETIME; - -ALTER TABLE onprc_billing.labWorkFeeDefinition ADD startDate DATETIME; -ALTER TABLE onprc_billing.labWorkFeeDefinition ADD endDate DATETIME; - - -ALTER TABLE onprc_billing.slaPerDiemFeeDefinition ADD startDate DATETIME; -ALTER TABLE onprc_billing.slaPerDiemFeeDefinition ADD endDate DATETIME; - -ALTER TABLE onprc_billing.leaseFeeDefinition ADD startDate DATETIME; -ALTER TABLE onprc_billing.leaseFeeDefinition ADD endDate DATETIME; -ALTER TABLE onprc_billing.chargeableItems ADD startDate DATETIME; -ALTER TABLE onprc_billing.chargeableItems ADD endDate DATETIME; - - -ALTER TABLE onprc_billing.perDiemFeeDefinition ADD startDate DATETIME; -ALTER TABLE onprc_billing.perDiemFeeDefinition ADD endDate DATETIME; - -ALTER TABLE onprc_billing.medicationFeeDefinition ADD startDate DATETIME; -ALTER TABLE onprc_billing.medicationFeeDefinition ADD endDate DATETIME; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.372-18.10.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.372-18.10.sql new file mode 100644 index 000000000..21f22c69b --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.372-18.10.sql @@ -0,0 +1,343 @@ +-- Contents of onprc_billing-12.373-12.374.sql to onprc_billing-17.501-17.502.sql from onprc19.1Prod + +--cREATED 8/25/2016 +--gjones +--NEW Data set to control Inflation factor for Rates for ONPRC +-- +CREATE TABLE onprc_billing.AnnualInflationRate ( + billingYear varchar(10) not null, + inflationRate decimal, + startDate datetime, + endDate datetime, + + createdBy integer, + created datetime, + modifiedBy integer, + modified datetime, + + +); + +EXEC sp_rename 'onprc_billing.AnnualInflationRate', 'AnnualRateChange'; + +-- Created: 4-26-2017 R.Blasa + +CREATE TABLE onprc_billing.MergeChargtypeUpdates ( + rowid int IDENTITY(1,1) NOT NULL, + ProjectName varchar(50) not null, + Protocol varchar(100) not null, + ChargeType varchar(50) not null, + objectid ENTITYID, + startDate datetime, + endDate datetime + + CONSTRAINT PK_MergeType PRIMARY KEY(rowid) +); + +-- Adds table Annual Rate Change to Billing +-- Note: Unnecessary due to onprc_billing.AnnualRateChange existing in the DB +-- from when it was renamed in the 12.378-12.379 script + + +-- SET ANSI_NULLS ON +-- GO +-- +-- SET QUOTED_IDENTIFIER ON +-- GO +-- DROP TABLE onprc_billing.AnnualRateChange; +-- CREATE TABLE onprc_billing.AnnualRateChange +-- ( +-- [billingYear] [varchar](10) NOT NULL, +-- [inflationRate] [decimal](18, 0) NULL, +-- [startDate] [datetime] NULL, +-- [endDate] [datetime] NULL, +-- [createdBy] [int] NULL, +-- [created] [datetime] NULL, +-- [modifiedBy] [int] NULL, +-- [modified] [datetime] NULL +-- ) ON [PRIMARY] +-- GO + +-- Adds table Annual Rate Change to Billing +-- add primary key and identity key +ALTER TABLE onprc_billing.AnnualRateChange Add RowID Int IDENTITY (1,1)not null; +ALTER TABLE onprc_billing.AnnualRateChange Add CONSTRAINT PK_AnnualRateChange_RowID PRIMARY KEY CLUSTERED (RowID); + +-- Adds change inflation rate to 3 position decimal +-- add primary key and identity key +alter table [onprc_billing].[AnnualRateChange] +ALTER COLUMN InflationRate Numeric(18,4) +GO +/****** Object: StoredProcedure [onprc_billing].[AnnualRateChangeProcess] Script Date: 5/4/2018 10:50:22 AM ******/ + +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= + +--DROP Procedure [onprc_billing].[AnnualRateChange] +--Go + +CREATE Procedure [onprc_billing].[AnnualRateChangeProcess] + +AS + +BEGIN +DECLARE + + +@Year1 float, + @Year2 float, + @Year3 float, + @Year4 float, + @Year5 float, + @Year6 float, + @Year7 float, + @Year8 float, + @Year9 float, + @Aprate1 float, + @Aprate2 float, + @Aprate3 float, + @Aprate4 float, + @Aprate5 float, + @Aprate6 float, + @Aprate7 float, + @Aprate8 float, + @Aprate9 float, + + @UnitCost float, + @nSearchkey int, + @TempSearchkey Int, + @ChargeId SmallInt, + @CurrentBillingYear SmallInt, + @Billingyear as Smallint + + + + + + + + + ---- Reset Temp tables + +Delete Rpt_ChargesProjection + + + + +----- INitialize variables + +Set @nSearchkey = 0 +Set @TempSearchkey = 0 +Set @Aprate1 = 0 +Set @Aprate2 = 0 +Set @Aprate3 = 0 +Set @Aprate4 = 0 +Set @Aprate5 = 0 +Set @Aprate6 = 0 +Set @Aprate7 = 0 +Set @Aprate8 = 0 +Set @Aprate9 = 0 +SET @CurrentBillingYear = (Select DATEDIFF(Year,'5/1/1959',GetDate())) +SET @Billingyear = @CurrentBillingYear + 1 + + + +---- Begin Processing Data + +select Top 1 @nSearchkey = rowid from onprc_billing.chargeRates +where endDate >= GETDATE() +order by rowid + + + +--Billing Year Constant + + + +Select @Aprate1 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + +Select @Aprate2 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + 1 + +Select @Aprate3 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + 2 + + If exists (Select InflationRate from onprc_billing.AnnualRateChange + + Where Billingyear = @BillingYear + 3) +Begin + +Select @Aprate4 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + 3 +End + + + + If exists (Select InflationRate from onprc_billing.AnnualRateChange + + Where Billingyear = @BillingYear + 4) +Begin + +Select @Aprate5 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + 4 +End + + If exists (Select InflationRate from onprc_billing.AnnualRateChange + + Where Billingyear = @BillingYear + 5) +Begin + +Select @Aprate6 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + 5 + +End + + If exists (Select InflationRate from onprc_billing.AnnualRateChange + + Where Billingyear = @BillingYear + 6) +Begin + +Select @Aprate7 = InflationRate from onprc_billing.AnnualRateChange +Where Billingyear = @BillingYear + 6 + +End + + If exists (Select InflationRate from onprc_billing.AnnualRateChange + + Where Billingyear = @BillingYear + 7) +Begin + +Select @Aprate8 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + 7 + +End + + + If exists (Select InflationRate from onprc_billing.AnnualRateChange + + Where Billingyear = @BillingYear + 8) +Begin + +Select @Aprate9 = InflationRate from onprc_billing.AnnualRateChange + +Where Billingyear = @BillingYear + 8 +End + + + + While @TempSearchKey < @nSearchkey +Begin + +Set @Year1 = 0.0 +Set @Year2 = 0.0 +Set @Year3 = 0.0 +Set @Year4 = 0.0 +Set @Year5 = 0.0 +Set @Year6 = 0.0 +Set @Year7 = 0.0 +Set @Year8 = 0.0 +Set @Year9 = 0.0 +Set @UnitCost = 0.0 +Set @ChargeId = 0 + + If exists(select * from onprc_billing.chargeRates + where endDate >= GETDATE() + And rowid = @nSearchkey) +BEgin + +select Top 1 @UnitCost = unitcost, @ChargeId = chargeid from onprc_billing.chargeRates +where endDate >= GETDATE() + and rowid = @nSearchkey +order by rowid + + + +set @Year1 = @Aprate1 * @UnitCost +Set @year2 = @year1 * @Aprate2 +Set @Year3 = @year2 * @Aprate3 +Set @Year4 = @year3 * @Aprate4 +Set @Year5 = @year4 * @Aprate5 +Set @Year6 = @year5 * @Aprate6 +Set @Year7 = @year6 * @Aprate7 +Set @Year8 = @year7 * @Aprate8 +Set @Year9 = @year8 * @Aprate9 + + + +Insert into Rpt_ChargesProjection +values( + @ChargeId, ------- ChargeId + @UnitCost, ---- starting unit cost for the project year + @Year1, ----- !st Rate computation + @Year2, ----- !st Rate computation + @Year3, ----- !st Rate computation + @Year4, ----- !st Rate computation + @Year5, ----- !st Rate computation + @Year6, ----- !st Rate computation + @Year7, ----- !st Rate computation + @Year8, ----- !st Rate computation + -- @Year9, ----- !st Rate computation, + @Aprate1, ------ inflation rate year 57 + @Aprate2, ------ inflation rate year 58 + @Aprate3, ------ inflation rate year 59 + @Aprate4, ------ inflation rate year 60 + @Aprate5, ------ inflation rate year 61 + @Aprate6, ------ inflation rate year 62 + @Aprate7, ------ inflation rate year 63 + @Aprate8, ------ inflation rate year 64 + @Aprate9, ------ inflation rate year 65 + @nSearchkey, ---- RowID + getdate() ---- run date + + ) + +End ---(if) + + +Set @TempSearchKey = @nSearchkey + + +select Top 1 @nSearchkey = rowid from onprc_billing.chargeRates +where endDate >= GETDATE() + And rowid > @nSearchkey +order by rowid + + + + +End ----(While) + + + +---Now display the results of the computation +Select chargeid as [ChargeID], + unitcost as [UnitCost], + Year1, + Year2, + Year3, + Year4, + Year5, + Year6, + Year7, + Year8, + -- year9, + Rowid as [Row ID], + posteddate as [PostedDate] + + +from Rpt_ChargesProjection + +Order by chargeid + +END \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.373-12.374.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.373-12.374.sql deleted file mode 100644 index bbe028608..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.373-12.374.sql +++ /dev/null @@ -1,17 +0,0 @@ ---cREATED 8/25/2016 ---gjones ---NEW Data set to control Inflation factor for Rates for ONPRC --- -CREATE TABLE onprc_billing.AnnualInflationRate ( - billingYear varchar(10) not null, - inflationRate decimal, - startDate datetime, - endDate datetime, - - createdBy integer, - created datetime, - modifiedBy integer, - modified datetime, - - -); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.378-12.379.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.378-12.379.sql deleted file mode 100644 index 612471a28..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.378-12.379.sql +++ /dev/null @@ -1 +0,0 @@ -EXEC sp_rename 'onprc_billing.AnnualInflationRate', 'AnnualRateChange'; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.101-20.102.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.101-20.102.sql new file mode 100644 index 000000000..8bcb5091d --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.101-20.102.sql @@ -0,0 +1,13 @@ +-- Adds change inflation rate to 3 position decimal +-- add primary key and identity key +--If the field exists in the current build we drop the column and recreate +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [COMMENTS]; +ALTER TABLE onprc_billing.aliases ADD [COMMENTS] VarChar(255) Null; + +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [dateDisabled]; +ALTER TABLE onprc_billing.aliases ADD [dateDisabled] DATETIME Null; + +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [PPQNumber]; +ALTER TABLE onprc_billing.aliases ADD [PPQNumber] VARCHAR(25) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [PPQDate]; +ALTER TABLE onprc_billing.aliases ADD [PPQDate] DATETIME Null; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.102-20.103.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.102-20.103.sql new file mode 100644 index 000000000..25154f119 --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.102-20.103.sql @@ -0,0 +1,52 @@ +DROP TABLE IF EXISTS onprc_billing.ogaSynch +GO + +CREATE TABLE [onprc_billing].[ogasynch]( + [lastIndexed] [datetime] NULL, + [modifiedBy] [int] NULL, + [container] [dbo].[ENTITYID] NOT NULL, + [modified] [datetime] NULL, + [created] [datetime] NULL, + [entityId] [dbo].[ENTITYID] NOT NULL, + [createdBy] [int] NULL, + [ADFM EMP NUM] [int] NULL, + [ADFM FULL NAME] [nvarchar](4000) NULL, + [ADFM LAST NAME] [nvarchar](4000) NULL, + [ADFM FIRST NAME] [nvarchar](4000) NULL, + [PI EMP NUM] [int] NULL, + [PI FULL NAME] [nvarchar](4000) NULL, + [PI LAST NAME] [nvarchar](4000) NULL, + [PI FIRST NAME] [nvarchar](4000) NULL, + [PDFM EMP NUM] [int] NULL, + [PDFM FULL NAME] [nvarchar](4000) NULL, + [PDFM LAST NAME] [nvarchar](4000) NULL, + [PDFM FIRST NAME] [nvarchar](4000) NULL, + [AGENCY AWARD NUMBER] [nvarchar](4000) NULL, + [OGA AWARD NUMBER] [nvarchar](4000) NULL, + [OGA AWARD TYPE] [nvarchar](4000) NULL, + [OGA PROJECT NUMBER] [nvarchar](4000) NULL, + [ALIAS] [int] NULL, + [ALIAS ENABLED FLAG] [bit] NULL, + [ALIAS ENABLED FLAG_MVIndicator] [nvarchar](50) NULL, + [PROJECT DESCRIPTION] [nvarchar](4000) NULL, + [APPLICATION TYPE] [int] NULL, + [ACTIVITY TYPE] [nvarchar](4000) NULL, + [AWARD NUMBER] [nvarchar](4000) NULL, + [AWARD SUFFIX] [nvarchar](4000) NULL, + [ORG] [nvarchar](4000) NULL, + [CURRENT BUDGET START DATE] [datetime] NULL, + [CURRENT BUDGET END DATE] [datetime] NULL, + [PROJECT TITLE] [nvarchar](4000) NULL, + [PPQ CODE] [nvarchar](4000) NULL, + [PPQ DATE] [datetime] NULL, + [IACUC NUMBER] [nvarchar](4000) NULL, + [AWARD STATUS] [nvarchar](4000) NULL, + [PROJECT STATUS] [nvarchar](4000) NULL, + [AWARD ID] [int] NULL, + [PROJECT ID] [int] NULL, + [BURDEN SCHEDULE] [nvarchar](4000) NULL, + [BURDEN RATE] [float] NULL, + [faRate] [float] NULL, + [Key] [int] IDENTITY(1,1) NOT NULL +) ON [PRIMARY] +GO \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.104-20.105.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.104-20.105.sql new file mode 100644 index 000000000..684ad4a48 --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.104-20.105.sql @@ -0,0 +1,39 @@ +-- Adding additional Fields for Alias insert from OGA Synch +--Rerunning and it does not appear in Build +--2020-03-4 Revision to add this to UAT +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ApplicationType]; +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VarChar(255) Null; + +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ApplicationTypeDescription]; +ALTER TABLE onprc_billing.aliases ADD [ApplicationTypeDescription] VarChar(255) Null; + +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardStatus]; +ALTER TABLE onprc_billing.aliases ADD [AwardStatus] VARCHAR(100) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardID]; +ALTER TABLE onprc_billing.aliases ADD [AwardID] VARCHAR(100) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ApplicationType]; +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ProjectID]; +ALTER TABLE onprc_billing.aliases ADD [ProjectID] VARCHAR(100) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ActivityType]; +ALTER TABLE onprc_billing.aliases ADD [ActivityType] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardNumber]; +ALTER TABLE onprc_billing.aliases ADD [AwardNumber] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardSuffix]; +ALTER TABLE onprc_billing.aliases ADD [AwardSuffix] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [Org]; +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ADFMEmpNum]; +ALTER TABLE onprc_billing.aliases ADD [ADFMEmpNum] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ADFMFullName]; +ALTER TABLE onprc_billing.aliases ADD [ADFMFullName] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ActivityTypeDescription]; +ALTER TABLE onprc_billing.aliases ADD [ActivityTypeDescription] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [FundingSourceNumber]; +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceNumber] VARCHAR(255) NUll +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [FundingSourceName]; +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceName] VARCHAR(255) NUll +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [Org]; +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll + +--Adding additional fields to OGA Synch diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.410-20.411.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.410-20.411.sql new file mode 100644 index 000000000..feff5121f --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.410-20.411.sql @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2015-2016 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +-- ================================================ +-- Template generated from Template Explorer using: +-- Create Procedure (New Menu).SQL +-- +-- Use the Specify Values for Template Parameters +-- command (Ctrl-Shift-M) to fill in the parameter +-- values below. +-- +-- This block of comments will not be included in +-- the definition of the procedure. +-- ================================================ +-- ============================================= +-- Author: Jonesga@phsu.edu +-- Create date: 2020/4/11 +-- Description: Process to clean the onprc_billing.aliases dataset to only pertient +-- ============================================= +IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'AliasCleanup202004') + DROP PROCEDURE ALIASCleanup202004 +GO +CREATE PROCEDURE onprc_billing.AliasCleanup202004 + +AS +BEGIN + --Handles active non OGA Aliases + Update a + Set a.projectStatus = 'Active',a.comments = 'In Use - Non ONPRC Alias', a.category = 'OHSU GL' +--Se[onprc_billing].[OGA_RemoveRecords]ect a.Alias,p.account -- update the category to + from onprc_billing.aliases a join onprc_billing.projectAccountHistory p on p.account = a.alias + where p.enddate > = GetDate() and a.alias Not Like '9%' + +-- updates the alias dataset setting end date and comment for disabled aliases + Update a + Set dateDisabled = '4/1/2020', Comments = 'Alias Disabled' + from onprc_billing.aliases a + where aliasEnabled = 'N' + + Update a1 + set a1.projectStatus = 'Non Active GL', a1.aliasEnabled = 'n', a1.datedisabled = GetDate(), a1.comments = 'GL Alias Not Active entered Previously' + + from onprc_billing.aliases a1 left outer join onprc_billing.projectAccountHistory p on p.account = a1.alias + where a1.alias not like '9%' and (a1.comments != 'In Use - Non ONPRC Alias' or a1.comments is null) + + Update a2 + Set a2.dateDisabled = GetDate(), comments = 'Expired Alias', aliasEnabled = 'n' +--select a1.alias,a1.budgetEndDate + from onprc_billing.aliases a2 + where a2.budgetEndDate <=GetDate() + + Update a4 + set dateDisabled = GetDate(), comments = 'Grant Closed', projectStatus = 'Grant Closed', aliasEnabled = 'N' +--Select a4.alias,s.[PROJECT STATUS],a4.projectStatus + from onprc_billing.aliases a4 left Outer join onprc_billing.ogaSynch s on Cast(a4.alias as varchar(50)) = Cast(s.[alias] as VarChar(50)) + where a4.dateDisabled is null and a4.projectstatus in ('Archived','Closed','IM PURGEd') +--Remove Records not associated with ONPRC + DELETE FROM onprc_billing.aliases + where alias in (Select a.alias + from onprc_billing.aliases a left outer join onprc_billing.projectAccountHistory p on a.alias = p.account + where p.account is null and a.dateDisabled is not null) + --Update the existing data to add PPQ, ORG PPQ Date to Existing Aliases +--Update a10 +--Set A10. = s.ORG, a10.PPQNumber = s.[PPQ CODE], a10.PPQDate = s.[PPQ DATE] +--from onprc_billing.aliases a10 left Outer join onprc_billing.ogaSynch s on Cast(a10.alias as varchar(50)) = Cast(s.[alias] as VarChar(50)) +--where a10.Org is null +END +GO + + + diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.508-20.509.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.508-20.509.sql new file mode 100644 index 000000000..684ad4a48 --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.508-20.509.sql @@ -0,0 +1,39 @@ +-- Adding additional Fields for Alias insert from OGA Synch +--Rerunning and it does not appear in Build +--2020-03-4 Revision to add this to UAT +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ApplicationType]; +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VarChar(255) Null; + +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ApplicationTypeDescription]; +ALTER TABLE onprc_billing.aliases ADD [ApplicationTypeDescription] VarChar(255) Null; + +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardStatus]; +ALTER TABLE onprc_billing.aliases ADD [AwardStatus] VARCHAR(100) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardID]; +ALTER TABLE onprc_billing.aliases ADD [AwardID] VARCHAR(100) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ApplicationType]; +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ProjectID]; +ALTER TABLE onprc_billing.aliases ADD [ProjectID] VARCHAR(100) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ActivityType]; +ALTER TABLE onprc_billing.aliases ADD [ActivityType] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardNumber]; +ALTER TABLE onprc_billing.aliases ADD [AwardNumber] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [AwardSuffix]; +ALTER TABLE onprc_billing.aliases ADD [AwardSuffix] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [Org]; +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ADFMEmpNum]; +ALTER TABLE onprc_billing.aliases ADD [ADFMEmpNum] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ADFMFullName]; +ALTER TABLE onprc_billing.aliases ADD [ADFMFullName] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [ActivityTypeDescription]; +ALTER TABLE onprc_billing.aliases ADD [ActivityTypeDescription] VARCHAR(255) NUll; +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [FundingSourceNumber]; +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceNumber] VARCHAR(255) NUll +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [FundingSourceName]; +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceName] VARCHAR(255) NUll +ALTER TABLE onprc_billing.aliases DROP COLUMN IF EXISTS [Org]; +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll + +--Adding additional fields to OGA Synch diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.511-20.512.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.511-20.512.sql new file mode 100644 index 000000000..903b6828c --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.511-20.512.sql @@ -0,0 +1,19 @@ + +/****** Object: StoredProcedure [onprc_billing].[OGA_RemoveRecords] + cREATED 2020-05-18 + cREATED BY JONESGA + Purpose: Resets the Alias Dataset for Insert from OGA, Keeping GL Accounts + + Script Date: 5/18/2020 10:33:15 AM ******/ +DROP PROCEDURE IF EXISTS [onprc_billing].[OGA_RemoveRecords] +GO +CREATE PROCEDURE [onprc_billing].[OGA_RemoveRecords] + AS + BEGIN + + Delete from onprc_billing.aliases + where category != 'OHSU GL' + + + + END \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.512-20.513.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.512-20.513.sql new file mode 100644 index 000000000..1f2a9f0bd --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.512-20.513.sql @@ -0,0 +1,83 @@ + +/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] Script Date: 5/18/2020 10:35:50 AM ******/ +DROP PROCEDURE IF EXISTS [onprc_billing].[oga_InsertRecords] +GO + +CREATE PROCEDURE [onprc_billing].[oga_InsertRecords] + + AS + BEGIN + + INSERT INTO [onprc_billing].[aliases] + ([alias] + ,[aliasEnabled] + ,[projectNumber] + ,[grantNumber] + ,[agencyAwardNumber] + ,[investigatorId] + ,[investigatorName] + ,[fiscalAuthority] + ,[container] + ,[createdBy] + ,[created] + ,[category] + ,[faRate] + ,[faSchedule] + ,[budgetStartDate] + ,[budgetEndDate] + ,[projectTitle] + ,[projectDescription] + ,[projectStatus] + ,[aliasType] + ,[COMMENTS] + ,[PPQNumber] + ,[PPQDate] + ,[AwardStatus] + ,[AwardID] + ,[ApplicationType] + ,[ProjectID] + ,[ActivityType] + ,[AwardNumber] + ,[AwardSuffix] + ,[ADFMEmpNum] + ,[ADFMFullName] + ,[Org] + ) + SELECT + [Alias] + ,[ALIAS ENABLED FLAG_MVIndicator] + ,[OGA PROJECT NUMBER] + ,[OGA AWARD NUMBER] + ,[AGENCY AWARD NUMBER] + ,[PI EMP NUM] + ,[PI FULL NAME] + ,[PDFM EMP NUM] + ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' + ,1003 + ,GetDate() + ,'OGA' + ,[BURDEN RATE] + ,[BURDEN SCHEDULE] + ,[CURRENT BUDGET START DATE] + ,[CURRENT BUDGET END DATE] + ,[PROJECT TITLE] + ,[PROJECT DESCRIPTION] + ,[PROJECT STATUS] + ,[ACTIVITY TYPE] + ,'ENTERED BY ISE' + ,[PPQ CODE] + ,[PPQ DATE] + ,[AWARD STATUS] + ,[AWARD ID] + ,[APPLICATION TYPE] + ,[PROJECT ID] + ,[OGA AWARD TYPE] + ,[AWARD NUMBER] + ,[AWARD SUFFIX] + ,[ADFM EMP NUM] + ,[ADFM FULL NAME] + ,[ORG] + From [onprc_billing].[ogasynch] + END + + diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.514-20.515.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.514-20.515.sql new file mode 100644 index 000000000..35bbc3d6b --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.514-20.515.sql @@ -0,0 +1,100 @@ +/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] Script Date: 5/21/2020 5:43:28 AM ******/ +/*****Update 2020-05-21 to handle Investigator and FA Ids in Prime*******/ + +ALTER PROCEDURE [onprc_billing].[oga_InsertRecords] + + AS + BEGIN + + INSERT INTO [onprc_billing].[aliases] + ([alias] + ,[aliasEnabled] + ,[projectNumber] + ,[grantNumber] + ,[agencyAwardNumber] + ,[investigatorId] + ,[investigatorName] + ,[fiscalAuthority] + ,[container] + ,[createdBy] + ,[created] + ,[category] + ,[faRate] + ,[faSchedule] + ,[budgetStartDate] + ,[budgetEndDate] + ,[projectTitle] + ,[projectDescription] + ,[projectStatus] + ,[aliasType] + ,[COMMENTS] + ,[PPQNumber] + ,[PPQDate] + ,[AwardStatus] + ,[AwardID] + ,[ApplicationType] + ,[ProjectID] + ,[ActivityType] + ,[AwardNumber] + ,[AwardSuffix] + ,[ADFMEmpNum] + ,[ADFMFullName] + ,[Org] + ) + SELECT + [Alias] + ,Case + when [ALIAS ENABLED FLAG] = 0 then 'n' + when [ALIAS ENABLED FLAG] = 1 then 'y' + End as AliasEndabled + + --,[ALIAS ENABLED FLAG] + ,[OGA PROJECT NUMBER] + ,[OGA AWARD NUMBER] + ,[AGENCY AWARD NUMBER] + ,Case + When (Select rowID from [onprc_ehr].[investigators] where [PI EMP NUM] = employeeID and datedisabled is null) is not null + Then (Select rowID from [onprc_ehr].[investigators] where [PI EMP NUM] = employeeID and datedisabled is null) + Else Null + End as InvestigatorID + -- ,[PI EMP NUM] + -- ,(Select rowID from [onprc_ehr].[investigators] where [PI EMP NUM] = employeeID and datedisabled is null) as PILastName + -- [PI EMP NUM] + ,[PI FULL NAME] + ,(Select rowid from [onprc_billing].[fiscalAuthorities] where [PDFM EMP NUM] = employeeID and active = 1) as fiscalAuthority + ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' + ,1003 + ,GetDate() + ,'OGA' + ,[BURDEN RATE] + ,[BURDEN SCHEDULE] + ,[CURRENT BUDGET START DATE] + ,[CURRENT BUDGET END DATE] + ,[PROJECT TITLE] + ,[PROJECT DESCRIPTION] + ,[PROJECT STATUS] + ,[ACTIVITY TYPE] + ,'ENTERED BY ISE' + ,[PPQ CODE] + ,[PPQ DATE] + ,[AWARD STATUS] + ,[AWARD ID] + ,[APPLICATION TYPE] + ,[PROJECT ID] + ,[OGA AWARD TYPE] + ,[AWARD NUMBER] + ,[AWARD SUFFIX] + ,[ADFM EMP NUM] + ,[ADFM FULL NAME] + ,[ORG] + From [onprc_billing].[ogasynch] + + Update [Labkey].[onprc_billing].[aliases] + Set aliasEnabled = 'n' + --where AliasEnabled is null + --Select * from [Labkey].[onprc_billing].[aliases] + where ((budgetEndDate < GetDate() or budgetEndDate is null) or category != 'OHSU GL') + + END + + diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.515-20.516.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.515-20.516.sql new file mode 100644 index 000000000..e30936961 --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.515-20.516.sql @@ -0,0 +1,125 @@ + + +CREATE FUNCTION [onprc_ehr].[RateCalc] + ( + @alias varchar(20), + @chargeId float, + @project float, + @startDate date, + @baseSubsidyVal float + ) + + RETURNS float + AS +BEGIN +Declare @unitCostVal float, + @projectExemption float, + @projectMultipler float, + @unitCost float, + @NonOGAAlias varchar(20), + @blankAliasType varchar(20), + @baseSubsidy float, + @subsidy float, + @faRate float, + @removeSubsidy smallInt, + @aliasRaiseFA smallInt, + @chargeRaiseFA smallInt + + + --initiate Variables + --determine if there is a project level exemption + --the base subsidy is defined as a gloabl variable in the Labkey Java Code in onprc_ehr.java and if a change in the base rate is requested, the data needs to be updated in each position +Set @baseSubsidyVal = .47 +Set @basesubsidy = .47 +Set @unitCost = 1000 +Set @subsidy = @baseSubsidyVal +Set @projectExemption = (Select cr.unitcost From onprc_billing.chargeRateExemptions cr + Where cr.chargeId = @chargeId + and cr.project = @project + and cr.startDate < @startDate + and ((@startDate <= cr.endDate) or (cr.enddate is null))) + +--determine if there is a project level multiplier -- onprc_billing.projectMultipler +--verified the query +Set @projectMultipler = (Select pm.multiplier From onprc_billing.projectMultipliers pm + Where pm.account = @alias + and pm.startdate <= @startDate + and ((pm.enddate >= @startDate) or (pm.enddate is Null))) + + +--determine if the alias is a non oga rate --onprc_billing.aliases --category column +--verified query +Set @NonOGAAlias = (Select a.category From onprc_billing.aliases a + Where a.alias = @alias + and (a.budgetStartDate < @startDate and a.budgetEndDate > @startDate)) + +----determine if Alias Type is Blank +----verified query +Set @blankAliasType = (Select a.aliasType From onprc_billing.aliases a + Where a.alias = @alias + and (a.budgetStartDate < @startDate and a.budgetEndDate > @startDate)) + +----determine if remove subsidy if true +----verified query +Set @removeSubsidy = (Select t.removeSubsidy From onprc_billing.aliases a join onprc_billing.aliasTypes t on a.aliasType = t.aliasType + Where a.alias = @alias + and (a.budgetStartDate < @startDate and a.budgetEndDate > @startDate)) + +----determine if raise F&A is True for Charge Rate --Need to set date parameters on most of these +----Need to lock down date range +Set @chargeRaiseFA = (Select c.canRaiseFA From onprc_billing.chargeableItems c join onprc_billing.chargeRates cr on c.rowId = cr.chargeId + Where cr.chargeId = @chargeId + and (cr.StartDate < @startDate and cr.EndDate > @startDate)) + +----determine if rate F&A is true for alias +Set @aliasRaiseFA = (Select t.canRaiseFA From onprc_billing.aliases a join onprc_billing.aliasTypes t on a.aliasType = t.aliasType + Where a.alias = @alias + and (a.budgetStartDate < @startDate and a.budgetEndDate > @startDate)) + +----get FA Rate for Alias +Set @faRate = (Select a.faRate From onprc_billing.aliases a + Where a.alias = @alias + and (a.budgetStartDate < @startDate and a.budgetEndDate > @startDate)) + +--determine unit cost +--if it retunrs null there is no charge rate +Set @unitCost = (Select r.unitcost From onprc_billing.chargeRates r + Where r.chargeID = @chargeId + and r.startDate <= @startDate + and ((r.enddate >= @startDate) or r.enddate Is Null)) + +--determine Unit Cost +Select @unitCostVal = + + Case + --returns unit cost when there is an exemption at the project level + When @projectExemption is not null then @projectExemption + --return value for a charge that has a pm multiplier + When @projectMultipler is not null then @projectMultipler * @unitCost + ------ --where there is no unit cost listed return null + When @unitCost is null then null + --where the alias type is not OGA charge NIH Rate + When @NonOGAAlias is not null and @NonOGAAlias != 'OGA' then @unitCost + ------when alias type is not known then return null + When @blankAliasType is null then null + + When (@removeSubsidy = 1 AND (@aliasRaiseFA = 1 AND @chargeRaiseFA = 1)) + THEN ((@unitCost / (1 - COALESCE(@subsidy, 0))) * (CASE WHEN (@faRate IS NOT NULL AND @faRate < @baseSubsidy) THEN (1 + @baseSubsidy / (1 + @faRate)) ELSE 1 END)) + + When (@removeSubsidy = 1 AND @aliasRaiseFA = 0) + THEN (@unitCost / (1 - COALESCE(@subsidy, 0))) + + + When (@removeSubsidy = 0 AND (@aliasRaiseFA = 1 AND @chargeRaiseFA = 1)) + Then (@unitCost * (CASE WHEN (@faRate IS NOT NULL AND @faRate = 0) THEN (1 + @Subsidy / (1 + @faRate)) ELSE 1 END)) + + When (@removeSubsidy = 0 AND (@aliasRaiseFA = 1 AND @chargeRaiseFA = 1)) + Then (@unitCost * (CASE WHEN (@faRate IS NOT NULL AND @faRate < @Subsidy) THEN (1 + @Subsidy / (1 + @faRate)) ELSE 1 END)) + + Else @unitCost + END + + --return @unitCost + return @unitCostVal--@projectExemption + +End \ No newline at end of file diff --git a/onprc_billing/resources/schemas/onprc_billing.xml b/onprc_billing/resources/schemas/onprc_billing.xml index 6cae5f0f0..d2675a73e 100644 --- a/onprc_billing/resources/schemas/onprc_billing.xml +++ b/onprc_billing/resources/schemas/onprc_billing.xml @@ -1,4 +1,4 @@ - + Charge Rates @@ -18,7 +18,7 @@ End Date false - yyyy-MM-dd + Date @@ -52,7 +52,7 @@ End Date false - yyyy-MM-dd + Date @@ -97,7 +97,7 @@ Service Center A code used to categorize these items by department, primarily used when exporting or communicating with external billing systems. Similar to itemCode - + Allow Custom Unit Cost? @@ -118,11 +118,12 @@ Start Date + Date End Date false - yyyy-MM-dd + Date
@@ -156,6 +157,7 @@
Transaction Date + Date Item @@ -290,11 +292,14 @@ true - + + Date +
+ Ext4 ehr.context /onprc_billing/window/ReverseChargeWindow.js @@ -321,16 +326,18 @@ Start Date false - yyyy-MM-dd + Date End Date false - yyyy-MM-dd + Date - + + Date + @@ -347,7 +354,7 @@ Date of Charge This column typically refers to the date the charge took place (ie. date blood was drawn). This differs from the column labeled Date Charge Created, which refers to the date the charge was actually entered into the system. This column is used in the IBS sheet; however, it is not used to determine which billing period the item falls into. - yyyy-MM-dd + Date @@ -535,6 +542,7 @@ Housing Type false + EHR ehr_lookups housingTypes rowid @@ -545,6 +553,7 @@ Housing Definition false + EHR ehr_lookups housingDefinition rowid @@ -569,12 +578,12 @@ Start Date false - yyyy-MM-dd + Date End Date false - yyyy-MM-dd + Date @@ -625,12 +634,12 @@ Start Date false - yyyy-MM-dd + Date End Date false - yyyy-MM-dd + Date @@ -650,10 +659,12 @@ Billing Period Start + Date false Billing Period End + Date false @@ -751,12 +762,12 @@ Start Date false - yyyy-MM-dd + Date End Date false - yyyy-MM-dd + Date @@ -853,7 +864,7 @@ End Date true - yyyy-MM-dd + Date Fiscal Authority @@ -876,9 +887,11 @@ Budget Start Date + Date Budget End Date + Date Comment @@ -911,6 +924,7 @@ Charge Type false + EHR ehr_lookups procedureChargeType value @@ -920,6 +934,7 @@ Assisting Staff true + EHR ehr_lookups procedureChargeType value @@ -941,12 +956,12 @@ Start Date false - yyyy-MM-dd + Date End Date false - yyyy-MM-dd + Date @@ -966,6 +981,7 @@ SNOMED Code false + EHR ehr_lookups snomed code @@ -976,6 +992,7 @@ If provided, only medications using this route will be billed. Can be left blank for all routes. false + EHR ehr_lookups routes route @@ -993,12 +1010,12 @@ Start Date false - yyyy-MM-dd + Date End Date false - yyyy-MM-dd + Date @@ -1020,14 +1037,14 @@ Start Date This column refers to the date that this alias was first associated with this project. In other words, this alias is the active alias for the project between the dates listed. - yyyy-MM-dd + Date false End Date This column refers to the date that this alias is no longer associated with this project. In other words, this alias is the active alias for the project between the dates listed. true - yyyy-MM-dd + Date @@ -1087,9 +1104,11 @@ Current Budget Start Date + Date Current Budget End Date + Date Fiscal Authority @@ -1133,9 +1152,11 @@ OGA Grant Number + Agency Award Number + Investigator @@ -1155,9 +1176,11 @@ Alias Start Date + Date Alias End Date + Date F&A Rate @@ -1187,6 +1210,24 @@ + + + + + + + + + + + + + + + + + + @@ -1209,7 +1250,7 @@ End Date - yyyy-MM-dd + Date @@ -1230,6 +1271,7 @@ Service/Panel Name false + /ONPRC/EHR ehr_lookups labwork_services servicename @@ -1240,6 +1282,7 @@ true true + /ONPRC/EHR ehr_lookups labworkChargeType value @@ -1256,12 +1299,12 @@ Start Date false - yyyy-MM-dd + Date End Date false - yyyy-MM-dd + Date @@ -1485,4 +1528,96 @@
+ + + DETAILED + Annual Rate Change + + + Row Id + + + Billing Year + + + + Inflation Rate + 0.0000 + false + + + false + Start Date + + + false + End Date + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
\ No newline at end of file diff --git a/onprc_billing/resources/schemas/onprc_billing_public.template.xml b/onprc_billing/resources/schemas/onprc_billing_public.template.xml index 55f8674d2..c39838ce0 100644 --- a/onprc_billing/resources/schemas/onprc_billing_public.template.xml +++ b/onprc_billing/resources/schemas/onprc_billing_public.template.xml @@ -59,7 +59,7 @@ Aliases Receiving Credits For Each Charge - +
Charge Units
diff --git a/onprc_billing/resources/scripts/onprc_billing/billing_triggers.js b/onprc_billing/resources/scripts/onprc_billing/billing_triggers.js index e9c11453f..5dee9574d 100644 --- a/onprc_billing/resources/scripts/onprc_billing/billing_triggers.js +++ b/onprc_billing/resources/scripts/onprc_billing/billing_triggers.js @@ -100,19 +100,19 @@ exports.init = function(EHR){ } }); - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'Clinical Encounters', function(helper, scriptErrors, row, oldRow){ + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'encounters', function(helper, scriptErrors, row, oldRow){ if (row && oldRow){ processUpdate(helper, 'encounters', ['project', 'Id', 'date', 'chargetype', 'procedureid'], row, oldRow); } }); - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'Clinpath Runs', function(helper, scriptErrors, row, oldRow){ + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'clinpathruns', function(helper, scriptErrors, row, oldRow){ if (row && oldRow){ processUpdate(helper, 'clinpathRuns', ['project', 'Id', 'date', 'chargetype', 'servicerequested'], row, oldRow); } }); - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'Blood Draws', function(helper, scriptErrors, row, oldRow){ + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'blood', function(helper, scriptErrors, row, oldRow){ console.log('inspecting blood draws record for billing audit'); if (row && oldRow){ diff --git a/onprc_billing/resources/views/financeManagement.html b/onprc_billing/resources/views/financeManagement.html index ebd027237..7ef0c6308 100644 --- a/onprc_billing/resources/views/financeManagement.html +++ b/onprc_billing/resources/views/financeManagement.html @@ -53,15 +53,9 @@ header: 'Reference Tables', items: [ {name: 'IACUC Protocols', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', ctx.EHRStudyContainer, {schemaName: 'ehr', 'query.queryName': 'protocol'})}, - {name: 'ONPRC Projects', url: LABKEY.ActionURL.buildURL(ehrQueryController, queryAction, ctx.EHRStudyContainer, {schemaName: 'ehr', 'query.queryName': 'project', showImport: true})}, - - {name: 'Grants', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'grants', 'query.viewName': 'Active Grants'})}, - {name: 'Grant Projects', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'grantProjects', 'query.viewName': 'Active Grant Projects'})}, - {name: 'Aliases', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'aliases', 'query.viewName': 'Active Aliases'})}, - - //{name: 'Approved IACUC Funding Sources', url: LABKEY.ActionURL.buildURL(queryController, queryAction, ctx.EHRStudyContainer, {schemaName: 'onprc_billing', 'query.queryName': 'iacucFundingSources'})}, - - {name: 'Investigators', url: LABKEY.ActionURL.buildURL(ehrQueryController, queryAction, ctx.EHRStudyContainer, {schemaName: 'onprc_ehr', 'query.queryName': 'investigators', showImport: true})}, + {name: 'ONPRC Projects', url: LABKEY.ActionURL.buildURL(queryController, queryAction, ctx.EHRStudyContainer, {schemaName: 'ehr', 'query.queryName': 'project', showImport: true})}, + {name: 'Aliases (Grants Data included)', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'aliases', 'query.viewName': 'Active Aliases'})}, + {name: 'Investigators', url: LABKEY.ActionURL.buildURL(queryController, queryAction, ctx.EHRStudyContainer, {schemaName: 'onprc_ehr', 'query.queryName': 'investigators', showImport: true})}, {name: 'Financial Analysts', url: LABKEY.ActionURL.buildURL(queryController, queryAction, ctx.EHRStudyContainer, {schemaName: 'onprc_billing', 'query.queryName': 'fiscalAuthorities', showImport: true})}, {name: 'OGA Raw Data', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'OGA', 'query.queryName': 'ZGMS_PRIM_ALL_V'})} ] @@ -72,8 +66,8 @@ {name: 'Chargeable Items', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'chargeableItems', 'query.viewName': 'Active Items', showImport: true})}, {name: 'Standard Rates', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'chargeRates', 'query.viewName': 'Active Rates', showImport: true})}, //note: exemptions uses ehr controller so we can apply metadata for the project field. - {name: 'Alias-Level Multipliers', url: LABKEY.ActionURL.buildURL(ehrQueryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'projectMultipliers', 'query.viewName': 'Active Items', showImport: true})}, - {name: 'Item-Level Rate Exemptions', url: LABKEY.ActionURL.buildURL(ehrQueryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'chargeRateExemptions', 'query.viewName': 'Active Items', showImport: true})}, + {name: 'Alias-Level Multipliers', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'projectMultipliers', 'query.viewName': 'Active Items', showImport: true})}, + {name: 'Item-Level Rate Exemptions', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'chargeRateExemptions', 'query.viewName': 'Active Items', showImport: true})}, {name: 'Aliases Receiving Credit Per Item', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'creditAccount', 'query.viewName': 'Active Items', showImport: true})}, {name: 'Charge Units', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'chargeUnits', 'query.viewName': 'Active Items', showImport: true})}, {name: 'Charge Unit Credit Aliases', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'chargeUnitAccounts', showImport: true})}, @@ -83,7 +77,7 @@ {name: 'Lease Fee Structure', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'leaseFeeDefinition'})}, {name: 'Medication Fee Structure', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'medicationFeeDefinition'})}, {name: 'NHP Per Diem Fee Structure', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'perDiemFeeDefinition'})}, - {name: 'Procedure Fee Structure', url: LABKEY.ActionURL.buildURL(ehrQueryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'procedureFeeDefinition', showImport: true})}, + {name: 'Procedure Fee Structure', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'procedureFeeDefinition', showImport: true})}, {name: 'SLA Per Diem Fee Structure', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'slaPerDiemFeeDefinition'})}, {name: 'ONPRC Annual Rate Change', url: LABKEY.ActionURL.buildURL(queryController, queryAction, null, {schemaName: 'onprc_billing', 'query.queryName': 'AnnualRateChange',showImport: true})}, diff --git a/onprc_billing/resources/views/invoiceRunDetails.html b/onprc_billing/resources/views/invoiceRunDetails.html index a7b9e5919..01d2955bf 100644 --- a/onprc_billing/resources/views/invoiceRunDetails.html +++ b/onprc_billing/resources/views/invoiceRunDetails.html @@ -161,9 +161,12 @@ {name: 'Download IBS Spreadsheet (PDAR - Leases)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~eq': 'PDAR', 'query.category~in': 'Lease Fees;Lease Setup Fees;Lease Fee Adjustment'})}, {name: 'Download IBS Spreadsheet (PDAR - Per Diems)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~eq': 'PDAR', 'query.category~eq': 'Animal Per Diem'})}, {name: 'Download IBS Spreadsheet (PDAR - Other)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~eq': 'PDAR', 'query.category~notin': 'Animal Per Diem;Lease Fees;Lease Setup Fees;Lease Fee Adjustment'})}, + {name: 'Download IBS Spreadsheet (PMIC)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~eq': 'PMIC', 'query.category~in': 'PMIC'})}, {name: 'Download IBS Spreadsheet (PSURG)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~eq': 'PSURG'})}, + {name: 'Download IBS Spreadsheet (PVIRO)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~eq': 'PVIRO'})}, + {name: 'Download IBS Spreadsheet (SLAU)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~eq': 'SLAU'})}, - {name: 'Download IBS Spreadsheet (Other)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~notin': 'PDAR;PSURG;SLAU'})} + {name: 'Download IBS Spreadsheet (Other)', url: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'onprc_billing', 'query.queryName': 'chargesIBS', 'query.invoiceId~eq': this.invoiceRunId, 'query.servicecenter~notin': 'PDAR;PSURG;SLAU;PVIRO;PMIC'})}, ] },{ header: 'Charge Calculations For This Billing Period', diff --git a/onprc_billing/resources/web/onprc_billing/model/sources/AliasMisc.js b/onprc_billing/resources/web/onprc_billing/model/sources/AliasMisc.js new file mode 100644 index 000000000..377327207 --- /dev/null +++ b/onprc_billing/resources/web/onprc_billing/model/sources/AliasMisc.js @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +//Created: 6-8-2017 R.Blasa +EHR.model.DataModelManager.registerMetadata('AliasMisc', { + allQueries: { + }, + byQuery: { + 'onprc_billing.miscCharges': { + debitedaccount: { + xtype: 'textfield', + header: 'Alias', + width: 200, + hidden: false + }, + project: { + allowBlank: true + } + } + } +}); \ No newline at end of file diff --git a/onprc_billing/resources/web/onprc_billing/model/sources/VirologyMisc.js b/onprc_billing/resources/web/onprc_billing/model/sources/VirologyMisc.js new file mode 100644 index 000000000..5c0797b56 --- /dev/null +++ b/onprc_billing/resources/web/onprc_billing/model/sources/VirologyMisc.js @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + + +EHR.model.DataModelManager.registerMetadata('VirologyMisc', { + allQueries: { + }, + byQuery: { + 'onprc_billing.miscCharges': { + Id: { + hidden: false, + header: 'Animal Id' + }, + + chargeId: { + xtype: 'combo', + header: 'Charge Name', + hidden: false, + lookup: { + schemaName: 'onprc_billing', + queryName: 'virologyBillingCharges', + displayColumn: 'chargeName', + keyColumn: 'rowid', + columns: 'rowid, category, chargeName, unitCost' + }, + editorConfig: { + listConfig: { + //innerTpl: '{[(values.category ? "" + values.category + ": " : "") + values.chargeName]}', + innerTpl: '{[("" + values.chargeName + "" )]}', + getInnerTpl: function(){ + return this.innerTpl; + } + } + }, + columnConfig: { + width: 400 + } + + }, + + debitedaccount: { + xtype: 'combo', + header: 'Alias', + hidden: false, + lookup: { + schemaName: 'onprc_billing', + queryName: 'virologyAliases', + displayColumn: 'aliasPI', + keyColumn: 'alias', + columns: 'alias, aliasPI' + }, + editorConfig: { + listConfig: { + innerTpl: '{[("" + values.aliasPI + "" )]}', + getInnerTpl: function(){ + return this.innerTpl; + } + } + }, + columnConfig: { + width: 300 + } + + }, + + project: { + allowBlank: true, + hidden: true + }, + + comment: { + allowBlank: true, + columnConfig: { + width: 200 + } + }, + + unitcost: { + hidden: false, + header: 'NIH Rate', + editorConfig: { + decimalPrecision: 2 + } + }, + + lineItemTotal: { + allowBlank: true, + header: 'Estimated Charge', + nullable: true, + hidden: false, + shownInGrid: true, + columnConfig: { + width: 200 + } + }, + + chargetype: { + allowBlank: true, + defaultValue: 'Virology Core', + hidden: false + } + + } + } +}); \ No newline at end of file diff --git a/onprc_billing/resources/web/onprc_billing/panel/ChargesInstructionPanel.js b/onprc_billing/resources/web/onprc_billing/panel/ChargesInstructionPanel.js index f433b4655..5d1a2e893 100644 --- a/onprc_billing/resources/web/onprc_billing/panel/ChargesInstructionPanel.js +++ b/onprc_billing/resources/web/onprc_billing/panel/ChargesInstructionPanel.js @@ -11,7 +11,9 @@ Ext4.define('ONPRC_Billing.panel.ChargesInstructionPanel', { items: [{ html: 'This form allows authorized users to enter new charges. This should only be used for changes that are not automatically calculated from the animal record. ' + '

' + - 'Important: The vast majority of the time, you should leave unit cost blank. It will be calculated based on standard rates (at the time of the charge), and based on known exemptions. This field will only be editable if the item you selected supports variable unit cost.', + 'Important: The vast majority of the time, you should leave unit cost blank. It will be calculated based on standard rates (at the time of the charge), and based on known exemptions. This field will only be editable if the item you selected supports variable unit cost.' + + '

' + + 'Note: Recent changes to the property settings now allows you to enter either the Center Project, or the Alias number.', style: 'padding: 5px;' }] }) diff --git a/onprc_billing/src/org/labkey/onprc_billing/ONPRC_BillingModule.java b/onprc_billing/src/org/labkey/onprc_billing/ONPRC_BillingModule.java index aff7da8c5..20673ed3a 100644 --- a/onprc_billing/src/org/labkey/onprc_billing/ONPRC_BillingModule.java +++ b/onprc_billing/src/org/labkey/onprc_billing/ONPRC_BillingModule.java @@ -22,6 +22,7 @@ import org.labkey.api.audit.AuditLogService; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; +import org.labkey.api.data.JdbcType; import org.labkey.api.ehr.EHRService; import org.labkey.api.ehr.buttons.MarkCompletedButton; import org.labkey.api.ehr.dataentry.DefaultDataEntryFormFactory; @@ -33,6 +34,7 @@ import org.labkey.api.pipeline.PipelineService; import org.labkey.api.query.DefaultSchema; import org.labkey.api.query.QuerySchema; +import org.labkey.api.query.QueryService; import org.labkey.api.security.roles.RoleManager; import org.labkey.api.view.ViewContext; import org.labkey.api.view.WebPartFactory; @@ -42,6 +44,8 @@ import org.labkey.onprc_billing.button.ProjectEditButton; import org.labkey.onprc_billing.dataentry.ChargesAdvancedFormType; import org.labkey.onprc_billing.dataentry.ChargesFormType; +//import org.labkey.onprc_billing.dataentry.ChargesVirologyCoreFormType; +import org.labkey.onprc_billing.dataentry.ChargesVirologyCoreFormType; import org.labkey.onprc_billing.dataentry.ReversalFormType; import org.labkey.onprc_billing.notification.BillingValidationNotification; import org.labkey.onprc_billing.notification.DCMFinanceNotification; @@ -53,6 +57,7 @@ import org.labkey.onprc_billing.security.ONPRCAliasEditorRole; import org.labkey.onprc_billing.security.ONPRCBillingAdminPermission; import org.labkey.onprc_billing.security.ONPRCBillingAdminRole; +import org.labkey.onprc_billing.security.ONPRCVirologyAccessRole; import org.labkey.onprc_billing.table.ChargeableItemsCustomizer; import org.labkey.onprc_billing.table.ONPRC_BillingCustomizer; @@ -71,11 +76,11 @@ public String getName() { return NAME; } - +//This was updated to match all sets @Override public @Nullable Double getSchemaVersion() { - return 12.372; + return 20.516; } @Override @@ -98,6 +103,7 @@ protected void init() RoleManager.registerRole(new ONPRCBillingAdminRole()); RoleManager.registerRole(new ONPRCAliasEditorRole()); + RoleManager.registerRole(new ONPRCVirologyAccessRole()); } @Override @@ -117,6 +123,9 @@ protected void doStartupAfterSpringConfig(ModuleContext moduleContext) EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ChargesFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ReversalFormType.class, this)); + //Added: 5/6/2018 Kollil + EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ChargesVirologyCoreFormType.class, this)); + //NOTE: not really being used, so have disabled //Resource billingTriggers = getModuleResource("/scripts/onprc_billing/billing_triggers.js"); //assert billingTriggers != null; @@ -136,6 +145,9 @@ protected void doStartupAfterSpringConfig(ModuleContext moduleContext) EHRService.get().registerMoreActionsButton(new ChargeEditButton(this, ONPRC_BillingSchema.NAME, ONPRC_BillingSchema.TABLE_CHARGE_RATE_EXEMPTIONS), ONPRC_BillingSchema.NAME, ONPRC_BillingSchema.TABLE_CHARGE_RATE_EXEMPTIONS); EHRService.get().registerMoreActionsButton(new ChargeEditButton(this, ONPRC_BillingSchema.NAME, ONPRC_BillingSchema.TABLE_CHARGE_RATES), ONPRC_BillingSchema.NAME, ONPRC_BillingSchema.TABLE_CHARGE_RATES); EHRService.get().registerMoreActionsButton(new ChargeEditButton(this, ONPRC_BillingSchema.NAME, ONPRC_BillingSchema.TABLE_CREDIT_ACCOUNT), ONPRC_BillingSchema.NAME, ONPRC_BillingSchema.TABLE_CREDIT_ACCOUNT); + QueryService.get().registerPassthroughMethod("RateCalc","onprc_ehr",JdbcType.DOUBLE,5,5); + + } @Override diff --git a/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormSection.java b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormSection.java index a736fe454..0c4ccdac1 100644 --- a/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormSection.java +++ b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormSection.java @@ -18,8 +18,11 @@ import org.labkey.api.ehr.EHRService; import org.labkey.api.ehr.dataentry.SimpleFormSection; import org.labkey.api.view.template.ClientDependency; +import org.json.JSONObject; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; import java.util.Collections; +import java.util.List; /** * User: bimber @@ -40,4 +43,24 @@ public ChargesFormSection(EHRService.FORM_SECTION_LOCATION location) setClientStoreClass("EHR.data.MiscChargesClientStore"); addClientDependency(ClientDependency.supplierFromPath("ehr/data/MiscChargesClientStore.js")); } + // Added: 3-8-2018 R.Blasa + @Override + public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) + { + JSONObject jsonObject = super.toJSON(ctx, includeFormElements); + jsonObject.put("topAndBottomButtons", true); + return jsonObject; + } + + + + @Override + public List getTbarButtons() + { + List defaultButtons = super.getTbarButtons(); + defaultButtons.remove("ADDANIMALS"); + defaultButtons.add(0, "ADDANIMALST"); + + return defaultButtons; + } } diff --git a/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormType.java b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormType.java index a97bbc4b5..8c8181987 100644 --- a/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormType.java +++ b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesFormType.java @@ -6,7 +6,11 @@ import org.labkey.api.ehr.dataentry.TaskForm; import org.labkey.api.ehr.dataentry.TaskFormSection; import org.labkey.api.module.Module; +import org.labkey.api.security.Group; +import org.labkey.api.security.GroupManager; +import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.view.template.ClientDependency; +import org.labkey.security.xml.GroupEnumType; import java.util.Arrays; import java.util.List; @@ -41,4 +45,29 @@ protected List getMoreActionButtonConfigs() return defaultButtons; } + + //Added: 8-22-2018 R.Blasa + @Override + public boolean isVisible() + { + Group g = GroupManager.getGroup(getCtx().getContainer(), "SLA Users", GroupEnumType.SITE); + if (g != null && getCtx().getUser().isInGroup(g.getUserId()) && !getCtx().getContainer().hasPermission(getCtx().getUser(), AdminPermission.class)) + { + return false; + } +// Added: 12-3-2019 R.blasa + Group j = GroupManager.getGroup(getCtx().getContainer(), "Pathology External Entry", GroupEnumType.SITE); + if (j != null && getCtx().getUser().isInGroup(j.getUserId()) && !getCtx().getContainer().hasPermission(getCtx().getUser(), AdminPermission.class)) + { + return false; + } + + // Added: 12-3-2019 R.blasa + Group L = GroupManager.getGroup(getCtx().getContainer(), "Virology Core", GroupEnumType.SITE); + if (L != null && getCtx().getUser().isInGroup(L.getUserId()) && !getCtx().getContainer().hasPermission(getCtx().getUser(), AdminPermission.class)) + { + return false; + } + return super.isVisible(); + } } diff --git a/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesVirologyCoreFormSection.java b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesVirologyCoreFormSection.java new file mode 100644 index 000000000..9e91fc4cd --- /dev/null +++ b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesVirologyCoreFormSection.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2013 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_billing.dataentry; + +import org.labkey.api.data.TableInfo; +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.SimpleFormSection; +import org.labkey.api.query.FieldKey; +import org.labkey.api.view.template.ClientDependency; + +import java.util.Collections; +import java.util.List; + + +public class ChargesVirologyCoreFormSection extends SimpleFormSection +{ + public ChargesVirologyCoreFormSection() + { + this(EHRService.FORM_SECTION_LOCATION.Body); + } + + public ChargesVirologyCoreFormSection(EHRService.FORM_SECTION_LOCATION location) + { + super("onprc_billing", "miscCharges", "Virology Charges", "ehr-gridpanel", location); + //super("onprc_billing", "virologyCharges", "Virology Charges", "ehr-gridpanel", location); + setConfigSources(Collections.singletonList("Task")); + setClientStoreClass("EHR.data.MiscChargesClientStore"); + addClientDependency(ClientDependency.supplierFromPath("ehr/data/MiscChargesClientStore.js")); + +// setClientStoreClass("EHR.data.VirologyChargesClientStore"); +// addClientDependency(ClientDependency.fromPath("ehr/data/VirologyChargesClientStore.js")); + + addClientDependency(ClientDependency.supplierFromPath("onprc_billing/model/sources/VirologyMisc.js")); + addConfigSource("VirologyMisc"); + } + + @Override + protected List getFieldKeys(TableInfo ti) + { + List result = super.getFieldKeys(ti); + + result.add(10,FieldKey.fromParts("lineItemTotal")); + return result; + } +} + + diff --git a/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesVirologyCoreFormType.java b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesVirologyCoreFormType.java new file mode 100644 index 000000000..ebe351249 --- /dev/null +++ b/onprc_billing/src/org/labkey/onprc_billing/dataentry/ChargesVirologyCoreFormType.java @@ -0,0 +1,66 @@ +package org.labkey.onprc_billing.dataentry; + +import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.FormSection; +import org.labkey.api.ehr.dataentry.TaskForm; +import org.labkey.api.ehr.dataentry.TaskFormSection; +import org.labkey.api.module.Module; +import org.labkey.api.view.template.ClientDependency; +import org.labkey.onprc_billing.security.ONPRCBillingAdminPermission; +import org.labkey.onprc_billing.security.ONPRCVirologyCoreEntryPermission; +import org.labkey.security.xml.GroupEnumType; +import org.labkey.api.security.GroupManager; +import org.labkey.api.security.permissions.AdminPermission; +import org.labkey.api.security.Group; + +import java.util.Arrays; +import java.util.List; + + +public class ChargesVirologyCoreFormType extends TaskForm +{ + public static final String NAME = "VirologyCoreCharges"; + + public ChargesVirologyCoreFormType(DataEntryFormContext ctx, Module owner) + { + super(ctx, owner, NAME, "Virology Charges", "Billing - Virology Core", Arrays.asList( + new TaskFormSection(), +// new AnimalDetailsFormSection(), + new ChargesInstructionFormSection(), + new ChargesVirologyCoreFormSection() + )); + + addClientDependency(ClientDependency.supplierFromPath("onprc_billing/panel/ChargesInstructionPanel.js")); + } + + + + @Override + protected List getMoreActionButtonConfigs() + { + List defaultButtons = super.getMoreActionButtonConfigs(); + defaultButtons.add("COPY_TASK"); + + return defaultButtons; + } + +// Added: 12-3-2019 R.Blasa +@Override +public boolean canInsert() +{ + if (!getCtx().getContainer().hasPermission(getCtx().getUser(), ONPRCVirologyCoreEntryPermission.class)) + return false; + + return super.canInsert(); +} + + @Override + public boolean canRead() + { + if (!getCtx().getContainer().hasPermission(getCtx().getUser(), ONPRCVirologyCoreEntryPermission.class)) + return false; + + return super.canRead(); + } +} diff --git a/onprc_billing/src/org/labkey/onprc_billing/notification/FinanceNotification.java b/onprc_billing/src/org/labkey/onprc_billing/notification/FinanceNotification.java index 99d2bfd3f..2c4548de4 100644 --- a/onprc_billing/src/org/labkey/onprc_billing/notification/FinanceNotification.java +++ b/onprc_billing/src/org/labkey/onprc_billing/notification/FinanceNotification.java @@ -21,6 +21,8 @@ import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.CompareType; import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerFilter; +import org.labkey.api.data.ContainerFilterable; import org.labkey.api.data.Results; import org.labkey.api.data.ResultsImpl; import org.labkey.api.data.SQLFragment; @@ -189,6 +191,10 @@ public String getMessageBodyHTML(Container c, User u) getExpiredCreditAliases(ehrContainer, u, msg); getCreditAliasesDisabled(ehrContainer, u, msg); chargesMissingRates(financeContainer, u, msg); + + //Added by Kollil + getSchedulerAliases(ehrContainer, u, msg); + surgeriesNotBilled(ehrContainer, u, start, endDate, msg); simpleAlert(financeContainer, u , msg, "onprc_billing", "invalidChargeRateEntries", " charge rate records with invalid or overlapping intervals. This indicates a problem with how the records are setup in the system and may cause problems with the billing calculation."); simpleAlert(financeContainer, u , msg, "onprc_billing", "invalidChargeRateExemptionEntries", " charge rate exemptions with invalid or overlapping intervals. This indicates a problem with how the records are setup in the system and may cause problems with the billing calculation."); @@ -789,4 +795,28 @@ private void getProjectsNotActive(Container c, User u, StringBuilder msg) msg.append("
"); } } + + private void getSchedulerAliases(Container c, User u, StringBuilder msg) + { + + if (QueryService.get().getUserSchema(u, c, "extscheduler") == null) + { + msg.append("Warning: the extscheduler schema has not been enabled in this folder, so the alias alert cannot run


"); + return; + } + + TableInfo ti = QueryService.get().getUserSchema(u, c, "extscheduler").getTable("SchedulerAliases"); + ((ContainerFilterable) ti).setContainerFilter(ContainerFilter.Type.AllFolders.create(c, u)); + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("Alias"), null, CompareType.NONBLANK); + TableSelector ts = new TableSelector(ti, filter, null); + long count = ts.getRowCount(); + if (count > 0) + { + msg.append("Warning: In Resource Scheduler, there are " + count + " invalid Aliases.

"); + msg.append("Click here to view them"); + msg.append("


"); + } + + } + } diff --git a/onprc_billing/src/org/labkey/onprc_billing/security/ONPRCVirologyAccessRole.java b/onprc_billing/src/org/labkey/onprc_billing/security/ONPRCVirologyAccessRole.java new file mode 100644 index 000000000..a32a0ab34 --- /dev/null +++ b/onprc_billing/src/org/labkey/onprc_billing/security/ONPRCVirologyAccessRole.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_billing.security; + +import org.labkey.api.data.Container; +import org.labkey.api.ehr.security.EHRProjectEditPermission; +import org.labkey.api.module.ModuleLoader; +import org.labkey.api.security.SecurableResource; +import org.labkey.api.security.SecurityPolicy; +import org.labkey.api.security.permissions.DeletePermission; +import org.labkey.api.security.permissions.InsertPermission; +import org.labkey.api.security.permissions.ReadPermission; +import org.labkey.api.security.permissions.UpdatePermission; +import org.labkey.api.security.roles.AbstractModuleScopedRole; +import org.labkey.api.security.roles.AbstractRole; +import org.labkey.onprc_billing.ONPRC_BillingModule; + +/** + * User: bimber + * Date: 1/7/13 + * Time: 4:53 PM + */ +public class ONPRCVirologyAccessRole extends AbstractModuleScopedRole +{ + public ONPRCVirologyAccessRole() + { + super("ONPRC Billing VirologyCore Entry", "Users with this role are able to make changes to the billing and finance tables", ONPRC_BillingModule.class, + ReadPermission.class, + InsertPermission.class, + UpdatePermission.class, + DeletePermission.class, + ONPRCVirologyCoreEntryPermission.class + + ); + } +} diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.327-12.328.sql b/onprc_billing/src/org/labkey/onprc_billing/security/ONPRCVirologyCoreEntryPermission.java similarity index 63% rename from onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.327-12.328.sql rename to onprc_billing/src/org/labkey/onprc_billing/security/ONPRCVirologyCoreEntryPermission.java index 7dc71f230..b852ba34b 100644 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.327-12.328.sql +++ b/onprc_billing/src/org/labkey/onprc_billing/security/ONPRCVirologyCoreEntryPermission.java @@ -13,9 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -ALTER TABLE onprc_billing.miscCharges ADD objectid entityid NOT NULL; +package org.labkey.onprc_billing.security; -GO -EXEC core.fn_dropifexists 'miscCharges', 'onprc_billing', 'CONSTRAINT', 'pk_miscCharges'; +import org.labkey.api.security.permissions.AbstractPermission; + +//Created: 12-3-2019 R.Blasa +public class ONPRCVirologyCoreEntryPermission extends AbstractPermission +{ + public ONPRCVirologyCoreEntryPermission() + { + super("ONPRCVirologyCoreEntryPermission", "Can insert charges in the EHR"); + } +} -ALTER TABLE onprc_billing.miscCharges ADD CONSTRAINT pk_miscCharges PRIMARY KEY (objectid); \ No newline at end of file diff --git a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHIndustryRates.query.xml b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHIndustryRates.query.xml index 253897053..aad927725 100644 --- a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHIndustryRates.query.xml +++ b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHIndustryRates.query.xml @@ -6,53 +6,56 @@ NIH Industrial Rates - - - - Current Year - $#,##0.00 - - - - YR58: 5/1/17 to 4/30/18 - $#,##0.00 - - - YR59: 5/1/18 to 4/30/19 - $#,##0.00 - - - YR60: 5/1/19 to 4/30/20 - $#,##0.00 - - - YR61: 5/1/20 to 4/30/21 - $#,##0.00 - - - YR62: 5/1/21 to 4/30/22 - $#,##0.00 - - - YR63: 5/1/22 to 4/30/23 - $#,##0.00 - - - YR64: 5/1/23 to 4/30/24 - $#,##0.00 - - - - YR65: 5/1/24 to 4/30/25 - $#,##0.00 - - - - Posted Date - MM/dd/yyyy - - - + + + + Current Year + $#,##0.00 + + + + YR62: 5/1/21 to 4/30/22 + $#,##0.00 + + + YR63: 5/1/22 to 4/30/23 + $#,##0.00 + + + YR64: 5/1/23 to 4/30/24 + $#,##0.00 + + + YR65: 5/1/24 to 4/30/25 + $#,##0.00 + + + YR66: 5/1/25 to 4/30/26 + $#,##0.00 + + + + YR67: 5/1/26 to 4/30/27 + $#,##0.00 + + + + YR68: 5/1/27 to 4/30/28 + $#,##0.00 + + + YR69: 5/1/28 to 4/30/29 + $#,##0.00 + + + + + + Posted Date + MM/dd/yyyy + + + diff --git a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateConfig.query.xml b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateConfig.query.xml index f8fb313a4..943a1fd76 100644 --- a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateConfig.query.xml +++ b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateConfig.query.xml @@ -6,54 +6,56 @@ NIH Project Rate Config - - - - - Current Year - $#,##0.00 - - - - 5/1/2017 to 4/30/2018 - $###0.00 - - - 5/1/2018 to 4/30/2019 - $###0.00 - - - 5/1/2019 to 4/30/2020 - $###0.00 - - - 5/1/2020 to 4/30/2021 - $###0.00 - - - 5/1/2021 to 4/30/2022 - $###0.00 - - - 5/1/2022 to 4/30/2023 - $###0.00 - - - 5/1/2023 to 4/30/2024 - $###0.00 - - - - 5/1/2024 to 4/30/2025 - $###0.00 - - - - Posted Date - MM/dd/yyyy - - - + + + + Current Year + $#,##0.00 + + + + YR62: 5/1/21 to 4/30/22 + $#,##0.00 + + + YR63: 5/1/22 to 4/30/23 + $#,##0.00 + + + YR64: 5/1/23 to 4/30/24 + $#,##0.00 + + + YR65: 5/1/24 to 4/30/25 + $#,##0.00 + + + YR66: 5/1/25 to 4/30/26 + $#,##0.00 + + + + YR67: 5/1/26 to 4/30/27 + $#,##0.00 + + + + YR68: 5/1/27 to 4/30/28 + $#,##0.00 + + + YR69: 5/1/28 to 4/30/29 + $#,##0.00 + + + + + + Posted Date + MM/dd/yyyy + + + diff --git a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet.query.xml b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet.query.xml index 2cb976f4c..c65f15585 100644 --- a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet.query.xml +++ b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet.query.xml @@ -8,52 +8,59 @@ - + Current Year $#,##0.00 + + + + + - YR58: 5/1/17 to 4/30/18 + YR62: 5/1/21 to 4/30/22 $#,##0.00 - YR59: 5/1/18 to 4/30/19 + YR63: 5/1/22 to 4/30/23 $#,##0.00 - YR60: 5/1/19 to 4/30/20 + YR64: 5/1/23 to 4/30/24 $#,##0.00 - YR61: 5/1/20 to 4/30/21 + YR65: 5/1/24 to 4/30/25 $#,##0.00 - YR62: 5/1/21 to 4/30/22 + YR66: 5/1/25 to 4/30/26 $#,##0.00 + - YR63: 5/1/22 to 4/30/23 + YR67: 5/1/26 to 4/30/27 $#,##0.00 + - YR64: 5/1/23 to 4/30/24 + YR68: 5/1/27 to 4/30/28 $#,##0.00 - - YR65: 5/1/24 to 4/30/25 + YR69: 5/1/28 to 4/30/29 $#,##0.00 + + Posted Date MM/dd/yyyy - diff --git a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet/.qview.xml b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet/.qview.xml index 1cd7ebb69..0bcc0e520 100644 --- a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet/.qview.xml +++ b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRateSheet/.qview.xml @@ -2,49 +2,50 @@ - + - + + - + - + - + - + - + - + - + diff --git a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.query.xml b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.query.xml index b373a5bfb..9afb7bc29 100644 --- a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.query.xml +++ b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.query.xml @@ -8,45 +8,48 @@ - + Current Year $#,##0.00 - YR58: 5/1/17 to 4/30/18 + YR62: 5/1/21 to 4/30/22 $#,##0.00 - YR59: 5/1/18 to 4/30/19 + YR63: 5/1/22 to 4/30/23 $#,##0.00 - YR60: 5/1/19 to 4/30/20 + YR64: 5/1/23 to 4/30/24 $#,##0.00 - YR61: 5/1/20 to 4/30/21 + YR65: 5/1/24 to 4/30/25 $#,##0.00 - YR62: 5/1/21 to 4/30/22 + YR66: 5/1/25 to 4/30/26 $#,##0.00 + - YR63: 5/1/22 to 4/30/23 + YR67: 5/1/26 to 4/30/27 $#,##0.00 + - YR64: 5/1/23 to 4/30/24 + YR68: 5/1/27 to 4/30/28 $#,##0.00 - - YR65: 5/1/24 to 4/30/25 + YR69: 5/1/28 to 4/30/29 $#,##0.00 + + Posted Date MM/dd/yyyy diff --git a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.sql b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.sql index 2d5c640ed..e9d5e4447 100644 --- a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.sql +++ b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA.sql @@ -1,14 +1,16 @@ PARAMETERS (ProjectFA DOUBLE DEFAULT .2) SELECT n.category, -n.name, -(n.UnitCost *(1+(.47 - ProjectFA))) as CurrentYear, -(n.year1 *(1+(.47 - ProjectFA))) as Year1, -(n.year2 *(1+(.47 - ProjectFA))) as Year2, -(n.year3 *(1+(.47 - ProjectFA))) as Year3, -(n.year4 *(1+(.47 - ProjectFA))) as Year4, -(n.year5 *(1+(.47 - ProjectFA))) as Year5, -(n.year6 *(1+(.47 - ProjectFA))) as Year6, -(n.year7 *(1+(.47 - ProjectFA))) as Year7, -(n.year8 *(1+(.47 - ProjectFA))) as Year8, -n.PostedDate + n.name, + n.unitcost, + (1.47 / (1 + ProjectFA)) as NewRateCalc, + (n.UnitCost *(1.47 / (1 + ProjectFA))) as CurrentYear, + (n.year1 *(1.47 / (1 + ProjectFA))) as Year1, + (n.year2 *(1.47 / (1 + ProjectFA))) as Year2, + (n.year3 *(1.47 / (1 + ProjectFA))) as Year3, + (n.year4 *(1.47 / (1 + ProjectFA))) as Year4, + (n.year5 *(1.47 / (1 + ProjectFA))) as Year5, + (n.year6 *(1.47 / (1 + ProjectFA))) as Year6, + (n.year7 *(1.47 / (1 + ProjectFA))) as Year7, + (n.year8 *(1.47 / (1 + ProjectFA))) as Year8, + n.PostedDate FROM NIHRateConfig n \ No newline at end of file diff --git a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA/.qview.xml b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA/.qview.xml index 27e26da8a..784e8e236 100644 --- a/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA/.qview.xml +++ b/onprc_billingpublic/resources/queries/onprc_billing_public/NIHRates_ReducedFA/.qview.xml @@ -2,51 +2,48 @@ - + - - - - - - + + + - + - + - + - + - + + diff --git a/onprc_ehr/resources/data/AcquistionType.tsv b/onprc_ehr/resources/data/AcquistionType.tsv new file mode 100644 index 000000000..c009e9f45 --- /dev/null +++ b/onprc_ehr/resources/data/AcquistionType.tsv @@ -0,0 +1,3 @@ +value +Pending Arrival +Acquired \ No newline at end of file diff --git a/onprc_ehr/resources/data/lookup_sets.tsv b/onprc_ehr/resources/data/lookup_sets.tsv index b6b268bbb..0ecdc8b18 100644 --- a/onprc_ehr/resources/data/lookup_sets.tsv +++ b/onprc_ehr/resources/data/lookup_sets.tsv @@ -2,7 +2,7 @@ setname label keyfield titleColumn PregnancyConfirm Pregnancy Confirmation Types housingDefinition Housing Definition housingTypes Housing Types -AcquistionType Acquistion Types +AcquistionType Acquistion Types value RearingType Rearing Types MatingType Mating Types pairingEventType Pairing Event Types value diff --git a/onprc_ehr/resources/etl/deprecated/AntibioticSensitivity.sql b/onprc_ehr/resources/etl/deprecated/AntibioticSensitivity.sql deleted file mode 100644 index 4b440d7f0..000000000 --- a/onprc_ehr/resources/etl/deprecated/AntibioticSensitivity.sql +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(h.AnimalID as nvarchar(4000)) as Id, - h.date, - h.Microbe, - s2.Description as MicrobeMeaning, - - --d.ClinicalKey as ClinicalKey, - d.Antibiotic as Antibiotic , - - -- original usage: Flag = 0 Resistant to Antibiotics, Flag = 1 not Resistant to Antibiotics - -- converted to the reverse - CASE - when d.ResistanceFlag = 1 then 0 - when d.ResistanceFlag = 0 then 1 - end as Resistant, - CASE - when d.ResistanceFlag = 1 then 'Sensitive' - when d.ResistanceFlag = 0 then 'Resistant' - end as result, - --d.ResistanceFlag as Resistant, - - d.ts as rowversion, - d.objectid, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy , - h.objectid as runid - -FROM Cln_AntibioticSensData d -left join Cln_AntibioticSensHeader h on (d.ClinicalKey = h.ClinicalKey) -LEFT JOIN Ref_Technicians rt ON (rt.ID = h.Technician) -left join ref_snomed s1 on (s1.SnomedCode = h.Tissue) -left join ref_snomed s2 on (s2.SnomedCode = h.microbe) - -where d.ts > ? or h.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Arrival.sql b/onprc_ehr/resources/etl/deprecated/Arrival.sql deleted file mode 100644 index 775043b28..000000000 --- a/onprc_ehr/resources/etl/deprecated/Arrival.sql +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(AnimalID as nvarchar(4000)) as Id, - Date as Date, - - (SELECT rowid FROM labkey.ehr_lookups.lookups l WHERE l.set_name = 'AcquistionType' and l.value = s1.value) as AcquisitionType, - s1.Value as AcquisitionTypeMeaning, - - (SELECT rowid FROM labkey.ehr_lookups.lookups l WHERE l.set_name = 'RearingType' and l.value = s2.value) as RearingType, - s2.Value as RearingTypeMeaning, - - Afc.ISISInstitute as source, - Remarks as Remark, - Refis.GeographicName as geographic_origin, - oldIdNumber as originalId, - - --TODO: add these fields?? - s3.Value as AcquisitionAge, - NonISISSource as NonISISSource , - - CASE - WHEN (RefLoc.Location = 'No Location') then null - else RefLoc.Location - END as initialRoom, - rtrim(ltrim(rtrim(Refrow.row) + convert(char(2), RefRow.Cage))) As initialCage, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - Afc.objectid - --Afc.ts as rowversion - -From Af_Acquisition Afc -LEFT JOIN Sys_parameters s1 ON (s1.Field = 'AcquistionType' AND s1.Flag = Afc.AcquisitionType) -LEFT JOIN Sys_parameters s2 ON (s2.Flag = afc.RearingType and s2.Field = 'RearingType') -LEFT JOIN Sys_parameters s3 ON (s3.Flag = afc.AcquisitionAge and s3.Field = 'AcquisitionAge') -LEFT JOIN Ref_Technicians rt ON (rt.ID = Afc.Technician) -LEFT JOIN Sys_parameters s4 ON (s4.Field = 'DepartmentCode' and s4.Flag = rt.DeptCode) -LEFT JOIN Ref_RowCage RefRow ON (RefRow.CageID = Afc.InitialLocID) -LEFT JOIN Ref_Location RefLoc ON (RefRow.LocationID = RefLoc.LocationID) -LEFT JOIN Ref_IsisGeographic RefIs ON (Afc.GeographicOrigin = RefIs.GeographicCode) -LEFT JOIN Ref_IsisInstitution RefTT ON (afc.ISISInstitute = RefTT.Institutioncode) - -WHERE afc.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Assignment.sql b/onprc_ehr/resources/etl/deprecated/Assignment.sql deleted file mode 100644 index 3b82b3e13..000000000 --- a/onprc_ehr/resources/etl/deprecated/Assignment.sql +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(af.AnimalID as nvarchar(4000)) as Id, - af.ProjectID as Project, - --RefProj.Title, - - ----- Ref_ProjectsIacuc (ProjectID) - AssignDate as Date, --- ReleaseDate as Enddate, - - coalesce(ReleaseDate, q.deathdate, q.departuredate) as enddate , - estimatedreleasedate as projectedRelease, - - AssignPool as assignCondition, --Ref_Pool - EstimatedReleasePool as projectedReleaseCondition, --Ref_Pool - ActualReleasePool as releaseCondition, -- - --- -- --NOTE: according to raymond replacementFlag is not in use and can be ignored --- ReplacementFlag as ReplacementFlagRaw, --- s1.Value as ReplacementFlag, - - af.objectid - --af.ts as rowversion - -From Af_Assignments af - -LEFT JOIN Ref_ProjectsIacuc RefProj ON (RefProj.ProjectID = af.ProjectID) -LEFT JOIN Ref_Pool p1 ON (p1.PoolCode = AssignPool) -LEFT JOIN Ref_Pool p2 ON (p2.PoolCode = EstimatedReleasePool) -LEFT JOIN Ref_Pool p3 ON (p3.PoolCode = ActualReleasePool) -LEFT JOIN Sys_Parameters s1 ON (field = 'ReplacementFlag' and Flag = ReplacementFlag) -left join Af_Qrf q on (q.animalid = af.animalid) - -WHERE (af.ts > ? or q.ts > ?) diff --git a/onprc_ehr/resources/etl/deprecated/Birth.sql b/onprc_ehr/resources/etl/deprecated/Birth.sql deleted file mode 100644 index b722c51a7..000000000 --- a/onprc_ehr/resources/etl/deprecated/Birth.sql +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(AnimalID as nvarchar(4000)) as Id, - Date as Date, - s1.Value as type, - s2.Value as cond, - Birth_Weight As Weight, - - case - WHEN MotherID = 0 THEN null - ELSE MotherID - END As Dam, - case - WHEN FatherID = 0 THEN null - ELSE FatherID - END As Sire, - Remarks As Remark, - - --TODO: add these? - l1.Location as DeliveryLocationRoom, - rtrim(ltrim(rtrim(r1.row) + convert(char(2), r1.Cage))) As DeliveryLocationCage, - - l2.Location as room, - rtrim(ltrim(rtrim(r2.row) + convert(char(2), r2.Cage))) As cage, - - - ConceptualAge as ConceptualAge, - s3.Value as ConceptualAgeDeterm, - - --BirthType as BirthTypeInt, - (SELECT rowid from labkey.ehr_lookups.lookups l WHERE l.set_name = 'birth_condition' AND l.value = s2.value) as birthCondition, - --BirthCondition As BirthConditionInt, - --ConceptualAgeDeterm as ConceptualAgeDetermInt, - --BirthWtDescription as BirthWtDescriptionInt, - s4.Value as BirthWtDescription, - --DeliveryLocation As DeliveryLocationInt, - --AssignedLocation As AssignedLocationInt, - --- -- ?? As Conception, -- what is column 'conception' - - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - --afb.ts as rowversion, - afb.objectid - -FROM Af_Birth afb - -left join Sys_Parameters s1 on ( s1.Field = 'BirthType' and s1.Flag = afb.BirthType) -left join Sys_Parameters s2 on (s2.Field = 'BirthCondition' and s2.Flag = afb.BirthCondition) -left join Sys_Parameters s3 on (s3.Field = 'ConceptualAgeDeterm' and s3.Flag = afb.ConceptualAgeDeterm) -left join Sys_Parameters s4 on (s4.Field = 'BirthWtDescription' and s4.Flag = afb.BirthWtDescription) -left join Ref_Technicians rt on ( afb.Technician = rt.ID) -left join Sys_Parameters s5 on (s5.Field = 'DepartmentCode' and s5.Flag = rt.DeptCode ) -left join Ref_RowCage r1 on (r1.CageID = afb.DeliveryLocation) -left Join Ref_Location l1 on (r1.LocationID = l1.LocationId ) -left join Ref_RowCage r2 on (r2.CageID = afb.AssignedLocation) -left join Ref_Location l2 on (r2.LocationID = l2.LocationId) - -where afb.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Cases.sql b/onprc_ehr/resources/etl/deprecated/Cases.sql deleted file mode 100644 index 3158bf1f6..000000000 --- a/onprc_ehr/resources/etl/deprecated/Cases.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - afc.CaseID as CaseID, - cast(afc.AnimalID as nvarchar(4000)) as Id, - OpenDate as date , - --Status as StatusInt , - -- s1.Value as Status, --- CloseDate as enddate , - - coalesce(CloseDate, q.deathdate, q.departuredate) as enddate , - - ReviewDate as ReviewDate , - --GroupCode as GroupCode, ---- gCaseTypeConst: Clinical = 1, Surgery = 2, BehaviorCase = 3 - Case - When GroupCode = 1 Then 'Clinical' - When GroupCode = 2 Then 'Surgery' - When GroupCode = 3 Then 'Behavior' - When GroupCode = 4 Then 'Weight' - End AS Category, - (SELECT max(s1.value) expr FROM MasterProblemList ml LEFT JOIN Sys_parameters s1 ON (s1.Field = 'MasterProblemList' and s1.Flag = ml.MasterProblem) WHERE ml.caseid = afc.caseid) as problem, - --ml.objectid as problemId, - - --TODO: what is this second table for (Af_CaseReviewData)? --- af.Closing_Date as Closing_Date , --- af.Review_Date as Review_Date , --- af.Date_Posted as Date_Posted, - - Afc.objectid - - --COUNT(dx.objectid) as dxCount, - --COUNT(cr.objectid) as clinCount, - -From Af_Case afc -LEFT JOIN Sys_Parameters s1 ON (afc.Status = s1.Flag and s1.field = 'CaseStatus') ---LEFT JOIN MasterProblemList ML ON (afc.CaseID = ml.CaseID) -left join Af_Qrf q on (q.animalid = afc.animalid) - -WHERE afc.ts > ? or q.ts > ? diff --git a/onprc_ehr/resources/etl/deprecated/Chemistry Results.sql b/onprc_ehr/resources/etl/deprecated/Chemistry Results.sql deleted file mode 100644 index 97998403e..000000000 --- a/onprc_ehr/resources/etl/deprecated/Chemistry Results.sql +++ /dev/null @@ -1,660 +0,0 @@ -/* - * Copyright (c) 2012-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---Please note: All lab values = -1 is should be substitued with a Null value - -SELECT - --t.ClinicalKey , - cast(t.Id as nvarchar(4000)) as Id, - t.DATE , - t.projectId as project, - - --t.Specimen , -- Specimen database table - --sp.Name, - --sp.SNOMEDCODE as snomed, - t.MethodInt , - s2.Value as Method, - case - when t.Result = -1 then null - else t.Result - end as Result, - t.resultString as stringResults, - - t.TestId, - - t.rowversion, - (cast(t.objectid as varchar(38)) + '_' + t.TestId) as objectid, - null as parentId, - t.objectid as runId - -FROM ( - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Glucose as Result, - null as resultString, - 'GLU' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - BUN as Result, - null as resultString, - 'BUN' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Creatinine as Result, - null as resultString, - 'CREA' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Sodium as Result, - null as resultString, - 'NA' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Potassium as Result, - null as resultString, - 'K' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Chloride as Result, - null as resultString, - 'CL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - TotalProtein as Result , - null as resultString, - 'TP' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Albumin as Result, - null as resultString, - 'ALB' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - AGRatio as Result, - null as resultString, - 'A/G ratio' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Calcium as Result, - null as resultString, - 'Ca' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Phosphorus as Result, - null as resultString, - 'PHOS' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - UricAcid as Reuslt, - null as resultString, - 'UA' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Cholesterol as Result, - null as resultString, - 'CHOL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Triglycerides as Result, - null as resultString, - 'TRIG' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - AlkPhosphotase as Result, - null as resultString, - 'ALKP' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - LDH as Result, - null as resultString, - 'LDH' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - AST as Result, - null as resultString, - 'AST' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - ALT as Result, - null as resultString, - 'ALT' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Iron as Result, - null as resultString, - 'Fe' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - GGT as Result, - null as resultString, - 'GGT' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Globulin as Result, - null as resultString, - 'Glob' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - TotalBilirubin as Result, - null as resultString, - 'TBIL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - DirectBilirubin as Result, - null as resultString, - 'DBIL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - BunCreat as Result, - null as resultString, - 'B/C' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RefAmylase as Result, - null as resultString, - 'Amyl' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RefLipase as Result, - null as resultString, - 'Lip' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RefCPK as Result, - null as resultString, - 'CPK' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - HDL_CHOL as Result, - null as resultString, - 'HDL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - LDL as Result, - null as resultString, - 'LDL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - CHOL_HDL as Result, - null as resultString, - 'CHOL/HDL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - LDL_HDL as Result, - null as resultString, - 'LDL/HDL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - CK as Result, - null as resultString, - 'CPK' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - MG as Result, - null as resultString, - 'MG' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - CRP as Result, - null as resultString, - 'CRP' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - LACT as Result, - null as resultString, - --TODO: review w/ chris - 'LDH' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectid, - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - VLDL_Cholesterol as Result, - null as resultString, - 'VLDL/CHOL' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - -) t - -left join Sys_Parameters s2 on (s2.Flag = t.MethodInt And s2.Field = 'AnalysisMethodBiochem') - -WHERE result != -1 - AND t.rowversion > ? diff --git a/onprc_ehr/resources/etl/deprecated/Clinpath Runs.sql b/onprc_ehr/resources/etl/deprecated/Clinpath Runs.sql deleted file mode 100644 index e69a1fffd..000000000 --- a/onprc_ehr/resources/etl/deprecated/Clinpath Runs.sql +++ /dev/null @@ -1,517 +0,0 @@ -/* - * Copyright (c) 2012-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(Id as varchar(4000)) as Id, - date, - CASE - WHEN projectId IN (470,1173,1455) THEN 625 - ELSE projectId - END as project, - CASE - WHEN (projectId IS NULL AND servicerequested is not null) THEN 'Not Billable' - ELSE null - END as chargetype, - - servicerequested, - category as type, - --CategoryInt , - Category2, - - coalesce(t.Tissue, sp.SNOMEDCODE) as tissue, - Method, - collectionMethod, - - remarks as remark, - - case - WHEN TechLastName = 'Unassigned' or TechFirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(TechLastName) > 0 AND datalength(TechFirstName) > 0 AND datalength(TechInitials) > 0 THEN - TechLastName + ', ' + TechFirstName + ' (' + TechInitials + ')' - WHEN datalength(TechLastName) > 0 AND datalength(TechFirstName) > 0 THEN - TechLastName + ', ' + TechFirstName - WHEN datalength(TechLastName) > 0 AND datalength(TechInitials) > 0 THEN - TechLastName + ' (' + TechInitials + ')' - WHEN datalength(TechInitials) = 0 OR Techinitials = ' ' OR TechLastName = ' none' THEN - null - else - TechInitials - END as performedBy, - - --t.rowversion, - t.objectid - -FROM ( - ---AntibioticSensitivity -SELECT - ClinicalKey as ClinicalKey , - AnimalID as Id , - DATE as Date , - null as projectId, - 'Antibiotic Sensitivity' as category, - 'Antibiotic Sensitivity' as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - s4.Value as Department, - Specimen as Specimen , ---- information not required - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - cln.tissue as Tissue, - null as remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_AntibioticSensHeader cln - left join Ref_Technicians rt on (cln.Technician = rt.ID) - left join Sys_parameters s1 on (s1.Field = 'RequestCategory'and s1.Flag = Cln.Category) - left join Sys_parameters s2 on (s2.Field = 'AnalysisMethodAntibiotic'and s2.Flag = Cln.Method) - left join Sys_parameters s3 on (s3.Field = 'AnimalConditionLab'And s3.Flag = Cln.Condition) - left join Sys_Parameters s4 on (s4.Field = 'DepartmentCode' and s4.Flag = Rt.Deptcode) - - ---biochem -union all - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - projectId, - 'Biochemistry' as category, - CASE - WHEN cln.panelflag = 15 THEN 'Basic Chemistry Panel in-house' - WHEN cln.panelflag = 13 THEN 'Comprehensive Chemistry Panel in-house' - WHEN cln.panelflag = 14 THEN 'Lipid panel in-house: Cholesterol, Triglyceride, HDL, LDL' - WHEN cln.panelflag = 16 THEN 'High-density lipoprotein & Low-density lipoprotein (HDL & LDL)' - WHEN cln.panelflag = 17 THEN 'Albumin' - WHEN cln.panelflag = 18 THEN 'Amylase' - WHEN cln.panelflag = 16 THEN 'Lipase' - ELSE null - END as servicerequested, --panelflag - Category as CategoryInt , - s1.Value as Category2, - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - s4.Value as Department, - - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - null as Tissue, - Remarks as Remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_Biochemistry cln - - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethodBiochem') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - ---iSTAT -union all - -SELECT - IDKey, - AnimalID as Id , - DATE , - null as projectId, - 'iSTAT' as category, - null as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - s4.Value as Department, - - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - null as Tissue, - null as remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethodIStat') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - - ---occult blood -union all - -SELECT - ClinicalKey as ClinicalKey , - AnimalID as Id , - Date as Date , - projectId, - 'Misc Tests' as category, - 'Occult Blood' as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - --DeptCode as DepartmentCodeInt, - s4.Value as DepartmentCode, - - Specimen as Specimen , ----- Specimen database table - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - null as Tissue, - Remarks as Remarks, - cln.ts as rowversion, - cln.objectid - -FROM Cln_OccultBlood cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethod') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - - -UNION ALL - -SELECT - ClinicalKey AS ClinicalKey , - AnimalID as Id , - Date, - projectId, - 'Hematology' as category, - CASE - WHEN ManualDiff = 1 THEN 'WBC differential' - WHEN ManualDiff = 2 THEN 'Reticulocyte count' - ELSE 'CBC with automated differential' - END as servicerequested, - - Category as CategoryInt , - s1.Value as Category2, - - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - s4.Value as Department, - - Specimen , ----- Specimen database table - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - null as Tissue, - REMARKS as REMARKS, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_Hematology cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethodHematology') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - -UNION ALL - -SELECT - ClinicalKey, - AnimalID as Id , - DATE, - null as projectId, - 'Cerebral Spinal Fluid' as category, - null as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - s4.Value as Department, - - Specimen as Specimen , -------- Specimen database table - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - null as Tissue, - REMARKS as REMARKS, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_CerebralspinalFluid cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethodHematology') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - ---microbiology -UNION ALL - -SELECT - ClinicalKey as ClinicalKey , - AnimalID as Id , - DATE as Date , - projectId, - 'Microbiology' as category, - null as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - --DeptCode as DepartmentCodeInt, - s4.Value as DepartmentCode, - - Specimen as Specimen , ------ Specimen Database table - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - Tissue as Tissue, --- Ref_SnomedLists - null as remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_MicrobiologyHeader cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethod') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - -UNION ALL - -SELECT - ClinicalKey as ClinicalKey , - AnimalID as Id , - DATE as Date , - projectId, - 'Misc Tests' as category, - null as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - --DeptCode as DepartmentCodeInt, - s4.Value as Department, - - Specimen as Specimen , - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - Tissue as Tissue, ----- Ref_Snomedlists - null as remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_RareTestHeader cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethod') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - - ---virology - -UNION ALL - -SELECT - ClinicalKey as ClinicalKey , - AnimalID as Id , - DATE as DATE , - null as projectId, - 'Serology' as category, - null as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - --DeptCode as DepartmentCodeInt, - s4.Value as DepartmentCode, - Specimen as Specimen , ----- database table called Specimen - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - null as Tissue, - null as remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_VirologyHeader cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethodHematology') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - -UNION ALL - -SELECT - ClinicalKey as ClinicalKey , - AnimalID as ID, - DATE as Date , - null as projectId, - 'Serology' as category, - null as servicerequested, - Category as CategoryInt , - s1.Value as Category2, - - Technician As TechnicianID, - LastName as TechLastName, - FirstName as TechFirstName, - Initials as TechInitials, - --DeptCode as DepartmentCodeInt, - s4.Value as DepartmentCode, - - null as Specimen , - Method as MethodInt , - s2.Value as Method, - null as collectionMethod, - - null as tissue, - null as remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_SerologyHeader cln - left join Ref_Technicians rt on (Cln.Technician = rt.ID) - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethod') - left join Sys_Parameters s3 on (s3.Flag = Cln.Condition And s3.Field = 'AnimalConditionLab') - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - ---urinalysis -UNION ALL - -SELECT - ClinicalKey as ClinicalKey , - AnimalID as Id , - DATE as Date , - projectId, - 'Urinalysis' as category, - 'Urinalysis' as servicerequested, - - Category as CategoryInt , - s1.Value as Category2, - cln.Technician As TechnicianID, --Ref_Technicians - rt.LastName as TechLastName, - rt.FirstName as TechFirstName, - rt.Initials as TechInitials, - --rt.DeptCode as DepartmentCodeInt, - s15.Value as Department, - Specimen as Specimen , --database table called Specimen - Method as MethodInt , - s2.Value as Method, - s5.value as collectionMethod, - null as tissue, - Remarks as Remarks, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln - left join Ref_Technicians rt on ( cln.Technician = rt.ID) - left join Sys_parameters s1 on (s1.Field = 'RequestCategory' and s1.Flag = Category) - left join Sys_parameters s2 on (s2.Field = 'AnalysisMethodUrinalysis' and s2.Flag = Method) - left join Sys_parameters s3 on (s3.Field = 'AnimalConditionLab'and s3.Flag = Condition) --- left join Sys_parameters s4 on (s4.Field = 'UrineAppearance' and s4.Flag = Appearance) - left join Sys_parameters s5 on (s5.Field = 'UrineCollection' and s5.Flag = Collection) - left join Sys_parameters s15 on (s15.Field = 'DepartmentCode' and s15.Flag = rt.DeptCode) - ---parasitology -UNION all - -Select - ClinicalKey, - AnimalID, - date, - projectId, - 'Parasitology' as category, - 'Fecal parasite exam' as servicerequested, - Category as CategoryInt, - s1.Value as category2, - Technician as TechnicianId, - LastName as LastName, - FirstName as FirstName, - Initials as Initials, - s4.Value as Department, - - Specimen , ----- Specimen database table - Method as methodInt, - s2.Value as method, - null as collectionMethod, - null as tissue, - null as remarks, - - cp.ts as rowversion, - cp.objectid - -From Cln_Parasitology cp -left join Sys_Parameters s1 on (s1.Flag = cp.Category And s1.Field = 'RequestCategory') -left join Sys_Parameters s2 on (s2.Flag = cp.Method And s2.Field = 'AnalysisMethodParasitol') -left join Sys_Parameters s3 on (s3.Flag = cp.Condition And s3.Field = 'AnimalConditionLab') -left join Ref_Technicians rt on (cp.Technician = rt.ID) -left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - -) t - -left join Specimen sp on (sp.Value = t.Specimen) - -where t.rowversion > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Deaths.sql b/onprc_ehr/resources/etl/deprecated/Deaths.sql deleted file mode 100644 index 48c1f93d7..000000000 --- a/onprc_ehr/resources/etl/deprecated/Deaths.sql +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(AnimalID as nvarchar(4000)) as Id, - Date as Date, - - - --CauseOfDeath as CauseOfDeathInt, - s1.Value as Cause, - Remarks as Remark, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - --afd.DeathLocation as CageId, - loc.Location as roomattime, - ltrim(rtrim(row.row + convert(char(2), row.Cage))) As cageattime, - - afd.objectid - --afd.ts as rowversion - -From Af_Death AfD -left join Sys_Parameters s1 ON (Afd.CauseOfDeath = s1.Flag And s1.Field = 'Deathcause') -left join Ref_Location loc ON (loc.LocationId = afd.DeathLocation) -left join Ref_RowCage row on (afd.DeathLocation = row.CageID AND loc.LocationId = row.LocationID) -left join Ref_Technicians rt ON (afd.Technician = rt.ID) -left join Sys_Parameters s2 ON (s2.Field = 'DepartmentCode' And s2.Flag = rt.Deptcode) - -WHERE afd.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Demographics.sql b/onprc_ehr/resources/etl/deprecated/Demographics.sql deleted file mode 100644 index fa9424af7..000000000 --- a/onprc_ehr/resources/etl/deprecated/Demographics.sql +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(afq.AnimalID as nvarchar(4000)) as Id, - --Species as Species, ----- Ref_Species - sp.CommonName as Species, - - --Sex as SexCode , ---- Ref_Sex - CASE - WHEN rs.Value = 'Male' THEN 'm' - WHEN rs.Value = 'Female' THEN 'f' - WHEN rs.Value = 'Hermaphrodite' THEN 'h' - WHEN rs.Value = 'Unknown' THEN 'u' - ELSE rs.Value - END AS Gender, - - CASE - WHEN (gr.DamId IS NOT NULL AND gr.DamId != '0') THEN cast(gr.DamId as nvarchar(4000)) - --WHEN c.DamId != '0' THEN cast(c.DamId as nvarchar(4000)) - WHEN b.MotherID != '0' THEN cast(b.MotherId as nvarchar(4000)) - ELSE NULL - END as dam, - --b.MotherID, - - CASE - WHEN (gr.sireId IS NOT NULL AND gr.SireId != '0') THEN cast(gr.SireId as nvarchar(4000)) - --WHEN c.SireId != '0' THEN cast(c.SireId as nvarchar(4000)) - WHEN b.FatherID != '0' THEN cast(b.FatherId as nvarchar(4000)) - ELSE NULL - END as sire, - --b.FatherID, - - --l2.Location as room, - --rtrim(r2.row) + convert(char(2), r2.Cage) As cage, - - afq.BirthDate as Birth, - - afq.DeathDate as Death, - - CASE - WHEN s1.Value IS NULL THEN null - WHEN s1.value = 'Dead' THEN 'Dead' - WHEN s1.value = 'Live' THEN 'Alive' - WHEN s1.value = 'Sold' THEN 'Shipped' - else s1.value - END as calculated_status, - COALESCE(t.geographic_origin, aq.geographic_origin) as geographic_origin, - - --TODO: most of these should get moved into study.notes - PregnancyDate as PregnancyDate , - Toys as Toys , - - --NOTE: these are just calculated on demand, so we dont cache in demographics. - --TODO: need to verify we are capturing all of them from their associated tables. - --AcquiDate as AcquiDate, - --DepartureDate as DepartureDate , - --Assigned as Assigned , ------ Flag > 0 Numeric count of assigned projects , Flag = 0 Not Assigned - --LastTBTestdate as LastTBTestdate , - - afq.objectid - --afq.ts as rowversion - -From Af_Qrf afq -left join Sys_Parameters s1 on (afq.Deathflag = s1.Flag And s1.Field = 'DeathFlag') -left join Sys_Parameters s2 on (afq.BirthFlag = s2.Flag and s2.Field = 'BirthFlag') -left join Ref_RowCage r2 on (r2.CageID = afq.CageID) -left join Ref_Location l2 on (r2.LocationID = l2.LocationId) -left join Ref_SEX rs ON (rs.Flag = afq.Sex) -left join Ref_Species sp ON (sp.SpeciesCode = afq.Species) -left join Ref_RowCage rc ON (rc.CageID = afq.CageID) --- left join ( --- select --- c.AnimalId, --- max(c.DamId) as DamId, --- max(c.SireId) as SireId, --- max(c.birthdate) as birthdate, --- max(cast(c.objectid as varchar(38))) as objectid, --- max(r.Description) as description --- from combinedrelationship c --- left join refs r ON (r.field like '%calc%' AND r.Code = c.CalcType) --- group by c.AnimalId --- ) c ON (c.AnimalId = afq.AnimalID) -left join Af_Birth b ON (b.AnimalID = afq.AnimalID) -left join ( - SELECT - gr.animalid, - max(gr.sireid) as sireid, - max(gr.damid) as damid, - max(gr.ts) as ts - FROM Geneticrelationship gr - GROUP BY gr.animalid -) gr ON (gr.animalid = afq.animalid) - -left JOIN ( - -select - q.AnimalID, - --labkey.core.group_concat_d(a.PoolCode, ',') as codes, - CASE - WHEN q.Species = 291 THEN 'Japan' - WHEN q.Species = 305 AND count(distinct a.PoolCode) = 1 AND max(a.PoolCode) = 1052 THEN 'China' - WHEN q.Species = 305 AND count(distinct a.PoolCode) = 1 AND max(a.PoolCode) = 1053 THEN 'Hybrid (China / India)' - WHEN q.Species = 305 AND count(distinct a.PoolCode) = 1 AND max(a.PoolCode) = 1050 THEN 'India' - else null - END as geographic_origin, - MAX(a.ts) as ts -from Af_QRF q -LEFT JOIN af_pool a ON (q.AnimalID = a.AnimalID AND a.poolcode in (1050,1052,1053) AND q.Species = 305 AND coalesce(a.DateReleased, CURRENT_TIMESTAMP) >= CURRENT_TIMESTAMP) -GROUP BY q.AnimalID, q.Species - -) t ON (t.animalid = cast(afq.animalid AS nvarchar(4000))) - -LEFT JOIN ( - select - AnimalID, - max(RefIs.GeographicName) as geographic_origin, - max(afc.ts) as maxTs - from Af_Acquisition afc - LEFT JOIN Ref_IsisGeographic RefIs ON (Afc.GeographicOrigin = RefIs.GeographicCode) - WHERE afc.GeographicOrigin > 0 - GROUP BY afc.AnimalId -) aq ON (t.animalid = cast(aq.animalid AS nvarchar(4000))) - -WHERE (afq.ts > ? or b.ts > ? or t.ts > ? or gr.ts > ? or aq.maxTs > ?) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Departure.sql b/onprc_ehr/resources/etl/deprecated/Departure.sql deleted file mode 100644 index a20015f2d..000000000 --- a/onprc_ehr/resources/etl/deprecated/Departure.sql +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(afd.AnimalID as nvarchar(4000)) as Id, - afd.Date as Date, - isis.InstitutionCode as destination, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - --afd.IDKey as IDKey, - - afd.Remarks as Remark, - afd.objectid - --afd.ts as rowversion - -From AF_Departure afd -LEFT JOIN Ref_Technicians rt ON (afd.Technician = rt.ID) -LEFT JOIN Sys_Parameters s1 ON (s1.Field = 'DepartmentCode' and s1.Flag = rt.DeptCode) -left join Ref_ISISInstitution isis ON (isis.InstitutionCode = ISISDestination) - -where afd.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Diet.sql b/onprc_ehr/resources/etl/deprecated/Diet.sql deleted file mode 100644 index 3be2e9ce6..000000000 --- a/onprc_ehr/resources/etl/deprecated/Diet.sql +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select --top 1000 - --IDKey as IDKey , - cast(afd.AnimalID as nvarchar(4000)) as Id, - afd.ProjectID as Project, ---- Ref_ProjectsIacuc - afd.StartDate as Date , --- ReleaseDate as enddate , - - coalesce(ReleaseDate, q.deathdate, q.departuredate) as enddate , - - - --afd.DietCode as DietCode, ----- Ref_Diet - d.Description as Diet, - Frequency as FrequencyInt, - s1.value as FrequencyMeaning, - --Duration as Duration , -- # of days - Billable as Billable , -- 0 = no, 1 = yes - Status as StatusField , - --BillID as BillID, -- not used - - afd.objectid, - afd.ts as rowversion - -From Af_Diet afd -left join Sys_Parameters s1 on (s1.Field = 'Frequency' and afd.Frequency = s1.Flag) -left join Ref_ProjectsIacuc proj on (proj.ProjectID = afd.ProjectID) -left join Ref_Diet d on (d.DietCode = afd.DietCode) -left join Af_Qrf q on (q.animalid = afd.animalid) - -where afd.ts > ? diff --git a/onprc_ehr/resources/etl/deprecated/Enrichment.sql b/onprc_ehr/resources/etl/deprecated/Enrichment.sql deleted file mode 100644 index 4f5d70161..000000000 --- a/onprc_ehr/resources/etl/deprecated/Enrichment.sql +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - --IDKey as IDKey , - cast(AnimalID as nvarchar(4000)) as Id, - GivenDate as date, - RemoveDate as enddate, - t.ToyCode as ToyCode, ------ Ref_Snomed - s.description as toyCodeMeaning, - - toy.ToyType as type, - Reason, - Remarks as Remark, - t.objectid, - t.ts as rowversion - -From Af_Toys t -left join ref_snomed s ON (s.SnomedCode = t.ToyCode) - -left join ref_toys toy ON (toy.ToyCode = t.ToyCode) - -where t.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Flags.sql b/onprc_ehr/resources/etl/deprecated/Flags.sql deleted file mode 100644 index 987b2a26b..000000000 --- a/onprc_ehr/resources/etl/deprecated/Flags.sql +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -Select - cast(p.AnimalID as nvarchar(4000)) as Id, - --p.PoolCode as PoolCode, ----- Ref_Pool - rp.objectid AS flag, - rtrim(ltrim(rp.ShortDescription)) AS category, - rp.Description as value, - - DateAssigned as date, --- DateReleased as enddate, - - coalesce(DateReleased, q.deathdate, q.departuredate, rp.datedisabled) as enddate , - - --NOTE: redundant w/ enddate? - --Status as Status, ---- flag = 1 Active pools, Flag = 0 Inactive Pools - - --p.ts as rowversion, - cast(p.objectid as varchar(38)) as objectid - -From Af_Pool p -left join ref_pool rp ON (rp.PoolCode = p.PoolCode) -left join Af_Qrf q on (q.animalid = p.animalid) - -where (p.ts > ? or q.ts > ? or rp.ts > ?) and rp.ShortDescription not in ('CBG', 'EBG', 'HBG', 'PBG', 'STG', 'SBG', 'JBG', 'CCBG', 'CTG', 'Origin') - -UNION ALL - -select - -r.animalid as Id, -null as flag, -'Genetics' as category, -'Parentage Blood Draw Collected' as value, -r.DateProcessed as date, -coalesce(q.deathdate, q.departuredate) as enddate, -(cast(r.objectid as varchar(38)) + '_parentage') as objectid - -from Res_DNABank r -join Af_Qrf q on (cast(q.AnimalID as nvarchar(4000)) = r.animalid) - -where r.DateProcessed is not null ---exclude non-center animals -and r.animalid not like '%n' and r.animalid not like '%f' -and (r.ts > ?) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Hematology Results.sql b/onprc_ehr/resources/etl/deprecated/Hematology Results.sql deleted file mode 100644 index 7c24bc67a..000000000 --- a/onprc_ehr/resources/etl/deprecated/Hematology Results.sql +++ /dev/null @@ -1,603 +0,0 @@ -/* - * Copyright (c) 2012-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---Please note: All lab values = -1 is should be substitued with a Null value - -SELECT - t.ClinicalKey , - cast(t.Id as nvarchar(4000)) as Id, - t.DATE , - --t.Specimen , -- Specimen database table - t.projectId as project, - --sp.Name, - --sp.SNOMEDCODE as snomed, - --t.MethodInt , - s2.Value as Method, - CASE - WHEN t.result = -1 THEN null - else t.result - END as result, - t.qual_result, - - t.TestId, - - t.remarks as remark, - (cast(t.objectid as varchar(38)) + '_' + t.TestId) as objectid, - t.objectid as runid - -FROM ( - --- SELECT --- ClinicalKey , --- AnimalID as Id , --- DATE , --- Specimen as Specimen , -- Specimen database table --- Method as MethodInt , --- ManualDiff as Result, --- 'ManualDiff' as TestId, --- cln.ts as rowversion, --- cln.objectid --- --- FROM Cln_Hematology cln --- WHERE ManualDiff != 0 --- --- union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - WBC as Result, - null as qual_result, - 'WBC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RBC as Result, - null as qual_result, - 'RBC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Hemoglobin as Result, - null as qual_result, - 'HGB' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Hematocrit as Result, - null as qual_result, - 'HCT' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - MCV as Result, - null as qual_result, - 'MCV' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - MCH as Result, - null as qual_result, - 'MCH' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - MCHC as Result, - null as qual_result, - 'MCHC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - PlateletCount as Result, - null as qual_result, - 'PLT' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - TotalProtein as Result, - null as qual_result, - 'TP' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - MPMN as Result, - null as qual_result, - 'NEUT%' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - IPMN as Result, - null as qual_result, - 'Bands' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Lymphocyte as Result, - null as qual_result, - 'LYMPH%' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Monocyte as Result, - null as qual_result, - 'MONO%' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Eosinophil as Result, - null as qual_result, - 'EOS%' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Basophil as Result, - null as qual_result, - 'BASO%' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - SEDRate as Result, - null as qual_result, - 'SEDRate' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - LUC as Result, - null as qual_result, - 'LUC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - NRBC as Result, - null as qual_result, - 'NRBC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Reticulocyte as Result, - null as qual_result, - 'RETIC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RBCHypochromic as Result, - null as qual_result, - 'Hypochromic RBC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - cast(RBC_Acanthocytes as double precision) as Result, - null as qual_result, - 'RBC Acanthocytes' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - cast(RBC_Poikilocytes as double precision) as Result, - null as qual_result, - 'RBC Poikilocytes' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - cast(RBC_Spherocytes as double precision) as Result, - null as qual_result, - 'RBC Spherocytes' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - null as result, - RBC_TargetCells as qual_result, - 'RBC TargetCells' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - MPV as Result, - null as qual_result, - 'MPV' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RDW as Result, - null as qual_result, - 'RDW' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RBCMicrocyte as Result, - null as qual_result, - 'Microcytic RBC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RBCPolychromasia as Result, - null as qual_result, - 'Polychromasia RBC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RBCMacrocyte as Result, - null as qual_result, - 'Macrocytic RBC' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -union all - -SELECT - ClinicalKey , - projectId, - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - RBCAnisocytosis as Result, - null as qual_result, - 'Anisocytosis' as TestId, - cln.ts as rowversion, - cln.remarks, - cln.objectid - -FROM Cln_Hematology cln - -) t - -left join Sys_Parameters s2 on (s2.Flag = t.MethodInt And s2.Field = 'AnalysisMethodHematology') ---left join Specimen sp on (sp.Value = t.Specimen) - -WHERE t.result != -1 AND (t.result is not null or t.qual_result is not null) - and t.rowversion > ? - diff --git a/onprc_ehr/resources/etl/deprecated/Housing.sql b/onprc_ehr/resources/etl/deprecated/Housing.sql deleted file mode 100644 index 79d4f7190..000000000 --- a/onprc_ehr/resources/etl/deprecated/Housing.sql +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(aft.AnimalID as nvarchar(4000)) as Id, - aft.TransferDate as Date, - coalesce(aft.RemovalDate, q.deathdate, q.departuredate) as enddate, - - --Aft.CageID as TransferCageID , - l2.Location as room, - rtrim(ltrim(rtrim(r2.row) + convert(char(2), r2.Cage))) As cage, - (select l.rowid FROM labkey.ehr_lookups.lookups l where l.set_name = s3.Field and l.value = s3.Value) as housingType, - (select l.rowid FROM labkey.ehr_lookups.lookups l where l.set_name = s4.Field and l.value = s4.Value) as housingCondition, - --Reason as ReasonInt, - s1.Value as Reason, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - --Latest as Latest, ---- Flag = 1 Current Transfer Record, Flag = 0 Historical Transfer information - - aft.objectid - --aft.ts as rowversion - -From Af_Transfer Aft -left join Ref_Technicians Rt on (Aft.Technician = Rt.ID) -left join Sys_Parameters s2 on (s2.Flag = Rt.Deptcode And S2.Field = 'Departmentcode') -left join Sys_Parameters s1 on ( AfT.Reason = s1.Flag And s1.Field = 'TransferReason') -left join Ref_RowCage r2 on (r2.CageID = aft.CageID) -left join Ref_Location l2 on (r2.LocationID = l2.LocationId) -left join Sys_Parameters s3 on ( l2.LocationType = s3.Flag And s3.Field = 'LocationType') -left join Sys_Parameters s4 on ( l2.LocationDefinition = s4.Flag And s4.Field = 'LocationDefinition') - -left join Af_Qrf q on (q.animalid = aft.animalid) - -WHERE (aft.ts > ? OR q.ts > ?) and l2.Location != 'No Location' \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Matings.sql b/onprc_ehr/resources/etl/deprecated/Matings.sql deleted file mode 100644 index c2babbe6a..000000000 --- a/onprc_ehr/resources/etl/deprecated/Matings.sql +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(AnimalID as nvarchar(4000)) as Id, - Date as Date , - MaleId as Male, - - (SELECT rowid FROM labkey.ehr_lookups.lookups l WHERE l.set_name = 'MatingType' and l.value = s1.value) as MatingType, - --s1.Value as MatingType, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - --IDKey as IDKey, - --bm.ts as rowversion, - bm.objectid AS objectid - -FROM Brd_Matings bm -left join Sys_parameters s1 ON (s1.Field = 'MatingType' and s1.Flag = MatingType) -left join Ref_Technicians rt ON (bm.Technician = rt.ID) -left join Sys_parameters s2 On (s2.Field = 'DepartmentCode' and s2.Flag = rt.DeptCode) - -where bm.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Measurements.sql b/onprc_ehr/resources/etl/deprecated/Measurements.sql deleted file mode 100644 index 85497acce..000000000 --- a/onprc_ehr/resources/etl/deprecated/Measurements.sql +++ /dev/null @@ -1,570 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(pm.Id as nvarchar(4000)) as Id, - pm.date, - - pm.objectid as parentid, - (cast(pm.objectid as varchar(38)) + '||' + coalesce(pm.tissue, '') + '||' + CAST(pm.measurement1 as nvarchar(4000))) as objectid, - --pm.rowversion, - - --pm.MeasurementID, - pm.tissue, - pm.measurement1, - pm.measurement2, - pm.measurement3, - null as category, - 'cm' as units, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy -FROM ( - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate as date, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9650' as tissue, - --'Crown Rump' as dimension, - CrownRump AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9750' as tissue, - --'Transtemporal' as dimension, - Transtemporal AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y8710' as tissue, --right hand - --null as dimension, - RightHand AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9710' as tissue, --right foot - --null as dimension, - RightFoot AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-YZ050' as tissue, - --null as dimension, - PrimaryPlacentalDisc1 AS measurement1, - PrimaryPlacentalDisc2 AS measurement2, - PrimaryPlacentalDisc3 AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-YZ060' as tissue, - --null as dimension, - SecondaryPlacentalDisc1 AS measurement1, - SecondaryPlacentalDisc2 AS measurement2, - SecondaryPlacentalDisc3 AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9855' as tissue, - --'Abdominal Circumference' as dimension, - AbdominalCircumference AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9845' as tissue, - --'Head Circumference' as dimension, - HeadCircumference AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9889' as tissue, - --'Thoracic Circumference' as dimension, - ThoracicCircumference AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9880' as tissue, - --'Femur Length' as dimension, - FemurLength AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9865' as tissue, - --'Torso Length' as dimension, - TorsoLength AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-36000' as tissue, --heart - --'LAV' as dimension, - HeartLAV AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-38000' as tissue, --heart - --'RAV' as dimension, - HeartRAV AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-37000' as tissue, --heart - --'PUL' as dimension, - HeartPUL AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-39000' as tissue, --heart - --'AO' as dimension, - HeartAO AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9890' as tissue, --heart - --'LVW' as dimension, - HeartLVW AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-Y9870' as tissue, --heart - --'RVW' as dimension, - HeartRVW AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - 'T-32410' as tissue, --heart - --'IVS' as dimension, - HeartIVS AS measurement1, - null AS measurement2, - null AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - TissueSnomed1 as tissue, - --null as dimension, - Tissue1Dimension1 AS measurement1, - Tissue1Dimension2 AS measurement2, - Tissue1Dimension3 AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - TissueSnomed2 as tissue, - --null as dimension, - Tissue2Dimension1 AS measurement1, - Tissue2Dimension2 AS measurement2, - Tissue3Dimension3 AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - TissueSnomed4 as tissue, - --null as dimension, - Tissue4Dimension1 AS measurement1, - Tissue4Dimension2 AS measurement2, - Tissue4Dimension3 AS measurement3 - -From Path_Measurements pm - -UNION ALL - -Select - MeasurementID, - AnimalID as Id, - MeasurementDate, - Technician As TechnicianInt, - pm.objectid, - pm.ts as rowversion, - TissueSnomed5 as tissue, - --null as dimension, - Tissue5Dimension1 AS measurement1, - Tissue5Dimension2 AS measurement2, - Tissue5Dimension3 AS measurement3 - -From Path_Measurements pm - -) pm - -left join Ref_Technicians rt on pm.TechnicianInt = rt.ID -left join Sys_Parameters s1 on (s1.Flag = rt.DeptCode And s1.Field = 'DepartmentCode') - -where (measurement1 > 0 or measurement2 > 0 or measurement3 > 0) -and pm.rowversion > ? - -UNION ALL - -SELECT - cast(t.AnimalID as nvarchar(4000)) as Id, - t.date, - t.objectid as parentId, - (cast(t.objectid as varchar(38)) + t.tissue + CAST(t.measurement1 as nvarchar(4000))) as objectid, - t.tissue, - t.measurement1, - t.measurement2, - null as measurement3, - 'Placental' as category, - 'cm' as units, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy - -FROM ( - -Select - - AnimalID, - MeasurementDate as date, - 'T-Y9650' as tissue, - --'Crown Rump' as dimension, - CrownRump as measurement1, - null as measurement2, - - Technician, - path.objectid, - path.ts - -From Path_FetalMeasurements Path -where CrownRump > 0 - -UNION ALL - -Select - - AnimalID, - MeasurementDate as date, - 'T-Y9750' as tissue, - --'Transtemporal' as dimension, - Transtemporal as measurement1, - null as measurement2, - - Technician, - path.objectid, - path.ts - -From Path_FetalMeasurements Path -where Transtemporal > 0 - -UNION ALL - -Select - - AnimalID, - MeasurementDate as date, - 'T-Y8710' as tissue, --right hand - --null as dimension, - RightHand as measurement1, - null as measurement2, - - Technician, - path.objectid, - path.ts - -From Path_FetalMeasurements Path -where RightHand > 0 - -UNION ALL - -Select - - AnimalID, - MeasurementDate as date, - 'T-Y9710' as tissue, --right foot - --null as dimension, - RightFoot as measurement1, - null as measurement2, - - Technician, - path.objectid, - path.ts - -From Path_FetalMeasurements Path -where RightFoot > 0 - -UNION ALL - -Select - - AnimalID, - MeasurementDate as date, - 'T-YZ050' as tissue, - --null as dimension, - PrimaryPlacentalDisc1 as measurement1, - PrimaryPlacentalDisc2 as measurement2, - - Technician, - path.objectid, - path.ts - -From Path_FetalMeasurements Path -where (PrimaryPlacentalDisc1 > 0 or PrimaryPlacentalDisc2 > 0) - -UNION ALL - -Select - - AnimalID, - MeasurementDate as date, - 'T-YZ060' as tissue, - --null as dimension, - SecondaryPlacentalDisc1 as measurement1, - SecondaryPlacentalDisc2 as measurement2, - - Technician, - path.objectid, - path.ts - -From Path_FetalMeasurements Path -where (SecondaryPlacentalDisc1 > 0 OR SecondaryPlacentalDisc2 > 0) - -) t - -left join Ref_Technicians rt on (t.Technician = rt.ID) -left join Sys_Parameters s1 on (s1.Flag = rt.DeptCode And s1.Field = 'DepartmentCode') - -where t.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Microbiology.sql b/onprc_ehr/resources/etl/deprecated/Microbiology.sql deleted file mode 100644 index 8027718e3..000000000 --- a/onprc_ehr/resources/etl/deprecated/Microbiology.sql +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(mh.AnimalID as nvarchar(4000)) as Id, - mh.DATE, - mh.projectid as project, - --m.ClinicalKey as ClinicalKey , - m.Bacteria as organism, ----- Ref_Snomedlists - s.Description as organismMeaning, - --m.Quantity, - CASE - WHEN Quantity = 5 THEN NULL - else sp.value - END as quantity, - --m.Searchkey , - - --m.ts as rowversion, - m.objectid, - mh.objectid as runId - -FROM Cln_MicrobiologyData m -left join Cln_MicrobiologyHeader mh ON (m.ClinicalKey = mh.ClinicalKey) -left join ref_snomed s ON (m.Bacteria = s.SnomedCode) -left join sys_parameters sp ON (sp.field = 'Microbiologyquantity' and sp.flag = m.quantity) ---left join ref_snomed s2 ON (mh.tissue = s2.SnomedCode) - -where m.ts > ? or mh.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Misc Tests.sql b/onprc_ehr/resources/etl/deprecated/Misc Tests.sql deleted file mode 100644 index 32401890f..000000000 --- a/onprc_ehr/resources/etl/deprecated/Misc Tests.sql +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2012-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(t.id as nvarchar(4000)) as Id, - t.date, - t.projectid as project, - t.category, - - t.specimen, - t.name as specimenName, - t.Method, - - t.TestId, - t.result, - t.stringResults, - t.qualResult, - t.remarks as remark, - - case - WHEN tech.LastName = 'Unassigned' or tech.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rtrim(tech.LastName)) > 0 AND datalength(rtrim(tech.FirstName)) > 0 AND datalength(tech.Initials) > 0 THEN - tech.LastName + ', ' + tech.FirstName + ' (' + tech.Initials + ')' - WHEN datalength(rtrim(tech.LastName)) > 0 AND datalength(rtrim(tech.FirstName)) > 0 THEN - tech.LastName + ', ' + tech.FirstName - WHEN datalength(rtrim(tech.LastName)) > 0 AND datalength(tech.Initials) > 0 THEN - tech.LastName + ' (' + tech.Initials + ')' - WHEN datalength(tech.Initials) = 0 OR tech.initials = ' ' OR tech.lastname = ' none' THEN - null - else - tech.Initials - END as performedBy, - - t.runid, - t.objectid, - t.rowversion - - -from ( - ---occult blood - -SELECT - ClinicalKey as ClinicalKey , - AnimalID as Id , - Date as Date , - projectid, - Category as CategoryInt , - s1.Value as Category, - - Technician As TechnicianID, - - Specimen as Specimen , ----- Specimen database table - sp.name, - sp.SNOMEDCODE, - Method as MethodInt , - s2.Value as Method, - - 'Occult Blood' as TestId, - --OccultFlag as OccultFlag , - null as result, - null as stringResults, - CASE - when OccultFlag =1 THEN 'Positive' - else 'Negative' - END as QualResult, - Remarks as Remarks, - cln.ts as rowversion, - cln.ts as rowversion2, - cast(cln.objectid as varchar(38)) as objectid, - null as runid - -FROM Cln_OccultBlood cln - left join Sys_Parameters s1 on (s1.Flag = Cln.Category And s1.Field = 'RequestCategory') - left join Sys_Parameters s2 on (s2.Flag = Cln.Method And s2.Field = 'AnalysisMethod') - left join Specimen sp on (sp.Value = cln.Specimen) - ---occult blood from parasitology table -UNION ALL - -select -null as clinicalKey, -cp.AnimalID, -cp.DATE, -cp.projectid, -cp.Category as categoryInt, -null as category, -cp.Technician as technicianId, - -cp.Specimen, -sp.name, -sp.SNOMEDCODE, -cp.Method as methodInt, -s2.Value as Method, - -'Occult Blood' as TestId, -null as result, -null as stringResults, -s5.Value as qualResult, ---cp.OccultBlood, -null as remark, -cp.ts as rowversion, -cp.ts as rowversion2, -cast(cp.objectid as varchar(38)) as objectid, -null as runid - -from Cln_Parasitology cp -left join Sys_Parameters s5 on (s5.Flag = cp.OccultBlood And s5.Field = 'occultblood') -left join Sys_Parameters s1 on (s1.Flag = cp.Category And s1.Field = 'RequestCategory') -left join Sys_Parameters s2 on (s2.Flag = cp.Method And s2.Field = 'AnalysisMethod') -left join Specimen sp on (sp.Value = cp.Specimen) - -where OccultBlood != -1 - -UNION ALL - ---misc tests: - -SELECT - cln.ClinicalKey as ClinicalKey , - h.AnimalID, - h.DATE, - projectid, - h.Category as CategoryInt, - s1.Value as category, - h.Technician as technicianId, - - h.Specimen, - sp.Name, - coalesce(sp.SNOMEDCODE, h.tissue) as code, - h.Method as MethodInt, - s2.Value as Method, - - --cln.RareTestID as RareTestID , ----- Ref_RareTests - rt.RareTest as TestId, - - null as result, - cln.Value as stringResults , - null as qualResult, - cln.Remarks as Remarks, - cln.ts as rowversion, - h.ts as rowversion2, - cast(cln.objectid as varchar(38)) as objectid, - h.objectid as runid - -FROM Cln_RareTestData cln -left join Ref_RareTests rt on (rt.RareTestID = cln.RareTestID) -left join Cln_RareTestHeader h on (h.ClinicalKey = cln.ClinicalKey) -left join Sys_Parameters s1 on (s1.Flag = h.Category And s1.Field = 'RequestCategory') -left join Sys_Parameters s2 on (s2.Flag = h.Method And s2.Field = 'AnalysisMethod') -left join Specimen sp on (sp.Value = h.Specimen) - ---these will be in serology -where rt.RareTest != 'Interferon-Gamma Mycobacterium Testing (Primagam)' - ---CSF -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - null as projectId, - null as categoryInt, - null as category, - cln.Technician as technicianId, - - Specimen as Specimen , -- Specimen database table - sp.name, - sp.snomedcode, - null as MethodInt, - null as Method , - 'CSF WBC' as TestId, - TotalWBC as Result, - null as stringResults, - null as qual_result, - remarks , - cln.ts as rowversion, - null as rowversion2, - (cast(cln.objectid as varchar(38)) + '_WBC') as objectid, - null as runid - -FROM Cln_CerebralspinalFluid cln -left join Specimen sp on (sp.Value = cln.Specimen) -WHERE cln.TotalWBC != -1 AND cln.TotalWBC is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - null as projectId, - null as categoryInt, - null as category, - cln.Technician as technicianId, - - Specimen as Specimen , -- Specimen database table - sp.name, - sp.snomedcode, - null as MethodInt, - null as Method , - 'CSF Neut' as TestId, - WBCNeurophils as Result, - null as stringResults, - null as qual_result, - remarks , - cln.ts as rowversion, - null as rowversion2, - (cast(cln.objectid as varchar(38)) + '_Neut') as objectid, - null as runid - -FROM Cln_CerebralspinalFluid cln -left join Specimen sp on (sp.Value = cln.Specimen) -WHERE cln.WBCNeurophils != -1 AND cln.WBCNeurophils is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - null as projectId, - null as categoryInt, - null as category, - cln.Technician as technicianId, - - Specimen as Specimen , -- Specimen database table - sp.name, - sp.snomedcode, - null as MethodInt, - null as Method , - 'CSF Lymph' as TestId, - WBCLymphocytes as Result, - null as stringResults, - null as qual_result, - remarks , - cln.ts as rowversion, - null as rowversion2, - (cast(cln.objectid as varchar(38)) + '_Lymph') as objectid, - null as runid - -FROM Cln_CerebralspinalFluid cln -left join Specimen sp on (sp.Value = cln.Specimen) -WHERE cln.WBCLymphocytes != -1 AND cln.WBCLymphocytes is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - null as projectId, - null as categoryInt, - null as category, - cln.Technician as technicianId, - - Specimen as Specimen , -- Specimen database table - sp.name, - sp.snomedcode, - null as MethodInt, - null as Method , - 'CSF Total Protein' as TestId, - TotalProtein as Result, - null as stringResults, - null as qual_result, - remarks , - cln.ts as rowversion, - null as rowversion2, - (cast(cln.objectid as varchar(38)) + '_TP') as objectid, - null as runid - -FROM Cln_CerebralspinalFluid cln -left join Specimen sp on (sp.Value = cln.Specimen) -WHERE cln.TotalProtein != -1 AND cln.TotalProtein is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - null as projectId, - null as categoryInt, - null as category, - cln.Technician as technicianId, - - Specimen as Specimen , -- Specimen database table - sp.name, - sp.snomedcode, - null as MethodInt, - null as Method , - 'CSF Glucose' as TestId, - Glucose as Result, - null as stringResults, - null as qual_result, - remarks , - cln.ts as rowversion, - null as rowversion2, - (cast(cln.objectid as varchar(38)) + '_Gluc') as objectid, - null as runid - -FROM Cln_CerebralspinalFluid cln -left join Specimen sp on (sp.Value = cln.Specimen) -WHERE cln.Glucose != -1 AND cln.Glucose is not null - -) t - -left join Ref_Technicians tech on (t.TechnicianId = tech.ID) - - -where (t.rowversion > ? or t.rowversion2 > ?) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Notes.sql b/onprc_ehr/resources/etl/deprecated/Notes.sql deleted file mode 100644 index 419368ae7..000000000 --- a/onprc_ehr/resources/etl/deprecated/Notes.sql +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - --RemarksID as RemarksID , - cast(afr.AnimalID as nvarchar(4000)) as Id, - RemarksDate as date, - coalesce(afr.datedisabled, q.deathdate, q.departuredate) as enddate, - - --Afr.Topic as TopicInt , - s1.value as Category, - Remarks as value, - - --TODO - --ActionDate as ActionDate , - --afr.PoolCode as PoolCode , ----- Ref_Pool - --rp.ShortDescription, - --rp.Description, - --afr.DateCreated as DateCreated , - --afr.DateDisabled as DateDisabled, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - afr.objectid - --afr.ts as rowversion - -From Af_Remarks Afr -left join Sys_Parameters s1 on (Afr.Topic = s1.Flag And s1.Field = 'Remarks Topic') -left join Sys_Parameters s2 on (s2.Field = 'DepartmentCode' And Afr.Department = s2.flag) -left join Ref_Technicians Rt on (Afr.TechnicianID = Rt.ID) -left join Sys_Parameters s3 on (s3.flag = Rt.Deptcode And s3.Field = 'DepartmentCode') -left join Ref_pool rp on (rp.PoolCode = afr.PoolCode) -left join Af_Qrf q on (q.animalid = afr.animalid) - -WHERE (afr.ts > ?) diff --git a/onprc_ehr/resources/etl/deprecated/Parasitology Results.sql b/onprc_ehr/resources/etl/deprecated/Parasitology Results.sql deleted file mode 100644 index 717df588d..000000000 --- a/onprc_ehr/resources/etl/deprecated/Parasitology Results.sql +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - category, - cast(AnimalID as nvarchar(4000)) as Id, - date, - projectid as project, - - tissue as organism, - sno.Description as organismMeaning, - s.SNOMEDCODE as sampletype, ---quantity as quantityInt, - s7.Value as remark, - ---analysis as analysisInt, - s6.Value as method, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - cp.ts as rowversion, - cp.objectid as runid, - (cast(cp.objectid as varchar(38)) + '_' + cp.tissue + '_' + category) as objectid - -FROM ( - - Select - 'wetMount1' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - WetMount1 as tissue, - WetQuantity1 as quantity, - Wet1Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where WetMount1 is not null and WetMount1 != '' - - UNION ALL - - Select - 'wetMount2' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - WetMount2 as tissue, - WetQuantity2 as quantity, - Wet2Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where WetMount2 is not null and WetMount2 != '' - - UNION ALL - - Select - 'wetMount3' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - WetMount3 as tissue, - WetQuantity3 as quantity, - Wet3Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where WetMount3 is not null and WetMount3 != '' - - UNION ALL - - Select - 'float1' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - Floatation1 as tissue, - FlotQuantity1 as quantity, - Flot1Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where Floatation1 is not null and Floatation1 != '' - - UNION ALL - - Select - 'float2' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - Floatation2 as tissue, - FlotQuantity2 as quantity, - Flot2Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where Floatation2 is not null and Floatation2 != '' - - UNION ALL - - Select - 'float3' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - Floatation3 as tissue, - FlotQuantity3 as quantity, - Flot3Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where Floatation3 is not null and Floatation3 != '' - - UNION ALL - - Select - 'misc1' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - Misc1 as tissue, - MiscQuantity1 as quantity, - Misc1Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where Misc1 is not null and Misc1 != '' - - UNION ALL - - Select - 'misc2' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - Misc2 as tissue, - MiscQuantity2 as quantity, - Misc2Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where Misc2 is not null and Misc2 != '' - - UNION ALL - - Select - 'misc3' as category, - AnimalID, - date, - projectid, - Technician, - cp.ts, - cp.objectid, - - Misc3 as tissue, - MiscQuantity3 as quantity, - Misc3Analysis as analysis, - cp.Specimen - - From Cln_Parasitology cp - where Misc3 is not null and Misc3 != '' - - ) cp - - left join Ref_Technicians rt on (cp.Technician = rt.ID) - left join Sys_Parameters s4 on (s4.Flag = rt.DeptCode And s4.Field = 'DepartmentCode') - left join Sys_Parameters s6 on (s6.Flag = cp.analysis and s6.Field = 'AnalysisParasitology') - left join Sys_Parameters s7 on (s7.Flag = cp.quantity and s7.Field = 'ParasitologyQuantity') - left join ref_snomed sno ON (sno.SnomedCode = cp.tissue) - left join Specimen s ON (s.Value = cp.Specimen) - -where cp.ts > ? diff --git a/onprc_ehr/resources/etl/deprecated/Parentage.sql b/onprc_ehr/resources/etl/deprecated/Parentage.sql deleted file mode 100644 index 24aa8168d..000000000 --- a/onprc_ehr/resources/etl/deprecated/Parentage.sql +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select - cast(c.AnimalId as varchar(4000)) as Id, - c.Calculation_Date as date, - null as enddate, - cast(c.SireId as varchar(4000)) as parent, - 'Sire' as relationship, - CASE - WHEN c.CalcType = 0 THEN 'Observed' --Unknown or Observed Sire/Dam - WHEN c.CalcType = 1 THEN 'Genetic' --Genetic Sire/Genetic Dam - WHEN c.CalcType = 2 THEN 'Genetic' --Genetic Sire/Observed or Unknown Dam - WHEN c.CalcType = 3 THEN 'Observed' --Observed or Unknown Sire/Genetic Dam - WHEN c.CalcType = 4 THEN 'Excluded' --Observed Sire Excluded/Observed or Unknown Dam - WHEN c.CalcType = 5 THEN 'Excluded' --Observed Sire Excluded/Genetic Dam - WHEN c.CalcType = 6 THEN 'Unknown' --Observed or Unknown Sire/Observed Dam Excluded - WHEN c.CalcType = 7 THEN 'Genetic' --Genetic Sire/Observed Dam Excluded - WHEN c.CalcType = 8 THEN 'Excluded' --Both Observed Parents Excluded - WHEN c.CalcType = 9 THEN 'Genetic' --Genetic Sire/Provisional Dam - WHEN c.CalcType = 10 THEN 'Observed' --Observed or Unknown Sire/Provisional Dam - WHEN c.CalcType = 11 THEN 'Provisional Genetic' --Provisional Sire/Genetic Dam - WHEN c.CalcType = 12 THEN 'Provisional Genetic' --Provisional Sire/Observed or Unknown Dam - WHEN c.CalcType = 13 THEN 'Provisional Genetic' --Provisional Sire/Provisional Dam - END as method, - (cast(c.objectid as varchar(38)) + '_sire') as objectid - -from combinedrelationship c -where SireId != '0' and SireId is not null -AND c.ts > ? - -UNION ALL - -select - cast(c.AnimalId as varchar(4000)) as Id, - c.Calculation_Date as date, - null as enddate, - cast(c.DamId as varchar(4000)) as parent, - 'Dam' as relationship, - CASE - WHEN c.CalcType = 0 THEN 'Observed' --Unknown or Observed Sire/Dam - WHEN c.CalcType = 1 THEN 'Genetic' --Genetic Sire/Genetic Dam - WHEN c.CalcType = 2 THEN 'Observed' --Genetic Sire/Observed or Unknown Dam - WHEN c.CalcType = 3 THEN 'Genetic' --Observed or Unknown Sire/Genetic Dam - WHEN c.CalcType = 4 THEN 'Observed' --Observed Sire Excluded/Observed or Unknown Dam - WHEN c.CalcType = 5 THEN 'Genetic' --Observed Sire Excluded/Genetic Dam - WHEN c.CalcType = 6 THEN 'Excluded' --Observed or Unknown Sire/Observed Dam Excluded - WHEN c.CalcType = 7 THEN 'Excluded' --Genetic Sire/Observed Dam Excluded - WHEN c.CalcType = 8 THEN 'Excluded' --Both Observed Parents Excluded - WHEN c.CalcType = 9 THEN 'Provisional Genetic' --Genetic Sire/Provisional Dam - WHEN c.CalcType = 10 THEN 'Provisional Genetic' --Observed or Unknown Sire/Provisional Dam - WHEN c.CalcType = 11 THEN 'Genetic' --Provisional Sire/Genetic Dam - WHEN c.CalcType = 12 THEN 'Observed' --Provisional Sire/Observed or Unknown Dam - WHEN c.CalcType = 13 THEN 'Provisional Genetic' --Provisional Sire/Provisional Dam - END as method, - (cast(c.objectid as varchar(38)) + '_dam') as objectid - -from combinedrelationship c -where DamId != '0' and DamId is not null -AND c.ts > ? - -UNION ALL - -SELECT - cast(Infant_ID as nvarchar(4000)) as Id, - Foster_Start_Date as date, - Foster_End_Date as enddate, - cast(Foster_Mom as nvarchar(4000)) as parent, - 'Foster Dam' as relationship, - 'Observed' as method, - cast(objectid as varchar(38)) as objectid -From Birth_FosterMom -WHERE ts > ? - -UNION ALL - -select - cast(b.AnimalID as nvarchar(4000)) as Id, - b.Date as date, - null as enddate, - cast(b.SurrogateMotherID as nvarchar(4000)) as parent, - 'Surrogate Dam' as relationship, - 'Other' as method, - cast(objectid as varchar(38)) as objectid -from Af_Birth b -where SurrogateMotherID is not null -AND ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Pathology Diagnoses.sql b/onprc_ehr/resources/etl/deprecated/Pathology Diagnoses.sql deleted file mode 100644 index 04ed8eef4..000000000 --- a/onprc_ehr/resources/etl/deprecated/Pathology Diagnoses.sql +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(pa.AnimalID as nvarchar(4000)) as Id, - pa.Date as date, - pa.objectid as parentid, - SequenceNo as sort_order, - d.objectid - -From Path_AutopsyDiagnosis d -join Path_Autopsy pa on (d.AutopsyID = pa.AutopsyId) - -WHERE d.ts > ? - -UNION ALL - -Select - cast(pa.AnimalID as nvarchar(4000)) as Id, - pa.Date as date, - pa.objectid as parentid, - SequenceNo, - d.objectid - -From Path_biopsyDiagnosis d -join Path_Biopsy pa on (d.BiopsyID = pa.BiopsyId) - -WHERE d.ts > ? or pa.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/PregnancyConfirmation.sql b/onprc_ehr/resources/etl/deprecated/PregnancyConfirmation.sql deleted file mode 100644 index b5510277e..000000000 --- a/onprc_ehr/resources/etl/deprecated/PregnancyConfirmation.sql +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(AnimalID as nvarchar(4000)) as Id, - ConfirmationDate as date, - - cast(MaleId as nvarchar(4000)) as sire, - EstDeliveryDate as EstDeliveryDate, - - (SELECT rowid FROM labkey.ehr_lookups.lookups l WHERE l.set_name = 'PregnancyConfirm' and l.value = s1.value) as ConfirmationType, - --ConfirmationType as ConfirmationType, - --s1.Value as ConfirmationType, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - - --bm.ts as rowversion, - bm.objectid - -FROM Brd_PregnancyConfirm bm -LEFT JOIN Sys_parameters s1 ON (s1.Field = 'PregnancyConfirm' and s1.Flag = ConfirmationType) -LEFT JOIN Ref_Technicians rt ON (bm.Technician = rt.ID) -LEFT JOIN Sys_parameters s2 ON (s2.Field = 'DepartmentCode' and s2.Flag = rt.DeptCode) - -WHERE bm.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Problem List.sql b/onprc_ehr/resources/etl/deprecated/Problem List.sql deleted file mode 100644 index 10549f0f7..000000000 --- a/onprc_ehr/resources/etl/deprecated/Problem List.sql +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* -MasterProblemList - -Created by: Lakshmi Kolli Date: 8/16/2012 - -Tested by: Date: - Raymond Blasa 8/21/2012 - -*/ - - SELECT - cast(ml.AnimalID as nvarchar(4000)) as Id, - ML.DateCreated as date, - - CASE - WHEN c.CloseDate < ml.DateDisabled THEN coalesce(c.CloseDate, q.deathdate, q.departuredate) - ELSE coalesce(ML.DateDisabled, q.deathdate, q.departuredate) - END as enddate, - - null as parentid, - c.objectid as caseid, - s1.Value as category, - ml.objectid - -FROM MasterProblemList ML -left join Af_Case c on (c.CaseID = ml.CaseID) -LEFT JOIN Sys_parameters s1 ON (s1.Field = 'MasterProblemList' and s1.Flag = MasterProblem) -left join Af_Qrf q on (q.animalid = ml.animalid) - -WHERE (ml.ts > ? or q.ts > ? OR c.ts > ?) diff --git a/onprc_ehr/resources/etl/deprecated/Serology Results.sql b/onprc_ehr/resources/etl/deprecated/Serology Results.sql deleted file mode 100644 index 02fc7ce5e..000000000 --- a/onprc_ehr/resources/etl/deprecated/Serology Results.sql +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(h.AnimalID as nvarchar(4000)) as Id, - h.DATE, - 'Virology' as category, - - tissue, ----- Ref_SnomedLists - sno1.Description as tissueMeaning, - agent, ------ Ref_SnomedLists - sno2.Description as agentMeaning, - --Method as MethodInt , - s1.value as Method, - --Negative as NegativeInt , - null as numericResult, - null as units, - s2.value as result, - cln.Positive as qualifier, - - cln.Remarks as Remark, - - --cln.ts as rowversion, - cln.objectid, - h.objectid as runid - -FROM Cln_VirologyData cln - left join Sys_parameters s1 on (s1.Flag = Method and s1.Field = 'VirologyMethod') - left join Sys_Parameters s2 on (s2.Field = 'VirologyNegative' And s2.Flag = cln.Negative) - left join ref_snomed sno1 on (sno1.SnomedCode = cln.Tissue) - left join ref_snomed sno2 on (sno2.SnomedCode = cln.Agent) - left join Cln_VirologyHeader h on (cln.ClinicalKey = h.ClinicalKey) - -where cln.ts > ? or h.ts > ? - -UNION ALL - -SELECT - cast(sh.AnimalID as nvarchar(4000)) as Id, - sh.DATE, - 'Serology' as category, - - Tissue as Tissue , ----- Ref_SnomedLists - sno.Description as tissueMeaning, - agent, - sno2.description as agentMeaning, - s2.Value as method, - - null as numericresult, - null as units, - --at least let this field show whether it's positive or not - CASE - WHEN Negative = 0 THEN 'Positive' - WHEN Negative = 1 THEN 'Negative' - WHEN Negative = 3 THEN 'Indeterminate' - else null - END as result, - rtrim(positive) as qualifier, - - Remarks as remark, - - --cln.ts as rowversion, - cln.objectid, - sh.objectid as runId - -FROM Cln_SerologyData cln -left join Cln_SerologyHeader sh on (cln.ClinicalKey = sh.ClinicalKey) -left join Sys_parameters s2 on (s2.Field = 'SerologyMethod' and s2.Flag = cln.Method) -left join ref_snomed sno ON (sno.SnomedCode = cln.Tissue) -left join ref_snomed sno2 ON (sno2.SnomedCode = cln.Agent) - -WHERE cln.ts > ? or sh.ts > ? - -UNION ALL - -SELECT - h.AnimalID, - h.DATE, - 'Serology' as category, - --s1.Value as category2, - - h.Tissue, - sno.Description as tissueMeaning, - 'E-20010' as agent, - null as agentMeaning, - rt.RareTest as method, - - null as numericresult, - null as units, - CASE WHEN cln.Value like 'Negative' THEN 'Negative' ELSE cln.value END as Result, - null as qualifier, - - cln.Remarks as Remark, - cln.objectid, - rt.objectid as runid - -FROM Cln_RareTestData cln -left join Ref_RareTests rt on (rt.RareTestID = cln.RareTestID) -left join Cln_RareTestHeader h on (h.ClinicalKey = cln.ClinicalKey) -left join Sys_Parameters s1 on (s1.Flag = h.Category And s1.Field = 'RequestCategory') -left join Sys_Parameters s2 on (s2.Flag = h.Method And s2.Field = 'AnalysisMethod') -left join Ref_SnoMed sno on (h.Tissue = sno.SnomedCode) -left join Specimen sp on (sp.Value = h.Specimen) - -where rt.RareTest = 'Interferon-Gamma Mycobacterium Testing (Primagam)' -AND (cln.ts > ? OR rt.ts > ? OR h.ts > ?) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/TB Tests.sql b/onprc_ehr/resources/etl/deprecated/TB Tests.sql deleted file mode 100644 index 87dcbd85c..000000000 --- a/onprc_ehr/resources/etl/deprecated/TB Tests.sql +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(w.AnimalID as nvarchar(4000)) as Id, - w.date, - (cast(w.objectid as varchar(38)) + '_tb') as objectid - -FROM af_weights w -where w.tbflag = 1 and w.ts > ? - -UNION ALL - -SELECT - dx.AnimalID, - dx.Date, - cast(sno.objectid as varchar(36)) as objectid - -FROM Cln_DXSnomed sno - LEFT JOIN Cln_DX dx ON (sno.DiagnosisID = dx.DiagnosisID) - LEFT JOIN af_weights w2 ON (w2.AnimalId = dx.AnimalID AND w2.Date = dx.Date and w2.TBFlag = 1) - -WHERE sno.Snomed = 'P-54268' AND w2.AnimalId IS NULL and sno.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Tissue Distributions.sql b/onprc_ehr/resources/etl/deprecated/Tissue Distributions.sql deleted file mode 100644 index 11e066040..000000000 --- a/onprc_ehr/resources/etl/deprecated/Tissue Distributions.sql +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(td.AnimalID as varchar(4000)) as Id, - td.Date, - s3.Value as Origination, - - (select rowid from labkey.onprc_ehr.customers r where r.objectid = tr.objectid) as recipient, ---ptd.Recipient, --Ref_TissueRecipients - ptd.Organ as tissue, --Ref_Snomed - sno.Description as tissueMeaning, ---ptd.Affiliation as AffiliationInt, - s1.Value as requestCategory, ---Sample as SampleInt, - s2.Value as sampleType, - - ptd.objectid - -From Path_TissueDistributions td - left join Path_TissueDetails ptd on (td.tissueId = ptd.tissueid) - left join Sys_Parameters s1 on (s1.Field = 'TissueAffiliation' and ptd.Affiliation = s1.Flag) - left join Sys_Parameters s2 on (s2.Field = 'TissueSample' and ptd.Sample = s2.Flag) - left join Sys_Parameters s3 on (s3.flag = td.Origination And s3.Field = 'TissueOrigination' ) - left join ref_snomed sno on (sno.SnomedCode = ptd.organ) - left join Ref_TissueRecipients tr ON (tr.recipientId = ptd.recipient) - -WHERE (ptd.ts > ? or td.ts > ?) - diff --git a/onprc_ehr/resources/etl/deprecated/Tissue Samples.sql b/onprc_ehr/resources/etl/deprecated/Tissue Samples.sql deleted file mode 100644 index 38872d58a..000000000 --- a/onprc_ehr/resources/etl/deprecated/Tissue Samples.sql +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(pa.AnimalID as nvarchar(4000)) as Id, - pa.date as date, - 'Necropsy' as type, - pat.objectid as parentId, - pat.Organ as tissue, ----- Ref_SnomedLists - sno.Description as tissueMeaning, - - --pat.Preparation as PreparationInt, - s1.Value as Preparation, - pat.Weight as Weight, - --pat.WeightModifier as WeightModifierInt, - s2.Value as tissueCondition, - --pat.Appearance as AppearanceInt, - s3.Value as remark, - --Pat.Displayorder as Displayorder, - --pa.objectid as parentid, - - pat.objectid - --pat.ts as rowversion - -From Path_AutopsyWtsMaterials Pat - left join Sys_Parameters s1 on (Pat.Preparation = s1.Flag And s1.Field = 'AutopsyPreparation') - left join Sys_Parameters s2 on (Pat.WeightModifier = s2.Flag And s2.Field = 'AutopsyWeightModifier') - left join Sys_Parameters s3 on (Pat.Appearance = s3.Flag And s3.Field = 'TissueAppearance') - left join ref_snomed sno ON (sno.SnomedCode = pat.Organ) - left join Path_Autopsy pa ON (pa.AutopsyId = pat.AutopsyID) -where (pat.ts > ? or pa.ts > ?) - -union all - -Select - cast(pa.AnimalID as nvarchar(4000)) as Id, - pa.date as date, - 'Biopsy' as type, - pa.objectid as parentid, - - Organ as tissue, ----- Ref_SnomedLists - sno.Description as tissueMeaning, - --Preparation as PreparationInt, - s1.Value as Preparation, - - Weight as Weight, - --WeightModifier as WeightModifierInt, - s2.Value as tissueCondition, - --Appearance as AppearanceInt, - s3.Value as remark, - --null as displayorder, - - pat.objectid - --pat.ts as rowversion - -From Path_BiopsyWtsMaterials Pat - left join Sys_Parameters s1 on (Pat.Preparation = s1.Flag And s1.Field = 'AutopsyPreparation') - left join Sys_Parameters s2 on (Pat.Appearance = s2.Flag And s2.Field = 'TissueAppearance') - left join sys_Parameters s3 on (Pat.WeightModifier = s3.Flag And s3.Field = 'AutopsyWeightModifier') - left join ref_snomed sno ON (sno.SnomedCode = pat.Organ) - left join Path_biopsy pa ON (pa.BiopsyID = pat.BiopsyID) - -where (pat.ts > ? or pa.ts > ?) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/Urinalysis Results.sql b/onprc_ehr/resources/etl/deprecated/Urinalysis Results.sql deleted file mode 100644 index 5c0c33eaa..000000000 --- a/onprc_ehr/resources/etl/deprecated/Urinalysis Results.sql +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright (c) 2012-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---Please note: All lab values = -1 is should be substitued with a Null value - -SELECT - --t.ClinicalKey , - cast(t.Id as nvarchar(4000)) as Id, - t.DATE , - --t.Specimen , -- Specimen database table - --sp.Name, - --sp.SNOMEDCODE as snomed, - t.MethodInt , - s2.Value as method, - - t.CollectionInt , - s5.Value as collectionMethod, - t.result, - t.rangeMax, - t.QualResult, - t.TestId, - - --t.rowversion, - (cast(t.objectid as varchar(38)) + '_' + t.TestId) as objectid, - t.objectid as runid - -FROM ( - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s4.value as QualResult, - 'App' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s4 on (s4.Field = 'UrineAppearance' and s4.Flag = Appearance) -where s4.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s6.value as QualResult, - 'Color' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s6 on (s6.Field = 'UrineColor' and s6.Flag = Color) -where s6.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s7.value as QualResult, - 'Bact' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s7 on (s7.Field = 'BacteriaCount' and s7.Flag = Bacteria) -where s7.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s8.value as QualResult, - 'Prot' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s8 on (s8.Field = 'UrineMeasurement' and s8.Flag = Protein) -where s8.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s9.value as QualResult, - 'Glu' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s9 on (s9.Field = 'UrineMeasurement' and s9.Flag = Glucose) -where s9.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s10.value as QualResult, - 'Ket' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s10 on (s10.Field = 'UrineMeasurement' and s10.Flag = Ketone) -where s10.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s11.value as QualResult, - 'Bili' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s11 on (s11.Field = 'UrineMeasurement' and s11.Flag = Bilirubin) -where s11.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s12.value as QualResult, - 'Blood' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s12 on (s12.Field = 'UrineMeasurement' and s12.Flag = Blood) -where s12.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s13.value as QualResult, - 'Cast-1' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s13 on (s13.Field = 'Casts' and s13.Flag = CastsType1) -where s13.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - s14.value as QualResult, - 'Cast-2' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -left join Sys_parameters s14 on (s14.Field = 'Casts' and s14.Flag = CastsType2) -where s14.value is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - CASE WHEN RBCMin != -1 THEN RBCMin ELSE NULL END as result, - CASE WHEN RBCMax != -1 THEN RBCMax ELSE NULL END as rangeMax, - null as QualResult, - 'RBC' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE RBCMin != 0 - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - CASE WHEN WBCMin != -1 THEN WBCMin ELSE null END as result, - CASE WHEN WBCMax != -1 THEN WBCMax ELSE null END as rangeMax, - null as QualResult, - 'WBC' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE WBCMin is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - SpecificGravity as result, - null as rangeMax, - null as QualResult, - 'SpecGrav' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE SpecificGravity is not null and SpecificGravity != -1 - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - CASE WHEN EpitheliaMin != -1 THEN EpitheliaMin ELSE null END as result, - CASE WHEN EpitheliaMax != -1 THEN EpitheliaMax ELSE null END as rangeMax, - null as QualResult, - 'Epith' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE EpitheliaMin is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - PHValue as result, - null as rangeMax, - null as QualResult, - 'pH' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE cln.PHValue IS NOT NULL and cln.PHValue != -1 - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - CASE WHEN CastsMin != -1 THEN CastsMin ELSE null END as result, - CASE WHEN CastsMax != -1 THEN CastsMax ELSE null END as rangeMax, - null as QualResult, - 'Casts' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE CastsMin is not null - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - Crystals as QualResult, - 'Crystals' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE Crystals is not null and Crystals != '' - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - Urobilinogen as QualResult, - 'Urobili' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE Urobilinogen is not null and Urobilinogen != '' - -UNION ALL - -SELECT - ClinicalKey , - AnimalID as Id , - DATE , - Specimen as Specimen , -- Specimen database table - Method as MethodInt , - Collection as CollectionInt , - null as result, - null as rangeMax, - Other as QualResult, - 'Other' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_Urinalysis cln -WHERE Other is not null and Other != '' - -) t - -left join Sys_parameters s2 on (s2.Field = 'AnalysisMethodUrinalysis' and s2.Flag = t.MethodInt) -left join Sys_parameters s5 on (s5.Field = 'UrineCollection' and s5.Flag = t.CollectionInt) - -where t.rowversion > ? diff --git a/onprc_ehr/resources/etl/deprecated/allowableAnimals.sql b/onprc_ehr/resources/etl/deprecated/allowableAnimals.sql deleted file mode 100644 index 9a2dd7f08..000000000 --- a/onprc_ehr/resources/etl/deprecated/allowableAnimals.sql +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT * FROM ( - -select -CASE WHEN t.protocolId IS NULL THEN project WHEN t.protocolId = t.project THEN null ELSE t.project END as project, -CASE WHEN t.protocolId = project THEN RTRIM(ltrim(i2.IACUCCode)) ELSE null END as protocol, -t.species, -t.gender, -t.allowed, -t.startdate, -t.endDate, -t.objectid - -from ( - -select -y.ProjectID as project, -(select top 1 ipc.projectparentid - from Ref_ProjectsIACUC rpi2 join Ref_IACUCParentChildren ipc on (rpi2.ProjectID = ipc.ProjectParentID and ipc.datedisabled is null) - where ipc.projectchildid = r.projectid order by ipc.datecreated desc -) as protocolId, - -(select max(rpi2.ts) as maxTs - from Ref_ProjectsIACUC rpi2 join Ref_IACUCParentChildren ipc on (rpi2.ProjectID = ipc.ProjectParentID and ipc.datedisabled is null) - where ipc.projectchildid = r.projectid -) as maxTs, -y.CurrentYearStartDate as startdate, -y.CurrentYearEndDate as enddate, ---a.Species, -sp.Value as species, -a.Strain, -a.Sex, -s.Value as gender, -a.Age, -a.NumAnimals as allowed, -a.Remarks as comment, -a.objectid - -from IACUC_SLAYearly y -join IACUC_SLAAnimals a on (y.SLAYearlyID = a.SLAYearlyID) -join ref_ProjectsIACUC r on (r.ProjectID = y.ProjectID) -left join Sys_Parameters sp on (sp.field = 'SmallAnimals' and sp.Flag = a.Species) -left join Sys_Parameters s on (s.field = 'RodentSex' and s.Flag = a.Sex) - -where (y.DateDisabled is null and a.DateDisabled is Null) and y.CurrentYearEndDate > '1/1/2010' -and (y.ts > ? OR a.ts > ? OR r.ts > ?) - -) t - -LEFT JOIN Ref_ProjectsIACUC i2 ON (i2.ProjectID = t.protocolId) - -WHERE (maxTs > ? or maxTs IS NULL) - -) t - -WHERE (t.project IS NOT NULL OR t.protocol IS NOT NULL) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/animal_group_members.sql b/onprc_ehr/resources/etl/deprecated/animal_group_members.sql deleted file mode 100644 index c8cbcbb8f..000000000 --- a/onprc_ehr/resources/etl/deprecated/animal_group_members.sql +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -SELECT - t.Id, - t.groupId, - t.groupName, - t.date, - CASE - WHEN (t.enddate IS NULL) THEN t.poolDisabledDate - WHEN (t.poolDisabledDate IS NULL) THEN t.enddate - WHEN (t.enddate < t.poolDisabledDate) THEN t.enddate - ELSE t.poolDisabledDate - END as enddate, - t.objectid - -FROM ( -Select - cast(p.AnimalID as nvarchar(4000)) as Id, - (select rowid FROM labkey.ehr.animal_groups g where g.name = rp.description) as groupId, - rp.Description as groupName, - - DateAssigned as date, - coalesce(DateReleased, q.deathdate, q.departuredate) as enddate, - rp.datedisabled as poolDisabledDate, - p.objectid - -From Af_Pool p -left join ref_pool rp ON (rp.PoolCode = p.PoolCode) -left join Af_Qrf q on (q.animalid = p.animalid) - -where (p.ts > ? or q.ts > ? or rp.ts > ?) and rp.ShortDescription in ('CBG', 'EBG', 'HBG', 'PBG', 'STG', 'SBG', 'JBG', 'CCBG', 'CTG') - -) t - diff --git a/onprc_ehr/resources/etl/deprecated/billing.sql b/onprc_ehr/resources/etl/deprecated/billing.sql deleted file mode 100644 index f8dc7d724..000000000 --- a/onprc_ehr/resources/etl/deprecated/billing.sql +++ /dev/null @@ -1,573 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---chargableItems, only importing new items -INSERT INTO labkey.onprc_billing.chargeableItems -(name, shortName, category, itemCode, departmentCode, active, container) - -SELECT t.name, t.shortName, t.category, t.itemCode, t.departmentCode, t.active, t.container FROM ( - -SELECT - t.name, - max(t.shortname) as shortname, - max(t.category) as category, - max(t.itemcode) as itemcode, - max(t.departmentcode) as departmentcode, - min(active) as active, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container -FROM ( -Select - 'Small Animal Fees - ' + s2.Value + ': ' + s3.Value + ', ' + s4.value as name, - 'Small Animal Fees' as shortname, - 'Small Animal Per Diem' as category, - '7' as itemcode, - 'SLAU' as departmentcode, - CASE WHEN rf.DateDisabled IS NULL THEN 1 ELSE 0 END as active -From IRIS_Production.dbo.Ref_FeesRodents rf ---LEFT JOIN IRIS_Production.dbo.Sys_Parameters s1 on (rf.Species = s1.Flag And s1.Field = 'SmallAnimals') - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s2 on (rf.CageType = s2.Flag And s2.Field = 'SmallCageType') - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s3 on (rf.CageSize = s3.Flag And s3.Field = 'SmallCageSize') - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s4 on (rf.Species = s4.Flag And s4.Field = 'SmallAnimals') - where rf.DateDisabled is null -) t where name is not null GROUP BY t.name --- EO Rodent definitions - -UNION ALL - -SELECT - rfp.ProcedureName as name, - null as shortName, - s3.value as category, - rfp.ProcedureID as itemCode, - 'PDAR' as departmentCode, - CASE WHEN rfp.DateDisabled IS NULL THEN 1 ELSE 0 END as active, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container -FROM IRIS_Production.dbo.Ref_FeesProcedures rfp -left join IRIS_Production.dbo.Sys_Parameters s3 on (s3.Field = 'ChargeType'and s3.Flag = rfp.ChargeType) - -UNION ALL - ---add ref_feesSurgical to chargeableItems -select - t.name, - max(t.shortName) as shortName, - 'Surgery' as category, - max(t.itemCode) as itemCode, - 'PSURG' as departmentCode, - MAX(t.active) as active, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container -FROM ( - -Select - s.ProcedureName + ' - No Staff' as name, - s.ProcedureName as shortName, - fs.ProcedureID as itemCode, - CASE WHEN fs.DateDisabled is null THEN 1 else 0 END as active - -From IRIS_Production.dbo.Ref_FeesSurgical fs -LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure s ON (fs.ProcedureID = s.ProcedureID) -WHERE s.procedureName IS NOT NULL -UNION ALL - -Select - s.ProcedureName + ' - Staff' as name, - s.ProcedureName as shortName, - fs.ProcedureID as itemCode, - CASE WHEN fs.DateDisabled is null THEN 1 else 0 END as active - -From IRIS_Production.dbo.Ref_FeesSurgical fs -LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure s ON (fs.ProcedureID = s.ProcedureID) -WHERE s.procedureName IS NOT NULL -) t - -GROUP BY name - -UNION ALL ---add lease fees to chargeableItems -SELECT - name, - max(shortName) as shortName, - 'Lease Fees' as category, - max(t.itemCode) as itemCode, - 'PDAR' as departmentCode, - 1 as active, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -FROM ( -Select - CASE - WHEN rfl.AssignPool = 0 AND rf.ProcedureName = 'Lease Setup Fees' THEN rf.ProcedureName - WHEN rfl.AssignPool = 0 AND rf.ProcedureName = 'Animal Lease Fee' THEN rf.ProcedureName + ' - TMB' - WHEN s1.Value IS null THEN rf.ProcedureName + ' - General: ' + cast(rfl.AssignPool AS nvarchar) + '->' + cast(rfl.ReleasePool AS nvarchar) - ELSE rf.ProcedureName + ' - ' + s1.Value + ': ' + cast(rfl.AssignPool AS nvarchar) + '->' + cast(rfl.ReleasePool AS nvarchar) - END as name, - rf.ProcedureName as shortName, - rfl.ProcedureID as itemCode - -From IRIS_Production.dbo.Ref_FeesLease rfl - left join IRIS_Production.dbo.Sys_Parameters s1 on (s1.Flag = rfl.AgeCategory and s1.Field = 'AgeCategory') - left join IRIS_Production.dbo.Ref_FeesProcedures rf ON (rf.ProcedureID = rfl.procedureId) - left join labkey.onprc_billing.chargeableItems lk ON (lk.name = rf.procedureName) -where rfl.DateDisabled is null -) t -GROUP BY name - ---TODO: procedure fee definition - -) t -LEFT JOIN labkey.onprc_billing.chargeableItems ci ON (ci.name = t.name) -WHERE ci.name IS NULL; - - - - ---chargeableExemptions -TRUNCATE TABLE labkey.onprc_billing.chargeRateExemptions; -INSERT INTO labkey.onprc_billing.chargeRateExemptions -(project, chargeId, unitCost, startDate, enddate, container) -SELECT - projectId, - (SELECT max(rowid) FROM labkey.onprc_billing.chargeableItems ci WHERE ci.name = r.ProcedureName) as chargeId, - ChargeAmount as unitCost, - rf.DateCreated as startDate, - rf.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container -FROM IRIS_Production.dbo.Ref_FeesSpecial rf -left join IRIS_Production.dbo.Ref_FeesProcedures r ON (rf.ProcedureID = r.ProcedureID) -WHERE coalesce(rf.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02'; - --- NOTE: the way PRIMe and IRIS handle lease fees is different. PRIMe has more categories --- for these charges, so expand out that list on exemptions -INSERT INTO labkey.onprc_billing.chargeRateExemptions -(project, chargeId, unitCost, startDate, enddate, container) -SELECT - projectId, - lfd.chargeId, - ChargeAmount as unitCost, - rf.DateCreated as startDate, - rf.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container -FROM IRIS_Production.dbo.Ref_FeesSpecial rf - left join IRIS_Production.dbo.Ref_FeesProcedures r ON (rf.ProcedureID = r.ProcedureID) - left join labkey.onprc_billing.leaseFeeDefinition lfd on (lfd.chargeId != (select rowId from labkey.onprc_billing.chargeableItems where name = 'Lease Setup Fees')) -WHERE (r.procedureName = 'Animal Lease Fee' and rf.DateDisabled is null) -AND coalesce(rf.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02'; ---EO: lease fee exemptions - ---we also need special handling of per diems / tiers -INSERT INTO labkey.onprc_billing.chargeRateExemptions -(project, chargeId, unitCost, startDate, enddate, container) -SELECT * FROM ( -SELECT - t.projectId, - (SELECT max(rowid) FROM labkey.onprc_billing.chargeableItems ci WHERE ci.name = (t.ProcedureName + t2.col)) as chargeId, - t.unitCost, - t.startDate, - t.enddate, - t.container -FROM ( -SELECT - projectId, - procedureName, - ChargeAmount as unitCost, - rf.DateCreated as startDate, - rf.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container -FROM IRIS_Production.dbo.Ref_FeesSpecial rf -left join IRIS_Production.dbo.Ref_FeesProcedures r ON (rf.ProcedureID = r.ProcedureID) -WHERE coalesce(rf.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02' -and r.ProcedureName like 'Per Diem%' -) t -LEFT JOIN (SELECT * FROM (select ' Tier 1' as col UNION ALL SELECT ' Tier 2' UNION ALL SELECT ' Tier 3') t4) t2 on (1=1) -) t2 WHERE t2.chargeId IS NOT NULL AND t2.enddate IS NULL - - -INSERT INTO labkey.onprc_billing.chargeRateExemptions -(project, chargeId, unitCost, startDate, enddate, container) -Select - fs.ProjectID, --Ref_ProjectsIacuc - lk.rowid as chargeid, - --lk.name, - --fs.ChargeAmountStaff, - fs.ChargeAmountNoStaff as unitCost, - --fs.ChargeDate, - fs.DateCreated as startdate, - fs.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesSpecialSurg fs -LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure s ON (fs.ProcedureID = s.ProcedureID) -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = s.procedureName + ' - No Staff' AND lk.category = 'Surgery') -WHERE coalesce(fs.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02'; - -INSERT INTO labkey.onprc_billing.chargeRateExemptions -(project, chargeId, unitCost, startDate, enddate, container) -Select - fs.ProjectID, --Ref_ProjectsIacuc - lk.rowid as chargeid, - --lk.name, - fs.ChargeAmountStaff as unitCost, - --fs.ChargeAmountNoStaff as unitCost, - --fs.ChargeDate, - fs.DateCreated as startdate, - fs.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesSpecialSurg fs -LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure s ON (fs.ProcedureID = s.ProcedureID) -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = s.procedureName + ' - Staff' AND lk.category = 'Surgery') -WHERE coalesce(fs.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02'; - ---creditAccount -TRUNCATE TABLE labkey.onprc_billing.creditAccount; -INSERT INTO labkey.onprc_billing.creditAccount -(chargeId, account, startDate, enddate, container) -Select - lk.rowid as chargeId, - --f.ItemCode, --Ref_FeesProcedures, Ref_SurgProcedure - f.CreditAlias as account, - f.DateCreated as startdate, - f.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesCreditAlias f -left join IRIS_Production.dbo.Ref_FeesProcedures fp ON (f.ItemCode = cast(fp.ProcedureID as nvarchar) + 'C') -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = fp.procedureName) -WHERE lk.rowid is not null; - ---lease fees -INSERT INTO labkey.onprc_billing.creditAccount -(chargeId, account, startDate, enddate, container) -select - lfd.chargeId, ---f.ItemCode, --Ref_FeesProcedures, Ref_SurgProcedure - f.CreditAlias as account, - f.DateCreated as startdate, - f.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesCreditAlias f - left join IRIS_Production.dbo.Ref_FeesProcedures fp ON (f.ItemCode = cast(fp.ProcedureID as nvarchar) + 'C') - left join labkey.onprc_billing.chargeableItems lk ON (lk.name = fp.procedureName) - left join labkey.onprc_billing.leaseFeeDefinition lfd on (lfd.chargeId != (select rowId from labkey.onprc_billing.chargeableItems where name = 'Lease Setup Fees')) -WHERE fp.ProcedureName = 'Animal Lease Fee' and lfd.chargeId is not null; - ---surgery -INSERT INTO labkey.onprc_billing.creditAccount -(chargeId, account, startDate, enddate, container) -select - lk.rowId AS chargeId, - --lk.name, - --fs.ChargeCode, - --f.ItemCode, --Ref_FeesProcedures, Ref_SurgProcedure - --s.ProcedureID, - coalesce(f.CreditAlias, '90184863') as account, - COALESCE(f.DateCreated, '') as startdate, - f.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_SurgProcedure s - JOIN IRIS_Production.dbo.Ref_FeesSurgical fs ON (fs.ProcedureID = s.ProcedureID and fs.DateDisabled is null) - left JOIN IRIS_Production.dbo.Ref_FeesCreditAlias f ON (f.ItemCode = cast(fs.ProcedureID as nvarchar(10)) + 'C' and f.DateDisabled is null) - left join labkey.onprc_billing.chargeableItems lk ON (lk.category = 'Surgery' AND (lk.name LIKE s.ProcedureName + ' - Staff' OR lk.name LIKE s.ProcedureName + ' - No Staff')) - WHERE lk.rowId is not null - ---SLA -INSERT INTO labkey.onprc_billing.creditAccount -(chargeId, account, startDate, enddate, container) -Select - (select max(rowid) from labkey.onprc_billing.chargeableItems ci WHERE ci.active = 1 AND ci.name = 'Small Animal Fees - ' + s2.Value + ': ' + s3.Value + ', ' + s4.value) as chargeId, - -1 as account, - rf.dateCreated as startdate, - rf.datedisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - From IRIS_Production.dbo.Ref_FeesRodents rf - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s2 on (rf.CageType = s2.Flag And s2.Field = 'SmallCageType') - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s3 on (rf.CageSize = s3.Flag And s3.Field = 'SmallCageSize') - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s4 on (rf.Species = s4.Flag And s4.Field = 'SmallAnimals') - ---EO credit account - ---charge rates -TRUNCATE TABLE labkey.onprc_billing.chargeRates; -INSERT INTO labkey.onprc_billing.chargeRates -(chargeId, unitCost, startDate, enddate, container) - select * from ( - Select - (select max(rowid) from labkey.onprc_billing.chargeableItems ci WHERE ci.active = 1 AND ci.name = 'Small Animal Fees - ' + s2.Value + ': ' + s3.Value + ', ' + s4.value) as chargeId, - rf.BaseCharge as unitCost, - rf.DateCreated as startdate, - rf.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - - From IRIS_Production.dbo.Ref_FeesRodents rf - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s2 on (rf.CageType = s2.Flag And s2.Field = 'SmallCageType') - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s3 on (rf.CageSize = s3.Flag And s3.Field = 'SmallCageSize') - LEFT JOIN IRIS_Production.dbo.Sys_Parameters s4 on (rf.Species = s4.Flag And s4.Field = 'SmallAnimals') - WHERE coalesce(rf.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02' - ) t where t.chargeId is not null - - - -INSERT INTO labkey.onprc_billing.chargeRates -(chargeId, unitCost, startDate, enddate, container) -Select - lk.rowid as chargeId, - c.BaseCharge as unitCost, - c.DateCreated as startdate, - c.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesClinical c -left join IRIS_Production.dbo.Ref_FeesProcedures r ON (c.ProcedureID = r.ProcedureID) -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = r.procedureName) -WHERE coalesce(c.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02' -; - -INSERT INTO labkey.onprc_billing.chargeRates -(chargeId, unitCost, startDate, enddate, container) -Select - lk.rowid as chargeId, - c.BaseCharge as unitCost, - c.DateCreated as startdate, - c.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesMiscellaneous c -left join IRIS_Production.dbo.Ref_FeesProcedures r ON (c.ProcedureID = r.ProcedureID) -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = r.procedureName) -WHERE coalesce(c.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02' -; - ---add surg fees -INSERT INTO labkey.onprc_billing.chargeRates -(chargeId, unitCost, startDate, enddate, container) -Select - lk.rowid as chargeId, - c.SurgeryStaff as unitCost, - c.DateCreated as startdate, - c.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesSurgical c -left join IRIS_Production.dbo.Ref_SurgProcedure r ON (c.ProcedureID = r.ProcedureID) -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = (r.procedureName + ' - Staff')) -WHERE r.ProcedureID is not null AND coalesce(c.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02' - -UNION ALL - -Select - lk.rowid as chargeId, - c.NoStaff as unitCost, - c.DateCreated as startdate, - c.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -From IRIS_Production.dbo.Ref_FeesSurgical c -left join IRIS_Production.dbo.Ref_SurgProcedure r ON (c.ProcedureID = r.ProcedureID) -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = (r.procedureName + ' - No Staff')) -WHERE r.ProcedureID is not null AND coalesce(c.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02'; ---EO surg fees - - -INSERT INTO labkey.onprc_billing.chargeRates -(chargeId, unitCost, startDate, enddate, container) -select - (SELECT rowid FROM labkey.onprc_billing.chargeableItems ci WHERE ci.name = fp.ProcedureName) as chargeId, - pd.BaseCharge as unitCost, - pd.DateCreated as startdate, - pd.DateDisabled as enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -from IRIS_Production.dbo.Ref_FeesPerDiem pd - left join IRIS_Production.dbo.Ref_FeesProcedures fp - left join IRIS_Production.dbo.Sys_Parameters s1 ON (s1.Field = 'LocationType' and s1.Flag = HousingType) - left join IRIS_Production.dbo.Sys_Parameters s2 ON (s2.Field = 'LocationDefinition' and s2.Flag = HousingDefinition) - - ON ( - fp.HousingDefinition = pd.HousingDefinition AND - fp.HousingType = pd.HousingType AND - fp.DateCreated <= coalesce(pd.DateDisabled, CURRENT_TIMESTAMP) AND - coalesce(fp.DateDisabled, CURRENT_TIMESTAMP) >= pd.DateCreated - ) -where fp.ProcedureID is not null AND coalesce(pd.DateDisabled, CURRENT_TIMESTAMP) >= '2009/05/02' - - ---add lease records to charge rates -INSERT INTO labkey.onprc_billing.chargeRates -(chargeId, unitCost, startDate, enddate, container) -select - lk.rowid, - t.unitCost, - --lk.name, - t.startdate, - t.enddate, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container - -FROM ( -Select - CASE - WHEN rfl.AssignPool = 0 AND rf.ProcedureName = 'Lease Setup Fees' THEN rf.ProcedureName - WHEN rfl.AssignPool = 0 AND rf.ProcedureName = 'Animal Lease Fee' THEN rf.ProcedureName + ' - TMB' - WHEN s1.Value IS null THEN rf.ProcedureName + ' - General: ' + cast(rfl.AssignPool AS nvarchar) + '->' + cast(rfl.ReleasePool AS nvarchar) - ELSE rf.ProcedureName + ' - ' + s1.Value + ': ' + cast(rfl.AssignPool AS nvarchar) + '->' + cast(rfl.ReleasePool AS nvarchar) - END as name, - - CASE WHEN rf.ProcedureName = 'Lease Setup Fees' THEN rfl.SetupFee ELSE rfl.BaseCharge END as unitCost, - rfl.DateCreated as startdate, - rfl.DateDisabled as enddate, - rfl.objectid - -From IRIS_Production.dbo.Ref_FeesLease rfl - left join IRIS_Production.dbo.Sys_Parameters s1 on (s1.Flag = rfl.AgeCategory and s1.Field = 'AgeCategory') - left join IRIS_Production.dbo.Ref_FeesProcedures rf ON (rf.ProcedureID = rfl.procedureId) - -) t -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = t.name) -WHERE coalesce(t.enddate, CURRENT_TIMESTAMP) >= '2009/05/02'; - ---lease fee definition -TRUNCATE TABLE labkey.onprc_billing.leaseFeeDefinition; -INSERT INTO labkey.onprc_billing.leaseFeeDefinition -(chargeId, minAge, maxAge, active, assignCondition, releaseCondition, objectid) -SELECT - lk.rowid, - --t.name, - t.minAge, - t.maxAge, - t.active, - t.assignCondition, - t.releaseCondition, - t.objectid - -FROM ( -Select - CASE - WHEN rfl.AssignPool = 0 AND rf.ProcedureName = 'Lease Setup Fees' THEN rf.ProcedureName - WHEN rfl.AssignPool = 0 AND rf.ProcedureName = 'Animal Lease Fee' THEN rf.ProcedureName + ' - TMB' - WHEN s1.Value IS null THEN rf.ProcedureName + ' - General: ' + cast(rfl.AssignPool AS nvarchar) + '->' + cast(rfl.ReleasePool AS nvarchar) - ELSE rf.ProcedureName + ' - ' + s1.Value + ': ' + cast(rfl.AssignPool AS nvarchar) + '->' + cast(rfl.ReleasePool AS nvarchar) - END as name, - - CASE - WHEN rfl.AgeCategory = 1 THEN 0 - WHEN rfl.AgeCategory = 2 THEN 1 - WHEN rfl.AgeCategory = 3 THEN 4 - WHEN rfl.AgeCategory = 4 THEN 18 - END as minAge, - CASE - WHEN rfl.AgeCategory = 1 THEN 1 - WHEN rfl.AgeCategory = 2 THEN 4 - WHEN rfl.AgeCategory = 3 THEN 18 - WHEN rfl.AgeCategory = 4 THEN null - END as maxAge, - - --TODO: translate - rfl.AssignPool as assignCondition, --Ref_Pool - rfl.ReleasePool as releaseCondition, --Ref_Pool - CASE WHEN rf.ProcedureName = 'Lease Setup Fees' THEN rfl.SetupFee ELSE rfl.BaseCharge END as unitCost, - 1 as active, - rfl.objectid - -From IRIS_Production.dbo.Ref_FeesLease rfl - left join IRIS_Production.dbo.Sys_Parameters s1 on (s1.Flag = rfl.AgeCategory and s1.Field = 'AgeCategory') - left join IRIS_Production.dbo.Ref_FeesProcedures rf ON (rf.ProcedureID = rfl.procedureId) -where rfl.DateDisabled is null -) t -left join labkey.onprc_billing.chargeableItems lk ON (lk.name = t.name); - ---per diem definition -truncate table labkey.onprc_billing.perDiemFeeDefinition; -INSERT INTO labkey.onprc_billing.perDiemFeeDefinition (chargeId, housingType, housingDefinition, tier) -select -(SELECT rowid FROM labkey.onprc_billing.chargeableItems ci WHERE ci.name = r.ProcedureName) as chargeId, -(select rowid from labkey.ehr_lookups.lookups l WHERE l.value = s1.Value and l.set_name = 'LocationType') as HousingType, -(select rowid from labkey.ehr_lookups.lookups l WHERE l.value = CASE - WHEN s2.Value LIKE '%Tier 1%' THEN replace(s2.value, ' Tier 1', '') - WHEN s2.Value LIKE '%Tier 2%' THEN replace(s2.value, ' Tier 2', '') - WHEN s2.Value LIKE '%Tier 3%' THEN replace(s2.value, ' Tier 3', '') - ELSE s2.value - END and l.set_name = 'LocationDefinition') as HousingDefinition, -coalesce(CASE - WHEN s2.Value LIKE '%Tier 1%' THEN 'Tier 1' - WHEN s2.Value LIKE '%Tier 2%' THEN 'Tier 2' - WHEN s2.Value LIKE '%Tier 3%' THEN 'Tier 3' - ELSE null -END, 'Tier 2') as tier - -from IRIS_Production.dbo.ref_feesProcedures r -left join IRIS_Production.dbo.Sys_Parameters s1 ON (s1.Field = 'LocationType' and s1.Flag = HousingType) -left join IRIS_Production.dbo.Sys_Parameters s2 ON (s2.Field = 'LocationDefinition' and s2.Flag = HousingDefinition) -where r.HousingDefinition is not null and r.DateDisabled is null; - - ---SLA Fee Definition -Truncate table labkey.onprc_billing.slaPerDiemFeeDefinition; -INSERT INTO labkey.onprc_billing.slaPerDiemFeeDefinition (chargeId, CageType, CageSize, Species, active, modified, created, modifiedby, createdby) -Select - (SELECT max(rowid) FROM onprc_billing.chargeableItems ci WHERE ci.active = 1 AND ci.name = ('Small Animal Fees - ' + s2.Value + ': ' + s3.Value + ', ' + s4.value)) as chargeId, - s2.Value as cageType, - s3.Value as cageSize, - s4.Value as species, - 1 as active, - getdate() as modified, - getdate() as created, - (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby, - (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby - -From IRIS_Production.dbo.Ref_FeesRodents rf -LEFT JOIN IRIS_Production.dbo.Sys_Parameters s2 on (rf.CageType = s2.Flag And s2.Field = 'SmallCageType') -LEFT JOIN IRIS_Production.dbo.Sys_Parameters s3 on (rf.CageSize = s3.Flag And s3.Field = 'SmallCageSize') -LEFT JOIN IRIS_Production.dbo.Sys_Parameters s4 on (rf.Species = s4.Flag And s4.Field = 'SmallAnimals') -where rf.DateDisabled is null - - ---procedureFeeDef -truncate table labkey.onprc_billing.procedureFeeDefinition; -insert into labkey.onprc_billing.procedureFeeDefinition (procedureId, chargeId, chargetype, active, created, modified, createdBy, modifiedBy) - select - (select rowid from labkey.ehr_lookups.procedures p WHERE p.name = t.ProcedureName and p.category = 'Surgery') as procedureId, - (select rowid from labkey.onprc_billing.chargeableItems p WHERE p.name = t.name) as chargeId, - max(chargeType) as chargeType, - MAX(t.active) as active, - getdate() as modified, - getdate() as created, - (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby, - (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby - FROM ( - - Select - s.ProcedureName + ' - No Staff' as name, - s.ProcedureName, - 'Research Staff' AS chargeType, - CASE WHEN fs.DateDisabled is null THEN 1 else 0 END as active - - From IRIS_Production.dbo.Ref_FeesSurgical fs - LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure s ON (fs.ProcedureID = s.ProcedureID) - WHERE s.procedureName IS NOT NULL - UNION ALL - - Select - s.ProcedureName + ' - Staff' as name, - s.ProcedureName, - 'Center Staff' AS chargeType, - CASE WHEN fs.DateDisabled is null THEN 1 else 0 END as active - - From IRIS_Production.dbo.Ref_FeesSurgical fs - LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure s ON (fs.ProcedureID = s.ProcedureID) - WHERE s.procedureName IS NOT NULL - ) t - - GROUP BY name, ProcedureName diff --git a/onprc_ehr/resources/etl/deprecated/cage.sql b/onprc_ehr/resources/etl/deprecated/cage.sql deleted file mode 100644 index 26eb43cc8..000000000 --- a/onprc_ehr/resources/etl/deprecated/cage.sql +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select - -t.location, -t.room, -t.cage, ---TODO: int -MAX(t.cagedivider) as divider, -MAX(t.cagetype) as cage_type, -MAX(CONVERT(VARCHAR(38), t.objectid)) as objectid - -FROM ( -Select - CASE - WHEN row.row IS NULL THEN rl.Location - ELSE rl.Location + '-' + rtrim(row.Row) + CONVERT(varchar, row.Cage) - END as location, - rl.Location as room, - rtrim(ltrim(rtrim(row.Row) + CONVERT(varchar, row.Cage))) as cage, - - CASE - WHEN row.CageTypeID = 19 THEN ct.CageDescription - ELSE CONVERT(VARCHAR, ct.CageDescription + ' - ') + CONVERT(VARCHAR, ct.CageSize) - END as cagetype, - - --s2.Value as CageDivider, - (select cd.rowid from labkey.ehr_lookups.divider_types cd where cd.divider = CASE WHEN s2.value = 'Pairing Divider (No Divider)' THEN 'No Divider' ELSE s2.value END) as cageDivider, - --row.CagePosition, - row.objectid - -From Ref_RowCage row - left join Sys_Parameters s1 on (s1.field = 'CageSize' and s1.Flag = row.Size) - left join Sys_Parameters s2 on (s2.field = 'CageDivider' and s2.Flag = row.CageDivider) - left join Ref_Location rl ON (rl.LocationId = row.LocationID) - left join Ref_CageTypes ct ON (ct.CageTypeID = row.CageTypeID) - -WHERE row.DateDisabled IS NULL -and row.status = 1 -AND row.ts > ? - -) t -where t.cage is not null -GROUP BY location, room, cage \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/ehr_lookups.sql b/onprc_ehr/resources/etl/deprecated/ehr_lookups.sql deleted file mode 100644 index 786dc3b6a..000000000 --- a/onprc_ehr/resources/etl/deprecated/ehr_lookups.sql +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---source --- TRUNCATE TABLE labkey.ehr_lookups.source; --- INSERT into labkey.ehr_lookups.source (code, meaning, SourceCity, SourceState, SourceCountry) --- select InstitutionCode, InstitutionName, InstitutionCity, InstitutionState, InstitutionCountry from IRIS_Production.dbo.Ref_ISISInstitution; - ---antibiotic subset --- DELETE FROM labkey.ehr_lookups.snomed_subsets WHERE subset = 'Antibiotics'; --- INSERT INTO labkey.ehr_lookups.snomed_subsets (container, subset) VALUES ((SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC'), 'Antibiotics'); --- --- DELETE FROM labkey.ehr_lookups.snomed_subset_codes WHERE primaryCategory = 'Antibiotics'; --- DELETE FROM labkey.ehr_lookups.snomed_subset_codes WHERE primarycategory = 'Antibiotic'; --- INSERT INTO labkey.ehr_lookups.snomed_subset_codes (primaryCategory, code, container, modified, created, modifiedby, createdby) --- Select --- 'Antibiotics' as primaryCategory, --- AntibioticCode as code, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as modified, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby --- From IRIS_Production.dbo.Ref_Antibiotics WHERE DateDisabled IS NULL; - ---buildings --- TRUNCATE TABLE labkey.ehr_lookups.buildings; --- INSERT INTO labkey.ehr_lookups.buildings (name, description) --- SELECT buildingname, description FROM IRIS_Production.dbo.ref_building WHERE datedisabled IS NULL; - --- --species --- TRUNCATE TABLE labkey.ehr_lookups.species; --- INSERT INTO labkey.ehr_lookups.species (common, scientific_name) --- Select max(commonname), max(latinname) From IRIS_Production.dbo.ref_species WHERE Active = 1 GROUP BY CommonName; --- --- UPDATE labkey.ehr_lookups.species SET blood_draw_interval = 21; --- --- UPDATE labkey.ehr_lookups.species SET blood_per_kg = 56; --- UPDATE labkey.ehr_lookups.species SET blood_per_kg = 65 WHERE common = 'CYNOMOLGUS MACAQUE'; --- UPDATE labkey.ehr_lookups.species SET max_draw_pct = 0.125; - --- UPDATE labkey.ehr_lookups.species --- SET cites_code = (SELECT min(SpeciesCode) FROM IRIS_Production.dbo.ref_species WHERE Active = 1 AND species.common = ref_species.CommonName) - ---snomed ---TRUNCATE TABLE labkey.ehr_lookups.snomed; -INSERT INTO labkey.ehr_lookups.snomed (code, meaning, modified, created, modifiedby, createdby, container) -Select -ltrim(rtrim(SnomedCode)) as code, -max(description) as meaning, -getdate() as modified, -getdate() as created, -(SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby, -(SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, -(SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') -From IRIS_Production.dbo.Ref_SnoMed -WHERE ltrim(rtrim(SnomedCode)) not in (select code from labkey.ehr_lookups.snomed WHERE container = (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC')) AND snomedcode != '---' -GROUP BY SnomedCode; - - ---gender --- TRUNCATE TABLE labkey.ehr_lookups.gender_codes; --- INSERT INTO labkey.ehr_lookups.gender_codes (code, meaning, origgender) VALUES ('f', 'Female', 'f'); --- INSERT INTO labkey.ehr_lookups.gender_codes (code, meaning, origgender) VALUES ('m', 'Male', 'm'); --- INSERT INTO labkey.ehr_lookups.gender_codes (code, meaning, origgender) VALUES ('h', 'Hermaphrodite', null); --- INSERT INTO labkey.ehr_lookups.gender_codes (code, meaning, origgender) VALUES ('u', 'Unknown', null); - ---toys subset --- DELETE FROM labkey.ehr_lookups.snomed_subsets WHERE subset = 'Toys'; --- INSERT INTO labkey.ehr_lookups.snomed_subsets (subset) VALUES ('Toys'); --- --- DELETE FROM labkey.ehr_lookups.snomed_subset_codes WHERE primaryCategory = 'Toys'; --- INSERT INTO labkey.ehr_lookups.snomed_subset_codes (primaryCategory, code, container, modified, created, modifiedby, createdby) --- Select --- 'Toys' as primaryCategory, --- ToyCode as code, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as modified, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby --- From IRIS_Production.dbo.Ref_Toys WHERE ToyType = 1; --active only - - ---geographic origins --- TRUNCATE TABLE labkey.ehr_lookups.geographic_origins; --- INSERT INTO labkey.ehr_lookups.geographic_origins (meaning) --- SELECT upper(ltrim(rtrim(GeographicName))) as meaning From IRIS_Production.dbo.Ref_ISISGeographic; - - - ---treatment frequency --- INSERT INTO labkey.ehr_lookups.treatment_frequency --- (meaning) --- SELECT --- value --- FROM IRIS_Production.dbo.Sys_Parameters s3 --- LEFT JOIN labkey.ehr_lookups.treatment_frequency f ON (s3.Value = f.meaning) --- WHERE s3.Field = 'MedicationFrequency' AND f.meaning IS NULL; - - - --- TRUNCATE TABLE labkey.ehr_lookups.rooms; --- INSERT INTO labkey.ehr_lookups.rooms (room, area, building, maxCages, housingtype, housingCondition, dateDisabled, sort_order) --- SELECT --- t.Location as room, --- max(t.area) as area, --- max(t.buildingName) as buildingName, --- max(t.Size) as size, --- max(t.LocationType) as locationtype, --- max(t.LocationDefinition) as housingcategory, --- min(t.datedisabled) as datedisabled, --- min(sort_order) as sort_order --- --- FROM ( --- Select --- Location, --- BuildingName as area, --- BuildingName, --- Size, --- Status as active, --- --s1.SearchKey as LocationTypeInt, --- (select l.rowid FROM labkey.ehr_lookups.lookups l where l.set_name = s1.Field and l.value = s1.Value) as locationType, --- --s1.Value as LocationType, --- --s2.searchkey as LocationDefinitionInt --- --- (select l.rowid FROM labkey.ehr_lookups.lookups l where l.set_name = s2.Field and l.value = s2.Value) as locationDefinition, --- loc.DateDisabled, --- loc.DisplayOrder as sort_order --- --s2.Value as LocationDefinition, --- --loc.DateCreated, --- --loc.DateDisabled, --- --loc.DisplayOrder, --- --LockDownDate --- --- From IRIS_Production.dbo.Ref_Location loc, --- IRIS_Production.dbo.Sys_Parameters s1, IRIS_Production.dbo.Sys_Parameters s2, IRIS_Production.dbo.Ref_Building rb --- Where s1.Field = 'LocationType' --- and s1.Flag = loc.LocationType --- and s2.Field = 'LocationDefinition' --- and s2.Flag = loc.LocationDefinition --- and rb.BuildingId = loc.BuildingID --- --and loc.DateDisabled is null --- --- UNION ALL --- --- Select --- Location, --- BuildingName as area, --- BuildingName, --Ref_Building --- Size, --- Status, --- (select l.rowid FROM labkey.ehr_lookups.lookups l where l.set_name = s1.Field and l.value = s1.Value) as locationType, --- --s1.Value as LocationType, --- --s2.searchkey as LocationDefinitionInt --- --- (select l.rowid FROM labkey.ehr_lookups.lookups l where l.set_name = s2.Field and l.value = s2.Value) as locationDefinition, --- --s2.Value as LocationDefinition, --- rls.datedisabled, --- rls.DisplayOrder as sort_order --- --- From IRIS_Production.dbo.Ref_LocationSPF rls, --- IRIS_Production.dbo.Sys_Parameters s1, IRIS_Production.dbo.Sys_Parameters s2, IRIS_Production.dbo.Ref_Building rb --- Where s1.Field = 'LocationType' --- and s1.Flag = rls.LocationType --- and s2.Field = 'LocationDefinition' --- and s2.Flag = rls.LocationDefinition --- and rb.BuildingId = rls.BuildingID --- --and rls.DateDisabled is null --- --- ) t --- GROUP BY t.location; - ---cage types --- TRUNCATE TABLE labkey.ehr_lookups.cage_type; --- INSERT INTO labkey.ehr_lookups.cage_type (cagetype,sqft,cageslots) --- --- Select --- CASE --- WHEN ct.CageTypeID = 19 THEN ct.CageDescription --- ELSE CONVERT(VARCHAR, ct.CageDescription + ' - ') + CONVERT(VARCHAR, ct.CageSize) --- END as cagetype, --- --ugly --- convert(float, rtrim(replace(replace(replace(cagesize, 'T', ''), 'O', ''), 'U', ''))) as cagesize, --- CageSlots --- From IRIS_Production.dbo.Ref_CageTypes ct --- WHERE DateDisabled is null; - ---areas --- DELETE FROM labkey.ehr_lookups.areas; --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('ASA'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('ASB'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('NSI'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Research'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Harem'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Colony'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Colony Annex - South'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Colony Annex - North'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Shelters'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Corrals'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Kroc'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Catch 2'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Catch 5'); --- INSERT INTO labkey.ehr_lookups.areas (area) VALUES ('Catch 8'); - --- TRUNCATE TABLE labkey.ehr_lookups.areas; --- INSERT INTO labkey.ehr_lookups.areas (area, description) --- SELECT buildingname, description FROM IRIS_Production.dbo.ref_building WHERE datedisabled IS NULL; - - --- INSERT INTO labkey.ehr_lookups.divider_types (divider) --- SELECT --- s2.value --- from IRIS_Production.dbo.sys_parameters s2 --- left join labkey.ehr_lookups.divider_types d ON (s2.value = d.divider) --- where s2.field = 'CageDivider' and s2.DateDisabled IS NULL and d.divider is null; - - --- DELETE FROM labkey.ehr_lookups.lookups where set_name = 'housing_reason' --- and value not in (select value from iris_production.dbo.Sys_Parameters s where s.Field = 'TRANSFERREASON'); - --- INSERT INTO labkey.ehr_lookups.lookups (set_name, value, sort_order) --- select --- 'housing_reason' as setname, --- s.Value as value, --- s.DisplayOrder as sort_order --- --- from iris_production.dbo.Sys_Parameters s --- where s.Field = 'TRANSFERREASON' --- and s.value not in (select value from labkey.ehr_lookups.lookups WHERE set_name = 'housing_reason'); - --- DELETE FROM labkey.ehr_lookups.lookups where set_name = 'birth_type' --- and value not in (select value from iris_production.dbo.Sys_Parameters s where s.Field = 'BirthType'); - --- INSERT INTO labkey.ehr_lookups.lookups (set_name, value, sort_order) --- select --- 'birth_type' as setname, --- s.Value as value, --- s.DisplayOrder as sort_order --- --- from iris_production.dbo.Sys_Parameters s --- where s.Field = 'BirthType' --- and s.value not in (select value from labkey.ehr_lookups.lookups WHERE set_name = 'birth_type'); - --- DELETE FROM labkey.ehr_lookups.lookups where set_name = 'birth_condition' --- and value not in (select value from iris_production.dbo.Sys_Parameters s where s.Field = 'BirthCondition'); --- --- INSERT INTO labkey.ehr_lookups.lookups (set_name, value, sort_order) --- select --- 'birth_condition' as setname, --- s.Value as value, --- s.DisplayOrder as sort_order --- --- from iris_production.dbo.Sys_Parameters s --- where s.Field = 'BirthCondition' --- and s.value not in (select value from labkey.ehr_lookups.lookups WHERE set_name = 'birth_condition'); - - --- DELETE FROM labkey.ehr_lookups.lookups where set_name = 'death_cause' --- and value not in (select value from iris_production.dbo.Sys_Parameters s where s.Field = 'Deathcause'); --- --- INSERT INTO labkey.ehr_lookups.lookups (set_name, value, sort_order) --- select --- 'death_cause' as setname, --- s.Value as value, --- s.DisplayOrder as sort_order --- --- from iris_production.dbo.Sys_Parameters s --- where s.Field = 'Deathcause' --- and s.value not in (select value from labkey.ehr_lookups.lookups WHERE set_name = 'death_cause'); - - --- DELETE FROM labkey.ehr_lookups.lookups where set_name = 'problem_list_category' --- and value not in (select value from iris_production.dbo.Sys_Parameters s where s.Field = 'MasterProblemList'); --- --- INSERT INTO labkey.ehr_lookups.lookups (set_name, value, sort_order) --- select --- 'problem_list_category' as setname, --- s.Value as value, --- s.DisplayOrder as sort_order --- --- from iris_production.dbo.Sys_Parameters s --- where s.Field = 'MasterProblemList' --- and s.value not in (select value from labkey.ehr_lookups.lookups WHERE set_name = 'problem_list_category'); - --- TRUNCATE TABLE labkey.ehr_lookups.animal_condition; --- INSERT INTO labkey.ehr_lookups.animal_condition (code, meaning, created, createdby, modified, modifiedby) --- select --- PoolCode as code, --- Description as meaning, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, --- getdate() as modified, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby --- from iris_production.dbo.ref_pool where (ShortDescription = 'Condition' or poolcode = 207) and DateDisabled is null and PoolCode != 203; - ---append custom flags --- insert into ehr_lookups.flag_values (category, value,code,datedisabled,objectid,container,created,createdby,modified,modifiedby) --- select --- 'Genetics' as category, --- 'DNA Bank Blood Draw Collected' as value, --- null as code, --- null as datedisabled, --- NEWID() as objectid, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, --- getdate() as modified, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby --- --- WHERE NOT EXISTS (SELECT rowid FROM labkey.ehr_lookups.flag_values WHERE 'Genetics' = category AND 'DNA Bank Blood Draw Collected' = value); --- --- insert into ehr_lookups.flag_values (category, value,code,datedisabled,objectid,container,created,createdby,modified,modifiedby) --- select --- 'Genetics' as category, --- 'DNA Bank Blood Draw Needed' as value, --- null as code, --- null as datedisabled, --- NEWID() as objectid, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, --- getdate() as modified, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby --- --- WHERE NOT EXISTS (SELECT rowid FROM labkey.ehr_lookups.flag_values WHERE 'Genetics' = category AND 'DNA Bank Blood Draw Needed' = value); --- --- insert into ehr_lookups.flag_values (category, value,code,datedisabled,objectid,container,created,createdby,modified,modifiedby) --- select --- 'Genetics' as category, --- 'MHC Blood Draw Collected' as value, --- null as code, --- null as datedisabled, --- NEWID() as objectid, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, --- getdate() as modified, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby --- --- WHERE NOT EXISTS (SELECT rowid FROM labkey.ehr_lookups.flag_values WHERE 'Genetics' = category AND 'MHC Blood Draw Collected' = value); --- --- insert into ehr_lookups.flag_values (category, value,code,datedisabled,objectid,container,created,createdby,modified,modifiedby) --- select --- 'Genetics' as category, --- 'MHC Blood Draw Needed' as value, --- null as code, --- null as datedisabled, --- NEWID() as objectid, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, --- getdate() as modified, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby --- --- WHERE NOT EXISTS (SELECT rowid FROM labkey.ehr_lookups.flag_values WHERE 'Genetics' = category AND 'MHC Blood Draw Needed' = value); --- --- insert into ehr_lookups.flag_values (category, value,code,datedisabled,objectid,container,created,createdby,modified,modifiedby) --- select --- 'Genetics' as category, --- 'Parentage Blood Draw Collected' as value, --- null as code, --- null as datedisabled, --- NEWID() as objectid, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, --- getdate() as modified, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby --- --- WHERE NOT EXISTS (SELECT rowid FROM labkey.ehr_lookups.flag_values WHERE 'Genetics' = category AND 'Parentage Blood Draw Collected' = value); --- --- insert into ehr_lookups.flag_values (category, value,code,datedisabled,objectid,container,created,createdby,modified,modifiedby) --- select --- 'Genetics' as category, --- 'Parentage Blood Draw Needed' as value, --- null as code, --- null as datedisabled, --- NEWID() as objectid, --- (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, --- getdate() as created, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, --- getdate() as modified, --- (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby --- --- WHERE NOT EXISTS (SELECT rowid FROM labkey.ehr_lookups.flag_values WHERE 'Genetics' = category AND 'Parentage Blood Draw Needed' = value); \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/flag_values.sql b/onprc_ehr/resources/etl/deprecated/flag_values.sql deleted file mode 100644 index d3fc1fd78..000000000 --- a/onprc_ehr/resources/etl/deprecated/flag_values.sql +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT -rp.objectid, -rp.PoolCode as code, -rtrim(ltrim(rp.ShortDescription)) as category, -rtrim(ltrim(rp.Description)) as value, -rp.DateDisabled - -FROM Ref_Pool rp -WHERE rp.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/iStat.sql b/onprc_ehr/resources/etl/deprecated/iStat.sql deleted file mode 100644 index f07d1d738..000000000 --- a/onprc_ehr/resources/etl/deprecated/iStat.sql +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2013-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---Please note: All lab values = -1 is should be substitued with a Null value - -SELECT - --t.ClinicalKey , - cast(t.Id as nvarchar(4000)) as Id, - t.DATE , - --t.Specimen , -- Specimen database table - --sp.Name, - --sp.SNOMEDCODE as snomed, - t.MethodInt , - s2.Value as Method, - case - when t.Result = -1 then null - else t.Result - end as Result, - t.resultString as stringResults, - - t.TestId, - - t.rowversion, - (cast(t.objectid as varchar(38)) + '_' + t.TestId) as objectid, - null as parentId, - t.objectid as runId - -FROM ( - - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - Sodium as ResultString, - 'Na' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - Potassium as ResultString, - 'K' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - Chlorine as ResultString , - 'Cl' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - TCO2 as ResultString, - 'TCO2' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - BUN as ResultString , - 'BUN' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - Glu as ResultString, - 'Glu' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - Hct as ResultString , - 'HCT' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - PH as ResultString, - 'pH' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - PCO2 as ResultString, - 'pCO2' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - HCO3 as ResultString, - 'HCO3' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - BE as ResultString, - 'BE' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - AnGap as ResultString , - 'AnGap' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - Hgb as ResultString, - 'Hb' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - PO2 as ResultString, - 'pO2' as TestId, - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - SO2 as ResultString, - 'SO2' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -UNION ALL - -SELECT - null as IDKey, - AnimalID as Id , - DATE , - Specimen as Specimen , ------ Specimen database table - Method as MethodInt , - null as result, - LAC as ResultString, - 'Lact' as TestId, - - cln.ts as rowversion, - cln.objectid - -FROM Cln_IStat cln - -) t - -left join Sys_Parameters s2 on (s2.Flag = t.MethodInt And s2.Field = 'AnalysisMethodBiochem') - -WHERE t.ResultString is not null and t.ResultString != '' - AND t.rowversion > ? diff --git a/onprc_ehr/resources/etl/deprecated/invoiceRuns.sql b/onprc_ehr/resources/etl/deprecated/invoiceRuns.sql deleted file mode 100644 index afc2d4b9d..000000000 --- a/onprc_ehr/resources/etl/deprecated/invoiceRuns.sql +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select - 'IRIS Legacy data' as comment, - 'Finalized' as status, - max(ri2.RunDate) as runDate, - ri.StartDate as billingPeriodStart, - ri.EndDate as billingPeriodEnd, - max(cast(ri.objectid as varchar(38))) as objectid, - min(ri.StartInvoice) as invoiceNumber -from Ref_Invoice ri -left join ref_invoice ri2 ON (ri.startdate = ri2.startdate AND ri.enddate = ri2.enddate) -where (ri.ts > ? or ri2.ts > ?) -group by ri.startdate, ri.enddate diff --git a/onprc_ehr/resources/etl/deprecated/invoicedItems.sql b/onprc_ehr/resources/etl/deprecated/invoicedItems.sql deleted file mode 100644 index e803fd187..000000000 --- a/onprc_ehr/resources/etl/deprecated/invoicedItems.sql +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ --- --- PDAR debit entries - missing FAID --- -SELECT - t.*, - (select max(bci.rowId) from labkey.onprc_billing.chargeableItems bci where t.item = bci.name) as chargeId -FROM ( -SELECT - ri.objectid as invoiceId, - CASE - WHEN (ci.ServiceCenter = 'PDAR' OR ci.ServiceCenter = 'SLAU') THEN rfp.ProcedureName - WHEN ci.ServiceCenter = 'PSURG' THEN sp.ProcedureName - ELSE 'ERROR' - END as item, - CASE - WHEN sys.Value IS NOT NULL THEN sys.value - WHEN ci.ServiceCenter = 'PSURG' THEN 'Surgery' - ELSE null - END as category, - - ci.objectid as objectid, - inves.investigatorId as investigatorId, - ci.ServiceCenter as ServiceCenter, - ci.TransactionType as transactionType, - ci.TransactionNumber as transactionNumber, - ci.TransactionDate as date, - CASE - WHEN (LEN(ci.TransactionDescription) = 5) and ISNUMERIC(ci.TransactionDescription) = 1 THEN ci.TransactionDescription - WHEN (ci.TransactionDescription IS NOT NULL and ISNUMERIC(substring(ci.TransactionDescription, 1, 5)) = 1) THEN substring(ci.TransactionDescription, 1, 5) - ELSE null - END as id, - CASE - WHEN (LEN(ci.TransactionDescription) = 5) and ISNUMERIC(ci.TransactionDescription) = 1 THEN null - WHEN (ci.TransactionDescription IS NOT NULL and ISNUMERIC(substring(ci.TransactionDescription, 1, 5)) = 1) THEN ltrim(substring(ci.TransactionDescription, 6, LEN(ci.TransactionDescription))) - ELSE ci.TransactionDescription - END as comment, - - ci.LastName as lastName, - ci.FirstName as firstName, - CASE - WHEN (ci.faid IS NULL or ci.faid = '') THEN null - ELSE (select fa.rowid from labkey.onprc_billing.fiscalAuthorities fa where fa.faid like '%' + ci.faid + '%') - END as faid, - ci.Department as department, - ci.MailCode as mailCode, - ci.ContactPhone as contactPhone, - ci.ItemCode as ItemCode, - ci.Quantity as quantity, - ci.Price as unitCost, - ci.OHSUAlias as debitedAccount, - ci2.OHSUAlias as creditedaccount, - ci.TotalAmount as totalCost, - ci.InvoiceDate as invoiceDate, - ci.InvoiceNumber as invoiceNumber, - ci.ProjectID as project, - ci.CageID as cageId, - null as credit -from Af_Chargesibs ci - ---find corresponding debit - left join Af_Chargesibs ci2 ON (ci2.ChargesIDKey = ci.ChargesIDKey AND ci.TransactionNumber = ci2.TransactionNumber AND ci.IDKey != ci2.IDKey) - ---used to find the chargeid - left join Ref_FeesProcedures rfp on (ci.ItemCode = (Convert(varchar(10),rfp.ProcedureID)) AND (ci.ServiceCenter = 'PDAR' OR ci.servicecenter = 'SLAU')) - - left join Ref_SurgProcedure sp on (ci.ItemCode = (Convert(varchar(10), sp.ProcedureID)) AND ci.ServiceCenter = 'PSURG') - left join Sys_Parameters sys on (sys.Field = 'ChargeType' and sys.Flag = rfp.ChargeType) - - LEFT JOIN ( - select max(i.rowid) as investigatorId, lastName, firstName - from labkey.onprc_ehr.investigators i - group by i.LastName, i.firstname - having count(*) <= 1 - ) inves ON (inves.firstname = ci.firstname and inves.lastname = ci.lastname) - - left join ( - SELECT max(ri.ts) as maxTs, max(cast(ri2.objectid as varchar(38))) as objectid, max(ri.StartInvoice) as StartInvoice, max(ri.EndInvoice) as EndInvoice - from ref_invoice ri - left join ref_invoice ri2 ON (ri.startdate = ri2.startdate AND ri.enddate = ri2.enddate) - GROUP BY ri.objectid - ) ri ON (ci.InvoiceNumber >= ri.StartInvoice AND ci.InvoiceNumber <= ri.EndInvoice) - -WHERE ci.ItemCode not like '%C' -and (ci.ts > ? or ci2.ts > ? or rfp.ts > ? or sp.ts > ?) --Note: removing or ri.maxTs > ?, as this is very slow and no strictly necessary at this point since we have migrated most data - -) t - diff --git a/onprc_ehr/resources/etl/deprecated/miscCharges.sql b/onprc_ehr/resources/etl/deprecated/miscCharges.sql deleted file mode 100644 index 94679570e..000000000 --- a/onprc_ehr/resources/etl/deprecated/miscCharges.sql +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* -First get new charges -*/ - -select - t.*, - CASE - WHEN t.chargeType = 'Adjustment' THEN t.rawUnitCost - WHEN t.rawUnitCost = cr.unitcost AND cre.rowId IS null THEN NULL - WHEN t.rawUnitCost = cre.unitcost THEN NULL - ELSE t.rawUnitCost - END as unitcost - -FROM ( - -select - afc.AnimalID as id, - afc.ChargeDate as date, - afc.ProjectID as project, - afc.OHSUAccountNo as account, - --afc.ChargeType as chargeType, - (select s.value from sys_parameters s where afc.ChargeType = s.Flag and s.Field = 'ChargeType') as category, - afc.ProcedureID as procedureID, - rfp.ProcedureName as item, - (select bci.rowId from Labkey.onprc_billing.chargeableItems bci where rfp.ProcedureName = bci.name) as chargeID, - afc.ProcedureCount as quantity, - afc.Amount as rawunitCost, - --(afc.Amount * afc.ProcedureCount) as totalCost, - afc.Remarks as comment, - CASE WHEN (afc.invoiceDate IS NOT NULL AND afc.invoiceDate < afc.billingDate) THEN afc.invoiceDate ELSE afc.BillingDate END as billingDate, - afc.InvoiceNo as invoiceNumber, - ri.objectid as invoiceId, - null as invoicedItemId, - afc.objectid, - null as sourceInvoicedItem, - null as chargeType -from Af_Charges afc -left join Ref_ProjectsIACUC rpi on (afc.ProjectID = rpi.ProjectID) -left join Ref_FeesProcedures rfp on (afc.ProcedureID = rfp.ProcedureID) -left join ( - SELECT max(ri.ts) as maxTs, max(cast(ri2.objectid as varchar(38))) as objectid, max(ri.StartInvoice) as StartInvoice, max(ri.EndInvoice) as EndInvoice - from ref_invoice ri - left join ref_invoice ri2 ON (ri.startdate = ri2.startdate AND ri.enddate = ri2.enddate) - GROUP BY ri.objectid -) ri ON (afc.InvoiceNo >= ri.StartInvoice AND afc.InvoiceNo <= ri.EndInvoice) - -where afc.ChargeType not in (1, 4, 8, 10) and ChargeDate >= '1/1/2008' and (AccountNo is null or AccountNo = '') ---blood now automatically calculated. dont migrate draws after 1/1 -and (rfp.ProcedureName != 'Blood Draw' OR (rfp.ProcedureName = 'Blood Draw' AND ChargeDate < '1/1/2014')) -and (afc.ts > ? or rpi.ts > ? or rfp.ts > ? or ri.maxTs > ?) - -UNION ALL - -/* -Next get non-surgery adjustments -*/ - -select - afc2.AnimalID as id, - afc2.ChargeDate as date, - afc2.ProjectID as project, - afc2.OHSUAccountNo as account, - --afc2.ChargeType as chargeType, - (select s.value from sys_parameters s where afc2.ChargeType = s.Flag and s.Field = 'ChargeType') as category, - afc2.ProcedureID as procedureID, - rfp.ProcedureName as item, - (select bci.rowId from Labkey.onprc_billing.chargeableItems bci where rfp.ProcedureName = bci.name) as chargeID, - afc2.ProcedureCount as quantity, - afc2.Amount as rawunitCost, - --(afc2.Amount * afc2.ProcedureCount) as totalCost, - afc2.Remarks as comment, - CASE WHEN (afc2.invoiceDate IS NOT NULL AND afc2.invoiceDate < afc2.billingDate) THEN afc2.invoiceDate ELSE afc2.BillingDate END as billingDate, - afc2.InvoiceNo as invoiceNumber, - ri.objectid as invoiceId, - (SELECT MAX(cast(ibs.objectid as varchar(38))) FROM AF_ChargesIBS ibs WHERE afc2.AccountNo = cast(ibs.ChargesIDKey as varchar(100))) as invoicedItemId, - afc2.objectid, - null as sourceInvoicedItem, - 'Adjustment' as chargeType -from af_charges afc -left join AF_Charges afc2 on (cast(afc.IDKEY as varchar(100))= afc2.AccountNo) -left join Ref_ProjectsIACUC rpi on (afc2.ProjectID = rpi.ProjectID) -left join Ref_FeesProcedures rfp on (afc2.ProcedureID = rfp.ProcedureID) -left join ( - SELECT max(ri.ts) as maxTs, max(cast(ri2.objectid as varchar(38))) as objectid, max(ri.StartInvoice) as StartInvoice, max(ri.EndInvoice) as EndInvoice - from ref_invoice ri - left join ref_invoice ri2 ON (ri.startdate = ri2.startdate AND ri.enddate = ri2.enddate) - GROUP BY ri.objectid -) ri ON (afc.InvoiceNo >= ri.StartInvoice AND afc.InvoiceNo <= ri.EndInvoice) - -where afc.ChargeType not in (4, 10) and afc2.AccountNo is not null and afc2.AccountNo <> '' -and afc.ChargeDate >= '1/1/2008' and afc2.ChargeDate >= '7/1/2012' -and (afc.ts > ? or afc2.ts > ? or rpi.ts > ? or rfp.ts > ? or ri.maxTs > ?) - -UNION ALL - -/* -Next get surgery adjustments -*/ - -select - afc2.AnimalID as id, - afc2.ChargeDate as date, - afc2.ProjectID as project, - afc2.OHSUAccountNo as account, - --afc2.ChargeType as chargeType, - (select s.value from sys_parameters s where afc2.ChargeType = s.Flag and s.Field = 'ChargeType') as category, - afc2.ProcedureID as procedureID, - rsp.ProcedureName as description, - (select bci.rowId from Labkey.onprc_billing.chargeableItems bci where rsp.ProcedureName = bci.name) as chargeID, - afc2.ProcedureCount as quantity, - afc2.Amount as rawunitCost, - --(afc2.Amount * afc2.ProcedureCount) as totalCost, - afc2.Remarks as comment, - CASE WHEN (afc2.invoiceDate IS NOT NULL AND afc2.invoiceDate < afc2.billingDate) THEN afc2.invoiceDate ELSE afc2.BillingDate END as billingDate, - afc2.InvoiceNo as invoiceNumber, - ri.objectid as invoiceId, - (SELECT MAX(cast(ibs.objectid as varchar(38))) FROM AF_ChargesIBS ibs WHERE afc2.AccountNo = cast(ibs.ChargesIDKey as varchar(100))) as invoicedItemId, - afc2.objectid, - null as sourceInvoicedItem, - 'Adjustment' as chargeType -from af_charges afc -left join AF_Charges afc2 on (cast(afc.IDKEY as varchar(100)) = afc2.AccountNo) -left join Ref_ProjectsIACUC rpi on (afc2.ProjectID = rpi.ProjectID) -left join Ref_SurgProcedure rsp on (afc2.ProcedureID = rsp.ProcedureID) -left join ( - SELECT max(ri.ts) as maxTs, max(cast(ri2.objectid as varchar(38))) as objectid, max(ri.StartInvoice) as StartInvoice, max(ri.EndInvoice) as EndInvoice - from ref_invoice ri - left join ref_invoice ri2 ON (ri.startdate = ri2.startdate AND ri.enddate = ri2.enddate) - GROUP BY ri.objectid -) ri ON (afc.InvoiceNo >= ri.StartInvoice AND afc.InvoiceNo <= ri.EndInvoice) - -where afc.ChargeType in (4, 10) and afc2.AccountNo is not null and afc2.AccountNo <> '' -and afc.ChargeDate >= '1/1/2008' -and afc2.ChargeDate >= '7/1/2012' -and (afc.ts > ? or afc2.ts > ? or rpi.ts > ? or rsp.ts > ? or ri.maxTs > ?) - -UNION ALL - -/* -Next get NHP per diem adjustments -*/ - -select - afc.AnimalID as id, - afc.ChargeDate as date, - afc.ProjectID as project, - afc.OHSUAccountNo as account, - --afc.ChargeType as chargeType, - (select s.value from sys_parameters s - where afc.ChargeType = s.Flag and s.Field = 'ChargeType') as category, - afc.ProcedureID as procedureID, - rfp.ProcedureName as description, - (select bci.rowId from Labkey.onprc_billing.chargeableItems bci where rfp.ProcedureName = bci.name) as chargeID, - afc.ProcedureCount as quantity, - afc.Amount as rawunitCost, - --(afc.Amount * afc.ProcedureCount) as totalCost, - null as comment, - CASE WHEN (afc.invoiceDate IS NOT NULL AND afc.invoiceDate < afc.billingDate) THEN afc.invoiceDate ELSE afc.BillingDate END as billingDate, - afc.InvoiceNo as invoiceNumber, - ri.objectid as invoiceId, - null as invoicedItemId, - afc.objectid, - null as sourceInvoicedItem, - 'Adjustment' as chargeType -from Af_ChargesPerDiem afc -left join Ref_ProjectsIACUC rpi on (afc.ProjectID = rpi.ProjectID) -left join Ref_FeesProcedures rfp on (afc.ProcedureID = rfp.ProcedureID) -left join ( - SELECT max(ri.ts) as maxTs, max(cast(ri2.objectid as varchar(38))) as objectid, max(ri.StartInvoice) as StartInvoice, max(ri.EndInvoice) as EndInvoice - from ref_invoice ri - left join ref_invoice ri2 ON (ri.startdate = ri2.startdate AND ri.enddate = ri2.enddate) - GROUP BY ri.objectid -) ri ON (afc.InvoiceNo >= ri.StartInvoice AND afc.InvoiceNo <= ri.EndInvoice) -where afc.AccountNo is not null and afc.AccountNo <> '' and ChargeDate >= '1/1/2008' -and (afc.ts > ? or rpi.ts > ? or rfp.ts > ? or ri.maxTs > ?) - -UNION ALL - -Select - afc.AnimalID as id, - afc.chargeDate as date, - afc.ProjectID as project, - afc.OHSUAccountNo as account, - --afc.ChargeType as chargeType, - (select s.value from sys_parameters s where afc.ChargeType = s.Flag and s.Field = 'ChargeType') as category, - afc.ProcedureID as procedureID, - rfp.ProcedureName as item, - (select bci.rowId from Labkey.onprc_billing.chargeableItems bci where rfp.ProcedureName = bci.name) as chargeID, - afc.ProcedureCount as quantity, - afc.Amount as rawunitCost, - --(afc.Amount * afc.ProcedureCount) as totalCost, - afc.Remarks as comment, - CASE WHEN (afc.invoiceDate IS NOT NULL AND afc.invoiceDate < afc.billingDate) THEN afc.invoiceDate ELSE afc.BillingDate END as billingDate, - afc.InvoiceNo as invoiceNumber, - ri.objectid as invoiceId, - (SELECT MAX(cast(ibs.objectid as varchar(38))) FROM AF_ChargesIBS ibs WHERE afc.AccountNo = cast(ibs.ChargesIDKey as varchar(100))) as invoicedItemId, - afc.objectid, - null as sourceInvoicedItem, - null as chargeType -from af_charges afc ---left join AF_Charges afc2 on (afc.IDKEY = afc2.AccountNo) -left join Ref_ProjectsIACUC rpi on (afc.ProjectID = rpi.ProjectID) -left join Ref_FeesProcedures rfp on (afc.ProcedureID = rfp.ProcedureID) -left join ( -SELECT max(ri.ts) as maxTs, max(cast(ri2.objectid as varchar(38))) as objectid, max(ri.StartInvoice) as StartInvoice, max(ri.EndInvoice) as EndInvoice - from ref_invoice ri - left join ref_invoice ri2 ON (ri.startdate = ri2.startdate AND ri.enddate = ri2.enddate) - GROUP BY ri.objectid -) ri ON (afc.InvoiceNo >= ri.StartInvoice AND afc.InvoiceNo <= ri.EndInvoice) - -where afc.ChargeType in (1,8) and - (afc.Chargedate < afc.BillingDate AND (afc.AccountNo is null or afc.AccountNo = '') AND ( - --the intent of this is to capture any charge entered 1 billing period after the actual record - DATEDIFF(day, afc.Chargedate, afc.BillingDate) > 15 OR - CASE WHEN DAY(afc.Chargedate) <= 15 THEN 1 ELSE 2 END != CASE WHEN DAY(afc.BillingDate) <= 15 THEN 1 ELSE 2 END - )) -and (afc.ts > ? or rpi.ts > ? or rfp.ts > ? or ri.maxTs > ?) - -) t - -left join labkey.onprc_billing.chargeRates cr ON (cr.chargeId = t.chargeId and cr.startDate <= t.date AND coalesce(cr.enddate, CURRENT_TIMESTAMP) >= t.date) -left join labkey.onprc_billing.chargeRateExemptions cre ON (cre.chargeId = t.chargeId and cre.startDate <= t.date AND coalesce(cre.enddate, CURRENT_TIMESTAMP) >= t.date and cre.project = t.project) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/onprc_ehr.sql b/onprc_ehr/resources/etl/deprecated/onprc_ehr.sql deleted file mode 100644 index bab7655d3..000000000 --- a/onprc_ehr/resources/etl/deprecated/onprc_ehr.sql +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -INSERT INTO labkey.onprc_ehr.investigators (firstname,lastName,position,address,city,state,country,zip,phoneNumber, investigatorType,emailAddress,dateCreated,dateDisabled,division,objectid) -Select - rtrim(ltrim(firstname)) as FirstName, - rtrim(ltrim(LastName)) as LastName, - Position, - Address, - City, - State, - Country, - ZIP, - PhoneNumber, - --InvestigatorType as InvestigatorTypeInt, - s1.Value as InvestigatorType, - EmailAddress, - rinv.DateCreated, - rinv.DateDisabled, - --Division as DivisionInt, - s2.Value as Division, - rinv.objectid -From IRIS_Production.dbo.Ref_Investigator rinv - left join IRIS_Production.dbo.Sys_Parameters s1 on (s1.Field = 'InvestigatorType'and s1.Flag = rinv.InvestigatorType) - left join IRIS_Production.dbo.Sys_Parameters s2 on (s2.Field = 'Division' and s2.Flag = rinv.Division) -WHERE rinv.objectid NOT IN (select objectid FROM labkey.onprc_ehr.investigators); - -update onprc_ehr.investigators set firstName = null where firstName = ''; \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/orderssynced.sql b/onprc_ehr/resources/etl/deprecated/orderssynced.sql deleted file mode 100644 index 5b9da967d..000000000 --- a/onprc_ehr/resources/etl/deprecated/orderssynced.sql +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select -Accession_Number as order_accession, -Recorded_Date merge_datecreated, -Posted_Date merge_dateposted, -objectid, -1 as resultsreceived - -from IRIS_Lis_TransactionlogMaster -WHERE ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/pairings.sql b/onprc_ehr/resources/etl/deprecated/pairings.sql deleted file mode 100644 index de41a275c..000000000 --- a/onprc_ehr/resources/etl/deprecated/pairings.sql +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(pp.Animalid1 as nvarchar(4000)) as Id, ---cast(pp.Animalid2 as nvarchar(4000)) as Id2, - pp.Pairingdate as date, ---pp.SeparationDate as enddate, - - L1.Location as room, - ltrim(rtrim(rtrim(r1.row) + convert(char(2), r1.Cage))) As Cage, - CASE - WHEN (ltrim(rtrim(rtrim(r1.row) + convert(char(2), r1.Cage))) < ltrim(rtrim(rtrim(r2.row) + convert(char(2), r2.Cage)))) THEN ltrim(rtrim(rtrim(r1.row) + convert(char(2), r1.Cage))) - ELSE ltrim(rtrim(rtrim(r2.row) + convert(char(2), r2.Cage))) - END as lowestCage, - pp.objectid as pairid, - ---L2.Location as room2, ---ltrim(rtrim(rtrim(r2.row) + convert(char(2), r2.Cage))) As Cage2, - - 'Pair attempt' as eventType, - s2.Value as housingType, - s3.Value as outcome, - - s4.Value AS separationReason, - - case when pp.aggressor = pp.Animalid1 THEN 'Aggression' ELSE null END as observation, - pp.Remarks as Remark, - - s5.Value AS PairingOrigin, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - cast(pp.objectid as varchar(38)) + '1' as objectid - -FROM Psych_Pairings PP - left join Ref_Technicians rt on (PP.Technician = rt.ID) - left join Sys_parameters s1 on (s1.Field = 'DepartmentCode' And s1.Flag = rt.DeptCode) - left join Sys_parameters s2 on (s2.Field = 'PairingType' And s2.Flag = PP.PairingType) - left join Sys_parameters s3 on (s3.Field = 'PairingOutcome' And s3.Flag = PP.PairingOutcome) - left join Sys_parameters s4 on (s4.Field = 'PairingSeparationReason' And s4.Flag = PP.SeparationReason) - left join Sys_parameters s5 on (s5.Field = 'PairingOrigin' And s5.Flag = PP.PairingOrigin) - - left join Ref_RowCage r1 on (r1.CageID = PP.CageID1) - left join Ref_Location L1 on (r1.LocationID = L1.LocationId) - - left join Ref_RowCage r2 on (r2.CageID = PP.CageID2) - left join Ref_Location L2 on (r2.LocationID = L2.LocationId) - -where s5.Value != 'Autogenerated' and s5.Value != 'Unscheduled' -and pp.ts > ? - -union all - -SELECT - --cast(pp.Animalid1 as nvarchar(4000)) as Id, - cast(pp.Animalid2 as nvarchar(4000)) as Id, - pp.Pairingdate as date, - --pp.SeparationDate as enddate, - --- L1.Location as room, --- ltrim(rtrim(rtrim(r1.row) + convert(char(2), r1.Cage))) As Cage, - - L2.Location as room, - ltrim(rtrim(rtrim(r2.row) + convert(char(2), r2.Cage))) As Cage, - CASE - WHEN (ltrim(rtrim(rtrim(r1.row) + convert(char(2), r1.Cage))) < ltrim(rtrim(rtrim(r2.row) + convert(char(2), r2.Cage)))) THEN ltrim(rtrim(rtrim(r1.row) + convert(char(2), r1.Cage))) - ELSE ltrim(rtrim(rtrim(r2.row) + convert(char(2), r2.Cage))) - END as lowestCage, - pp.objectid as pairid, - - 'Pair attempt' as eventType, - s2.Value as housingType, - s3.Value as outcome, - - s4.Value AS separationReason, - - case when pp.aggressor = pp.Animalid2 THEN 'Aggression' ELSE null END as observation, - pp.Remarks as Remark, - - s5.Value AS PairingOrigin, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - cast(pp.objectid as varchar(38)) + '2' as objectid - -FROM Psych_Pairings PP - left join Ref_Technicians rt on (PP.Technician = rt.ID) - left join Sys_parameters s1 on (s1.Field = 'DepartmentCode' And s1.Flag = rt.DeptCode) - left join Sys_parameters s2 on (s2.Field = 'PairingType' And s2.Flag = PP.PairingType) - left join Sys_parameters s3 on (s3.Field = 'PairingOutcome' And s3.Flag = PP.PairingOutcome) - left join Sys_parameters s4 on (s4.Field = 'PairingSeparationReason' And s4.Flag = PP.SeparationReason) - left join Sys_parameters s5 on (s5.Field = 'PairingOrigin' And s5.Flag = PP.PairingOrigin) - - left join Ref_RowCage r1 on (r1.CageID = PP.CageID1) - left join Ref_Location L1 on (r1.LocationID = L1.LocationId) - - left join Ref_RowCage r2 on (r2.CageID = PP.CageID2) - left join Ref_Location L2 on (r2.LocationID = L2.LocationId) - -where s5.Value != 'Autogenerated' and s5.Value != 'Unscheduled' -and pp.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/procedure_lookups.sql b/onprc_ehr/resources/etl/deprecated/procedure_lookups.sql deleted file mode 100644 index d2ce1dce8..000000000 --- a/onprc_ehr/resources/etl/deprecated/procedure_lookups.sql +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---insert procedures, only if not already present --- INSERT INTO labkey.ehr_lookups.procedures (name, category, active, major) --- Select --- ProcedureName as name, --- 'Surgery' as category, --- CASE --- WHEN Status = 1 THEN 1 --- ELSE 0 --- END as active, -- 1 = active, 0 = inactive --- --rsp.DisplayOrder, --- --Category as CategoryInt, --- CASE --- WHEN s1.Value = 'Major Surgery' then 1 --- ELSE 0 --- END as major --- From IRIS_Production.dbo.Ref_SurgProcedure rsp --- left join IRIS_Production.dbo.Sys_Parameters s1 on (s1.Field = 'SurgeryCategory' and rsp.Category = s1.Flag) --- LEFT JOIN labkey.ehr_lookups.procedures p ON (rsp.ProcedureName = p.name) --- WHERE p.name IS NULL - - ---procedure comments --- TRUNCATE TABLE labkey.ehr_lookups.procedure_default_comments; --- INSERT INTO labkey.ehr_lookups."procedure_default_comments" (procedureid, comment) --- Select --- --p0.ProcedureID, --Ref_SurgProcedure --- (SELECT rowid from labkey.ehr_lookups.procedures p WHERE p.name = r.procedureName) as procedureid, --- cast(coalesce(p0.LogText, '') as nvarchar(4000)) + cast(coalesce(p1.LogText, '') as nvarchar(4000)) + cast(coalesce(p2.LogText, '') as nvarchar(4000)) + cast(coalesce(p3.LogText, '') as nvarchar(4000)) + cast(coalesce(p4.LogText, '') as nvarchar(4000)) + cast(coalesce(p5.LogText, '') as nvarchar(4000)) as Comment --- --- From IRIS_Production.dbo.Ref_SurgLog p0 --- LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure r on (p0.procedureid = r.procedureid) --- LEFT JOIN IRIS_Production.dbo.Ref_SurgLog p1 ON (p0.ProcedureID = p1.ProcedureID AND p1.LogPage = 1) --- LEFT JOIN IRIS_Production.dbo.Ref_SurgLog p2 ON (p0.ProcedureID = p2.ProcedureID AND p2.LogPage = 2) --- LEFT JOIN IRIS_Production.dbo.Ref_SurgLog p3 ON (p0.ProcedureID = p3.ProcedureID AND p2.LogPage = 3) --- LEFT JOIN IRIS_Production.dbo.Ref_SurgLog p4 ON (p0.ProcedureID = p4.ProcedureID AND p2.LogPage = 4) --- LEFT JOIN IRIS_Production.dbo.Ref_SurgLog p5 ON (p0.ProcedureID = p5.ProcedureID AND p2.LogPage = 5) --- --- WHERE p0.LogPage = 0 - - ---procedure flags --- TRUNCATE TABLE labkey.ehr_lookups.procedure_default_flags; --- INSERT INTO labkey.ehr_lookups.procedure_default_flags (procedureId, flag, value) --- Select --- (SELECT rowid from labkey.ehr_lookups.procedures p WHERE p.name = r.procedureName) as procedureid, --- 'BreedImpair' as flag, --- 'Y' as value --- --- FROM IRIS_Production.dbo.Ref_SurgProcedure r --- WHERE BreedImpairFlag = 1; - --- INSERT INTO labkey.ehr_lookups.procedure_default_flags (procedureId, flag, value) --- Select --- (SELECT rowid from labkey.ehr_lookups.procedures p WHERE p.name = r.procedureName) as procedureid, --- 'USDASurvival' as flag, --- 'Y' as value --- --- FROM IRIS_Production.dbo.Ref_SurgProcedure r --- WHERE USDASurvivalFlag = 1; - --- INSERT INTO labkey.ehr_lookups.procedure_default_flags (procedureId, flag, value) --- Select --- (SELECT rowid from labkey.ehr_lookups.procedures p WHERE p.name = r.procedureName) as procedureid, --- 'Vessel Surgery' as flag, --- 'Y' as value --- --- FROM IRIS_Production.dbo.Ref_SurgProcedure r --- WHERE VesselID = 1; - ---NOTE: due to additions in PRIMe, these are no longer synced --- --procedure medications --- TRUNCATE TABLE labkey.ehr_lookups.procedure_default_treatments; --- INSERT INTO labkey.ehr_lookups.procedure_default_treatments (procedureid, code, dosage, dosage_units, route, frequency) --- Select --- (SELECT rowid from labkey.ehr_lookups.procedures p WHERE p.name = r.procedurename and p.category = 'Surgery') as procedureid, --- Medication as code, --- rsm.Dose as dosage, --- s1.Value as dosage_units, --- --Route as RouteInt, --- s2.Value as Route, --- null as frequency --- --(SELECT rowid from labkey.ehr_lookups.treatment_frequency f WHERE f.meaning = s3.Value) as Frequency --- --- From IRIS_Production.dbo.Ref_SurgMedications rsm --- left join IRIS_Production.dbo.Sys_Parameters s1 on (s1.Field = 'MedicationUnits' and s1.Flag = rsm.Units) --- left join IRIS_Production.dbo.Sys_Parameters s2 on (s2.Field = 'MedicationRoute' and s2.Flag = rsm.route) --- left join IRIS_Production.dbo.Sys_Parameters s3 on (s3.Field = 'MedicationFrequency' and s3.Flag = rsm.frequency) --- LEFT JOIN IRIS_Production.dbo.Ref_SurgProcedure r on (rsm.procedureid = r.procedureid); --- --- --- --procedure_default_codes --- TRUNCATE TABLE labkey.ehr_lookups.procedure_default_codes; --- INSERT INTO labkey.ehr_lookups.procedure_default_codes (procedureid, sort_order, code) --- Select --- (SELECT max(rowid) as rowid from labkey.ehr_lookups.procedures p2 WHERE p.ProcedureName = p2.name) as procedureid, --- s2.i as sort, --- s2.value as code --- --- From IRIS_Production.dbo.Ref_SurgSnomed r --- left join IRIS_Production.dbo.Ref_SurgProcedure p on (r.ProcedureID = p.ProcedureID) --- cross apply IRIS_Production.dbo.fn_splitter(r.SnomedCodes, ',') s2 --- where s2.value is not null and s2.value != '' and p.ProcedureID is not null; diff --git a/onprc_ehr/resources/etl/deprecated/project.sql b/onprc_ehr/resources/etl/deprecated/project.sql deleted file mode 100644 index 093a09f68..000000000 --- a/onprc_ehr/resources/etl/deprecated/project.sql +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - t2.*, - CASE - WHEN t2.enddateRaw > CURRENT_TIMESTAMP THEN NULL - else t2.enddateRaw - END as enddate - -FROM ( - -select - --coalesce(i2.eIACUCNum, rtrim(ltrim(lower(i2.IACUCCode)))) as protocol, - rtrim(ltrim(i2.IACUCCode)) as protocol, - CASE - WHEN (t.grantStart IS NOT NULL AND (t.IcacucStartDate IS NULL OR t.IcacucStartDate < t.grantStart)) THEN t.grantStart - ELSE t.IcacucStartDate - END as startdate, - CASE - WHEN (t.grantEnd IS NOT NULL AND (t.IcacucEndDate IS NULL OR t.IcacucEndDate > t.grantEnd) AND ((coalesce(i2.dateDisabled, i2.EndDate) IS NULL OR coalesce(i2.dateDisabled, i2.EndDate) > t.grantEnd))) THEN t.grantEnd - WHEN (t.IcacucEndDate IS NULL OR ((coalesce(i2.dateDisabled, i2.EndDate) IS NOT NULL AND coalesce(i2.dateDisabled, i2.EndDate) < t.IcacucEndDate))) THEN coalesce(i2.dateDisabled, i2.EndDate) - ELSE t.IcacucEndDate - END as enddateRaw, - t.* - -FROM ( - -select - - Rpi.ProjectId as project, - rpi.IACUCCode, - rtrim(ltrim(Rpi.IACUCCode)) as name, - coalesce ((select top 1 - ipc.projectparentid - from Ref_ProjectsIACUC rpi2 join Ref_IACUCParentChildren ipc on (rpi2.ProjectID = ipc.ProjectParentID and ipc.datedisabled is null) - where ipc.projectchildid = rpi.projectid order by ipc.datecreated desc), rpi.projectid) as protocolId, - - rtrim(ltrim((select top 1 ohsuaccountnumber from Ref_ProjectAccounts rpa where rpi.projectid = rpa.ProjectID order by datecreated desc))) as account, - Rpi.Title, - Rpi.StartDate as IcacucStartDate, - coalesce(rpi.dateDisabled, Rpi.EndDate) as IcacucEndDate, - (select max(pg.GrantStartDate) as startdate FROM Ref_ProjectGrants pg WHERE pg.ProjectID = rpi.ProjectID) as grantStart, - (select max(coalesce(pg.GrantEndDate, pg.datedisabled)) as enddate FROM Ref_ProjectGrants pg WHERE pg.ProjectID = rpi.ProjectID) as grantEnd, - - CASE - WHEN pc2.InvestigatorID IS NULL THEN (select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri.firstname and i.lastname = ri.lastname group by i.LastName, i.firstname having count(*) <= 1) - ELSE (select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri2.firstname and i.lastname = ri2.lastname group by i.LastName, i.firstname having count(*) <= 1) - END as investigatorId, - rpi.objectid, - CASE - WHEN Rpi.IACUCCode LIKE '%0492%' THEN 0 - ELSE 1 - END as research, - - CASE - WHEN Rpi.IACUCCode = '0492' THEN 1 --P51 - ELSE 0 - END as alwaysavailable, - - CASE - WHEN Rpi.IACUCCode = '0492' THEN 'Base Grant' --P51 - ELSE null - END as shortname, - - CASE - WHEN Rpi.IACUCCode = '0492' THEN 'P51' --P51 - WHEN Rpi.IACUCCode = '0492-03' THEN 'U24' - WHEN Rpi.IACUCCode = '0492-02' THEN 'U42' - WHEN Rpi.IACUCCode = '0300' THEN 'Center Resource' - WHEN Rpi.IACUCCode = '0456' THEN 'Center Resource' - WHEN Rpi.IACUCCode = '0027' THEN 'Center Resource' - WHEN Rpi.IACUCCode = '0833' THEN 'Center Resource' - WHEN Rpi.IACUCCode = '0095-50' THEN 'Center Resource' - WHEN Rpi.IACUCCode = '0689' THEN 'Center Resource' - WHEN Rpi.IACUCCode = '0794' THEN 'Center Resource' - - ELSE 'Research' - END as use_category, - s2.value as projectType - -From Ref_ProjectsIACUC rpi - left join Ref_ProjInvest pc on (pc.ProjectID = rpi.ProjectID AND pc.DateDisabled is null and pc.PIFlag = 1 and pc.investigatorid != 0) - left join Ref_Investigator ri on (ri.InvestigatorID = pc.investigatorid) - - left join Ref_ProjInvest pc2 on (pc2.ProjectID = rpi.ProjectID AND pc2.DateDisabled is null and pc2.PIFlag = 2 and pc2.investigatorid != 0) - left join Ref_Investigator ri2 on (ri2.InvestigatorID = pc2.investigatorid) - left join Sys_Parameters s2 on (rpi.projecttype = s2.Flag and s2.Field = 'ProjectType') - -WHERE (rpi.ts > ? or pc.ts > ? or ri.ts > ? - OR (select max(ts) as maxts FROM Ref_ProjectGrants g WHERE g.ProjectID = rpi.ProjectID) > ? - OR (select max(ts) as maxts from Ref_ProjectAccounts rpa where rpi.ProjectID = rpa.ProjectID) > ? - OR (select max(rpi2.ts) as maxTs from Ref_ProjectsIACUC rpi2 join Ref_IACUCParentChildren ipc on (rpi2.ProjectID = ipc.ProjectParentID and ipc.datedisabled is null) where ipc.projectchildid = rpi.projectid) > ? -) -) t - -LEFT JOIN Ref_ProjectsIACUC i2 ON (i2.ProjectID = t.protocolId) -) t2 \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/projectAccountHistory.sql b/onprc_ehr/resources/etl/deprecated/projectAccountHistory.sql deleted file mode 100644 index 7da89c41e..000000000 --- a/onprc_ehr/resources/etl/deprecated/projectAccountHistory.sql +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -SELECT * FROM ( -select - rpa.projectid as project, - ltrim(rtrim(rpa.ohsuaccountnumber)) as account, - CASE - WHEN (rpa.aliasstartdate >= rpa.DateCreated) THEN CAST(rpa.aliasstartdate AS DATE) - ELSE CAST(rpa.DateCreated AS DATE) - END as startdate, - COALESCE(CASE - WHEN (rpa.AliasExpirationDate >= rpa.DateDisabled) THEN CAST(dateadd(d, -1, rpa.DateDisabled) AS DATE) - ELSE CAST(Dateadd(d, -1,rpa.AliasExpirationDate) AS DATE) - END, CAST('2015/04/30' as date)) as enddate, - rpa.objectid - from Ref_ProjectAccounts rpa - where rpa.ts > ? -) t WHERE t.startdate >= '2009-01-01' and ltrim(rtrim(t.account)) IS NOT NULL and ltrim(rtrim(t.account)) != '' \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/protocol.sql b/onprc_ehr/resources/etl/deprecated/protocol.sql deleted file mode 100644 index ec149e3a2..000000000 --- a/onprc_ehr/resources/etl/deprecated/protocol.sql +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -select - --rpi.ProjectID, --- case --- when Rpi.eIACUCNum is null OR datalength(rtrim(ltrim(Rpi.eIACUCNum))) = 0 then rtrim(ltrim(Rpi.IACUCCode)) --- else rtrim(ltrim(Rpi.eIACUCNum)) --- end as protocol, - rtrim(ltrim(Rpi.IACUCCode)) as protocol, - rtrim(ltrim(Rpi.Title)) as title, - - --(select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri.firstname and i.lastname = ri.lastname group by i.LastName, i.firstname having count(*) <= 1) as investigatorId, - CASE - WHEN pi2.InvestigatorID IS NULL THEN (select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri.firstname and i.lastname = ri.lastname group by i.LastName, i.firstname having count(*) <= 1) - ELSE (select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri2.firstname and i.lastname = ri2.lastname group by i.LastName, i.firstname having count(*) <= 1) - END as investigatorId, - --(ri.LastName + ', ' + ri.FirstName) as inves, - - --i think this is the last yearly approval - --rpi.IACUCApprovalDate as approve, - rpi.OriginalApprovalDate as approve, - coalesce(rpi.dateDisabled, Rpi.EndDate) as enddate, - s1.Value as USDA_Level, - Rpi.eIACUCNum as external_id, - Rpi.IBCApprovalNum as ibc_approval_num, - Rpi.IBCApprovalRequired as ibc_approval_required, - Rpi.DateCreated as created, - --S2.Value as Project_Type, - rpi.objectid - From Ref_ProjectsIACUC rpi - left join Ref_IACUCParentChildren ipc on (rpi.ProjectID = ipc.ProjectParentID and ipc.ProjectChildID = ipc.ProjectParentID and ipc.DateDisabled is null) - - left join Ref_ProjInvest pi on (pi.ProjectID = rpi.ProjectID AND pi.DateDisabled is null and pi.PIFlag = 1 and pi.InvestigatorID != 0) - left join Ref_Investigator ri on ri.InvestigatorID = pi.investigatorid - - left join Ref_ProjInvest pi2 on (pi2.ProjectID = rpi.ProjectID AND pi2.DateDisabled is null and pi2.PIFlag = 2 and pi2.investigatorid != 0) - left join Ref_Investigator ri2 on (ri2.InvestigatorID = pi2.investigatorid) - - left join Sys_Parameters s1 on (rpi.USDALevel = s1.Flag and s1.Field = 'USDALevel') - left join Sys_Parameters s2 on (rpi.projecttype = s2.Flag and s2.Field = 'ProjectType') - where rpi.datedisabled is null and rpi.projectid = ipc.ProjectParentID - - AND (rpi.ts > ? OR ipc.ts > ? or pi.ts > ? or ri.ts > ?) - ---also include any project missing from the parent/child table -UNION ALL - -select - --rpi.ProjectID, --- case --- when Rpi.eIACUCNum is null OR datalength(rtrim(ltrim(Rpi.eIACUCNum))) = 0 then rtrim(ltrim(Rpi.IACUCCode)) --- else rtrim(ltrim(Rpi.eIACUCNum)) --- end as protocol, - rtrim(ltrim(Rpi.IACUCCode)) as protocol, - rtrim(ltrim(Rpi.Title)) as title, - - --(select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri.firstname and i.lastname = ri.lastname group by i.LastName, i.firstname having count(*) <= 1) as investigatorId, - CASE - WHEN pi2.InvestigatorID IS NULL THEN (select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri.firstname and i.lastname = ri.lastname group by i.LastName, i.firstname having count(*) <= 1) - ELSE (select max(i.rowid) from labkey.onprc_ehr.investigators i where i.firstname = ri2.firstname and i.lastname = ri2.lastname group by i.LastName, i.firstname having count(*) <= 1) - END as investigatorId, - - --(ri.LastName + ', ' + ri.FirstName) as inves, - - --i think this is the last yearly approval - --rpi.IACUCApprovalDate as approve, - rpi.OriginalApprovalDate as approve, - coalesce(rpi.dateDisabled, Rpi.EndDate) as enddate, - s1.Value as USDA_Level, - Rpi.eIACUCNum as external_id, - Rpi.IBCApprovalNum as ibc_approval_num, - Rpi.IBCApprovalRequired as ibc_approval_required, - Rpi.DateCreated as created, - --S2.Value as Project_Type, - rpi.objectid - From Ref_ProjectsIACUC rpi - left join Ref_IACUCParentChildren pc ON (rpi.ProjectID = pc.ProjectChildID) - left join Ref_IACUCParentChildren pc2 ON (rpi.ProjectID = pc.ProjectParentID) - - left join Ref_ProjInvest pi on (pi.ProjectID = rpi.ProjectID AND pi.DateDisabled is null and pi.PIFlag = 1 and pi.InvestigatorID != 0) - left join Ref_Investigator ri on (ri.InvestigatorID = pi.investigatorid) - - left join Ref_ProjInvest pi2 on (pi2.ProjectID = rpi.ProjectID AND pi2.DateDisabled is null and pi2.PIFlag = 2 and pi2.investigatorid != 0) - left join Ref_Investigator ri2 on (ri2.InvestigatorID = pi2.investigatorid) - - left join Sys_Parameters s1 on (rpi.USDALevel = s1.Flag and s1.Field = 'USDALevel') - left join Sys_Parameters s2 on (rpi.projecttype = s2.Flag and s2.Field = 'ProjectType') - where pc.IDKey is null and pc2.IDKey is null - - AND (rpi.ts > ? OR pc.ts > ? OR pc2.ts > ? or pi.ts > ? or ri.ts > ?) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/protocolProcedures.sql b/onprc_ehr/resources/etl/deprecated/protocolProcedures.sql deleted file mode 100644 index 0bc911cc1..000000000 --- a/onprc_ehr/resources/etl/deprecated/protocolProcedures.sql +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - SELECT - --iacuc.ProjectID as ProjectID , --Ref_ProjectsIACUC - coalesce(rtrim(ltrim(lower(ri.IACUCCode))), 'None') as protocol, - - --iacuc.ProcedureID as ProcedureID , --Ref_SurgProcedure - s.procedurename as procedurename, - (SELECT rowid from labkey.ehr_lookups.procedures p WHERE p.name = s.procedureName and p.category = 'Surgery') as procedureid, - - iacuc.ProcedureCount as allowed, - iacuc.DateCreated as startdate, - iacuc.objectid - -FROM IACUC_NHPSurgeries IACUC -left join Ref_SurgProcedure s on (iacuc.ProcedureID = s.ProcedureID) -left join Ref_ProjectsIACUC ri on (IACUC.ProjectID = ri.ProjectID) -where IACUC.DateDisabled is null -and (iacuc.ts > ? or s.ts > ? or ri.ts > ?) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/protocol_counts.sql b/onprc_ehr/resources/etl/deprecated/protocol_counts.sql deleted file mode 100644 index 9c23bfedc..000000000 --- a/onprc_ehr/resources/etl/deprecated/protocol_counts.sql +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT * FROM ( - -select -CASE WHEN t.protocolId IS NULL THEN project WHEN t.protocolId = t.project THEN null ELSE t.project END as project, -CASE WHEN t.protocolId = project THEN RTRIM(ltrim(i2.IACUCCode)) ELSE null END as protocol, -t.species, -t.gender, -t.allowed, -t.start, -t.endDate, -t.objectid - -from ( - -Select -y.projectID as project, ---r.IACUCCode as project, - -(select top 1 ipc.projectparentid - from Ref_ProjectsIACUC rpi2 join Ref_IACUCParentChildren ipc on (rpi2.ProjectID = ipc.ProjectParentID and ipc.datedisabled is null) - where ipc.projectchildid = r.projectid order by ipc.datecreated desc -) as protocolId, - -(select max(rpi2.ts) as maxTs - from Ref_ProjectsIACUC rpi2 join Ref_IACUCParentChildren ipc on (rpi2.ProjectID = ipc.ProjectParentID and ipc.datedisabled is null) - where ipc.projectchildid = r.projectid -) as maxTs, - ---r.eIACUCNum, -y.CurrentYearStartDate as start, -y.CurrentYearEndDate as endDate, -a.NumAnimalsAssigned as allowed, -CASE -WHEN sp.commonname like '%Cynomolgus%' THEN 'CYNOMOLGUS MACAQUE' -WHEN sp.commonname like '%Rhesus%' THEN 'RHESUS MACAQUE' -WHEN sp.commonname like '%Japanese%' THEN 'JAPANESE MACAQUE' -ELSE sp.CommonName -END as species, -CASE -WHEN s.value = 'Female' then 'f' -WHEN s.value = 'Male' then 'm' -ELSE s.Value -END as gender, -y.objectid - -from IACUC_NHPYearly y -join IACUC_NHPAnimals a on (y.NHPYearlyID = a.NHPYearlyID) -join ref_ProjectsIACUC r on (r.ProjectID = y.ProjectID) -left join ref_species sp on (sp.SpeciesCode = a.Species) -left join ref_sex s on (s.Flag = a.Sex) - -where (y.DateDisabled is null and a.DateDisabled is Null) and y.CurrentYearEndDate > '1/1/2010' -and (y.ts > ? OR a.ts > ? OR r.ts > ?) - -) t - -LEFT JOIN Ref_ProjectsIACUC i2 ON (i2.ProjectID = t.protocolId) - -WHERE (maxTs > ? or maxTs IS NULL) - -) t - -WHERE (t.project IS NOT NULL OR t.protocol IS NOT NULL) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/ehr/encounter_flags.sql b/onprc_ehr/resources/etl/ehr/encounter_flags.sql deleted file mode 100644 index bfe379064..000000000 --- a/onprc_ehr/resources/etl/ehr/encounter_flags.sql +++ /dev/null @@ -1,1120 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -select -id, -date, -flag, -value, -objectid as parentid, -(cast(t.objectid as varchar(38)) + '_' + t.flag) as objectid - -FROM ( - ---Cln_AntibioticSensHeader -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid - -FROM Cln_AntibioticSensHeader cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_AntibioticSensHeader cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_AntibioticSensHeader cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_AntibioticSensHeader cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_AntibioticSensHeader cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_AntibioticSensHeader cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_AntibioticSensHeader cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_AntibioticSensHeader cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_AntibioticSensHeader - -UNION ALL - ---Cln_Biochemistry -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_Biochemistry cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_Biochemistry - -UNION ALL - ---Cln_IStat -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_IStat cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_IStat - -UNION ALL - ---Cln_OccultBlood -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_OccultBlood cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_OccultBlood - -UNION ALL - ---Cln_Hematology -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - ---hematology manualDiff -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Manual Diff' as flag, - 'Y' as value, - objectid - -FROM Cln_Hematology cln -WHERE manualDiff = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_Hematology cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_Hematology - -UNION ALL - ---Cln_CerebralspinalFluid -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_CerebralspinalFluid cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_CerebralspinalFluid - -UNION ALL - ---Cln_MicrobiologyHeader -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_MicrobiologyHeader cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_MicrobiologyHeader - -UNION ALL - ---Cln_RareTestHeader -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_RareTestHeader cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_RareTestHeader - -UNION ALL - ---Cln_VirologyHeader -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_VirologyHeader cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_VirologyHeader - -UNION ALL - ---Cln_SerologyHeader -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_SerologyHeader cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_SerologyHeader - -UNION ALL - ---Cln_Urinalysis -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_Urinalysis cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_Urinalysis - -UNION ALL - ---Cln_Parasitology -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Experimental' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE experimental = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'PreAssignment' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE PreAssignment = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Quarantine' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE Quarantine = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Pregnant' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE Pregnant = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Followup' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE Followup = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Presale' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE Presale = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Fasting' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE Fasting = 1 AND cln.ts > ? - -UNION ALL - -SELECT - cast(AnimalId as nvarchar(4000)) as Id, - Date , - 'Sedated' as flag, - 'Y' as value, - objectid -FROM Cln_Parasitology cln -WHERE Sedated = 1 AND cln.ts > ? ---EO Cln_Parasitology - -) t - diff --git a/onprc_ehr/resources/etl/ehr/encounter_participants.sql b/onprc_ehr/resources/etl/ehr/encounter_participants.sql deleted file mode 100644 index a1dfd63e5..000000000 --- a/onprc_ehr/resources/etl/ehr/encounter_participants.sql +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - null as userid, - cast(AnimalId as nvarchar(4000)) as Id, - t.role, - t.procedure_id as parentid, - (cast(t.procedure_id as varchar(38)) + '_' + t.role) as objectid, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as username - -FROM ( - -SELECT - p.pathologist as userId, - p.animalid, - 'Pathologist' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Autopsy p -WHERE datalength(p.pathologist) > 0 - -UNION ALL - -SELECT - p.prosector1 as userId, - p.animalid, - 'Prosector1' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Autopsy p -WHERE datalength(p.prosector1) > 0 - -UNION ALL - -SELECT - p.prosector2 as userId, - p.animalid, - 'Prosector2' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Autopsy p -WHERE datalength(p.prosector2) > 0 - -UNION ALL - -SELECT - p.prosector3 as userId, - p.animalid, - 'Prosector3' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Autopsy p -WHERE datalength(p.prosector3) > 0 - -UNION ALL - -SELECT - p.pathologist as userId, - p.animalid, - 'Pathologist' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Biopsy p -WHERE datalength(p.pathologist) > 0 - -UNION ALL - -SELECT - p.prosector1 as userId, - p.animalid, - 'Prosector1' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Biopsy p -WHERE datalength(p.prosector1) > 0 - -UNION ALL - -SELECT - p.prosector2 as userId, - p.animalid, - 'Prosector2' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Biopsy p -WHERE datalength(p.prosector2) > 0 - -UNION ALL - -SELECT - p.prosector3 as userId, - p.animalid, - 'Prosector3' as role, - objectid as procedure_id, - ts as rowversion - -From Path_Biopsy p -WHERE datalength(p.prosector3) > 0 - -UNION ALL - -SELECT - s.surgeon as userId, - s.animalid, - 'Surgeon' as role, - objectid as procedure_id, - ts as rowversion - -From Sur_General s -WHERE datalength(s.surgeon) > 0 - -UNION ALL - -SELECT - s.Assistant as userId, - s.animalid, - 'Assistant' as role, - objectid as procedure_id, - ts as rowversion - -From Sur_General s -WHERE datalength(s.Assistant) > 0 - -UNION ALL - -SELECT - s.Anesthetist as userId, - s.animalid, - 'Anesthetist' as role, - objectid as procedure_id, - ts as rowversion - -From Sur_General s -WHERE datalength(s.Anesthetist) > 0 - -UNION ALL - -SELECT - s.InstrumentTech as userId, - s.animalid, - 'Instrument Tech' as role, - objectid as procedure_id, - ts as rowversion - -From Sur_General s -WHERE datalength(s.InstrumentTech) > 0 - -UNION ALL - -SELECT - s.Circulator as userId, - s.animalid, - 'Circulator' as role, - objectid as procedure_id, - ts as rowversion - -From Sur_General s -WHERE datalength(s.Circulator) > 0 - -UNION ALL - -SELECT - i.surgeon as userId, - i.animalid, - 'Surgeon' as role, - max(cast(objectid as varchar(38))) as procedure_id, - max(ts) as rowversion - -From Sur_Implants i -WHERE datalength(i.surgeon) > 0 -GROUP BY i.AnimalId, i.Date, i.Surgeon - -) t - -left join Ref_Technicians Rt on (t.userId = Rt.ID) - -where t.rowversion > ? and rt.lastname != ' none' \ No newline at end of file diff --git a/onprc_ehr/resources/etl/ehr/encounter_summaries.sql b/onprc_ehr/resources/etl/ehr/encounter_summaries.sql deleted file mode 100644 index 2272048cc..000000000 --- a/onprc_ehr/resources/etl/ehr/encounter_summaries.sql +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(pat.AnimalID as nvarchar(4000)) as Id, - pat.Date, - 'Summary Comments' as category, - l.LogText as remark, - --l.SequenceNo, - - pat.objectid as parentid, - l.objectid -From Path_Autopsy Pat -left join Path_AutopsyLog l ON (l.AutopsyID = pat.AutopsyId) -where l.LogText is not null and DATALENGTH(l.LogText) > 0 and l.LogText != '' and l.LogText not like 'Testing testing%' -and pat.ts > ? - -UNION ALL - -Select - cast(pat.AnimalID as nvarchar(4000)) as Id, - pat.Date, - 'Summary Comments' as category, - l.LogText as remark, - --l.SequenceNo, - - pat.objectid as parentid, - l.objectid -From Path_Biopsy Pat -left join Path_BiopsyLog l ON (l.BiopsyID = pat.BiopsyId) -where l.LogText is not null and DATALENGTH(l.LogText) > 0 and l.LogText != '' and l.LogText not like 'Testing testing%' -and pat.ts > ? - -UNION ALL - -select * FROM ( -Select - cast(pat.AnimalID as nvarchar(4000)) as Id, - pat.Date, - 'Narrative' as category, - REPLACE( - cast(coalesce(log0.logtext, '') as nvarchar(4000)) + - cast(coalesce(log1.logtext, '') as nvarchar(4000)) + - cast(coalesce(log2.logtext, '') as nvarchar(4000)) + - cast(coalesce(log3.logtext, '') as nvarchar(4000)) + - cast(coalesce(log4.logtext, '') as nvarchar(4000)) + - cast(coalesce(log5.logtext, '') as nvarchar(4000)) + - cast(coalesce(log6.logtext, '') as nvarchar(4000)) + - cast(coalesce(log7.logtext, '') as nvarchar(4000)) + - cast(coalesce(log8.logtext, '') as nvarchar(4000)) - --TODO - , char(25), CHAR(10)) AS remark, - - pat.objectid as parentid, - log0.objectid -From Sur_General Pat -left join Sur_Log log0 ON (log0.SurgeryID = pat.SurgeryID and log0.SequenceNo = 0) -left join Sur_Log log1 ON (log1.SurgeryID = pat.SurgeryID and log1.SequenceNo = 1) -left join Sur_Log log2 ON (log2.SurgeryID = pat.SurgeryID and log2.SequenceNo = 2) -left join Sur_Log log3 ON (log3.SurgeryID = pat.SurgeryID and log3.SequenceNo = 3) -left join Sur_Log log4 ON (log4.SurgeryID = pat.SurgeryID and log4.SequenceNo = 4) -left join Sur_Log log5 ON (log5.SurgeryID = pat.SurgeryID and log5.SequenceNo = 5) -left join Sur_Log log6 ON (log6.SurgeryID = pat.SurgeryID and log6.SequenceNo = 6) -left join Sur_Log log7 ON (log7.SurgeryID = pat.SurgeryID and log7.SequenceNo = 7) -left join Sur_Log log8 ON (log8.SurgeryID = pat.SurgeryID and log8.SequenceNo = 8) - -WHERE pat.surgeryid IN (select sl.SurgeryID FROM Sur_Log sl WHERE sl.ts > ?) -) t - -WHERE t.remark not like '%Testing testing%' and datalength(t.remark) > 0 - -UNION ALL - ---implant data -Select - cast(im.AnimalID as nvarchar(4000)) as Id, - im.Date, - 'Narrative' as category, - im.Comments AS remark, - - max(cast(im.objectid as varchar(38))) as parentid, - max(cast(im.objectid as varchar(38))) as objectid -From sur_implants im - -WHERE comments is not null and comments != '' -GROUP BY im.AnimalID, im.Date, im.Comments -having max(im.ts) > ? - - diff --git a/onprc_ehr/resources/etl/ehr/snomed_tags.sql b/onprc_ehr/resources/etl/ehr/snomed_tags.sql deleted file mode 100644 index 0abb427b0..000000000 --- a/onprc_ehr/resources/etl/ehr/snomed_tags.sql +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(dx.AnimalID as nvarchar(4000)) as Id, - c.objectid as caseid, - dx.objectid as recordid, - - (cast(s.objectid as varchar(38)) + '-' + cast(s2.i as varchar(100)) + '-' + cast(s2.value as nvarchar(100))) as objectid, - coalesce(s.sequenceNo, 0) as set_number, - s2.i as sort, - cast(s2.value as nvarchar(100)) as code - -FROM Cln_DxSnomed s -left join cln_dx dx ON (dx.DiagnosisID = s.DiagnosisID) -left join af_case c ON (dx.caseid = c.caseid) -cross apply dbo.fn_splitter(s.snomed, ',') s2 -where s2.value is not null and s2.value != '' -and s2.value not in ('P-Y0038', 'P-26600') --exclude weighing and blood collection -and s.Snomed != 'T-00010,P-02315' --limited visual exam plus body as a whole -and s.snomed != 'P-02315' --limited visual exam without other codes ---BCS / alopecia: -AND s2.value NOT IN ( - --observations - 'F-YY002', - 'F-YY003', - 'F-YY004', - 'F-YY005', - 'F-YY006', - 'F-Y3712', - 'F-Y3714', - 'F-Y3716', - 'F-Y3718', - 'F-Y3720', - 'F-Y3722', - - --TB test - 'P-54268' -) -and s.ts > ? - -UNION ALL - -SELECT - cast(dx.AnimalID as nvarchar(4000)) as Id, - null as caseid, - dx.objectid as recordid, - - (cast(s.objectid as varchar(38)) + '-' + cast(s2.i as varchar(100)) + '-' + cast(s2.value as nvarchar(100))) as objectid, - s.Idkey as set_number, - s2.i as sort, - cast(s2.value as nvarchar(100)) as code - -FROM sur_snomed s -left join sur_general dx ON (dx.SurgeryId = s.SurgeryId) -cross apply dbo.fn_splitter(s.SnomedCodes, ',') s2 -where s2.value is not null and s2.value != '' -and s.ts > ? - --- UNION ALL --- --- Select --- cast(pa.AnimalID as nvarchar(4000)) as Id, --- null as caseid, --- d.objectid as recordid, --- (cast(d.objectid as varchar(38)) + '-' + cast(s2.i as varchar(100)) + '-' + cast(s2.value as nvarchar(100))) as objectid, --- coalesce(d.sequenceno, 0) as set_number, --- s2.i as sort, --- cast(s2.value as nvarchar(100)) as code --- --- From Path_AutopsyDiagnosis d --- left join Path_Autopsy pa on (d.AutopsyID = pa.AutopsyId) --- cross apply dbo.fn_splitter(d.SnomedCodes, ',') s2 --- where s2.value is not null and s2.value != '' --- and d.ts > ? --- --- UNION ALL --- --- Select --- cast(pa.AnimalID as nvarchar(4000)) as Id, --- null as caseid, --- d.objectid as recordid, --- (cast(d.objectid as varchar(38)) + '-' + cast(s2.i as varchar(100)) + '-' + cast(s2.value as nvarchar(100))) as objectid, --- coalesce(d.sequenceno, 0) as set_number, --- s2.i as sort, --- cast(s2.value as nvarchar(100)) as code --- --- From Path_BiopsyDiagnosis d --- left join Path_Biopsy pa on (d.BiopsyID = pa.BiopsyId) --- cross apply dbo.fn_splitter(d.SnomedCodes, ',') s2 --- where s2.value is not null and s2.value != '' --- and d.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/pending/Anesthesia.sql b/onprc_ehr/resources/etl/pending/Anesthesia.sql deleted file mode 100644 index 6fbd52afb..000000000 --- a/onprc_ehr/resources/etl/pending/Anesthesia.sql +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select - t.AnimalId, - t.date, - case - when t.timeString is null or t.timeString = '' or LEN(t.timeString) = 0 then t.date - when LEN(t.timeString) = 3 then convert(datetime, CONVERT(varchar(100), t.timeString, 111) + ' 0' + left(t.timeString, 1) + ':' + RIGHT(t.timeString, 2)) - else convert(datetime, CONVERT(varchar(100), t.date, 111) + ' ' + left(t.timeString, 2) + ':' + RIGHT(t.timeString, 2)) - end as date, - - t.parentid, - t.runid, - t.result, - t.qualResult, - t.testid, - t.objectid - -from ( - -select - t0.AnimalID, - t0.Date, - ltrim(rtrim(replace(t0.time, '_', '0'))) as timeString, - t0.objectid, - t0.parentid, - t0.qualResult, - t0.result, - t0.runid, - t0.testid - from ( - -select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.DiastolicBP as result, - null as qualResult, - 'DiastolicBP' as testid, - cast(l.objectid as varchar(36)) + 'DiastolicBP' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.DiastolicBP is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.EtCO2 as result, - null as qualResult, - 'EtCO2' as testid, - cast(l.objectid as varchar(36)) + 'EtCO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.EtCO2 is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.HeartRate as result, - null as qualResult, - 'HeartRate' as testid, - cast(l.objectid as varchar(36)) + 'HeartRate' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.HeartRate is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.IBPMap as result, - null as qualResult, - 'IBPMap' as testid, - cast(l.objectid as varchar(36)) + 'IBPMap' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.IBPMap is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - null as result, - l.IBPSD as qualResult, - 'IBPSD' as testid, - cast(l.objectid as varchar(36)) + 'IBPSD' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.IBPSD is not null and l.IBPSD != '') - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.N2OFlow as result, - null as qualResult, - 'N2OFlow' as testid, - cast(l.objectid as varchar(36)) + 'N2OFlow' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.N2OFlow is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.NIBPMap as result, - null as qualResult, - 'NIBPMap' as testid, - cast(l.objectid as varchar(36)) + 'NIBPMap' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.NIBPMap is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.O2Flow as result, - null as qualResult, - 'O2Flow' as testid, - cast(l.objectid as varchar(36)) + 'O2Flow' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.O2Flow is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.RespirationRate as result, - null as qualResult, - 'RespirationRate' as testid, - cast(l.objectid as varchar(36)) + 'RespirationRate' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.RespirationRate is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.SpO2 as result, - null as qualResult, - 'SpO2' as testid, - cast(l.objectid as varchar(36)) + 'SpO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.SpO2 is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.SystolicBP as result, - null as qualResult, - 'SystolicBP' as testid, - cast(l.objectid as varchar(36)) + 'SystolicBP' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.SystolicBP is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.Temperature as result, - null as qualResult, - 'Temperature' as testid, - cast(l.objectid as varchar(36)) + 'Temperature' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.Temperature is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.Vaporizer as result, - null as qualResult, - 'Vaporizer' as testid, - cast(l.objectid as varchar(36)) + 'Vaporizer' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.Vaporizer is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.pCO2 as result, - null as qualResult, - 'pCO2' as testid, - cast(l.objectid as varchar(36)) + 'pCO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.pCO2 is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.pH as result, - null as qualResult, - 'pH' as testid, - cast(l.objectid as varchar(36)) + 'pH' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.pH is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.pO2 as result, - null as qualResult, - 'pO2' as testid, - cast(l.objectid as varchar(36)) + 'pO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.pO2 is not null) - -) t0 - -where t0.ts > ? - -) t \ No newline at end of file diff --git a/onprc_ehr/resources/etl/pending/Sur_AnesthesiaLogData.sql b/onprc_ehr/resources/etl/pending/Sur_AnesthesiaLogData.sql deleted file mode 100644 index ba4c53832..000000000 --- a/onprc_ehr/resources/etl/pending/Sur_AnesthesiaLogData.sql +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select - t.AnimalId, - t.date, - case - when t.timeString is null or t.timeString = '' or LEN(t.timeString) = 0 then t.date - when LEN(t.timeString) = 3 then convert(datetime, CONVERT(varchar(100), t.timeString, 111) + ' 0' + left(t.timeString, 1) + ':' + RIGHT(t.timeString, 2)) - else convert(datetime, CONVERT(varchar(100), t.date, 111) + ' ' + left(t.timeString, 2) + ':' + RIGHT(t.timeString, 2)) - end as date, - - t.parentid, - t.runid, - t.result, - t.qualResult, - t.testid, - t.objectid - -from ( - -select - t0.AnimalID, - t0.Date, - ltrim(rtrim(replace(t0.time, '_', '0'))) as timeString, - t0.objectid, - t0.parentid, - t0.qualResult, - t0.result, - t0.runid, - t0.testid - from ( - -select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.DiastolicBP as result, - null as qualResult, - 'DiastolicBP' as testid, - cast(l.objectid as varchar(36)) + 'DiastolicBP' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.DiastolicBP is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.EtCO2 as result, - null as qualResult, - 'EtCO2' as testid, - cast(l.objectid as varchar(36)) + 'EtCO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.EtCO2 is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.HeartRate as result, - null as qualResult, - 'HeartRate' as testid, - cast(l.objectid as varchar(36)) + 'HeartRate' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.HeartRate is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.IBPMap as result, - null as qualResult, - 'IBPMap' as testid, - cast(l.objectid as varchar(36)) + 'IBPMap' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.IBPMap is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - null as result, - l.IBPSD as qualResult, - 'IBPSD' as testid, - cast(l.objectid as varchar(36)) + 'IBPSD' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.IBPSD is not null and l.IBPSD != '') - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.N2OFlow as result, - null as qualResult, - 'N2OFlow' as testid, - cast(l.objectid as varchar(36)) + 'N2OFlow' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.N2OFlow is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.NIBPMap as result, - null as qualResult, - 'NIBPMap' as testid, - cast(l.objectid as varchar(36)) + 'NIBPMap' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.NIBPMap is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.O2Flow as result, - null as qualResult, - 'O2Flow' as testid, - cast(l.objectid as varchar(36)) + 'O2Flow' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.O2Flow is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.RespirationRate as result, - null as qualResult, - 'RespirationRate' as testid, - cast(l.objectid as varchar(36)) + 'RespirationRate' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.RespirationRate is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.SpO2 as result, - null as qualResult, - 'SpO2' as testid, - cast(l.objectid as varchar(36)) + 'SpO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.SpO2 is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.SystolicBP as result, - null as qualResult, - 'SystolicBP' as testid, - cast(l.objectid as varchar(36)) + 'SystolicBP' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.SystolicBP is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.Temperature as result, - null as qualResult, - 'Temperature' as testid, - cast(l.objectid as varchar(36)) + 'Temperature' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.Temperature is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.Vaporizer as result, - null as qualResult, - 'Vaporizer' as testid, - cast(l.objectid as varchar(36)) + 'Vaporizer' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.Vaporizer is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.pCO2 as result, - null as qualResult, - 'pCO2' as testid, - cast(l.objectid as varchar(36)) + 'pCO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.pCO2 is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.pH as result, - null as qualResult, - 'pH' as testid, - cast(l.objectid as varchar(36)) + 'pH' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.pH is not null) - - UNION ALL - - select - g.AnimalID, - g.Date, - l.Time, - g.objectid as parentid, - h.objectid as runid, - - l.pO2 as result, - null as qualResult, - 'pO2' as testid, - cast(l.objectid as varchar(36)) + 'pO2' as objectid, - l.ts - - from Sur_AnesthesiaLogData l - left join Sur_General g on (l.SurgeryID = g.SurgeryID) - left join Sur_AnesthesiaLogHeader h on (h.SurgeryID = g.SurgeryID) - WHERE (l.pO2 is not null) - -) t0 - -where t0.ts > ? - -) t \ No newline at end of file diff --git a/onprc_ehr/resources/etl/pending/Sur_implants.sql b/onprc_ehr/resources/etl/pending/Sur_implants.sql deleted file mode 100644 index d5f1ee6d6..000000000 --- a/onprc_ehr/resources/etl/pending/Sur_implants.sql +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select - v.AnimalID, - v.date, - v.SequenceNo, - v.implantcount, - v.size as sizeInt, - s1.Value as size, - v.type as typeInt, - s2.Value as type, - v.site as siteInt, - s3.Value as site, - v.action as actionInt, - s4.Value as action, - v.chargecode as charcodeCodeInt, - s5.Value as chargeCode, - v.surgeon, - v.comments, - v.objectid - -from Sur_Implants v -LEFT JOIN Sys_parameters s1 ON (s1.Field = 'ImplantSize' AND s1.Flag = v.size) -LEFT JOIN Sys_parameters s2 ON (s2.Field = 'ImplantType' AND s2.Flag = v.type) -LEFT JOIN Sys_parameters s3 ON (s3.Field = 'ImplantSite' AND s3.Flag = v.site) -LEFT JOIN Sys_parameters s4 ON (s4.Field = 'ImplantAction' AND s4.Flag = v.action) -LEFT JOIN Sys_parameters s5 ON (s5.Field = 'SurgeryChargeCode' AND s5.Flag = v.chargecode) - - \ No newline at end of file diff --git a/onprc_ehr/resources/etl/pending/accounts.sql b/onprc_ehr/resources/etl/pending/accounts.sql deleted file mode 100644 index b6fad08d7..000000000 --- a/onprc_ehr/resources/etl/pending/accounts.sql +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT -p.ohsuaccountnumber as account, -MAX(CONVERT(varchar(38), p.objectid)) as objectid, - -count(*) as total - -FROM Ref_ProjectAccounts p - -WHERE p.datedisabled is null and datalength(p.OHSUAccountNumber) > 0 -and p.OHSUAccountNumber != ' ' -and p.OHSUAccountNumber != '0' -and p.OHSUAccountNumber != '00000000000' -and p.OHSUAccountNumber NOT LIKE '111%' - -group by p.ohsuaccountnumber - -having MAX(ts) > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/pending/cagehistory.sql b/onprc_ehr/resources/etl/pending/cagehistory.sql deleted file mode 100644 index 958219c6d..000000000 --- a/onprc_ehr/resources/etl/pending/cagehistory.sql +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -select - t.Cageid, - t.Location, - t.Row, - t.Cage, - t.CagetypeID, - t.DividerType, - t.maxDifferent, - t.datestarted, - CASE - WHEN maxDifferent IS NULL THEN (select min(datestarted) from Ref_RowCageHistory r2 WHERE r2.DateStarted < t.DateStarted and r2.Cageid = t.Cageid and r2.CagetypeID = t.CagetypeID and r2.DividerType = t.DividerType and r2.DateStarted >= '2012-12-31') - ELSE maxDifferent - END as StartDate ---max(t.datestarted) as datestarted - -from ( - - select - r.Cageid, - l.Location, - rc.Row, - rc.Cage, - r.CageTypeId, - r.dividertype, - r.datestarted, ---find the last date this cage did not have this configuration - (select max(datestarted) from Ref_RowCageHistory r2 WHERE r2.DateStarted < r.DateStarted and r2.Cageid = r.Cageid and r2.CagetypeID != r.CagetypeID and r2.DividerType != r.DividerType and r2.DateStarted >= '2012-12-31') as maxDifferent - - from Ref_RowCageHistory r - left join Ref_RowCage rc on (r.Cageid = rc.CageID) - left join Ref_Location l on (rc.LocationID = l.LocationId) - where r.DateStarted > '2013-01-01' - - ) t - ---group by Cageid, CagetypeID, DividerType, coalesce(t.startdate, t.datestarted) - -order by Location, row, Cage, DateStarted desc - - diff --git a/onprc_ehr/resources/etl/pending/sur_vessels.sql b/onprc_ehr/resources/etl/pending/sur_vessels.sql deleted file mode 100644 index c2cae58e1..000000000 --- a/onprc_ehr/resources/etl/pending/sur_vessels.sql +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - g.AnimalID, - g.Date, - v.Vessel as code, - s.Description as codeMeaning, - v.Action as actionInt, - s1.Value as action, - v.Notes as remark, - v.objectid - -from Sur_vessels v -LEFT JOIN Sur_General g ON (v.SurgeryID = g.SurgeryID) -LEFT JOIN Sys_parameters s1 ON (s1.Field = 'VesselAction' AND s1.Flag = v.Action) -LEFT JOIN Sys_parameters s2 ON (s2.Field = 'VesselNotes' AND s2.Flag = v.Notes) -left join ref_snomed s ON (s.SnomedCode = v.Vessel) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/pending/tissue_recipients.sql b/onprc_ehr/resources/etl/pending/tissue_recipients.sql deleted file mode 100644 index 9a891d369..000000000 --- a/onprc_ehr/resources/etl/pending/tissue_recipients.sql +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -insert into labkey.onprc_ehr.tissue_recipients (firstName, lastName, institution, title, affiliation, address, city, state, country, zip, phoneNumber, emailAddress, - shipAddress, shipCity, shipState, shipCountry, shipZip, dateCreated, dateDisabled, investigatorId, objectid, container, createdby, created, modifiedby, modified) - select - rt.firstName, - rt.lastName, - rt.institution, - rt.title, ---rt.affiliation, - s1.Value as affiliation, - rt.address, - rt.city, - rt.state, - rt.country, - rt.zip, - rt.phoneNumber, - - null as emailAddress, - - rt.shipAddress, - rt.shipCity, - rt.shipState, - rt.shipCountry, - rt.shipZip, - - rt.establishdate as dateCreated, - rt.InactiveDate as dateDisabled, - - (SELECT i.rowid from labkey.onprc_ehr.investigators i WHERE i.objectid = ri.objectid) as investigatorId, - - rt.objectid, - (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC') as container, - (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as createdby, - CURRENT_TIMESTAMP as created, - (SELECT userid from labkey.core.principals WHERE Name = 'onprcitsupport@ohsu.edu') as modifiedby, - CURRENT_TIMESTAMP as modified - from Ref_TissueRecipients rt - left join Ref_Investigator ri on (rt.InvestigatorID = ri.InvestigatorID) - LEFT JOIN Sys_Parameters s1 ON (field = 'TissueAffiliation' and Flag = affiliation) \ No newline at end of file diff --git a/onprc_ehr/resources/etl/static/splitter.sql b/onprc_ehr/resources/etl/static/splitter.sql deleted file mode 100644 index f9892ee6f..000000000 --- a/onprc_ehr/resources/etl/static/splitter.sql +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -If Exists (SELECT * FROM sysobjects WHERE id = object_id('fn_splitter') and type = 'TF') - DROP FUNCTION fn_splitter -GO -CREATE FUNCTION dbo.fn_splitter(@text nvarchar(max), @separator nvarchar(100)) -RETURNS @result TABLE (i int, value nvarchar(max)) -AS -BEGIN - DECLARE @i int - DECLARE @offset int - SET @i = 0 - - WHILE @text IS NOT NULL - BEGIN - SET @i = @i + 1 - SET @offset = charindex(@separator, @text) - INSERT @result SELECT @i, CASE WHEN @offset > 0 THEN LEFT(@text, @offset - 1) ELSE @text END - SET @text = CASE WHEN @offset > 0 THEN SUBSTRING(@text, @offset + LEN(@separator), LEN(@text)) END - END - RETURN -END \ No newline at end of file diff --git a/onprc_ehr/resources/etl/study/Blood Draws.sql b/onprc_ehr/resources/etl/study/Blood Draws.sql deleted file mode 100644 index 8d92d3fae..000000000 --- a/onprc_ehr/resources/etl/study/Blood Draws.sql +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(afb.AnimalID as nvarchar(4000)) as Id, - Date as Date, - ref1.projectId as project, - CASE - WHEN bd.NoChargeFlag = 1 THEN 'No Charge' - ELSE null - END as chargeType, - - Amount as quantity, - DrawCount as needlesticks, - --- Investigator as Investigator , ----- Ref_Investigator(InvestigatorID) --- Ref.LastName as LastName, --- IDKey as IDKey, - - s1.Value as Reason, - --Reason as ReasonInt, - - afb.objectid, - - --blood data - --bd.BloodIDKey as BloodIDkey, - - bd.InvestigatorId as InvestigatorId, ----- Ref_Investigator(InvestigatorID) - ref.LastName + ', ' + ref.FirstName as requestor, - bd.NoChargeFlag as NoChargeFlag, ------When Not to be billed transaction Flag = 1, When it is to be billed Flag = 0 - bd.BloodDrawFlag as BloodDrawFlag ------When Blood Draw transaction Flag = 1, When injections Flag = 0 - - -From Af_Blood Afb -LEFT JOIN Sys_Parameters s1 ON (Afb.Reason = s1.Flag And s1.Field = 'BloodReason') -LEFT JOIN Ref_Investigator ref ON (Afb.Investigator = ref.InvestigatorID) - -LEFT JOIN Af_BloodData bd ON (bd.BloodIDKey = afb.IDKey) -LEFT JOIN Ref_Projectsiacuc ref1 ON (ref1.ProjectID = bd.ProjectId) -LEFT JOIN Ref_Investigator ref2 ON (ref2.InvestigatorId = bd.InvestigatorId) - -WHERE (afb.ts > ? or bd.ts > ?) diff --git a/onprc_ehr/resources/etl/study/Clinical Encounters.sql b/onprc_ehr/resources/etl/study/Clinical Encounters.sql deleted file mode 100644 index 614655d3f..000000000 --- a/onprc_ehr/resources/etl/study/Clinical Encounters.sql +++ /dev/null @@ -1,481 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - --- Select --- cast(AnimalID as nvarchar(4000)) as Id, --- Date, --- null as enddate, --- 'Biopsy' as type, --- cast(BiopsyYear as nvarchar(4000)) + BiopsyFlag + BiopsyCode as caseno, --- null as caseid, --- --- case --- WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN --- 'Unassigned' --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN --- rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN --- rt.LastName + ', ' + rt.FirstName --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN --- rt.LastName + ' (' + rt.Initials + ')' --- WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN --- null --- else --- rt.Initials --- END as performedBy, --- null as procedureId, --- --- CAST(pat.objectid as varchar(38)) as objectid, --- null as chargetype, --- null as project, --- null as remark --- --- From Path_Biopsy Pat --- left join Ref_Technicians Rt on (Pat.Pathologist = Rt.ID) --- left join Sys_Parameters s3 on (s3.flag = Rt.Deptcode And s3.Field = 'Departmentcode') --- left join Ref_Technicians Rt2 on (Pat.Prosector1 = Rt2.ID) --- left join Sys_Parameters s4 on (Rt2.Deptcode = s4.Flag And s4.Field = 'DepartmentCode') --- left join Ref_Technicians Rt3 on (Pat.Prosector2 = Rt3.ID) --- left join Sys_Parameters s5 on (Rt3.Deptcode = s5.Flag And s5.Field = 'DepartmentCode') --- left join Ref_Technicians Rt4 on (Pat.Prosector3 = Rt4.ID) --- left join Sys_Parameters s6 on (Rt4.Deptcode = s6.Flag And s6.Field = 'DepartmentCode') --- --- WHERE Pat.ts > ? --- --- UNION ALL - --- Select --- cast(PTT.AnimalID as nvarchar(4000)) as Id, --- PTT.Date as Date , --- null as enddate, --- 'Necropsy' as type, --- cast(PTT.PathYear as nvarchar(4000)) + PTT.PathFlag + PTT.PathCode as caseno, --- null as caseid, --- --- --the pathologist --- case --- WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN --- 'Unassigned' --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN --- rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN --- rt.LastName + ', ' + rt.FirstName --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN --- rt.LastName + ' (' + rt.Initials + ')' --- WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN --- null --- else --- rt.Initials --- END as performedBy, --- null as procedureId, --- --- CAST(PTT.objectid as varchar(38)) as objectid, --- null as chargetype, --- null as project, --- null as remark --- --- From Path_Autopsy PTT --- left join Sys_Parameters s1 on (PTT.CauseofDeath = s1.flag And s1.Field = 'Deathcause') --- left join Sys_Parameters s2 on (PTT.Status = s2.flag And s2.field = 'AutopsyStatus') --- left join Ref_Technicians Rt on (PTT.Pathologist = Rt.ID) --- left join Sys_Parameters s3 on (s3.flag = Rt.Deptcode And s3.Field = 'Departmentcode') --- left join Ref_Technicians Rt2 on (PTT.Prosector1 = Rt2.ID) --- left join Sys_Parameters s4 on (Rt2.Deptcode = s4.Flag And s4.Field = 'DepartmentCode') --- left join Ref_Technicians Rt3 on (PTT.Prosector2 = Rt3.ID) --- left join Sys_Parameters s5 on (Rt3.Deptcode = s5.Flag And s5.Field = 'DepartmentCode') --- left join Ref_Technicians Rt4 on (PTT.Prosector3 = Rt4.ID) --- left join Sys_Parameters s6 on (Rt4.Deptcode = s6.Flag And s6.Field = 'DepartmentCode') --- WHERE ptt.ts > ? --- --- UNION ALL - ---surgeries -Select - cast(sg.AnimalID as nvarchar(4000)) as Id, - sg.Date as Date , - (SELECT - CASE - when (l.time = 'NULL' or l.time is null or l.time = '' or l.time = 0) then null - --when LEN(l.time) = 3 then convert(datetime, CONVERT(varchar(100), sg.date, 111) + ' 0' + left(l.time, 1) + ':' + RIGHT(l.time, 2)) - when l.time = '0094' then null - when l.time = '2400' OR l.time = '0000' then convert(datetime, CONVERT(varchar(100), sg.date, 111) + ' ' + '00:00') - when LEN(l.time) = 3 then null - when LEN(l.time) = 4 and substring(l.time, 1, 2) < 60 then convert(datetime, CONVERT(varchar(100), sg.date, 111) + ' ' + left(l.time, 2) + ':' + RIGHT(l.time, 2)) - else null - end as enddate - FROM (select MAX(l.Time) as time FROM ( - select l.surgeryid, max(ltrim(rtrim(replace(l.time, '_', '0')))) as time - FROM Sur_AnesthesiaLogData l - WHERE l.time is not null AND l.time != '' AND l.Time not like '%-%' AND l.Time not like '^_%' AND l.Time != '0' AND l.Time != '00' AND l.Time != '000' - GROUP BY l.SurgeryID) l - WHERE l.SurgeryID = sg.SurgeryID) l - ) as enddate, - 'Surgery' as type, - null as caseno, - c.objectid as caseid, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' OR rt.lastname = 'none' THEN - null - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - else - rt.Initials - END as performedBy, - (SELECT rowid from labkey.ehr_lookups.procedures p WHERE p.category = 'Surgery' AND p.name = r.procedureName) as procedureid, - - cast(sg.objectid as varchar(38)) as objectid, - CASE - WHEN s4.value = 'Surgery Staff' THEN 'DCM: Surgery Services' - WHEN s4.value = 'No Surgery Staff' THEN 'Research Staff' - WHEN s4.value = 'No Charge' THEN 'No Charge' - ELSE ('ERROR: ' + s4.value) - END as chargetype, - coalesce(ibs.projectId, afc.project) as project, - null as remark - -From Sur_General sg -LEFT JOIN Ref_SurgProcedure r on (sg.procedureid = r.procedureid) -left join Ref_Technicians Rt on (sg.Surgeon = Rt.ID) -left join Sys_Parameters s3 on (s3.flag = Rt.Deptcode And s3.Field = 'Departmentcode') -left join Sys_Parameters s4 on (s4.flag = sg.ChargeCode And s4.Field = 'SurgeryChargeCode') -left join ( - select c.AnimalID, max(ts) as ts, count(c.CaseID) as count, max(CAST(c.objectid AS varchar(36))) as objectid, c.OpenDate as date - from af_case c - WHERE c.GroupCode = 2 - GROUP BY c.AnimalID, c.OpenDate -) c ON (c.AnimalID = sg.AnimalID AND c.date = sg.date) - -LEFT JOIN ( -Select - t1.surgeryId, - max(ibs2.ProjectID) as projectId, - max(ibs2.ts) as ts -from ( - SELECT - sg1.SurgeryID, - MAX(sg1.AnimalID) as AnimalID, - MAX(sg1.date) as date, - MAX(sg1.procedureId) as procedureId, - max(ibs1.InvoiceNumber) as maxNumber - From Sur_General sg1 - left join AF_ChargesIBS ibs1 on (convert(varchar(10),sg1.AnimalID) = ibs1.TransactionDescription and sg1.Date = ibs1.TransactionDate and convert(varchar(10), sg1.ProcedureID) = ibs1.ItemCode) - group by sg1.SurgeryID - ) t1 - left join AF_ChargesIBS ibs2 on (t1.maxNumber = ibs2.InvoiceNumber And convert(varchar(10),t1.AnimalID) = ibs2.TransactionDescription and t1.Date = ibs2.TransactionDate and convert(varchar(10), t1.ProcedureID) = ibs2.ItemCode) - group by t1.SurgeryID -) ibs ON (ibs.surgeryId = sg.surgeryId) - -LEFT JOIN ( - SELECT - sg1.SurgeryID, - MAX(sg1.AnimalID) as AnimalID, - max(afc.ts) as maxTs, - --MAX(sg1.date) as date, - --MAX(sg1.procedureId) as procedureId, - max(afc.ProjectID) as project - --COUNT(distinct afc.projectID) as total - - From Sur_General sg1 - left join AF_Charges afc on (sg1.AnimalID = afc.AnimalID and sg1.Date = afc.ChargeDate and sg1.ProcedureID = afc.ProcedureID) - group by sg1.SurgeryID -) afc ON (afc.surgeryId = sg.surgeryId) - -WHERE (sg.ts > ? or c.ts > ? or ibs.ts > ? or afc.maxTs > ?) - -UNION ALL - ---diagnosis -Select - cast(cln.AnimalId as varchar(4000)) as Id, - cln.Date , - null as enddate, - 'Diagnosis' as type, - null as caseno, - c.objectid as caseId, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - null as procedureId, - - cast(cln.objectid as varchar(38)) as objectid, - null as chargetype, - null as project, - null as remark - -FROM Cln_Dx cln - left join Ref_Technicians rt on (cln.Technician = rt.ID) - left join Sys_parameters s4 on (s4.Field = 'DepartmentCode' And s4.Flag = rt.DeptCode) - left join Af_Case c ON (c.CaseID = cln.CaseID) - -WHERE cln.ts > ? - -UNION ALL - ---implant procedures -Select - cast(cln.AnimalId as varchar(4000)) as Id, - cln.Date , - null as enddate, - 'Surgery' as type, - null as caseno, - NULL as caseId, - - max(case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END) as performedBy, - (select rowid from labkey.ehr_lookups.procedures WHERE name = 'Hormone Implant/Removal' and active = 1) as procedureId, - - max(cast(cln.objectid as varchar(36))) as objectid, - CASE - WHEN max(s5.Value) = 'Surgery Staff' THEN 'DCM: Surgery Services' - WHEN max(s5.Value) = 'No Surgery Staff' THEN 'Research Staff' - WHEN max(s5.Value) = 'No Charge' THEN 'No Charge' - ELSE ('ERROR: ' + max(s4.value)) - END as chargetype, - max(proj.ProjectId) as project, - null as remark --note: remark being entered into encounter_summaries - -FROM sur_implants cln - left join Ref_Technicians rt on (cln.Surgeon = rt.ID) - LEFT JOIN Sys_parameters s1 ON (s1.Field = 'ImplantSize' AND s1.Flag = cln.size) - LEFT JOIN Sys_parameters s2 ON (s2.Field = 'ImplantType' AND s2.Flag = cln.type) - LEFT JOIN Sys_parameters s3 ON (s3.Field = 'ImplantSite' AND s3.Flag = cln.site) - LEFT JOIN Sys_parameters s4 ON (s4.Field = 'ImplantAction' AND s4.Flag = cln.action) - LEFT JOIN Sys_parameters s5 ON (s5.Field = 'SurgeryChargeCode' AND s5.Flag = cln.chargecode) - - left join Sys_parameters s6 on (s6.Field = 'DepartmentCode' And s6.Flag = rt.DeptCode) - LEFT JOIN ( - SELECT - i.IDKey, - --a.AnimalID, - --a.ChargeDate, - max(a.ProjectID) as ProjectID, - max(a.ts) as maxChargeTs - - FROM Sur_Implants i - left join Af_Charges a ON (i.AnimalID = a.AnimalID AND i.Date = a.ChargeDate) - left join Ref_FeesSurgical fs on (a.ProcedureID = fs.ProcedureID and fs.DateDisabled is null) - left join Ref_SurgProcedure r on (fs.ProcedureID = r.ProcedureID) - where r.ProcedureName like '%Hormone%' and a.AccountNo is null - and a.ChargeDate > '2013-10-01' - GROUP BY i.IdKey - ) proj ON (cln.IdKey = proj.IdKey) - -GROUP BY cln.AnimalID, cln.Date -HAVING (MAX(cln.ts) > ? OR max(proj.maxChargeTs) > ?) - -UNION ALL - -SELECT - cast(dx.AnimalID as nvarchar(4000)) as Id, - dx.date, - null as enddate, - 'Procedure' as type, - null as caseno, - null as caseid, - null as performedBy, - (SELECT rowid FROM labkey.ehr_lookups.procedures WHERE category = 'Procedure' AND name = CASE - WHEN s2.value = 'F-79020' THEN 'Aspiration gastric contents' - WHEN s2.value = 'P-YY841' THEN 'Bottle feed' - WHEN s2.value = 'P-Y3060' THEN 'Cage change' - WHEN s2.value = 'P-1210C' THEN 'Chorio-Decidual Infusion' - WHEN s2.value = 'F-Y0215' THEN 'Collar Check' - WHEN s2.value = 'F-Y0225' THEN 'Collar Placement' - WHEN s2.value = 'F-Y0220' THEN 'Collar Rmvl' - WHEN s2.value = 'P-X1550' THEN 'CT Scan' - WHEN s2.value = 'P-X7200' THEN 'DEXA Scan' - WHEN s2.value = 'P-17800' THEN 'Dressing, apply' - WHEN s2.value = 'P-X0820' THEN 'Dx Rads Bilateral INJ, w/Cont Media' - WHEN s2.value = 'P-X1000' THEN 'Dx Rads INJ w/Cont Media' - WHEN s2.value = 'P-X0650' THEN 'Dx Rads PO w/Cont Media' - WHEN s2.value = 'P-X0900' THEN 'Dx Rads Positive INJ, w/Cont Media' - WHEN s2.value = 'P-YY500' THEN 'Dye marking' - WHEN s2.value = 'P-95700' THEN 'Ejaculation' - WHEN s2.value = 'P-40370' THEN 'Glucose Tolerance Test' - WHEN s2.value = 'P-yy780' THEN 'HbA1C test' - WHEN s2.value = 'P-Y3230' THEN 'Heelstick lancet' - WHEN s2.value = 'P-X9770' THEN 'ID monitor of fetus' - WHEN s2.value = 'P-40375' THEN 'Insulin Tolerance Test' - WHEN s2.value = 'P-X9770' THEN 'Intrapartum Doppler monitor of fetus' - WHEN s2.value = 'P-12550' THEN 'Intubation' - WHEN s2.value = 'P-1920X' THEN 'Jacket, Apply' - WHEN s2.value = 'P-1927X' THEN 'Jacket, Maintain' - WHEN s2.value = 'P-1924X' THEN 'Jacket, Remove' - WHEN s2.value = 'P-71630' THEN 'Monitoring Temperature' - WHEN s2.value = 'p-x5200' THEN 'MRI' - WHEN s2.value = 'P-YY838' THEN 'Nasal (only) swab' - WHEN s2.value = 'P-YY843' THEN 'Nasal gastric swab' - WHEN s2.value = 'P-YY835' THEN 'Nasal/gastric gavage' - WHEN s2.value = 'P-02360' THEN 'Palpation' - WHEN s2.value = 'P-02400' THEN 'Palpation, bimanual' - WHEN s2.value = 'P-00110' THEN 'Procedure for Staff Training' - WHEN s2.value = 'P-10850' THEN 'Puncture & Drainage' - WHEN s2.value = 'P-Y3192' THEN 'Remove animal appendage from cage' - WHEN s2.value = '' THEN 'Sedation' - WHEN s2.value = 'P-Y3130' THEN 'Sex determination' - WHEN s2.value = 'P-2037X' THEN 'Spec Clltn: Urine cystocentesis' - WHEN s2.value = 'P-1926x' THEN 'Swivel-Tether change' - WHEN s2.value = 'P-12090' THEN 'Tattoo' - WHEN s2.value = 'P-Y3100' THEN 'Transporting' - WHEN s2.value = 'P-X9751' THEN 'Ultrasonic guidance of amniocentesis' - WHEN s2.value = 'P-X9750' THEN 'Ultrasound' - WHEN s2.value = 'P-2035X' THEN 'Vag Swab Cltn(by Lab)' - WHEN s2.value = 'P-YY787' THEN 'Vag tampon insertion, initial' - WHEN s2.value = 'P-YY790' THEN 'Vaginal ring, insertion' - WHEN s2.value = 'P-YY791' THEN 'Vaginal ring, removal' - WHEN s2.value = 'P-YY789' THEN 'Vaginal tampon, final removal' - WHEN s2.value = 'P-YY788' THEN 'Vaginal tampon, maintenance' - WHEN s2.value = 'P-Y3110' THEN 'Worming' - WHEN s2.value = 'P-02314' THEN 'Physical Exam Complete' --annual exam - WHEN s2.value = 'P-02310' THEN 'Physical Exam Complete' --PE complete - END) as procedureId, - - cast(s.objectid as varchar(38)) + '-' + cast(s2.i as varchar(100)) + '-' + cast(s2.value as nvarchar(100)) as objectid, - null as chargetype, - null as project, - null as remark - -FROM Cln_DxSnomed s - left join cln_dx dx ON (dx.DiagnosisID = s.DiagnosisID) - left join af_case c ON (dx.caseid = c.caseid) - cross apply dbo.fn_splitter(s.snomed, ',') s2 -where s2.value is not null and s2.value IN ( - 'F-79020', - 'P-YY841', - 'P-Y3060', - 'P-1210C', - 'F-Y0215', - 'F-Y0225', - 'F-Y0220', - 'P-X1550', - 'P-X7200', - 'P-17800', - 'P-X0820', - 'P-X1000', - 'P-X0650', - 'P-X0900', - 'P-YY500', - 'P-95700', - 'P-40370', - 'P-yy780', - 'P-Y3230', - 'P-X9770', - 'P-40375', - 'P-X9770', - 'P-12550', - 'P-1920X', - 'P-1927X', - 'P-1924X', - 'P-71630', - 'p-x5200', - 'P-YY838', - 'P-YY843', - 'P-YY835', - 'P-02360', - 'P-02400', - 'P-00110', - 'P-10850', - 'P-Y3192', - 'P-Y3130', - 'P-2037X', - 'P-1926x', - 'P-12090', - 'P-Y3100', - 'P-X9751', - 'P-X9750', - 'P-2035X', - 'P-YY787', - 'P-YY790', - 'P-YY791', - 'P-YY789', - 'P-YY788', - 'P-Y3110', - 'P-02314', - 'P-02310' -) -and s.ts > ? - ---add TB tests -UNION ALL - -SELECT - cast(w.AnimalID as nvarchar(4000)) as Id, - w.date, - null as enddate, - 'Procedure' as type, - null as caseno, - null as caseid, - null as performedBy, - (SELECT rowid FROM labkey.ehr_lookups.procedures WHERE category = 'Procedure' AND name = 'TB Test Intradermal') as procedureid, - (cast(w.objectid as varchar(38)) + '_tb') as objectid, - null as chargetype, - null as project, - null as remark - -FROM af_weights w -where w.tbflag = 1 and w.ts > ? - -UNION ALL - -SELECT - cast(dx.AnimalID as nvarchar(4000)) as Id, - dx.date, - null as enddate, - 'Procedure' as type, - null as caseno, - null as caseid, - null as performedBy, - (SELECT rowid FROM labkey.ehr_lookups.procedures WHERE category = 'Procedure' AND name = 'TB Test Intradermal') as procedureid, - cast(sno.objectid as varchar(36)) as objectid, - null as chargetype, - null as project, - null as remark - -FROM Cln_DXSnomed sno - LEFT JOIN Cln_DX dx ON (sno.DiagnosisID = dx.DiagnosisID) - LEFT JOIN af_weights w2 ON (w2.AnimalId = dx.AnimalID AND w2.Date = dx.Date and w2.TBFlag = 1) - -WHERE sno.Snomed = 'P-54268' AND w2.AnimalId IS NULL and sno.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/study/Clinical Observations.sql b/onprc_ehr/resources/etl/study/Clinical Observations.sql deleted file mode 100644 index 1495bfdd5..000000000 --- a/onprc_ehr/resources/etl/study/Clinical Observations.sql +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - cast(AnimalID as nvarchar(4000)) as Id, - Date as Date, - 'N/A' as area, - 'Menses' as category, - 'M' as observation, - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' or rt.LastName = ' none' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - cast(bm.objectid as varchar(38)) as objectid - -FROM Brd_Menstruations bm - -LEFT JOIN Ref_Technicians rt ON (bm.Technician = rt.ID) -LEFT JOIN Sys_parameters s1 ON (s1.Field = 'DepartmentCode' and s1.Flag = rt.DeptCode) - -where bm.ts > ? - -UNION ALL - -SELECT - cast(dx.AnimalID as nvarchar(4000)) as Id, - dx.date, - 'N/A' as area, - CASE - WHEN s2.value ='F-YY002' THEN 'BCS' - WHEN s2.value ='F-YY003' THEN 'BCS' - WHEN s2.value ='F-YY004' THEN 'BCS' - WHEN s2.value ='F-YY005' THEN 'BCS' - WHEN s2.value ='F-YY006' THEN 'BCS' - WHEN s2.value ='F-Y3712' THEN 'Alopecia Score' - WHEN s2.value ='F-Y3714' THEN 'Alopecia Score' - WHEN s2.value ='F-Y3716' THEN 'Alopecia Score' - WHEN s2.value ='F-Y3718' THEN 'Alopecia Score' - WHEN s2.value ='F-Y3720' THEN 'Alopecia Score' - WHEN s2.value ='F-Y3722' THEN 'Alopecia Score' - END as category, - CASE - WHEN s2.value ='F-YY002' THEN '1' - WHEN s2.value ='F-YY003' THEN '2' - WHEN s2.value ='F-YY004' THEN '3' - WHEN s2.value ='F-YY005' THEN '4' - WHEN s2.value ='F-YY006' THEN '5' - WHEN s2.value ='F-Y3712' THEN '0' - WHEN s2.value ='F-Y3714' THEN '1' - WHEN s2.value ='F-Y3716' THEN '2' - WHEN s2.value ='F-Y3718' THEN '3' - WHEN s2.value ='F-Y3720' THEN '4' - WHEN s2.value ='F-Y3722' THEN '5' - END as observation, - null as performedby, - cast(s.objectid as varchar(38)) + '-' + cast(s2.i as varchar(100)) + '-' + cast(s2.value as nvarchar(100)) as objectid - -FROM Cln_DxSnomed s - left join cln_dx dx ON (dx.DiagnosisID = s.DiagnosisID) - left join af_case c ON (dx.caseid = c.caseid) - cross apply dbo.fn_splitter(s.snomed, ',') s2 -where s2.value is not null and s2.value IN ( - 'F-YY002', - 'F-YY003', - 'F-YY004', - 'F-YY005', - 'F-YY006', - 'F-Y3712', - 'F-Y3714', - 'F-Y3716', - 'F-Y3718', - 'F-Y3720', - 'F-Y3722' -) -and s.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/study/Clinical Remarks.sql b/onprc_ehr/resources/etl/study/Clinical Remarks.sql deleted file mode 100644 index 149e2b1dc..000000000 --- a/onprc_ehr/resources/etl/study/Clinical Remarks.sql +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT * FROM ( -SELECT - cast(dx.AnimalID as nvarchar(4000)) as Id, - dx.date, - c.objectid as caseid, - - REPLACE(REPLACE( - cast(coalesce(cln0.Remarks, '') as nvarchar(4000)) + - cast(coalesce(cln1.Remarks, '') as nvarchar(4000)) + - cast(coalesce(cln2.Remarks, '') as nvarchar(4000)) + - cast(coalesce(cln3.Remarks, '') as nvarchar(4000)) + - cast(coalesce(cln4.Remarks, '') as nvarchar(4000)) + - cast(coalesce(cln5.Remarks, '') as nvarchar(4000)) + - cast(coalesce(cln6.Remarks, '') as nvarchar(4000)) - , char(25), '<>'), Char(21), Char(39)) AS remark, - - coalesce(cln0.objectid, cln1.objectid, cln2.objectid, cln3.objectid) as objectid, - dx.objectid as parentid , - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - Case - When c.GroupCode = 1 Then 'Clinical' - When c.GroupCode = 2 Then 'Surgery' - When c.GroupCode = 3 Then 'Behavior' - When c.GroupCode = 4 Then 'Weight' - Else null - End AS Category - -FROM Cln_Dx dx -left join Af_Case c ON (dx.CaseID = c.CaseID) -left join Ref_Technicians rt on (dx.Technician = rt.ID) -left JOIN Cln_DxRemarks cln0 ON (dx.DiagnosisID = cln0.DiagnosisID AND cln0.SequenceNo = 0) -LEFT JOIN Cln_DxRemarks cln1 ON (dx.DiagnosisID = cln1.DiagnosisID AND cln1.SequenceNo = 1) -LEFT JOIN Cln_DxRemarks cln2 ON (dx.DiagnosisID = cln2.DiagnosisID AND cln2.SequenceNo = 2) -LEFT JOIN Cln_DxRemarks cln3 ON (dx.DiagnosisID = cln3.DiagnosisID AND cln3.SequenceNo = 3) -LEFT JOIN Cln_DxRemarks cln4 ON (dx.DiagnosisID = cln4.DiagnosisID AND cln4.SequenceNo = 4) -LEFT JOIN Cln_DxRemarks cln5 ON (dx.DiagnosisID = cln5.DiagnosisID AND cln5.SequenceNo = 5) -LEFT JOIN Cln_DxRemarks cln6 ON (dx.DiagnosisID = cln6.DiagnosisID AND cln6.SequenceNo = 6) - -WHERE dx.DiagnosisID IN (select diagnosisid from Cln_DxRemarks r WHERE r.ts > ?) -) t -WHERE t.remark is not null and t.remark != '' \ No newline at end of file diff --git a/onprc_ehr/resources/etl/study/Delivery.sql b/onprc_ehr/resources/etl/study/Delivery.sql deleted file mode 100644 index 6b74b6264..000000000 --- a/onprc_ehr/resources/etl/study/Delivery.sql +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(MotherID as nvarchar(4000)) as Id, - Date, - (SELECT rowid FROM labkey.ehr_lookups.lookups l WHERE l.set_name = 'DeliveryMode' and l.value = s1.value) as DeliveryType, - --DeliveryType as DeliveryType, - --s1.Value as DeliveryType, - - cast(InfantID as nvarchar(4000)) as Infant, - case when fatherId = 0 then null else cast(FatherID as nvarchar(4000)) end as Sire, - - cast(NaturalMother as nvarchar(4000)) as NaturalMother, - MultipleBirthsFlag , - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - Remarks as remark, - --IDKey, - - afd.objectid - --afd.ts as rowversion - -From Af_Delivery AfD -left join Sys_Parameters s1 on (Afd.DeliveryType = s1.Flag And s1.Field = 'DeliveryMode') -left join Ref_Technicians Rt on ( Rt.ID = AfD.Technician ) -left join Sys_Parameters s2 on ( s2.field = 'Departmentcode' And rt.Deptcode = s2.flag ) - -where afd.ts > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/study/Drug Administration.sql b/onprc_ehr/resources/etl/study/Drug Administration.sql deleted file mode 100644 index beb16add8..000000000 --- a/onprc_ehr/resources/etl/study/Drug Administration.sql +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ --- SELECT --- d.*, --- --add in projects --- coalesce( --- (SELECT CASE WHEN count(projectId) = 1 THEN max(projectId) ELSE null END as project FROM Af_ChargesIBS ibs WHERE ibs.IDKey = d.IDKey), --- (SELECT CASE WHEN count(projectId) = 1 THEN max(projectId) ELSE null END as project FROM AF_Assignments a WHERE a.animalid = d.animalid AND (d.date >= a.AssignDate AND d.Date <= a.ReleaseDate)) --- ) as project, --- --- coalesce( --- (SELECT max(ts) as ts FROM Af_ChargesIBS ibs WHERE ibs.IDKey = d.IDKey), --- (SELECT max(ts) as ts FROM AF_Assignments a WHERE a.animalid = d.animalid AND (d.date >= a.AssignDate AND d.Date <= a.ReleaseDate)) --- ) as projectTs --- --- FROM ( - --- -- TODO: deprecate? --- SELECT * FROM ( --- SELECT --- t.Id, --- DATEADD (DAY , i.value, t.date) as date, --- t.treatmentStartDate, --- t.enddate as treatmentEndDate, --- --t.duration, --- --i.value, --- t.code, --- t.meaning, --- t.remark, --- t.amount, --- t.amount_units, --- t.route, --- (cast(t.objectid as varchar(38)) + '_' + convert(varchar, t.date, 120)) as objectid, --- t.parentId, --- t.treatmentId, --- CASE WHEN t.treatmentid IS NULL THEN NULL ELSE DATEADD(DAY , i.value, t.date) END as timeordered, --- t.performedBy, --- t.category, --- null as caseid --- --- FROM ( --- SELECT --- t1.*, --- CASE --- WHEN t1.enddate2 is null THEN t1.alternateEnd --- WHEN t1.alternateEnd is null then t1.enddate2 --- WHEN t1.alternateEnd < t1.enddate2 THEN t1.alternateEnd --- ELSE t1.enddate2 --- END as enddate, --- CASE --- WHEN (t1.enddate2 is null AND t1.alternateEnd is null) THEN null --- WHEN t1.enddate2 is null THEN DateDiff(d, cast(t1.date as date), cast(t1.alternateEnd as date)) --- WHEN t1.alternateEnd is null then DateDiff(d, cast(t1.date as date), cast(t1.enddate2 as date)) --- WHEN t1.alternateEnd < t1.enddate2 THEN DateDiff(d, cast(t1.date as date), cast(t1.alternateEnd as date)) --- ELSE DateDiff(d, t1.date, t1.enddate2) --- END + 1 as duration --- FROM ( --- SELECT --- CASE --- WHEN enddate IS NULL THEN cast(DATEADD(minute, -1, DATEADD(day, 1+CASE WHEN duration = 0 THEN 1 ELSE duration END, cast(cast(date as date) AS datetime))) as datetime) --- ELSE coalesce(EndDate, q.deathdate, q.departuredate) --- END as enddate2, --- coalesce(q.deathdate, q.departuredate) as alternateEnd, --- --- cast(m.AnimalId as nvarchar(4000)) as Id, --- m.date AS treatmentStartDate, --- --- case --- when cln.MedicationTime is null or cln.MedicationTime = '' or LEN(medicationtime) = 0 then m.date --- when LEN(medicationtime) = 3 then convert(datetime, CONVERT(varchar(100), m.date, 111) + ' 0' + left(cln.MedicationTime, 1) + ':' + RIGHT(cln.medicationtime, 2)) --- else convert(datetime, CONVERT(varchar(100), m.date, 111) + ' ' + left(cln.MedicationTime, 2) + ':' + RIGHT(cln.medicationtime, 2)) --- end as date, --- --- Medication as code, --- sno.Description as meaning, --- --- null as remark, --- Dose as amount, --- CASE --- WHEN s6.value = 'Surgery' THEN 'Surgical' --- WHEN ss.code is not null THEN 'Diet' --- ELSE 'Clinical' --- END as category, --- --- s2.Value as amount_units, --- s3.Value as route, --- cast(coalesce(cln.objectid, m.objectid) as varchar(38)) as objectid, --- null as parentId, --- m.objectId as treatmentId, --- --- case --- WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN --- 'Unassigned' --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN --- rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' --- WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN --- rt.LastName + ', ' + rt.FirstName --- WHEN datalength(LastName) > 0 AND datalength(rt.Initials) > 0 THEN --- rt.LastName + ' (' + rt.Initials + ')' --- WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN --- null --- else --- rt.Initials --- END as performedBy, --- tf.intervalindays --- --- FROM Cln_Medications m --- left join Cln_MedicationTimes cln on (m.SearchKey = cln.SearchKey) --- left join ref_snomed sno on (sno.SnomedCode = m.Medication) --- left join Sys_parameters s2 on (s2.Field = 'MedicationUnits' and s2.Flag = m.Units) --- left join Sys_parameters s3 on (s3.Field = 'MedicationRoute' and s3.Flag = m.Route) --- left join Ref_Technicians rt ON (rt.ID = m.Technician) --- left join Sys_parameters s6 on (s6.Field = 'DepartmentCode' and s6.Flag = rt.DeptCode) --- --- left join Sys_parameters s4 on (s4.Field = 'MedicationFrequency' and s4.Flag = Frequency) --- left join labkey.ehr_lookups.treatment_frequency tf ON (tf.meaning = s4.value) --- left join Af_Qrf q on (q.animalid = m.animalid) --- left join labkey.ehr_lookups.snomed_subset_codes ss ON (ss.code = m.Medication AND ss.primaryCategory = 'Diet' and ss.container = (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC')) --- --- where m.AnimalId is not null --- and (cln.ts > ? or m.ts > ? or q.ts > ?) --- ) t1 --- --- ) t --- --- LEFT JOIN labkey.ldk.integers i on (i.value < t.Duration AND ((i.value + 1) % t.intervalindays = 0)) --- --- ) t2 --- --- WHERE t2.date >= t2.treatmentStartDate and t2.date <= t2.treatmentEndDate --- --- UNION ALL - -SELECT - cast(g.AnimalId as nvarchar(4000)) as Id, - g.Date, - null as treatmentStartDate, - null as treatmentEndDate, - --null as datetime, - - AnesthesiaGas as code, - sno.Description as meaning, - - 'IV Location: ' + coalesce(s1.Value, '') + '\n' + - 'IV Side: ' + coalesce(s2.Value, '') + '\n' + - 'IV Tube Size: ' + coalesce(s3.Value, '') + '\n' - as remark, --- ,[Ventilator] --boolean - - null as amount, - null as amount_Units, - 'IV' as Route, - cast(h.objectid as varchar(38)) as objectid, - g.objectid as parentId, - null as treatmentId, - null as timeordered, - - null as performedby, - 'Anesthesia' as category, - c.objectid as caseid - -FROM Sur_AnesthesiaLogHeader h -LEFT JOIN sur_general g ON (g.surgeryid = h.surgeryid) -left join ref_snomed sno on (sno.SnomedCode = h.AnesthesiaGas) -LEFT JOIN Sys_parameters s1 ON (s1.Field = 'IVLocation' AND s1.Flag = h.IVLocation) -LEFT JOIN Sys_parameters s2 ON (s1.Field = 'IVSide' AND s2.Flag = h.IVSide) -LEFT JOIN Sys_parameters s3 ON (s3.Field = 'GasTubeSize' AND s3.Flag = h.TubeSize) -left join ( - select c.AnimalID, max(ts) as ts, count(c.CaseID) as count, max(CAST(c.objectid AS varchar(36))) as objectid, c.OpenDate as date - from af_case c - WHERE c.GroupCode = 2 - GROUP BY c.AnimalID, c.OpenDate -) c ON (c.AnimalID = g.AnimalID AND c.date = g.date) - -WHERE h.ts > ? or g.ts > ? - -UNION ALL - -SELECT -cast(g.AnimalId as nvarchar(4000)) as Id, -g.Date, -null as treatmentStartDate, -null as treatmentEndDate, -Medication as code, -sno.Description as meaning, -null as remark, -Dose as amount, -s2.value as amount_units, -s3.value as Route, -cast(m.objectid as varchar(38)) as objectid, -g.objectid as parentid, -null as treatmentId, -null as timeordered, -null as performedby, -'Surgical' as category, -c.objectid as caseid - -FROM Sur_Medications m - left join Sur_General g on (g.SurgeryID = m.SurgeryID) - left join Ref_SnoMed sno on (sno.SnomedCode = m.Medication) - left join Sys_parameters s2 on (s2.Field = 'MedicationUnits' and s2.Flag = m.Units) - left join Sys_parameters s3 on (s3.Field = 'MedicationRoute' and s3.Flag = m.Route) - left join ( - select c.AnimalID, max(ts) as ts, count(c.CaseID) as count, max(CAST(c.objectid AS varchar(36))) as objectid, c.OpenDate as date - from af_case c - WHERE c.GroupCode = 2 - GROUP BY c.AnimalID, c.OpenDate - ) c ON (c.AnimalID = g.AnimalID AND c.date = g.date) - -WHERE m.ts > ? or g.ts > ? - --- --implant data --- UNION ALL --- --- SELECT --- cast(v.AnimalId as nvarchar(4000)) as Id, --- v.Date, --- null as treatmentStartDate, --- null as treatmentEndDate, --- null as code, --- null as meaning, --- v.comments as remark, --- v.implantcount as amount, --- null as amount_units, --- null as Route, --- cast(v.objectid as varchar(38)) as objectid, --- v.objectid as parentid, --- null as treatmentId, --- null as performedby, --- 'Surgical' as category, --- null as caseid --- --- --TODO: --- --s1.Value as size, --- --s2.Value as type, --- --s3.Value as site, --- --s4.Value as action, --- --- from Sur_Implants v --- LEFT JOIN Sys_parameters s1 ON (s1.Field = 'ImplantSize' AND s1.Flag = v.size) --- LEFT JOIN Sys_parameters s2 ON (s2.Field = 'ImplantType' AND s2.Flag = v.type) --- LEFT JOIN Sys_parameters s3 ON (s3.Field = 'ImplantSite' AND s3.Flag = v.site) --- LEFT JOIN Sys_parameters s4 ON (s4.Field = 'ImplantAction' AND s4.Flag = v.action) --- LEFT JOIN Sys_parameters s5 ON (s5.Field = 'SurgeryChargeCode' AND s5.Flag = v.chargecode) --- --- WHERE v.ts > ? - --- ) d --- --- WHERE d.projectTs > ? \ No newline at end of file diff --git a/onprc_ehr/resources/etl/study/Treatment Orders.sql b/onprc_ehr/resources/etl/study/Treatment Orders.sql deleted file mode 100644 index d9d869ee5..000000000 --- a/onprc_ehr/resources/etl/study/Treatment Orders.sql +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2012-2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -select -t.id, -t.date, -t.frequency, ---t.times, -CASE - WHEN t.enddate is null THEN t.alternateEnd - WHEN t.alternateEnd is null then t.enddate - WHEN t.alternateEnd < t.enddate THEN t.alternateEnd - ELSE t.enddate -END as enddate, -t.code, -t.snomedMeaning, -t.amount, -t.amount_units, -t.route, -t.Reason, -t.performedBy, -t.category, -REPLACE(t.Remark, Char(21), Char(39)) as remark, -t.objectid - - -from ( -SELECT - cast(cln.AnimalId as nvarchar(4000)) as Id, - Date, - Medication as code, - sno.Description as snomedMeaning, - Dose as amount, - - s2.Value as amount_units, - --Route as RouteInt , - s3.Value as Route, - --Frequency as FrequencyInt , - (select rowid FROM labkey.ehr_lookups.treatment_frequency tf WHERe tf.meaning = s4.value) as frequency, - - --Duration as Duration, - CASE - WHEN enddate IS NULL THEN cast(DATEADD(minute, -1, DATEADD(day, 1+CASE WHEN duration = 0 THEN 1 ELSE duration END, cast(cast(date as date) AS datetime))) as datetime) - ELSE coalesce(EndDate, q.deathdate, q.departuredate) - END as enddate, - coalesce(q.deathdate, q.departuredate) as alternateEnd, - - --Reason as ReasonInt , - s5.Value as Reason, - --(select labkey.core.GROUP_CONCAT_DS(mt.medicationtime, ',', 1) as time FROM Cln_MedicationTimes mt where cln.SearchKey=mt.SearchKey) as times, - CASE - WHEN s6.value = 'Surgery' THEN 'Surgical' - WHEN ss.code is not null THEN 'Clinical' - ELSE 'Clinical' - END as category, - - case - WHEN rt.LastName = 'Unassigned' or rt.FirstName = 'Unassigned' THEN - 'Unassigned' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ', ' + rt.FirstName + ' (' + rt.Initials + ')' - WHEN datalength(rt.LastName) > 0 AND datalength(rt.FirstName) > 0 THEN - rt.LastName + ', ' + rt.FirstName - WHEN datalength(rt.LastName) > 0 AND datalength(rt.Initials) > 0 THEN - rt.LastName + ' (' + rt.Initials + ')' - WHEN datalength(rt.Initials) = 0 OR rt.initials = ' ' OR rt.lastname = ' none' THEN - null - else - rt.Initials - END as performedBy, - - Remarks as Remark, - --cln.SearchKey as SearchKey, - - --cln.ts as rowversion, - cln.objectid - -FROM Cln_Medications cln - left join Ref_Technicians rt on (cln.Technician = rt.ID) - left join Sys_parameters s2 on (s2.Field = 'MedicationUnits'and s2.Flag = Units) - left join Sys_parameters s3 on (s3.Field = 'MedicationRoute'and s3.Flag = Route) - left join Sys_parameters s4 on (s4.Field = 'MedicationFrequency' and s4.Flag = Frequency) - left join Sys_parameters s5 on (s5.Field = 'MedicationReason' and s5.Flag = Reason) - left join Sys_parameters s6 on (s6.Field = 'DepartmentCode' and s6.Flag = rt.DeptCode) - left join labkey.ehr_lookups.snomed_subset_codes ss ON (ss.code = cln.medication AND ss.primaryCategory = 'Diet' and ss.container = (SELECT c.entityid from labkey.core.containers c LEFT JOIN labkey.core.Containers c2 on (c.Parent = c2.EntityId) WHERE c.name = 'EHR' and c2.name = 'ONPRC')) - left join ref_snomed sno on (sno.SnomedCode = cln.Medication) - left join Af_Qrf q on (q.animalid = cln.animalid) - -where Medication is not null and Medication != '' -AND (cln.ts > ?) - -) t diff --git a/onprc_ehr/resources/etl/study/Weight.sql b/onprc_ehr/resources/etl/study/Weight.sql deleted file mode 100644 index 257adf66e..000000000 --- a/onprc_ehr/resources/etl/study/Weight.sql +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2012-2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Select - cast(AnimalID as nvarchar(4000)) as Id, - Date as Date, - WeightAmount as Weight, - --TODO: why is this stored in weights? - --TBFlag as TBFlag , ----- TBFlag = 1 TB Test Intradermal TBFlag = 2 TB Test Serological - - --NOTE: should not be necessary - --CurrentFlag as CurrentFlag , ----- CurrentFlag = 1 Current Weight, CurrentFlag = 2 Historical Weights information - --IDKey as IDKey, - - af.objectid, - af.ts as rowversion - -From Af_Weights af -WHERE af.ts > ? and af.weightAmount != 0 and af.weightAmount is not null - ---see death for final weights -UNION ALL - -Select - cast(AnimalID as nvarchar(4000)) as Id, - Date as Date, - WeightAtDeath as weight, - afd.objectid, - afd.ts as rowversion - -From Af_Death AfD -WHERE afd.ts > ? and afd.WeightAtDeath > 0 AND afd.WeightAtDeath is not null - -UNION ALL - select - cast(sg.AnimalID as nvarchar(4000)) as Id, - sg.Date, - sg.weight, - sg.objectid, - sg.ts as rowversion - -From Sur_general sg -left join Af_Weights w -on (w.AnimalId = sg.AnimalID and w.Date = sg.Date and sg.Weight = w.WeightAmount) -WHERE sg.ts > ? and w.objectid IS NULL and sg.weight is not null and sg.weight > 0 diff --git a/onprc_ehr/resources/etls/AvailableBlood.xml b/onprc_ehr/resources/etls/AvailableBlood.xml new file mode 100644 index 000000000..7cadfb985 --- /dev/null +++ b/onprc_ehr/resources/etls/AvailableBlood.xml @@ -0,0 +1,36 @@ + + + + + AvailableBloodVolume + + Transfers from the Available Blood Volume Calculation in labkeyPublic.onprc_ehr to Production + + + + + + + + Truncate and Populate Available Blood Data + + + + + + + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/etls/HarvestToPrime_Process.xml b/onprc_ehr/resources/etls/HarvestToPrime_Process.xml new file mode 100644 index 000000000..d8a0ee0bc --- /dev/null +++ b/onprc_ehr/resources/etls/HarvestToPrime_Process.xml @@ -0,0 +1,83 @@ + + + + + Harvest_To_Prime_Process + + Transfers LIS schema temp tables into study dataset lab values + + + + + + Runs a stored procedure that generates lab values + + + + + + + + Transfer to EHR Tasks + + + + + + + + + + Transfer to ClinpathRuns + + + + + + + + + + Transfer to ChemistryResults + + + + + + + + + + Transfer to HematologyResults + + + + + + + + + + Transfer to EHR Requests + + + + + + + + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/etls/PotentialParent2020.xml b/onprc_ehr/resources/etls/PotentialParent2020.xml new file mode 100644 index 000000000..0e82fa1bc --- /dev/null +++ b/onprc_ehr/resources/etls/PotentialParent2020.xml @@ -0,0 +1,42 @@ + + + + + + + + PotentialParentUpdate + + Executes Stored Procedutres to Populate Potential Parent Datasets + + + + + + + Runs a stored procedure to Update Potential Dam for Prime. + + + + + + Runs a stored procedure to Update Potential Sire for Prime + + + + + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/etls/drugAdministration.xml b/onprc_ehr/resources/etls/drugAdministration.xml new file mode 100644 index 000000000..4302c2a4b --- /dev/null +++ b/onprc_ehr/resources/etls/drugAdministration.xml @@ -0,0 +1,34 @@ + + + + + AddDrugToAnimalRecord + + Vitamin Administartion on Saturdays + + + + + Runs a stored procedure to update the drug table. + + + + + + + Import the drug data ( Multivitamin, NOS (E-87600)) from labkey_public.dbo.Temp_Drug table to Drug table in Prime + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/etls/extSchedulerCovid19.xml b/onprc_ehr/resources/etls/extSchedulerCovid19.xml new file mode 100644 index 000000000..5caa17eee --- /dev/null +++ b/onprc_ehr/resources/etls/extSchedulerCovid19.xml @@ -0,0 +1,41 @@ + + + + + Covid19Scheduler + + This ETL Runs a series of Stored Procedures to Block out Section of Scheduler + + + + + + Runs Stored Procedure to Block out All Days Except Monday and Friday + + + + + + Runs a stored procedure to BLock out 7 to 8 AM MOnday and Friday. + + + + + + Runs a stored procedure to BLock out 3:30 to 7 PM MOnday and Friday. + + + + + + + + + + + + diff --git a/onprc_ehr/resources/etls/ogaAliasCleanup2020.xml b/onprc_ehr/resources/etls/ogaAliasCleanup2020.xml new file mode 100644 index 000000000..efccb1e45 --- /dev/null +++ b/onprc_ehr/resources/etls/ogaAliasCleanup2020.xml @@ -0,0 +1,25 @@ + + + + + ogaAliasCleanUp2020 + + Code to enddate or remove Aliases not Assocatied with ONPRC + + + + + Code to enddate or remove Aliases not Assocatied with ONPRC. + + + + + + + + + + + diff --git a/onprc_ehr/resources/etls/ogaSynch2020.xml b/onprc_ehr/resources/etls/ogaSynch2020.xml new file mode 100644 index 000000000..8dc148a82 --- /dev/null +++ b/onprc_ehr/resources/etls/ogaSynch2020.xml @@ -0,0 +1,46 @@ + + + + + + + + + OGASync2020 + + Copies OGA Data from external source to PRIME for PRocessing + + + + + + Import to OGA Sync in Prime + + + + + + + + + Runs a stored procedure to Update Transaction log based on OGA External Schema. + + + + + + + Runs a stored procedure Update the OGA Associated Datasets in Prime based on Transaction Log. + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/etls/rateChangeprocess.xml b/onprc_ehr/resources/etls/rateChangeprocess.xml new file mode 100644 index 000000000..119af1439 --- /dev/null +++ b/onprc_ehr/resources/etls/rateChangeprocess.xml @@ -0,0 +1,27 @@ + + + + + ratechangeProcess + + Updates the Rate Sheets for Investigators in the Billing Folder + + + + + Runs a stored procedure to update the Rate Sheet for Public Rate Projections. + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/module.xml b/onprc_ehr/resources/module.xml index 97f3fbc8c..62ed31853 100644 --- a/onprc_ehr/resources/module.xml +++ b/onprc_ehr/resources/module.xml @@ -28,5 +28,12 @@ ADMIN
+ + true + /ONPRC/DCM/NHP Resources + + ADMIN + + diff --git a/onprc_ehr/resources/queries/ehr/SnomedBySetSearch.sql b/onprc_ehr/resources/queries/ehr/SnomedBySetSearch.sql new file mode 100644 index 000000000..bb81c25ad --- /dev/null +++ b/onprc_ehr/resources/queries/ehr/SnomedBySetSearch.sql @@ -0,0 +1,75 @@ + +---- Created: 12-15-2017 R.Blasa + +PARAMETERS(SNOMEDCODE VARCHAR, STARTDATE TIMESTAMP, ENDDATE TIMESTAMP) + + +SELECT + t1.Id, + e.date, + e.caseno, + t1.type, + t1.sort_order, + t1.codes, + t1.codesMeaning, + t1.meaning, + e.taskid +FROM ( +SELECT + +e.Id, +e.recordid, +e.sort_order, +e.parentid, +group_concat(DISTINCT e.type) as type, +group_concat(e.codeWithSort, chr(10)) as codes, +group_concat(e.codeMeaning, chr(10)) as codesMeaning, +group_concat(e.meaning, chr(10)) as meaning + +FROM ( + +SELECT + pd.Id, + pd.date, + 'Diagnosis' as type, + --e.objectid, + --e.caseno, + s.recordid, + pd.sort_order, + pd.parentid, + cast(s.codeWithSort as varchar) as codeWithSort, + s.code, + sno.meaning, + cast((cast(s.sort as varchar(10)) || cast(': ' as varchar(2)) || sno.meaning || ' (' || s.code || ')') as varchar(2000)) as codeMeaning + +FROM ehr.snomed_tags s +JOIN study.pathologyDiagnoses pd ON (s.recordid = pd.objectid And s.code.code = rtrim(snomedCode)) +JOIN ehr_lookups.snomed sno ON (s.code = sno.code) + + UNION ALL + +SELECT + pd.Id, + pd.date, + 'Histology' as type, + --e.objectid, + --e.caseno, + s.recordid, + pd.formSort as sort_order, + pd.parentid, + cast(s.codeWithSort as varchar) as codeWithSort, + s.code, + sno.meaning, + cast((cast(s.sort as varchar(10)) || cast(': ' as varchar(2)) || sno.meaning || ' (' || s.code || ')') as varchar(2000)) as codeMeaning + +FROM ehr.snomed_tags s +JOIN study.histology pd ON (s.recordid = pd.objectid And s.code.code = rtrim(snomedCode)) +JOIN ehr_lookups.snomed sno ON (s.code = sno.code) + +) e + +GROUP BY e.Id, e.recordid, e.parentid, e.sort_order + +) t1 + +JOIN study.encounters e ON (e.Id = t1.Id AND e.objectid = t1.parentid And (e.date < ENDDATE and e.date >= STARTDATE)) diff --git a/onprc_ehr/resources/queries/ehr/SnomedBySetSearch/.qview.xml b/onprc_ehr/resources/queries/ehr/SnomedBySetSearch/.qview.xml new file mode 100644 index 000000000..44c78d360 --- /dev/null +++ b/onprc_ehr/resources/queries/ehr/SnomedBySetSearch/.qview.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/ehr/project_active.sql b/onprc_ehr/resources/queries/ehr/project_active.sql new file mode 100644 index 000000000..f2875619e --- /dev/null +++ b/onprc_ehr/resources/queries/ehr/project_active.sql @@ -0,0 +1,13 @@ +SELECT project.name, +project.protocol, +project.investigatorId, +project.title, +project.use_category, +project.startdate, +project.enddate, +project.shortname, +project.container, +project.displayName, +project.account +FROM project +where (enddate is null or enddate >= Now()) \ No newline at end of file diff --git a/onprc_ehr/resources/queries/ehr/requests.query.xml b/onprc_ehr/resources/queries/ehr/requests.query.xml new file mode 100644 index 000000000..d170de320 --- /dev/null +++ b/onprc_ehr/resources/queries/ehr/requests.query.xml @@ -0,0 +1,128 @@ + + + + + + /ehr/requestDetails.view?formtype=${formtype}&requestid=${requestid} + + + + + RowId + requestid + + + Request Id + true + true + /ehr/requestDetails.view?formtype=${formtype}&requestid=${requestid} + + + /ehr/requestDetails.view?formtype=${formtype}&requestid=${requestid} + + + true + true + Request Id + + + Request Type + + ehr + formtypes + type + + + + Created By + + core + users + userid + + + + First Contact + + core + PrincipalsWithoutAdmin + userid + + + + Second Contact + + + + + + + + Third Contact + + + + + + + + PI + + + + ehr_lookups + request_priority + priority + + + + Lab Phone # + + + Created + yyyy-MM-dd HH:mm + + + Modified By + + + Modified + + + Date Requested + + + true + + + true + Status + + study + qcstate + rowid + + 200 + + + 200 + + + textarea + + + + + Grid views + + + Export + + + Print + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/ehr/requests/.qview.xml b/onprc_ehr/resources/queries/ehr/requests/.qview.xml new file mode 100644 index 000000000..f4a3f11f0 --- /dev/null +++ b/onprc_ehr/resources/queries/ehr/requests/.qview.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/ehr/requests/Requests.qview.xml b/onprc_ehr/resources/queries/ehr/requests/Requests.qview.xml new file mode 100644 index 000000000..40b99e5c3 --- /dev/null +++ b/onprc_ehr/resources/queries/ehr/requests/Requests.qview.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/ehr/snomed_tags.js b/onprc_ehr/resources/queries/ehr/snomed_tags.js new file mode 100644 index 000000000..41ebf2961 --- /dev/null +++ b/onprc_ehr/resources/queries/ehr/snomed_tags.js @@ -0,0 +1,13 @@ +/* + * Copyright (c) 2011-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +require("ehr/triggers").initScript(this); +function onInit(event, helper) { + helper.setScriptOptions({ + allowFutureDates: true + + }); +} \ No newline at end of file diff --git a/onprc_ehr/resources/queries/ehr_lookups/Flag_Categories_Active.query.xml b/onprc_ehr/resources/queries/ehr_lookups/Flag_Categories_Active.query.xml new file mode 100644 index 000000000..0805b73f1 --- /dev/null +++ b/onprc_ehr/resources/queries/ehr_lookups/Flag_Categories_Active.query.xml @@ -0,0 +1,14 @@ + + + + + Procedure Names + + + true + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/ehr_lookups/Flag_Categories_Active.sql b/onprc_ehr/resources/queries/ehr_lookups/Flag_Categories_Active.sql new file mode 100644 index 000000000..aa9667660 --- /dev/null +++ b/onprc_ehr/resources/queries/ehr_lookups/Flag_Categories_Active.sql @@ -0,0 +1,3 @@ + + +SELECT * FROM ehr_lookups.Flag_Categories Where datedisabled is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/ehr_lookups/behavior_Types_Current.sql b/onprc_ehr/resources/queries/ehr_lookups/behavior_Types_Current.sql new file mode 100644 index 000000000..fa2c3808e --- /dev/null +++ b/onprc_ehr/resources/queries/ehr_lookups/behavior_Types_Current.sql @@ -0,0 +1,4 @@ +-- Created: 9-30-2019 R.Blasa + +Select * from ehr_lookups.behavior_types +Where date_disabled is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/ehr_lookups/snomed/.qview.xml b/onprc_ehr/resources/queries/ehr_lookups/snomed/.qview.xml new file mode 100644 index 000000000..467820a1e --- /dev/null +++ b/onprc_ehr/resources/queries/ehr_lookups/snomed/.qview.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/ChemistryDept.sql b/onprc_ehr/resources/queries/onprc_ehr/ChemistryDept.sql new file mode 100644 index 000000000..743a99914 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/ChemistryDept.sql @@ -0,0 +1,3 @@ +select value, sort_order from sla.Reference_Data +where columnName = 'BiochemistryDept' +And endDate is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/LabServiceRequest_Active.sql b/onprc_ehr/resources/queries/onprc_ehr/LabServiceRequest_Active.sql new file mode 100644 index 000000000..6b849e87f --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/LabServiceRequest_Active.sql @@ -0,0 +1,2 @@ +select * from ehr_Lookups.labwork_services +where datedisabled is null diff --git a/onprc_ehr/resources/queries/onprc_ehr/NHP_Training.js b/onprc_ehr/resources/queries/onprc_ehr/NHP_Training.js new file mode 100644 index 000000000..9ee75ca8f --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/NHP_Training.js @@ -0,0 +1,4 @@ + +//Created: 1-31-2019 R.Blasa NHP_Training input screen triggers + +require("ehr/triggers").initScript(this); diff --git a/onprc_ehr/resources/queries/onprc_ehr/NHP_Training.query.xml b/onprc_ehr/resources/queries/onprc_ehr/NHP_Training.query.xml new file mode 100644 index 000000000..741a2af88 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/NHP_Training.query.xml @@ -0,0 +1,64 @@ + + + + + NHP Training + DETAILED + + + + true + + + + Id + /ehr/participantView.view?participantId=${Id} + + + + Start Date + + + + End Date + + + Training Type + + + true + + + true + + + + Training Reason + + + Training Result + + + + + study + qcstate + RowId + + + + + Task Id + + ehr + tasks + taskid + + + + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/onprc_ehr/NHP_Training/.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/NHP_Training/.qview.xml index 952afc42f..4f18338ce 100644 --- a/onprc_ehr/resources/queries/onprc_ehr/NHP_Training/.qview.xml +++ b/onprc_ehr/resources/queries/onprc_ehr/NHP_Training/.qview.xml @@ -39,6 +39,18 @@
+ + + + + + + + + + + + diff --git a/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask.query.xml b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask.query.xml new file mode 100644 index 000000000..c2e807c6a --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask.query.xml @@ -0,0 +1,57 @@ + + + + + Necropsy Task + + + Task ID + /ehr/dataEntryForm.view?formType=${formtype}&taskid=${taskid} + + + Title + /ehr/dataEntryForm.view?formType=${formtype}&taskid=${taskid} + + + Procedure Name + + + Investigator + + + Assigned To + true + + core + PrincipalsWithoutAdmin + UserId + + + + Due Date + true + yyyy-MM-dd HH:mm + + + Created By + + core + users + userid + + + + + false + true + Status + 50 + + + + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask.sql b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask.sql new file mode 100644 index 000000000..be3101474 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask.sql @@ -0,0 +1,22 @@ +-- Created: 3-30-2017 R.Blasa + + +SELECT +t.taskid, +t.title, +g.procedureid.name as ProcedureName, +g.project.InvestigatorId.lastname as Investigator, +t.assignedto, +t.duedate, +t.createdby, +t.created, +t.qcstate, +t.formtype + + +FROM ehr.tasks t + Left join study.encounters g on (t.taskid = g.taskid And g.type = 'Necropsy') + + + + diff --git a/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask/.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask/.qview.xml new file mode 100644 index 000000000..b8e232b24 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask/.qview.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask/ActiveTasks.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask/ActiveTasks.qview.xml new file mode 100644 index 000000000..f8b08e55b --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/NecropsyTask/ActiveTasks.qview.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/PairingEndType.sql b/onprc_ehr/resources/queries/onprc_ehr/PairingEndType.sql new file mode 100644 index 000000000..3c7ec649c --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/PairingEndType.sql @@ -0,0 +1,7 @@ + +-- Created: 6-20-2018 R.Blasa + + +select value, sort_order from sla.Reference_Data +where columnName = 'PairingEndtype' +And endDate is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/PairingStartType.sql b/onprc_ehr/resources/queries/onprc_ehr/PairingStartType.sql new file mode 100644 index 000000000..5aa0add81 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/PairingStartType.sql @@ -0,0 +1,5 @@ +-- Created: 6-20-2018 R.Blasa + +select value, sort_order from sla.Reference_Data +where columnName = 'PairingStarttype' +And endDate is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/Vet_assignmentMissingSummary.sql b/onprc_ehr/resources/queries/onprc_ehr/Vet_assignmentMissingSummary.sql new file mode 100644 index 000000000..c37cceb8b --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/Vet_assignmentMissingSummary.sql @@ -0,0 +1,6 @@ +SELECT m.MissingItem, +Count(m.Item) As TotalMissing +--m.Vet_AssignedItem, +--m.totalNHps +FROM vet_assignmentMissingData m +group by m.missingItem \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/my_tasks.sql b/onprc_ehr/resources/queries/onprc_ehr/my_tasks.sql new file mode 100644 index 000000000..22a600958 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/my_tasks.sql @@ -0,0 +1,24 @@ +-- Created: 3-24-2017 R.Blasa + + +SELECT +t.taskid, +t.updateTitle, +t.category, +t.title, +t.formtype, +t.qcstate, +t.assignedto, +t.duedate, +t.requestid, +t.datecompleted, +t.createdby, +t.created, +t.description, +g.procedureid.name as ProcedureName, +g.project.InvestigatorId.lastname as Investigator +FROM ehr.tasks t + Left join study.encounters g on (t.taskid = g.taskid And g.type = 'Necropsy') + +WHERE ISMEMBEROF(t.assignedto) + diff --git a/onprc_ehr/resources/queries/onprc_ehr/my_tasks/.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/.qview.xml new file mode 100644 index 000000000..8fde9e2a7 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/.qview.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Active Tasks.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Active Tasks.qview.xml new file mode 100644 index 000000000..cd21c338e --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Active Tasks.qview.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Necropsies.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Necropsies.qview.xml new file mode 100644 index 000000000..70c2229cb --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Necropsies.qview.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Review Required.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Review Required.qview.xml new file mode 100644 index 000000000..74173fca0 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Review Required.qview.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Today.qview.xml b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Today.qview.xml new file mode 100644 index 000000000..4400e56bd --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/my_tasks/Today.qview.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/userNames.query.xml b/onprc_ehr/resources/queries/onprc_ehr/userNames.query.xml new file mode 100644 index 000000000..6543f0fe5 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/userNames.query.xml @@ -0,0 +1,14 @@ + + + + + DisplayName + + + true + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/userNames.sql b/onprc_ehr/resources/queries/onprc_ehr/userNames.sql new file mode 100644 index 000000000..f3ccc7b56 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/userNames.sql @@ -0,0 +1,8 @@ +SELECT + u.DisplayName, + 'u' as type, + u.FirstName, + u.LastName, + u.Active + +FROM onprc_ehr.usersActiveNames u \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/vet_assignmenMissingData.query.xml b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmenMissingData.query.xml new file mode 100644 index 000000000..e4bb5e01c --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmenMissingData.query.xml @@ -0,0 +1,30 @@ + + + + + + + Vet Assignment Missing Item Summary + + + /query/executeQuery.view? + schemaName=onprc_ehr& + queryName=Vet_assignmentMissingSummary& + query.MissingItem~eq=${MissingItem}& + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingData.sql b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingData.sql new file mode 100644 index 000000000..da320d1c3 --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingData.sql @@ -0,0 +1,52 @@ +Select +'Research Protocol_Missing' as MissingItem, +a.project.protocol.displayName as Item, +v.protocol.displayName as Vet_AssignedItem, +Count(a.participantId) as totalNHps +from study.assignment a left outer join vet_assignment v on a.project.protocol = v.protocol.protocol +where a.project.use_category = 'Research' and a.enddate is null and v.protocol.displayName is null +group by a.project.protocol.displayname,v.protocol.displayName + +Union + +Select +'Resource Protocol_Missing' as MissingItem, +a.project.protocol.displayName as Item, +v.protocol.displayName as Vet_AssignedItem, +Count(a.participantId) as totalNHps +from study.assignment a left outer join vet_assignment v on a.project.protocol = v.protocol.protocol +where a.project.use_category != 'Research'and a.enddate is null and v.protocol.displayName is null +group by a.project.protocol.displayname,v.protocol.displayName +Union + +Select +'Area_Missing' as MissingItem, +a.area as Item, +v.area as Vet_AssignedItem, +Count(h.ID) as TotalNHPS +from ehr_lookups.areas a left outer join vet_assignment v on a.area = v.area + left outer join study.housing h on h.room.area = a.area +where v.area is null and h.enddate is null +group by a.area,v.area + + +Union + +Select +'Room_Missing' as MissingItem, +r.room as Item, +v.room as Vet_AssignedItem, +Count(h.id) as totalNHPs +from ehr_lookups.rooms r left outer join vet_assignment v on r.room = v.room + left outer join study.housing h on h.room = r.room and h.enddate is null +where v.room is null and r.area not in (Select v1.area from vet_assignment v1 where v1.area = r.area) +group by r.room,v.room + +union + +Select +'NHP No Vet', +v.id, +v.assignedVet, +0 +from study.demographicsAssignedVet v where v.assignedvet is null diff --git a/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingLink.query.xml b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingLink.query.xml new file mode 100644 index 000000000..e4bb5e01c --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingLink.query.xml @@ -0,0 +1,30 @@ + + + + + + + Vet Assignment Missing Item Summary + + + /query/executeQuery.view? + schemaName=onprc_ehr& + queryName=Vet_assignmentMissingSummary& + query.MissingItem~eq=${MissingItem}& + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingLink.sql b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingLink.sql new file mode 100644 index 000000000..c37cceb8b --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmentMissingLink.sql @@ -0,0 +1,6 @@ +SELECT m.MissingItem, +Count(m.Item) As TotalMissing +--m.Vet_AssignedItem, +--m.totalNHps +FROM vet_assignmentMissingData m +group by m.missingItem \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.query.xml b/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.query.xml index e5e46d5ff..ab4f169d4 100644 --- a/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.query.xml +++ b/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.query.xml @@ -3,7 +3,7 @@ Vet Assignment - + diff --git a/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.sql b/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.sql index 1346ed6ae..afce6ef7a 100644 --- a/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.sql +++ b/onprc_ehr/resources/queries/onprc_ehr/vet_assignment_summary.sql @@ -15,9 +15,14 @@ */ SELECT v.userId, - group_concat(DISTINCT (v.area || CASE WHEN v.priority = true THEN '*' ELSE '' END), chr(10)) as areas, + + group_concat(DISTINCT ( CASE WHEN (v.protocol is not null and v.room is not null) THEN (v.protocol.displayname || '-' || v.room) ELSE '' END), chr(10)) as Protocol_Room, + group_concat(DISTINCT ( CASE WHEN (v.protocol is not null and v.area is not null) THEN (v.protocol.displayname || '-' || v.area) ELSE '' END), chr(10)) as Protocol_Area, + group_concat(DISTINCT (v.protocol.displayName || ' (' || v.protocol.investigatorid.lastname || ')'), chr(10)) as protocols, group_concat(DISTINCT (v.room || CASE WHEN v.priority = true THEN '*' ELSE '' END), chr(10)) as rooms, - group_concat(DISTINCT (v.protocol.displayName || ' (' || v.protocol.investigatorid.lastname || ')'), chr(10)) as protocols + group_concat(DISTINCT (v.area || CASE WHEN v.priority = true THEN '*' ELSE '' END), chr(10)) as areas + + FROM onprc_ehr.vet_assignment v GROUP BY v.userId \ No newline at end of file diff --git a/onprc_ehr/resources/queries/onprc_ehr/vet_assignmnetMissingLink.sql b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmnetMissingLink.sql new file mode 100644 index 000000000..c37cceb8b --- /dev/null +++ b/onprc_ehr/resources/queries/onprc_ehr/vet_assignmnetMissingLink.sql @@ -0,0 +1,6 @@ +SELECT m.MissingItem, +Count(m.Item) As TotalMissing +--m.Vet_AssignedItem, +--m.totalNHps +FROM vet_assignmentMissingData m +group by m.missingItem \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/ActiveStudyDetails.sql b/onprc_ehr/resources/queries/study/ActiveStudyDetails.sql new file mode 100644 index 000000000..07d04c5e6 --- /dev/null +++ b/onprc_ehr/resources/queries/study/ActiveStudyDetails.sql @@ -0,0 +1,21 @@ +Select + Id, + project, project.protocol, project.protocol.investigatorId, + Date StartDate, endDate, + studyCohort, + studyGroup, + studyGroupNum, + studyPhase, + remark, + performedby, + Id.demographics.calculated_status, + Id.demographics.gender, + Id.curLocation.room, + Id.curLocation.cage, + taskid +From Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.StudyDetails +Where (curdate() between Date and endDate) OR ( (curdate() >= Date) and (endDate IS NULL)) + + + + diff --git a/onprc_ehr/resources/queries/study/AssignmentTypes.sql b/onprc_ehr/resources/queries/study/AssignmentTypes.sql new file mode 100644 index 000000000..9cdd408a0 --- /dev/null +++ b/onprc_ehr/resources/queries/study/AssignmentTypes.sql @@ -0,0 +1,5 @@ +--- Created: 4-24-2019 R.Blasa + +Select value from sla.Reference_Data +where columnName = 'AssignmentType' +and enddate is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/BCS_Recent_Score.sql b/onprc_ehr/resources/queries/study/BCS_Recent_Score.sql new file mode 100644 index 000000000..37ff7ed46 --- /dev/null +++ b/onprc_ehr/resources/queries/study/BCS_Recent_Score.sql @@ -0,0 +1,21 @@ +Select +c.id, +c.observation as score, +c.date, +c.created +From study.clinical_Observations c + +RIGHT JOIN + (Select + a.id, + MAX(CAST(a.date AS DATE)) as MaxDate + From study.clinical_Observations a + Where a.category = 'bcs' + And a.date > TIMESTAMPADD('SQL_TSI_MONTH', -18, Now()) + and a.observation is not null + --And a.id in ('30661', '16609') + Group by a.id -- , a.date + ) As d + +ON c.id = d.id And CAST(c.date AS DATE) = d.MaxDate +Where c.category = 'bcs' and c.id not like '[a-z]%' diff --git a/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch.query.xml b/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch.query.xml new file mode 100644 index 000000000..a3a7295a2 --- /dev/null +++ b/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch.query.xml @@ -0,0 +1,15 @@ + + + +
+ Birth Locations with Mismatched Initial Housing Record + + + + + ehr.context + +
+
+ + diff --git a/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch.sql b/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch.sql new file mode 100644 index 000000000..a4c9af46f --- /dev/null +++ b/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch.sql @@ -0,0 +1,8 @@ +select k.Id,K.date,k.room,k.cage,s.room as "Housing Room",s.cage as "Housing Cage" + +from study.birth k, study.Housing s +where ((s.reason = 'initialTransfer' or s.reason is null) and s.reason <> 'unknown') +and (s.room.room <> k.room.room and (s.cage <> k.cage or s.cage is null and k.cage is null)) +and (k.Id = s.participantid) +and k.qcstate.publicdata = true + diff --git a/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch/.qview.xml b/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch/.qview.xml new file mode 100644 index 000000000..a6e973473 --- /dev/null +++ b/onprc_ehr/resources/queries/study/BirthInitialHousingMismatch/.qview.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/BloodCalcBCS.sql b/onprc_ehr/resources/queries/study/BloodCalcBCS.sql new file mode 100644 index 000000000..13404ba81 --- /dev/null +++ b/onprc_ehr/resources/queries/study/BloodCalcBCS.sql @@ -0,0 +1,19 @@ +SELECT c.id, +c.species, +c.gender, +c.DaysAge, +c.Weight, +c.MostRecentWeightDate, +c.date as BCSDate, +c.bcs as BCSScore, +c.CalcMethod, +c.bpk, +c.interval, +c.Percentage, +c.CalcMethodReason, +((c.Weight * (113.753+(0.752 * c.Weight ) - (18.919 * c.bcs)))) as BcsTbv, +(c.bpk*c.Weight) as StandardTBV + + +FROM bloodCalcCriteria c +WHere c.CalcMethod = 'BCS' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/CTACType_values.sql b/onprc_ehr/resources/queries/study/CTACType_values.sql new file mode 100644 index 000000000..15b31b241 --- /dev/null +++ b/onprc_ehr/resources/queries/study/CTACType_values.sql @@ -0,0 +1 @@ +SELECT value, columnname from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.reference_data where columnname like 'CTACType' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/CTContrastType_values.sql b/onprc_ehr/resources/queries/study/CTContrastType_values.sql new file mode 100644 index 000000000..0930454ff --- /dev/null +++ b/onprc_ehr/resources/queries/study/CTContrastType_values.sql @@ -0,0 +1 @@ +SELECT value, columnname from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.reference_data where columnname like 'ContrastType' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/CageMateInfant.sql b/onprc_ehr/resources/queries/study/CageMateInfant.sql index da283f4a7..bf0dbe6c9 100644 --- a/onprc_ehr/resources/queries/study/CageMateInfant.sql +++ b/onprc_ehr/resources/queries/study/CageMateInfant.sql @@ -15,17 +15,24 @@ */ + select a.id, -a.room, -e.offspringUnder1Yr as InfantCageMate, +group_concat(e.Id ) as InfantCageMate, a.QCState - from study.housingRoommates a, study.demographicsInfantUnderOne e -where a.RoommateId.Id = e.offspringUnder1Yr -And a.Id.DataSet.demographics.calculated_status.code = 'Alive' -And e.Id.DataSet.demographics.calculated_status.code = 'Alive' -and a.roommateEnd is null -and a.qcstate = 18 -and a.room.housingtype.value = 'Cage Location' \ No newline at end of file + + from study.housing a, study.demographics e +where a.Id <> e.Id +And e.calculated_status.code = 'Alive' +and a.Enddate is null +and a.qcstate = 18 and e.qcstate = 18 +and a.housingType.value = 'Cage Location' +and (a.room.room = e.Id.curLocation.room and a.cage = e.Id.curLocation.cage) +and e.Id.age.ageInyears < 1 + + +Group by a.id, a.QCState + + diff --git a/onprc_ehr/resources/queries/study/Clinical Encounters/.qview.xml b/onprc_ehr/resources/queries/study/Clinical Encounters/.qview.xml new file mode 100644 index 000000000..f1da9f3a4 --- /dev/null +++ b/onprc_ehr/resources/queries/study/Clinical Encounters/.qview.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/Clinical Remarks.js b/onprc_ehr/resources/queries/study/Clinical Remarks.js deleted file mode 100644 index 58a1f6d74..000000000 --- a/onprc_ehr/resources/queries/study/Clinical Remarks.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2010-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - */ - -require("ehr/triggers").initScript(this); - -function onInit(event, helper){ - helper.setScriptOptions({ - allowDeadIds: true - }); -} - -function onUpsert(helper, scriptErrors, row, oldRow){ - //NOTE: each center has slightly different names on the SOAP fields. this check tests all, and should not get in the way of either - if(!row.hx && !row.so && !row.s && !row.p2 && !row.o && !row.a && !row.p && !row.remark){ - EHR.Server.Utils.addError(scriptErrors, 'remark', 'Must enter at least one comment', 'WARN'); - EHR.Server.Utils.addError(scriptErrors, 'so', 'Must enter at least one comment', 'WARN'); - EHR.Server.Utils.addError(scriptErrors, 's', 'Must enter at least one comment', 'WARN'); - - } - //find the id of the anima; - //run the demographics vedtassignemnt to get the userid - //insert the value into the row for assignedVet - //for compatibility with old system - - - - var currentVet = []; - LABKEY.Query.selectRows({ - schemaName: 'study', - queryName: 'demographicsAssignedVet', - scope: this, - filterArray: [ - LABKEY.Filter.create('id', row.Id, LABKEY.Filter.Types.EQUAL) - ], - success: function(data){ - if(data.rows && data.rows.length){ - /* var rowData; */ - currentVet = data.rows[0].assignedVet; - // for (var i=0;i - +
Clinical Remarks Open + + + diff --git a/onprc_ehr/resources/queries/study/ClinicalCases_Open.sql b/onprc_ehr/resources/queries/study/ClinicalCases_Open.sql new file mode 100644 index 000000000..1b9b00b03 --- /dev/null +++ b/onprc_ehr/resources/queries/study/ClinicalCases_Open.sql @@ -0,0 +1,17 @@ +SELECT + c.Id, + c.date, + c.enddate, + c.reviewdate, + c.category, + c.performedby, + c.description, + c.problemCategories, + c.remark, + c.mostRecentP2, + c.isActive, + c.assignedvet, + c.mostRecentCeg_Plan + +FROM study.cases c +WHERE c.isOpen = true AND c.category = 'Clinical' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/ClinpathRuns.query.xml b/onprc_ehr/resources/queries/study/ClinpathRuns.query.xml new file mode 100644 index 000000000..b7ec57b91 --- /dev/null +++ b/onprc_ehr/resources/queries/study/ClinpathRuns.query.xml @@ -0,0 +1,136 @@ + + + +
+ /ehr/clinpathDetails.view?lsid=${lsid}&objectid=${objectid} + + + + + servicerequested + + + + + + Collection Date + + + + + + Service Requested + + ehr_lookups + Labwork_services + servicename + + + + Charge Unit + + ehr_lookups + labworkChargeType + value + + + + Sample Type + + ehr_lookups + clinpath_sampletype + value + + + + Tissue + + ehr_lookups + snomed + code + + + + Sample Quantity + true + + + Quantity Units + true + + + Sample Units + true + + + Collected By + + + Collection Method + + ehr_lookups + clinpath_collection_method + value + + + + Method + + + Remark + + + Category + + ehr_lookups + clinpath_types + value + + + + + Special Instructions + textarea + + + Reviewed By + + + Date Reviewed + + + true + + + true + + + true + + + true + + + true + + + true + + + Units + + + Clinical Remark + + + Sample Id + true + + + Condition + + +
+
+
+ \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/DrugsGiven72hours.sql b/onprc_ehr/resources/queries/study/DrugsGiven72hours.sql new file mode 100644 index 000000000..1d26c7b65 --- /dev/null +++ b/onprc_ehr/resources/queries/study/DrugsGiven72hours.sql @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +-- Created: 10-4-2019 R.Blasa + +SELECT + p.id as Id, + p.date, + timestampadd('SQL_TSI_HOUR',72,p.date ) as enddate, + p.code.code as code, + p.code.meaning as meaning, + p.amountAndVolume, + p.route, + timestampdiff('SQL_TSI_HOUR',p.date, now() ) as ElapseHours, + p.remark, + p.category + +FROM study.drug p +WHERE p.qcstate.publicdata = true +and timestampdiff('SQL_TSI_HOUR',p.date, now() ) < 73 +and p.code in (select code from ehr_lookups.snomed_subset_codes Where primaryCategory = 'Sustained Medications' ) +and p.route <> 'Spillage' + +UNION + +SELECT + s.id as Id, + s.date, + timestampadd('SQL_TSI_HOUR',72,s.date ) as enddate, + s.code.code as code, + s.code.meaning as meaning, + s.amountAndVolume, + s.route, + timestampdiff('SQL_TSI_HOUR',s.date, now() ) as ElapseHours, + s.remark, + s.category + +FROM study.treatment_order s +WHERE s.qcstate.publicdata = true +and timestampdiff('SQL_TSI_HOUR',s.date, now() ) < 73 +and s.code in (select code from ehr_lookups.snomed_subset_codes Where primaryCategory = 'Sustained Medications' ) +and s.route <> 'Spillage' diff --git a/onprc_ehr/resources/queries/study/GeneticValueRanking.sql b/onprc_ehr/resources/queries/study/GeneticValueRanking.sql new file mode 100644 index 000000000..4cad5be82 --- /dev/null +++ b/onprc_ehr/resources/queries/study/GeneticValueRanking.sql @@ -0,0 +1,12 @@ +Select +Id, +meanKinship, +zscore, +genomeUniqueness, +totalOffspring, +livingOffspring, +assignments as TotalAssignments, +condition, +value as GeneticValue, +rank +From Site.{substitutePath moduleProperty('ONPRC_EHR','DCM_NHP_Resources_Container')}.lists.GeneticValue \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/Histology.query.xml b/onprc_ehr/resources/queries/study/Histology.query.xml index 9e8f7bc6f..d8519b8e7 100644 --- a/onprc_ehr/resources/queries/study/Histology.query.xml +++ b/onprc_ehr/resources/queries/study/Histology.query.xml @@ -8,9 +8,12 @@ - + + 80 + Date + 130 false http://cpas.labkey.com/Study#VisitDate @@ -22,9 +25,11 @@ Sort Order + 50 Organ/Tissue + 80 ehr_lookups snomed @@ -48,7 +53,7 @@ - 110 + 700 Diagnosis urn:ehr.labkey.org/#Remark textarea diff --git a/onprc_ehr/resources/queries/study/InfantsBorntoAssigned.sql b/onprc_ehr/resources/queries/study/InfantsBorntoAssigned.sql new file mode 100644 index 000000000..753663de7 --- /dev/null +++ b/onprc_ehr/resources/queries/study/InfantsBorntoAssigned.sql @@ -0,0 +1,56 @@ +Select +a.Id, +a.date, +a.dam, +a.sire, +(select group_concat( b.project.name) from study.assignment b +where b.qcstate = 18 and b.isActive ='true' And b.participantid = a.dam) ProjectName, + +a.QCState +FROM study.birth a +Where a.dam in (select b.Id from study.assignment b +where b.project.name not in ('0492-02','0492-03','1063') +and b.qcstate = 18 and b.isActive ='true') + +And a.Id.DataSet.demographics.calculated_status.code = 'Alive' +and a.qcstate = 18 +and not(a.species in ('rabbit', 'guinea pig')) + +UNION + +Select +a.Id, +a.date, +a.dam, +a.sire, +(select group_concat( b.project.name) from study.assignment b +where b.qcstate = 18 and b.isActive ='true' And b.participantid = a.dam) ProjectName, + +a.QCState +FROM study.birth a +Where a.dam in (select b.Id from study.assignment b +where b.project.name not in ('0492-02','0492-03','1063') +and b.qcstate = 18 and b.isActive ='true') +And a.Id.DataSet.demographics.calculated_status.code = 'Dead' +and a.qcstate = 18 +and not(a.species in ('rabbit', 'guinea pig')) + +UNION + +Select +a.Id, +a.date, +a.dam, +a.sire, +(select group_concat( b.project.name) from study.assignment b +where b.qcstate = 18 and b.isActive ='true' And b.participantid = a.dam) ProjectName, + +a.QCState +FROM study.birth a +Where a.dam in (select b.Id from study.assignment b +where b.project.name not in ('0492-02','0492-03','1063') +and b.qcstate = 18 and b.isActive ='true') +and a.qcstate = 18 +and a.birth_condition = 'Fetus - Prenatal' +and not(a.species in ('rabbit', 'guinea pig')) + diff --git a/onprc_ehr/resources/etl/pending/lookups.sql b/onprc_ehr/resources/queries/study/LastHousingLocation.sql similarity index 67% rename from onprc_ehr/resources/etl/pending/lookups.sql rename to onprc_ehr/resources/queries/study/LastHousingLocation.sql index d6d208a3f..22ba636e6 100644 --- a/onprc_ehr/resources/etl/pending/lookups.sql +++ b/onprc_ehr/resources/queries/study/LastHousingLocation.sql @@ -1,5 +1,6 @@ + /* - * Copyright (c) 2012-2013 LabKey Corporation + * Copyright (c) 2017 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -SELECT - field as set_name, - value, - displayorder as sort_order, - datedisabled, - objectid -FROM sys_parameters s +-- Created: 12-19-2018 R.Blasa -WHERE ts > ? \ No newline at end of file +select a.Id,(a.room + ' ' + coalesce(a.cage, '')) as location from study.housing a +where a.date in (Select max( b.date) from study.housing b + where a.Id = b.Id + and a.qcstate.publicdata = true ) diff --git a/onprc_ehr/resources/queries/study/NMRadioisotope_values.sql b/onprc_ehr/resources/queries/study/NMRadioisotope_values.sql new file mode 100644 index 000000000..e25a9e87d --- /dev/null +++ b/onprc_ehr/resources/queries/study/NMRadioisotope_values.sql @@ -0,0 +1 @@ +SELECT value, columnname from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.reference_data Where columnname like 'NMIsotope' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/NecropsyToMiscCharges.query.xml b/onprc_ehr/resources/queries/study/NecropsyToMiscCharges.query.xml new file mode 100644 index 000000000..0f907026c --- /dev/null +++ b/onprc_ehr/resources/queries/study/NecropsyToMiscCharges.query.xml @@ -0,0 +1,54 @@ + + + + + Necropsy To Misc Charges Report + + + + Id + + + Charge Date + + + Necropsy Procedure Name + + + Necropsy Case No + + + Necropsy Center Project + + + Necropsy Investigator + + + Necropsy TaskID + + + + Misc Center Project + + + Charge Name + + + Quantity + + + Unit Cost + + + Charge Category + + + + Misc TaskID + + +
+
+
+
+ diff --git a/onprc_ehr/resources/queries/study/NecropsyToMiscCharges.sql b/onprc_ehr/resources/queries/study/NecropsyToMiscCharges.sql new file mode 100644 index 000000000..8a41e254c --- /dev/null +++ b/onprc_ehr/resources/queries/study/NecropsyToMiscCharges.sql @@ -0,0 +1,32 @@ +SELECT +b.Id as "NecropsyID", +b.date as "NecropsyDate", +b.procedureid as "Necropsyprocedure", +b.caseno, +b.project as "NecropsyProject", +b.project.investigatorId.lastname as "NecropsyInvestigator", +b.taskid as "NecropsyTaskID", +b.QCstate as "NecropsyStatus", + r1.Id as "MiscID", +r1.date as "MiscDate", +r1.project as "MiscProject", +r1.chargeId, +r1.quantity, +r1.unitCost, +r1.chargecategory, +r1.QCstate as "MiscStatus", +r1.taskid as "MiscTaskID" + + +FROM study.encounters b + + +Left join ( + Select a.Id, a.date, a.project, a.chargeId, a.quantity, a.unitCost, a.chargecategory, a.QCState, a.taskid + from onprc_billing.miscCharges a + Where a.chargeid.rowid in (4484,4485,4486,4487,4488,4489,5283, 4516,5296,5297,5298) + group by a.Id, a.date, a.project, a.chargeId, a.quantity, a.unitCost, a.chargecategory, a.QCState, a.taskid + +) r1 on (r1.id = b.id ) +Where b.type = 'Necropsy' + diff --git a/onprc_ehr/resources/queries/study/NecropsyToMiscCharges/.qview.xml b/onprc_ehr/resources/queries/study/NecropsyToMiscCharges/.qview.xml new file mode 100644 index 000000000..6895486f9 --- /dev/null +++ b/onprc_ehr/resources/queries/study/NecropsyToMiscCharges/.qview.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/PETRadioisotope_values.sql b/onprc_ehr/resources/queries/study/PETRadioisotope_values.sql new file mode 100644 index 000000000..7f7554dc9 --- /dev/null +++ b/onprc_ehr/resources/queries/study/PETRadioisotope_values.sql @@ -0,0 +1 @@ +SELECT value, columnname from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.reference_data where columnname like 'PETRadioisotope' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/Pairings.query.xml b/onprc_ehr/resources/queries/study/Pairings.query.xml index 4ab8684e0..cff5930aa 100644 --- a/onprc_ehr/resources/queries/study/Pairings.query.xml +++ b/onprc_ehr/resources/queries/study/Pairings.query.xml @@ -9,45 +9,35 @@ - - - - Pair Id This is used to identify the lowest cage number of the pair. It is used to determine which animals in the group are considered part of the pair. - - Pair ID - true - This field is used to differentiate pairs. By convention is should usually be the lowest cage number in the group; however, it does not need to match this - Room Cage + + Start Date + - Event Type + Start Type - ehr_lookups - pairingEventType + onprc_ehr + PairingStartType value + - - true - Housing Type - - ehr_lookups - pairingHousingType - value - + + Start Remark + 300 - Pair Goal + Divider Goal ehr_lookups pairingGoal @@ -55,13 +45,36 @@ - Pair Outcome + Divider Outcome ehr_lookups pairingOutcome value + + false + End Date + + + + End Type + + onprc_ehr + PairingEndType + value + + + + + Separation Reason + + ehr_lookups + pairingSeparationReason + value + + + Observation @@ -70,16 +83,25 @@ value - - Separation Reason + + + End Remark + 300 + + + + true + Housing Type ehr_lookups - pairingSeparationReason + pairingHousingType value - - Remark + + Pair ID + true + This field is used to differentiate pairs. By convention is should usually be the lowest cage number in the group; however, it does not need to match this Performed By diff --git a/onprc_ehr/resources/queries/study/ParentageCompleted.query.xml b/onprc_ehr/resources/queries/study/ParentageCompleted.query.xml new file mode 100644 index 000000000..dfd40838f --- /dev/null +++ b/onprc_ehr/resources/queries/study/ParentageCompleted.query.xml @@ -0,0 +1,52 @@ + + + + + Complete Parentage + + + + Area + + + Room + + + Cage + + + + Projects and Groups + + + + Gender + + + Status + + + Birth Date + + + Current Weight + + + Weight Date + + + + Observed Dam + + + Genetic Dam + + + Foster Dam + + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/ParentageCompleted.sql b/onprc_ehr/resources/queries/study/ParentageCompleted.sql new file mode 100644 index 000000000..044c4946f --- /dev/null +++ b/onprc_ehr/resources/queries/study/ParentageCompleted.sql @@ -0,0 +1,37 @@ + + + +SELECT + + d.Id.curLocation.area as Area, + d.Id.curLocation.room as Room, + d.Id.curLocation.cage as Cage, + d.Id, + (select e.groupId.name from study.animal_group_members e where e.Id = d.id and e.qcstate = 18 And e.enddate is null) as Project, ------- assigned groups, + d.gender.meaning as gender, + d.calculated_status.code as livestatus, + d.birth as birthdate, + d.Id.MostRecentWeight.MostRecentWeight as currentweight , + d.Id.MostRecentWeight.MostRecentWeightDate as weightdate, + + coalesce(b.dam, '') as observeddam, + coalesce(p2.parent, '') as geneticdam, + coalesce(p3.parent, '') as fosterdam + + +FROM study.demographics d + +LEFT JOIN ( + select p2.id, min(p2.method) as method, max(p2.parent) as parent + FROM study.parentage p2 + WHERE (p2.method = 'Genetic' OR p2.method = 'Provisional Genetic') AND p2.relationship = 'Dam' --AND p2.enddate IS NULL + GROUP BY p2.Id +) p2 ON (d.Id = p2.id) +LEFT JOIN ( + select p3.id, min(p3.method) as method, max(p3.parent) as parent + FROM study.parentage p3 + WHERE p3.relationship = 'Foster Dam' + GROUP BY p3.Id +) p3 ON (d.Id = p3.id) +LEFT JOIN study.birth b ON (b.id = d.id ) +Where d.calculated_status.code = 'Alive' And d.qcstate = 18 \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/ParentageCompleted/.qview.xml b/onprc_ehr/resources/queries/study/ParentageCompleted/.qview.xml new file mode 100644 index 000000000..a4fac810f --- /dev/null +++ b/onprc_ehr/resources/queries/study/ParentageCompleted/.qview.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species.query.xml b/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species.query.xml new file mode 100644 index 000000000..7e30923d8 --- /dev/null +++ b/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species.query.xml @@ -0,0 +1,15 @@ + + + + + Protocol Housing Summary By Specie + + + Total Animals + /query/executeQuery.view?schemaName=study&query.queryName=demographics&query.viewName=By Location&query.id/demographics/species~eq=${species}&query.id/activeAssignments/protocols~contains=${protocol/displayName} + + +
+
+
+
diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.316-12.317.sql b/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species.sql similarity index 72% rename from onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.316-12.317.sql rename to onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species.sql index 052591f88..2f3db7999 100644 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.316-12.317.sql +++ b/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species.sql @@ -13,7 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +-- Created" 4-10-2019 R.Blasa +SELECT + a.project.protocol, + a.id.demographics.species, + count(distinct a.id) as totalAnimals -ALTER Table onprc_billing.invoiceRuns ADD billingPeriodStart datetime; -ALTER Table onprc_billing.invoiceRuns ADD billingPeriodEnd datetime; - \ No newline at end of file +FROM study.assignment a +WHERE a.isActive = true + +GROUP BY a.project.protocol, a.id.demographics.species \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species/.qview.xml b/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species/.qview.xml new file mode 100644 index 000000000..b0199058f --- /dev/null +++ b/onprc_ehr/resources/queries/study/ProtocolHousingSummary_Species/.qview.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/SLAOccupiedLocations.sql b/onprc_ehr/resources/queries/study/SLAOccupiedLocations.sql new file mode 100644 index 000000000..619608009 --- /dev/null +++ b/onprc_ehr/resources/queries/study/SLAOccupiedLocations.sql @@ -0,0 +1,13 @@ +SELECT +r.room, +r.building, +--c.room, +c.Species, +c.Date, +c.Animal_Count, +c.Cage_Count, +c.recentdate +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr_lookups.rooms r +Left join Site.{substitutePath moduleProperty('SLA','SLAContainer')}.sla.SLAMostRecentCensus c on r.room = c.room +Where r.housingType.value = 'Rodent Location' +and r.datedisabled is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetails.js b/onprc_ehr/resources/queries/study/StudyDetails.js new file mode 100644 index 000000000..43d63ca92 --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetails.js @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2010-2015 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +require("ehr/triggers").initScript(this); +var ONPRC_triggerHelper = new org.labkey.onprc_ehr.query.ONPRC_EHRTriggerHelper(LABKEY.Security.currentUser.id, LABKEY.Security.currentContainer.id); + +//Added by Kolli on 3/3/2020. This function automatically sets the study details endDate if previous study details endDate is empty when a new study is created. +function onComplete(event, errors, triggerHelper){ + if (!triggerHelper.isETL() && !triggerHelper.isValidateOnly()){ + var studyRows = triggerHelper.getRows(); + var idsToClose = []; + if (studyRows){ + for (var i=0;i + + + + + + Study Details + + + true + + + + Id + + + + Center Project + false + + + + Start Date + + + + End Date + + + + Study Cohort + + + + Study Group + + study + StudyDetails_group_values + value + + + + + Study Group # + + study + StudyDetails_cohort_values + value + + + + + Study Phase + + study + StudyDetails_phase_values + value + + + + + Remark + + + + + study + qcstate + RowId + + + + + Task Id + + ehr + tasks + taskid + + + + true + + + Performed by + + + true + + + + + true + + + + + true + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetailsHistory.query.xml b/onprc_ehr/resources/queries/study/StudyDetailsHistory.query.xml new file mode 100644 index 000000000..7e733f6e0 --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetailsHistory.query.xml @@ -0,0 +1,9 @@ + + + + + Study Details +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetailsHistory.sql b/onprc_ehr/resources/queries/study/StudyDetailsHistory.sql new file mode 100644 index 000000000..a449e3415 --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetailsHistory.sql @@ -0,0 +1,40 @@ +Select + Id, + project, project.protocol, project.protocol.investigatorId, + Date StartDate, endDate, + studyCohort, + studyGroup, + studyGroupNum, + studyPhase, + remark, + performedby, + Id.demographics.calculated_status, + Id.demographics.gender, + CASE + --if enddate is null and start date is before the current date - list current room & cage + WHEN endDate IS NULL AND Date <= curDate() THEN Id.curLocation.room + --if endate is null and start date is a future date - do not list room & cage + WHEN endDate IS NULL AND Date >= curDate() THEN NULL + --if enddate is before the current date - list room & cage at time of enddate + WHEN endDate <= curDate() AND Date <= curDate() THEN (Select h.room From housing h + Where (h.Id = Id) And (h.date <= endDate and h.enddateCoalesced >= endDate) ORDER BY h.date DESC LIMIT 1) + --if enddate is a future date and start date is before the current date - list current room & cage + WHEN endDate >= curDate() AND Date <= curDate() THEN Id.curLocation.room + ELSE NULL + END AS Room, + CASE + --if enddate is null and start date is before the current date - list current room & cage + WHEN endDate IS NULL AND Date <= curDate() THEN Id.curLocation.cage + --if endate is null and start date is a future date - do not list room & cage + WHEN endDate IS NULL AND Date >= curDate() THEN NULL + --if enddate is before the current date - list room & cage at time of enddate + WHEN endDate <= curDate() AND Date <= curDate() THEN (Select h.cage From housing h + Where (h.Id = Id) And (h.date <= endDate and h.enddateCoalesced >= endDate) ORDER BY h.date DESC LIMIT 1) + --(h.Id = Id And h.enddate IS NULL) + --OR (h.Id = Id And h.enddate IS NOT NULL And (endDate between h.date and h.enddate)) + --if enddate is a future date and start date is before the current date - list current room & cage + WHEN endDate >= curDate() AND Date <= curDate() THEN Id.curLocation.cage + ELSE NULL + END AS Cage, + taskid +From Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.StudyDetails \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetails_cohort_values.query.xml b/onprc_ehr/resources/queries/study/StudyDetails_cohort_values.query.xml new file mode 100644 index 000000000..34632182d --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetails_cohort_values.query.xml @@ -0,0 +1,15 @@ + + + + + Study Details + + + true + false + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetails_cohort_values.sql b/onprc_ehr/resources/queries/study/StudyDetails_cohort_values.sql new file mode 100644 index 000000000..91471de5e --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetails_cohort_values.sql @@ -0,0 +1,2 @@ +SELECT value, name, sort_order from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_ehr.StudyDetails_Reference_Data +where name like 'Study_Cohort' and dateDisabled is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetails_group_values.query.xml b/onprc_ehr/resources/queries/study/StudyDetails_group_values.query.xml new file mode 100644 index 000000000..34632182d --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetails_group_values.query.xml @@ -0,0 +1,15 @@ + + + + + Study Details + + + true + false + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetails_group_values.sql b/onprc_ehr/resources/queries/study/StudyDetails_group_values.sql new file mode 100644 index 000000000..f8cb8f492 --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetails_group_values.sql @@ -0,0 +1,2 @@ +SELECT value, name, sort_order from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_ehr.StudyDetails_Reference_Data +where name like 'Study_Group' and dateDisabled is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetails_phase_values.query.xml b/onprc_ehr/resources/queries/study/StudyDetails_phase_values.query.xml new file mode 100644 index 000000000..34632182d --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetails_phase_values.query.xml @@ -0,0 +1,15 @@ + + + + + Study Details + + + true + false + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/StudyDetails_phase_values.sql b/onprc_ehr/resources/queries/study/StudyDetails_phase_values.sql new file mode 100644 index 000000000..aa15a28e6 --- /dev/null +++ b/onprc_ehr/resources/queries/study/StudyDetails_phase_values.sql @@ -0,0 +1,2 @@ +SELECT value, name, sort_order from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_ehr.StudyDetails_Reference_Data +where name like 'Study_Phase' and dateDisabled is null \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.319-12.320.sql b/onprc_ehr/resources/queries/study/TBObservationArea.sql similarity index 81% rename from onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.319-12.320.sql rename to onprc_ehr/resources/queries/study/TBObservationArea.sql index e0dddf578..d11384424 100644 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.319-12.320.sql +++ b/onprc_ehr/resources/queries/study/TBObservationArea.sql @@ -13,5 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +SELECT + t.value, + t.label, + t.sort_order + + +FROM sla.Reference_Data t +where t.columnName = 'TBTestObserveArea' +And t.enddate is null + -ALTER Table onprc_billing.invoiceRuns ADD objectid entityid; diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.317-12.318.sql b/onprc_ehr/resources/queries/study/TBObservationsReport.sql similarity index 74% rename from onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.317-12.318.sql rename to onprc_ehr/resources/queries/study/TBObservationsReport.sql index 3256357b3..42777f1b9 100644 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.317-12.318.sql +++ b/onprc_ehr/resources/queries/study/TBObservationsReport.sql @@ -13,7 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +SELECT + t.id, + t.date, + t.category, + t.area, + t.observation, + t.remark, + t.performedby, + t.taskid, + t.qcstate, + +FROM study.clinical_observations t +where t.category like 'TB TST Score%' +And t.qcstate = 18 -ALTER Table onprc_billing.chargeableItems ADD itemCode varchar(100); -ALTER Table onprc_billing.chargeableItems ADD departmentCode varchar(100); -ALTER Table onprc_billing.invoicedItems ADD itemCode varchar(100); diff --git a/onprc_ehr/resources/queries/study/TBObservationsReport/.qview.xml b/onprc_ehr/resources/queries/study/TBObservationsReport/.qview.xml new file mode 100644 index 000000000..8cadb7526 --- /dev/null +++ b/onprc_ehr/resources/queries/study/TBObservationsReport/.qview.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.318-12.319.sql b/onprc_ehr/resources/queries/study/TBTestEnounters.sql similarity index 79% rename from onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.318-12.319.sql rename to onprc_ehr/resources/queries/study/TBTestEnounters.sql index 1006bd072..a6269d9d6 100644 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.318-12.319.sql +++ b/onprc_ehr/resources/queries/study/TBTestEnounters.sql @@ -13,7 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +SELECT + t.id, + t.date, + t.procedureid, + t.qcstate, + t.taskid + +FROM study.encounters t +where procedureid.name in ('TB Test Intradermal','TB Test Serologic') -ALTER Table onprc_billing.procedureFeeDefinition DROP COLUMN chargeType; -GO -ALTER Table onprc_billing.procedureFeeDefinition ADD billedby varchar(100); \ No newline at end of file diff --git a/onprc_ehr/resources/etl/ehr/treatment_times.sql b/onprc_ehr/resources/queries/study/TBTestSerologyLabResults.sql similarity index 63% rename from onprc_ehr/resources/etl/ehr/treatment_times.sql rename to onprc_ehr/resources/queries/study/TBTestSerologyLabResults.sql index acff8adf3..a454ccb8d 100644 --- a/onprc_ehr/resources/etl/ehr/treatment_times.sql +++ b/onprc_ehr/resources/queries/study/TBTestSerologyLabResults.sql @@ -1,5 +1,4 @@ -/* - * Copyright (c) 2013 LabKey Corporation +/* Copyright (c) 2013 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +14,23 @@ */ SELECT - m.objectid as treatmentid, - cln.objectid, - cast(cln.MedicationTime as int) as time + t.id, + t.date, + t.agent, + t.tissue, + t.result, + t.method, + t.remark, + t.units, + t.category, + t.numericresult, + t.qualifier, + t.requestid, + t.taskid, + t.qcstate -FROM Cln_MedicationTimes cln -left join Cln_Medications m on (m.SearchKey = cln.SearchKey) -where m.AnimalId is not null and cln.medicationtime is not null -and (cln.ts > ? or m.ts > ?) +FROM study.serology t +where t.agent in ('E-20170', 'E-20030') +and t.method like 'GIFT%' +And t.qcstate = 18 diff --git a/onprc_ehr/resources/queries/study/TBTestSerologyLabResults/.qview.xml b/onprc_ehr/resources/queries/study/TBTestSerologyLabResults/.qview.xml new file mode 100644 index 000000000..1d2a9332d --- /dev/null +++ b/onprc_ehr/resources/queries/study/TBTestSerologyLabResults/.qview.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/Tissue Measurements.js b/onprc_ehr/resources/queries/study/Tissue Measurements.js deleted file mode 100644 index fdc915f8c..000000000 --- a/onprc_ehr/resources/queries/study/Tissue Measurements.js +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - */ - -require("ehr/triggers").initScript(this); diff --git a/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr.query.xml b/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr.query.xml new file mode 100644 index 000000000..be13b4ba6 --- /dev/null +++ b/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr.query.xml @@ -0,0 +1,20 @@ + + + + + Tissue Distribution Summary + + + Total Samples + /query/executeQuery.view? + schemaName=study& + query.queryName=Tissue Distributions& + query.calendarYear~eq=${calendarYear}& + query.requestCategory~eq=${requestCategory}& + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr.sql b/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr.sql new file mode 100644 index 000000000..7df1aedd7 --- /dev/null +++ b/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr.sql @@ -0,0 +1,11 @@ +-- Created: 1-2-2-18 R.Blasa +SELECT + calendarYear, + t.requestCategory, + count(t.Id) as totalSamples, + count(distinct t.Id) as distinctAnimals, + count(distinct t.recipient) as distinctRecipients + +FROM study.tissueDistributions t + +GROUP BY calendarYear, t.requestCategory \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr/.qview.xml b/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr/.qview.xml new file mode 100644 index 000000000..ad537ace4 --- /dev/null +++ b/onprc_ehr/resources/queries/study/TissueDistributionSummaryCalendarYr/.qview.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr.query.xml b/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr.query.xml new file mode 100644 index 000000000..0ae656fcc --- /dev/null +++ b/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr.query.xml @@ -0,0 +1,20 @@ + + + + + Tissue Distribution Summary By Recipient + + + Total Samples + /query/executeQuery.view? + schemaName=study& + query.queryName=Tissue Distributions& + query.calendarYear~eq=${calendarYear}& + query.recipient~eq=${recipient}& + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr.sql b/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr.sql new file mode 100644 index 000000000..f6eed75eb --- /dev/null +++ b/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr.sql @@ -0,0 +1,13 @@ +-- Added: 1-2-2018 R.Blasa +SELECT + calendarYear, + t.recipient, + t.recipient.affiliation, + t.requestCategory, + count(t.Id) as totalSamples, + count(distinct t.Id) as distinctAnimals, + count(distinct t.recipient) as distinctRecipients, + +FROM study.tissueDistributions t + +GROUP BY calendarYear, t.recipient, t.recipient.affiliation, t.requestCategory \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr/.qview.xml b/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr/.qview.xml new file mode 100644 index 000000000..27d2df941 --- /dev/null +++ b/onprc_ehr/resources/queries/study/TissueDistributionSummarybyRecipientCalendarYr/.qview.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/TreatmentSchedulePostOps.sql b/onprc_ehr/resources/queries/study/TreatmentSchedulePostOps.sql index 91edad81a..1ef8ef9bf 100644 --- a/onprc_ehr/resources/queries/study/TreatmentSchedulePostOps.sql +++ b/onprc_ehr/resources/queries/study/TreatmentSchedulePostOps.sql @@ -1,94 +1,73 @@ /* * Copyright (c) 2015 LabKey Corporation - * * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - */ - -SELECT -h.id, -h.calculated_status, -s.*, -s.objectid as treatmentid, - ---Modified 7-2-2015 Blasa from d.qcstate to d.qcstate.label -(SELECT max(d.qcstate.label) as label FROM study.drug d WHERE s.objectid = d.treatmentid AND s.date = d.timeordered) as treatmentStatus + -- Modified by Kolli on 9/10/2019 +*/ +SELECT + h.id, + h.calculated_status, + --s.TreatmentStatus, + (SELECT max(d.qcstate.label) as label FROM study.drug d WHERE s.objectid = d.treatmentid and s.date = d.timeordered) as TreatmentStatus, + h.Id.curLocation.room as room, + h.Id.curLocation.cage as cage, + s.date, + s.startDate, + s.endDate, + s.dayselapsed, + s.category, + s.code, + s.code.meaning as medication, + s.volume, + s.vol_units, + s.concentration, + s.conc_units, + s.amountWithUnits, + s.amountAndVolume, + s.dosage, + s.dosage_units, + s.frequency, + s.route, + s.reason, + s.remark, + s.performedby FROM study.demographics h JOIN ( SELECT - s.*, - timestampadd('SQL_TSI_MINUTE', ((s.hours * 60) + s.minutes), s.origDate) as date, - CASE - WHEN (hours >= 6 AND hours < 20) THEN 'AM' - WHEN (hours < 6 OR hours >= 20) THEN 'PM' - ELSE 'Other' - END as timeOfDay, - - ((s.hours * 60) + s.minutes) as timeOffset - + s.animalid, s.TreatmentStatus, timestampadd('SQL_TSI_MINUTE', ((s.hours * 60) + s.minutes), s.origDate) as date, s.objectid, + s.startdate, s.enddate, s.dayselapsed, s.category, s.code, s.volume, s.vol_units, s.concentration, s.conc_units, + s.amountWithUnits, s.amountAndVolume, s.dosage, s.dosage_units, s.frequency, s.route, s.reason, s.remark, s.performedby FROM ( SELECT - t1.lsid, - t1.objectid, - t1.dataset, - t1.id as animalid, - - coalesce(tt.time, ft.hourofday, ((hour(t1.date) * 100) + minute(t1.date))) as time, - (coalesce(tt.time, ft.hourofday, (hour(t1.date) * 100)) / 100) as hours, - CASE - WHEN (tt.time IS NOT NULL OR ft.hourofday IS NOT NULL) THEN (((coalesce(tt.time, ft.hourofday) / 100.0) - floor(coalesce(tt.time, ft.hourofday) / 100)) * 100) - ELSE minute(t1.date) - END as minutes, - dr.date as origDate, - --ft.timedescription as timeOfDay, - CASE - WHEN (tt.time IS NULL) THEN 'Default' - ELSE 'Custom' - END as timeType, - - CASE - WHEN snomed.code IS NOT NULL THEN 'Post Op Meds' - ELSE t1.category - END as category, - --t1.category, - - t1.frequency.meaning as frequency, - t1.date as startDate, - timestampdiff('SQL_TSI_DAY', cast(t1.dateOnly as timestamp), dr.dateOnly) + 1 as daysElapsed, - t1.enddate, - --t1.duration, - t1.project, - t1.code, - - t1.volume, - t1.vol_units, - t1.concentration, - t1.conc_units, - t1.amount, - t1.amount_units, - t1.amountWithUnits, - t1.amountAndVolume, - t1.dosage, - t1.dosage_units, - t1.qualifier, - - t1.route, - t1.reason, - t1.performedby, - t1.remark, - --t1.description, - - t1.qcstate + t1.objectid, + t1.id as animalid, + (coalesce(tt.time, ft.hourofday, (hour(t1.date) * 100)) / 100) as hours, + + CASE + WHEN (tt.time IS NOT NULL OR ft.hourofday IS NOT NULL) THEN (((coalesce(tt.time, ft.hourofday) / 100.0) - floor(coalesce(tt.time, ft.hourofday) / 100)) * 100) + ELSE minute(t1.date) + END as minutes, + dr.date as origDate, + + CASE + WHEN snomed.code IS NOT NULL THEN 'Post Op Meds' + ELSE t1.category + END as category, + + t1.date as startDate, + timestampdiff('SQL_TSI_DAY', cast(t1.dateOnly as timestamp), dr.dateOnly) + 1 as daysElapsed, + t1.enddate, t1.code, t1.volume, t1.vol_units, t1.concentration, t1.conc_units, t1.amountWithUnits, + t1.amountAndVolume, t1.dosage, t1.dosage_units, t1.frequency.meaning + ' (' + t1.frequency.times + ')' as frequency, t1.route, + t1.reason, t1.performedby, t1.remark, t1.qcstate.label as TreatmentStatus FROM ehr_lookups.dateRange dr -JOIN study."Treatment Orders" t1 - --NOTE: should the enddate consider date/time? - ON (dr.dateOnly >= t1.dateOnly and dr.dateOnly <= t1.enddateCoalesced AND - --technically the first day of the treatment is day 1, not day 0 - mod(CAST(timestampdiff('SQL_TSI_DAY', CAST(t1.dateOnly as timestamp), dr.dateOnly) as integer), t1.frequency.intervalindays) = 0 - ) +Join study."Treatment Orders" t1 + ON (dr.dateOnly >= t1.dateOnly and dr.dateOnly <= t1.enddateCoalesced AND + mod(CAST(timestampdiff('SQL_TSI_DAY', CAST(t1.dateOnly as timestamp), dr.dateOnly) as integer), t1.frequency.intervalindays) = 0 + ) LEFT JOIN ehr.treatment_times tt ON (tt.treatmentid = t1.objectid) LEFT JOIN ehr_lookups.treatment_frequency_times ft ON (ft.frequency = t1.frequency.meaning AND tt.rowid IS NULL) @@ -104,13 +83,128 @@ INNER JOIN ( --NOTE: if we run this report on a future interval, we want to include those treatments WHERE t1.date is not null --NOTE: they have decided to include non-public data ---AND t1.qcstate.publicdata = true --and t1.dateOnly <= curdate() ) s ) s ON (s.animalid = h.id) - -WHERE h.calculated_status = 'Alive' - ---account for date/time in schedule -and s.date >= s.startDate and s.date <= s.enddate \ No newline at end of file + WHERE h.calculated_status = 'Alive' + --account for date/time in schedule + and s.date >= s.startDate and s.date <= s.enddate + + +-- /* +-- * Copyright (c) 2015 LabKey Corporation +-- * +-- * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 +-- */ +-- +-- SELECT +-- h.id, +-- h.calculated_status, +-- s.*, +-- s.objectid as treatmentid, +-- ---Modified 7-2-2015 Blasa from d.qcstate to d.qcstate.label +-- (SELECT max(d.qcstate.label) as label FROM study.drug d WHERE s.objectid = d.treatmentid AND s.date = d.timeordered) as treatmentStatus +-- +-- +-- FROM study.demographics h JOIN ( +-- +-- SELECT +-- s.*, +-- timestampadd('SQL_TSI_MINUTE', ((s.hours * 60) + s.minutes), s.origDate) as date, +-- CASE +-- WHEN (hours >= 6 AND hours < 20) THEN 'AM' +-- WHEN (hours < 6 OR hours >= 20) THEN 'PM' +-- ELSE 'Other' +-- END as timeOfDay, +-- +-- ((s.hours * 60) + s.minutes) as timeOffset +-- +-- FROM ( +-- +-- SELECT +-- t1.lsid, +-- t1.objectid, +-- t1.dataset, +-- t1.id as animalid, +-- +-- coalesce(tt.time, ft.hourofday, ((hour(t1.date) * 100) + minute(t1.date))) as time, +-- (coalesce(tt.time, ft.hourofday, (hour(t1.date) * 100)) / 100) as hours, +-- CASE +-- WHEN (tt.time IS NOT NULL OR ft.hourofday IS NOT NULL) THEN (((coalesce(tt.time, ft.hourofday) / 100.0) - floor(coalesce(tt.time, ft.hourofday) / 100)) * 100) +-- ELSE minute(t1.date) +-- END as minutes, +-- dr.date as origDate, +-- --ft.timedescription as timeOfDay, +-- CASE +-- WHEN (tt.time IS NULL) THEN 'Default' +-- ELSE 'Custom' +-- END as timeType, +-- +-- CASE +-- WHEN snomed.code IS NOT NULL THEN 'Post Op Meds' +-- ELSE t1.category +-- END as category, +-- --t1.category, +-- +-- t1.frequency.meaning as frequency, +-- t1.date as startDate, +-- timestampdiff('SQL_TSI_DAY', cast(t1.dateOnly as timestamp), dr.dateOnly) + 1 as daysElapsed, +-- t1.enddate, +-- --t1.duration, +-- t1.project, +-- t1.code, +-- +-- t1.volume, +-- t1.vol_units, +-- t1.concentration, +-- t1.conc_units, +-- t1.amount, +-- t1.amount_units, +-- t1.amountWithUnits, +-- t1.amountAndVolume, +-- t1.dosage, +-- t1.dosage_units, +-- t1.qualifier, +-- +-- t1.route, +-- t1.reason, +-- t1.performedby, +-- t1.remark, +-- --t1.description, +-- +-- t1.qcstate +-- +-- FROM ehr_lookups.dateRange dr +-- +-- JOIN study."Treatment Orders" t1 +-- --NOTE: should the enddate consider date/time? +-- ON (dr.dateOnly >= t1.dateOnly and dr.dateOnly <= t1.enddateCoalesced AND +-- --technically the first day of the treatment is day 1, not day 0 +-- mod(CAST(timestampdiff('SQL_TSI_DAY', CAST(t1.dateOnly as timestamp), dr.dateOnly) as integer), t1.frequency.intervalindays) = 0 +-- ) +-- +-- LEFT JOIN ehr.treatment_times tt ON (tt.treatmentid = t1.objectid) +-- LEFT JOIN ehr_lookups.treatment_frequency_times ft ON (ft.frequency = t1.frequency.meaning AND tt.rowid IS NULL) +-- +-- INNER JOIN ( +-- SELECT +-- sc.code +-- from ehr_lookups.snomed_subset_codes sc +-- WHERE sc.primaryCategory = 'Post Op Meds' +-- GROUP BY sc.code +-- ) snomed ON snomed.code = t1.code +-- +-- --NOTE: if we run this report on a future interval, we want to include those treatments +-- WHERE t1.date is not null +-- --NOTE: they have decided to include non-public data +-- --AND t1.qcstate.publicdata = true --and t1.dateOnly <= curdate() +-- +-- ) s +-- +-- ) s ON (s.animalid = h.id) +-- +-- WHERE h.calculated_status = 'Alive' +-- +-- --account for date/time in schedule +-- and s.date >= s.startDate and s.date <= s.enddate \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/Weight/Weight Details.qview.xml b/onprc_ehr/resources/queries/study/Weight/Weight Details.qview.xml new file mode 100644 index 000000000..ab41e5154 --- /dev/null +++ b/onprc_ehr/resources/queries/study/Weight/Weight Details.qview.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/alopeciaData.sql b/onprc_ehr/resources/queries/study/alopeciaData.sql index 8817c8ef6..e6f1f0269 100644 --- a/onprc_ehr/resources/queries/study/alopeciaData.sql +++ b/onprc_ehr/resources/queries/study/alopeciaData.sql @@ -14,38 +14,34 @@ * limitations under the License. */ SELECT -pvt.*, -grp.performedBy -FROM -(SELECT - o.Id, - max(o.date) as date, - o.taskId, - o.category, - (SELECT group_concat(distinct d.code.meaning) as code FROM study.drug d WHERE d.Id = o.Id AND d.taskId = o.taskId AND d.code IN ('E-70590', 'E-YY992')) as sedation, - group_concat(DISTINCT o.observation, ',') as observation, - (SELECT group_concat(distinct room) as rooms - FROM study.housing h - WHERE h.Id = o.Id AND h.date <= max(o.date) AND h.enddateTimeCoalesced >= timestampadd('SQL_TSI_DAY', -30, max(o.date))) as rooms, - (SELECT group_concat(distinct room.area) as areas FROM study.housing h - WHERE h.Id = o.Id AND h.date <= max(o.date) AND h.enddateTimeCoalesced >= timestampadd('SQL_TSI_DAY', -30, max(o.date))) as areas +o.Id, +o.taskId, +o.Id.Demographics.species as Specie, +o.Id.demographics.gender as Gender, +max(o.date) as date, +o.dateMonthNumber as MonthNumber, +o.ageAtTime.AgeAtTimeYearsRounded as AgeTimeYears, +o.category, +(SELECT group_concat(distinct d.code.meaning) as code FROM study.drug d WHERE d.Id = o.Id AND d.taskId = o.taskId AND d.code IN ('E-70590', 'E-YY992')) as sedation, +group_concat(DISTINCT o.observation, ',') as observation, +group_concat(DISTINCT o.remark, ',') as remark, +max(o.performedby) as performedBy, +max(o.housingAtTime.RoomAtTime) as RoomAtTime, +max(o.groupsAtTime.groupsAtTime) as GroupAtTime, +(SELECT group_concat(distinct room) as rooms FROM study.housing h +WHERE h.Id = o.Id + AND h.date <= max(o.date) + AND h.enddateTimeCoalesced >= timestampadd('SQL_TSI_DAY', -30, max(o.date)) +) as rooms, +(SELECT group_concat(distinct room.area) as areas FROM study.housing h +WHERE h.Id = o.Id + AND h.date <= max(o.date) + AND h.enddateTimeCoalesced >= timestampadd('SQL_TSI_DAY', -30, max(o.date)) +) as areas FROM study.clinical_observations o WHERE o.category IN ('Alopecia Score', 'Alopecia Type', 'Alopecia Regrowth') --note: this is a fairly arbitrary cutoff, used because we only started tracking these measures after this date and date > '2014-05-01' -GROUP BY o.Id, o.taskId, o.category -PIVOT observation BY category IN ('Alopecia Score', 'Alopecia Type', 'Alopecia Regrowth')) pvt - -LEFT OUTER JOIN - -(SELECT - b.Id, - b.taskId, - group_concat(DISTINCT b.performedby, ',') as performedBy - FROM study.clinical_observations b -WHERE b.category IN ('Alopecia Score', 'Alopecia Type', 'Alopecia Regrowth') -and date > '2014-05-01' -GROUP BY b.Id, b.taskId) grp - -ON pvt.Id = grp.Id AND pvt.taskId = grp.taskId \ No newline at end of file +GROUP BY o.Id, o.taskId, o.Id.Demographics.species, o.Id.demographics.gender,o.dateMonthNumber,o.ageAtTime.AgeAtTimeYearsRounded , o.category +PIVOT observation,remark BY category IN ('Alopecia Score', 'Alopecia Type', 'Alopecia Regrowth') diff --git a/onprc_ehr/resources/queries/study/alopeciaData/.qview.xml b/onprc_ehr/resources/queries/study/alopeciaData/.qview.xml index 336b92006..8bb4cadc1 100644 --- a/onprc_ehr/resources/queries/study/alopeciaData/.qview.xml +++ b/onprc_ehr/resources/queries/study/alopeciaData/.qview.xml @@ -1,15 +1,22 @@ + + - - - + + + + + + + + diff --git a/onprc_ehr/resources/queries/study/assignment.query.xml b/onprc_ehr/resources/queries/study/assignment.query.xml new file mode 100644 index 000000000..94c371565 --- /dev/null +++ b/onprc_ehr/resources/queries/study/assignment.query.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + ehr + project + project + + + + Assign Date + Date + + + Projected Release Date + + + Release Date + false + true + true + Date + + + true + + + + + + + + + + Assignment Type + false + + study + AssignmentTypes + value + value + + + + Condition At Assignment + + ehr_lookups + animal_condition + code + + + + Projected Release Condition + + ehr_lookups + animal_condition + code + + + + + Condition At Release + + ehr_lookups + animal_condition + code + + + + true + + + Release Type + + ehr_lookups + assignmentReleaseType + value + + + + Date Assignment End Entered + This records the date the end of the assignment was actually entered, which may differ from the enddate itself + true + + + CoAssignments + false + true + + study + assignmentTotalCoAssigned + lsid + + + +
+
+
+
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/assignment/.qview.xml b/onprc_ehr/resources/queries/study/assignment/.qview.xml index 90d4e430e..f17bd295a 100644 --- a/onprc_ehr/resources/queries/study/assignment/.qview.xml +++ b/onprc_ehr/resources/queries/study/assignment/.qview.xml @@ -30,6 +30,7 @@ + diff --git a/onprc_ehr/resources/queries/study/birth_resourceDam.sql b/onprc_ehr/resources/queries/study/birth_resourceDam.sql new file mode 100644 index 000000000..53bd493fd --- /dev/null +++ b/onprc_ehr/resources/queries/study/birth_resourceDam.sql @@ -0,0 +1,14 @@ +SELECT b.Id, +b.date, +b.date_type, +b.birth_condition, +b.room, +b.cage, +b.dam, +b.gender, +b.species, +a.project.use_category, +a.project as DammProject + +FROM birth b join study.assignment a on b.dam = a.id +where a.project.use_Category not in ('Research','Aging Resources') \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/bloodCalcCriteria.sql b/onprc_ehr/resources/queries/study/bloodCalcCriteria.sql new file mode 100644 index 000000000..7dc60b4b6 --- /dev/null +++ b/onprc_ehr/resources/queries/study/bloodCalcCriteria.sql @@ -0,0 +1,29 @@ +SELECT d.id, +d.species, +d.gender, +d.DaysAge, +d.MostRecentWeight as weight, +d.MostRecentWeightDate, +d.date, +d.score as bcs, +d.blood_per_kg as bpk, +d.blood_draw_interval as interval, +d.max_draw_pct as Percentage, +Case + When d.species <> 'Rhesus Macaque' then 'Fixed Rate by Speices' + WHen d.score is Null then 'Fixed Rate no BCS' + when TIMESTAMPDIFF('SQL_TSI_DAY',d.date,Now()) > 548 Then 'Fixed Rate BCS out of Date' + when d.DaysAge < 730 then 'Fixed Rate NHP Too Young' + + else 'BCS' + End as CalcMethodReason, +Case + When d.species <> 'Rhesus Macaque' then 'Fr' + WHen d.score is Null then 'fr' + when TIMESTAMPDIFF('SQL_TSI_DAY',d.date,Now()) > 548 Then 'fr' + when d.DaysAge < 730 then 'Fr' + + else 'BCS' + End as CalcMethod + +FROM blooddrawDemographics d \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/bloodCalcFixedRate.sql b/onprc_ehr/resources/queries/study/bloodCalcFixedRate.sql new file mode 100644 index 000000000..1e36afc2b --- /dev/null +++ b/onprc_ehr/resources/queries/study/bloodCalcFixedRate.sql @@ -0,0 +1,17 @@ +SELECT c.id, +c.species, +c.gender, +c.DaysAge, +c.Weight, +c.MostRecentWeightDate, +c.date as BCSDate, +c.bcs as BCSScore, +c.CalcMethod, +c.bpk, +c.interval, +c.Percentage, +c.CalcMethodReason, +(c.bpk*c.Weight) as TOtalBloodVolume + +FROM bloodCalcCriteria c +WHere c.CalcMethod = 'FR' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/bloodCalcPastandFuture.sql b/onprc_ehr/resources/queries/study/bloodCalcPastandFuture.sql new file mode 100644 index 000000000..e26199119 --- /dev/null +++ b/onprc_ehr/resources/queries/study/bloodCalcPastandFuture.sql @@ -0,0 +1,36 @@ +/* +* 2017/9/20 Updated statement to handle an issue where records where the qc state was set to deleted, caancelled or pending approval were being +* marked as counts against volume. The method used here was to determine the current qcstate and exclude these values + */ + +Select bd.id, +0 as FutureDraws, +bd.qcState, +COALESCE + +(Sum(bd.quantity),0) as PreviousDraws + + +from blood bd join study.bloodCalcTotalAllowableBlood d on bd.id = d.id +where +bd.dateOnly >= cast(TIMESTAMPADD('SQL_TSI_DAY', -1 * d.species.blood_draw_interval, now()) as date) +AND bd.dateOnly <= cast(curdate() as date) +--and (bd.countsAgainstVolume = true) +and bd.QCState not in (19,22,23,27) +group by bd.id,bd.qcstate + +Union + +Select bd.id, + +COALESCE + +(Sum(bd.quantity),0) as FutureDraws, +bd.qcState, +0 as PreviousDraws +from blood bd join study.bloodCalcTotalAllowableBlood d on bd.id = d.id +where bd.dateOnly <= cast(TIMESTAMPADD('SQL_TSI_DAY', d.species.blood_draw_interval, curdate()) as date) + AND bd.dateOnly >= cast(curdate() as date) +--and (bd.countsAgainstVolume = true) +and bd.QCState not in (19,22,23,27) +group by bd.id,bd.qcstate diff --git a/onprc_ehr/resources/queries/study/bloodCalcTotalAllowableBlood.sql b/onprc_ehr/resources/queries/study/bloodCalcTotalAllowableBlood.sql new file mode 100644 index 000000000..cacd9355f --- /dev/null +++ b/onprc_ehr/resources/queries/study/bloodCalcTotalAllowableBlood.sql @@ -0,0 +1,24 @@ +SELECT c.id, +c.species, +c.gender, +c.DaysAge, +c.weight, +c.MostRecentWeightDate, +c.date, +c.bcs, +c.bpk, +c.interval, +c.Percentage, +c.CalcMethodReason, +c.CalcMethod, +(Select fr.totalBloodVolume from study,bloodcalcFixedRate fr where c.id = fr.id) as TotalBloodVolumeFR, +(Select b.bcstbv from study.Bloodcalcbcs b where c.id = b.id) as TotalBloodVolumeBCS, + +CAST( +Case + When c.CalcMethod = 'fr' then + (Select (fr.totalBloodVolume * c.percentage) as frtba from study,bloodcalcFixedRate fr where c.id = fr.id) + When c.calcMethod = 'BCS' then + (Select (b.bcstbv * c.percentage) as bcstba from study.Bloodcalcbcs b where c.id = b.id) + End AS DOUBLE) as ABV +FROM bloodCalcCriteria c \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/bloodCalcTotalAvailableBlood.sql b/onprc_ehr/resources/queries/study/bloodCalcTotalAvailableBlood.sql new file mode 100644 index 000000000..e58ebf0c0 --- /dev/null +++ b/onprc_ehr/resources/queries/study/bloodCalcTotalAvailableBlood.sql @@ -0,0 +1,22 @@ +SELECT a.id, +a.species, +a.gender, +a.DaysAge, +a.weight, +a.MostRecentWeightDate, +a.date, +a.bcs, +a.bpk, +a.interval, +a.Percentage, +a.CalcMethodReason, +a.CalcMethod, +a.ABV as TotalAllowableBlood, +fp.PreviousDraws, +fp.futureDraws, +Case + When fp.PReviousDraws > fp.futureDraws then (a.ABV - fp.PReviousDraws) + When fp.FutureDraws > fp.PReviousDraws then (a.abv - fp.futureDraws) + else ABV + End as TotalAvailableBlood +FROM bloodCalcTotalAllowableBlood a left outer join bloodCalcPastandFuture fp on a.id = fp.id \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/blooddrawDemographics.sql b/onprc_ehr/resources/queries/study/blooddrawDemographics.sql new file mode 100644 index 000000000..0c23c2cf6 --- /dev/null +++ b/onprc_ehr/resources/queries/study/blooddrawDemographics.sql @@ -0,0 +1,35 @@ +/**** +2017/1-/15 Issue with Blank G +Tores o resolve the issue of BCS Score being blank, I changed the source from the demographcis Table to a direct read from BCS + + +*** */ + + +select +d.id, +d.species, +d.gender, +Case + when b.date is not null then TIMESTAMPDIFF('SQL_TSI_Day', b.date,Now()) + else (Select TIMESTAMPDIFF('SQL_TSI_Day', a.date,Now()) from study.arrival a where a.id = d.id ) + End as DaysAge, +--d.id.age.ageinDays as DaysAge, +w.MostRecentWeight, +w.MostRecentWeightDate, + +--d.Id.mostRecentBCS.date, +--d.Id.mostRecentBCS.score, +mbcs.date, +mbcs.score, +d.species.max_draw_pct , +d.species.blood_draw_interval, + d.species.blood_per_kg + + +from study.demographics d + left outer join study.birth b on d.id = b.id + left outer join study.demographicsMostRecentWeight w on d.id = w.id + left outer join demographicsMostRecentBCS mbcs on mbcs.id = d.id +where d.calculated_status = 'Alive' +and d.ID not like '[a-z]%' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/chemPivot.query.xml b/onprc_ehr/resources/queries/study/chemPivot.query.xml index ff96cd5d8..e52ee4ce3 100644 --- a/onprc_ehr/resources/queries/study/chemPivot.query.xml +++ b/onprc_ehr/resources/queries/study/chemPivot.query.xml @@ -18,7 +18,8 @@ Id - + + Testing Performed By
diff --git a/onprc_ehr/resources/queries/study/chemPivot.sql b/onprc_ehr/resources/queries/study/chemPivot.sql index bb7a12e6e..cd3f3f8ce 100644 --- a/onprc_ehr/resources/queries/study/chemPivot.sql +++ b/onprc_ehr/resources/queries/study/chemPivot.sql @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013-2016 LabKey Corporation + * Copyright (c) 2013-2017 LabKey Corporation * * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 */ @@ -13,7 +13,7 @@ FROM b.Id, b.date, b.method, - b.chargetype, ---Added 9-14-2015 Blasa + b.performedby, ---Added 2-21-2020 R.Blasa b.testId, group_concat(b.result) as results FROM ( @@ -26,7 +26,7 @@ FROM --NOTE: removed to allow legacy runs to group into 1 row. since we already group on Id/Date/Test, this should be ok --coalesce(b.taskId, b.runId) as groupingId, b.runid.method as method, - b.runid.chargetype as chargetype, ---Added 9-14-2015 Blasa + b.performedby, ---Added 2-21-2020 R.Blasa b.remark, b.runId.remark as runRemark, b.resultoorindicator, @@ -39,8 +39,8 @@ FROM ) b - --Updated 6-3-2015 Blasa - GROUP BY b.runid,b.id, b.date, b.testId, b.method, b.chargetype + ---Updated 2-21-2020 Blasa + GROUP BY b.runid,b.id, b.date, b.testId, b.method, b.performedby PIVOT results BY testId IN (select testid from ehr_lookups.chemistry_tests t WHERE t.includeInPanel = true order by sort_order)) pivot_ LEFT OUTER JOIN @@ -48,7 +48,7 @@ LEFT OUTER JOIN (SELECT group_concat(distinct d.remark, chr(10)) as remark, group_concat(distinct d.runRemark, chr(10)) as runRemark, - d.runid,d.id, d.date, d.method, d.chargetype + d.runid,d.id, d.date, d.method FROM ( @@ -59,7 +59,6 @@ LEFT OUTER JOIN --NOTE: removed to allow legacy runs to group into 1 row. since we already group on Id/Date/Test, this should be ok --coalesce(b.taskId, b.runId) as groupingId, d.runid.method as method, - d.runid.chargetype as chargetype, ---Added 9-14-2015 Blasa d.remark, d.runId.remark as runRemark, d.resultoorindicator, @@ -73,7 +72,7 @@ LEFT OUTER JOIN ) d --Updated 6-3-2015 Blasa - GROUP BY d.runid,d.id, d.date, d.method, d.chargetype) grp + GROUP BY d.runid,d.id, d.date, d.method) grp -ON pivot_.runId = grp.runId AND pivot_.id = grp.id AND pivot_.date = grp.date AND pivot_.method = grp.method AND pivot_.chargetype = grp.chargetype +ON pivot_.runId = grp.runId AND pivot_.id = grp.id AND pivot_.date = grp.date AND pivot_.method = grp.method diff --git a/onprc_ehr/resources/queries/study/chemistryRefRange.sql b/onprc_ehr/resources/queries/study/chemistryRefRange.sql index 2a161f356..f787cb8b5 100644 --- a/onprc_ehr/resources/queries/study/chemistryRefRange.sql +++ b/onprc_ehr/resources/queries/study/chemistryRefRange.sql @@ -33,7 +33,8 @@ END as status, c.remark, c.taskid, c.runId, -c.qcstate +c.qcstate, + r.type FROM ( SELECT @@ -53,6 +54,7 @@ FROM ( c.date, c.runId, c.remark, + c.type, ROUND(CONVERT(age_in_months(c.id.dataset.demographics.birth, c.date), DOUBLE) / 12.0, 1) as ageAtTime FROM "Chemistry Results" c WHERE c.qcstate.publicdata = true @@ -66,9 +68,9 @@ FROM ( LEFT JOIN ehr_lookups.lab_test_range r ON ( c.testId = r.test AND - c.species = r.species AND + (c.species = r.species or (c.species is not null and r.species is null)) AND --(ac.ageClass = r.age_class OR (ac.ageClass IS NULL AND r.age_class IS NULL)) AND - c.gender = r.gender and - r.type = 'Chemistry' + (c.gender = r.gender or (c.gender is not null and r.gender is null)) and + coalesce(c.type,'Biochemistry') = r.type ) diff --git a/onprc_ehr/resources/queries/study/clinicalCases.sql b/onprc_ehr/resources/queries/study/clinicalCases.sql index 6f1a97984..487cffa1d 100644 --- a/onprc_ehr/resources/queries/study/clinicalCases.sql +++ b/onprc_ehr/resources/queries/study/clinicalCases.sql @@ -25,7 +25,8 @@ SELECT c.remark, c.mostRecentP2, c.isActive, - c.assignedvet + c.assignedvet, + c.mostRecentCeg_Plan FROM study.cases c WHERE c.isActive = true AND c.category = 'Clinical' @@ -33,9 +34,8 @@ WHERE c.isActive = true AND c.category = 'Clinical' UNION ALL SELECT - d.Id, - d.date, - + h.Id, + h.date, null as enddate, null as reviewdate, null as category, @@ -45,7 +45,9 @@ SELECT null as remark, null as mostrecentP2, null as isActive, - null as assignedVet + null as assignedVet, + null as mostRecentCeg_Plan -FROM study.demographicsCurrentLocation d -WHERE d.area = 'Hospital' AND (d.Id.activecases.categories NOT LIKE '%Clinical%' OR d.Id.activecases.categories IS NULL) \ No newline at end of file +FROM study.housing h +WHERE h.room.area = 'Hospital' and h.enddate is null +and h.id not in (Select c1.id from study.cases c1 where c1.id = h.id and c1.IsActive = true) diff --git a/onprc_ehr/resources/queries/study/Clinical Remarks/.qview.xml b/onprc_ehr/resources/queries/study/clinremarks/.qview.xml similarity index 94% rename from onprc_ehr/resources/queries/study/Clinical Remarks/.qview.xml rename to onprc_ehr/resources/queries/study/clinremarks/.qview.xml index 5e6eb94af..9f5ac339e 100644 --- a/onprc_ehr/resources/queries/study/Clinical Remarks/.qview.xml +++ b/onprc_ehr/resources/queries/study/clinremarks/.qview.xml @@ -6,6 +6,7 @@ + diff --git a/onprc_ehr/resources/queries/study/Clinical Remarks/Behavior Remarks.qview.xml b/onprc_ehr/resources/queries/study/clinremarks/Behavior Remarks.qview.xml similarity index 100% rename from onprc_ehr/resources/queries/study/Clinical Remarks/Behavior Remarks.qview.xml rename to onprc_ehr/resources/queries/study/clinremarks/Behavior Remarks.qview.xml diff --git a/onprc_ehr/resources/queries/study/clinremarks/CEG_Plan.qview.xml b/onprc_ehr/resources/queries/study/clinremarks/CEG_Plan.qview.xml new file mode 100644 index 000000000..0bc73f1c6 --- /dev/null +++ b/onprc_ehr/resources/queries/study/clinremarks/CEG_Plan.qview.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/Clinical Remarks/SOAP Note.qview.xml b/onprc_ehr/resources/queries/study/clinremarks/SOAP Note.qview.xml similarity index 100% rename from onprc_ehr/resources/queries/study/Clinical Remarks/SOAP Note.qview.xml rename to onprc_ehr/resources/queries/study/clinremarks/SOAP Note.qview.xml diff --git a/onprc_ehr/resources/queries/study/currentBloodAvailable.sql b/onprc_ehr/resources/queries/study/currentBloodAvailable.sql deleted file mode 100644 index f090a8d81..000000000 --- a/onprc_ehr/resources/queries/study/currentBloodAvailable.sql +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2013-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -* 8/8/2016 gJones This needs to be dependant on demograhics blood panel - - - - - */ - -SELECT - t.id, - t.date, - cast(t.quantity as double) as quantity, - t.species, - t.max_draw_pct, - t.blood_draw_interval, - t.blood_per_kg, - t.mostRecentWeight, - t.mostRecentWeightDate, - cast(t.allowableBlood as double) as maxAllowableBlood, - cast(t.bloodPrevious as double) as bloodPrevious, - cast((t.allowableBlood - t.bloodPrevious) as double) as allowablePrevious, - - cast(t.bloodFuture as double) as bloodFuture, - cast((t.allowableBlood - t.bloodFuture) as double) as allowableFuture, - - --if the draw is historic, always consider previous draws only. - --otherwise, look both forward and backwards, then take the interval with the highest volume - cast(case - WHEN t.date < curdate() THEN (t.allowableBlood - t.bloodPrevious) - WHEN t.bloodPrevious < t.bloodFuture THEN (t.allowableBlood - t.bloodFuture) - ELSE (t.allowableBlood - t.bloodPrevious) - end as double) as allowableBlood, - t.minDate, - t.maxDate - -FROM ( - -SELECT - bd.id, - bd.dateOnly as date, - bd.quantity, - d.species, - d.id.mostRecentWeight.MostRecentWeight, - d.id.mostRecentWeight.MostRecentWeightDate, - d.species.blood_per_kg, - d.species.max_draw_pct, - bd.blood_draw_interval, - b.allowableBlood, - bd.minDate, - bd.maxDate, - COALESCE( - (SELECT SUM(coalesce(draws.quantity, 0)) AS _expr - FROM study."Blood Draws" draws - WHERE draws.id = bd.id - AND draws.dateOnly > bd.minDate - AND draws.dateOnly <= bd.dateOnly - --NOTE: this has been changed to include penidng/non-approved draws - AND draws.countsAgainstVolume = true - ), 0) AS BloodPrevious, - - COALESCE( - (SELECT SUM(coalesce(draws.quantity, 0)) AS _expr - FROM study."Blood Draws" draws - WHERE draws.id = bd.id - AND draws.dateOnly < bd.maxDate - AND draws.dateOnly >= bd.dateOnly - --NOTE: this has been changed to include penidng/non-approved draws - AND draws.countsAgainstVolume = true - ), 0) AS BloodFuture - -FROM study.bloodDrawChanges bd -JOIN study.DemographicsBloodSummary b on (b.id = bd.id) -join study.demographics d ON (d.id = bd.id) - -) t \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/currentBloodDraws.query.xml b/onprc_ehr/resources/queries/study/currentBloodDraws.query.xml deleted file mode 100644 index b061db414..000000000 --- a/onprc_ehr/resources/queries/study/currentBloodDraws.query.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - Current Blood Draws - - - 0.## - - - 0.## - Maximum allowable blood - - - 0.## - Blood drawn over interval, looking backwards - - - 0.## - Max allowable blood, accounting for previous draws only - - - 0.## - Blood drawn over interval, looking forwards - - - 0.## - Max allowable blood, accounting for future draws only - - - 0.## - Max allowable blood on this date - - -
-
-
-
\ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/currentBloodDraws.sql b/onprc_ehr/resources/queries/study/currentBloodDraws.sql index ab11c1e06..ebf5fa62e 100644 --- a/onprc_ehr/resources/queries/study/currentBloodDraws.sql +++ b/onprc_ehr/resources/queries/study/currentBloodDraws.sql @@ -17,71 +17,18 @@ */ SELECT - t.id, - t.date, - cast(t.quantity as double) as quantity, - t.species, - t.max_draw_pct, - t.blood_draw_interval, - t.blood_per_kg, - t.mostRecentWeight, - t.mostRecentWeightDate, - cast(t.allowableBlood as double) as maxAllowableBlood, - cast(t.bloodPrevious as double) as bloodPrevious, - cast((t.allowableBlood - t.bloodPrevious) as double) as allowablePrevious, + bs.id + ,bs.gender + ,bs.species + ,bs.yoa as YearofBirth + ,bs.mostrecentweightdate + ,bs.weight as MostRecentWeight + ,bs.calcmethod as CalculationMethod + ,bs.BCS as MostRecentBCS + ,bs.BCSage + ,bs.previousdraws + ,bs.ABV as TotalAvailableBlood - cast(t.bloodFuture as double) as bloodFuture, - cast((t.allowableBlood - t.bloodFuture) as double) as allowableFuture, - --if the draw is historic, always consider previous draws only. - --otherwise, look both forward and backwards, then take the interval with the highest volume - cast(case - WHEN t.date < curdate() THEN (t.allowableBlood - t.bloodPrevious) - WHEN t.bloodPrevious < t.bloodFuture THEN (t.allowableBlood - t.bloodFuture) - ELSE (t.allowableBlood - t.bloodPrevious) - end as double) as allowableBlood, - t.minDate, - t.maxDate -FROM ( - -SELECT - bd.id, - bd.dateOnly as date, - bd.quantity, - d.species, - d.id.mostRecentWeight.MostRecentWeight, - d.id.mostRecentWeight.MostRecentWeightDate, - d.species.blood_per_kg, - d.species.max_draw_pct, - bd.blood_draw_interval, - bs.availableblood, - bs.allowableBlood, - -- (d.id.mostRecentWeight.MostRecentWeight * d.species.blood_per_kg * d.species.max_draw_pct) as allowableBlood, - bd.minDate, - bd.maxDate, - COALESCE( - (SELECT SUM(coalesce(draws.quantity, 0)) AS _expr - FROM study."Blood Draws" draws - WHERE draws.id = bd.id - AND draws.dateOnly > bd.minDate - AND draws.dateOnly <= bd.dateOnly - --NOTE: this has been changed to include penidng/non-approved draws - AND draws.countsAgainstVolume = true - ), 0) AS BloodPrevious, - - COALESCE( - (SELECT SUM(coalesce(draws.quantity, 0)) AS _expr - FROM study."Blood Draws" draws - WHERE draws.id = bd.id - AND draws.dateOnly < bd.maxDate - AND draws.dateOnly >= bd.dateOnly - --NOTE: this has been changed to include penidng/non-approved draws - AND draws.countsAgainstVolume = true - ), 0) AS BloodFuture - -FROM study.bloodDrawChanges bd -JOIN study.demographics d ON (d.id = bd.id) -Join demographicsBloodSummary bs on (bs.id = bd.id) - -) t \ No newline at end of file +FROM demographicsBloodSummary bs diff --git a/onprc_ehr/resources/queries/study/demographicsAssignedVet.sql b/onprc_ehr/resources/queries/study/demographicsAssignedVet.sql index d7fe7474a..bdc172201 100644 --- a/onprc_ehr/resources/queries/study/demographicsAssignedVet.sql +++ b/onprc_ehr/resources/queries/study/demographicsAssignedVet.sql @@ -1,121 +1,73 @@ -/* - * Copyright (c) 2014-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -SELECT - d.Id, - COALESCE(n.assignedVet,c.vetNames, h.highPriRoomVetNames, h.highPriAreaVetNames, a1.vetName,a2.vetName, h.roomVetNames, h.areaVetNames) as assignedVet, - --COALESCE(c.vetUserIds, h.highPriRoomVetUserIds, h.highPriAreaVetUserIds, a.vetUserIds, h.roomVetUserIds, h.areaVetUserIds) as assignedVetId, - CASE - WHEN (n.status IS NOT null) THEN 'DECEASED NHP' - WHEN (c.vetNames IS NOT NULL) THEN 'Active Case' - WHEN (h.highPriRoomVetNames IS NOT NULL) THEN 'Room (Priority)' - WHEN (h.highPriAreaVetNames IS NOT NULL) THEN 'Area (Priority)' - WHEN (a1.vetName IS NOT NULL) THEN 'Research Assignment' - WHEN (a2.vetName IS NOT NULL) THEN 'Resource Assignment' - WHEN (h.roomVetNames IS NOT NULL) THEN 'Room' - WHEN (h.areaVetNames IS NOT NULL) THEN 'Area' - ELSE 'None' - END as assignmentType, - a1.protocol as ResearchProtocol, - a2.protocol as ResourceProtocol, - h.areas, - h.rooms - -FROM study.demographics d - -LEFT JOIN ( - Select - n.id, - vd.assignedVet, - 'Deceased' as status - from study.deaths n left outer join study.vetAssignedDeceased vd on n.Id = vd.id - -) - n on (n.Id =d.id) - -LEFT JOIN ( - SELECT - c.Id, - group_concat(distinct c.assignedvet.DisplayName) as vetNames, - CAST(group_concat(distinct c.assignedvet) as varchar(200)) as vetUserIds - FROM study.cases c - --WHERE c.isOpen = true - WHERE c.enddateCoalesced >= curdate() OR CAST(c.enddate AS DATE) = CAST(c.Id.demographics.lastDayAtCenter AS DATE) - GROUP BY c.Id -) c ON (c.Id = d.Id) - ---LEFT JOIN( ---Select cr.assignedVet ---from study.clinremarks cr) ---cr ON (cr.id = d.Id) --- ---need to insure we get the last record in Clinical Remarks for the animal. --- --- --- ---) - - -LEFT JOIN ( -Select a1.id, -a1.vetAssigned as vetName, -a1.protocol -from researchAssigned a1) -a1 ON (a1.Id = d.Id) - -LEFT JOIN ( -Select a2.id, -a2. vetAssigned as vetName, -a2.protocol -from resourceAssigned a2 ) -a2 ON (a2.Id = d.Id) - - - - --- SELECT --- a.Id, --- group_concat(distinct CAST(v.userId.displayName as varchar(120))) as vetNames, --- CAST(group_concat(distinct v.userId) as varchar(200)) as vetUserIds, --------- Need to only look at Vets on assignment as assigned vet for reseach protocols --- (Select distinct a2.project.protocol.displayname from study.assignment a2 where a2.project.protocol = v.protocol and a2.project.use_category.value = 'Research') as protocols ----- group_concat.use_cagte(distinct a.project.protocol.displayName) as protocols --- FROM study.assignment a --- JOIN onprc_ehr.vet_assignment v ON (a.project.protocol = v.protocol) --- WHERE a.enddateCoalesced >= curdate() OR CAST(a.enddateCoalesced AS DATE) = CAST(a.Id.demographics.lastDayAtCenter AS DATE) --- GROUP BY a.Id,v.protocol - - -LEFT JOIN ( - SELECT - h.Id, - group_concat(distinct CASE WHEN (v.area IS NOT NULL) THEN CAST(v.userId.displayName as varchar(120)) ELSE NULL END) as areaVetNames, - group_concat(distinct CASE WHEN (v.room IS NOT NULL) THEN CAST(v.userId.displayName as varchar(120)) ELSE NULL END) as roomVetNames, - group_concat(distinct CASE WHEN (v.area IS NOT NULL and v.priority = true) THEN CAST(v.userId.displayName as varchar(120)) ELSE NULL END) as highPriAreaVetNames, - group_concat(distinct CASE WHEN (v.room IS NOT NULL and v.priority = true) THEN CAST(v.userId.displayName as varchar(120)) ELSE NULL END) as highPriRoomVetNames, - - group_concat(distinct CASE WHEN (v.area IS NOT NULL) THEN v.userId ELSE NULL END) as areaVetUserIds, - group_concat(distinct CASE WHEN (v.room IS NOT NULL) THEN v.userId ELSE NULL END) as roomVetUserIds, - group_concat(distinct CASE WHEN (v.area IS NOT NULL and v.priority = true) THEN v.userId ELSE NULL END) as highPriAreaVetUserIds, - group_concat(distinct CASE WHEN (v.room IS NOT NULL and v.priority = true) THEN v.userId ELSE NULL END) as highPriRoomVetUserIds, - - group_concat(distinct h.room.area) as areas, - group_concat(distinct h.room) as rooms - - FROM study.housing h - JOIN onprc_ehr.vet_assignment v ON (v.area = h.room.area OR v.room = h.room) - WHERE h.enddateTimeCoalesced >= now() OR CAST(h.enddateCoalesced AS DATE) = CAST(h.Id.demographics.lastDayAtCenter AS DATE) - GROUP BY h.Id -) h ON (h.Id = d.Id) --Where d.calculated_status = 'alive' \ No newline at end of file +--Update 3/7/2019 load to test + +Select + Distinct + d.Id, + d.room.area as Area, + d.room, + d.CaseVet, + d.protocol, + d.ProtocolPI, + d.Calculated_status, + Case + -- when d.DeceaseDAssignedVet is not null then d.DeceaseDAssignedVet + when d.caseVet is not null then d.CaseVet + when p1.userId is not null then p1.userId.displayName + when p2.userId is not null then p2.userId.DisplayName + when v1.userId is not null then v1.userId.displayName + when v2.userId is not null then v2.userId.DisplayName + when v3.userId is not null then v3.userId.DisplayName + when v4.userId is not null then v4.userId.DisplayName + when p3.userId is not null then p3.userId.DisplayName + when p4.userId is not null then p4.userId.DisplayName + when v5.userId is not null then v5.userId.DisplayName + when v6.userId is not null then v6.userId.DisplayName + when h1.userId is not null then h1.userId.DisplayName + when h2.userId is not null then h2.userId.DisplayName + + End as AssignedVet, + + Case + -- when d.DeceaseDAssignedVet is not null then 'Deceased or Shipped NHP' + when d.caseVet is not null then 'Open Case' + when p1.userId is not null then 'Room Priority' + when p2.userId is not null then 'Area Priority' + When p3.userId is not null then 'Protocol Room Priority' + When p4.userId is not null then 'Protocol Area Priority' + when v1.userId is not null then 'Protocol Research Room' + when v2.userId is not null then 'Protocol Research Area' + when v3.userId is not null then 'Protocol Resource Room' + when v4.userId is not null then 'Protocol Resource Area' + when v5.userId is not null then 'Protocol Research Only' + when v6.userId is not null then 'Protocol Resource Only' + + when h1.userId is not null then 'Room Only' + when h2.userId is not null then 'Area Only' + + End as AssignmentType + +FROM study.vet_assignmentDemographics d +--this handles REsearch Protocol Room + Left Join onprc_ehr.vet_assignment v1 on (v1.protocol.displayName = d.protocol and v1.room = d.room and d.assignmentType = 'Research Assigned') +--this handles Research Protocol Area + Left Join onprc_ehr.vet_assignment v2 on (v2.protocol.displayName = d.protocol and v2.area = d.room.area and d.assignmentType = 'Research Assigned') +--this handles Resource Protocol Room + Left Join onprc_ehr.vet_assignment v3 on (v3.protocol.displayName = d.protocol and v3.room = d.room and d.assignmentType = 'Resource Assigned') +--this handles Research Protocol Area + Left Join onprc_ehr.vet_assignment v4 on (v4.protocol.displayName = d.protocol and v4.area = d.room.area and d.assignmentType = 'Resource Assigned') +--this handled Research Assigned No Additional Sekections + Left Join onprc_ehr.vet_assignment v5 on (v5.protocol.displayName = d.protocol and v5.room is null and v5.area is null and d.assignmentType = 'Research Assigned' ) +--this handles resource Protocol Only + Left Join onprc_ehr.vet_assignment v6 on (v6.protocol.displayName = d.protocol and v6.room is null and v6.area is null and d.assignmentType = 'Resource Assigned' ) +--this handles when the room is a priorty + Left join onprc_ehr.vet_assignment p1 on (p1.room = d.room and p1.protocol is null and p1.priority = true) +--this handles when the room is a priorty- + Left join onprc_ehr.vet_assignment p2 on (p2.area = d.room.area and p2.protocol is null and p2.priority = true) +--THis handles when a priority is placed on Room and Protocol -- + Left Join onprc_ehr.vet_assignment p3 on (p3.protocol.displayName = d.protocol and p3.room = d.room and p3.priority = true) +--THis handles when a priority is placed on Areaand Protocol - + Left Join onprc_ehr.vet_assignment p4 on (p4.protocol.displayName = d.protocol and p4.area = d.room.area and p4.priority = true) +--these deal with assignment based on housing only + Left join onprc_ehr.vet_assignment h1 on (h1.room = d.room and h1.protocol is null and h1.area is null and h1.priority = false) + Left join onprc_ehr.vet_assignment h2 on (h2.area = d.room.area and h2.room is null and h2.protocol is null and h2.priority = false) +--where d.id not like '[a-z]%' \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/demographicsAssignedVet/.qview.xml b/onprc_ehr/resources/queries/study/demographicsAssignedVet/.qview.xml index d7244d056..10667f78a 100644 --- a/onprc_ehr/resources/queries/study/demographicsAssignedVet/.qview.xml +++ b/onprc_ehr/resources/queries/study/demographicsAssignedVet/.qview.xml @@ -1,16 +1,18 @@ - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/demographicsBloodSummary.query.xml b/onprc_ehr/resources/queries/study/demographicsBloodSummary.query.xml index 4057765ac..d5f4d3d67 100644 --- a/onprc_ehr/resources/queries/study/demographicsBloodSummary.query.xml +++ b/onprc_ehr/resources/queries/study/demographicsBloodSummary.query.xml @@ -1,59 +1,60 @@ + - +
Available Blood + true - true + false - - true + + Gender - + + Speices + + + Year of Birth + + + Most Recent Weight (kg) - + + Most Recent Weight Date + + + Most Recent BCS + + + Days Since BCS Reported + + + Most Recent BCS Date + + + Calc Method Used + + + Previous Draws (mL) 0.## - /query/executeQuery.view?schemaName=study& - query.queryName=Blood Draws& - query.Id~eq=${Id}& - query.Date~lte=${Date}& - query.sort=-Date& - - - - Future Draws (mL) - 0.## - /query/executeQuery.view?schemaName=study& - query.queryName=Blood Draws& - query.Id~eq=${Id}& - query.Date~gt=${Date}& - query.sort=-Date& - - - - Max blood, assuming no other draws (mL) - 0.## - true + 0 - - Available Blood (mL) + + + + Total Available blood(mL) 0.## - - - - - - FBEC5D - - + availBlood
+ diff --git a/onprc_ehr/resources/queries/study/demographicsBloodSummary.sql b/onprc_ehr/resources/queries/study/demographicsBloodSummary.sql index 4e841ee75..7b34d8eb4 100644 --- a/onprc_ehr/resources/queries/study/demographicsBloodSummary.sql +++ b/onprc_ehr/resources/queries/study/demographicsBloodSummary.sql @@ -1,171 +1,14 @@ -/* - * Copyright (c) 2013-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - * Research completed by Dr Ted Hobbs ONPRC has updated the process for calculating availaable blood - * The new research uses the Body Condition Score of DXA Scan to determine body fat. - * the rule to be applied relates to Rheses Macaque Animals as follows: - ****If a BCS score is recorded that is within the last 365 days the frolumla to be applied is - ****TBV = (113.753 + (0.752 × BW) – (18.919 × BCS))*BW) - ***Total Available is TBV*.125 - ****Else if either no BCS is available or it is older than 1 year, the current method based on standard Available AVolume with be Applied - ** A second process is availbale relating to DXA Scans but these are only performed by Researach Staff and not entered into PRIME - */ - -SELECT - b.lsid, - b.id, - b.Species, - b.Gender, - -b.MostRecentBCS, -b.BCSDate, -b.weight as mostRecentWeight, - b.wdate as mostRecentWeightDate, - b.blood_draw_interval, - b.bloodPrevious, - b.bloodFuture, - b.species.blood_per_kg, -round(b.bloodVolume,2) as FixedRateCalculation, -round(b.TBV,2) as TotalBloodVolume, ---round((b.TBV*.125),2) as AllowableBlood1, - - Case - When species<> 'Rhesus Macaque' --'Fixed Rate Process' - Then round((b.species.blood_per_kg * b.id.MostRecentWeight.MostRecentWeight * b.max_draw_pct),2) - When - b.DaysSinceBCS > 365 - Then round((b.species.blood_per_kg * b.id.MostRecentWeight.MostRecentWeight * b.max_draw_pct),2) - When b.MostRecentBCS is not null - Then round((b.TBV * .125),2) - Else round((b.species.blood_per_kg * b.id.MostRecentWeight.MostRecentWeight * b.max_draw_pct),2) - end As AllowableBlood, - - Case - When species<> 'Rhesus Macaque' --'Fixed Rate Process' - Then - Case - When (b.bloodPrevious>b.bloodFuture) - Then - round(((b.species.blood_per_kg * b.id.MostRecentWeight.MostRecentWeight * b.max_draw_pct)-b.bloodPrevious),2) - ELSE - round(((b.species.blood_per_kg * b.id.MostRecentWeight.MostRecentWeight * b.max_draw_pct)-b.bloodFuture),2) - End - When - b.DaysSinceBCS > 365 - then - Case - When b.bloodPrevious > b.bloodFuture - Then - round(((b.species.blood_per_kg * b.id.MostRecentWeight.MostRecentWeight * b.max_draw_pct)-b.bloodPrevious),2) - Else - round(((b.species.blood_per_kg * b.id.MostRecentWeight.MostRecentWeight * b.max_draw_pct)-b.bloodFuture),2) - End ---Available Blood is Allowable Blood minus the larger of Previous and Future - When - b.MostRecentBCS is not null THEN - Case - When b.bloodPrevious > b.bloodFuture - Then - round(((b.TBV * .125)-b.bloodPrevious),2) - Else - round(((b.TBV * .125)-b.bloodFuture),2) - End - - --- Else - - - - - end As AvailableBlood, - - Case - When species<> 'Rhesus Macaque' Then 'FR' - When - b.DaysSinceBCS > 365 - Then 'FR' - When - b.MostRecentBCS is not null then - 'BCS' - Else'FR' - end As Method - - -FROM ( - -SELECT - d.lsid, - d.id, - d.species, - d.gender, - --NOTE: this uses date part only - lastWeight.dateOnly as wdate, - (SELECT AVG(w.weight) AS _expr - FROM study.weight w - WHERE w.id = d.id - --NOTE: this uses date part only - AND w.dateOnly = lastWeight.dateOnly - AND w.qcstate.publicdata = true - ) AS weight, - d.species.blood_per_kg, - d.species.max_draw_pct , - d.species.blood_draw_interval, - Cast(d.species.cites_Code as Float) as SpeciesCode, - bcs.score as MostRecentBCS, - bcs.date as BCSDate, - TIMESTAMPDIFF('SQL_TSI_DAY',bcs.date,Now()) as DaysSinceBCS, - --This ca;ciates tje tt - Case - when TIMESTAMPDIFF('SQL_TSI_DAY',bcs.date,Now()) < 365 THEN round(cast (113.753 + ((0.752 * d.id.MostRecentWeight.MostRecentWeight ) - (18.919 * bcs.score))as double),2) - Else (d.species.blood_per_kg * d.id.MostRecentWeight.MostRecentWeight) - END as TotalBloodAvailable, - - - - COALESCE (( - SELECT - SUM(bd.quantity) AS quantity - FROM study.blood bd - WHERE bd.id = d.id - --NOTE: this has been changed in the DB to include penidng/non-approved draws - AND (bd.countsAgainstVolume = true) --NOTE: this does mean non-completed past requests will count against blood - AND bd.dateOnly > cast(TIMESTAMPADD('SQL_TSI_DAY', -1 * d.species.blood_draw_interval, now()) as date) - AND bd.dateOnly <= cast(curdate() as date) - ), 0) AS bloodPrevious, --- ***************New Calculation Base *********************************************** - - -- blood volume (ml/kg) -------113.753+(0.752*Wt)- (18.919*BCS) -(113.753+(0.752 * d.id.MostRecentWeight.MostRecentWeight ) - (18.919 * bcs.score)) as BloodVolume, - ---TBV(mnl) ------weight * Blood Volume -(d.id.MostRecentWeight.MostRecentWeight * (113.753+(0.752 * d.id.MostRecentWeight.MostRecentWeight ) - (18.919 * bcs.score))) as TBV, ---Allowable BV ------TBV*.125 - - ---***********************Determines Previous and Future Blood******************************** - COALESCE (( - SELECT - SUM(bd.quantity) AS quantity - FROM study.blood bd - WHERE bd.id = d.id - --NOTE: this has been changed to include penidng/non-approved draws - AND (bd.countsAgainstVolume = true) - AND bd.dateOnly < cast(TIMESTAMPADD('SQL_TSI_DAY', d.species.blood_draw_interval, curdate()) as date) - AND bd.dateOnly >= cast(curdate() as date) - ), 0) AS bloodFuture - - - - -FROM - study.demographics d - --NOTE: this uses date part only - JOIN (SELECT w.id, MAX(dateOnly) as dateOnly FROM study.weight w WHERE w.qcstate.publicdata = true GROUP BY w.id) lastWeight ON (d.id = lastWeight.id) - LEFT OUTER JOIN study.demographicsCurrentBCS bcs on bcs.id = d.id -WHERE d.calculated_status = 'Alive' - -) b \ No newline at end of file +SELECT datecreated + ,id + ,gender + ,species + ,yoa + ,mostrecentweightdate + ,weight + ,calcmethod + ,BCS + ,BCSage + ,previousdraws + ,ABV + ,dsrowid +FROM onprc_ehr.AvailableBloodVolume \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/demographicsBloodSummary/.qview.xml b/onprc_ehr/resources/queries/study/demographicsBloodSummary/.qview.xml index da6699561..097ecaa31 100644 --- a/onprc_ehr/resources/queries/study/demographicsBloodSummary/.qview.xml +++ b/onprc_ehr/resources/queries/study/demographicsBloodSummary/.qview.xml @@ -3,16 +3,18 @@ - - - + + + - - - - - - + + + + +
- \ No newline at end of file + + + + diff --git a/onprc_ehr/resources/queries/study/demographicsGeneticAncestry.query.xml b/onprc_ehr/resources/queries/study/demographicsGeneticAncestry.query.xml new file mode 100644 index 000000000..b95a27bbc --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsGeneticAncestry.query.xml @@ -0,0 +1,15 @@ + + + + + Genetic Ancestry + + + true + true + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/demographicsGeneticAncestry.sql b/onprc_ehr/resources/queries/study/demographicsGeneticAncestry.sql new file mode 100644 index 000000000..4b24cac01 --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsGeneticAncestry.sql @@ -0,0 +1,7 @@ +SELECT +d.Id, +group_concat(distinct d.result) as geneticAncestry + +FROM study.geneticAncestry d +WHERE d.isActive = true +GROUP BY d.Id \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/demographicsMostRecentBCS.sql b/onprc_ehr/resources/queries/study/demographicsMostRecentBCS.sql index 432b03dbc..5c55a710d 100644 --- a/onprc_ehr/resources/queries/study/demographicsMostRecentBCS.sql +++ b/onprc_ehr/resources/queries/study/demographicsMostRecentBCS.sql @@ -2,25 +2,39 @@ * Copyright (c) 2014 LabKey Corporation * * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + * updated 9/4/2017 by Kolli to adjust issue of multiple bcs on same date + * results verified in Test and readyfor Production */ +Select DISTINCT +a.id, +CAST(a.date AS DATE) as date, +a.score +From +(Select b.id, b.date, b.score + From study.BCS_Recent_Score b + Where b.score = (Select Min(b1.score) from study.BCS_Recent_Score b1 where b1.id =b.id) +) AS a -select - co.Id, - max(co2.maxDate) as date, - group_concat(DISTINCT co.observation) as score -from study.clinical_observations co -join ( - SELECT - co.Id, - max(co.date) as maxDate - FROM study.clinical_observations co - WHERE co.qcstate.publicdata = true AND co.category = 'BCS' - GROUP BY co.Id -) co2 ON (co.Id = co2.Id AND co.date = co2.maxDate) -WHERE co.qcstate.publicdata = true AND co.category = 'BCS' -GROUP BY co.Id +/* code as of 9/1/2017 +Select +b.id, +b.date, +b.observation as score +from study.clinical_observations b +where b.category = 'bcs' +and b.created > TIMESTAMPADD('SQL_TSI_MONTH', -18, Now()) +and b.date = (Select Max(b2.date) from study.clinical_observations b2 where b2.id =b.id and b2.category = 'bcs' and b2.observation is not null) +and b.observation = (Select Min(b1.observation) from study.clinical_observations b1 where b1.id =b.id and b1.category = 'bcs' and b1.observation is not null) +and b.observation is not null + and b.id not like '[a-z]%'*/ + + + +-- when coiunt more than 1 use smallest value +-- need to determine when 2 bcs scores are entered for the same date, then use min bCS + diff --git a/onprc_ehr/resources/queries/study/demographicsOffspring.sql b/onprc_ehr/resources/queries/study/demographicsOffspring.sql index b68cb6e3f..82ba0fe31 100644 --- a/onprc_ehr/resources/queries/study/demographicsOffspring.sql +++ b/onprc_ehr/resources/queries/study/demographicsOffspring.sql @@ -6,7 +6,7 @@ SELECT d.id, -d.gender, +d.gender.meaning as gender, 'Offspring' as Relationship, d2.id AS Offspring, @@ -17,5 +17,7 @@ d.qcstate FROM study.Demographics d INNER JOIN study.Demographics d2 - ON ((d2.id.parents.sire = d.id OR d2.id.parents.dam = d.id) AND d.id != d2.id) + ON ((d2.id.parents.sire = d.id OR d2.id.parents.dam = d.id OR d2.id.parents.fostermom = d.id) AND d.id != d2.id) + + diff --git a/onprc_ehr/resources/queries/study/demographicsOffspring/.qview.xml b/onprc_ehr/resources/queries/study/demographicsOffspring/.qview.xml index 0fd322a62..a1b484e9e 100644 --- a/onprc_ehr/resources/queries/study/demographicsOffspring/.qview.xml +++ b/onprc_ehr/resources/queries/study/demographicsOffspring/.qview.xml @@ -13,6 +13,9 @@ + + + diff --git a/onprc_ehr/resources/queries/study/demographicsOffspringBSU.query.xml b/onprc_ehr/resources/queries/study/demographicsOffspringBSU.query.xml new file mode 100644 index 000000000..161f83fec --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsOffspringBSU.query.xml @@ -0,0 +1,59 @@ + + + + + + + true + + + + /query/executeQuery.view?schemaName=study& + query.queryName=demographicsOffspringBSU& + query.Id~eq=${Id} + + + + + study + animal + Id + + + + Gender + + + Birth + + + Birth Type + + + Status + + + + Genetic Dam + + + + Observed Dam + + + Foster Dam + + + + Sire + + + + Sire type + + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/demographicsOffspringBSU.sql b/onprc_ehr/resources/queries/study/demographicsOffspringBSU.sql new file mode 100644 index 000000000..26a72138b --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsOffspringBSU.sql @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +SELECT + +d.id, +d.gender.meaning as gender, +'Offspring' as Relationship, + +d2.id AS Offspring, +d2.birth, +d2.birthType, +d2.offspringgender, +d2.status, +d2.geneticdam, +d2.observeddam, +d2.fosterMom, +d2.sire, +d2.sireType, +d.qcstate + +FROM study.Demographics d + +INNER JOIN study.demographicsParentsBSU d2 + + ON ((d2.sire = d.id OR d2.geneticdam = d.id OR d2.fostermom = d.id OR d2.observeddam = d.id) AND d.id != d2.id) + + + diff --git a/onprc_ehr/resources/queries/study/demographicsOffspringBSU/.qview.xml b/onprc_ehr/resources/queries/study/demographicsOffspringBSU/.qview.xml new file mode 100644 index 000000000..cda4e0878 --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsOffspringBSU/.qview.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/demographicsParents.query.xml b/onprc_ehr/resources/queries/study/demographicsParents.query.xml index a151cf172..e3ef57f38 100644 --- a/onprc_ehr/resources/queries/study/demographicsParents.query.xml +++ b/onprc_ehr/resources/queries/study/demographicsParents.query.xml @@ -8,6 +8,7 @@ true
+ Dam study animal @@ -15,6 +16,23 @@ + Sire + + study + animal + id + + + + Foster Dam + + study + animal + id + + + + Genetic Dam study animal diff --git a/onprc_ehr/resources/queries/study/demographicsParents.sql b/onprc_ehr/resources/queries/study/demographicsParents.sql index f1cebab46..673cc8bb2 100644 --- a/onprc_ehr/resources/queries/study/demographicsParents.sql +++ b/onprc_ehr/resources/queries/study/demographicsParents.sql @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + SELECT d.id, coalesce(p2.parent, b.dam) as dam, @@ -28,24 +29,34 @@ SELECT WHEN b.sire IS NOT NULL THEN 'Observed' ELSE null END as sireType, - CASE - WHEN (coalesce(p2.parent, b.dam) IS NOT NULL AND coalesce(p1.parent, b.sire) IS NOT NULL) THEN 2 - WHEN (coalesce(p2.parent, b.dam) IS NOT NULL OR coalesce(p1.parent, b.sire) IS NOT NULL) THEN 1 - ELSE 0 - END as numParents -FROM study.demographics d + p3.parent as fosterMom, + p3.method as fosterType, + + (CASE WHEN p3.parent IS NOT NULL THEN 1 ELSE 0 END + + CASE WHEN coalesce(p2.parent, b.dam) IS NOT NULL THEN 1 ELSE 0 END + + CASE WHEN coalesce(p1.parent, b.sire) IS NOT NULL THEN 1 ELSE 0 END) as numParents + +FROM study.demographics d LEFT JOIN ( select p1.id, min(p1.method) as method, max(p1.parent) as parent FROM study.parentage p1 - WHERE (p1.method = 'Genetic' OR p1.method = 'Provisional Genetic') AND p1.relationship = 'Sire' --AND p1.enddate IS NULL + WHERE (p1.method = 'Genetic' OR p1.method = 'Provisional Genetic') AND p1.relationship = 'Sire' AND p1.enddate IS NULL GROUP BY p1.Id ) p1 ON (d.Id = p1.id) + LEFT JOIN ( select p2.id, min(p2.method) as method, max(p2.parent) as parent FROM study.parentage p2 - WHERE (p2.method = 'Genetic' OR p2.method = 'Provisional Genetic') AND p2.relationship = 'Dam' --AND p2.enddate IS NULL + WHERE (p2.method = 'Genetic' OR p2.method = 'Provisional Genetic') AND p2.relationship = 'Dam' AND p2.enddate IS NULL GROUP BY p2.Id ) p2 ON (d.Id = p2.id) + +LEFT JOIN ( + select p3.id, min(p3.method) as method, max(p3.parent) as parent + FROM study.parentage p3 + WHERE p3.relationship = 'Foster Dam' AND p3.enddate IS NULL + GROUP BY p3.Id +) p3 ON (d.Id = p3.id) LEFT JOIN study.birth b ON (b.id = d.id) diff --git a/onprc_ehr/resources/queries/study/demographicsParents/.qview.xml b/onprc_ehr/resources/queries/study/demographicsParents/.qview.xml index ce003e39e..2ab5905b4 100644 --- a/onprc_ehr/resources/queries/study/demographicsParents/.qview.xml +++ b/onprc_ehr/resources/queries/study/demographicsParents/.qview.xml @@ -5,6 +5,8 @@ + + diff --git a/onprc_ehr/resources/queries/study/demographicsParentsBSU.query.xml b/onprc_ehr/resources/queries/study/demographicsParentsBSU.query.xml new file mode 100644 index 000000000..5790dc400 --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsParentsBSU.query.xml @@ -0,0 +1,59 @@ + + + + + Parents + + + true + + + true + + + true + + + true + + + Dam + + study + animal + id + + + + Genetic Dam + + study + animal + id + + + + Sire + + study + animal + id + + + + Foster Dam + + study + animal + id + + + + + Number of Parents Known + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/demographicsParentsBSU.sql b/onprc_ehr/resources/queries/study/demographicsParentsBSU.sql new file mode 100644 index 000000000..76f64855f --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsParentsBSU.sql @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2013 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +SELECT + d.id, + d.birth, + b.type.value as birthType, + b.Id.demographics.gender.meaning as offspringgender, + d.calculated_status as status, + coalesce(p2.parent, '') as geneticdam, + CASE + WHEN p2.parent IS NOT NULL THEN p2.method + ELSE null + END as geneticDamType, + + coalesce(b.dam, '') as observeddam, + CASE + WHEN b.dam IS NOT NULL THEN 'Observed' + ELSE null + END as observedDamType, + + coalesce(p1.parent, b.sire) as sire, + CASE + WHEN p1.parent IS NOT NULL THEN p1.method + WHEN b.sire IS NOT NULL THEN 'Observed' + ELSE null + END as sireType, + + p3.parent as fosterMom, + p3.method as fosterType, + + (CASE WHEN p3.parent IS NOT NULL THEN 1 ELSE 0 END + + CASE WHEN coalesce(p2.parent, b.dam) IS NOT NULL THEN 1 ELSE 0 END + + CASE WHEN coalesce(p1.parent, b.sire) IS NOT NULL THEN 1 ELSE 0 END) as numParents + +FROM study.demographics d + +LEFT JOIN ( + select p1.id, min(p1.method) as method, max(p1.parent) as parent + FROM study.parentage p1 + WHERE (p1.method = 'Genetic' OR p1.method = 'Provisional Genetic') AND p1.relationship = 'Sire' AND p1.enddate IS NULL + GROUP BY p1.Id +) p1 ON (d.Id = p1.id) + +LEFT JOIN ( + select p2.id, min(p2.method) as method, max(p2.parent) as parent + FROM study.parentage p2 + WHERE (p2.method = 'Genetic' OR p2.method = 'Provisional Genetic') AND p2.relationship = 'Dam' AND p2.enddate IS NULL + GROUP BY p2.Id +) p2 ON (d.Id = p2.id) + +LEFT JOIN ( + select p3.id, min(p3.method) as method, max(p3.parent) as parent + FROM study.parentage p3 + WHERE p3.relationship = 'Foster Dam' AND p3.enddate IS NULL + GROUP BY p3.Id +) p3 ON (d.Id = p3.id) +LEFT JOIN study.birth b ON (b.id = d.id) + diff --git a/onprc_ehr/resources/queries/study/demographicsParentsBSU/.qview.xml b/onprc_ehr/resources/queries/study/demographicsParentsBSU/.qview.xml new file mode 100644 index 000000000..25ca78e42 --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsParentsBSU/.qview.xml @@ -0,0 +1,21 @@ + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/demographics_Vet_Assignment_Alert.sql b/onprc_ehr/resources/queries/study/demographics_Vet_Assignment_Alert.sql new file mode 100644 index 000000000..a9685aba6 --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographics_Vet_Assignment_Alert.sql @@ -0,0 +1,11 @@ +Select +d.id, +d.calculated_Status, +d.earliestRemarkSinceReview, +d.lastVetReview, +d.lastDayAtCenter, +v.assignedVet +From demographics d, demographicsAssignedVet v +Where d.id = v.id +And ( (d.lastDayAtCenter >= timestampadd('SQL_TSI_Day', -90, Now())) or (d.lastDayAtCenter IS NULL)) +and v.assignedVet is Not Null diff --git a/onprc_ehr/resources/queries/study/demographics_assignedVetNotification.sql b/onprc_ehr/resources/queries/study/demographics_assignedVetNotification.sql new file mode 100644 index 000000000..ce613375f --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographics_assignedVetNotification.sql @@ -0,0 +1,11 @@ +--date: 6/19/2019 +--Promotoed to UAT by gjones + +SELECT +d.id, +d.calculated_Status, +d.earliestRemarkSinceReview, +d.lastVetReview, +v.assignedVet +FROM demographicsAssignedVet v join demographics d on v.id = d.id +where d.lastDayAtCenter > TimestampDiff('SQL_TSI_Day', 90, Now()) \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/dualassigned.sql b/onprc_ehr/resources/queries/study/dualassigned.sql new file mode 100644 index 000000000..48a02aa0c --- /dev/null +++ b/onprc_ehr/resources/queries/study/dualassigned.sql @@ -0,0 +1,104 @@ +SELECT a.Id, +a.id.demographics.gender, +-- +a.project as Project1, +a2.project as Project2, +Case + when a.project.use_category != 'Research' then a.project + when a2.project.use_category != 'Research' then a2.project + else Null + end as project, + +Case + when a.project.use_category != 'Research' then a.project.account.alias + when a2.project.use_category != 'Research' then a2.project.account.alias + else Null + end as projectAccount, +Case + when a.project.use_category != 'Research' then a.project.displayname + when a2.project.use_category != 'Research' then a2.project.displayName + else Null + end as projectName, + + +Case + when a.project.use_category != 'Research' then a.project.use_category + when a2.project.use_category != 'Research' then a2.project.use_category + else Null + end as projectCategory, +--date should be the assignment date of the resource +Case + when a.project.use_category != 'Research' then a.date + when a2.project.use_category != 'Research' then a2.date + else Null + end as date, + +Case + when a.project.use_category != 'Research' then a.projectedRelease + when a2.project.use_category != 'Research' then a2.projectedRelease + else Null + end as projectedRelease, +Case + when a.project.use_category != 'Research' then a.enddate + when a2.project.use_category != 'Research' then a2.enddate + else Null + end as enddate, + +Case + when a.project.use_category != 'Research' then a.assignCondition + when a2.project.use_category != 'Research' then a2.assignCondition + else Null + end as assignCondition, + +Case + when a.project.use_category != 'Research' then a.projectedReleaseCondition + when a2.project.use_category != 'Research' then a2.projectedReleaseCondition + else Null + end as projectedReleaseCondition, + + + + +--this places the research project as the Dual assigned +Case + When a2.project.use_category = 'Research' then a2.project + when a.project.use_category = 'Research' then a.project + Else Null + ENd as DualAssignment, +--a2.project as DualAssignment, +Case + When a2.project.use_category = 'Research' then a2.project.displayName + when a.project.use_category = 'Research' then a.project.DisplayName + Else Null + ENd as DualName, + +--this places the research project as the Dual assigned +Case + When a2.project.use_category = 'Research' then a2.project.use_category + when a.project.use_category = 'Research' then a.project.use_category + Else Null + ENd as DualProjectCategory, +Case + When a2.project.use_category = 'Research' then a2.date + when a.project.use_category = 'Research' then a.date + Else Null + ENd as DualStartDate, + +Case + When a2.project.use_category = 'Research' then a2.projectedRelease + when a.project.use_category = 'Research' then a.projectedRelease + Else Null + ENd as DualProjectedRelease, + +Case + When a2.project.use_category = 'Research' then a2.enddate + when a.project.use_category = 'Research' then a.enddate + Else Null + ENd as DualEndDate + + + + + +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.assignment a2 on a.id = a2.id +where ( a.project <> a2.project) and a.project.use_category != 'Research' diff --git a/onprc_ehr/resources/queries/study/geneticAncestry.js b/onprc_ehr/resources/queries/study/geneticAncestry.js new file mode 100644 index 000000000..71df2a651 --- /dev/null +++ b/onprc_ehr/resources/queries/study/geneticAncestry.js @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2013 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +require("ehr/triggers").initScript(this); + +var triggerHelper = new org.labkey.onprc_ehr.query.ONPRC_EHRTriggerHelper(LABKEY.Security.currentUser.id, LABKEY.Security.currentContainer.id); + +function onInit(event, helper){ + helper.setScriptOptions({ + lookupValidationFields: ['result'] + }); +} + +EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.COMPLETE, 'study', 'Genetic Ancestry', function(event, errors, helper) { + if (!helper.isETL() && helper.getPublicParticipantsModified().length) { + triggerHelper.updateGeographicStatus(helper.getPublicParticipantsModified()); + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/geneticAncestry.query.xml b/onprc_ehr/resources/queries/study/geneticAncestry.query.xml new file mode 100644 index 000000000..3d2346aab --- /dev/null +++ b/onprc_ehr/resources/queries/study/geneticAncestry.query.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + Date Added + + + Date Disabled + + + + + + + + + Result + false + + ehr_lookups + geographic_origins + meaning + + + + true + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/geneticAncestry/.qview.xml b/onprc_ehr/resources/queries/study/geneticAncestry/.qview.xml new file mode 100644 index 000000000..af9d56dcb --- /dev/null +++ b/onprc_ehr/resources/queries/study/geneticAncestry/.qview.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/geneticAncestry/Active Calls.qview.xml b/onprc_ehr/resources/queries/study/geneticAncestry/Active Calls.qview.xml new file mode 100644 index 000000000..b900c40f2 --- /dev/null +++ b/onprc_ehr/resources/queries/study/geneticAncestry/Active Calls.qview.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/etl/deprecated/_animal_groups.sql b/onprc_ehr/resources/queries/study/geneticAncestryConflicts.sql similarity index 72% rename from onprc_ehr/resources/etl/deprecated/_animal_groups.sql rename to onprc_ehr/resources/queries/study/geneticAncestryConflicts.sql index 5c5f9cb96..750df0c65 100644 --- a/onprc_ehr/resources/etl/deprecated/_animal_groups.sql +++ b/onprc_ehr/resources/queries/study/geneticAncestryConflicts.sql @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -select -p.ShortDescription as category, -p.Description as name, -p.Date as date, -p.DateDisabled as enddate, -p.objectid +SELECT + p.Id, + group_concat(distinct p.result) as result, + count(p.Id) as totalRecords -From ref_pool p -where p.ShortDescription IN ('CBG', 'EBG', 'HBG', 'PBG', 'STG', 'SBG', 'JBG', 'CCBG', 'CTG') -and p.ts > ? \ No newline at end of file +FROM study.geneticAncestry p +WHERE p.qcstate.publicdata = true and p.isActive = true + +GROUP BY p.Id +HAVING COUNT(DISTINCT p.result) > 1 \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/geographicOriginConflicts.sql b/onprc_ehr/resources/queries/study/geographicOriginConflicts.sql new file mode 100644 index 000000000..5985f602a --- /dev/null +++ b/onprc_ehr/resources/queries/study/geographicOriginConflicts.sql @@ -0,0 +1,8 @@ +SELECT +t.Id, +t.geneticAncestry, +d.geographic_origin, + +FROM study.demographicsGeneticAncestry t +JOIN study.demographics d on (t.Id = d.Id) +WHERE t.geneticAncestry != d.geographic_origin OR (t.geneticAncestry IS NOT NULL AND d.geographic_origin IS NULL) diff --git a/onprc_ehr/resources/queries/study/iStat/.qview.xml b/onprc_ehr/resources/queries/study/grossFindings/.qview.xml similarity index 100% rename from onprc_ehr/resources/queries/study/iStat/.qview.xml rename to onprc_ehr/resources/queries/study/grossFindings/.qview.xml diff --git a/onprc_ehr/resources/queries/study/hematologyPivot.query.xml b/onprc_ehr/resources/queries/study/hematologyPivot.query.xml index d61a4a043..7713cb3c8 100644 --- a/onprc_ehr/resources/queries/study/hematologyPivot.query.xml +++ b/onprc_ehr/resources/queries/study/hematologyPivot.query.xml @@ -29,7 +29,8 @@ objectid
- + + Testing Performed By diff --git a/onprc_ehr/resources/queries/study/hematologyPivot.sql b/onprc_ehr/resources/queries/study/hematologyPivot.sql index 26f3015cc..6c811d947 100644 --- a/onprc_ehr/resources/queries/study/hematologyPivot.sql +++ b/onprc_ehr/resources/queries/study/hematologyPivot.sql @@ -13,7 +13,7 @@ FROM b.id, b.date, b.method, - b.chargetype, + b.performedby, ---Added 2-21-2020 R.Blasa b.testId, b.runId @hidden, group_concat(b.result) as results @@ -25,7 +25,7 @@ FROM b.date, b.testId, b.runid.method as method, - b.runid.chargetype as chargetype, + b.performedby as performedby, ---Added 2-21-2020 R.Blasa coalesce(b.runId, b.objectid) as runId, CASE WHEN b.result IS NULL THEN b.qualresult @@ -35,9 +35,9 @@ FROM WHERE b.testId.includeInPanel = true and b.qcstate.publicdata = true ) b -GROUP BY b.id, b.date, b.runId, b.testId, b.method, b.chargetype +GROUP BY b.id, b.date, b.runId, b.testId, b.method, b.performedby PIVOT results BY testId IN -(select testid from ehr_lookups.hematology_tests t WHERE t.includeInPanel = true)) pvt +(select testid from ehr_lookups.hematology_tests t WHERE t.includeInPanel = true order by sort_order)) pvt LEFT OUTER JOIN @@ -47,7 +47,7 @@ LEFT OUTER JOIN group_concat(distinct servicerequested, chr(10)) as servicerequested, b.runId, b.method, - b.chargetype, + b.performedby, ---Added 2-21-2020 R.Blasa, group_concat(distinct b.remark, chr(10)) as remark, group_concat(distinct b.runRemark, chr(10)) as runRemark @@ -57,7 +57,7 @@ FROM ( b.id, b.date, b.runid.method as method, - b.runid.chargetype as chargetype, + b.performedby as performedby, ---Added 5-10-2020 R.Blasa b.runid.servicerequested as servicerequested, coalesce(b.runId, b.objectid) as runId, b.remark, @@ -66,6 +66,6 @@ FROM ( WHERE b.testId.includeInPanel = true and b.qcstate.publicdata = true ) b -GROUP BY b.id, b.date, b.runId, b.method, b.chargetype) grp +GROUP BY b.id, b.date, b.runId, b.method, performedby) grp -ON pvt.id = grp.id AND pvt.date = grp.date AND pvt.runID = grp.runId AND pvt.method = grp.method AND pvt.chargetype = grp.chargetype \ No newline at end of file +ON pvt.id = grp.id AND pvt.date = grp.date AND pvt.runID = grp.runId AND pvt.method = grp.method AND pvt.performedby = grp.performedby \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/lease_ObeseInfant_HFDDam.sql b/onprc_ehr/resources/queries/study/lease_ObeseInfant_HFDDam.sql new file mode 100644 index 000000000..6ed162fba --- /dev/null +++ b/onprc_ehr/resources/queries/study/lease_ObeseInfant_HFDDam.sql @@ -0,0 +1,9 @@ +SELECT b.Id, +b.date, +b.date_type, +b.birth_condition, +b.room, +b.cage, +b.dam + +FROM birth b join study.flags s on b.dam = s.id and s.flag.value = 'JMac Obese HFD' and s.enddate is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/measurementsMisc.sql b/onprc_ehr/resources/queries/study/measurementsMisc.sql index bb5c47f84..b2bf6cfd9 100644 --- a/onprc_ehr/resources/queries/study/measurementsMisc.sql +++ b/onprc_ehr/resources/queries/study/measurementsMisc.sql @@ -20,7 +20,8 @@ SELECT m.tissue, m.measurement1, m.measurement2, - m.measurement3 + m.measurement3, + m.remark from study.measurements m where m.tissue NOT IN (SELECT code FROM ehr_lookups.snomed_subset_codes sc WHERE sc.primaryCategory = 'Measurements') diff --git a/onprc_ehr/resources/queries/study/measurementsPivotedBody.sql b/onprc_ehr/resources/queries/study/measurementsPivotedBody.sql index 63982f4a0..9f5161835 100644 --- a/onprc_ehr/resources/queries/study/measurementsPivotedBody.sql +++ b/onprc_ehr/resources/queries/study/measurementsPivotedBody.sql @@ -19,11 +19,12 @@ select m.id, m.date, m.tissue, - max(m.measurement) as value + max(m.measurement) as value, + m.remark FROM study.measurementsPivotedRawData m WHERE m.categories like '%Body%' and m.measurementNo = '1' -group by m.id, m.date, m.tissue, m.parentid +group by m.id, m.date, m.tissue, m.parentid, m.remark pivot value by tissue \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/measurementsPivotedFetal.sql b/onprc_ehr/resources/queries/study/measurementsPivotedFetal.sql index 3baa82232..981b44e3a 100644 --- a/onprc_ehr/resources/queries/study/measurementsPivotedFetal.sql +++ b/onprc_ehr/resources/queries/study/measurementsPivotedFetal.sql @@ -19,11 +19,12 @@ select m.id, m.date, m.tissue, - max(m.measurement) as value + max(m.measurement) as value, + m.remark FROM study.measurementsPivotedRawData m WHERE m.categories like '%Fetal%' and m.measurementNo = '1' -group by m.id, m.date, m.tissue, m.parentid +group by m.id, m.date, m.tissue, m.parentid, m.remark pivot value by tissue \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/measurementsPivotedHeart.sql b/onprc_ehr/resources/queries/study/measurementsPivotedHeart.sql index c0633819c..83315498c 100644 --- a/onprc_ehr/resources/queries/study/measurementsPivotedHeart.sql +++ b/onprc_ehr/resources/queries/study/measurementsPivotedHeart.sql @@ -19,11 +19,12 @@ select m.id, m.date, m.tissue, - max(m.measurement) as value + max(m.measurement) as value, + m.remark FROM study.measurementsPivotedRawData m WHERE m.categories like '%Heart%' and m.measurementNo = '1' -group by m.id, m.date, m.tissue, m.parentid +group by m.id, m.date, m.tissue, m.parentid, m.remark pivot value by tissue \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/measurementsPivotedPlacental.sql b/onprc_ehr/resources/queries/study/measurementsPivotedPlacental.sql index a157ddd4b..dd695b4c8 100644 --- a/onprc_ehr/resources/queries/study/measurementsPivotedPlacental.sql +++ b/onprc_ehr/resources/queries/study/measurementsPivotedPlacental.sql @@ -19,11 +19,12 @@ select m.id, m.date, m.label as tissue, - max(m.measurement) as value + max(m.measurement) as value, + m.remark FROM study.measurementsPivotedRawData m WHERE m.categories like '%Placental%' -group by m.id, m.date, m.label, m.parentid +group by m.id, m.date, m.label, m.parentid, m.remark pivot value by tissue \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/measurementsPivotedRawData.sql b/onprc_ehr/resources/queries/study/measurementsPivotedRawData.sql index 47b14a15c..43b16794a 100644 --- a/onprc_ehr/resources/queries/study/measurementsPivotedRawData.sql +++ b/onprc_ehr/resources/queries/study/measurementsPivotedRawData.sql @@ -25,6 +25,7 @@ SELECT m0.measurementNo, m0.measurement, m0.parentid, + m0.remark, (SELECT group_concat(distinct sc.secondaryCategory) as expr FROM ehr_lookups.snomed_subset_codes sc WHERE sc.primaryCategory = 'Measurements' and m0.snomed = sc.code) as categories FROM ( @@ -36,7 +37,8 @@ SELECT m.tissue as snomed, '1' as measurementNo, m.measurement1 as measurement, - m.parentid + m.parentid, + m.remark from study.measurements m where measurement1 is not null @@ -50,7 +52,8 @@ select m.tissue as snomed, '2' as measurementNo, m.measurement2 as measurement, - m.parentid + m.parentid, + m.remark from study.measurements m where measurement2 is not null @@ -64,7 +67,8 @@ select m.tissue as snomed, '3' as measurementNo, m.measurement3 as measurement, - m.parentid + m.parentid, + m.remark from study.measurements m where measurement3 is not null diff --git a/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior.query.xml b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior.query.xml new file mode 100644 index 000000000..6dc12a515 --- /dev/null +++ b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior.query.xml @@ -0,0 +1,11 @@ + + + + + Most Recent Observations For Behavior Case + oOservations +
+
+ +
+
diff --git a/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior.sql b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior.sql new file mode 100644 index 000000000..e24e9410b --- /dev/null +++ b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior.sql @@ -0,0 +1,12 @@ + +--- Created: 8-23-2018 R.Blasa +select a.id,a.date,a.reviewdate, +a.isactive, +a.allproblemcategories, +a.caseHistory, +a.isopen, +b.observations + from study.cases a, mostrecentobservationsforcase b +where a.id = b.id +and a.objectid = b.caseid +and a.category = 'Behavior' diff --git a/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/.qview.xml b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/.qview.xml new file mode 100644 index 000000000..ccfd1d520 --- /dev/null +++ b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/.qview.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/All Behavior Cases.qview.xml b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/All Behavior Cases.qview.xml new file mode 100644 index 000000000..32b94fa86 --- /dev/null +++ b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/All Behavior Cases.qview.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/Open Behavior Case.qview.xml b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/Open Behavior Case.qview.xml new file mode 100644 index 000000000..5fcf9794e --- /dev/null +++ b/onprc_ehr/resources/queries/study/mostRecentObservationsBehavior/Open Behavior Case.qview.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/mostRecentObservationsForCase.sql b/onprc_ehr/resources/queries/study/mostRecentObservationsForCase.sql index f3cc2389d..ac3323eab 100644 --- a/onprc_ehr/resources/queries/study/mostRecentObservationsForCase.sql +++ b/onprc_ehr/resources/queries/study/mostRecentObservationsForCase.sql @@ -31,7 +31,7 @@ FROM (SELECT o.caseid, o.date, CASE - WHEN o.category = javaConstant('org.labkey.ehr.EHRManager.OBS_CATEGORY_OBSERVATIONS') THEN null + WHEN o.category = 'Observations' THEN null ELSE o.category END as category, CASE @@ -49,14 +49,14 @@ JOIN ( SELECT o2.Id, o2.caseid, max(o2.date) as date FROM study.clinical_observations o2 WHERE o2.caseid IS NOT NULL - AND o2.category != javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.VET_REVIEW') - AND o2.category != javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.TECH_REVIEW') + AND o2.category != 'Vet Review' + AND o2.category != 'Reviewed' GROUP BY o2.Id, o2.caseid ) t ON (t.Id = o.Id AND t.caseid = o.caseid AND t.date = o.date) WHERE o.caseid IS NOT NULL - AND o.category != javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.VET_REVIEW') - AND o.category != javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.TECH_REVIEW') + AND o.category != 'Vet Review' + AND o.category != 'Reviewed' ) t GROUP BY t.Id, t.caseid \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/pairingEvents.query.xml b/onprc_ehr/resources/queries/study/pairingEvents.query.xml new file mode 100644 index 000000000..828e8e3dc --- /dev/null +++ b/onprc_ehr/resources/queries/study/pairingEvents.query.xml @@ -0,0 +1,36 @@ + + + + + Pairing Summary + + + + + + + + + + + + + + + + + + + Other Ids + + + + + + + + +
+
+
+
diff --git a/onprc_ehr/resources/etl/pending/grants.sql b/onprc_ehr/resources/queries/study/pairingEvents.sql similarity index 53% rename from onprc_ehr/resources/etl/pending/grants.sql rename to onprc_ehr/resources/queries/study/pairingEvents.sql index 2df3ab77e..2359ca5ca 100644 --- a/onprc_ehr/resources/etl/pending/grants.sql +++ b/onprc_ehr/resources/queries/study/pairingEvents.sql @@ -13,15 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ ---TODO: this needs works SELECT -p.grantNumber, -max(p.grantTitle) as title, -MAX(CONVERT(varchar(38), p.objectid)) as objectid, -count(*) as total + p.Id, + (SELECT group_concat(distinct p2.Id, chr(10)) FROM study.pairings p2 WHERE p.Id != p2.id AND p.pairId = p2.pairId) as otherIds, + p.pairid, + p.date, + p.lowestCage, + p.room, + p.cage, + p.eventType, + p.goal, + p.observation, + p.outcome, + p.separationreason, + p.remark, + p.remark2, + p.enddate, + p.endeventType, + p.performedby, + p.taskid, + TIMESTAMPDIFF('SQL_TSI_DAY', p.date, coalesce(p.enddate,curdate())) as duration, + p.qcstate -FROM Ref_ProjectGrants p -WHERE p.datedisabled is null -group by p.grantNumber--, p.grantTitle - -having MAX(p.ts) > ? \ No newline at end of file +FROM study.pairings p +where not (p.eventtype in ('General Comment', 'Pair monitor')) diff --git a/onprc_ehr/resources/queries/study/pairingEvents/.qview.xml b/onprc_ehr/resources/queries/study/pairingEvents/.qview.xml new file mode 100644 index 000000000..ed72dc87c --- /dev/null +++ b/onprc_ehr/resources/queries/study/pairingEvents/.qview.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/queries/study/pairingSummary.query.xml b/onprc_ehr/resources/queries/study/pairingSummary.query.xml index 798fd1333..f4d62fb54 100644 --- a/onprc_ehr/resources/queries/study/pairingSummary.query.xml +++ b/onprc_ehr/resources/queries/study/pairingSummary.query.xml @@ -1,20 +1,36 @@ - - - - Pairing Summary - - - - - - - - - Other Ids - - -
-
-
+ + + + Pairing Summary + + + + + + + + + + + + + + + + + + + Other Ids + + + + + + + + +
+
+
diff --git a/onprc_ehr/resources/queries/study/pairingSummary.sql b/onprc_ehr/resources/queries/study/pairingSummary.sql index 32e04c463..a670ae47f 100644 --- a/onprc_ehr/resources/queries/study/pairingSummary.sql +++ b/onprc_ehr/resources/queries/study/pairingSummary.sql @@ -15,7 +15,8 @@ */ SELECT p.Id, - (SELECT group_concat(distinct p2.Id, chr(10)) FROM study.pairings p2 WHERE p.Id != p2.id AND p.pairId = p2.pairId) as otherIds, + (SELECT group_concat(distinct p2.Id, chr(10)) FROM study.pairings p2 WHERE p.Id != p2.id AND p.pairId = p2.pairId) as otherIds, + p.pairid, p.date, p.lowestCage, p.room, @@ -26,8 +27,13 @@ SELECT p.outcome, p.separationreason, p.remark, + p.remark2, + p.enddate, + p.endeventType, p.performedby, p.taskid, + TIMESTAMPDIFF('SQL_TSI_DAY', p.date, coalesce(p.enddate,curdate())) as duration, p.qcstate FROM study.pairings p + diff --git a/onprc_ehr/resources/queries/study/pairingSummary/.qview.xml b/onprc_ehr/resources/queries/study/pairingSummary/.qview.xml index 05c69057d..ed72dc87c 100644 --- a/onprc_ehr/resources/queries/study/pairingSummary/.qview.xml +++ b/onprc_ehr/resources/queries/study/pairingSummary/.qview.xml @@ -1,17 +1,24 @@ + - + - - + + + + + + - + + + diff --git a/onprc_ehr/resources/queries/study/pairingSummaryComments.query.xml b/onprc_ehr/resources/queries/study/pairingSummaryComments.query.xml new file mode 100644 index 000000000..067dca034 --- /dev/null +++ b/onprc_ehr/resources/queries/study/pairingSummaryComments.query.xml @@ -0,0 +1,36 @@ + + + + + Pairing Summary Comments + + + + + + + + + + + + + + + + + + + Other Ids + + + + + + + + +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/pairingSummaryComments.sql b/onprc_ehr/resources/queries/study/pairingSummaryComments.sql new file mode 100644 index 000000000..8f961e72e --- /dev/null +++ b/onprc_ehr/resources/queries/study/pairingSummaryComments.sql @@ -0,0 +1,24 @@ +SELECT + p.Id, + (SELECT group_concat(distinct p2.Id, chr(10)) FROM study.pairings p2 WHERE p.Id != p2.id AND p.pairId = p2.pairId) as otherIds, + p.pairid, + p.date, + p.lowestCage, + p.room, + p.cage, + p.eventType, + p.goal, + p.observation, + p.outcome, + p.separationreason, + p.remark, + p.remark2, + p.enddate, + p.endeventType, + p.performedby, + p.taskid, + TIMESTAMPDIFF('SQL_TSI_DAY', p.date, coalesce(p.enddate,curdate())) as duration, + p.qcstate + +FROM study.pairings p +where p.eventtype in ('General Comment', 'Pair monitor') \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/pairingSummaryComments/.qview.xml b/onprc_ehr/resources/queries/study/pairingSummaryComments/.qview.xml new file mode 100644 index 000000000..f19f9408f --- /dev/null +++ b/onprc_ehr/resources/queries/study/pairingSummaryComments/.qview.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/queries/study/pairings/.qview.xml b/onprc_ehr/resources/queries/study/pairings/.qview.xml index c7dae903d..b4ddd890d 100644 --- a/onprc_ehr/resources/queries/study/pairings/.qview.xml +++ b/onprc_ehr/resources/queries/study/pairings/.qview.xml @@ -6,11 +6,14 @@ + + + + - diff --git a/onprc_ehr/resources/queries/study/Parasitology Results/.qview.xml b/onprc_ehr/resources/queries/study/parasitologyResults/.qview.xml similarity index 100% rename from onprc_ehr/resources/queries/study/Parasitology Results/.qview.xml rename to onprc_ehr/resources/queries/study/parasitologyResults/.qview.xml diff --git a/onprc_ehr/resources/queries/study/potentialDams.query.xml b/onprc_ehr/resources/queries/study/potentialDams.query.xml index fbe016be9..43404963f 100644 --- a/onprc_ehr/resources/queries/study/potentialDams.query.xml +++ b/onprc_ehr/resources/queries/study/potentialDams.query.xml @@ -5,6 +5,13 @@ Potential Dams This query identifies all female animals co-housed in the same room/cage at time of birth + + + study + animal + Id + + Dam Age At Birth (years) diff --git a/onprc_ehr/resources/queries/study/potentialDams.sql b/onprc_ehr/resources/queries/study/potentialDams.sql index 274277796..17b9e8362 100644 --- a/onprc_ehr/resources/queries/study/potentialDams.sql +++ b/onprc_ehr/resources/queries/study/potentialDams.sql @@ -1,40 +1,22 @@ /* * Copyright (c) 2013-2014 LabKey Corporation * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Updated 2020-04-23 by jones ga + * changed the source to a insert from a stored procedure */ SELECT - b.Id, - b.date as birth, - h.Id as potentialDam, - b.room as birthRoom, - b.cage as birthCage, - --NOTE: SQL_TSI_YEAR not support in postgres - (timestampdiff('SQL_TSI_DAY', h.Id.demographics.birth, b.date) / 365) as damAgeAtTime - -FROM study.birth b - -JOIN study.housing h ON ( - (b.Id != h.Id AND - h.dateOnly <= b.dateOnly AND - h.enddateCoalesced >= b.dateOnly AND - h.room = b.room AND (h.cage = b.cage OR (h.cage is null and b.cage is null)) - ) - --note: this is to always include observed parents - OR h.Id = b.dam -) + d.RowId, + d.participantId as id, + d.Date as birth, + d.Species, + d.room as birthroom, + d.cage as birthCage, + d.DamAgeAtTime, + d.potentialDam, + d.DamBirth, + d.Damgender, + d.DamSpecies, + d.DamDeath -WHERE h.id.demographics.gender = 'f' and timestampdiff('SQL_TSI_DAY', h.Id.demographics.birth, b.date) > 912.5 --(2.5 years) -AND h.Id.demographics.species = b.Id.demographics.species +from onprc_ehr.PotentialDam_source d -GROUP BY b.Id, b.date, b.room, b.cage, h.Id, h.Id.demographics.birth \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/potentialParents.query.xml b/onprc_ehr/resources/queries/study/potentialParents.query.xml index f6ce229cb..6e843cfd5 100644 --- a/onprc_ehr/resources/queries/study/potentialParents.query.xml +++ b/onprc_ehr/resources/queries/study/potentialParents.query.xml @@ -4,7 +4,13 @@ Potential Parents - + + + study + animal + Id + +
diff --git a/onprc_ehr/resources/queries/study/potentialSires.query.xml b/onprc_ehr/resources/queries/study/potentialSires.query.xml index 5f1b81e96..cc201d872 100644 --- a/onprc_ehr/resources/queries/study/potentialSires.query.xml +++ b/onprc_ehr/resources/queries/study/potentialSires.query.xml @@ -4,6 +4,13 @@ Potential Sires + + + study + animal + Id + + Sire Age At Conception Window (years) diff --git a/onprc_ehr/resources/queries/study/potentialSires.sql b/onprc_ehr/resources/queries/study/potentialSires.sql index a00af8b5e..f20548692 100644 --- a/onprc_ehr/resources/queries/study/potentialSires.sql +++ b/onprc_ehr/resources/queries/study/potentialSires.sql @@ -13,29 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -SELECT - c.Id, - h.Id as potentialSire, - group_concat(DISTINCT h.room) as rooms, - group_concat(DISTINCT h.cage) as cages, - --NOTE: SQL_TSI_YEAR not support in postgres - (max(timestampdiff('SQL_TSI_DAY', h.Id.demographics.birth, c.minDate)) / 365) as sireAgeAtTime - -FROM study.potentialConceptionLocations c ---then find all males overlapping with these locations that also overlap with the conception window -JOIN study.housing h ON (( - h.Id.demographics.gender = 'm' AND - h.room = c.room AND - (h.cage = c.cage OR (h.cage IS NULL AND c.cage IS NULL)) AND - h.dateOnly <= cast(c.maxDate as date) AND h.enddateCoalesced >= cast(c.minDate as date) -) +SELECT + d.RowId, + d.participantId as id, + d.Date as Birth, + d.Species, + d.room as birthRooom, + d.cage as birthCage, + d.sireAgeAtTime, + d.potentialSire, + d.SireBirth, + d.Siregender, + d.SireSpecies, + d.SireDeath ---note: this is to always include all observed sires -OR h.Id = c.Id.birth.sire -) +from onprc_ehr.PotentialSire_source d -WHERE timestampdiff('SQL_TSI_DAY', h.Id.demographics.birth, c.minDate) > 912.5 --(2.5 years) -AND h.Id.demographics.species = c.Id.demographics.species -GROUP BY c.Id, h.Id \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/Pregnancy Confirmations/.qview.xml b/onprc_ehr/resources/queries/study/pregnancyConfirmations/.qview.xml similarity index 100% rename from onprc_ehr/resources/queries/study/Pregnancy Confirmations/.qview.xml rename to onprc_ehr/resources/queries/study/pregnancyConfirmations/.qview.xml diff --git a/onprc_ehr/resources/queries/study/pregnancyGestation.sql b/onprc_ehr/resources/queries/study/pregnancyGestation.sql index b07f05eb3..82e0aecaf 100644 --- a/onprc_ehr/resources/queries/study/pregnancyGestation.sql +++ b/onprc_ehr/resources/queries/study/pregnancyGestation.sql @@ -18,7 +18,7 @@ SELECT m.id, m.date, m.gestation_days as gestation_days, -TIMESTAMPADD('SQL_TSI_DAY',(p.Gestation - m.gestation_days), curdate()) as ExpectedDelivery, +TIMESTAMPADD('SQL_TSI_DAY',(p.Gestation - m.gestation_days), m.date) as ExpectedDelivery, m.QCState FROM study.pregnancyConfirmation m diff --git a/onprc_ehr/resources/queries/study/processingSerology.sql b/onprc_ehr/resources/queries/study/processingSerology.sql index f908763c8..075cad4f2 100644 --- a/onprc_ehr/resources/queries/study/processingSerology.sql +++ b/onprc_ehr/resources/queries/study/processingSerology.sql @@ -65,7 +65,7 @@ SELECT END as isSRVCurrent, --all Jmacs and all non-SPF cynos CASE - WHEN (d.Id.age.ageInDays > 180 AND ((spf.Id IS NULL AND d.species = 'CYNOMOLGUS MACAQUE') OR d.species = 'JAPANESE MACAQUE')) THEN true + WHEN (d.Id.age.ageInDays > 180 AND ((spf.Id IS NULL AND (d.species = 'CYNOMOLGUS MACAQUE' OR d.species = 'RHESUS MACAQUE')) OR d.species = 'JAPANESE MACAQUE')) THEN true ELSE false END as isSRVRequired, diff --git a/onprc_ehr/resources/queries/study/TB Tests.js b/onprc_ehr/resources/queries/study/tb.js similarity index 100% rename from onprc_ehr/resources/queries/study/TB Tests.js rename to onprc_ehr/resources/queries/study/tb.js diff --git a/onprc_ehr/resources/queries/study/TB Tests.query.xml b/onprc_ehr/resources/queries/study/tb.query.xml similarity index 100% rename from onprc_ehr/resources/queries/study/TB Tests.query.xml rename to onprc_ehr/resources/queries/study/tb.query.xml diff --git a/onprc_ehr/resources/queries/study/tmbBirth.sql b/onprc_ehr/resources/queries/study/tmbBirth.sql new file mode 100644 index 000000000..894ff4738 --- /dev/null +++ b/onprc_ehr/resources/queries/study/tmbBirth.sql @@ -0,0 +1,41 @@ +--created 8/22/2018 by jonesga +--purpose to identify dual assigned animals for use with lease fee queries + +--We are now showing TMB assignments +--need to determine whether the Dam was assigned to the +--We are now showing TMB assignments +--need to determine whether the Dam was assigned to the +--Update 3/11/2019 Added to Test +Select distinct +b.id, +b.date, +--going to want to add the NonTMB Assignment data to the project details +a.project, +a.date as InfantAssignmentDate, +--(Select a3.id from study.assignment a3 where a3.id = b.dam and a3.project = a.project and a3.date <= b.date and a3.enddate > b.date or a3.enddate is null and a3.project <> 559) as DamAssignment, +b.dam, +t.id as TMBDam, +t.date as TMBAssignedDate, +t.endDate as TMBEndDate, + +da.dualassignment, +da.dualstartDate, +da.dualEndDate, + +t.enddate as RemovalDate, +--determine how the dam was assigned at the time of birth +Case + When a.project is not Null and b.dam in (Select a2.id from study.assignment a2 where a2.id = b.dam and a2.project = a.project and a2.date <= b.date and a2.enddate > b.date or a2.enddate is null) then 'Dam on Project' + When b.dam in (Select a2.id from study.assignment a2 where a2.id = b.dam and a2.project <> a.project and a2.date <= b.date and a2.enddate > b.date or a2.enddate is null) then 'Dam TMB Only' + --When then ' Dam TMB Only' + else 'Undetermined' + end as TMBDamStatus +-- WHEN MOM NOT on other project except TMB we will look for infant assignment within 30 days of birth to credit otherwisse it is P51 +--Determine if animal was not immediately assigned to a Research project and then assigned to a Research project within 30 days of its birth + + +from study.birth b join study.tmbdam t on b.dam = t.id + left join study.assignment a on (a.id = b.id and a.dateOnly = b.dateOnly) + left outer join study.dualAssigned da on (da.id = b.dam and a.project = da.dualAssignment + and (da.dualstartDate < b.date and da.dualendDate > b.date)) +where b.date > t.date \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/tmbDam.sql b/onprc_ehr/resources/queries/study/tmbDam.sql new file mode 100644 index 000000000..8f1cc7ae9 --- /dev/null +++ b/onprc_ehr/resources/queries/study/tmbDam.sql @@ -0,0 +1,10 @@ +--Update 3/11/2019 Added to Test + +SELECT a.Id, +a.id.demographics.gender, +a.project, +a.date, +a.projectedRelease, +a.enddate + +FROM assignment a where a.project = 559 and enddate is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/treatmentSchedule.sql b/onprc_ehr/resources/queries/study/treatmentSchedule.sql index df0911113..6a0e2e993 100644 --- a/onprc_ehr/resources/queries/study/treatmentSchedule.sql +++ b/onprc_ehr/resources/queries/study/treatmentSchedule.sql @@ -87,8 +87,10 @@ JOIN study."Treatment Orders" t1 --NOTE: should the enddate consider date/time? ON (dr.dateOnly >= t1.dateOnly and dr.dateOnly <= t1.enddateCoalesced AND --technically the first day of the treatment is day 1, not day 0 - mod(CAST(timestampdiff('SQL_TSI_DAY', CAST(t1.dateOnly as timestamp), dr.dateOnly) as integer), t1.frequency.intervalindays) = 0 - ) + ( (mod(CAST(timestampdiff('SQL_TSI_DAY', CAST(t1.dateOnly as timestamp), dr.dateOnly) as integer), t1.frequency.intervalindays) = 0 And t1.frequency.intervalindays is not null And t1.frequency.dayofweek is null ) + + OR (t1.frequency.dayofweek is not null And t1.frequency.intervalindays is null And dr.DayOfWeek in (select k.value from onprc_ehr.Frequency_DayofWeek k where k.FreqKey = t1.frequency.rowid ) ) ) + ) LEFT JOIN ehr.treatment_times tt ON (tt.treatmentid = t1.objectid) LEFT JOIN ehr_lookups.treatment_frequency_times ft ON (ft.frequency = t1.frequency.meaning AND tt.rowid IS NULL) @@ -110,7 +112,8 @@ WHERE t1.date is not null ) s ON (s.animalid = d.id) -WHERE d.calculated_status = 'Alive' +WHERE (d.lastDayatCenter Is Null or d.lastDayAtCenter > s.enddate) + --account for date/time in schedule and s.date >= s.startDate and s.date <= s.enddate \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/urinalysisPivot.sql b/onprc_ehr/resources/queries/study/urinalysisPivot.sql index c335bfef8..7b1b0add6 100644 --- a/onprc_ehr/resources/queries/study/urinalysisPivot.sql +++ b/onprc_ehr/resources/queries/study/urinalysisPivot.sql @@ -31,7 +31,7 @@ FROM WHERE b.testId.includeInPanel = true and b.qcstate.publicdata = true ) b - GROUP BY b.id, b.date, b.runId, b.testId, b.method, b.collectionmethod, b.remark + GROUP BY b.id, b.date, b.runId, b.testId, b.method, b.collectionmethod PIVOT results BY testId IN (select testid from ehr_lookups.urinalysis_tests t WHERE t.includeInPanel = true order by sort_order) ) pvt @@ -43,7 +43,7 @@ FROM b.method, b.collectionmethod, b.runId, - group_concat(distinct b.remark, chr(10)) as remark, + group_concat(distinct b.remark, chr(10)) as remark FROM ( @@ -53,12 +53,12 @@ FROM coalesce(b.runId, b.objectid) as runId, b.remark, b.method, - b.runid.collectionmethod, + b.runid.collectionmethod FROM study."Urinalysis Results" b WHERE b.testId.includeInPanel = true and b.qcstate.publicdata = true ) b - GROUP BY b.id, b.date, b.runId, b.method, b.collectionmethod, b.remark + GROUP BY b.id, b.date, b.runId, b.method, b.collectionmethod ) grp - ON pvt.id = grp.id AND pvt.date = grp.date AND pvt.method = grp.method AND pvt.runId = grp.runId AND pvt.collectionmethod = grp.collectionmethod + ON pvt.id = grp.id AND pvt.date = grp.date AND pvt.runId = grp.runId AND pvt.collectionmethod = grp.collectionmethod diff --git a/onprc_ehr/resources/queries/study/vet_assignedResearch.sql b/onprc_ehr/resources/queries/study/vet_assignedResearch.sql new file mode 100644 index 000000000..78587d425 --- /dev/null +++ b/onprc_ehr/resources/queries/study/vet_assignedResearch.sql @@ -0,0 +1,35 @@ +--20190410 - changed to address no assigned vet for protocol in research update1 +--Iss was this was not loaded at the prodctuib level + +SELECT distinct a.Id, + a.project, + a.project.use_category, + a.project.protocol, + a.project.protocol.investigatorID.lastName as PI, + a.date, + a.projectedRelease, + a.enddate, + a.assignCondition, + 'Research Assigned' as ProtocolType, + v.protocol.displayName as VetAssignedProtocol +FROM study.assignment a left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_ehr.vet_assignment v on a.project.protocol = v.protocol +where (a.project.use_category = 'Research') + and a.date = CurDate() and a.date = a.enddate + and v.protocol is not null + +Union + +SELECT a.Id, + a.project, + a.project.use_category, + a.project.protocol, + a.project.protocol.investigatorID.lastName as PI, + a.date, + a.projectedRelease, + a.enddate, + a.assignCondition, + 'Research Assigned' as ProtocolType, + v.protocol.displayName as VetAssignedProtocol +FROM study.assignment a left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_ehr.vet_assignment v on a.project.protocol = v.protocol +where ((a.date <= Now() and a.enddate is null) and (a.project.use_category = 'Research')) + and v.protocol is not null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/vet_assignedResource.sql b/onprc_ehr/resources/queries/study/vet_assignedResource.sql new file mode 100644 index 000000000..68d958c6d --- /dev/null +++ b/onprc_ehr/resources/queries/study/vet_assignedResource.sql @@ -0,0 +1,31 @@ +SELECT a.Id, + a.project, + a.project.use_category, + a.project.protocol, + a.project.protocol.investigatorID.lastName as PI, + a.date, + a.projectedRelease, + a.enddate, + a.assignCondition, + 'Resource Assigned' as ProtocolType, + v.protocol.displayName as VetAssignedProtocol +FROM study.assignment a left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_ehr.vet_assignment v on a.project.protocol = v.protocol +where ((a.date <= Now() and a.enddate is null) and (a.project.use_category != 'Research')) + +UNION + +SELECT a.Id, + a.project, + a.project.use_category, + a.project.protocol, + a.project.protocol.investigatorID.lastName as PI, + a.date, + a.projectedRelease, + a.enddate, + a.assignCondition, + 'Resource Assigned' as ProtocolType, + v.protocol.displayName as VetAssignedProtocol +FROM study.assignment a left outer join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.onprc_ehr.vet_assignment v on a.project.protocol = v.protocol +where (a.project.use_category != 'Research') + and a.date = CurDate() and a.date = a.enddate + and v.protocol is not null diff --git a/onprc_ehr/resources/queries/study/vet_assignmentDemographics.sql b/onprc_ehr/resources/queries/study/vet_assignmentDemographics.sql new file mode 100644 index 000000000..5dbfe2b4b --- /dev/null +++ b/onprc_ehr/resources/queries/study/vet_assignmentDemographics.sql @@ -0,0 +1,139 @@ +SELECT + Distinct + + Case + when dm.Id is not null then dm.id + else d.id + end as id, + b.gender, + b.species, + b.geographic_origin, + b.date, + dm.death as death, + dm.LastDayAtCenter, + h.room.area, + h.room, +--d.calculated_status, + Case + when dm.id is not null then dm.calculated_status + When d2.id = d.id then 'Deceased' + wHEN D1.ID = d.id then 'Shipped' + Else 'Unknown' + End + As Calculated_status, + + TimeStampAdd('SQL_TSI_YEAR', -1,Now()) as LastYear, + Case + when dm.calculated_status = 'alive' then Null + When n.assignedVet is not Null then n.assignedVet + when d3.assignedvet is not null then d3.assignedVet + -- when cr.date >TimeStampAdd('SQL_TSI_MONTH', -12,Now()) then 'Remark OVer 12 Months' + --when (n.assignedVet is null or d3.assignedVet is Null and cr.date >TimeStampAdd('SQL_TSI_MONTH', -12,Now()) ) then '' + Else Null + End as DeceasedAssignedVet, + +--n.assignedVet as DeceaseDAssignedVet, + c.vetNames as CaseVet, + c.category, + CASE + -- When cr.id is null then 'No Clin Remarks Found' + WHen dm.id = d.id and dm.calculated_status = 'dead' then 'Deceased NHP' + When (d3.id = d.id) then 'Deceased NHP' + WHEN (n.id IS NOT null) THEN 'SHIPPED NHP' + WHEN (c.id IS NOT NULL) THEN 'Active Case' + WHen r1.id is not null then 'Research Assigned' + WHen r2.id is not null then 'Resource Assigned' + + ELSE 'P51' + END as assignmentType, + + Case + when r1.protocol is not null then r1.use_Category + when r2.protocol is not null then r2.use_category + else ' ' + End As use_category, +--r1.use_Category, +--This needs to be a case statement that resturned the protocol whether Resource or research with research being the priority + + Case + when r1.protocol is not null then r1.VetAssignedProtocol + when r2.protocol is not null then r2.VetAssignedProtocol + else ' ' + End As protocol, + + Case + when r1.protocol is not null then r1.PI + when r2.protocol is not null then r2.PI + else ' ' + End As ProtocolPI + +--r1.protocol +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.animal d + +--Handles Shipped NHPs + +LEFT JOIN ( + select r.id, r.assignedVet + + + from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.departure d1 join study.clinremarks r on d1.id = r.id + where d1.date > TimeStampAdd('SQL_TSI_month', -12,Now()) + and r.date = (Select Max(r1.date) from study.clinremarks r1 where r1.id = d1.id)) + + + + n on (n.Id =d.id) + +--Handles Deceased NHPs + + LEFT JOIN ( + select d1.id, r.assignedVet + + + from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.demographics d1 join + Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.clinremarks r on d1.id = r.id + where (d1.date > TimeStampAdd('SQL_TSI_month', -12,Now()) and d1.calculated_status = 'dead' + and r.date = (Select Max(r1.date) from Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.clinremarks r1 where r1.id = d1.id))) + + + + d3 on (d3.Id =d.id) + + + + + +--Handles NHPS with open Cases + + LEFT JOIN ( + SELECT + c.Id, + c.category, + c.assignedvet.DisplayName as vetNames, + c.date + + FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.cases c + WHERE (c.category not in ('Behavior','Surgery') + and c.IsOpen= 'true') + --and c.enddateCoalesced >= curdate() ) + --and c.allProblemCategories not like 'Routine%' + GROUP BY c.Id,c.category,c.date,c.assignedvet.DisplayName + ) c ON (c.Id = d.Id) + +--Review for Assigned Animals + left Join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.birth b on b.id = d.id + Left Join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.vet_AssignedResearch r1 on d.id = r1.id + Left Join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.vet_assignedResource r2 on d.id = r2.id --and r2.id not in (Select r3.id from study.vet_AssignedResearch r3) + Left Join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.housing h on h.id = d.id and (h.enddateTimeCoalesced >= now()) + left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.deaths d1 on d.id = d1.id + left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.departure d2 on d2.id = d.id + left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.demographics dm on dm.id = d.id + --left join Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study.clinRemarks cr on cr.id = d.id + + +--report only on animals that are alive or deceased in last year +where + (d2.date is Null or Cast(d2.date as varchar(20)) > d.MostRecentArrival or (d2.date > TimeStampAdd('SQL_TSI_MONTH', -12,Now()))) + and (d.demographics.calculated_status is not null) --and +-- d.id not Like '[A-Z]%' + and (d1.date < TimeStampAdd('SQL_TSI_DAY',-90,d1.date) or d1.date is Null) \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/vet_assignmentselect.sql b/onprc_ehr/resources/queries/study/vet_assignmentselect.sql new file mode 100644 index 000000000..90854e092 --- /dev/null +++ b/onprc_ehr/resources/queries/study/vet_assignmentselect.sql @@ -0,0 +1,54 @@ +SELECT +d.Id, +d.room.area as Area, +d.room, + +Case + when d.deceaseDAssignedVet is not null then 'Deceased NHP' + when d.caseVet is not null then 'Open Case' + when v1.userId.userId.DisplayName is not null then 'research Room' + when v2.userId.userId.DisplayName is not null then 'REsearch Area' + when v3.userId.userId.DisplayName is not null then 'Resource Room' + when v4.userId.userId.DisplayName is not null then 'Resource Area' + when v5.userId.userId.DisplayName is not null then 'Research Only' + when v6.userId.userId.DisplayName is not null then 'Resource Only' + when p1.userId.userId.DisplayName is not null then 'Room Priority' + when p2.userId.userId.DisplayName is not null then 'AreaPriority' + when h1.userId.userId.DisplayName is not null then 'Room Only' + when h2.userId.userId.DisplayName is not null then 'Area Only' + Else ' ' + End as AssignmentType, + +d.deceaseDAssignedVet as DeceasedVet, +d.CaseVet, +v1.userId.userId.DisplayName as ResearchRoom, +v2.userId.userId.DisplayName as REsearchArea, +v3.userId.userId.DisplayName as REsourceRoom, +v4.userId.userId.DisplayName as ResourceArea, +v5.userId.userId.DisplayName as ResearchOnly, +v6.userId.userId.DisplayName as ResourceOnly, +p1.userId.userId.DisplayName as RoomPriority, +p2.userId.userId.DisplayName as AreaPriority, +h1.userId.userId.DisplayName as RoomOnly, +h2.userId.userId.DisplayName as AreaOnly + + +FROM study.vet_assignmentDemographics d +--this handles REsearch Protocol Room +Left Join onprc_ehr.vet_assignment v1 on (v1.protocol = d.protocol and v1.room = d.room and d.assignmentType = 'Research Assigned') +--this handles Research Protocol Area +Left Join onprc_ehr.vet_assignment v2 on (v2.protocol = d.protocol and v2.area = d.room.area and d.assignmentType = 'Research Assigned') +--this handles Resource Protocol Room +Left Join onprc_ehr.vet_assignment v3 on (v3.protocol = d.protocol and v3.room = d.room and d.assignmentType = 'Resource Assigned') +--this handles Research Protocol Area +Left Join onprc_ehr.vet_assignment v4 on (v4.protocol = d.protocol and v4.area = d.room.area and d.assignmentType = 'Resource Assigned') +--this handled Research Assigned No Additional Sekections +Left Join onprc_ehr.vet_assignment v5 on (v5.protocol = d.protocol and d.assignmentType = 'Research Assigned' and (v5.area is null and v5.room is null)) +--this handles resource Protocol Only +Left Join onprc_ehr.vet_assignment v6 on (v6.protocol = d.protocol and d.assignmentType = 'Resource Assigned' and (v6.area is null and v5.room is null)) +--this handles when the room is a priorty +Left join onprc_ehr.vet_assignment p1 on (p1.room = d.room and p1.priority = true) +--this handles when the room is a priorty +Left join onprc_ehr.vet_assignment p2 on (p2.area = d.room.area and p2.priority = true) +Left join onprc_ehr.vet_assignment h1 on (h1.room = d.room and h1.priority = false) +Left join onprc_ehr.vet_assignment h2 on (h2.area = d.room.area and h2.priority = false) diff --git a/onprc_ehr/resources/referenceStudy/datasets/datasets_manifest.xml b/onprc_ehr/resources/referenceStudy/datasets/datasets_manifest.xml index fb3170d99..68528b111 100644 --- a/onprc_ehr/resources/referenceStudy/datasets/datasets_manifest.xml +++ b/onprc_ehr/resources/referenceStudy/datasets/datasets_manifest.xml @@ -146,5 +146,8 @@ + + + diff --git a/onprc_ehr/resources/referenceStudy/datasets/datasets_metadata.xml b/onprc_ehr/resources/referenceStudy/datasets/datasets_metadata.xml index 784dafb35..989d3c8f7 100644 --- a/onprc_ehr/resources/referenceStudy/datasets/datasets_metadata.xml +++ b/onprc_ehr/resources/referenceStudy/datasets/datasets_metadata.xml @@ -874,6 +874,9 @@ varchar + + varchar + Clinical Remarks
@@ -1235,6 +1238,9 @@ varchar + + varchar +
Chemistry Results @@ -1390,6 +1396,9 @@ varchar + + varchar + varchar @@ -1717,6 +1726,9 @@ timestamp + + varchar +
Assignment @@ -2254,6 +2266,9 @@ varchar + + varchar + varchar @@ -2269,6 +2284,9 @@ varchar + + varchar + integer urn:ehr.labkey.org/#Project @@ -2395,4 +2413,46 @@ Organ Weights + + + + varchar + http://cpas.labkey.com/Study#ParticipantId + + ptid + + + + timestamp + http://cpas.labkey.com/Study#VisitDate + http://cpas.labkey.com/Study#VisitDate + + + timestamp + urn:ehr.labkey.org/#EndDate + + + varchar + + + varchar + + + varchar + + + varchar + + + integer + urn:ehr.labkey.org/#Project + + + entityid + urn:ehr.labkey.org/#ObjectId + true + + + StudyDetails +
diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-0.00-18.10.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-0.00-18.10.sql new file mode 100644 index 000000000..094bacee8 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-0.00-18.10.sql @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2012 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* onprc_ehr-12.20-12.30.sql */ + +/* onprc_ehr-12.20-12.21.sql */ + +CREATE SCHEMA onprc_ehr; +GO +CREATE TABLE onprc_ehr.etl_runs +( + RowId int identity(1,1), + date datetime, + + Container ENTITYID NOT NULL, + + CONSTRAINT PK_etl_runs PRIMARY KEY (rowId) +); + +/* onprc_ehr-12.21-12.22.sql */ + +ALTER TABLE onprc_ehr.etl_runs ADD queryname varchar(200); +ALTER TABLE onprc_ehr.etl_runs ADD rowversion varchar(200); + +CREATE TABLE onprc_ehr.investigators ( + rowId int identity(1,1) NOT NULL, + firstName varchar(100), + lastName varchar(100), + position varchar(100), + address varchar(500), + city varchar(100), + state varchar(100), + country varchar(100), + zip varchar(100), + phoneNumber varchar(100), + investigatorType varchar(100), + emailAddress varchar(100), + dateCreated datetime, + dateDisabled datetime, + division varchar(100), + financialAnalyst int, + + createdby userid, + created datetime, + modifiedby userid, + modified datetime, + CONSTRAINT pk_investigators PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_ehr.investigators ADD objectid ENTITYID; + +alter table onprc_ehr.investigators add assignedVet int; + +create table onprc_ehr.serology_test_schedule ( + rowid int identity(1,1), + code varchar(100), + flag varchar(100), + interval int, + + CONSTRAINT PK_serology_test_schedule PRIMARY KEY (rowid) +); + +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32140','SPF', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY351','SPF', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3284','SPF', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY331','SPF', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32221','SPF 9', 1); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32140','SPF 9', 3); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32218','SPF 9', 1); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY351','SPF 9', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY370','SPF 9', 1); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3283','SPF 9', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3284','SPF 9', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3287','SPF 9', 12); +INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY331','SPF 9', 12); + +--implemented based on SQLServer database engine tuning monitor +CREATE INDEX investigators_rowid_lastname ON onprc_ehr.investigators (rowid, lastname); + +CREATE TABLE onprc_ehr.tissue_recipients ( + rowId int identity(1,1) NOT NULL, + firstName varchar(100), + lastName varchar(100), + institution varchar(100), + + title varchar(1000), + affiliation varchar(1000), + address varchar(1000), + city varchar(100), + state varchar(100), + country varchar(100), + zip varchar(100), + phoneNumber varchar(100), + recipientType varchar(100), + emailAddress varchar(100), + + shipAddress varchar(1000), + shipCity varchar(100), + shipState varchar(100), + shipCountry varchar(100), + shipZip varchar(100), + + dateCreated DATETIME, + dateDisabled DATETIME, + + investigatorId int, + + objectid entityid, + container entityid, + createdby userid, + created DATETIME, + modifiedby userid, + modified DATETIME, + CONSTRAINT pk_tissue_recipients PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_ehr.investigators ADD userid int; + +ALTER TABLE onprc_ehr.investigators ADD employeeid varchar(100); + +--added to facilitate the split billing code into a separate module from ONPRC_EHR. +--this should cause the server to think all existing scripts were in fact run, even though they ran as the onprc_ehr module +INSERT INTO core.SqlScripts (Created, Createdby, Modified, Modifiedby, FileName, ModuleName) +SELECT Created, Createdby, Modified, Modifiedby, FileName, 'ONPRC_Billing' as ModuleName +FROM core.SqlScripts +WHERE FileName LIKE 'onprc_billing-%'AND ModuleName = 'ONPRC_EHR'; + +CREATE TABLE onprc_ehr.vet_assignment ( + rowid int identity(1,1), + userid int, + area varchar(100), + protocol varchar(100), + + container ENTITYID NOT NULL, + created datetime, + createdby int, + modified datetime, + modifiedby int, + + CONSTRAINT PK_vet_assignment PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_ehr.vet_assignment add room varchar(100); + +ALTER TABLE onprc_ehr.vet_assignment add priority integer; + +EXEC sp_rename 'onprc_ehr.tissue_recipients', 'customers'; + +ALTER TABLE onprc_ehr.vet_assignment DROP COLUMN priority; +GO +ALTER TABLE onprc_ehr.vet_assignment add priority bit; + +CREATE TABLE onprc_ehr.housing_transfer_requests ( + Id varchar(100), + date datetime, + room varchar(200), + cage varchar(100), + reason varchar(100), + remark varchar(4000), + qcstate int, + + requestid entityid, + objectid entityid NOT NULL, + container entityid, + created datetime, + createdby int, + modified datetime, + modifiedby int, + + CONSTRAINT PK_housing_transfer_requests PRIMARY KEY (objectid) +); + +ALTER TABLE onprc_ehr.housing_transfer_requests ADD divider integer; +ALTER TABLE onprc_ehr.housing_transfer_requests ADD formSort integer; + +UPDATE ehr.tasks SET formtype = 'Bulk Clinical Entry' WHERE formtype = 'Clinical Remarks'; + +CREATE TABLE onprc_ehr.birth_condition ( + rowid int identity(1,1), + value varchar(200), + alive bit, + description varchar(4000), + container entityid, + createdby int, + created datetime, + modifiedby int, + modified datetime, + + CONSTRAINT PK_birth_condition PRIMARY KEY (rowid) +); + +--this should be OK since we declare a dependency on EHR, meaning its scripts will run first +UPDATE ehr.qcStateMetadata SET draftData = 1 WHERE QCStateLabel = 'Request: Pending'; + +CREATE TABLE onprc_ehr.observation_types ( + value varchar(200), + category varchar(200), + editorconfig varchar(4000), + schemaname varchar(200), + queryname varchar(200), + valuecolumn varchar(200), + createdby int, + created datetime, + modifiedby int, + modified datetime, + + CONSTRAINT PK_observation_types PRIMARY KEY (value) +); + +ALTER TABLE onprc_ehr.serology_test_schedule ADD species VARCHAR(100); + +CREATE TABLE onprc_ehr.encounter_summaries_remarks ( + + id varchar(100), + date datetime, + parentid entityid, + schemaName varchar(100), + queryName varchar(100), + remark text, + + objectid varchar(60) NOT NULL, + container entityid NOT NULL, + createdby smallint, + created datetime, + modifiedby smallint, + modified datetime, + taskid entityid, + category varchar(100), + formsort integer + + constraint pk_encounter_summaries_remarks PRIMARY KEY (objectid) +); + +CREATE TABLE onprc_ehr.NHP_Training( + RowId INT IDENTITY(1,1)NOT NULL, + Id varchar(100), + date datetime NULL, + training_Ending_Date datetime NULL, + training_type varchar(255) NULL, + reason varchar(255) NULL, + qcstate INTEGER NULL, + taskid nvarchar(4000) NULL, + remark nvarchar(4000) NULL, + objectid ENTITYID NOT NULL, + formSort SMALLINT NULL, + performedby nvarchar(4000) NULL, + createdby int NULL, + created datetime NULL, + modifiedby int NULL, + modified datetime NULL, + Container ENTITYID, + training_results varchar(255) NULL + + CONSTRAINT PK_NHPTrainingObject PRIMARY KEY (objectid) +); + +GO + + +---- BEGIN contents of onprc_ehr-17.20-17.21.sql (script in release20.7-SNAPSHOT), which is also in onprc_ehr-20.414-20.415.sql (script in onprc19.1Prod) +-- Upgrading from release20.7-SNAPSHOT (module v. 18.10), will already have below run as part of onprc_ehr-17.20-17.21.sql +-- Upgrading from onprc19.1Prod (module v. 20.417), will already have below run as part of onprc_ehr-20.414-20.415.sql + +--Add container column +ALTER TABLE onprc_ehr.observation_types ADD container entityid; +GO + +--Add container ids to onprc_ehr.observation_types: +UPDATE onprc_ehr.observation_types +SET container = (SELECT c.entityid FROM core.containers c + LEFT JOIN core.Containers c2 ON c.Parent = c2.EntityId + WHERE c.name = 'EHR' and c2.name = 'ONPRC') +WHERE container IS NULL; +GO + +--copy data into ehr table +INSERT INTO ehr.observation_types +(value, + category, + editorconfig, + schemaName, + queryName, + valueColumn, + createdby, + created, + modifiedby, + modified, + container +) +SELECT + value, + category, + editorconfig, + schemaName, + queryName, + valueColumn, + createdby, + created, + modifiedby, + modified, + container +FROM onprc_ehr.observation_types obs +WHERE obs.container IS NOT NULL; +GO + +--drop table +DROP TABLE onprc_ehr.observation_types +GO + +---- END contents of onprc_ehr-17.20-17.21.sql... diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.20-12.30.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.20-12.30.sql deleted file mode 100644 index 29d03c31c..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.20-12.30.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* onprc_ehr-12.20-12.21.sql */ - -CREATE SCHEMA onprc_ehr; -GO -CREATE TABLE onprc_ehr.etl_runs -( - RowId int identity(1,1), - date datetime, - - Container ENTITYID NOT NULL, - - CONSTRAINT PK_etl_runs PRIMARY KEY (rowId) -); - -/* onprc_ehr-12.21-12.22.sql */ - -ALTER TABLE onprc_ehr.etl_runs ADD queryname varchar(200); -ALTER TABLE onprc_ehr.etl_runs ADD rowversion varchar(200); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.21-12.22.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.21-12.22.sql deleted file mode 100644 index 131030e73..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.21-12.22.sql +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.etl_runs ADD queryname varchar(200); -ALTER TABLE onprc_ehr.etl_runs ADD rowversion varchar(200); diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.302-12.303.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.302-12.303.sql deleted file mode 100644 index 3940d6758..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.302-12.303.sql +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.investigators ( - rowId int identity(1,1) NOT NULL, - firstName varchar(100), - lastName varchar(100), - position varchar(100), - address varchar(500), - city varchar(100), - state varchar(100), - country varchar(100), - zip varchar(100), - phoneNumber varchar(100), - investigatorType varchar(100), - emailAddress varchar(100), - dateCreated datetime, - dateDisabled datetime, - division varchar(100), - financialAnalyst int, - - createdby userid, - created datetime, - modifiedby userid, - modified datetime, - CONSTRAINT pk_investigators PRIMARY KEY (rowid) -); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.308-12.309.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.308-12.309.sql deleted file mode 100644 index b9aa0cb3e..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.308-12.309.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.investigators ADD objectid ENTITYID; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.311-12.312.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.311-12.312.sql deleted file mode 100644 index c24f3560f..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.311-12.312.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -alter table onprc_ehr.investigators add assignedVet int; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.312-12.313.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.312-12.313.sql deleted file mode 100644 index c0d99ea78..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.312-12.313.sql +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -create table onprc_ehr.serology_test_schedule ( - rowid int identity(1,1), - code varchar(100), - flag varchar(100), - interval int, - - CONSTRAINT PK_serology_test_schedule PRIMARY KEY (rowid) -); - -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32140','SPF', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY351','SPF', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3284','SPF', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY331','SPF', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32221','SPF 9', 1); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32140','SPF 9', 3); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-32218','SPF 9', 1); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY351','SPF 9', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY370','SPF 9', 1); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3283','SPF 9', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3284','SPF 9', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-Y3287','SPF 9', 12); -INSERT INTO onprc_ehr.serology_test_schedule (code, flag, interval) VALUES ('E-YY331','SPF 9', 12); diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.313-12.314.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.313-12.314.sql deleted file mode 100644 index f8162950d..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.313-12.314.sql +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---implemented based on SQLServer database engine tuning monitor -CREATE INDEX investigators_rowid_lastname ON onprc_ehr.investigators (rowid, lastname); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.314-12.315.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.314-12.315.sql deleted file mode 100644 index 3210dffa4..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.314-12.315.sql +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.tissue_recipients ( - rowId int identity(1,1) NOT NULL, - firstName varchar(100), - lastName varchar(100), - institution varchar(100), - - title varchar(1000), - affiliation varchar(1000), - address varchar(1000), - city varchar(100), - state varchar(100), - country varchar(100), - zip varchar(100), - phoneNumber varchar(100), - recipientType varchar(100), - emailAddress varchar(100), - - shipAddress varchar(1000), - shipCity varchar(100), - shipState varchar(100), - shipCountry varchar(100), - shipZip varchar(100), - - dateCreated DATETIME, - dateDisabled DATETIME, - - investigatorId int, - - objectid entityid, - container entityid, - createdby userid, - created DATETIME, - modifiedby userid, - modified DATETIME, - CONSTRAINT pk_tissue_recipients PRIMARY KEY (rowid) -); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.333-12.334.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.333-12.334.sql deleted file mode 100644 index e78e3bc07..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.333-12.334.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.investigators ADD userid int; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.335-12.336.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.335-12.336.sql deleted file mode 100644 index 7a4abf5ac..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.335-12.336.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2013 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.investigators ADD employeeid varchar(100); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.350-12.351.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.350-12.351.sql deleted file mode 100644 index 6192a1b75..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.350-12.351.sql +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---added to facilitate the split billing code into a separate module from ONPRC_EHR. ---this should cause the server to think all existing scripts were in fact run, even though they ran as the onprc_ehr module -INSERT INTO core.SqlScripts (Created, Createdby, Modified, Modifiedby, FileName, ModuleName) -SELECT Created, Createdby, Modified, Modifiedby, FileName, 'ONPRC_Billing' as ModuleName -FROM core.SqlScripts -WHERE FileName LIKE 'onprc_billing-%'AND ModuleName = 'ONPRC_EHR'; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.352-12.353.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.352-12.353.sql deleted file mode 100644 index 661fbfe04..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.352-12.353.sql +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.vet_assignment ( - rowid int identity(1,1), - userid int, - area varchar(100), - protocol varchar(100), - - container ENTITYID NOT NULL, - created datetime, - createdby int, - modified datetime, - modifiedby int, - - CONSTRAINT PK_vet_assignment PRIMARY KEY (rowid) -); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.353-12.354.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.353-12.354.sql deleted file mode 100644 index 6194624d3..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.353-12.354.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.vet_assignment add room varchar(100); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.354-12.355.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.354-12.355.sql deleted file mode 100644 index 520e0f8ca..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.354-12.355.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.vet_assignment add priority integer; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.355-12.356.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.355-12.356.sql deleted file mode 100644 index 17e8cd6cf..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.355-12.356.sql +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -EXEC sp_rename 'onprc_ehr.tissue_recipients', 'customers'; - -ALTER TABLE onprc_ehr.vet_assignment DROP COLUMN priority; -GO -ALTER TABLE onprc_ehr.vet_assignment add priority bit; diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.356-12.357.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.356-12.357.sql deleted file mode 100644 index 6eeccc4e9..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.356-12.357.sql +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.housing_transfer_requests ( - Id varchar(100), - date datetime, - room varchar(200), - cage varchar(100), - reason varchar(100), - remark varchar(4000), - qcstate int, - - requestid entityid, - objectid entityid NOT NULL, - container entityid, - created datetime, - createdby int, - modified datetime, - modifiedby int, - - CONSTRAINT PK_housing_transfer_requests PRIMARY KEY (objectid) -); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.357-12.358.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.357-12.358.sql deleted file mode 100644 index 7f3200967..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.357-12.358.sql +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.housing_transfer_requests ADD divider integer; -ALTER TABLE onprc_ehr.housing_transfer_requests ADD formSort integer; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.358-12.359.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.358-12.359.sql deleted file mode 100644 index ffa55b6dd..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.358-12.359.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -UPDATE ehr.tasks SET formtype = 'Bulk Clinical Entry' WHERE formtype = 'Clinical Remarks'; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.359-12.360.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.359-12.360.sql deleted file mode 100644 index 30947e8b6..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.359-12.360.sql +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.birth_condition ( - rowid int identity(1,1), - value varchar(200), - alive bit, - description varchar(4000), - container entityid, - createdby int, - created datetime, - modifiedby int, - modified datetime, - - CONSTRAINT PK_birth_condition PRIMARY KEY (rowid) -); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.360-12.361.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.360-12.361.sql deleted file mode 100644 index bd6a0891f..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.360-12.361.sql +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ ---this should be OK since we declare a dependency on EHR, meaning its scripts will run first -UPDATE ehr.qcStateMetadata SET draftData = 1 WHERE QCStateLabel = 'Request: Pending'; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.361-12.362.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.361-12.362.sql deleted file mode 100644 index db9d609c3..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.361-12.362.sql +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.observation_types ( - value varchar(200), - category varchar(200), - editorconfig varchar(4000), - schemaname varchar(200), - queryname varchar(200), - valuecolumn varchar(200), - createdby int, - created datetime, - modifiedby int, - modified datetime, - - CONSTRAINT PK_observation_types PRIMARY KEY (value) -); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.362-12.363.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.362-12.363.sql deleted file mode 100644 index 5ebb8da11..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.362-12.363.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2014 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -ALTER TABLE onprc_ehr.serology_test_schedule ADD species VARCHAR(100); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.371-12.372.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.371-12.372.sql deleted file mode 100644 index 61d7369ed..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.371-12.372.sql +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2016-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.encounter_summaries_remarks ( - - id varchar(100), - date datetime, - parentid entityid, - schemaName varchar(100), - queryName varchar(100), - remark text, - - objectid varchar(60) NOT NULL, - container entityid NOT NULL, - createdby smallint, - created datetime, - modifiedby smallint, - modified datetime, - taskid entityid, - category varchar(100), - formsort integer - - constraint pk_encounter_summaries_remarks PRIMARY KEY (objectid) -); diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.378-12.379.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.378-12.379.sql deleted file mode 100644 index f2be1bb8e..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-12.378-12.379.sql +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2016-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -CREATE TABLE onprc_ehr.NHP_Training( - RowId INT IDENTITY(1,1)NOT NULL, - Id varchar(100), - date datetime NULL, - training_Ending_Date datetime NULL, - training_type varchar(255) NULL, - reason varchar(255) NULL, - qcstate INTEGER NULL, - taskid nvarchar(4000) NULL, - remark nvarchar(4000) NULL, - objectid ENTITYID NOT NULL, - formSort SMALLINT NULL, - performedby nvarchar(4000) NULL, - createdby int NULL, - created datetime NULL, - modifiedby int NULL, - modified datetime NULL, - Container ENTITYID, - training_results varchar(255) NULL - - CONSTRAINT PK_NHPTrainingObject PRIMARY KEY (objectid) -); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-17.20-17.21.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-17.20-17.21.sql deleted file mode 100644 index 06e332521..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-17.20-17.21.sql +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - */ - ---Add container column -ALTER TABLE onprc_ehr.observation_types ADD container entityid; -GO - ---Add container ids to onprc_ehr.observation_types: -UPDATE onprc_ehr.observation_types -SET container = (SELECT c.entityid FROM core.containers c - LEFT JOIN core.Containers c2 ON c.Parent = c2.EntityId - WHERE c.name = 'EHR' and c2.name = 'ONPRC') -WHERE container IS NULL; -GO - ---copy data into ehr table -INSERT INTO ehr.observation_types -(value, -category, -editorconfig, -schemaName, -queryName, -valueColumn, -createdby, -created, -modifiedby, -modified, -container -) -SELECT - value, - category, - editorconfig, - schemaName, - queryName, - valueColumn, - createdby, - created, - modifiedby, - modified, - container -FROM onprc_ehr.observation_types obs -WHERE obs.container IS NOT NULL; -GO - ---drop table -DROP TABLE onprc_ehr.observation_types -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-18.10-20.101.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-18.10-20.101.sql new file mode 100644 index 000000000..984499a18 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-18.10-20.101.sql @@ -0,0 +1,835 @@ +-- includes content of onprc_ehr-12.395-12.396.sql to onprc_ehr-17.704-17.705.sql from onprc19.1Prod + +/****** Object: StoredProcedure [onprc_ehr].[etl1_eIACUCtoPRIMEProcessing] Script Date: 2/7/2018 2:01:46 PM ******/ +Create PROCEDURE onprc_ehr.etlStep1eIACUCtoPRIMEProcessing +AS +Begin + +Update [onprc_ehr].[PRIME_VIEW_PROTOCOL_Processing] +set modifiedby = 000,modified = GetDate() + where modified is Null + + + +INSERT INTO [onprc_ehr].[PRIME_VIEW_PROTOCOL_Processing] +( + [Protocol_ID] +,[Template_OID] +,[Protocol_OID] +,[Protocol_Title] +,[PI_ID] +,[PI_First_Name] +,[PI_Last_Name] +,[PI_Email] +,[PI_Phone] +,[USDA_Level] +,[ProcessDate] +,[Approval_Date] +,[Annual_Update_Due] +,[Three_year_Expiration] +,[Last_Modified] +,created +,createdby +,recordStatus +,PPQ_Numbers +,PROTOCOL_State + + +) +Select + Distinct + e.Protocol_ID, + e.Template_OID, + CONVERT(BINARY(16),e.Protocol_OID,2) as Protocol_OID, + e.Protocol_Title, + e.PI_ID, + e.PI_First_Name, + e.PI_Last_Name, + e.PI_Email, + e.PI_Phone, + e.USDA_Level, + GetDate () as ProcessDate, + e.Approval_Date, + e.Annual_Update_Due, + e.Three_year_Expiration, + e.Last_Modified, + GetDate(), + 1011, + + Case + When e.protocol_ID in + (Select e1.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e1 left outer join onprc_ehr.protocol p on p.external_id = e1.protocol_id where p.external_ID is Null) then 'new Record' + --in the update state we look at each possible area for change + When e.protocol_ID in + (Select e1.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e1 + left outer join onprc_ehr.protocol p on p.external_id = e1.protocol_id + where e1.Template_OID <> p.template_oid) then 'Update TemplateOID' + When e.protocol_ID in + (Select e2.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e2 + left outer join onprc_ehr.protocol p on p.external_id = e2.protocol_id + where e2.PPQ_numbers <> p.PPQ_Numbers) then 'Update PPQ Change' + When e.protocol_ID in + (Select e3.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e3 + left outer join onprc_ehr.protocol p on p.external_id = e3.protocol_id + where e3.Protocol_State <> p.PROTOCOL_State) then 'Update Protocol State' + When e.protocol_ID in + (Select e4.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e4 + left outer join onprc_ehr.protocol p on p.external_id = e4.protocol_id + where e4.Protocol_Title <> p.title) then 'Update Protocol Title' + else 'No Change' + End as RecordStatus + ,e.PPQ_Numbers + ,e.PROTOCOL_State + +from [onprc_ehr].[PRIME_VIEW_PROTOCOLS] e + + + + + If @@Error <> 0 + GoTo Err_Proc + + + + + + Return 0 + + Err_Proc: Return 1 + +END +GO +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.animalGroups Dataset which is populated by the ETL Process + * + */ +CREATE TABLE [onprc_ehr].[PRIME_VIEW_ANIMAL_GROUPS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Parent_Protocol] [varchar](255) NOT NULL, + [Group_ID] [varchar](255) NULL, + [Group_Name] [varchar](255) NULL, + [Species] [varchar](255) NULL, + [SPF_Status] [varchar](255) NULL, + [Weight_Start] [varchar](255) NULL, + [Weight_End] [varchar](255) NULL, + [Age_Start] [varchar](255) NULL, + [Age_End] [varchar](255) NULL, + [Gender] [varchar](255) NULL, + [Number_of_Animals_Max] [int] NULL, + [Non_Standard_Housing_Types] [nvarchar](max) NULL, + [Non_Standard_Housing_Description] [ntext] NULL, + [Non_Standard_Housing_Frequency_and_Duration] [ntext] NULL, + [Non_Standard_Housing_Monitoring] [ntext] NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL, + [Restraint] [nvarchar](max) NULL, + [Nutritional_Manipulation_Description] [ntext] NULL, + [Nutritional_Manipulation_Adverse_Consequences] [nvarchar](255) NULL, + [Nutritional_Manipulation_Health_Assessment] [nchar](10) NULL, + [Non_Pharmaceutical_Grade_Drug_Use] [ntext] NULL, + [Food_Withheld] [int] NULL, + [Water_Withheld] [int] NULL, + [Food_Water_Withheld_Description] [ntext] NULL, + [Food_Water_Withheld_Justification] [ntext] NULL, + [Food_Water_Withheld_Adverse_Consequences] [ntext] NULL, + [Death_As_Endpoint_Number_of_Animals] [nvarchar](255) NULL, + [Death_As_Endpoint_Justification] [ntext] NULL + ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.IBC_Numberss Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[PRIME_VIEW_IBC_NUMBERS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Animal_Group] [varchar](255) NOT NULL, + [IBC_Registration_Number] [varchar](255) NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL + ) ON [PRIMARY] + GO + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.PRIME_VIEW_NON_SURGICAL_PROCS Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[PRIME_VIEW_NON_SURGICAL_PROCS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Animal_Group] [varchar](255) NOT NULL, + [NS_Procedure_Name] [varchar](255) NULL, + [Standard_Procedure] [int] NULL, + [Iterations] [int] NULL, + [Deviation] [int] NULL, + [Deviation_Description] [varchar](255) NULL, + [Recovery_Days] [int] NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL + ) ON [PRIMARY] + GO + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.PRIME_VIEW_PROTOCOL_Processing Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[PRIME_VIEW_PROTOCOL_Processing]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Protocol_ID] [varchar](255) NOT NULL, + [Template_OID] [varchar](32) NULL, + [Protocol_OID] [binary](16) NULL, + [Protocol_Title] [varchar](255) NULL, + [PI_ID] [varchar](255) NULL, + [PI_First_Name] [varchar](255) NULL, + [PI_Last_Name] [varchar](255) NULL, + [PI_Email] [varchar](255) NULL, + [PI_Phone] [varchar](255) NULL, + [USDA_Level] [varchar](255) NULL, + [ProcessDate] [datetime] NULL, + [Approval_Date] [datetime] NULL, + [Annual_Update_Due] [datetime] NULL, + [Three_year_Expiration] [datetime] NULL, + [Last_Modified] [datetime] NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL, + [recordstatus] [nchar](25) NULL, + [PROTOCOL_STATE] [varchar](100) NULL, + [PPQ_Numbers] [varchar](255) NULL + ) ON [PRIMARY] + GO + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.PRIME_VIEW_PROTOCOLS Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[PRIME_VIEW_PROTOCOLS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Protocol_ID] [varchar](255) NOT NULL, + [Template_OID] [varchar](32) NULL, + [Protocol_OID] [varchar](255) NULL, + [Protocol_Title] [varchar](255) NULL, + [PI_ID] [varchar](255) NULL, + [PI_First_Name] [varchar](255) NULL, + [PI_Last_Name] [varchar](255) NULL, + [PI_Email] [varchar](255) NULL, + [PI_Phone] [varchar](255) NULL, + [USDA_Level] [varchar](255) NULL, + [Approval_Date] [datetime] NULL, + [Annual_Update_Due] [datetime] NULL, + [Three_year_Expiration] [datetime] NULL, + [Last_Modified] [datetime] NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL, + [PROTOCOL_State] [varchar](250) NULL, + [PPQ_Numbers] [varchar](255) NULL, + [Description] [varchar](255) NULL + ) ON [PRIMARY] + GO + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.PRIME_VIEW_SURGICAL_PROCS Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[PRIME_VIEW_SURGICAL_PROCS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [OID] [int] NOT NULL, + [Animal_Group] [varchar](255) NOT NULL, + [Standard_Procedure] [int] NULL, + [Iterations] [int] NULL, + [Deviation] [int] NULL, + [Deviation_Description] [varchar](255) NULL, + [Recovery_Days] [int] NULL, + [Surgery_Name] [varchar](255) NULL + ) ON [PRIMARY] + GO + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.project Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[project]( + [project] [int] NOT NULL, + [protocol] [varchar](200) NULL, + [account] [varchar](200) NULL, + [inves] [varchar](200) NULL, + [avail] [varchar](100) NULL, + [title] [varchar](200) NULL, + [research] [bit] NULL, + [reqname] [varchar](200) NULL, + [createdby] [int] NOT NULL, + [created] [datetime] NULL, + [modifiedby] [int] NOT NULL, + [modified] [datetime] NULL, + [contact_emails] [varchar](4000) NULL, + [startdate] [datetime] NULL, + [enddate] [datetime] NULL, + [inves2] [varchar](200) NULL, + [name] [varchar](100) NULL, + [investigatorId] [int] NULL, + [use_category] [varchar](100) NULL, + [alwaysavailable] [bit] NULL, + [shortname] [varchar](200) NULL, + [projecttype] [varchar](100) NULL, + [container] [uniqueidentifier] NULL, + [objectid] [uniqueidentifier] NOT NULL + ) ON [PRIMARY] + GO + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.protocol Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[protocol]( + [rowId] [int] IDENTITY(1,1) NOT NULL, + [protocol] [varchar](200) NOT NULL, + [inves] [varchar](200) NULL, + [approve] [datetime] NULL, + [description] [text] NULL, + [createdby] [int] NOT NULL, + [created] [datetime] NULL, + [modifiedby] [int] NOT NULL, + [modified] [datetime] NULL, + [maxanimals] [int] NULL, + [enddate] [datetime] NULL, + [title] [varchar](1000) NULL, + [usda_level] [varchar](100) NULL, + [external_id] [varchar](200) NULL, + [project_type] [varchar](200) NULL, + [ibc_approval_required] [bit] NULL, + [ibc_approval_num] [varchar](200) NULL, + [investigatorId] [int] NULL, + [last_modification] [datetime] NULL, + [first_approval] [datetime] NULL, + [container] [uniqueidentifier] NULL, + [objectid] [uniqueidentifier] NOT NULL, + [lastAnnualReview] [datetime] NULL, + [PROTOCOL_State] [varchar](250) NULL, + [PPQ_Numbers] [varchar](255) NULL, + [template_oid] [varchar](255) NULL, + [Restraint] [varchar](255) NULL + ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + GO + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the Stored Procedure etl1_eIACUCtoPRIMEProcessing + * + */ + +DROP PROCEDURE onprc_ehr.etlStep1eIACUCtoPRIMEProcessing; +GO + +/****** Object: StoredProcedure [onprc_ehr].[etl1_eIACUCtoPRIMEProcessing] Script Date: 2/7/2018 2:01:46 PM ******/ +CREATE PROCEDURE [onprc_ehr.etlStep1eIACUCtoPRIMEProcessing] + +AS + + +Begin + +Update [onprc_ehr].[PRIME_VIEW_PROTOCOL_Processing] +set modifiedby = 000,modified = GetDate() + where modified is Null + + + +INSERT INTO [onprc_ehr].[PRIME_VIEW_PROTOCOL_Processing] +( + [Protocol_ID] +,[Template_OID] +,[Protocol_OID] +,[Protocol_Title] +,[PI_ID] +,[PI_First_Name] +,[PI_Last_Name] +,[PI_Email] +,[PI_Phone] +,[USDA_Level] +,[ProcessDate] +,[Approval_Date] +,[Annual_Update_Due] +,[Three_year_Expiration] +,[Last_Modified] +,created +,createdby +,recordStatus +,PPQ_Numbers +,PROTOCOL_State + + +) +Select + Distinct + e.Protocol_ID, + e.Template_OID, + CONVERT(BINARY(16),e.Protocol_OID,2) as Protocol_OID, + e.Protocol_Title, + e.PI_ID, + e.PI_First_Name, + e.PI_Last_Name, + e.PI_Email, + e.PI_Phone, + e.USDA_Level, + GetDate () as ProcessDate, + e.Approval_Date, + e.Annual_Update_Due, + e.Three_year_Expiration, + e.Last_Modified, + GetDate(), + 1011, + + Case + When e.protocol_ID in + (Select e1.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e1 left outer join onprc_ehr.protocol p on p.external_id = e1.protocol_id where p.external_ID is Null) then 'new Record' + --in the update state we look at each possible area for change + When e.protocol_ID in + (Select e1.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e1 + left outer join onprc_ehr.protocol p on p.external_id = e1.protocol_id + where e1.Template_OID <> p.template_oid) then 'Update TemplateOID' + When e.protocol_ID in + (Select e2.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e2 + left outer join onprc_ehr.protocol p on p.external_id = e2.protocol_id + where e2.PPQ_numbers <> p.PPQ_Numbers) then 'Update PPQ Change' + When e.protocol_ID in + (Select e3.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e3 + left outer join onprc_ehr.protocol p on p.external_id = e3.protocol_id + where e3.Protocol_State <> p.PROTOCOL_State) then 'Update Protocol State' + When e.protocol_ID in + (Select e4.protocol_ID from onprc_ehr.PRIME_VIEW_PROTOCOLS e4 + left outer join onprc_ehr.protocol p on p.external_id = e4.protocol_id + where e4.Protocol_Title <> p.title) then 'Update Protocol Title' + else 'No Change' + End as RecordStatus + ,e.PPQ_Numbers + ,e.PROTOCOL_State + +from [onprc_ehr].[PRIME_VIEW_PROTOCOLS] e + + + + + If @@Error <> 0 + GoTo Err_Proc + + + + + + Return 0 + + Err_Proc: Return 1 + + + + +END + GO +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the Stored Procedure etl1s_eIACUCtoPublicAction + * + */ + +/****** Object: StoredProcedure [onprc_ehr].[etl.Step1A_eIACUCtoPublicAction] Script Date: 2/7/2018 2:04:29 PM ******/ +Create PROCEDURE [onprc_ehr].[etl1_eIACUCtoPublicAction] + +AS +Begin + + +INSERT INTO [Labkey_Public].[dbo].[protocolEiacucActions] +([objectid] +,[DateEntered] +,[actionType] +,[Protocol_ID] +,[Date_Modified] +,[Protocol_OID] +,[Template_OID] +,[Protocol_Title] +,[InvestigatorID] +,[PI_ID] +,[PI_First_Name] +,[PI_Last_Name] +,[PI_Email] +,[PI_Phone] +,[USDA_Level] +,[Approval_Date] +,[Annual_Update_Due] +,[Three_year_Expiration] +,[Last_Modified] +,[createdby] +,[created] +,[modifiedby] +,[modified] +,[status] +,[container] +,[PPQ_Numbers] +,[PROTOCOL_State] +,[description] +) + + + +Select + NewID(), + null , + Case When p.recordStatus like 'update%' then 'update' + + when p.recordStatus = 'New Record' then 'Insert New' + + End as ActionType + ,p.Protocol_ID + ,p.modified as Date_Modified + ,p.Protocol_OID + ,p.Template_OID + ,p.Protocol_Title + ,(Select i.rowID from onprc_ehr.investigators i where i.employeeID = p.pi_id and i.dateDisabled is null) as InvestigatorID + ,p.PI_ID + ,p.PI_First_Name + ,p.PI_Last_Name + ,p.PI_Email + ,p.PI_Phone + ,p.USDA_Level + ,p.Approval_Date + ,p.Annual_Update_Due + ,p.Three_year_Expiration + ,p.Last_Modified + ,p.createdby + ,p.created + , + Case + when p.modifiedby is null then 0000 else p.modifiedby end as modifiedBy, + Case + when p.modified is null then getDate() else p.modified end as modified, + + p.recordstatus + ,'CD17027B-C55F-102F-9907-5107380A54BE' + ,p.PPQ_Numbers + ,p.PROTOCOL_State + ,Case when p.recordStatus like 'update%' then ('Update from eIACUC ' + p.recordstatus) + End as description + + +FROM onprc_ehr.PRIME_VIEW_Protocol_processing p + +where + p.recordstatus not in ('processed','No Change') + +Update onprc_ehr.PRIME_VIEW_Protocol_processing +Set modified = GetDate(),recordStatus = 'processed', ProcessDate = GetDate() +where modified is null + + If @@Error <> 0 + GoTo Err_Proc + + + + + + Return 0 + + Err_Proc: Return 1 + + + + +END + GO +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the Stored Procedure etl3_insertToEhr_Protocol + * + */ + +/****** Object: StoredProcedure [onprc_ehr].[etl3_insertToEhr_Protocol] Script Date: 2/7/2018 2:30:52 PM ******/ +CREATE PROCEDURE [onprc_ehr].[etl3_insertToEhr_Protocol] + +AS + +Begin + +INSERT INTO [LABKEY].[onprc_ehr].[protocol] +([protocol] ,[approve],[createdby],[created],[modifiedby],[modified],[title] + ,[usda_level],[external_id],[investigatorId],[last_modification],[objectid],container,PROTOCOL_State,PPQ_Numbers +) +Select + Protocol_ID,Approval_Date,createdby,created,modifiedby,modified,Protocol_Title + ,USDA_Level,Protocol_ID,InvestigatorID,Last_Modified,NewID(),'CD17027B-C55F-102F-9907-5107380A54BE',Protocol_State,PPQ_Numbers +FROM [Labkey_Public].dbo.protocolEIACUCActions +Where actionType in ('update','Insert New') + And dateentered is null + + If @@Error <> 0 + GoTo Err_Proc + +Update [Labkey_Public].[dbo].[protocolEiacucActions] +set dateentered = getdate(), status = 'processed' + Where status not like ('processed') + And dateentered is null + + Return 0 + + Err_Proc: Return 1 + + +END + GO +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the Stored Procedure etl2_update_ehrProtocol + * + */ + +/****** Object: StoredProcedure [onprc_ehr].[etl2_update_ehrProtocol] Script Date: 2/7/2018 2:29:18 PM ******/ +CREATE PROCEDURE [onprc_ehr].[etl2_update_ehrProtocol] + +AS + +Begin + +--reviews the current table and insures that there is only 1 record per protocol + + + + +Update prot +Set prot.enddate = getDate(), + prot.description = p.description +From onprc_ehr.protocol prot join [labkey_public].dbo.protocolEiacucActions p on prot.external_id = p.protocol_ID +where prot.enddate is null and p.dateEntered is Null + and prot.objectID in + (Select e.objectID from onprc_ehr.protocol e, [labkey_public].dbo.protocolEiacucActions p where e.external_ID = p.Protocol_ID and e.enddate is null and p.status like 'Update%') + + + If exists (Select * from [Labkey_Public].dbo.protocolEIACUCActions + where status = 'new import' + And dateentered is null) + + + If @@Error <> 0 + GoTo Err_Proc + + + + Return 0 + + Err_Proc: Return 1 + + + + +END + GO + +CREATE TABLE [onprc_ehr].[AvailableBloodVolume]( + [datecreated] [datetime] NULL, + [id] [nvarchar](32) NULL, + [gender] [nvarchar](4000) NULL, + [species] [nvarchar](4000) NULL, + [yoa] [float] NULL, + [mostrecentweightdate] [datetime] NULL, + [weight] [float] NULL, + [calcmethod] [nvarchar](32) NULL, + [BCS] [float] NULL, + [BCSage] [int] NULL, + [previousdraws] [float] NULL, + [ABV] [float] NULL, + [dsrowid] [bigint] NOT NULL + ) ON [PRIMARY] + GO + +CREATE TABLE onprc_ehr.Reference_StaffNames( + RowId INT IDENTITY(1,1)NOT NULL, + username varchar(100), + LastName varchar(100) NULL, + FirstName varchar(100) NULL, + displayname varchar(100) NULL, + Type varchar(100) NULL, + role varchar(100) NULL, + remark varchar(200) NULL, + SortOrder smallint NULL, + StartDate smalldatetime NULL, + DisableDate smalldatetime NULL + + CONSTRAINT pk_reference PRIMARY KEY (username) + +); + +CREATE TABLE onprc_ehr.Frequency_DayofWeek( + RowId INT IDENTITY(1,1)NOT NULL, + FreqKey SMALLINT NULL, + value SMALLINT NULL, + Meaning varchar(400) NULL, + calenderType varchar(100) NULL, + Sort_order SMALLINT NULL, + DisableDate smalldatetime NULL + + CONSTRAINT pk_FreqWeek PRIMARY KEY (RowId) + +); + +CREATE TABLE onprc_ehr.usersActiveNames( + Email nvarchar(64) NULL, + _ts timestamp NOT NULL, + EntityId ENTITYID NULL, + CreatedBy USERID NULL, + Created datetime NULL, + ModifiedBy USERID NULL, + Modified datetime NULL, + Owner USERID NULL, + UserId USERID NOT NULL, + DisplayName nvarchar(64) NOT NULL, + FirstName nvarchar(64) NULL, + LastName nvarchar(64) NULL, + Phone nvarchar(64) NULL, + Mobile nvarchar(64) NULL, + Pager nvarchar(64) NULL, + IM nvarchar(64) NULL, + Description nvarchar(255) NULL, + LastLogin datetime NULL, + Active bit NOT NULL + ) + GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.101-20.102.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.101-20.102.sql new file mode 100644 index 000000000..efb94f791 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.101-20.102.sql @@ -0,0 +1,50 @@ + /* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.animalGroups Dataset which is populated by the ETL Process + * + */ +CREATE TABLE [onprc_ehr].[eIACUC_PRIME_VIEW_ANIMAL_GROUPS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Parent_Protocol] [varchar](255) NOT NULL, + [Group_ID] [varchar](255) NULL, + [Group_Name] [varchar](255) NULL, + [Species] [varchar](255) NULL, + [SPF_Status] [varchar](255) NULL, + [Weight_Start] [varchar](255) NULL, + [Weight_End] [varchar](255) NULL, + [Age_Start] [varchar](255) NULL, + [Age_End] [varchar](255) NULL, + [Gender] [varchar](255) NULL, + [Number_of_Animals_Max] [int] NULL, + [Breeding_Colony] [int] NULL, + [Non_Standard_Housing_Types] [nvarchar](max) NULL, + [Non_Standard_Housing_Description] [nvarchar](max) NULL, + [Non_Standard_Housing_Frequency_and_Duration][nvarchar](max) NULL, + [Non_Standard_Housing_Monitoring] [nvarchar](max) NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL, + [Restraint] [nvarchar](max) NULL, + [Nutritional_Manipulation_Description] [nvarchar](max) NULL, + [Nutritional_Manipulation_Adverse_Consequences] [nvarchar](max) NULL, + [Nutritional_Manipulation_Health_Assessment] [nvarchar](max) NULL, + [Non_Pharmaceutical_Grade_Drug_Use] [nvarchar](max) NULL, + [Food_Withheld] [int] NULL, + [Water_Withheld] [int] NULL, + [Food_Water_Withheld_Description] [nvarchar](max) NULL, + [Food_Water_Withheld_Justification] [nvarchar](max) NULL, + [Food_Water_Withheld_Adverse_Consequences] [nvarchar](max) NULL, + [Death_As_Endpoint_Number_of_Animals] [nvarchar](max) NULL, + [Death_As_Endpoint_Justification] [nvarchar](max) NULL +) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.102-20.103.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.102-20.103.sql new file mode 100644 index 000000000..719f1c4fe --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.102-20.103.sql @@ -0,0 +1,26 @@ +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.IBC_Numberss Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[eIACUC_PRIME_VIEW_IBC_NUMBERS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Animal_Group] [varchar](255) NOT NULL, + [IBC_Registration_Number] [varchar](255) NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL +) ON [PRIMARY] +GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.103-20.104.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.103-20.104.sql new file mode 100644 index 000000000..eb1c5a1fd --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.103-20.104.sql @@ -0,0 +1,32 @@ + /* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.PRIME_VIEW_NON_SURGICAL_PROCS Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[eIACUC_PRIME_VIEW_NON_SURGICAL_PROCS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Animal_Group] [varchar](255) NOT NULL, + [NS_Procedure_Name] [varchar](255) NULL, + [Standard_Procedure] [int] NULL, + [Iterations] [int] NULL, + [Deviation] [int] NULL, + [Deviation_Description] [varchar](255) NULL, + [Recovery_Days] [int] NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL +) ON [PRIMARY] +GO + diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.104-20.105.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.104-20.105.sql new file mode 100644 index 000000000..818e499a4 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.104-20.105.sql @@ -0,0 +1,41 @@ +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.PRIME_VIEW_PROTOCOLS Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[eIACUC_PRIME_VIEW_PROTOCOLS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Protocol_ID] [varchar](255) NOT NULL, + [Template_OID] [varchar](32) NULL, + [Protocol_OID] [varchar](255) NULL, + [Protocol_Title] [varchar](255) NULL, + [PI_ID] [varchar](255) NULL, + [PI_First_Name] [varchar](255) NULL, + [PI_Last_Name] [varchar](255) NULL, + [PI_Email] [varchar](255) NULL, + [PI_Phone] [varchar](255) NULL, + [USDA_Level] [varchar](255) NULL, + [Approval_Date] [datetime] NULL, + [Annual_Update_Due] [datetime] NULL, + [Three_year_Expiration] [datetime] NULL, + [Last_Modified] [datetime] NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL, + [PROTOCOL_State] [varchar](250) NULL, + [PPQ_Numbers] [varchar](255) NULL, + [Description] [varchar](255) NULL +) ON [PRIMARY] +GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.105-20.106.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.105-20.106.sql new file mode 100644 index 000000000..851fcbebc --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.105-20.106.sql @@ -0,0 +1,28 @@ + /* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2/17/2018 Jones ga + * This script creates the ONPRC_EHR.PRIME_VIEW_SURGICAL_PROCS Dataset which is populated by the ETL Process + * + */ + +CREATE TABLE [onprc_ehr].[eIACUC_PRIME_VIEW_SURGICAL_PROCS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [OID] [int] NOT NULL, + [Animal_Group] [varchar](255) NOT NULL, + [Standard_Procedure] [int] NULL, + [Iterations] [int] NULL, + [Deviation] [int] NULL, + [Deviation_Description] [varchar](255) NULL, + [Recovery_Days] [int] NULL, + [Surgery_Name] [varchar](255) NULL +) ON [PRIMARY] +GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.106-20.107.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.106-20.107.sql new file mode 100644 index 000000000..b705a9d4d --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.106-20.107.sql @@ -0,0 +1,62 @@ + /* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * 2020/1/24 Update of Fields to accomodate incoming text straing. + * Manual updated the Database schema to verify that it resolved the issue + * This script creates the ONPRC_EHR.animalGroups Dataset which is populated by the ETL Process + * + */ + + +/****** Object: Table [onprc_ehr].[eIACUC_PRIME_VIEW_ANIMAL_GROUPS] Script Date: 1/24/2020 12:23:44 PM ******/ +DROP TABLE [onprc_ehr].[eIACUC_PRIME_VIEW_ANIMAL_GROUPS] +GO + +/****** Object: Table [onprc_ehr].[eIACUC_PRIME_VIEW_ANIMAL_GROUPS] Script Date: 1/24/2020 12:23:44 PM ******/ + +CREATE TABLE [onprc_ehr].[eIACUC_PRIME_VIEW_ANIMAL_GROUPS]( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [Parent_Protocol] [varchar](255) NOT NULL, + [Group_ID] [varchar](255) NULL, + [Group_Name] [varchar](255) NULL, + [Species] [varchar](255) NULL, + [SPF_Status] [varchar](255) NULL, + [Weight_Start] [varchar](255) NULL, + [Weight_End] [varchar](255) NULL, + [Age_Start] [varchar](255) NULL, + [Age_End] [varchar](255) NULL, + [Gender] [varchar](255) NULL, + [Number_of_Animals_Max] [int] NULL, + [Breeding_Colony] [int] NULL, + [Non_Standard_Housing_Types] [nvarchar](max) NULL, + [Non_Standard_Housing_Description] [ntext] NULL, + [Non_Standard_Housing_Frequency_and_Duration] [nvarchar](max) NULL, + [Non_Standard_Housing_Monitoring] [nvarchar](max) NULL, + [createdby] [int] NULL, + [created] [datetime] NULL, + [modifiedby] [int] NULL, + [modified] [datetime] NULL, + [Restraint] [nvarchar](max) NULL, + [Nutritional_Manipulation_Description] [nvarchar](max) NULL, + [Nutritional_Manipulation_Adverse_Consequences] [nvarchar](max) NULL, + [Nutritional_Manipulation_Health_Assessment] [nvarchar](max) NULL, + [Non_Pharmaceutical_Grade_Drug_Use] [ntext] NULL, + [Food_Withheld] [int] NULL, + [Water_Withheld] [int] NULL, + [Food_Water_Withheld_Description] [nvarchar](max) NULL, + [Food_Water_Withheld_Justification] [nvarchar](max) NULL, + [Food_Water_Withheld_Adverse_Consequences] [nvarchar](max) NULL, + [Death_As_Endpoint_Number_of_Animals] [nvarchar](max) NULL, + [Death_As_Endpoint_Justification] [nvarchar](max) NULL +) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] +GO + + diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.411-20.412.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.411-20.412.sql new file mode 100644 index 000000000..6930c55ca --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.411-20.412.sql @@ -0,0 +1,87 @@ +/****** Object: Table [onprc_ehr].[PotentialSire_source] Script Date: 4/121/20202 7:00:04 AM ******/ +/****** Object: Table [onprc_ehr].[PotentialDam_source] Script Date: 4/121/20202 7:00:04 AM ******/ +/****** Object: Table [onprc_ehr].[PotentialParents_source] Script Date: 4/121/20202 7:00:04 AM ******/ + +DROP TABLE IF EXISTS [onprc_ehr].[potentialDam_Source] +GO + +DROP TABLE IF EXISTS [onprc_ehr].[potentialsire_Source] +GO + +DROP TABLE IF EXISTS [onprc_ehr].[potentialParents_Source] +GO + + + +/****** Object: Table [onprc_ehr].[PotentialSire_source] Script Date: 4/121/20202 7:00:04 AM ******/ +CREATE TABLE [onprc_ehr].[PotentialSire_source]( + [RowId] INT IDENTITY(1,1)NOT NULL, + [participantId] [nvarchar](32) NULL, + [Date] [datetime] NULL, + [Species] [nvarchar](100) NULL, + [room][nvarchar](100) NULL, + [cage][nvarchar](100) NULL, + [SireAgeAtTime] [datetime] NULL, + [PotentialSire] [nvarchar](100) NULL, + [SireBirth] [datetime] NULL, + [Siregender] [nvarchar](100) NULL, + [Sirespecies] [nvarchar](100) NULL, + [SireDeath] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL, + [container] ENTITYID + + CONSTRAINT pk_potentialSire PRIMARY KEY (rowID) +) + + +/****** Object: Table [onprc_ehr].[PotentialSire_source] Script Date: 4/121/20202 7:00:04 AM ******/ +CREATE TABLE [onprc_ehr].[PotentialDam_source]( + [RowId] INT IDENTITY(1,1)NOT NULL, + [participantId] [nvarchar](32) NULL, + [Date] [datetime] NULL, + [Species] [nvarchar](100) NULL, + [room][nvarchar](100) NULL, + [cage][nvarchar](100) NULL, + [DamAgeAtTime] [datetime] NULL, + [PotentialDam] [nvarchar](100) NULL, + [DamBirth] [datetime] NULL, + [Damgender] [nvarchar](100) NULL, + [DamSpecies] [nvarchar](100) NULL, + [DamDeath] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL, + [container] ENTITYID + + CONSTRAINT pk_potentialDam PRIMARY KEY (rowID) +) + + + +/****** Object: Table [onprc_ehr].[PotentialParents_source] Script Date: 4/121/20202 7:00:04 AM ******/ +CREATE TABLE [onprc_ehr].[PotentialParents_source]( + [RowId] INT IDENTITY(1,1)NOT NULL, + [participantId] [nvarchar](32) NULL, + [BirthDate] [datetime] NULL, + [Species] [nvarchar](100) NULL, + [BirthRoom][nvarchar](100) NULL, + [Birthcage][nvarchar](100) NULL, + [ParentAgeAtTime] [datetime] NULL, + [PotentialParent] [nvarchar](100) NULL, + [[PotentialParentType] [nvarchar](100) NULL, + [ParentBirth] [datetime] NULL, + [Parentgender] [nvarchar](100) NULL, + [ParentSpecies] [nvarchar](100) NULL, + [ParentDeath] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL, + [container] ENTITYID + + CONSTRAINT pk_potentialParent PRIMARY KEY (rowID) +) \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.412-20.413.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.412-20.413.sql new file mode 100644 index 000000000..e6ff4895b --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.412-20.413.sql @@ -0,0 +1,71 @@ + +/****** Object: StoredProcedure [onprc_ehr].[PotentialDam_Insert] Script Date: 4/22/2020 10:16:00 AM ******/ +-- ============================================= +-- Author: jonesga@ohsu.edu +-- Create date: 2020-04-22 +-- Description: SP runs a query to populate the Potential Sire Dataset +-- ============================================= + CREATE PROCEDURE [onprc_ehr].[PotentialDam_Insert] + + AS + BEGIN + --Potential Sire Query +--This will be used in generation of potential parents + Truncate table [onprc_ehr].[PotentialDam_source] + INSERT INTO [onprc_ehr].[PotentialDam_source] + ([participantId] + ,[Date] + ,[Species] + ,[room] + ,[cage] + ,[DamAgeAtTime] + ,[PotentialDam] + ,[DamBirth] + ,[Damgender] + ,[DamSpecies] + ,[DamDeath] + ,[created] + ,[createdBy] + ,[modified] + ,[modifiedBy] + ,[container] + ) + select + b.participantid, + b.date, + b.species, + b.room, + b.cage, + DateDiff(day, d.birth, b.date) / 365 as SireAgeAtTime, +-- (timestampdiff('SQL_TSI_DAY', h.Id.demographics.birth, b.date) / 365) as damAgeAtTime +-- we want a list of potential dams that were of age at the time of the infants birth +-- So look at the housing table match the Room and Cage on that date + h.participantID, + d.birth as SireBirth, + d.gender, + d.species, + d.death as SireDeath, + GETDATE(), + 1011, + GetDate(), + 1011, + 'CD17027B-C55F-102F-9907-5107380A54BE' + from [studyDataset].[c6d202_birth] b + join [studyDataset].[c6d194_housing] h on + (b.participantId != h.participantId AND + (h.date <= b.date AND h.enddate >= b.date) AND + h.room = b.room AND (h.cage = b.cage OR (h.cage is null and b.cage is null)) + --note: this is to always include observed parents + OR h.participantid = b.dam + ) + join [studyDataset].[c6d203_demographics] d on d.participantid = h.participantid + join [studyDataset].[c6d203_demographics] d1 on d1.participantID = b.participantid + WHERE d.gender = 'm' and DateDiff(day, d.birth, b.date) > 912.5 --(2.5 years) + AND d.species = d1.species + + + + + + + END diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.413-20.414.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.413-20.414.sql new file mode 100644 index 000000000..f65cc938c --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.413-20.414.sql @@ -0,0 +1,70 @@ + +/****** Object: StoredProcedure [onprc_ehr].[PotentialSire_Insert] Script Date: 4/22/2020 10:16:39 AM ******/ +-- ============================================= +-- Author: jonesga@ohsu.edu +-- Create date: 2020-04-22 +-- Description: SP runs a query to populate the Potential Sire Dataset +-- ============================================= + + +CREATE PROCEDURE [onprc_ehr].[PotentialSire_Insert] + + AS + BEGIN + --Potential Sire Query +--This will be used in generation of potential parents + Truncate table [onprc_ehr].[PotentialSire_source] + INSERT INTO [onprc_ehr].[PotentialSire_source] + ([participantId] + ,[Date] + ,[Species] + ,[room] + ,[cage] + ,[SireAgeAtTime] + ,[PotentialSire] + ,[sireBirth] + ,[siregender] + ,[sireSpecies] + ,[SireDeath] + ,[created] + ,[createdBy] + ,[modified] + ,[modifiedBy] + ,[container] + ) + select + b.participantid, + b.date, + b.species, + b.room, + b.cage, + DateDiff(day, d.birth, b.date) / 365 as SireAgeAtTime, + h.participantID, + d.birth as SireBirth, + d.gender, + d.species, + d.death as SireDeath, + GETDATE(), + 1011, + GetDate(), + 1011, + 'CD17027B-C55F-102F-9907-5107380A54BE' + from [studyDataset].[c6d202_birth] b + join [studyDataset].[c6d194_housing] h on + (b.participantId != h.participantId AND + (h.date <= b.date AND h.enddate >= b.date) AND + h.room = b.room AND (h.cage = b.cage OR (h.cage is null and b.cage is null)) + --note: this is to always include observed parents + OR h.participantid = b.dam + ) + join [studyDataset].[c6d203_demographics] d on d.participantid = h.participantid + join [studyDataset].[c6d203_demographics] d1 on d1.participantID = b.participantid + WHERE d.gender = 'm' and DateDiff(day, d.birth, b.date) > 912.5 --(2.5 years) + AND d.species = d1.species + + + + + + + END diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.414-20.415.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.414-20.415.sql new file mode 100644 index 000000000..d1581d44b --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.414-20.415.sql @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +-- Dev machines on release20.7-SNAPSHOT would be on module v. 18.10, and will already have below run as part of onprc_ehr-17.20-17.21.sql, and won't be needing this script to run +-- Onprc devs/server will be getting upgraded from svn onprc19.1Prod, which is already on module v. 20.417, so won't be needing this script to run +-- Below is now part of rolled up script onprc_ehr-0.00-18.10.sql for bootstrapped database +-- Commenting it out instead of deleting this file in order to preserve script numbering continuity + +--Add container column +-- ALTER TABLE onprc_ehr.observation_types ADD container entityid; +-- GO +-- +-- --Add container ids to onprc_ehr.observation_types: +-- UPDATE onprc_ehr.observation_types +-- SET container = (SELECT c.entityid FROM core.containers c +-- LEFT JOIN core.Containers c2 ON c.Parent = c2.EntityId +-- WHERE c.name = 'EHR' and c2.name = 'ONPRC') +-- WHERE container IS NULL; +-- GO +-- +-- --copy data into ehr table +-- INSERT INTO ehr.observation_types +-- (value, +-- category, +-- editorconfig, +-- schemaName, +-- queryName, +-- valueColumn, +-- createdby, +-- created, +-- modifiedby, +-- modified, +-- container +-- ) +-- SELECT +-- value, +-- category, +-- editorconfig, +-- schemaName, +-- queryName, +-- valueColumn, +-- createdby, +-- created, +-- modifiedby, +-- modified, +-- container +-- FROM onprc_ehr.observation_types obs +-- WHERE obs.container IS NOT NULL; +-- GO +-- +-- --drop table +-- DROP TABLE onprc_ehr.observation_types +-- GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.415-20.416.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.415-20.416.sql new file mode 100644 index 000000000..5d69614f5 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.415-20.416.sql @@ -0,0 +1,74 @@ + +/****** Object: StoredProcedure [onprc_ehr].[PotentialDam_Insert] Script Date: 4/22/2020 10:16:00 AM ******/ +-- ============================================= +-- Author: jonesga@ohsu.edu +-- Create date: 2020-04-22 +-- Modified 2020-08024 +-- reset the gender to f was incorrectly set to M returning Male +-- Description: SP runs a query to populate the Potential Sire Dataset +-- Peer Review +-- ============================================= + ALTER PROCEDURE [onprc_ehr].[PotentialDam_Insert] + + AS + BEGIN + --Potential Sire Query +--This will be used in generation of potential parents + Truncate table [onprc_ehr].[PotentialDam_source] + INSERT INTO [onprc_ehr].[PotentialDam_source] + ([participantId] + ,[Date] + ,[Species] + ,[room] + ,[cage] + ,[DamAgeAtTime] + ,[PotentialDam] + ,[DamBirth] + ,[Damgender] + ,[DamSpecies] + ,[DamDeath] + ,[created] + ,[createdBy] + ,[modified] + ,[modifiedBy] + ,[container] + ) + select + b.participantid, + b.date, + b.species, + b.room, + b.cage, + DateDiff(day, d.birth, b.date) / 365 as SireAgeAtTime, +-- (timestampdiff('SQL_TSI_DAY', h.Id.demographics.birth, b.date) / 365) as damAgeAtTime +-- we want a list of potential dams that were of age at the time of the infants birth +-- So look at the housing table match the Room and Cage on that date + h.participantID, + d.birth as SireBirth, + d.gender, + d.species, + d.death as SireDeath, + GETDATE(), + 1011, + GetDate(), + 1011, + 'CD17027B-C55F-102F-9907-5107380A54BE' + from [studyDataset].[c6d202_birth] b + join [studyDataset].[c6d194_housing] h on + (b.participantId != h.participantId AND + (h.date <= b.date AND h.enddate >= b.date) AND + h.room = b.room AND (h.cage = b.cage OR (h.cage is null and b.cage is null)) + --note: this is to always include observed parents + OR h.participantid = b.dam + ) + join [studyDataset].[c6d203_demographics] d on d.participantid = h.participantid + join [studyDataset].[c6d203_demographics] d1 on d1.participantID = b.participantid + WHERE d.gender = 'f' and DateDiff(day, d.birth, b.date) > 912.5 --(2.5 years) + AND d.species = d1.species + + + + + + + END diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.416-20.417.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.416-20.417.sql new file mode 100644 index 000000000..ddf6ca201 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.416-20.417.sql @@ -0,0 +1,20 @@ +DROP TABLE IF EXISTS [onprc_ehr].[StudyDetails_Reference_Data] +GO + +/****** Object: Table [onprc_ehr].[StudyDetails_Reference_Data] Script Date: 2/20/2020 ******/ + +CREATE TABLE [onprc_ehr].[StudyDetails_Reference_Data]( + [rowId] INT IDENTITY(1,1)NOT NULL, + [value] [nvarchar](1000) NULL, + [name] [nvarchar](1000) NULL, + [remark] [nvarchar](4000) NULL, + [sort_order] INT NULL, + [dateDisabled] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL + + CONSTRAINT pk_StudyDetails_Reference_Data PRIMARY KEY (rowId) + ) +GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/onprc_ehr.xml b/onprc_ehr/resources/schemas/onprc_ehr.xml index 10e01662b..dd30651f5 100644 --- a/onprc_ehr/resources/schemas/onprc_ehr.xml +++ b/onprc_ehr/resources/schemas/onprc_ehr.xml @@ -59,7 +59,7 @@
Employee Id - true + Financial Analyst @@ -212,7 +212,7 @@ Ship ZIP - +
Nonprc_billing.xml Date Created @@ -299,9 +299,9 @@ Reason For Move - - - + + + @@ -383,8 +383,8 @@ Grid Views - - Charts + + Reports Export @@ -392,6 +392,9 @@ Print + + Paging + @@ -415,6 +418,7 @@
+ Encounter Summaries Remarks @@ -498,7 +502,7 @@ - core + study qcstate RowId @@ -527,4 +531,464 @@
- \ No newline at end of file + + + + StudyDetails_Reference_Data + + DETAILED + + + true + + + + Value + + + + Name + + + + + End Date + + + + Sort Order + + + + true + + + + true + + + + +
+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + +
+ diff --git a/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js b/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js index c9560cca6..bc52fdc08 100644 --- a/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js +++ b/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js @@ -13,6 +13,101 @@ var triggerHelper = new org.labkey.onprc_ehr.query.ONPRC_EHRTriggerHelper(LABKEY exports.init = function(EHR){ EHR.ETL = ETL; + EHR.Server.TriggerManager.registerHandler(EHR.Server.TriggerManager.Events.INIT, function (event, helper, EHR) { + + EHR.Server.TriggerManager.unregisterAllHandlersForQueryNameAndEvent('study', 'birth', EHR.Server.TriggerManager.Events.ON_BECOME_PUBLIC); + + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.ON_BECOME_PUBLIC, 'study', 'birth', function (scriptErrors, helper, row, oldRow) { + // Put custom ONPRC handler here + // skip normal birth records process when birth condition has a value of Fetus + console.log("onprc_ehr/birth.js entry") + if (row.Id && row.birth_condition == 'Fetus - Prenatal') + { + var obj = { + Id: row.Id, + birth: row.date, + date: row.date, + calculated_status: 'Fetus' + }; + + + helper.getJavaHelper().createDemographicsRecord(row.Id, obj); + } + + else + { + var isLiving = EHR.Server.Utils.isLiveBirth(row.birth_condition); + if (isLiving) + { + helper.registerLiveBirth(row.Id, row.date); + } + + if (!helper.isETL()) + { + //if a weight is provided, we insert into the weight table: + if (row.weight && row.wdate) + { + helper.getJavaHelper().insertWeight(row.Id, row.wdate, row.weight); + } + + //if room provided, we insert into housing. if this animal already has an active housing record, skip + + if (row.room && row.Id && row.date) + { + + helper.getJavaHelper().createHousingRecord(row.Id, row.date, (isLiving ? null : row.date), row.room, (row.cage || null),null); + } + + if (!helper.isGeneratedByServer()) + { + var obj = { + Id: row.Id, + gender: row.gender, + dam: row.dam, + sire: row.sire, + origin: row.origin, + birth: row.date, + date: row.date, + calculated_status: isLiving ? 'Alive' : 'Dead' + + }; + + //NOTE: the follow is designed to allow the table to either have physical columns for species/origin, or do display the demographics values. in the latter case, editing the form field will act to update the demographics record + if (row.species || row['Id/demographics/species']) + { + obj.species = row.species || row['Id/demographics/species']; + } + + if (row.geographic_origin || row['Id/demographics/geographic_origin']) + { + obj.geographic_origin = row.geographic_origin || row['Id/demographics/geographic_origin']; + } + + //find dam, if provided + if (row.dam && !obj.geographic_origin) + { + obj.geographic_origin = helper.getJavaHelper().getGeographicOrigin(row.dam); + } + + if (row.dam && !obj.species) + { + obj.species = helper.getJavaHelper().getSpecies(row.dam); + } + + if (!isLiving) + { + obj.death = row.date; + } + + //if not already present, we insert into demographics + helper.getJavaHelper().createDemographicsRecord(row.Id, obj); + } + } + } + }); + }); + + EHR.Server.TriggerManager.registerHandler(EHR.Server.TriggerManager.Events.INIT, function(event, helper, EHR){ EHR.Server.Utils.isLiveBirth = function(birthCondition){ EHR.Assert.assertNotEmpty('triggerHelper is null', triggerHelper); @@ -41,13 +136,50 @@ exports.init = function(EHR){ }); }); + //Added: 8-1-2019 R.Blasa EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.INIT, 'study', 'birth', function(event, helper){ //NOTE: births are sometimes not entered until processing, meaning they could be significantly in the past helper.setScriptOptions({ - allowDatesInDistantPast: true + allowDatesInDistantPast: true, + allowFutureDates: true + }); + }); + + + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'study','birth', function(helper, scriptErrors, row, oldRow){ + //Added: 8-1-2019 R.Blasa + + if (row.Id && row.birth_condition == 'Fetus - Prenatal') { + helper.setScriptOptions({ + allowFutureDates: true + }); + + } + }); + + //Added: kollil, 5/12/2020 + //Allow to enter future start dates + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.INIT, 'study', 'StudyDetails', function(event, helper){ + helper.setScriptOptions({ + allowFutureDates: true + }); + }); + + //Added: 7-19-2019 R.Blasa + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.INIT, 'study', 'Demographics', function(event, helper){ + helper.setScriptOptions({ + allowFutureDates: true }); }); + //Added: 7-22-2019 R.Blasa + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.INIT, 'study', 'housing', function(event, helper){ + helper.setScriptOptions({ + allowFutureDates: true + }); + }); + + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.INIT, 'study', 'clinpathRuns', function(event, helper){ helper.setScriptOptions({ allowDeadIds: false, @@ -62,6 +194,15 @@ exports.init = function(EHR){ }); }); + //Added : 12-19-2017 R.Blasa + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'study','clinpathRuns', function(helper, scriptErrors, row, oldRow){ + helper.setScriptOptions({ + + allowFutureDates: false //Added: R.Blasa + + }); + }); + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.INIT, 'study', 'deaths', function(event, helper){ helper.setScriptOptions({ allowDatesInDistantPast: true @@ -103,8 +244,8 @@ exports.init = function(EHR){ { EHR.Server.Utils.addError(scriptErrors, 'chargetype', 'If choosing Research Staff, you must enter the assisting staff.', 'WARN'); } - - if (row.chargetype != 'Research Staff' && row.assistingstaff) + //Modified: 6-9-2020 R. Blasa to allow to process Infectious Disease Resource as Charge unit + if (row.chargetype != 'Research Staff' && row.assistingstaff && row.assistingstaff != 'DCM: Surgery Services') { EHR.Server.Utils.addError(scriptErrors, 'assistingstaff', 'This field will be ignored unless Research Staff is selected, and should be blank.', 'WARN'); } @@ -181,6 +322,7 @@ exports.init = function(EHR){ } }); + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_INSERT, 'study', 'assignment', function(helper, scriptErrors, row, oldRow){ //check number of allowed animals at assign/approve time. use different behavior than core EHR if (!helper.isETL() && !helper.isQuickValidation() && @@ -214,6 +356,13 @@ exports.init = function(EHR){ } }); + //Created: 1-17-2018 R.Blasa + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'ehr', 'snomed_tags', function(helper, scriptErrors, row, oldRow){ + if (row.Id && !row.code){ + EHR.Server.Utils.addError(scriptErrors, 'code', 'A snomed code is required to continue', 'WARN'); + } + }); + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'study', 'assignment', function(helper, scriptErrors, row, oldRow){ // note: if this is automatically generated from death/departure, allow an incomplete record // alerts will flag these @@ -226,9 +375,10 @@ exports.init = function(EHR){ } //update condition on release + //Modified: 5-13-2019 R.Blasa if (!helper.isETL() && helper.getEvent() == 'update' && oldRow){ if (EHR.Server.Security.getQCStateByLabel(row.QCStateLabel).PublicData && EHR.Server.Security.getQCStateByLabel(oldRow.QCStateLabel).PublicData){ - if (row.releaseCondition && row.enddate){ + if (row.releaseCondition && row.enddate && row.releaseCondition != 206){ var msg = triggerHelper.checkForConditionDowngrade(row.Id, row.enddate, row.releaseCondition); if (msg){ EHR.Server.Utils.addError(scriptErrors, 'releaseCondition', msg, 'INFO'); @@ -268,7 +418,8 @@ exports.init = function(EHR){ }); EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.ON_BECOME_PUBLIC, 'study', 'assignment', function(scriptErrors, helper, row, oldRow){ - if (!helper.isETL() && row.Id && row.assignCondition){ + //Modified: 5-9-2019 R.Blasa Prevent flag enttrie for terminal monkey ids + if (!helper.isETL() && row.Id && row.assignCondition && row.assignCondition != 206){ triggerHelper.updateAnimalCondition(row.Id, row.date, row.assignCondition); } }); @@ -280,12 +431,49 @@ exports.init = function(EHR){ EHR.Server.Utils.addError(scriptErrors, 'groupId', msg, 'INFO'); } } + //Added: 12-29-2017 R.Blasa + if (row.Id && !row.groupId){ + EHR.Server.Utils.addError(scriptErrors, 'groupId', 'A Group Id selection is required.', 'WARN'); + } }); + + //Modified: 10-13-2016 R.Blasa added arrival date parameter EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'birth', function(helper, errors, row, oldRow) { - //NOTE: we want to perform the birth updates if this row is becoming public, or if we're updating to set the dam for the first time - if (!helper.isValidateOnly() && (row._becomingPublicData || (oldRow && !oldRow.dam && EHR.Server.Security.getQCStateByLabel(row.QCStateLabel).PublicData && row.dam))) { - triggerHelper.doBirthTriggers(row.Id, row.date, row.dam || null, row.arrival_date || null, row.birth_condition || null, !!row._becomingPublicData); + //Modified: 3-20-2017 R.Blasa Fetal Prenatal updates + if (row.id && oldRow) + { + if (row.id && oldRow.birth_condition && oldRow.birth_condition == 'Fetus - Prenatal' && row.birth_condition && row.birth_condition != 'Fetus - Prenatal') + { + //Modified: 10-27-2017 + triggerHelper.doBirthTriggers(row.Id, row.date, row.dam || null, row.Arrival_Date || null, row.birth_condition || null,row.species || null, !!row._becomingPublicData); + + //Added: 6-26-2017 R.Blasa + //set active flag condition after changing status from Fetus Prenatal to Alive. (Needs to execute because it is no longer considered isBecomingPublic status) + triggerHelper.doBirthConditionAfterPrenatal(row.Id, row.date, row.dam || null, row.Arrival_Date || null, row.birth_condition || null, !!row._becomingPublicData); + + //Created housing when room location is provided + if (row.id && row.room) + { + helper.getJavaHelper().createHousingRecord(row.Id, row.date, null, row.room, (row.cage || null), (row.initialCond || null)); + } + //Added: 6-26-2017 R.Blasa + //if a weight is provided, we insert into the weight table: + if (row.weight && row.wdate) + { + helper.getJavaHelper().insertWeight(row.Id, row.wdate, row.weight); + } + + } + } + //Added: 6-27-2017 R,Blasa Process only + if (row.birth_condition != 'Fetus - Prenatal') + { + //NOTE: we want to perform the birth updates if this row is becoming public, or if we're updating to set the dam for the first time + if (!helper.isValidateOnly() && (row._becomingPublicData || (oldRow && !oldRow.dam && EHR.Server.Security.getQCStateByLabel(row.QCStateLabel).PublicData && row.dam))) + { + triggerHelper.doBirthTriggers(row.Id, row.date, row.dam || null, row.Arrival_Date || null, row.birth_condition || null, row.species || null, !!row._becomingPublicData); + } } }); @@ -358,9 +546,29 @@ exports.init = function(EHR){ } }); } + + //Added: 1-17-2018 R.Blasa disallow male id + if (row.dam ) + { + EHR.Server.Utils.findDemographics({ + participant: row.dam , + helper: helper, + scope: this, + callback: function (data) + { + if (data) + { + if (data['gender/origGender'] && data['gender/origGender'] != 'f') + EHR.Server.Utils.addError(scriptErrors, 'dam', 'The dam has to be female', 'ERROR'); + } + } + }); + + } }); - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.ON_BECOME_PUBLIC, 'study', 'deaths', function(scriptErrors, helper, row, oldRow){ + //Modified: 6-8-2018 R.Blasa + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'deaths', function(helper, errors, row, oldRow){ if (row.Id && row.date){ //close assignment records. triggerHelper.closeActiveAssignmentRecords(row.Id, row.date, (row.cause || null)); @@ -396,13 +604,6 @@ exports.init = function(EHR){ } }); - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_INSERT, 'study', 'blood', function(helper, scriptErrors, row){ - if (!helper.isETL() && row.project && row.chargetype){ - if (row.chargetype == 'No Charge' && !helper.getJavaHelper().isDefaultProject(row.project)) - EHR.Server.Utils.addError(scriptErrors, 'chargetype', 'You have chosen \'No Charge\' with a project that does not support this. You may need to choose \'Research\' instead (which is not billed)', 'INFO'); - } - }); - EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'study', 'housing', function(helper, scriptErrors, row, oldRow){ if (row.cage){ row.cage = row.cage.toUpperCase(); @@ -436,6 +637,10 @@ exports.init = function(EHR){ else if (data.calculated_status != 'Alive' && !data.hasBirthRecord){ EHR.Server.Utils.addError(scriptErrors, 'enddate', 'This animal is not listed as alive, cannot enter an open ended housing record', 'WARN'); } + //Added: 6-14-2017 R.Blasa + else if (data.calculated_status == 'Dead' || data.calculated_status == 'Shipped'){ + EHR.Server.Utils.addError(scriptErrors, 'Id', 'This animal is deceased or shipped out, you are not allowed to make this changes to the housing record', 'WARN'); + } } } }); @@ -474,18 +679,25 @@ exports.init = function(EHR){ }); EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'study', 'arrival', function(helper, scriptErrors, row, oldRow){ - onprc_utils.doHousingCheck(EHR, helper, scriptErrors, triggerHelper, row, oldRow, 'initialRoom', 'initialCage', false); + //Don't process normally if Pending -- Modified: 4-25-2017 R.Blasa + var acquiValue = triggerHelper.retrieveAcquisitionType(row.acquisitionType); + if (row.id && acquiValue != 'Pending Arrival') + { + onprc_utils.doHousingCheck(EHR, helper, scriptErrors, triggerHelper, row, oldRow, 'initialRoom', 'initialCage', false); + } }); -// EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'Parentage', function(helper, errors, row, oldRow){ -// if (row.Id && row.parent && row.relationship && row.method && EHR.Server.Security.getQCStateByLabel(row.QCStateLabel).PublicData) { -// onprc_utils.updateParentage(row.Id, row.parent, row.relationship, row.method); -// } -// }); EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.ON_BECOME_PUBLIC, 'study', 'arrival', function(scriptErrors, helper, row, oldRow) { - if (row.Id && row.date) { - triggerHelper.ensureQuarantineFlag(row.Id, row.date); + //Don't process normally if Pending -- Modified: 4-5-2017 R.Blasa + var acquiValue = triggerHelper.retrieveAcquisitionType(row.acquisitionType); + if (row.id && acquiValue != 'Pending Arrival') + { + if (row.Id && row.date) + { + console.log('Qurantine flag') + triggerHelper.ensureQuarantineFlag(row.Id, row.date); + } } }); @@ -493,6 +705,80 @@ exports.init = function(EHR){ onprc_utils.doHousingCheck(EHR, helper, scriptErrors, triggerHelper, row, oldRow, null, null, false); }); + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_UPSERT, 'study', 'arrival', function(helper, errors, row, oldRow) { + //Don't process normally if Pending -- Created: 4-25-2017 R.Blasa + if (row.id && oldRow) + { + var acquiValueOld = triggerHelper.retrieveAcquisitionType(oldRow.acquisitionType); + var acquiValue = triggerHelper.retrieveAcquisitionType(row.acquisitionType); + if (row.id && acquiValueOld == 'Pending Arrival' && acquiValue != 'Pending Arrival' && EHR.Server.Security.getQCStateByLabel(row.QCStateLabel).PublicData) + { + //Add Housing record if room provided + if (row.initialRoom) + { + helper.getJavaHelper().createHousingRecord(row.Id, row.date, null, row.initialRoom, (row.initialCage || null), (row.initialCond || null)); + } + + //Add Birth record + triggerHelper.onAnimalArrival_AddBirth(row.id, row); + + triggerHelper.ensureQuarantineFlag(row.Id, row.date); + + } + + } + + if(row.id) + { + //Update demographics records + EHR.Server.Utils.findDemographics({ + participant: row.id, + helper: helper, + scope: this, + callback: function (data) + { + data = data || {}; + + var obj = {}; + var hasUpdates = false; + + if (row.gender && row.gender != data.gender ) + { + obj.gender = row.gender; + hasUpdates = true; + } + + if (row.species && row.species != data.species ) + { + obj.species = row.species; + hasUpdates = true; + } + + if (row.geographic_origin && row.geographic_origin != data.geographic_origin ) + { + obj.geographic_origin = row.geographic_origin; + hasUpdates = true; + } + + if (row.birth && row.birth.getTime() != (data.birth ? data.birth.getTime() : 0)) + { + obj.birth = row.birth; + hasUpdates = true; + } + + + if (hasUpdates) + { + obj.Id = row.id; + var demographicsUpdates = [obj]; + helper.getJavaHelper().updateDemographicsRecord(demographicsUpdates); + } + + } + }); + } + }); + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.ON_BECOME_PUBLIC, 'study', 'treatment_order', function(scriptErrors, helper, row, oldRow){ var fieldPairs = [ ['dosage_units', 'dosage'], @@ -561,8 +847,8 @@ exports.init = function(EHR){ if (helper.isETL() || helper.isValidateOnly()){ return; } - - if (row && oldRow && row.category != 'Research'){ + //Modified: 7-12-2017 R.blasa + if (row && oldRow ){ EHR.Assert.assertNotEmpty('triggerHelper is null', triggerHelper); var date = triggerHelper.onTreatmentOrderChange(row, oldRow); @@ -572,6 +858,8 @@ exports.init = function(EHR){ } }); + + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.ON_BECOME_PUBLIC, 'study', 'clinremarks', function(scriptErrors, helper, row, oldRow){ if (helper.isETL() || helper.isValidateOnly()){ return; @@ -583,4 +871,126 @@ exports.init = function(EHR){ triggerHelper.replaceSoap(row.parentid); } }); + + + EHR.Server.TriggerManager.registerHandler(EHR.Server.TriggerManager.Events.INIT, function (event, helper) { + + /* Override the default EHR validation for Blood draw validation. By LKolli, 2/01/2019 */ + + //unregister the default EHR validation code + EHR.Server.TriggerManager.unregisterAllHandlersForQueryNameAndEvent('study', 'blood', EHR.Server.TriggerManager.Events.BEFORE_UPSERT); + //register the new validation code + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'study', 'blood', function (helper, scriptErrors, row, oldRow) { + if (!helper.isETL() && row.date && !row.daterequested){ + if (!oldRow || !oldRow.daterequested){ + row.daterequested = row.date; + } + } + + if (row.quantity === 0){ + EHR.Server.Utils.addError(scriptErrors, 'quantity', 'This field is required', 'WARN'); + } + + if (!helper.isETL()){ + if (row.date && !row.requestdate) + row.requestdate = row.date; + + if (!row.quantity && row.num_tubes && row.tube_vol){ + row.quantity = row.num_tubes * row.tube_vol; + } + + if (row.additionalServices) { + if (row.tube_type || row.tube_vol){ + var tubeType = row.tube_type || null; + var quantity = row.quantity || 0; + var msgs = helper.getJavaHelper().validateBloodAdditionalServices(row.additionalServices, tubeType, quantity); + if (msgs && msgs.length){ + LABKEY.ExtAdapter.each(msgs, function(msg){ + EHR.Server.Utils.addError(scriptErrors, 'additionalServices', msg, 'INFO'); + }, this); + } + } + } + + if (row.quantity && row.tube_vol){ + if (row.quantity != (row.num_tubes * row.tube_vol)){ + EHR.Server.Utils.addError(scriptErrors, 'quantity', 'Quantity does not match tube vol / # tubes', 'INFO'); + EHR.Server.Utils.addError(scriptErrors, 'num_tubes', 'Quantity does not match tube vol / # tubes', 'INFO'); + } + } + + EHR.Server.Validation.checkRestraint(row, scriptErrors); + + if (row.Id && row.date && row.quantity){ + // volume is handled differently for requests vs actual draws + var errorQC; + if (EHR.Server.Security.getQCStateByLabel(row.QCStateLabel)['isRequest'] && !row.taskid) + errorQC = 'ERROR'; + else + errorQC = 'INFO'; + + var map = helper.getProperty('bloodInTransaction'); + var draws = []; + if (map && map[row.Id]){ + draws = map[row.Id]; + } + + var weightMap = helper.getProperty('weightInTransaction'); + var weights = []; + if (weightMap && weightMap[row.Id]){ + weights = weightMap[row.Id]; + } + + if (row.objectid) { + + if ((row.QCStateLabel != 'Request: Cancelled') || (row.QCStateLabel != 'Request: Denied')) + { + //Calling the new ONPRC blood draw validation code, LKolli, 2/1/2019 + var msg = triggerHelper.verifyBloodVolume_New(row.id, row.date, draws, weights, row.objectid || null, row.quantity); + if (msg != null) { + //TODO: change all future bloods draws to review required, if submitted for medical purpose. + EHR.Server.Utils.addError(scriptErrors, 'num_tubes', msg, errorQC); + EHR.Server.Utils.addError(scriptErrors, 'quantity', msg, errorQC); + } + } + } + else { + console.warn('objectid not provided for blood draw, cannot calculate allowable blood volume. this probably indicates an error with the form submitting these data') + } + } + } + }); + + + // Override the default EHR validation for project creation + EHR.Server.TriggerManager.unregisterAllHandlersForQueryNameAndEvent('ehr', 'project', EHR.Server.TriggerManager.Events.BEFORE_UPSERT); + + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.BEFORE_UPSERT, 'ehr', 'project', function (helper, scriptErrors, row, oldRow) { + var constraintHelper = org.labkey.ldk.query.UniqueConstraintHelper.create(LABKEY.Security.currentContainer.id, LABKEY.Security.currentUser.id, 'ehr', 'project_active', 'name'); + + //enforce name unique + if (row.name) { + var isValid = constraintHelper.validateKey(row.name, oldRow ? (oldRow.name || null) : null); + if (!isValid) { + EHR.Server.Utils.addError(scriptErrors, 'name', 'There is already an old project with the name in ehr: ' + row.name, 'ERROR'); + } + } + }); + + //Added 3-5-2019 R.Blasa + EHR.Server.TriggerManager.registerHandlerForQuery(EHR.Server.TriggerManager.Events.AFTER_INSERT, 'ehr', 'project', function(helper, scriptErrors, row, oldRow){ + + var triggerHelper = new org.labkey.onprc_ehr.query.ONPRC_EHRTriggerHelper(LABKEY.Security.currentUser.id, LABKEY.Security.currentContainer.id); + + if (row.project){ + console.log("project data collected " + row.project) + var msg = triggerHelper.sendProjectNotifications(row.project); + if (msg){ + EHR.Server.Utils.addError(scriptErrors, 'project', msg, 'ERROR'); + } + } + }); + }); + + }; \ No newline at end of file diff --git a/onprc_ehr/resources/views/Covid19Scheduler.html b/onprc_ehr/resources/views/Covid19Scheduler.html new file mode 100644 index 000000000..48356a110 --- /dev/null +++ b/onprc_ehr/resources/views/Covid19Scheduler.html @@ -0,0 +1,35 @@ + + + + + ONPRC Covid 19 Test Scheduler + + + + + + --> + + } + + +

Covid 19 Testing Scheduler

+
+ + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/Covid19Scheduler.webpart.xml b/onprc_ehr/resources/views/Covid19Scheduler.webpart.xml new file mode 100644 index 000000000..9ed3fb731 --- /dev/null +++ b/onprc_ehr/resources/views/Covid19Scheduler.webpart.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/Covie19Scheduler.view.xml b/onprc_ehr/resources/views/Covie19Scheduler.view.xml new file mode 100644 index 000000000..c1c27eb87 --- /dev/null +++ b/onprc_ehr/resources/views/Covie19Scheduler.view.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/IndustrialRatesCalc.html b/onprc_ehr/resources/views/IndustrialRatesCalc.html new file mode 100644 index 000000000..e493d6a14 --- /dev/null +++ b/onprc_ehr/resources/views/IndustrialRatesCalc.html @@ -0,0 +1,146 @@ + + + + + NIH Industrial Rates + + + + + +

Industrial Rates

+
+
+ + \ No newline at end of file diff --git a/onprc_ehr/resources/views/IndustrialRatesCalc.view.xml b/onprc_ehr/resources/views/IndustrialRatesCalc.view.xml new file mode 100644 index 000000000..cbaba6594 --- /dev/null +++ b/onprc_ehr/resources/views/IndustrialRatesCalc.view.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/IndustrialRatesCalc.webpart.xml b/onprc_ehr/resources/views/IndustrialRatesCalc.webpart.xml new file mode 100644 index 000000000..0affac058 --- /dev/null +++ b/onprc_ehr/resources/views/IndustrialRatesCalc.webpart.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHPublicFinanceRates.view.xml b/onprc_ehr/resources/views/NIHPublicFinanceRates.view.xml new file mode 100644 index 000000000..e26bbfb22 --- /dev/null +++ b/onprc_ehr/resources/views/NIHPublicFinanceRates.view.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHPublicFinanceRates.webpart.xml b/onprc_ehr/resources/views/NIHPublicFinanceRates.webpart.xml new file mode 100644 index 000000000..cb63ba539 --- /dev/null +++ b/onprc_ehr/resources/views/NIHPublicFinanceRates.webpart.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHRateSheet.html b/onprc_ehr/resources/views/NIHRateSheet.html new file mode 100644 index 000000000..b83614913 --- /dev/null +++ b/onprc_ehr/resources/views/NIHRateSheet.html @@ -0,0 +1,31 @@ + + + + + NIHRateSheet + + + +
+ + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHRateSheet.view.xml b/onprc_ehr/resources/views/NIHRateSheet.view.xml new file mode 100644 index 000000000..6c0266393 --- /dev/null +++ b/onprc_ehr/resources/views/NIHRateSheet.view.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHRateSheet.webpart.xml b/onprc_ehr/resources/views/NIHRateSheet.webpart.xml new file mode 100644 index 000000000..a80f61181 --- /dev/null +++ b/onprc_ehr/resources/views/NIHRateSheet.webpart.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHReducedRates.html b/onprc_ehr/resources/views/NIHReducedRates.html new file mode 100644 index 000000000..4de79a8e8 --- /dev/null +++ b/onprc_ehr/resources/views/NIHReducedRates.html @@ -0,0 +1,65 @@ + + + + + NIHReducedRates + + + + +

Reduced F&A Rate Sheet

+
+
+ + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHReducedRates.view.xml b/onprc_ehr/resources/views/NIHReducedRates.view.xml new file mode 100644 index 000000000..cdc69019e --- /dev/null +++ b/onprc_ehr/resources/views/NIHReducedRates.view.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/NIHReducedRates.webpart.xml b/onprc_ehr/resources/views/NIHReducedRates.webpart.xml new file mode 100644 index 000000000..3f1a7abe1 --- /dev/null +++ b/onprc_ehr/resources/views/NIHReducedRates.webpart.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/PE_ExamHistoryReportbyID.html b/onprc_ehr/resources/views/PE_ExamHistoryReportbyID.html new file mode 100644 index 000000000..59a56791b --- /dev/null +++ b/onprc_ehr/resources/views/PE_ExamHistoryReportbyID.html @@ -0,0 +1,63 @@ + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/PE_ExamHistoryReportbyID.view.xml b/onprc_ehr/resources/views/PE_ExamHistoryReportbyID.view.xml new file mode 100644 index 000000000..3c5ab2210 --- /dev/null +++ b/onprc_ehr/resources/views/PE_ExamHistoryReportbyID.view.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/SliderDefinition.html b/onprc_ehr/resources/views/SliderDefinition.html new file mode 100644 index 000000000..454f6f0ed --- /dev/null +++ b/onprc_ehr/resources/views/SliderDefinition.html @@ -0,0 +1,21 @@ + diff --git a/onprc_ehr/resources/views/SliderDefinition.view.xml b/onprc_ehr/resources/views/SliderDefinition.view.xml new file mode 100644 index 000000000..17a6fb71a --- /dev/null +++ b/onprc_ehr/resources/views/SliderDefinition.view.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/animalHistory.html b/onprc_ehr/resources/views/animalHistory.html index 6f39260b4..7c9d29ab9 100644 --- a/onprc_ehr/resources/views/animalHistory.html +++ b/onprc_ehr/resources/views/animalHistory.html @@ -7,27 +7,21 @@ return; Ext4.create('EHR.panel.AnimalHistoryPanel', { + + html: '**Please click the Update Report button if the program fails to display a report**', //Added: 11-17-2017 R.Blasa + defaultReport: ctx.DefaultAnimalHistoryReport, defaultTab: 'General', showFilterOptionsTitle: true, + clearBetweenClicks: false, filterTypes: [{ xtype: 'ldk-singlesubjectfiltertype', inputValue: LDK.panel.SingleSubjectFilterType.filterName, - label: 'Single Animal', - aliasTable: { - schemaName: 'study', - queryName: 'demographics', - idColumn: 'Id' - } + label:'Single Animal' },{ - xtype: 'ehr-multianimalfiltertype', + xtype: 'onprc_ehr-multianimalfiltertype', inputValue: EHR.panel.MultiAnimalFilterType.filterName, - label: EHR.panel.MultiAnimalFilterType.label, - aliasTable: { - schemaName: 'study', - queryName: 'demographics', - idColumn: 'Id' - } + label: EHR.panel.MultiAnimalFilterType.label },{ xtype: 'ehr-locationfiltertype', inputValue: EHR.panel.LocationFilterType.filterName, diff --git a/onprc_ehr/resources/views/animalHistory.view.xml b/onprc_ehr/resources/views/animalHistory.view.xml index 2b220c511..c938780dc 100644 --- a/onprc_ehr/resources/views/animalHistory.view.xml +++ b/onprc_ehr/resources/views/animalHistory.view.xml @@ -5,7 +5,7 @@ - + diff --git a/onprc_ehr/resources/views/begin.html b/onprc_ehr/resources/views/begin.html index 102700d03..6e9b6c297 100644 --- a/onprc_ehr/resources/views/begin.html +++ b/onprc_ehr/resources/views/begin.html @@ -48,7 +48,7 @@ style: 'font-weight: bold;' }, items: [ - {name: 'Browse All Datasets', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/datasets.view?'}, + {name: 'Browse All Datasets', url: '<%=contextPath%>/onprc_ehr' + ctx['EHRStudyContainer'] + '/datasets.view?'}, {name: 'Housing Queries', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/housingQueries.view?'}, {name: 'Protocol and Project Queries', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/projectQueries.view?'} ] @@ -109,9 +109,11 @@ items: [ {name: 'Compare Lists of Animals', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/utilities.view?'}, {name: 'Bulk History Export', url: '<%=contextPath%>/onprc_ehr' + ctx['EHRStudyContainer'] + '/historyExport.view?'}, - //Modified: 8-30-2016 R.Blasa - {name: 'Exposure Report', url: ctx['SSRSServerURL'] +'%2fAnnual+Reports%2fExposure+Report%2fDemographicsReportMain&rs:Command=Render'}, + //Modified: 9-9-2019 R.Blasa Display Basic instead of Full Expsure report + {name: 'Basic Exposure Report', url: ctx['SSRSServerURL'] +'%2fPrime+Reports%2fExposure+Reports%2fBasicExposureMain&rs:Command=Render'}, {name: 'Drug Formulary', url: '<%=contextPath%>/query' + ctx['EHRStudyContainer'] + '/executeQuery.view?schemaName=ehr_lookups&query.queryName=drug_defaults'}, + //Added by Kolli on 7/30/19 + {name: 'Common Medical Abbreviations', url: '<%=contextPath%>' + '/wiki/home/Support/page.view?name=Common%20Abbreviations'}, {name: 'Procedure List', url: '<%=contextPath%>/query' + ctx['EHRStudyContainer'] + '/executeQuery.view?schemaName=ehr_lookups&query.queryName=procedures&query.viewName=Active Procedures'}, {name: 'Search Center SNOMED Codes', url: '<%=contextPath%>/query' + ctx['EHRStudyContainer'] + '/executeQuery.view?schemaName=ehr_lookups&query.queryName=snomed'} ] @@ -122,7 +124,8 @@ style: 'font-weight: bold;' }, items: [ - {name: 'Enter Data / Task Review', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/enterData.view'}, +// Modified: 4-3-2017 R.Blasa Allow new method of presenting Necropsy entry screens + {name: 'Enter Data / Task Review', url: '<%=contextPath%>/onprc_ehr' + ctx['EHRStudyContainer'] + '/enterData.view'}, {name: 'Post Op Med Verification', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/dataEntryForm.view?formType=medsignoff'} ] @@ -133,9 +136,9 @@ style: 'font-weight: bold;' }, items: [ - {name: 'Manage Requests', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/serviceRequests.view'}, - //{name: 'ASB Services Request', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/dataEntryForm.view?formType=ASB Service Request'}, - //{name: 'Colony Services Request', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/dataEntryForm.view?formType=Colony Service Request'}, + // Modified: 7-18-2017 R.Blasa + {name: 'Manage Requests', url: '<%=contextPath%>/onprc_ehr' + ctx['EHRStudyContainer'] + '/serviceRequests.view'}, + {name: 'Request Labwork', url: '<%=contextPath%>/ehr' + ctx['EHRStudyContainer'] + '/dataEntryForm.view?formType=Labwork Request'} ] }] diff --git a/onprc_ehr/resources/views/citesReport.html b/onprc_ehr/resources/views/citesReport.html index 1bd4ac80b..148fc7829 100644 --- a/onprc_ehr/resources/views/citesReport.html +++ b/onprc_ehr/resources/views/citesReport.html @@ -39,10 +39,10 @@ Ext4.Msg.alert('Error', 'Must enter at least one animal Id'); return; } - + //Modified: 1-17-2019 R.Blasa var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'CITESReport'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/CITESReport'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString({ SessionID: LABKEY.Utils.getSessionID(), diff --git a/onprc_ehr/resources/views/datasets.html b/onprc_ehr/resources/views/datasets.html new file mode 100644 index 000000000..af46fd364 --- /dev/null +++ b/onprc_ehr/resources/views/datasets.html @@ -0,0 +1,96 @@ + diff --git a/onprc_ehr/resources/views/datasets.view.xml b/onprc_ehr/resources/views/datasets.view.xml new file mode 100644 index 000000000..cbe07b93a --- /dev/null +++ b/onprc_ehr/resources/views/datasets.view.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/enterData.html b/onprc_ehr/resources/views/enterData.html new file mode 100644 index 000000000..598366892 --- /dev/null +++ b/onprc_ehr/resources/views/enterData.html @@ -0,0 +1,14 @@ + diff --git a/onprc_ehr/resources/views/enterData.view.xml b/onprc_ehr/resources/views/enterData.view.xml new file mode 100644 index 000000000..7badacbee --- /dev/null +++ b/onprc_ehr/resources/views/enterData.view.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/onprc_ehr/resources/views/frontPage.html b/onprc_ehr/resources/views/frontPage.html new file mode 100644 index 000000000..d35883632 --- /dev/null +++ b/onprc_ehr/resources/views/frontPage.html @@ -0,0 +1,28 @@ + \ No newline at end of file diff --git a/onprc_ehr/resources/views/frontPage.view.xml b/onprc_ehr/resources/views/frontPage.view.xml new file mode 100644 index 000000000..f33aa86c2 --- /dev/null +++ b/onprc_ehr/resources/views/frontPage.view.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/frontPage.webpart.xml b/onprc_ehr/resources/views/frontPage.webpart.xml new file mode 100644 index 000000000..96163b513 --- /dev/null +++ b/onprc_ehr/resources/views/frontPage.webpart.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/onprc_ehr/resources/views/groupProcessing.html b/onprc_ehr/resources/views/groupProcessing.html index b5a680503..1165e0a94 100644 --- a/onprc_ehr/resources/views/groupProcessing.html +++ b/onprc_ehr/resources/views/groupProcessing.html @@ -72,13 +72,14 @@ var params = item.up('#processingBloodDrawsBtn').getUrlParams(); window.open(LABKEY.ActionURL.buildURL('query', 'executeQuery', null, params)) } - },{ - text: 'Download To Excel', - scope: this, - handler: function(item){ - var params = item.up('#processingBloodDrawsBtn').getUrlParams(); - window.open(LABKEY.ActionURL.buildURL('query', 'exportRowsXLSX', null, params)) - } +// Modified: 12-7-2018 R.Blasa Defaults to Open Browser since Export menu limits the size to 100 records +// },{ +// text: 'Download To Excel', +// scope: this, +// handler: function(item){ +// var params = item.up('#processingBloodDrawsBtn').getUrlParams(); +// window.open(LABKEY.ActionURL.buildURL('query', 'exportRowsXLSX', null, params)) +// } }] },{ html: '
Blood Needed For Viral Surveillance:', @@ -236,13 +237,13 @@ handler: function(item){ var params = item.up('#clinicalPeBtn').getUrlParams(); window.open(LABKEY.ActionURL.buildURL('query', 'executeQuery', null, params)) - } - },{ - text: 'Download To Excel', - scope: this, - handler: function(item){ - var params = item.up('#clinicalPeBtn').getUrlParams(); - window.open(LABKEY.ActionURL.buildURL('query', 'exportRowsXLSX', null, params)) +// } +// },{ +// text: 'Download To Excel', +// scope: this, +// handler: function(item){ +// var params = item.up('#clinicalPeBtn').getUrlParams(); +// window.open(LABKEY.ActionURL.buildURL('query', 'exportRowsXLSX', null, params)) } }] }] diff --git a/onprc_ehr/resources/views/historyExport.html b/onprc_ehr/resources/views/historyExport.html index 29e3354d2..6ed80843f 100644 --- a/onprc_ehr/resources/views/historyExport.html +++ b/onprc_ehr/resources/views/historyExport.html @@ -73,11 +73,11 @@ Ext4.Msg.alert('Error', 'Must enter at least one animal Id'); return; } - + //Modified: 1-17-2019 R.Blasa if (!hideHistory){ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'SalesMedicalHistoryReport'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/SalesMedicalHistoryReport'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString({ SessionID: LABKEY.Utils.getSessionID(), diff --git a/onprc_ehr/resources/views/onprcMenu.html b/onprc_ehr/resources/views/onprcMenu.html index 7b5743a0c..0795fc5db 100644 --- a/onprc_ehr/resources/views/onprcMenu.html +++ b/onprc_ehr/resources/views/onprcMenu.html @@ -23,28 +23,28 @@ cls: 'labkey-iconpanel', tpl: [ '', - '', - '
', - '{title:htmlEncode}:', - '', - ' [Public] ', - ' [Public] ', - '', + '', + '
', + '{title:htmlEncode}:', + '', + ' [Public] ', + ' [Public] ', + '', - ' [Private] ', - ' [Private] ', - '', - '', - '
', - '', - '
data-qtip="You do not have permission to view this page"', - 'style="width: 300px;height: auto;" class="thumb-wrap thumb-wrap-side">', - '', - '{title:htmlEncode}', - '', - '
', - '
', + ' [Private] ', + ' [Private] ', + '', + '
', + '
', + '', + '
data-qtip="You do not have permission to view this page"', + 'style="width: 300px;" class="thumb-wrap thumb-wrap-side">', + '', + '{title:htmlEncode}', + '', + '
', + '
', '
', '
' ], @@ -94,7 +94,7 @@ },{ title: 'Labs', itemId: 'labs' - },{ //Added 5-28-2015 Blasa + },{ //Added 5-28-2015 Blasa title: 'SLA', itemId: 'sla' },{ @@ -103,13 +103,31 @@ },{ //Added 12-7-2016 Blasa title: 'Resource Scheduler', itemId: 'scheduler' + },{ //Added by Kolli on 2-26-2019 + title: 'Room Reservations', + itemId: 'reservation' }] }); + // Ensure proper layout if webpart came back from the server after the menu item was already collapsed and didn't + // render to the desired size + var menu = div.up('.dropdown'); + if (menu) { + var obs = new MutationObserver(function (mutationsList) { + for (var i = 0; i < mutationsList.length; i++) { + var mutation = mutationsList[i]; + if (mutation.attributeName === 'class') { + panel.doLayout(); + } + } + }); + obs.observe(menu.dom, {attributes: true}); + } + ONPRC.Utils.getNavItems({ scope: this, success: function(results){ - Ext4.each(['labs', 'admin', 'cores', 'ehr', 'dcm', 'sla', 'scheduler'], function(name){ + Ext4.each(['labs', 'admin', 'cores', 'ehr', 'dcm', 'sla', 'scheduler', 'reservation'], function(name){ if (results[name] && results[name].length){ var section = panel.down('#' + name).items.get(0); var toAdd = []; @@ -132,4 +150,6 @@ }); }); - \ No newline at end of file + + + diff --git a/onprc_ehr/resources/views/populateData.html b/onprc_ehr/resources/views/populateData.html index 2a28ade27..4aaf1a664 100644 --- a/onprc_ehr/resources/views/populateData.html +++ b/onprc_ehr/resources/views/populateData.html @@ -759,6 +759,12 @@ schemaName: 'ehr_lookups', queryName: 'ageclass', pk: 'rowid' + },{ + label: 'Acquistion Types', + populateFn: 'populateFromFile', + schemaName: 'ehr_lookups', + queryName: 'AcquistionType', + pk: 'rowid' },{ label: 'Treatment Frequency Times', populateFn: 'populateTreatmentFrequencies', diff --git a/onprc_ehr/resources/views/populateTemplates.html b/onprc_ehr/resources/views/populateTemplates.html index 4335cf232..02ed40483 100644 --- a/onprc_ehr/resources/views/populateTemplates.html +++ b/onprc_ehr/resources/views/populateTemplates.html @@ -1107,11 +1107,6 @@ ['Treatment Orders', '{"code":"E-YY535"}'], ['Treatment Orders', '{"code":"E-YY732"}'] - - - - - ] },{ template: ['Treat and Release', 'Section', 'Treatment Orders', '', ''], diff --git a/onprc_ehr/resources/views/printableReports.html b/onprc_ehr/resources/views/printableReports.html index 00eb3e928..485113efe 100644 --- a/onprc_ehr/resources/views/printableReports.html +++ b/onprc_ehr/resources/views/printableReports.html @@ -25,7 +25,8 @@ html: 'This page provides reports to be printed by room or area. After picking the location(s) using the drop downs below, ' + 'hit the \'Print\' buttons below to print any of the reports

NOTE:' + ' For most reports, leave rooms/areas blank to print all.
Vet control only applies to "Active by Clinical Cases by Vets". ' + - '
Breeding Group control only applies to "Weights Sheets by Breeding Groups".
', + '
Breeding Group control only applies to "Weights Sheets by Breeding Groups".' + + '
Enter Animal ID only applies to "Weights Sheets by Monkey ID".
', style: 'padding-bottom: 20px;' },{ xtype: 'ehr-areafield', @@ -84,6 +85,12 @@ autoLoad: true } + },{ + xtype:'textarea', //Added: 7-27-2017 R.Blasa + itemId: 'animalField', + width: 295, + height: 100, + fieldLabel: 'Enter Animal ID' },{ html: '', style: 'margin-bottom: 10px;' @@ -148,7 +155,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'ActiveClinicalCasesVet'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/ActiveClinicalCasesVet'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); @@ -217,7 +224,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'ActiveClinicalCases'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/ActiveClinicalCases'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); @@ -309,7 +316,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'ActiveTreatments'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/ActiveTreatments'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); return url; @@ -347,6 +354,74 @@ window.open(url); } },{ + html: '
', + style: 'padding-top: 10px;', + colspan: 4 + },{ + + html: 'Sustained Release Medications:' + + },{ + + style: 'padding-left: 60px;', + + + },{ + xtype: 'button', + style: 'margin-left: 5px;', + text: 'Print Version', + + border: true, + getUrlString: function(){ + var panel = this.up('#sheetPanel'); + var params = panel.getParams(true, true); + if (!params) + return; + + if (params.Rooms) + params.Rooms = params.Rooms.join(';'); + + + Ext4.apply(params, { + 'rs:ClearSession': true, + 'rs:Command': 'render' + }); + + var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); + var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/ActiveTreatments_72hr'; + + url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); + return url; + }, + menu: [{ + text: 'Print', + handler: function(menu){ + var btn = menu.up('button'); + var url = btn.getUrlString(); + if (!url) + return; + + window.open(url); + } + },{ + text: 'Print To PDF', + handler: function(menu){ + var btn = menu.up('button'); + var url = btn.getUrlString(); + if (!url) + return; + + url += '&rs:Format=PDF'; + window.open(url); + } + }] + + },{ + style: 'margin-left: 5px;', + + },{ + html: '
', style: 'padding-top: 10px;', colspan: 4 @@ -400,7 +475,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'ActiveTreatments'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/ActiveTreatments'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); return url; @@ -467,7 +542,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'ActiveSurgicalCases'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/ActiveSurgicalCases'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); return url; @@ -558,7 +633,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'ActiveTreatments'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/ActiveTreatments'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); return url; @@ -622,7 +697,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'WeightSheets'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/WeightSheets'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); return url; @@ -682,7 +757,92 @@ return; if (!Ext4.isEmpty(value)) - params.Groups = value; //params.rooms is the parameter name + params.Groups = value; + + + Ext4.apply(params, { + 'rs:ClearSession': true, + 'rs:Command': 'render' + }); + + var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); + var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/WeightSheetsGroup'; + + url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); + return url; + }, + menu: [{ + text: 'Print', + handler: function(menu){ + var btn = menu.up('button'); + var url = btn.getUrlString(); + if (!url) + return; + + window.open(url); + } + },{ + text: 'Print To PDF', + handler: function(menu){ + var btn = menu.up('button'); + var url = btn.getUrlString(); + if (!url) + return; + + url += '&rs:Format=PDF'; + window.open(url); + } + }] + + },{ + html: '' + },{ + html: '
', + style: 'padding-top: 10px;', + colspan: 4 + + },{ + html: 'Weight Sheets by Monkey ID:' //Added: 7-27-2017 R.Blasa + },{ + style: 'padding-left: 5px;', + html: '' + },{ + xtype: 'button', + style: 'margin-left: 5px;', + text: 'Print Version', + border: true, + getUrlString: function(){ + var panel = this.up('#sheetPanel'); + var field = panel.down('#animalField'); + + var val = field.getValue() || []; + + + if (val){ + val = Ext4.String.trim(val); + val = val.replace(/[\s,;]+/g, ';'); + val = val.replace(/(^;|;$)/g, ''); + + val = val ? val.split(';') : []; + } + + if (!val){ + Ext4.Msg.alert('Error', 'Must enter at least one animal Id'); + return; + } + value = Ext4.isArray(val) ? val: [val]; + + var params = { + SessionId: LABKEY.Utils.getSessionID(), + HostName: location.hostname + + }; + if (!val) + return; + + if (!Ext4.isEmpty(value)) + params.AnimalID = val; Ext4.apply(params, { @@ -692,7 +852,7 @@ var url = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSServerURL'); var ssrsFolder = LABKEY.getModuleProperty('ONPRC_EHR', 'SSRSReportFolder'); - ssrsFolder = '/' + ssrsFolder + '/' + 'WeightSheetsGroup'; + ssrsFolder = '/' + ssrsFolder + '/' + 'Clinical/WeightSheetsID'; url += ssrsFolder + '&' + LABKEY.ActionURL.queryString(params); return url; diff --git a/onprc_ehr/resources/views/projectDetails.html b/onprc_ehr/resources/views/projectDetails.html index 9d98e6b27..aceff6de8 100644 --- a/onprc_ehr/resources/views/projectDetails.html +++ b/onprc_ehr/resources/views/projectDetails.html @@ -60,7 +60,7 @@ title: 'Housing Summary', schemaName: 'study', queryName: 'projectHousingSummary', - columns: 'room,room/housingType,totalAnimals', + columns: 'room,room/housingType,room/housingCondition,totalAnimals', filters: [LABKEY.Filter.create('project', project, LABKEY.Filter.Types.EQUAL)], failure: LDK.Utils.getErrorCallback() }).render('housingSummary_' + webpart.wrapperDivId); diff --git a/onprc_ehr/resources/views/protocolDetails.html b/onprc_ehr/resources/views/protocolDetails.html index 6feaacb92..91aec7f2f 100644 --- a/onprc_ehr/resources/views/protocolDetails.html +++ b/onprc_ehr/resources/views/protocolDetails.html @@ -33,6 +33,10 @@ tag: 'div', style: 'padding-bottom: 10px;', id: 'housingSummary_' + webpart.wrapperDivId + },{ + tag: 'div', + style: 'padding-bottom: 10px;', + id: 'housingSummarySpecie_' + webpart.wrapperDivId }]; var el = Ext4.get(webpart.wrapperDivId); @@ -119,11 +123,20 @@ title: 'Housing Summary', schemaName: 'study', queryName: 'protocolHousingSummary', - columns: 'room,room/housingType,totalAnimals', + columns: 'room,room/housingType,room/housingCondition,totalAnimals', filters: [LABKEY.Filter.create('protocol', protocol, LABKEY.Filter.Types.EQUAL)], failure: LDK.Utils.getErrorCallback() }).render('housingSummary_' + webpart.wrapperDivId); + LDK.Utils.getReadOnlyQWP({ + title: 'Housing Summary By Specie', + schemaName: 'study', + queryName: 'protocolHousingSummary_Species', + columns: 'id/demographics/species,totalAnimals', + filters: [LABKEY.Filter.create('protocol', protocol, LABKEY.Filter.Types.EQUAL)], + failure: LDK.Utils.getErrorCallback() + }).render('housingSummarySpecie_' + webpart.wrapperDivId); + LDK.Utils.getReadOnlyQWP({ title: 'Projects Under This Protocol', schemaName: 'ehr', diff --git a/onprc_ehr/resources/views/quickSearchonprc.html b/onprc_ehr/resources/views/quickSearchonprc.html index 194ceea8f..cfd03aec2 100644 --- a/onprc_ehr/resources/views/quickSearchonprc.html +++ b/onprc_ehr/resources/views/quickSearchonprc.html @@ -177,9 +177,13 @@ window.location = LABKEY.ActionURL.buildURL('ehr', 'projectDetails', ctx['EHRStudyContainer'], {project:value}); } },{ - html: '[View Active Projects] [View All Projects]', + html: '[View Active Projects] ' + + ' [View All Projects] ' + + ' [View Center Project To Alias]', colspan: 2 + },{ + html: 'IACUC Protocol:', style: 'padding-top: 10px;', colspan: 2 @@ -308,9 +312,29 @@ } }); - Ext4.create('onprc_ehr.panel.QuickSearchPanel', { + var panel = Ext4.create('onprc_ehr.panel.QuickSearchPanel', { // hoverPart: HoverNavigation.Parts[webpart.hoverPartName] - }).render(webpart.wrapperDivId); + }); + panel.render(webpart.wrapperDivId); + + // Ensure proper layout if webpart came back from the server after the menu item was already collapsed and didn't + // render to the desired size + + var div = Ext4.get(webpart.wrapperDivId); + + var menu = div.up('.dropdown'); + if (menu) { + var obs = new MutationObserver(function (mutationsList) { + for (var i = 0; i < mutationsList.length; i++) { + var mutation = mutationsList[i]; + if (mutation.attributeName === 'class') { + panel.doLayout(); + } + } + }); + obs.observe(menu.dom, {attributes: true}); + } + } \ No newline at end of file diff --git a/onprc_ehr/resources/views/vetReview.html b/onprc_ehr/resources/views/vetReview.html index 584124ab2..536beebfe 100644 --- a/onprc_ehr/resources/views/vetReview.html +++ b/onprc_ehr/resources/views/vetReview.html @@ -1,103 +1,110 @@ \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/DemographicsRecord.js b/onprc_ehr/resources/web/onprc_ehr/DemographicsRecord.js index c9fa5afbb..7ebf9bcb1 100644 --- a/onprc_ehr/resources/web/onprc_ehr/DemographicsRecord.js +++ b/onprc_ehr/resources/web/onprc_ehr/DemographicsRecord.js @@ -68,6 +68,16 @@ EHR.DemographicsRecord = function(data){ return data['fosterchild']; }, + //Added 12-20-2018 R.Blasa + getLastKnownlocation: function(){ + return data['lastlocation']; + }, + + //Created: 10-4-2019 R.Blasa + getActiveDrugs: function(){ + return data['activeDrugs']; + }, + getCurrentLocation: function(){ if (data['activeHousing'] && data['activeHousing'].length){ var ret = data['activeHousing'][0].room; @@ -138,7 +148,7 @@ EHR.DemographicsRecord = function(data){ }, getGeographicOrigin: function(){ - return data['geographic_origin']; + return data['geneticAncestry'] ? data['geneticAncestry'] + ' (Verified)' : data['geographic_origin']; }, getMostRecentWeight: function(){ @@ -190,14 +200,6 @@ EHR.DemographicsRecord = function(data){ } }, - getLastTBDate: function(){ - if (data['tb'] && data['tb'].length){ - var date = data['tb'][0]['MostRecentTBDate']; - if (date) - return LDK.ConvertUtils.parseDate(date); - } - }, - getRecentWeights: function(){ return data['weights']; }, diff --git a/onprc_ehr/resources/web/onprc_ehr/buttons/ClinicalActionsButton.js b/onprc_ehr/resources/web/onprc_ehr/buttons/ClinicalActionsButton.js index 36fcc20f6..4104f0c4d 100644 --- a/onprc_ehr/resources/web/onprc_ehr/buttons/ClinicalActionsButton.js +++ b/onprc_ehr/resources/web/onprc_ehr/buttons/ClinicalActionsButton.js @@ -77,7 +77,7 @@ Ext4.define('onprc_ehr.buttons.ClinicalActionsButton', { return; } - Ext4.create('EHR.window.ManageCasesWindow', { + Ext4.create('ONPRC_EHR.window.ManageCasesWindow', { animalId: animalId }).show(); } diff --git a/onprc_ehr/resources/web/onprc_ehr/buttons/bulkEditRequestButtons.js b/onprc_ehr/resources/web/onprc_ehr/buttons/bulkEditRequestButtons.js index 0205a2320..a0d13cfda 100644 --- a/onprc_ehr/resources/web/onprc_ehr/buttons/bulkEditRequestButtons.js +++ b/onprc_ehr/resources/web/onprc_ehr/buttons/bulkEditRequestButtons.js @@ -84,6 +84,7 @@ ONPRC_EHR.Buttons.bulkEditRequestHandler = function(dataRegionName, formType, is var newForm = Ext4.DomHelper.append(document.getElementsByTagName('body')[0], '
' + '' + + '' + '
'); newForm.submit(); } diff --git a/onprc_ehr/resources/web/onprc_ehr/buttons/pathologyButtons.js b/onprc_ehr/resources/web/onprc_ehr/buttons/pathologyButtons.js index 3bf9a7b09..7215a7d18 100644 --- a/onprc_ehr/resources/web/onprc_ehr/buttons/pathologyButtons.js +++ b/onprc_ehr/resources/web/onprc_ehr/buttons/pathologyButtons.js @@ -191,6 +191,21 @@ EHR.DataEntryUtils.registerDataEntryFormButton('ENTERDEATH_FOR_TISSUES', { } }); +EHR.DataEntryUtils.registerGridButton('PATH_SAVE_DRAFT', function(config) { + return Ext4.Object.merge({ + text: 'Save Draft', + name: 'saveDraft', + requiredQC: 'In Progress', + errorThreshold: 'WARN', + disabled: false, + itemId: 'saveDraftBtn', + handler: function(btn){ + var panel = btn.up('ehr-dataentrypanel'); + panel.onSubmit(btn) + }, + disableOn: 'ERROR' + }, config); +}); EHR.DataEntryUtils.registerGridButton('RESET_SORT_ORDER', function(config){ return Ext4.Object.merge({ text: 'Reset Sort Order', diff --git a/onprc_ehr/resources/web/onprc_ehr/data/sources/BehaviorExamStoreCollection.js b/onprc_ehr/resources/web/onprc_ehr/data/sources/BehaviorExamStoreCollection.js new file mode 100644 index 000000000..d0d4143e2 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/data/sources/BehaviorExamStoreCollection.js @@ -0,0 +1,140 @@ + + +//Created: 12-18-2017 R.Blasa + +Ext4.define('ONPRC_EHR.data.sources.BehaviorExamStoreCollection', { + extend: 'EHR.data.TaskStoreCollection', + + constructor: function(){ + this.callParent(arguments); + + this.mon(EHR.DemographicsCache, 'casecreated', this.onCaseCreated, this); + }, + + //Modified: 1-15-2020 R. Blasa + onCaseCreated: function(id, category, caseId){ + + if (category != 'Behavior') + return; + + //NOTE: if we opened a case from this form, tag the SOAP note + var rec = this.getRemarksRec(); + if (rec && id == rec.get('Id')){ + if (!rec.get('caseid')){ + rec.set('caseid', caseId); + } + } + }, + + setClientModelDefaults: function(model){ + var vals = this.getDefaultValues(); + if (!Ext4.Object.isEmpty(vals)){ + var toSet = {}; + + if (model.fields.get('Id') != null){ //Added : Testing R. Blasa + toSet.Id = vals.Id; + toSet.date = vals.date; + + } + if (model.fields.get('caseid') != null){ + toSet.caseid = vals.caseid; + } + + if (!Ext4.isEmpty(toSet)){ + model.suspendEvents(); + model.set(toSet); + model.resumeEvents(); + } + } + + return this.callParent([model]); + }, + + getRemarksStore: function(){ + if (this.remarkStore){ + return this.remarkStore; + } + + this.remarkStore = this.getClientStoreByName('Clinical Remarks'); + LDK.Assert.assertNotEmpty('Unable to find clinical remarks store in ClinicalReportStoreCollection', this.remarkStore); + + return this.remarkStore; + }, + + getRemarksRec: function(){ + var remarkStore = this.getRemarksStore(); + if (remarkStore){ + LDK.Assert.assertTrue('More than 1 record found in Clinical remarks store, actual: ' + remarkStore.getCount(), remarkStore.getCount() <= 1); + if (remarkStore.getCount() == 1){ + return remarkStore.getAt(0); + } + } + }, + + getDefaultValues: function(){ + var rec = this.getRemarksRec(); + if (rec){ + return { + Id: rec.get('Id'), + date:rec.get('date'), //Added R.Blasa + caseid: rec.get('caseid') + } + } + + return null; + }, + + onClientStoreUpdate: function(){ + this.doUpdateRecords(); + this.callParent(arguments); + }, + + doUpdateRecords: function(){ + var newValues = this.getDefaultValues() || {}; + var cacheKey = newValues ? (newValues.Id + '||' + newValues.caseid) : null; + + if (cacheKey !== this._cachedKey){ + var remarkStore = this.getRemarksStore(); + this.clientStores.each(function(cs){ + if (cs.storeId == remarkStore.storeId){ + return; + } + + var toSet = {}; + + if (cs.getFields().get('Id') != null){ + toSet.Id = newValues.Id; + } + if (cs.getFields().get('caseid') != null){ + toSet.caseid = newValues.caseid; + } + + if (Ext4.Object.isEmpty(toSet)){ + return; + } + + var storeChanged = false; + cs.suspendEvents(); + cs.each(function(rec){ + var needsUpdate = false; + for (var field in toSet){ + if (toSet[field] !== rec.get(field)){ + needsUpdate = true; + } + } + + if (needsUpdate){ + storeChanged = true; + rec.set(toSet); + } + }, this); + cs.resumeEvents(); + + if (storeChanged) + cs.fireEvent('datachanged', cs); + }, this); + } + + this._cachedKey = cacheKey; + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/data/sources/ClinpathRunsClientStore.js b/onprc_ehr/resources/web/onprc_ehr/data/sources/ClinpathRunsClientStore.js new file mode 100644 index 000000000..271b9d598 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/data/sources/ClinpathRunsClientStore.js @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * @param fieldConfigs + */ + +//Created: 3-12-2020 R.Blasa + +Ext4.define('ONPRC_EHR.data.ClinpathRunsClientStore', { + extend: 'EHR.data.DataEntryClientStore', + + constructor: function(){ + this.callParent(arguments); + + this.on('add', this.onAddRecord, this); + }, + + onAddRecord: function(store, records){ + Ext4.each(records, function(record){ + var modified = ['servicerequested']; + if (record.get('chargetype')){ + modified.push('chargetype'); + } + this.onRecordUpdate(record, modified); + }, this); + }, + + afterEdit: function(record, modifiedFieldNames){ + this.onRecordUpdate(record, modifiedFieldNames); + + this.callParent(arguments); + }, + + onRecordUpdate: function(record, modifiedFieldNames){ + if (record.get('servicerequested')){ + modifiedFieldNames = modifiedFieldNames || []; + + var store = EHR.DataEntryUtils.getLabworkServicesStore(); + if (!store){ + LDK.Utils.logToServer({ + message: 'Unable to find lookup store in ClinpathRunsClientStore' + }); + console.error('Unable to find lookup store in ClinpathRunsClientStore'); + + return; + } + + var lookupRecIdx = store.findExact('servicename', record.get('servicerequested')); + if (lookupRecIdx == -1){ + LDK.Utils.logToServer({ + message: 'Unable to find lookup record in ClinpathRunsClientStore' + }); + console.error('Unable to find lookup record in ClinpathRunsClientStore'); + + return; + } + + var lookupRec = store.getAt(lookupRecIdx); + var params = {}; + if (lookupRec.get('dataset')) + params.type = lookupRec.get('dataset'); + + //NOTE: if setting both service and chargetype simultaneously, do not override that selection + if (modifiedFieldNames.indexOf('servicerequested') > -1 && modifiedFieldNames.indexOf('chargetype') == -1 && lookupRec.get('chargetype')){ + //only update if using a standard value + if (!record.get('chargetype') || record.get('chargetype') == 'Clinpath' || record.get('chargetype') == 'SPF Surveillance Lab') + params.chargetype = lookupRec.get('chargetype'); + } + + if (modifiedFieldNames.indexOf('servicerequested') > -1 && lookupRec.get('tissue')){ + params.tissue = lookupRec.get('tissue'); + } + + if (!LABKEY.Utils.isEmptyObj(params)){ + record.beginEdit(); + record.set(params); + record.endEdit(true); + } + } + + //also cascade update children if Id/date changes + if (modifiedFieldNames && (modifiedFieldNames.indexOf('Id') > -1 || modifiedFieldNames.indexOf('project') > -1)){ + if (record.get('objectid')){ + if (!this.storeCollection){ + LDK.Utils.logError('this.storeCollection is null in ClinpathRunsClientStore'); + return; + } + + this.storeCollection.clientStores.each(function(cs){ + if (cs.storeId == this.storeId){ + return; + } + + var hasProject = cs.getFields().get('project') != null; + var hasChanges = false; + + if (cs.getFields().get('runid')){ + if (cs.getFields().get('Id') || cs.getFields().get('project')){ + cs.each(function(r){ + if (r.get('runid') === record.get('objectid')){ + var obj = {}; + if (hasProject && r.get('project') !== record.get('project')){ + obj.project = record.get('project'); + } + + if (r.get('Id') !== record.get('Id')){ + obj.Id = record.get('Id'); + } + + if (!Ext4.Object.isEmpty(obj)){ + r.beginEdit(); + r.set(obj); + r.endEdit(true); + hasChanges = true; + } + } + }, this); + } + } + + if (hasChanges){ + cs.fireEvent('datachanged', cs); + } + }, this); + } + } + } +}); diff --git a/onprc_ehr/resources/web/onprc_ehr/data/sources/ONPRCDefaults.js b/onprc_ehr/resources/web/onprc_ehr/data/sources/ONPRCDefaults.js index dc11d2d20..b6956c480 100644 --- a/onprc_ehr/resources/web/onprc_ehr/data/sources/ONPRCDefaults.js +++ b/onprc_ehr/resources/web/onprc_ehr/data/sources/ONPRCDefaults.js @@ -10,6 +10,16 @@ */ EHR.model.DataModelManager.registerMetadata('Default', { byQuery: { + + //Kolli1 3/19: Added this code to display the description field in the protocol details data entry screen. The Description field is hidden in the core. (Defaults.js) + // To overwrite the core code, this snippet is added on the onprc side + 'ehr.protocol': { + description: { + hidden: false, + label: "Notes" + } + }, + 'study.blood' : { tube_vol: { hidden: true @@ -30,22 +40,172 @@ EHR.model.DataModelManager.registerMetadata('Default', { } } + }, + + // //Added: 1-23-2019 R.Blasa allow drug sedation alert notification + // 'study.drug': { + // description: { + // hidden: false, + // width: 200 + // }, + // reason: { + // hidden: true, + // } + // }, + + //Added: 12-27-2017 R.Blasa + 'study.Arrival': { + date: { + xtype: 'xdatetime', + allowBlank: false, + extFormat: LABKEY.extDefaultDateTimeFormat, + columnConfig: { + width: 150 + } + }, + //Added: 5-3-2018 R.Blasa + acquisitionType: { + hidden: false, + allowBlank: false + } + }, + + //Added: 12-26-2017 R.Blasa + 'study.Assignment': { + + date: { + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, + columnConfig: { + width: 100 + } + }, + enddate: { + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, + columnConfig: { + width: 100 + } + }, + + projectedRelease: { + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, + columnConfig: { + width: 100 + } + }, + + projectedReleaseCondition: { + columnConfig: { + width: 200 + } + }, + releaseCondition: { + columnConfig: { + width: 200 + } , + lookup: { + filterArray: [ + LABKEY.Filter.create('datedisabled', null, LABKEY.Filter.Types.ISBLANK) + + ] + + } + }, + + assignCondition: { + columnConfig: { + width: 200 + } + + }, + + + projectedRelease: { + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, + columnConfig: { + width: 100 + } + } + + }, + + 'study.weight': { + project: { + hidden: true + }, + account: { + hidden: true + }, + performedby: { + allowBlank: false, + lookup: { + schemaName: 'core', + queryName: 'users', + keyColumn: 'DisplayName', + displayColumn: 'DisplayName', + columns: 'UserId,DisplayName,FirstName,LastName', + sort: 'Type,DisplayName' + } + }, + + 'id/curlocation/location': { + shownInGrid: true + }, + remark: { + shownInGrid: true + }, + weight: { + allowBlank: false, + useNull: true, + editorConfig: { + allowNegative: false, + decimalPrecision: 4 + } + } + }, + //Added: 11-20-2017 R.blasa + + 'study.clinremarks': { + + CEG_Plan: { + formEditorConfig: { + xtype: 'onprc_ehr-CEG_Plantextarea' + }, + height: 52 + } + }, + + //Added: 12-27-2017 R.blasa + + 'study.flags': { + + RequestedBy: { + columnConfig: { + width: 100 + } + + }, + ScheduleNecropsy: { + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, + columnConfig: { + width: 150 + } + + }, + TargetEndDate: { + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, + columnConfig: { + width: 150 + } + } + } - // 'study.Assignment' : { - // Cohort: { - // xtype: 'onprc-cohortfield', - // editorConfig: { - // - // }, - // shownInGrid: true, - // useNull: true, - // columnConfig: { - // width: 500 - // } - // } - // } - // } }); diff --git a/onprc_ehr/resources/web/onprc_ehr/data/sources/PathologyTissuesStoreCollection.js b/onprc_ehr/resources/web/onprc_ehr/data/sources/PathologyTissuesStoreCollection.js new file mode 100644 index 000000000..64ddeed8e --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/data/sources/PathologyTissuesStoreCollection.js @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +//Added 5-24-2017 R.Blasa +Ext4.define('onprc_ehr.data.sources.PathologyTissuesStoreCollection', { + extend: 'EHR.data.TaskStoreCollection', + + constructor: function(){ + this.callParent(arguments); + }, + + setClientModelDefaults: function(model){ + var vals = this.getDefaultValues(); + if (!Ext4.Object.isEmpty(vals)){ + var toSet = {}; + + if (model.fields.get('Id') != null){ + toSet.Id = vals.Id; + toSet.date = vals.date; + toSet.project = vals.project; + } + + + if (!Ext4.isEmpty(toSet)){ + model.suspendEvents(); + model.set(toSet); + model.resumeEvents(); + } + } + + return this.callParent([model]); + }, + + getRemarksStore: function(){ + if (this.remarkStore){ + return this.remarkStore; + } + + this.remarkStore = this.getClientStoreByName('encounters'); + LDK.Assert.assertNotEmpty('Unable to find Pathology tissue record store in PathologyTissuesReportStoreCollection', this.remarkStore); + + return this.remarkStore; + }, + + getRemarksRec: function(){ + var remarkStore = this.getRemarksStore(); + if (remarkStore){ + LDK.Assert.assertTrue('More than 1 record found in Pathology Tissues store, actual: ' + remarkStore.getCount(), remarkStore.getCount() <= 1); + if (remarkStore.getCount() == 1){ + return remarkStore.getAt(0); + } + } + }, + + getDefaultValues: function(){ + var rec = this.getRemarksRec(); + if (rec){ + return { + Id: rec.get('Id'), + date:rec.get('date'), + project:rec.get('project') + + } + } + + return null; + } + + +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/data/sources/TreatmentOrdersClientStore.js b/onprc_ehr/resources/web/onprc_ehr/data/sources/TreatmentOrdersClientStore.js new file mode 100644 index 000000000..0bc1c4ee6 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/data/sources/TreatmentOrdersClientStore.js @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2013-2015 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +//Created: 7-29-2020 R.Blasa + +Ext4.define('ONPRC_EHR.data.TreatmentOrdersClientStore', { + extend: 'EHR.data.DrugAdministrationRunsClientStore', + + constructor: function(){ + this.callParent(arguments); + + this.on('add', this.onAddRecord, this); + }, + + onAddRecord: function(store, records){ + Ext4.each(records, function(record){ + this.onRecordUpdate(record, ['objectid']); + }, this); + }, + + afterEdit: function(record, modifiedFieldNames){ + this.onRecordUpdate(record, modifiedFieldNames); + + this.callParent(arguments); + }, + + onRecordUpdate: function(record, modifiedFieldNames){ + if (record.get('code')){ + modifiedFieldNames = modifiedFieldNames || []; + + if (record.get('code') == 'E-85760' && record.get('remark')== null){ + record.beginEdit(); + record.set('remark', 'Please make a clinical prime entry at each administration once the administration is complete.'); + record.endEdit(true); + } + + if (!this.formularyStore){ + LDK.Utils.logToServer({ + message: 'Unable to find formulary store in DrugAdministrationRunsClientStore' + }); + console.error('Unable to find formulary store in DrugAdministrationRunsClientStore'); + + return; + } + + var values = this.formularyStore.getFormularyValues(record.get('code')); + if (!Ext4.Object.isEmpty(values)){ + var params = {}; + + for (var fieldName in this.fieldMap){ + if (!this.getFields().get(fieldName)){ + continue; + } + + if (modifiedFieldNames.indexOf(this.fieldMap[fieldName]) != -1){ + //console.log('field already set: ' + fieldName); + continue; + } + + var def = values[fieldName]; + if (Ext4.isDefined(def)){ + params[this.fieldMap[fieldName]] = def; + } + } + + if (!LABKEY.Utils.isEmptyObj(params)){ + record.beginEdit(); + record.set(params); + record.endEdit(true); + } + } + } + } + + +}); diff --git a/onprc_ehr/resources/web/onprc_ehr/form/field/AnimalGroupFieldsCombo.js b/onprc_ehr/resources/web/onprc_ehr/form/field/AnimalGroupFieldsCombo.js new file mode 100644 index 000000000..ae1e67757 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/form/field/AnimalGroupFieldsCombo.js @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + * + * @cfg pairedWithRoomField. Note: if true, you must implement getRoomField(), which returns the cognate ehr-roomfield + */ +Ext4.define('ONPRC_EHR.form.field.AnimalGroupField', { + extend: 'Ext.ux.CheckCombo', + alias: 'widget.onprc_ehr-animalgroupfield', + + fieldLabel: 'Animal Group', + expandToFitContent: true, + nullCaption: '[Blank]', + editable: false, + typeAhead: true, + + initComponent: function(){ + Ext4.apply(this, { + displayField: 'name', + valueField: 'rowid', + queryMode: 'local', + store: Ext4.create('LABKEY.ext4.data.Store', { + schemaName: 'ehr', + queryName: 'animal_groups', + sort: 'name', + filterArray: [LABKEY.Filter.create('isActive', true, LABKEY.Filter.Types.EQUAL)], + autoLoad: true + }) + }); + + this.callParent(arguments); + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/form/field/CEG_PlantextArea.js b/onprc_ehr/resources/web/onprc_ehr/form/field/CEG_PlantextArea.js new file mode 100644 index 000000000..3620e5e9d --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/form/field/CEG_PlantextArea.js @@ -0,0 +1,201 @@ +/** + * Created: R.Blasa on 10/25/2017. + */ +/* + * Copyright (c) 2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +Ext4.define('ONPRC_EHR.form.field.CEG_PlantextArea', { + extend: 'Ext.form.field.TextArea', + alias: 'widget.onprc_ehr-CEG_Plantextarea', + + onAnimalChange: function(){ + this.updateDisplayEl(); + }, + + onRender : function(ct, position){ + this.callParent(arguments); + + this.wrap = this.inputEl.wrap({ + tag: 'div', + cls: 'x4-form-field-wrap' + }); + + this.linkDiv = this.wrap.createChild({ + tag: 'div', + style: 'vertical-align:top;' + }, this.inputEl); + + this.linkEl = this.linkDiv.createChild({ + tag: 'a', + cls: 'labkey-text-link', + html: (this.getValue() ? 'Copy Latest CEG_Plan' : 'Edit CEG_Plan') + }); + + var panel = this.up('ehr-formpanel'); + if (panel){ + this.mon(panel, 'bindrecord', this.onAnimalChange, this, {buffer: 100}); + } + else { + LDK.Utils.logToServer({ + message: 'Unable to find ehr-formpanel in PlanTextArea' + }) + } + + var dataEntryPanel = this.up('ehr-dataentrypanel'); + if (dataEntryPanel){ + this.mon(dataEntryPanel, 'animalchange', this.onAnimalChange, this, {buffer: 100}); + } + else { + LDK.Utils.logToServer({ + message: 'Unable to find ehr-dataentrypanel in PlanTextArea' + }) + } + + this.linkEl.on('click', this.copyMostRecentCEG_Plan, this); + this.setupMask(); + }, + + setupMask: function(){ + if (this.getValue()){ + this.showTextArea(); + return; + } + + this.inputEl.setVisibilityMode(Ext4.dom.AbstractElement.DISPLAY); + this.inputEl.setVisible(false); + + this.displayEl = this.wrap.createChild({ + tag: 'div', + style: 'vertical-align:top;', + html: '' + }); + + this.displayEl.setWidth(this.width - this.labelWidth); + this.displayEl.setHeight(this.getHeight()); + + this.updateDisplayEl(); + }, + + showTextArea: function(){ + if (!this.rendered){ + return; + } + + if (this.displayEl){ + this.displayEl.remove(); + delete this.displayEl; + } + + if (this.linkEl){ + this.linkEl.update('Copy Latest CEG_Plan'); + } + + if (this.inputEl) + this.inputEl.setVisible(true); + }, + + updateDisplayEl: function(){ + if (!this.displayEl){ + return; + } + + var rec = EHR.DataEntryUtils.getBoundRecord(this); + if (rec && rec.get('Id')){ + this.getMostRecentCEG_Plan(rec, function(ret, Id){ + if (!ret || !this.displayEl){ + return; + } + + if (ret.mostRecentCeg_Plan && ret.isActive){ + this.displayEl.update(ret.mostRecentCeg_Plan); + } + else { + this.displayEl.update('Either no active case or no CEG_Plan for ' + (Id || rec.get('Id'))); + } + }); + } + else { + this.displayEl.update('No animal entered'); + } + }, + + copyMostRecentCEG_Plan: function(){ + var rec = EHR.DataEntryUtils.getBoundRecord(this); + if (!rec || !rec.get('Id')){ + Ext4.Msg.alert('Error', 'No Id Entered'); + return; + } + + Ext4.Msg.wait('Loading...'); + this.showTextArea(); + + this.getMostRecentCEG_Plan(rec, function(ret){ + Ext4.Msg.hide(); + + if (ret){ + this.setValue(ret.mostRecentCeg_Plan); + this.linkEl.update('Refresh CEG Plan'); + } + }, true); + }, + + getMostRecentCEG_Plan: function(rec, cb, alwaysUseCallback){ + var date = rec.get('date') || new Date(); + var id = rec.get('Id'); + this.pendingIdRequest = id; + + LABKEY.Query.executeSql({ + schemaName: 'study', + sql: 'SELECT c.Id, c.CEG_Plan as mostRecentCeg_Plan, c.caseid, c.caseid.category as caseCategory, c.caseid.isActive as isActive FROM study.clinRemarks c WHERE (c.category != \'Replaced SOAP\' OR c.category IS NULL) AND c.CEG_Plan IS NOT NULL AND c.Id = \'' + rec.get('Id') + '\' ORDER BY c.date DESC LIMIT 1', + failure: LDK.Utils.getErrorCallback(), + scope: this, + success: function(results){ + if (!alwaysUseCallback && id != this.pendingIdRequest){ + console.log('more recent request, aborting'); + return; + } + + if (results && results.rows && results.rows.length && results.rows[0].mostRecentCeg_Plan){ + cb.call(this, results.rows[0], results.rows[0].Id); + } + else { + cb.call(this, null, id); + } + } + }); + }, + + onDestroy : function(){ + if (this.linkEl){ + this.linkEl.removeAllListeners(); + this.linkEl.remove(); + } + + if (this.linkDiv){ + this.linkDiv.removeAllListeners(); + this.linkDiv.remove(); + } + + if (this.displayEl){ + //NOTE: no listeners were added + //this.displayEl.removeAllListeners(); + this.displayEl.remove(); + } + + if (this.wrap){ + this.wrap.remove(); + } + + this.callParent(this); + }, + + setValue: function(){ + this.callParent(arguments); + + if (this.getValue()){ + this.showTextArea(); + } + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/form/field/TB_TST_Scores_Type.js b/onprc_ehr/resources/web/onprc_ehr/form/field/TB_TST_Scores_Type.js new file mode 100644 index 000000000..392c8057a --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/form/field/TB_TST_Scores_Type.js @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2016-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * Created: R.Blasa on 11/4/2016. + */ +Ext4.define('onprc_ehr.form.field.onprc_TB_TST_ObservationScores', { + extend: 'Ext.form.field.ComboBox', + alias: 'widget.onprc_TB_TST_ObservationScores', + + + nullCaption: '[Blank]', + expandToFitContent: true, + caseSensitive: false, + anyMatch: true, + typeAhead: true, + + initComponent: function(){ + Ext4.apply(this, { + displayField:'value', + valueField: 'value', + queryMode: 'local', + store: Ext4.create('LABKEY.ext4.data.Store', { + schemaName: 'sla', + queryName: 'Reference_Data', + columns: 'value', + sort: 'value', + filterArray: [ + LABKEY.Filter.create('enddate', null, LABKEY.Filter.Types.ISBLANK), + LABKEY.Filter.create('ColumnName', 'TBTestObserveScore', LABKEY.Filter.Types.EQUAL)], + autoLoad: true + }) + }); + + this.callParent(arguments); + + + + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/form/field/onprc_SlaCensusConfig.js b/onprc_ehr/resources/web/onprc_ehr/form/field/onprc_SlaCensusConfig.js index 7272dbd3d..6e11dd97a 100644 --- a/onprc_ehr/resources/web/onprc_ehr/form/field/onprc_SlaCensusConfig.js +++ b/onprc_ehr/resources/web/onprc_ehr/form/field/onprc_SlaCensusConfig.js @@ -110,18 +110,13 @@ Ext4.define('onprc_ehr.form.field.onprc_Species', { } }); -/* - * Copyright (c) 2016-2017 LabKey Corporation - * - * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 - * - * @cfg pairedWithRoomField. Note: if true, you must implement getRoomField(), which returns the cognate ehr-roomfield - */ + Ext4.define('onprc_ehr.form.field.onprc_Roomfield', { extend: 'Ext.form.field.ComboBox', alias: 'widget.onprc_Roomfield', initComponent: function(){ + var ctx = EHR.Utils.getEHRContext(); Ext4.apply(this, { queryMode: 'local', nullCaption: '[Blank]', @@ -134,6 +129,7 @@ Ext4.define('onprc_ehr.form.field.onprc_Roomfield', { valueField: 'room', store: { type: 'labkey-store', + containerPath: ctx ? ctx['EHRStudyContainer'] : null, schemaName: 'ehr_lookups', queryName: 'rooms', columns: 'room', @@ -153,3 +149,43 @@ Ext4.define('onprc_ehr.form.field.onprc_Roomfield', { } }); + +Ext4.define('onprc_ehr.form.field.onprc_RoomfieldExtended', { + extend: 'Ext.ux.CheckCombo', + alias: 'widget.onprc_RoomfieldExtended', + + initComponent: function(){ + var ctx = EHR.Utils.getEHRContext(); + Ext4.apply(this, { + queryMode: 'local', + nullCaption: '[Blank]', + expandToFitContent: true, + typeAhead: true, + matchFieldWidth: false, + anyMatch: true, + displayField: 'room', + forceSelection: true, + valueField: 'room', + store: { + type: 'labkey-store', + containerPath: ctx ? ctx['EHRStudyContainer'] : null, + schemaName: 'ehr_lookups', + queryName: 'rooms', + columns: 'room', + sort: 'room', + filterArray: [ + LABKEY.Filter.create('dateDisabled', null, LABKEY.Filter.Types.ISBLANK), + LABKEY.Filter.create('housingType', 589, LABKEY.Filter.Types.EQUAL)], //Rodent Location + autoLoad: true + + } + }); + + this.callParent(arguments); + + + + } +}); + + diff --git a/onprc_ehr/resources/web/onprc_ehr/icons/PrimeSlideImage.gif b/onprc_ehr/resources/web/onprc_ehr/icons/PrimeSlideImage.gif new file mode 100644 index 000000000..c24547153 Binary files /dev/null and b/onprc_ehr/resources/web/onprc_ehr/icons/PrimeSlideImage.gif differ diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/ASB_Services.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/ASB_Services.js index 284227561..538377b0c 100644 --- a/onprc_ehr/resources/web/onprc_ehr/model/sources/ASB_Services.js +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/ASB_Services.js @@ -1,3 +1,4 @@ + /* * Copyright (c) 2013-2014 LabKey Corporation * @@ -12,12 +13,38 @@ EHR.model.DataModelManager.registerMetadata('ASB_Services', { chargetype: { defaultValue: 'DCM: ASB Services', hidden: true - } - }, + }, + date: { + xtype: 'xdatetime', + extFormat: 'Y-m-d H:i', + defaultValue: (new Date()).format('Y-m-d 8:0') + }, + type: { + defaultValue: 'Procedure', + hidden: true + }, + procedureid: { + lookup: { + filterArray: [ + LABKEY.Filter.create('category', 'Surgery', LABKEY.Filter.Types.NEQ), + LABKEY.Filter.create('category', 'Pathology', LABKEY.Filter.Types.NEQ), + LABKEY.Filter.create('active', true, LABKEY.Filter.Types.EQUAL) + ] + }}}, 'study.blood': { chargetype: { defaultValue: 'DCM: ASB Services', hidden: true + }, + performedby: { + //defaultValue: LABKEY.Security.currentUser.displayName, + hidden: false, + header: 'Completed by' + }, + date: { + xtype: 'xdatetime', + extFormat: 'Y-m-d H:i', + defaultValue: (new Date()).format('Y-m-d 8:0') } }, 'study.drug': { @@ -25,11 +52,73 @@ EHR.model.DataModelManager.registerMetadata('ASB_Services', { defaultValue: 'DCM: ASB Services', hidden: true }, + date: { + xtype: 'xdatetime', + extFormat: 'Y-m-d H:i', + defaultValue: (new Date()).format('Y-m-d 8:0') + }, + Billable: { + defaultValue: 'Yes', + hidden: false + }, + category: { + defaultValue: 'Research', + hidden: true + }, + remark: { + header: 'Special Instructions', + hidden: false + }, + reason: { + defaultValue: 'Research', + hidden: false + }, + lot: { + hidden: true + }, code: { editorConfig: { - defaultSubset: 'Drugs and Procedures' - } + defaultSubset: 'Research' + }, + header: 'Agent Administered' } + }, + 'ehr.requests': { + remark: { + label: 'Lab Phone # ', + width: 300, + height: 20, + hidden: false + } + } + // Modified: 7-27-2017 R.Blasa not needed for this version + //'study.treatment_order': { + // chargetype: { + // defaultValue: 'DCM: ASB Services', + // hidden: true + // }, + // date: { + // defaultValue: new Date() + // }, + // Billable: { + // defaultValue: 'Yes', + // hidden: true + // }, + // code: { + // header: 'Agent', + // editorConfig: { + // defaultSubset: 'Research' + // } + // }, + // category: { + // defaultValue: 'Research', + // hidden: true + // }, + // remark: { + // header: 'Special Instructions', + // hidden: false + // } + //} } }); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/Biopsy_Staff.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/Biopsy_Staff.js new file mode 100644 index 000000000..42b8f28ca --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/Biopsy_Staff.js @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +//Created: 10-12-2017 R.Blasa +EHR.model.DataModelManager.registerMetadata('Biopsy_Staff', { + + byQuery: { + + 'ehr.encounter_participants': { + Id: { + hidden: false, + allowBlank: false + }, + userid: { + hidden: true, + columnConfig: { + width: 200 + } + }, + username: { + hidden: false, + allowBlank: false, + columnConfig: { + width: 200 + }, + lookup: { + xtype: 'labkey-combo', + schemaName: 'onprc_ehr', + queryName: 'Reference_StaffNames', + keyColumn: 'username', + displayColumn: 'username', + filterArray: [ + LABKEY.Filter.create('DisableDate', null, LABKEY.Filter.Types.ISBLANK), + LABKEY.Filter.create('Type', 'Necropsy', LABKEY.Filter.Types.EQUAL)], + columns: 'username,FirstName,LastName,Type,DisableDate', + sort: 'username' + + }, + editorConfig: { + anyMatch: true, + listConfig: { + innerTpl: '{[values.username + (values.username ? " (" + values.LastName + (values.FirstName ? ", " + values.FirstName : "") + ")" : "")]}', + getInnerTpl: function(){ + return this.innerTpl; + } + } + } + }, + role: { + allowBlank: false, + columnConfig: { + width: 200 + } + }, + comment: { + hidden: true + } + } + + + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalEncounters.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalEncounters.js index fa761e834..639b9c85b 100644 --- a/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalEncounters.js +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalEncounters.js @@ -15,4 +15,4 @@ EHR.model.DataModelManager.registerMetadata('ClinicalEncounters', { } } } -}); \ No newline at end of file +}); diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalReport.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalReport.js new file mode 100644 index 000000000..c9618b8c1 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalReport.js @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +EHR.model.DataModelManager.registerMetadata('ClinicalReport_ONPRC', { + allQueries: { + date: { + getInitialValue: function(v, rec){ + if (v){ + return v; + } + else if (rec && rec.storeCollection && rec.storeCollection.getRemarksRec){ + var rr = rec.storeCollection.getRemarksRec(); + if (rr && rr.get('date')){ + return rr.get('date'); + } + } + + return new Date(); + } + } + }, + byQuery: { + 'study.clinremarks': { + project: { + hidden: false, + allowBlank: false + }, + hx: { + hidden: false + }, + p2: { + formEditorConfig: { + xtype: 'ehr-plantextarea' + }, + height: 75 + }, + CEG_Plan: { + formEditorConfig: { + xtype: 'onprc_ehr-CEG_Plantextarea' + }, + height: 52 + } + }, + 'study.treatment_order': { + date: { + getInitialValue: function(v, rec){ + if (v) + return v; + + var ret = Ext4.Date.clearTime(new Date()); + ret = Ext4.Date.add(ret, Ext4.Date.DAY, 1); + ret.setHours(8); + return ret; + } + } + } + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalRounds.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalRounds.js new file mode 100644 index 000000000..09bec1e6e --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/ClinicalRounds.js @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +//Created: 10-10-2017 R.Blasa + +EHR.model.DataModelManager.registerMetadata('ClinicalRounds_ONPRC', { + allQueries: { + + }, + byQuery: { + 'study.clinremarks': { + Id: { + editable: false, + columnConfig: { + editable: false + } + }, + category: { + defaultValue: 'Clinical', + hidden: true + }, + hx: { + hidden: false + }, + s: { + hidden: true + }, + o: { + hidden: true + }, + a: { + hidden: true + }, + p: { + hidden: true + }, + CEG_Plan: { + + height: 22 + }, + remark: { + hidden: false + } + }, + 'study.blood': { + reason: { + defaultValue: 'Clinical' + }, + instructions: { + hidden: true + } + }, + 'study.encounters': { + instructions: { + hidden: true + } + }, + 'study.clinical_observations': { + Id: { + editable: false, + columnConfig: { + editable: false + } + } + } + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/Gross_Finding.css b/onprc_ehr/resources/web/onprc_ehr/model/sources/Gross_Finding.css new file mode 100644 index 000000000..d7115e948 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/Gross_Finding.css @@ -0,0 +1,7 @@ + +.x4-form-item, +.x4-form-field { + font: normal 14px "Arial", Arial, Helvetica, sans-serif; } + +.x4-grid-editor +.x4-form-text{font: normal 14px/13px 'Roboto',Arial,Helvetica,sans serif;padding:1px 5px 2px 5px;height:20px;} \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/NHPTrainingProperties.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/NHPTrainingProperties.js index 9b50fa90c..5de5cceb3 100644 --- a/onprc_ehr/resources/web/onprc_ehr/model/sources/NHPTrainingProperties.js +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/NHPTrainingProperties.js @@ -15,29 +15,34 @@ EHR.model.DataModelManager.registerMetadata('NHPTraining', { byQuery: { 'onprc_ehr.NHP_Training': { training_Start_Date: { - xtype: 'xdatetime', - editorConfig: { - dateFormat: 'Y-m-d', - timeFormat: 'H:i' - }, - + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, columnConfig: { width: 150 } }, training_End_Date: { - xtype: 'xdatetime', - editorConfig: { - dateFormat: 'Y-m-d', - timeFormat: 'H:i' - }, - + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, columnConfig: { width: 150 } }, + //Added: 5-22-2018 R.Blasa + created: { + hidden: true, + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat + }, + //Added: 5-22-2018 R.Blasa + modified: { + hidden: true, + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat + }, + training_type: { allowBlank: false, xtype: 'onprc_TrainingType' , diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/Pairing_Properties.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/Pairing_Properties.js index 9852839e0..b4fc651e5 100644 --- a/onprc_ehr/resources/web/onprc_ehr/model/sources/Pairing_Properties.js +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/Pairing_Properties.js @@ -15,40 +15,40 @@ EHR.model.DataModelManager.registerMetadata('Pairing_Properties', { outcome: { allowBlank: false, - lookup: { filterArray: [ LABKEY.Filter.create('date_disabled', null, LABKEY.Filter.Types.ISBLANK) ] } + }, - } , - - eventType: { + eventtype: { allowBlank: false, - lookup: { - filterArray: [ - LABKEY.Filter.create('date_disabled', null, LABKEY.Filter.Types.ISBLANK) - ] + sort: 'sort_order' } - - }, - goal: { allowBlank: false, - lookup: { filterArray: [ - LABKEY.Filter.create('dated_disabled', null, LABKEY.Filter.Types.ISBLANK) + LABKEY.Filter.create('date_disabled', null, LABKEY.Filter.Types.ISBLANK) ] } + }, + endeventType: { + lookup: { + sort: 'sort_order' + } + }, + enddate: { + hidden: false }, + separationreason: { - allowBlank: false, + allowBlank: true, lookup: { filterArray: [ @@ -56,9 +56,9 @@ EHR.model.DataModelManager.registerMetadata('Pairing_Properties', { ] } - }, observation: { + allowBlank: true, columnConfig: { width: 200 }, @@ -68,8 +68,18 @@ EHR.model.DataModelManager.registerMetadata('Pairing_Properties', { ] } + }, + + remark2: { + xtype: 'textareafield', + width: 400, + + }, + remark: { + width: 400 + }, + } - } } }); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/Parentage_Properties.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/Parentage_Properties.js new file mode 100644 index 000000000..3c92b0548 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/Parentage_Properties.js @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2016-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +//Created 12-26-2017 R.Blasa +EHR.model.DataModelManager.registerMetadata('ParentageProperty', { + allQueries: { + + }, + byQuery: { + + 'study.parentage': { + + date: { + xtype: 'datefield', + extFormat: LABKEY.extDefaultDateFormat, + columnConfig: { + width: 100 + } + } + } + + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/PathologyTissues.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/PathologyTissues.js new file mode 100644 index 000000000..fc671ff3b --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/PathologyTissues.js @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +//Created: 5-5-2017 R.Blasa +EHR.model.DataModelManager.registerMetadata('PathTissues', { + allQueries: { + }, + byQuery: { + 'study.encounters': { + type: { + defaultValue: 'Tissues', + hidden: true + }, + enddate: { + hidden: true + }, + project: { + header: 'Center Project' + }, + + + chargetype: { + hidden: true + }, + procedureid: { + defaultValue: 1082, + hidden: true + }, + + caseno: { + hidden: true + }, + remark: { + hidden: true + } + } + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/Pathology_Notes.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/Pathology_Notes.js index a38f8ef10..33f9df103 100644 --- a/onprc_ehr/resources/web/onprc_ehr/model/sources/Pathology_Notes.js +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/Pathology_Notes.js @@ -30,6 +30,57 @@ EHR.model.DataModelManager.registerMetadata('Necropsy_Notes', { } } }, + //Added: 10-12-2017 R.Blasa + 'ehr.encounter_participants': { + Id: { + hidden: false, + allowBlank: false + }, + userid: { + hidden: true, + columnConfig: { + width: 200 + } + }, + username: { + hidden: false, + allowBlank: false, + columnConfig: { + width: 200 + }, + lookup: { + xtype: 'labkey-combo', + schemaName: 'onprc_ehr', + queryName: 'Reference_StaffNames', + keyColumn: 'username', + displayColumn: 'username', + filterArray: [ + LABKEY.Filter.create('DisableDate', null, LABKEY.Filter.Types.ISBLANK), + LABKEY.Filter.create('Type', 'Necropsy', LABKEY.Filter.Types.EQUAL)], + columns: 'username,FirstName,LastName,Type,DisableDate', + sort: 'username' + + }, + editorConfig: { + anyMatch: true, + listConfig: { + innerTpl: '{[values.username + (values.username ? " (" + values.LastName + (values.FirstName ? ", " + values.FirstName : "") + ")" : "")]}', + getInnerTpl: function(){ + return this.innerTpl; + } + } + } + }, + role: { + allowBlank: false, + columnConfig: { + width: 200 + } + }, + comment: { + hidden: true + } + }, 'onprc_ehr.encounter_summaries_remarks': { Id: { hidden: true diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/ProjectAnimalConditions.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/ProjectAnimalConditions.js index de1eb59fa..7a7ed5a7d 100644 --- a/onprc_ehr/resources/web/onprc_ehr/model/sources/ProjectAnimalConditions.js +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/ProjectAnimalConditions.js @@ -15,34 +15,23 @@ EHR.model.DataModelManager.registerMetadata('ProjectAnimalConditions', { assignCondition: { allowBlank: false, - - columnConfig: { - width: 200 - }, lookup: { filterArray: [ LABKEY.Filter.create('datedisabled', null, LABKEY.Filter.Types.ISBLANK) ] } - } , + } , projectedReleaseCondition: { allowBlank: false, - columnConfig: { - width: 20 - }, lookup: { filterArray: [ LABKEY.Filter.create('datedisabled', null, LABKEY.Filter.Types.ISBLANK) ] } - }, - releaseCondition: { - columnConfig: { - width: 200 - }, + lookup: { filterArray: [ LABKEY.Filter.create('datedisabled', null, LABKEY.Filter.Types.ISBLANK) @@ -50,7 +39,6 @@ EHR.model.DataModelManager.registerMetadata('ProjectAnimalConditions', { } } - } } }); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/ResearchProcedures.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/ResearchProcedures.js new file mode 100644 index 000000000..f25c595dd --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/ResearchProcedures.js @@ -0,0 +1,97 @@ + +//Created: 1-16-2018 R.Blasa + +EHR.model.DataModelManager.registerMetadata('ResearchProcedures', { + allQueries: { + performedby: { + allowBlank: true + } + }, + byQuery: { + 'study.encounters': { + instructions: { + header: 'Special Instructions', + hidden: false + }, + chargetype: { + defaultValue: 'Research Staff', + allowBlank: false + }, + performedby: { + defaultValue: LABKEY.Security.currentUser.displayName + }, + type: { + defaultValue: 'Procedure', + hidden: true + }, + + //Added: 6-21-2019 R.blasa hide Special Instructions + instructions: { + hidden: true + }, + title: { + hidden: true + }, + caseno: { + hidden: true + }, + remark: { + columnConfig: { + width: 400 + } + }, + procedureid: { + lookup: { + filterArray: [ + LABKEY.Filter.create('category', 'Research;Procedure', LABKEY.Filter.Types.EQUALS_ONE_OF), //Modified: 7-23-2019 R.Blasa + LABKEY.Filter.create('active', true, LABKEY.Filter.Types.EQUAL) + ] + } + } + }, + 'study.blood': { + chargetype: { + defaultValue: 'Research Staff', + allowBlank: false + }, + instructions: { + hidden: true + }, + reason: { + defaultValue: 'Research' + } + }, + 'study.drug': { + category: { + defaultValue: 'Research', + editable: false + }, + project: { + allowBlank: false + }, + code: { + editorConfig: { + xtype: 'ehr-snomedcombo', + defaultSubset: 'Drugs and Procedures' + } + }, + chargetype: { + defaultValue: 'Research Staff', + allowBlank: false + } + }, + 'study.treatment_order': { + category: { + defaultValue: 'Research', + editable: false + }, + code: { + editorConfig: { + xtype: 'ehr-snomedcombo', + defaultSubset: 'Drugs and Procedures' + } + } + } + } +}); + diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/StudyDetailsProperties.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/StudyDetailsProperties.js new file mode 100644 index 000000000..654afb48c --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/StudyDetailsProperties.js @@ -0,0 +1,95 @@ + +/** + * User: Kolli + * Date: 02/20/2020 + */ +EHR.model.DataModelManager.registerMetadata('StudyDetails', { + allQueries: { + }, + + byQuery: { + 'study.StudyDetails': { + + Date: { + header:'Start Date', + columnConfig: { + width: 200 + } + }, + + endDate: { + header:'End Date', + columnConfig: { + width: 200 + } + }, + + project: { + allowBlank: true, + columnConfig: { + width: 150 + } + }, + + studyCohort: { + header:"Study Cohort", + columnConfig: { + width: 125 + } + }, + + // studyGroup: { + // header:"Study Group", + // lookup: { + // schemaName: 'study', + // queryName: 'StudyDetails_group_values', + // sort: 'sort_order', + // columns: 'value, name' + // }, + // columnConfig: { + // width: 100 + // } + // }, + + studyGroupNum: { + header:"Study Group #", + lookup: { + schemaName: 'study', + queryName: 'StudyDetails_cohort_values', + sort: 'sort_order', + columns: 'value, name' + }, + columnConfig: { + width: 125 + } + }, + + studyPhase: { + header:"Study Phase", + lookup: { + schemaName: 'study', + queryName: 'StudyDetails_phase_values', + sort: 'sort_order', + columns: 'value, name' + }, + columnConfig: { + width: 100 + } + }, + + remark: { + header:'Remark', + columnConfig: { + width: 200 + } + }, + + performedby: { + defaultValue: LABKEY.Security.currentUser.displayName , + hidden: false + } + + } + + } +}); diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/SurgeryBlood.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/SurgeryBlood.js new file mode 100644 index 000000000..6cfa44050 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/SurgeryBlood.js @@ -0,0 +1,31 @@ + +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +EHR.model.DataModelManager.registerMetadata('Surgery_Blood', { + allQueries: { + + }, + byQuery: { + + 'study.blood': { + + date: { + getInitialValue: function(v){ + return v; + } + } + + }, + 'study.treatment_order': { + + enddate: { + hidden: false, + extFormat: 'Y-m-d 23:59' + } + } + + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/Surgery_Staff.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/Surgery_Staff.js new file mode 100644 index 000000000..a344d8590 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/Surgery_Staff.js @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +//Created: 7-23-2018 R.Blasa +EHR.model.DataModelManager.registerMetadata('Biopsy_Staff', { + + byQuery: { + + 'ehr.encounter_participants': { + Id: { + hidden: false, + allowBlank: false + }, + userid: { + hidden: true, + columnConfig: { + width: 200 + } + }, + username: { + hidden: false, + allowBlank: false, + columnConfig: { + width: 200 + }, + lookup: { + xtype: 'labkey-combo', + schemaName: 'onprc_ehr', + queryName: 'Reference_StaffNames', + keyColumn: 'username', + displayColumn: 'username', + filterArray: [ + LABKEY.Filter.create('DisableDate', null, LABKEY.Filter.Types.ISBLANK), + LABKEY.Filter.create('Type', 'Surgery', LABKEY.Filter.Types.EQUAL)], + columns: 'username,FirstName,LastName,Type,DisableDate,displayname', + sort: 'username' + }, + editorConfig: { + anyMatch: true, + listConfig: { + innerTpl: '{[values.username + (values.username ? " (" + values.LastName + (values.FirstName ? ", " + values.FirstName : "") + ")" : "")]}', + getInnerTpl: function(){ + return this.innerTpl; + } + } + } + }, + role: { + allowBlank: false, + columnConfig: { + width: 200 + } + }, + comment: { + hidden: true + } + } + + + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/TB_TestObservation.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/TB_TestObservation.js new file mode 100644 index 000000000..28a64c120 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/TB_TestObservation.js @@ -0,0 +1,59 @@ + +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +EHR.model.DataModelManager.registerMetadata('TB_TestObservation', { + allQueries: { + + }, + byQuery: { + 'study.clinical_observations': { + category: { + xtype: 'combo', + fieldLabel: 'Category', + defaultValue: 'TB TST Score (72 hr)', + displayField: 'value', + valueField: 'value', + + store: { + type: 'labkey-store', + schemaName: 'sla', + queryName: 'Reference_Data', + filterArray: [LABKEY.Filter.create('enddate', null, LABKEY.Filter.Types.ISBLANK), + LABKEY.Filter.create('columnName', 'TBTestObserveCategory', LABKEY.Filter.Types.EQUAL)], + autoLoad: true, + sort: 'sort_order' + } + + }, + observation: { + allowBlank: false, + xtype: 'onprc_TB_TST_ObservationScores' , + defaultValue: 'Grade: 0', + columnConfig: { + width: 200 + } + }, + + code:{ hidden: true}, + + area: { + xtype: 'combo', + fieldLabel: 'Area', + defaultValue: 'Right Eyelid', + displayField: 'label', + valueField: 'value', + store: { + type: 'labkey-store', + schemaName: 'study', + queryName: 'TBObservationArea', + autoLoad: true, + sort: 'sort_order' + } + } + } + + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/TreatmentDrugsClinical.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/TreatmentDrugsClinical.js new file mode 100644 index 000000000..dbb0138f3 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/TreatmentDrugsClinical.js @@ -0,0 +1,22 @@ + +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +//Created: 10-7-2019 R.Blasa + + EHR.model.DataModelManager.registerMetadata('TreatmentDrugsClinical', { + allQueries: { + + }, + byQuery: { + 'study.drug': { + category: { + allowBlank: false, + shownInGrid: false, + defaultValue: 'Clinical' + } + } + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/model/sources/labworkPanel.js b/onprc_ehr/resources/web/onprc_ehr/model/sources/labworkPanel.js index 3b8da502b..0f3875f2b 100644 --- a/onprc_ehr/resources/web/onprc_ehr/model/sources/labworkPanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/model/sources/labworkPanel.js @@ -10,6 +10,29 @@ EHR.model.DataModelManager.registerMetadata('LabworkPanel', { }, byQuery: { 'study.clinpathRuns': { + servicerequested: { + allowBlank: false, + columnConfig: { + width: 250 + }, + lookup: { + xtype: 'labkey-combo', + schemaName: 'onprc_ehr', + queryName: 'labServiceRequest_Active', + keyColumn: 'servicename', + columns: '*', + sort: 'chargetype,servicename,outsidelab' + }, + editorConfig: { + anyMatch: true, + listConfig: { + innerTpl: '{[(values.chargetype ? "" + values.chargetype + ": " : "") + values.servicename + (values.outsidelab ? "*" : "")]}', + getInnerTpl: function () { + return this.innerTpl; + } + } + } + }, performedby: { defaultValue: LABKEY.Security.currentUser.displayName , diff --git a/onprc_ehr/resources/web/onprc_ehr/onprcOverrides.js b/onprc_ehr/resources/web/onprc_ehr/onprcOverrides.js new file mode 100644 index 000000000..a6f35263e --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/onprcOverrides.js @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2015-2016 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +Ext4.namespace('ONPRC_EHR'); + +/** Override to never sort the IDs */ +LDK.Utils.splitIds = function(subjects, unsorted) { + subjects = Ext4.String.trim(subjects); + subjects = subjects.replace(/[\s,;]+/g, ';'); + subjects = subjects.replace(/(^;|;$)/g, ''); + subjects = subjects.toLowerCase(); + + if (subjects){ + subjects = subjects.split(';'); + } + else { + subjects = []; + } + + return Ext4.unique(subjects); +}; diff --git a/onprc_ehr/resources/web/onprc_ehr/onprcReports.js b/onprc_ehr/resources/web/onprc_ehr/onprcReports.js index d0b571d32..533b9a56f 100644 --- a/onprc_ehr/resources/web/onprc_ehr/onprcReports.js +++ b/onprc_ehr/resources/web/onprc_ehr/onprcReports.js @@ -152,6 +152,63 @@ EHR.reports.iStat = function(panel, tab){ }); } +//Added: 6-27-2019 R.Blasa +EHR.reports.TBTest = function(panel, tab){ + var filterArray = panel.getFilterArray(tab); + var title = panel.getTitleSuffix(); + + var target = tab.add({tag: 'span', style: 'padding-bottom: 20px'}); + tab.doLayout(); + + var config = panel.getQWPConfig({ + schemaName: 'study', + queryName: 'TBTestEnounters', + title: "TB Test Dates " + title, + titleField: 'Id', + filters: filterArray.nonRemovable, + removeableFilters: filterArray.removable, + sort: '-date' + }); + + tab.add({ + xtype: 'ldk-querypanel', + style: 'margin-bottom:20px;', + queryConfig: config + }); + + var miscConfig = panel.getQWPConfig({ + schemaName: 'study', + queryName: 'TBObservationsReport', + title: 'TB TST Scores' + title, + titleField: 'Id', + sort: '-date', + filters: filterArray.nonRemovable, + removeableFilters: filterArray.removable + }); + + tab.add({ + xtype: 'ldk-querypanel', + style: 'margin-bottom:20px;', + queryConfig: miscConfig + }); + + var resultsConfig = panel.getQWPConfig({ + schemaName: 'study', + queryName: 'TBTestSerologyLabResults', + title: 'TB Serology Results' + title, + titleField: 'Id', + sort: '-date', + filters: filterArray.nonRemovable, + removeableFilters: filterArray.removable + + }); + + tab.add({ + xtype: 'ldk-querypanel', + style: 'margin-bottom:20px;', + queryConfig: resultsConfig + }); +} EHR.reports.clinMedicationSchedule = function(panel, tab){ @@ -193,6 +250,8 @@ EHR.reports.currentBlood = function(panel, tab){ if (subjects.length < 2) { for (var i = 0; i < subjects.length; i++) + + { var str = subjects[i]; var filterArray = panel.getFilterArray(tab); @@ -245,10 +304,10 @@ EHR.reports.currentBlood = function(panel, tab){ title: 'Overview' + title, schemaName: 'study', queryName: 'demographicsBloodSummary',//'demographicsBloodSummary', - // viewName: 'NewBloodCalc', - filterArray: filterArray.removable.concat(filterArray.nonRemovable) - } - }); + // viewName: 'NewBloodCalc', + filterArray: filterArray.removable.concat(filterArray.nonRemovable) + } + }); } if (toAdd.length) @@ -347,11 +406,11 @@ EHR.reports.potentialParents = function(panel, tab){ style: 'padding-bottom: 20px;', bodyStyle: 'padding: 5px;', html: 'This report calculates potential parents for the selected animal(s). The potential parents are determined as follows:' + - '

' + - '
    ' + - '
  • Potential dams are determined by finding any female housed in the animal\'s birth location at the time of birth, which were at least 2.5 years old at the time. Note: this report considers housing in whole-day increments in order to avoid missing potential parents due to errors in the timestamp of transfers.
  • ' + - '
  • Potential sires are determined by finding the locations where all potential dams were housed during the conception window (defined below) relative to the animal\'s birth. The potential sires are any male animals housed in these locations during the conception window, which are at least 2.5 years old at the time.
  • ' + - '
' + '

' + + '
    ' + + '
  • Potential dams are determined by finding any female housed in the animal\'s birth location at the time of birth, which were at least 2.5 years old at the time. Note: this report considers housing in whole-day increments in order to avoid missing potential parents due to errors in the timestamp of transfers.
  • ' + + '
  • Potential sires are determined by finding the locations where all potential dams were housed during the conception window (defined below) relative to the animal\'s birth. The potential sires are any male animals housed in these locations during the conception window, which are at least 2.5 years old at the time.
  • ' + + '
' }); tab.add({ @@ -373,8 +432,8 @@ EHR.reports.potentialParents = function(panel, tab){ border: false }, items: [{ - html: 'Choose Conception Range (Days Prior To Birth):', - style: 'padding-bottom: 10px;' + html: 'Choose Conception Range (Days Prior To Birth):', + style: 'padding-bottom: 10px;' },{ xtype: 'numberfield', hideTrigger: true, @@ -761,12 +820,12 @@ EHR.reports.onprcSnapshot = function(panel, tab){ var idcolor = false; if (str.substr(0,2)== 'gp' || str.substr(0,3)== 'rbr') { - idcolor = true; + idcolor = true; } toAdd.push({ xtype: 'ldk-webpartpanel', //title: 'Overview: ' + subjects[i], //Added 4-12-2016 Blasa - // title: 'Overview: ' + '' + subjects[i]+ '', + // title: 'Overview: ' + '' + subjects[i]+ '', //Added 4-12-2016 Blasa title: idcolor?'Overview: ' + '' + subjects[i]+ '':'Overview: ' + subjects[i], @@ -970,4 +1029,108 @@ EHR.reports.surgeryCasesClosedToday = function(panel, tab){ removeableFilters: filterArray.removable }) }); -}; \ No newline at end of file +} + +//Modified 4-1-2016 R.Blasa +EHR.reports.onprcweightGraph = function(panel, tab){ + if (tab.filters.subjects){ + renderSubjects(tab.filters.subjects, tab); + } + else + { + panel.resolveSubjectsFromHousing(tab, renderSubjects, this); + } + + function renderSubjects(subjects, tab) + { + if (!subjects.length) + { + tab.add({ + html: 'No animals were found.', + border: false + }); + + return; + } + + var toAdd = []; + + toAdd.push({ + html: 'Note: Please click the animal ID to open the graphical representation of the same report. Choose a different tab, to display the animal\'s weight record in more detail.', + style: 'padding-bottom: 20px;', + border: false + }); + var filterArray = panel.getFilterArray(tab); + var title = panel.getTitleSuffix(); + toAdd.push({ + xtype: 'ldk-querypanel', + style: 'margin-bottom:20px;', + queryConfig: { + title: 'Weights' , + schemaName: 'study', + queryName: 'demographics', + viewName: 'Snapshot', + filterArray: filterArray.removable.concat(filterArray.nonRemovable) + } + }); + + if (toAdd.length) + tab.add(toAdd); + + } +}; + +EHR.reports.kinshipSummary = function(panel, tab){ + var filterArray = panel.getFilterArray(tab); + var title = panel.getTitleSuffix(); + var ids = tab.filters.subjects; + + tab.add({ + xtype: 'panel', + border: false, + subjectList: ids, + bodyStyle: 'padding: 5px;', + defaults: { + border: false + }, + items: [{ + xtype: 'ldk-linkbutton', + hidden: !ids || !ids.length, + text: 'Click Here To Limit To Animals In Selection', + linkTarget: '_blank', + linkCls: 'labkey-text-link', + style: 'margin-bottom: 20px;', + handler: function(btn){ + var p = btn.up('panel'); + if (p.subjectList) { + var qwp = p.down('ldk-querypanel').qwp; + if (qwp) { + qwp.removeableFilters = qwp.removeableFilters || []; + qwp.removeableFilters.push(LABKEY.Filter.create('Id2', p.subjectList.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)); + + var dr = LABKEY.DataRegions[qwp.dataRegionName]; + if (dr){ + dr.addFilter(LABKEY.Filter.create('Id2', p.subjectList.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)); + // dr.refresh(); Modidifed: 5-23-2019 R.Blasa Prevent from refreshing grid reports. + } + } + } + } + },{ + xtype: 'container', + border: false, + items: [{ + xtype: 'ldk-querypanel', + style: 'margin-bottom:20px;', + queryConfig: panel.getQWPConfig({ + schemaName: 'ehr', + queryName: 'kinshipSummary', + title: 'Kinship' + title, + filters: filterArray.nonRemovable, + removeableFilters: filterArray.removable || [] + }) + }] + }] + }); + +} \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/AddScheduledTreatmentPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/AddScheduledTreatmentPanel.js index 2df5758fc..08663bc16 100644 --- a/onprc_ehr/resources/web/onprc_ehr/panel/AddScheduledTreatmentPanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/panel/AddScheduledTreatmentPanel.js @@ -58,6 +58,7 @@ Ext4.define('onprc_ehr.panel.AddScheduledTreatmentPanel', { data: [ ['800', '8:00 AM'], ['1200', '12:00 Noon'], + ['1400', '2:00 PM'], ['1600', '4:00 PM'], ['2000', '8:00 PM'] ] diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/AnimalDetailsCasePanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/AnimalDetailsCasePanel.js index 4d17e285c..d0b42a561 100644 --- a/onprc_ehr/resources/web/onprc_ehr/panel/AnimalDetailsCasePanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/panel/AnimalDetailsCasePanel.js @@ -169,7 +169,7 @@ Ext4.define('onprc_ehr.panel.AnimalDetailsCasePanel', { hidden: EHR.Security.hasClinicalEntryPermission() && !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'update', [{schemaName: 'study', queryName: 'Treatment Orders'}]), handler: function(){ if (this.subjectId){ - Ext4.create('EHR.window.ManageTreatmentsWindow', {animalId: this.subjectId}).show(); + Ext4.create('onprc_ehr.window.ManageTreatmentsWindow', {animalId: this.subjectId}).show(); } else { console.log('no id'); diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/AnimalDetailsPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/AnimalDetailsPanel.js new file mode 100644 index 000000000..7d350807e --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/panel/AnimalDetailsPanel.js @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2013-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + * + * @param subjectId + */ +Ext4.define('ONPC_EHR.panel.AnimalDetailsPanel', { + extend: 'onprc_ehr.panel.SnapshotPanel', + alias: 'widget.onprc_ehr-animaldetailspanels', + + border: true, + showExtendedInformation: false, + showActionsButton: false, + doSuspendLayouts: false, + showDisableButton: true, + + initComponent: function(){ + Ext4.apply(this, { + border: true, + bodyStyle: 'padding: 5px;', + minHeight: 285, + defaults: { + border: false + } + }); + + this.callParent(arguments); + + if (this.dataEntryPanel){ + this.mon(this.dataEntryPanel, 'animalchange', this.onAnimalChange, this, {buffer: 500}); + } + + this.mon(EHR.DemographicsCache, 'cachechange', this.demographicsListener, this); + }, + + demographicsListener: function(animalId){ + if (this.isDestroyed){ + console.log('is destroyed'); + return; + } + + if (animalId == this.subjectId){ + this.loadAnimal(animalId, true); + } + }, + + onAnimalChange: function(animalId){ + //the intent of this is to avoid querying partial strings as the user types + if (animalId && animalId.length < 4){ + animalId = null; + } + + this.loadAnimal(animalId); + }, + + loadAnimal: function(animalId, forceReload){ + if (!forceReload && animalId == this.subjectId){ + return; + } + + this.subjectId = animalId; + + if (animalId) + EHR.DemographicsCache.getDemographics([this.subjectId], this.onLoad, this, (forceReload ? 0 : -1)); + else + this.getForm().reset(); + }, + + onLoad: function(ids, resultMap){ + if (ids && ids.length && ids[0] != this.subjectId){ + return; + } + + this.callParent(arguments); + }, + + getItems: function(){ + return [{ + itemId: 'columnSection', + layout: 'column', + defaults: { + border: false, + bodyStyle: 'padding-right: 20px;' + }, + items: [{ + xtype: 'container', + width: 380, + defaults: { + xtype: 'displayfield', + labelWidth: this.defaultLabelWidth + }, + items: [{ + fieldLabel: 'Id', + name: 'animalId' + },{ + fieldLabel: 'Location', + name: 'location' + },{ + fieldLabel: 'Last Recorded Location', //Added: 12-19-2018 R.Blasa + name: 'lastlocation' + },{ + fieldLabel: 'Gender', + name: 'gender' + },{ + fieldLabel: 'Species', + name: 'species' + },{ + fieldLabel: 'Age', + name: 'age' + },{ + xtype: 'displayfield', + fieldLabel: 'Source', + name: 'source' + },{ + fieldLabel: 'Projects / Groups', + name: 'assignmentsAndGroups' + }] + },{ + xtype: 'container', + width: 350, + defaults: { + xtype: 'displayfield' + }, + items: [{ + fieldLabel: 'Status', + name: 'calculated_status' + },{ + fieldLabel: 'Flags', + name: 'flags' + },{ + fieldLabel: 'Weight', + name: 'weights' + },{ + xtype: 'ldk-linkbutton', + style: 'margin-top: 10px;', + scope: this, + text: '[Show Full Hx]', + handler: function(){ + if (this.subjectId){ + EHR.window.ClinicalHistoryWindow.showClinicalHistory(null, this.subjectId, null); + } + else { + console.log('no id'); + } + } + },{ + xtype: 'ldk-linkbutton', + style: 'margin-top: 5px;', + scope: this, + text: '[Show Recent SOAPs]', + handler: function(){ + if (this.subjectId){ + EHR.window.RecentRemarksWindow.showRecentRemarks(this.subjectId); + } + else { + console.log('no id'); + } + } + },{ + xtype: 'ldk-linkbutton', + style: 'margin-top: 5px;', + scope: this, + text: '[Manage Treatments]', + hidden: EHR.Security.hasClinicalEntryPermission() && !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'update', [{schemaName: 'study', queryName: 'Treatment Orders'}]), + handler: function(){ + if (this.subjectId){ + Ext4.create('EHR.window.ManageTreatmentsWindow', {animalId: this.subjectId}).show(); + } + else { + console.log('no id'); + } + } + },{ + xtype: 'ldk-linkbutton', + style: 'margin-top: 5px;margin-bottom:10px;', + scope: this, + text: '[Manage Cases]', + hidden: EHR.Security.hasClinicalEntryPermission() && !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'update', [{schemaName: 'study', queryName: 'Cases'}]), + handler: function(){ + if (this.subjectId){ + Ext4.create('EHR.window.ManageCasesWindow', {animalId: this.subjectId}).show(); + } + else { + console.log('no id'); + } + } + }] + }] + },{ + layout: 'hbox', + style: 'padding-top: 10px;', + items: [{ + xtype: 'button', + border: true, + text: 'Reload', + scope: this, + handler: function(btn){ + this.loadAnimal(this.subjectId, true); + } + },{ + xtype: 'button', + hidden: !this.showDisableButton, + border: true, + text: 'Disable', + style: 'margin-left: 10px;', + scope: this, + handler: function(btn){ + this.disableAnimalLoad = btn.getText() == 'Disable'; + + btn.setText(this.disableAnimalLoad ? 'Enable' : 'Disable'); + this.down('#columnSection').setDisabled(this.disableAnimalLoad); + } + }] + }]; + }, + + appendWeightResults: function(toSet, results){ + var text; + if (results && results.length){ + var row = results[0]; + var date = LDK.ConvertUtils.parseDate(row.date); + var interval = ''; + if (date){ + //round to day for purpose of this comparison + var d1 = Ext4.Date.clearTime(new Date(), true); + var d2 = Ext4.Date.clearTime(date, true); + interval = Ext4.Date.getElapsed(d1, d2); + interval = interval / (1000 * 60 * 60 * 24); + interval = Math.floor(interval); + interval = interval + ' days ago'; + } + + text = row.weight + ' kg, ' + date.format(LABKEY.extDefaultDateFormat) + (!Ext4.isEmpty(interval) ? ' (' + interval + ')' : ''); + } + + toSet['weights'] = text; + }, + + appendAssignmentsAndGroups: function(toSet, record){ + toSet['assignmentsAndGroups'] = null; + + if (this.redacted) + return; + + var values = []; + if (record.getActiveAssignments() && record.getActiveAssignments().length){ + Ext4.each(record.getActiveAssignments(), function(row){ + var val = row['project/investigatorId/lastName'] || ''; + val += ' [' + row['project/displayName'] + ']'; + + if (val) + values.push(val); + }, this); + } + + if (record.getActiveAnimalGroups() && record.getActiveAnimalGroups().length){ + Ext4.each(record.getActiveAnimalGroups(), function(row){ + values.push(row['groupId/name']); + }, this); + } + + toSet['assignmentsAndGroups'] = values.length ? values.join('
') : null; + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/ArrivalDataEntryPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/ArrivalDataEntryPanel.js new file mode 100644 index 000000000..b014c8897 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/panel/ArrivalDataEntryPanel.js @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2014-2015 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +//Created: 8-6-2019 R.Blasa +Ext4.define('ONPRC_EHR.panel.ArrivalDataEntryPanel', { + extend: 'EHR.panel.TaskDataEntryPanel', + alias: 'widget.onprc-arrivaldataentrypanel', + + onStoreCollectionCommitComplete: function(sc, extraContext){ + if (Ext4.Msg.isVisible()) + Ext4.Msg.hide(); + + //Modified 6-5-2015 Blasa Note: provided a process to evaluate contents of store + // var store = sc.getClientStoreByName('housing'); + var store = sc.getClientStoreByName('arrival'); + LDK.Assert.assertNotEmpty('Unable to find housing store in HousingDataEntryPanel', store); + + if (extraContext && extraContext.successURL && store.getCount() > 0){ + Ext4.Msg.confirm('Success', 'Do you want to view the room layout now? This will allow you to verify and/or change dividers', function(val){ + window.onbeforeunload = Ext4.emptyFn; + if (val == 'yes'){ + + var rooms = []; + store.each(function(r){ + if (r.get('initialRoom') && rooms.indexOf(r.get('initialRoom')) == -1){ + rooms.push(r.get('initialRoom')); + } + }, this); + + window.location = LABKEY.ActionURL.buildURL('onprc_ehr', 'printRoom', null, {rooms: rooms}); + } + else { + window.location = extraContext.successURL; + } + }, this); + + return; + } + + this.callParent(arguments); + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/BloodSummaryPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/BloodSummaryPanel.js index 7b841e406..a200dcc60 100644 --- a/onprc_ehr/resources/web/onprc_ehr/panel/BloodSummaryPanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/panel/BloodSummaryPanel.js @@ -18,9 +18,9 @@ Ext4.define('ONPRC.panel.BloodSummaryPanel', { defaults: { border: false }, - items: [{ + /* items: [{ html: 'Loading...' - }] + }]*/ }); this.callParent(); @@ -37,7 +37,7 @@ Ext4.define('ONPRC.panel.BloodSummaryPanel', { // viewName: 'newBloodCalc', filterArray: [LABKEY.Filter.create('id', this.subjects.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)], // columns: 'id,species,species/blood_per_kg,species/max_draw_pct,species/blood_draw_interval,id/MostRecentWeight/mostRecentWeight,id/MostRecentWeight/mostRecentWeightDate,Id/demographics/calculated_status', - columns: 'id,Species,Gender,MostRecentBCS,BCSDate,mostRecentWeight,mostRecentWeightDate,blood_draw_interval,bloodPrevious,bloodFuture,blood_per_kg,FixedRateCalculation,TotalBloodVolume,AllowableBlood,AvailableBlood,Method,Id/demographics/calculated_status', + columns: 'id,Species,species/blood_per_kg,species/max_draw_pct,species/blood_draw_interval,Gender,MostRecentBCS,BCSDate,weight,MostRecentWeightDate,blood_draw_interval,bloodPrevious,bloodFuture,blood_per_kg,FixedRateCalculation,TotalBloodVolume,AllowableBlood,AvailableBlood,Method,Id/demographics/calculated_status', requiredVersion: 9.1, sort: 'id', @@ -128,7 +128,7 @@ Ext4.define('ONPRC.panel.BloodSummaryPanel', { }); if (!bds || !bds.length) { - var maxDraw = dd.getValue('species/blood_per_kg') * dd.getValue('species/max_draw_pct') * dd.getValue('id/MostRecentWeight/mostRecentWeight'); + var maxDraw = dd.getValue('totalAllowable'); cfg.items.push({ html: 'There are no previous or future blood draws with the relevant timeframe. The maximum amount of ' + Ext4.util.Format.round(maxDraw, 2) + ' mL can be drawn.', border: false @@ -164,6 +164,8 @@ Ext4.define('ONPRC.panel.BloodSummaryPanel', { }; //this assumes we sorted on date + + var newRows = []; var rowPrevious; var seriesIds = []; @@ -207,15 +209,57 @@ Ext4.define('ONPRC.panel.BloodSummaryPanel', { if (currentRow){ toAdd.push({ - html: 'The amount of blood available if drawn today is: ' + Ext4.util.Format.round(currentRow.allowableDisplay.value, 1) + ' mL. The graph below shows how the amount of blood available will change over time, including when previous draws will drop off.
', + html: 'The amount of blood available if drawn today is: ' + Ext4.util.Format.round(currentRow.allowableDisplay.value, 1) + ' mL.
', border: false, style: 'margin-bottom: 20px' }); } + toAdd.push({ + html: '', + border: false, + style: 'margin-bottom: 10px;' + }); + + toAdd.push({ + xtype: 'ldk-querypanel', + style: 'margin-bottom: 10px;', + queryConfig: LDK.Utils.getReadOnlyQWPConfig({ + title: 'Recent/Scheduled Blood Draws: ' + subject, + schemaName: 'study', + queryName: 'bloodDrawsByDay', + allowHeaderLock: false, + //frame: 'none', + filters: [ + LABKEY.Filter.create('Id', subject, LABKEY.Filter.Types.EQUAL), + //THis filter is looking to identify values from bloodDraws by Day and attempts to get the species value, it makes better sense to only filter for the animal + //ID and do the other calcs in the actual query + LABKEY.Filter.create('date', '-' + (dd.getValue('species/blood_draw_interval') * 2 ) + 'd', LABKEY.Filter.Types.DATE_GREATER_THAN_OR_EQUAL) + ] + + }) + }); + + toAdd.push({ + xtype: 'ldk-querypanel', + style: 'margin-bottom: 10px;', + queryConfig: LDK.Utils.getReadOnlyQWPConfig({ + title: 'Pending/Not-Yet-Approved Blood Draws: ' + subject, + schemaName: 'study', + queryName: 'blood', + allowHeaderLock: false, + //frame: 'none', + filters: [ + LABKEY.Filter.create('Id', subject, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('qcState','Completed' , LABKEY.Filter.Types.NOT_EQUAL) + ], + sort: '-date' + }) + }); +/*toAdd.push({ xtype: 'container', - //title: 'Available Blood: ' + subject, + title: 'Available Blood: ' + subject, items: [{ xtype: 'ldk-graphpanel', margin: '0 0 0 0', @@ -293,47 +337,7 @@ Ext4.define('ONPRC.panel.BloodSummaryPanel', { }, this); } }] - }); - - toAdd.push({ - html: '', - border: false, - style: 'margin-bottom: 10px;' - }); - - toAdd.push({ - xtype: 'ldk-querypanel', - style: 'margin-bottom: 10px;', - queryConfig: LDK.Utils.getReadOnlyQWPConfig({ - title: 'Recent/Scheduled Blood Draws: ' + subject, - schemaName: 'study', - queryName: 'bloodDrawsByDay', - allowHeaderLock: false, - //frame: 'none', - filters: [ - LABKEY.Filter.create('Id', subject, LABKEY.Filter.Types.EQUAL), - LABKEY.Filter.create('date', '-' + (dd.getValue('species/blood_draw_interval') * 2) + 'd', LABKEY.Filter.Types.DATE_GREATER_THAN_OR_EQUAL) - ], - sort: '-date' - }) - }); - - toAdd.push({ - xtype: 'ldk-querypanel', - style: 'margin-bottom: 10px;', - queryConfig: LDK.Utils.getReadOnlyQWPConfig({ - title: 'Pending/Not-Yet-Approved Blood Draws: ' + subject, - schemaName: 'study', - queryName: 'blood', - allowHeaderLock: false, - //frame: 'none', - filters: [ - LABKEY.Filter.create('Id', subject, LABKEY.Filter.Types.EQUAL), - LABKEY.Filter.create('countsAgainstVolume', false, LABKEY.Filter.Types.EQUAL) - ], - sort: '-date' - }) - }); + });*/ toAdd.push({ html: '', diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/EnterDataPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/EnterDataPanel.js new file mode 100644 index 000000000..1afd6bb3c --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/panel/EnterDataPanel.js @@ -0,0 +1,553 @@ + +//Created: 12-13-2016 R.Blasa +//Modified: 7-17-2017 R.Blasa + +Ext4.define('onprc_ehr.panel.EnterDataPanel', { + extend: 'LABKEY.ext4.BootstrapTabPanel', + autoHeight: true, + layout: 'anchor', + + initComponent: function(){ + Ext4.apply(this, { + items: this.getItems() + }); + + this.loadData(); + + this.callParent(); + }, + + loadData: function(){ + EHR.Utils.getDataEntryItems({ + includeFormElements: false, + scope: this, + success: this.onLoad + }); + }, + + onLoad: function(results){ + var formMap = {}; + Ext4.each(results.forms, function(form){ + if (form.isAvailable && form.isVisible && form.canInsert){ + formMap[form.category] = formMap[form.category] || []; + formMap[form.category].push({ + name: form.label, + url: LABKEY.ActionURL.buildURL('ehr', 'dataEntryForm', null, {formType: form.name}) + }); + } + }, this); + + var sectionNames = Ext4.Object.getKeys(formMap); + sectionNames = sectionNames.sort(); + + var sections = []; + Ext4.Array.forEach(sectionNames, function(section){ + var items = formMap[section]; + items = LDK.Utils.sortByProperty(items, 'name', false); + sections.push({ + header: section, + items: items + }); + }, this); + + var tab = Ext4.ComponentQuery.query("#enterNew")[0]; + tab.removeAll(); + tab.add({ + xtype: 'ldk-navpanel', + sections: sections + }); + }, + + onSuccessResize: function (dr){ + var width1 = Ext4.get(dr.domId).getSize().width + 50; + var width2 = Ext4.get(this.id).getSize().width; + + if(width1 > width2){ + console.log(width1+'/'+width2) + this.setWidth(width1); + console.log('resizing') + } + else { + this.setWidth('100%'); + } + }, + + + getItems: function(){ + return [ + { + title: 'Enter New Data', + ref: 'EnterNewData', + items: [{ + xtype: 'panel', + bodyStyle: 'margin: 5px; padding-top: 10px;', + itemId: 'enterNew', + id: 'enterNew', + defaults: { + border: false + }, + items: [{ + html: 'Loading...' + }] + }] + }, + { + title: 'My Tasks', + bodyStyle: 'padding-top: 10px;', + ref: 'MyTasks', + items: [{ + itemId: 'MyTasks', + xtype: 'ldk-querycmp', + cls: 'my-tasks-marker', + queryConfig: { + schemaName: 'onprc_ehr', + queryName: 'my_tasks', + viewName: 'Active Tasks', + scope: this, + success: this.onSuccessResize + } + }] + },{ + title: 'All Tasks', + ref: 'AllTasks', + bodyStyle: 'padding-top: 10px;', + items: [{ + itemId: 'AllTasks', + xtype: 'ldk-querycmp', + cls: 'all-tasks-marker', + queryConfig: { + schemaName: 'ehr', + queryName: 'tasks', + viewName: 'Active Tasks', + scope: this, + success: this.onSuccessResize + } + }] + },{ + title: 'Queues', + bodyStyle: 'margin: 5px;', + items: [{ + xtype: 'ldk-navpanel', + sections: [{ + header: 'Reports', + renderer: function (item) { + return item; + }, + items: [{ + xtype: 'ldk-linkbutton', + text: 'Service Request Summary', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('ldk', 'runNotification', null, {key: 'org.labkey.onprc_ehr.notification.RequestAdminNotification'}) + }] + },{ + //header: 'Blood Draw Requests', + header: 'ASB Service Requests', + renderer: function(item){ + return { + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: item.name + ':', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Unapproved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Blood Draws', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Approved Requests', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Blood Draws', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Scheduled Today', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Blood Draws', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + }] + } + }, + items: [{ + name: 'Blood Draw Request', //Modified: 1-7-2017 R.Blasa restored back as ASB Services + chargeType: 'DCM: ASB Services' +// },{ +// name: 'Clinical Services', +// chargeType: 'DCM: Clinical Services' +// },{ +// name: 'Colony Services', +// chargeType: 'DCM: Colony Services' +// },{ +// name: 'Surgery Services', +// chargeType: 'DCM: Surgery' + }] + },{ + //Modified: 7-27-2017 R.Blasa Removed + ////header: 'Treatment Requests', + //renderer: function(item){ + // return { + // layout: 'hbox', + // bodyStyle: 'padding: 2px;background-color: transparent;', + // defaults: { + // border: false + // }, + // items: [{ + // html: item.name + ':', + // width: 200 + // },{ + // xtype: 'ldk-linkbutton', + // text: 'Unapproved Requests', + // linkCls: 'labkey-text-link', + // href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Treatment Orders', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + // },{ + // xtype: 'ldk-linkbutton', + // text: 'Approved Requests', + // linkCls: 'labkey-text-link', + // style: 'padding-left: 5px;', + // href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Treatment Orders', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + // },{ + // xtype: 'ldk-linkbutton', + // text: 'Scheduled Today', + // linkCls: 'labkey-text-link', + // style: 'padding-left: 5px;', + // href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Treatment Orders', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + // }] + // } + //}, + //items: [{ + // //name: 'ASB Services', + // name: 'Treatment Orders Request', + // chargeType: 'DCM: ASB Services' + // + //}] + //},{ + //header: 'Treatment Requests', + renderer: function(item){ + return { + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: item.name + ':', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Unapproved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Drug Administration', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Approved Requests', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Drug Administration', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Scheduled Today', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Drug Administration', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + }] + } + }, + items: [{ + //name: 'ASB Services', + name: 'Treatment Given Request', + chargeType: 'DCM: ASB Services' + + }] + },{ + //header: 'Procedure Requests', + renderer: function(item){ + return { + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: item.name + ':', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Unapproved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'encounters', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Approved Requests', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'encounters', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Scheduled Today', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'encounters', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + }] + } + }, + items: [{ + //name: 'ASB Services', + name: 'Procedure Request', + chargeType: 'DCM: ASB Services' + + }] + },{ + //header: 'Blood Draw Requests', + header: 'Colony Service Requests', + renderer: function(item){ + return { + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: item.name + ':', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Unapproved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Blood Draws', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Approved Requests', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Blood Draws', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Scheduled Today', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Blood Draws', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + }] + } + }, + items: [{ + name: 'Blood Draw Request', //Modified: 1-7-2017 R.Blasa restored back as ASB Services + chargeType: 'DCM: Colony Services' + + }] + },{ + //Modified: 7-27-2017 R.Blasa not needed + ////header: 'Treatment Requests', + //renderer: function(item){ + // return { + // layout: 'hbox', + // bodyStyle: 'padding: 2px;background-color: transparent;', + // defaults: { + // border: false + // }, + // items: [{ + // html: item.name + ':', + // width: 200 + // },{ + // xtype: 'ldk-linkbutton', + // text: 'Unapproved Requests', + // linkCls: 'labkey-text-link', + // href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Treatment Orders', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + // },{ + // xtype: 'ldk-linkbutton', + // text: 'Approved Requests', + // linkCls: 'labkey-text-link', + // style: 'padding-left: 5px;', + // href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Treatment Orders', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + // },{ + // xtype: 'ldk-linkbutton', + // text: 'Scheduled Today', + // linkCls: 'labkey-text-link', + // style: 'padding-left: 5px;', + // href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Treatment Orders', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + // }] + // } + //}, + //items: [{ + // //name: 'ASB Services', + // name: 'Treatment Orders Request', + // chargeType: 'DCM: Colony Services' + // + //}] + + //},{ + + //header: 'Treatment Requests', + renderer: function(item){ + return { + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: item.name + ':', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Unapproved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Drug Administration', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Approved Requests', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Drug Administration', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Scheduled Today', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Drug Administration', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + }] + } + }, + items: [{ + //name: 'ASB Services', + name: 'Treatment Given Request', + chargeType: 'DCM: Colony Services' + + }] + + },{ + //header: 'Procedure Requests', + renderer: function(item){ + return { + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: item.name + ':', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Unapproved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'encounters', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Pending', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Approved Requests', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'encounters', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType}) + },{ + xtype: 'ldk-linkbutton', + text: 'Scheduled Today', + linkCls: 'labkey-text-link', + style: 'padding-left: 5px;', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'encounters', 'query.viewName': 'Requests', 'query.QCState/Label~eq': 'Request: Approved', 'query.chargetype~eq': item.chargeType, 'query.date~dateeq': (new Date()).format('Y-m-d')}) + }] + } + }, + items: [{ + //name: 'ASB Services', + name: 'Procedure Request', + chargeType: 'DCM: Colony Services' + + }] + },{ + header: 'Lab Tests', + renderer: function(item){ + return item; + }, + items: [{ + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: 'Clinpath:', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Requests With Manual Results', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Clinpath Runs', 'query.viewName': 'Requests', 'query.QCState/Label~startswith': 'Request:', 'query.servicerequested/chargetype~eq': 'Clinpath', 'query.mergeSyncInfo/automaticresults~eq': false}) + },{ + xtype: 'ldk-linkbutton', + text: 'Requests With Automatic Results', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Clinpath Runs', 'query.viewName': 'Requests', 'query.QCState/Label~startswith': 'Request:', 'query.servicerequested/chargetype~eq': 'Clinpath', 'query.mergeSyncInfo/automaticresults~eq': true}) + }] + },{ + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: 'SPF Surveillance:', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'All Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, {schemaName: 'study', 'query.queryName': 'Clinpath Runs', 'query.QCState/Label~startswith': 'Request:', 'query.servicerequested/chargetype~eq': 'SPF Surveillance Lab'}) + }] + }] + + },{ + header: 'Transfer Requests', + renderer: function(item){ + return { + layout: 'hbox', + bodyStyle: 'padding: 2px;background-color: transparent;', + defaults: { + border: false + }, + items: [{ + html: item.name + ':', + width: 200 + },{ + xtype: 'ldk-linkbutton', + text: 'Unapproved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, Ext4.apply({schemaName: 'onprc_ehr', 'query.queryName': 'housing_transfer_requests', 'query.viewName': 'Unapproved Requests'}, item.areaFilter)) + },{ + xtype: 'ldk-linkbutton', + text: 'Approved Requests', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, Ext4.apply({schemaName: 'onprc_ehr', 'query.queryName': 'housing_transfer_requests', 'query.viewName': 'Approved Requests'}, item.areaFilter)) + },{ + xtype: 'ldk-linkbutton', + text: 'Transfers Today', + linkCls: 'labkey-text-link', + href: LABKEY.ActionURL.buildURL('query', 'executeQuery', null, Ext4.apply({schemaName: 'onprc_ehr', 'query.queryName': 'housing_transfer_requests', 'query.viewName': 'Approved Requests', 'query.date~dateeq': (new Date()).format('Y-m-d')}, item.areaFilter)) + }] + } + }, + items: [{ + name: 'Corral', + chargeType: 'DCM: Colony Services', + areaFilter: { + 'query.room/area~eq': 'Corral' + } + },{ + name: 'PENS/Shelters', + chargeType: 'DCM: ASB Services', + areaFilter: { + 'query.room/area~in': 'PENS;Shelters' + } + },{ + name: 'All Other', + areaFilter: { + 'query.room/area~notin': 'Corral;PENS;Shelters' + } + }] + }] + }] + }] + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/LockAnimalsPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/LockAnimalsPanel.js index 58132adf7..3541dd8ac 100644 --- a/onprc_ehr/resources/web/onprc_ehr/panel/LockAnimalsPanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/panel/LockAnimalsPanel.js @@ -115,6 +115,9 @@ Ext4.define('ONPRC_EHR.panel.LockAnimalsPanel', { togglePanel: function(locked){ var btn = this.down('#lockBtn'); + //btn.setText(locked ? 'Unlock Entry' : 'Lock Entry'); + btn.setText(locked ? 'Exit data entry' : 'Enable the form for data entry'); + btn.locked = !locked; var up = this.dataEntryPanel.getUpperPanel(); diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/ManageCasesPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/ManageCasesPanel.js new file mode 100644 index 000000000..d7a0b837d --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/panel/ManageCasesPanel.js @@ -0,0 +1,1074 @@ +/* + * Copyright (c) 2013-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * @cfg {String} animalId + */ + +//Created: 1-22-2018 R.Blasa + +Ext4.define('ONPRC_EHR.panel.ManageCasesPanel', { + extend: 'Ext.panel.Panel', + alias: 'widget.onprc_ehr-managecasespanel', + + statics: { + CASE_CATEGORIES: { + Clinical: { + showAssignedVet: true, + requiredFields: ['assignedvet', 'problem'] + }, + Weight: { + showAssignedVet: true, + requiredFields: ['assignedvet', 'problem'] + }, + Surgery: { + showAssignedVet: false, + requiredFields: ['remark'] + }, + Behavior: { + showAssignedVet: false, + requiredFields: ['problem', 'subcategory'] + } + }, + + getButtonConfig: function(){ + return [{ + xtype: 'button', + text: 'Open Case', + disabled: !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'insert', [{schemaName: 'study', queryName: 'Cases'}]), + menu: [{ + text: 'Open Behavior Case', + handler: function(btn){ + var owner = btn.up('window'); + if (owner) + owner = owner.down('panel'); + + owner.showCreateWindow('Behavior'); + } + },{ + text: 'Open Clinical Case', + handler: function(btn){ + var owner = btn.up('window'); + if (owner) + owner = owner.down('panel'); + + owner.showCreateWindow('Clinical'); + } + },{ + text: 'Open Surgery Case', + handler: function(btn){ + var owner = btn.up('window'); + if (owner) + owner = owner.down('panel'); + + owner.showCreateWindow('Surgery'); + } + }] + },{ + xtype: 'button', + text: 'Show Inactive', + handler: function(btn){ + var owner = btn.up('window'); + if (owner) + owner = owner.down('panel'); + + var store = owner.getStore(); + LDK.Assert.assertNotEmpty('Unable to find animalId in ManageCasesPanel', owner.animalId); + var filterArray = [ + LABKEY.Filter.create('Id', owner.animalId, LABKEY.Filter.Types.EQUAL) + ]; + + if (btn.text == 'Show Inactive'){ + btn.setText('Hide Inactive'); + } + else { + btn.setText('Show Inactive'); + filterArray.push(LABKEY.Filter.create('isOpen', true, LABKEY.Filter.Types.EQUAL)); + } + + store.filterArray = filterArray; + store.load(); + } + }] + } + }, + + initComponent: function(){ + Ext4.apply(this, { + border: false, + items: [this.getGridConfig()], + buttons: this.hideButtons ? null : this.getButtonConfig() + }); + + this.callParent(); + + this.addEvents('storeloaded'); + }, + + getStore: function(){ + if (this.store) + return this.store; + + this.store = Ext4.create('LABKEY.ext4.data.Store', { + schemaName: 'study', + queryName: 'Cases', + columns: 'lsid,objectid,Id,date,enddate,reviewdate,category,remark,performedby,problemCategories,encounterid,assignedvet,assignedvet/DisplayName,isOpen,isActive', + filterArray: [ + LABKEY.Filter.create('Id', this.animalId, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('isOpen', true, LABKEY.Filter.Types.EQUAL) + ], + autoLoad: true, + listeners: { + scope: this, + synccomplete: function(store){ + var grid = this.down('grid'); + if (grid){ + grid.getView().refresh(); + } + + EHR.DemographicsCache.clearCache(this.animalId); + }, + load: function(store){ + //NOTE: consumed by SnapshotPanel + this.fireEvent('storeloaded', this); + }, + exception: function(store){ + //NOTE: refresh the store in order to avoid invalid data on the client + store.load(); + } + } + }); + + return this.store; + }, + + getGridConfig: function(){ + return { + xtype: 'grid', + cls: 'ldk-grid', //variable row height + border: false, + store: this.getStore(), + viewConfig: { + loadMask: !(Ext4.isIE && Ext4.ieVersion <= 8) + }, + columns: [{ + xtype: 'actioncolumn', + width: 40, + icon: LABKEY.ActionURL.getContextPath() + '/_images/editprops.png', + tooltip: 'Edit', + handler: function(view, rowIndex, colIndex, item, e, rec){ + Ext4.create('Ext.menu.Menu', { + items: [{ + text: 'Close Case', + disabled: !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'update', [{schemaName: 'study', queryName: 'Cases'}]), + scope: this, + handler: function(btn){ + Ext4.create('Ext.window.Window', { + modal: true, + closeAction: 'destroy', + bodyStyle: 'padding: 5px', + width: 400, + items: [{ + html: 'This will close this case and all open problems. If you only want to close one of the problems, but leave the others open, please use \'Edit Case\' and only close the desired problem.', + border: false, + style: 'padding-bottom: 10px;' + },{ + xtype: 'datefield', + itemId: 'dateField', + fieldLabel: 'Close Date', + value: new Date(), //Modified: 10-09-2018 R.Blasa restored to original code + minValue: rec.get('date'), + maxValue: new Date() //Modified: 10-09-2018 R.Blasa restored to original code + }], + buttons: [{ + text: 'Close Case', + scope: this, + handler: function(btn){ + var win = btn.up('window'); + var val = win.down('#dateField').getValue(); + if (!val){ + Ext4.Msg.alert('Error', 'Must choose a date'); + return; + } + + rec.set('enddate', val); + + Ext4.Msg.wait('Saving...'); + var store = rec.store; + store.sync({ + scope: this, + success: function(){ + Ext4.Msg.hide(); + store.load(); + } + }); + + win.close(); + } + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }).show(); + } + },{ + text: 'Close With Reopen Date', + disabled: !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'update', [{schemaName: 'study', queryName: 'Cases'}]), + scope: this, + handler: function(btn){ + Ext4.create('Ext.window.Window', { + title: 'Close With Reopen Date', + modal: true, + closeAction: 'destroy', + bodyStyle: 'padding: 5px', + width: 400, + items: [{ + html: 'This will close this case until the date selected below.', + border: false, + style: 'padding-bottom: 10px;' + },{ + xtype: 'datefield', + itemId: 'dateField', + fieldLabel: 'Reopen Date', + minValue: new Date(), //Modified: 10-09-2018 R.Blasa restored to original code + value: rec.get('reviewdate') || Ext4.Date.add(new Date(), Ext4.Date.DAY, 14) //Modified: 10-09-2018 R.Blasa restored to original code + }], + buttons: [{ + text: 'Submit', + scope: this, + handler: function(btn){ + var win = btn.up('window'); + var val = win.down('#dateField').getValue(); + if (!val){ + Ext4.Msg.alert('Error', 'Must choose a date'); + return; + } + + rec.set('reviewdate', val); + rec.set('enddate', null); + var store = rec.store; + store.sync({ + scope: this, + success: function(){ + if (Ext4.Msg.isVisible()) + Ext4.Msg.hide(); + store.load(); + } + }); + + win.close(); + } + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }).show(); + } + },{ + text: 'Delete Case', + disabled: !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'delete', [{schemaName: 'study', queryName: 'Cases'}]), + handler: function(btn){ + Ext4.Msg.confirm('Delete Case', 'This will delete all record of this case. If you just want to close the case, you should choose this option instead. Are you sure you want to do this?', function(val){ + if (val == 'yes'){ + var store = rec.store; + store.remove(rec); + store.sync(); + } + }, this); + } + },{ + text: 'Edit Case', + disabled: !EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'update', [{schemaName: 'study', queryName: 'Cases'}]), + scope: this, + handler: function(btn){ + this.up('onprc_ehr-managecasespanel').showEditCaseWindow(rec); + } + }] + }).showAt(e.getXY()); + } + },{ + header: 'Category', + dataIndex: 'category' + },{ + header: 'Active?', + dataIndex: 'isActive', + width: 60, + renderer: function(value){ + return value ? 'Y' : 'N'; + } + },{ + header: 'Open Date', + dataIndex: 'date', + xtype: 'datecolumn', + format: LABKEY.extDefaultDateFormat, + width: 130 + },{ + header: 'Reopen Date', + dataIndex: 'reviewdate', + xtype: 'datecolumn', + format: LABKEY.extDefaultDateFormat, + width: 130 + },{ + header: 'Description/Notes', + dataIndex: 'remark', + tdCls: 'ldk-wrap-text', + width: 250 + },{ + header: 'Vet', + dataIndex: 'assignedvet', + width: 130, + renderer: function(value, cellMetaData, record){ + if (Ext4.isDefined(record.get('assignedvet/DisplayName'))){ + return record.get('assignedvet/DisplayName'); + } + + return value ? '[' + value + ']' : value; + } + },{ + header: 'Problem(s)', + dataIndex: 'problemCategories', + tdCls: 'ldk-wrap-text', + renderer: function(v){ + if (v){ + return v.replace(/\n/g, '
'); + } + }, + width: 220 + }] + } + }, + + showEditCaseWindow: function(rec){ + if (Ext4.isArray(rec)){ + var data = []; + Ext4.Array.forEach(rec, function(r){ + var title = r.get('problemCategories') || r.get('remark'); + data.push({ + problems: r.get('problemCategories'), + title: title, + objectid: r.get('objectid'), + record: r + }); + }, this); + + Ext4.create('Ext.window.Window', { + title: 'Choose Case', + modal: true, + closeAction: 'destroy', + bodyStyle: 'padding: 5px;', + width: 420, + items: [{ + xtype: 'combo', + fieldLabel: 'Choose Case', + displayField: 'title', + triggerAction: 'all', + queryMode: 'local', + width: 400, + valueField: 'objectid', + store: { + type: 'store', + data: data, + fields: ['problems', 'objectid', 'record', 'title'] + }, + forceSelection: true + }], + buttons: [{ + text: 'Submit', + scope: this, + handler: function(btn){ + var win = btn.up('window'); + var field = win.down('combo'); + if (!field.getValue()){ + Ext4.Msg.alert('Error', 'Must choose a case'); + return; + } + + var selected = field.store.findRecord('objectid', field.getValue()); + LDK.Assert.assertNotEmpty('Unable to find record in ManageCasesPanel', selected); + win.close(); + + Ext4.create('EHR.window.EditCaseWindow', { + boundRecord: selected.get('record') + }).show(); + } + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }).show(); + } + else { + Ext4.create('EHR.window.EditCaseWindow', { + boundRecord: rec + }).show(); + } + }, + + showCreateWindow: function(category, defaultRemark){ + var store = this.getStore(); + if (store.isLoading()){ + Ext4.Msg.wait('Loading...'); + store.on('load', function(){ + Ext4.Msg.hide(); + this.showCreateWindow(category, defaultRemark); + }, this, {single: true}); + return; + } + + var existingRecs = []; + store.each(function(r){ + if (r.get('category') == category && r.get('isActive')){ + existingRecs.push(r); + } + }, this); + + if (existingRecs.length){ + Ext4.create('Ext.window.MessageBox', { + buttonText: { yes: 'Open New', no: 'Edit Existing'} + }).show({ + icon: Ext4.Msg.QUESTION, + buttons: Ext4.Msg.YESNO, + title: 'Open Case', + msg: 'This animal already has an open ' + category + ' case. Do you want to edit this case or open a second one or edit the first?', + callback: function(val){ + if (val == 'yes'){ + Ext4.create('EHR.window.OpenCaseWindow', { + caseCategory: category, + ownerPanel: this, + animalId: this.animalId, + defaultVet: existingRecs[0].get('assignedvet'), + defaultRemark: defaultRemark + }).show(); + } + else if (val == 'no'){ + this.showEditCaseWindow(existingRecs.length == 1 ? existingRecs[0] : existingRecs); + } + }, + scope: this + }); + } + else { + Ext4.create('EHR.window.OpenCaseWindow', { + caseCategory: category, + ownerPanel: this, + animalId: this.animalId, + defaultRemark: defaultRemark + }).show(); + } + } +}); + +Ext4.define('EHR.window.EditCaseWindow', { + extend: 'Ext.window.Window', + + initComponent: function(){ + Ext4.apply(this, { + modal: true, + closeAction: 'destroy', + title: 'Edit Case', + width: 750, + bodyStyle: 'padding: 5px;', + items: [{ + xtype: 'form', + border: false, + defaults: { + labelWidth: 140, + border: false + }, + items: [{ + html: 'There are three dates for a case. The open date is the date is was created. If you enter a value for \'Date Closed\' means the date this case is completely closed, and will never re-open. If you want to temporarily close this case and reopen at a future date, enter a date in the \'Reopen Date\' field', + bodyStyle: 'padding-bottom: 10px;' + },{ + xtype: 'ehr-vetfieldcombo', + fieldLabel: 'Assigned Vet', + itemId: 'assignedvet', + allowBlank: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.boundRecord.get('category')].requiredFields.indexOf('assignedvet') == -1, + width: 560, + value: this.boundRecord.get('assignedvet') + },{ + xtype: 'datefield', + fieldLabel: 'Initial Open Date', + itemId: 'date', + allowBlank: false, + width: 560, + value: this.boundRecord.get('date') + },{ + xtype: 'datefield', + fieldLabel: 'Reopen Date', + itemId: 'reviewdate', + allowBlank: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.boundRecord.get('category')].requiredFields.indexOf('reviewdate') == -1, + width: 560, + value: this.boundRecord.get('reviewdate'), + listeners: { + change: function(field, val, oldVal){ + if (val){ + field.up('panel').down('#enddate').setValue(null); + } + } + } + },{ + xtype: 'datefield', + fieldLabel: 'Date Closed', + itemId: 'enddate', + allowBlank: true, + width: 560, + value: this.boundRecord.get('enddate') + },{ + xtype: 'textarea', + fieldLabel: 'Description/Notes', + allowBlank: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.boundRecord.get('category')].requiredFields.indexOf('remark') == -1, + width: 560, + height: 75, + value: this.boundRecord.get('remark'), + itemId: 'remark' + }] + },{ + xtype: 'ldk-gridpanel', + itemId: 'problemGrid', + title: 'Master Problems', + viewConfig: { + loadMask: !(Ext4.isIE && Ext4.ieVersion <= 8) + }, + store: { + type: 'labkey-store', + schemaName: 'study', + queryName: 'problem', + sort: 'date', + columns: 'Id,date,lsid,objectid,category,subcategory,enddate,caseid', + filterArray: [LABKEY.Filter.create('caseid', this.boundRecord.get('objectid'), LABKEY.Filter.Types.EQUAL)], + autoLoad: true, + listeners: { + exception: function(store){ + //NOTE: refresh the store in order to avoid invalid data on the client + store.load(); + } + } + }, + columns: [{ + xtype: 'actioncolumn', + width: 40, + icon: LABKEY.ActionURL.getContextPath() + '/_images/editprops.png', + tooltip: 'Edit', + handler: function(view, rowIndex, colIndex, item, e, rec){ + Ext4.create('EHR.window.CreateProblemWindow', { + title: 'Edit Problem', + caseRecord: view.up('window').boundRecord, + problemRecord: rec, + mode: 'edit', + problemStore: rec.store + }).show(); + } + },{ + dataIndex: 'category', + width: 180, + header: 'Problem' + },{ + dataIndex: 'subcategory', + width: 180, + header: 'Subcategory' + },{ + dataIndex: 'date', + header: 'Date', + xtype: 'datecolumn', + width: 180, + format: LABKEY.extDefaultDateFormat + },{ + dataIndex: 'enddate', + header: 'End Date', + xtype: 'datecolumn', + width: 180, + format: LABKEY.extDefaultDateFormat + }], + dockedItems: [{ + xtype: 'toolbar', + position: 'top', + items: [{ + text: 'Add', + scope: this, + handler: function(button){ + var grid = button.up('grid'); + LDK.Assert.assertNotEmpty('No bound record', this.boundRecord); + + Ext4.create('EHR.window.CreateProblemWindow', { + caseRecord: this.boundRecord, + problemStore: grid.store + }).show(); + } + },{ + text: 'End Selected', + scope: this, + handler: function(btn){ + var grid = btn.up('grid'); + var recs = grid.getSelectionModel().getSelection(); + if (!recs || !recs.length){ + Ext4.Msg.alert('Error', 'No problems selected'); + return; + } + + Ext4.Array.forEach(recs, function(r){ + if (!r.get('enddate')){ + r.set('enddate', new Date()); + } + }, this); + + Ext4.Msg.wait('Saving...'); + grid.store.sync({ + scope: this, + success: function(){ + Ext4.Msg.hide(); + }, + failure: LDK.Utils.getErrorCallback() + }); + } + }] + }] + }], + buttons: [{ + text: 'Submit', + scope: this, + handler: function(btn){ + var win = btn.up('window'); + + if (!win.down('form').isValid()){ + Ext4.Msg.alert('Error', 'Missing one or more required fields'); + return; + } + + win.boundRecord.set({ + remark: win.down('#remark').getValue(), + assignedvet: win.down('#assignedvet').getValue(), + date: win.down('#date').getValue(), + reviewdate: win.down('#reviewdate').getValue() + }); + + win.boundRecord.set('assignedvet/DisplayName', win.down('#assignedvet').getDisplayValue()); + win.boundRecord.store.sync(); + + var problemGrid = win.down('#problemGrid'); + problemGrid.store.sync(); + + win.close(); + } + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }); + + this.callParent(arguments); + } +}); + + +/** + * @cfg caseCategory + * @cfg ownerPanel, + * @cfg animalId + * @cfg defaultVet + * @cfg defaultRemark + */ +Ext4.define('EHR.window.OpenCaseWindow', { + extend: 'Ext.window.Window', + + initComponent: function(){ + Ext4.apply(this, { + title: 'Open Case: ' + this.animalId, + width: 600, + modal: true, + closeAction: 'destroy', + bodyStyle: 'padding: 5px;', + items: [{ + xtype: 'form', + border: false, + defaults: { + border: false, + labelWidth: 140, + width: 550 + }, + items: [{ + xtype: 'displayfield', + fieldLabel: 'Category', + value: this.caseCategory, + name: 'category' + },{ + xtype: 'ehr-vetfieldcombo', + fieldLabel: 'Assigned Vet', + name: 'assignedvet', + value: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.caseCategory].showAssignedVet ? this.defaultVet : null, + allowBlank: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.caseCategory].requiredFields.indexOf('assignedvet') == -1, + hidden: !ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.caseCategory].showAssignedVet + },{ + xtype: 'labkey-combo', + fieldLabel: 'Problem', + allowBlank: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.caseCategory].requiredFields.indexOf('problem') == -1, + anyMatch: true, + queryMode: 'local', + forceSelection: true, + name: 'problem', + valueField: 'value', + displayField: 'value', + store: { + type: 'labkey-store', + schemaName: 'ehr_lookups', + queryName: 'problem_list_category', + autoLoad: true + }, + value: this.caseCategory == 'Behavior' ? 'Behavioral' : null, + listeners: { + change: function(field, val){ + var sc = field.up('window').down('#subcategory'); + sc.store.filterArray = [LABKEY.Filter.create('category', val)]; + sc.store.load(); + sc.setDisabled(false); + }, + render: function(field){ + if (field.getValue()){ + field.fireEvent('change', field, field.getValue()); + } + } + } + },{ + xtype: 'labkey-combo', + fieldLabel: 'Subcategory', + allowBlank: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.caseCategory].requiredFields.indexOf('subcategory') == -1, + valueField: 'value', + displayField: 'value', + itemId: 'subcategory', + name: 'subcategory', + disabled: true, + anyMatch: true, + queryMode: 'local', + forceSelection: true, + store: { + type: 'labkey-store', + schemaName: 'ehr_lookups', + queryName: 'problem_list_subcategory', + columns: 'value,category' + } + },{ + xtype: 'textarea', + fieldLabel: 'Description/Notes', + name: 'remark', + value: this.defaultRemark, + allowBlank: ONPRC_EHR.panel.ManageCasesPanel.CASE_CATEGORIES[this.caseCategory].requiredFields.indexOf('remark') == -1, + height: 75 + }] + }], + buttons: [{ + text: 'Open Case', + handler: function(btn){ + var win = btn.up('window'); + win.doSave(); //Modified: 12-20-2017 R.Blasa restored to original code + } + },{ + text: 'Open & Immediately Close', + menu: [{ + text: 'Close Permanently', + handler: function(btn){ + var win = btn.up('window'); + win.doSave(new Date()); //Modified: 12-20-2017 R.Blasa restored to original code + + } + },{ + text: 'Close With Reopen Date', + handler: function(btn){ + var ownerWindow = btn.up('window'); + if (!ownerWindow.down('form').getForm().isValid()){ + Ext4.Msg.alert('Error', 'Missing one or more required fields'); + return; + } + + Ext4.create('Ext.window.Window', { + modal: true, + closeAction: 'destroy', + bodyStyle: 'padding: 5px', + width: 400, + items: [{ + html: 'This will close this case until the date selected below.', + border: false, + style: 'padding-bottom: 10px;' + },{ + xtype: 'datefield', + itemId: 'dateField', + fieldLabel: 'Reopen Date', + minValue: new Date(), + value: Ext4.Date.add(new Date(), Ext4.Date.DAY, 14) + + }], + buttons: [{ + text: 'Submit', + scope: this, + handler: function(btn){ + var win = btn.up('window'); + var val = win.down('#dateField').getValue(); + if (!val){ + Ext4.Msg.alert('Error', 'Must choose a date'); + return; + } + + win.close(); + ownerWindow.doSave(null, val); + } + }] + }).show(); + } + }] + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }); + + this.callParent(arguments); + }, + + doSave: function(enddate, reviewdate){ + if (!this.down('form').getForm().isValid()){ + Ext4.Msg.alert('Error', 'Missing one or more required fields'); + return; + } + + var values = this.down('form').getForm().getValues(); + var caseId = LABKEY.Utils.generateUUID().toUpperCase(); + values.date = new Date(); //Modified: 10-08-2018 R.Blasa restored to original code + values.category = this.caseCategory; + values.Id = this.ownerPanel.animalId; + values.performedby = LABKEY.Security.currentUser.displayName; + values.objectid = caseId; + if (enddate){ + values.enddate = enddate; + } + if (reviewdate){ + values.reviewdate = reviewdate; + } + + var problemRow = { + Id: values.Id, + date: values.date, + reviewdate: values.reviewdate, + enddate: values.enddate, + category: values.problem, + subcategory: values.subcategory, + caseid: values.objectid + }; + + var panel = this.ownerPanel; + + Ext4.Msg.wait('Saving...'); + + var commands = []; + commands.push({ + command: 'insertWithKeys', + schemaName: 'study', + queryName: 'cases', + rows: [{ + values: values + }] + }); + + commands.push({ + command: 'insert', + schemaName: 'study', + queryName: 'problem', + rows: [problemRow] + }); + + LABKEY.Query.saveRows({ + commands: commands, + scope: this, + failure: LDK.Utils.getErrorCallback(), + success: function(results){ + this.close(); + Ext4.Msg.hide(); + + EHR.DemographicsCache.reportCaseCreated(this.animalId, this.caseCategory, caseId); + + if (panel){ + panel.fireEvent('casecreated', this.animalId, this.caseCategory, caseId); + panel.down('grid').store.load(); + } + + EHR.DemographicsCache.clearCache(this.animalId); + } + }); + } +}); + +/** + * @cfg mode + * @cfg caseRecord + * @cfg problemRecord + */ +Ext4.define('EHR.window.CreateProblemWindow', { + extend: 'Ext.window.Window', + mode: 'insert', + + initComponent: function(){ + Ext4.apply(this, { + modal: true, + title: this.mode == 'edit' ? 'Edit Problem' : 'Add Problem', + bodyStyle: 'padding: 5px;', + defaults: { + width: 350 + }, + items: [{ + xtype: 'labkey-combo', + fieldLabel: 'Problem', + valueField: 'value', + displayField: 'value', + itemId: 'category', + anyMatch: true, + queryMode: 'local', + forceSelection: true, + value: this.problemRecord ? this.problemRecord.get('category') : null, + store: { + type: 'labkey-store', + schemaName: 'ehr_lookups', + queryName: 'problem_list_category', + autoLoad: true + }, + //Modified: 10-5-2018 R. Blasa filter array changes + listeners: { + change: function(field, val){ + var sc = field.up('panel').down('#subcategory'); + var initialValue = sc.getValue(); + sc.store.filterArray = [LABKEY.Filter.create('category', val),LABKEY.Filter.create('date_disabled', null, LABKEY.Filter.Types.ISBLANK)]; + sc.store.load({ + scope: this, + callback: function(){ + if (initialValue){ + sc.setValue(initialValue); + } + } + }); + sc.setDisabled(false); + }, + render: function(field){ + if (field.getValue()){ + field.fireEvent('change', field, field.getValue()); + } + } + } + },{ + xtype: 'labkey-combo', + fieldLabel: 'Subcategory', + valueField: 'value', + displayField: 'value', + itemId: 'subcategory', + value: this.problemRecord ? this.problemRecord.get('subcategory') : null, + disabled: (this.mode == 'insert') || !(this.problemRecord && this.problemRecord.get('category')), + anyMatch: true, + queryMode: 'local', + forceSelection: true, + store: { + type: 'labkey-store', + schemaName: 'ehr_lookups', + queryName: 'problem_list_subcategory', + columns: 'value,category', + filterArray: (this.problemRecord && this.problemRecord.get('category')) ? [LABKEY.Filter.create('category', this.problemRecord.get('category'))] : null, + autoLoad: (this.problemRecord && this.problemRecord.get('category')) + } + },{ + xtype: 'datefield', + fieldLabel: 'Open Date', + itemId: 'dateField', + maxValue: new Date(), //Modified: 10-08-2018 R.Blasa restored to original code + //cant open prior to case open + minValue: this.caseRecord.get('date'), + value: this.problemRecord ? this.problemRecord.get('date') : new Date() + },{ + xtype: 'datefield', + fieldLabel: 'End Date', + itemId: 'enddateField', + hidden: this.mode == 'insert', + //cant open prior to case open + minValue: this.caseRecord.get('date'), + value: this.problemRecord ? this.problemRecord.get('enddate') : null + }], + buttons: [{ + text: 'Submit', + scope: this, + handler: function(btn){ + var win = btn.up('window'); + if (!win.down('#category').getValue() || !win.down('#dateField').getValue()){ + Ext4.Msg.alert('Error', 'Must enter the problem and date'); + return; + } + + if (win.mode == 'insert'){ + var newModel = win.problemStore.createModel({}); + newModel.set({ + Id: win.caseRecord.get('Id'), + caseid: win.caseRecord.get('objectid'), + category: win.down('#category').getValue(), + subcategory: win.down('#subcategory').getValue(), + date: win.down('#dateField').getValue() + }); + + win.problemStore.add(newModel); + } + else { + this.problemRecord.set({ + category: win.down('#category').getValue(), + subcategory: win.down('#subcategory').getValue(), + date: win.down('#dateField').getValue(), + enddate: win.down('#enddateField').getValue() + }); + } + + Ext4.Msg.wait('Saving...'); + win.problemStore.sync({ + scope: this, + success: function(){ + Ext4.Msg.hide(); + }, + failure: LDK.Utils.getErrorCallback() + }); + win.close(); + } + },{ + text: 'Delete', + hidden: !(this.mode == 'edit' && EHR.Security.hasPermission(EHR.QCStates.COMPLETED, 'delete', [{schemaName: 'study', queryName: 'Problem List'}])), + handler: function(btn){ + Ext4.Msg.confirm('Delete Problem', 'This will permanently delete this problem. Are you sure you want to do this?', function(val){ + if (val == 'yes'){ + var win = btn.up('window'); + var store = win.problemRecord.store; + store.remove(win.problemRecord); + + Ext4.Msg.wait('Saving...'); + store.sync({ + scope: this, + success: function(){ + Ext4.Msg.hide(); + }, + failure: LDK.Utils.getErrorCallback() + }); + win.close(); + } + }, this); + } + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }); + + this.callParent(arguments); + } +}); + diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/ManageTreatmentsPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/ManageTreatmentsPanel.js index cab3e2ce4..a759687be 100644 --- a/onprc_ehr/resources/web/onprc_ehr/panel/ManageTreatmentsPanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/panel/ManageTreatmentsPanel.js @@ -94,7 +94,7 @@ Ext4.define('onprc_ehr.panel.ManageTreatmentsPanel', { } }, config); - Ext4.create('EHR.window.ManageRecordWindow', cfg).show(); + Ext4.create('ONPRC_EHR.window.ManageRecordWindow', cfg).show(); //Modified: 7-18-2018 R.Blasa }, getActionBtnMenu: function(rec){ @@ -186,14 +186,14 @@ Ext4.define('onprc_ehr.panel.ManageTreatmentsPanel', { getStore: function(){ if (this.store) return this.store; - + var xdate = Ext4.Date.format(new Date(), 'Y-m-d'); this.store = Ext4.create('LABKEY.ext4.data.Store', { schemaName: 'study', queryName: 'treatment_order', - columns: 'lsid,objectid,Id,date,enddate,project,category,remark,performedby,code,route,frequency,frequency/meaning,amountAndVolume,modifiedby/DisplayName,modified', + columns: 'lsid,objectid,Id,date,enddate,project,category,remark,performedby,code,route,frequency,frequency/meaning,amountAndVolume,modifiedby/DisplayName,modified,enddateTimeCoalesced', filterArray: [ LABKEY.Filter.create('Id', this.animalId, LABKEY.Filter.Types.EQUAL), - LABKEY.Filter.create('isExpired', false, LABKEY.Filter.Types.EQUAL) + LABKEY.Filter.create('enddateTimeCoalesced', xdate, LABKEY.Filter.Types.GTE)//Modified: 6-28-2018 R.Blasa ], autoLoad: true, listeners: { diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/MultiAnimalFilterType.js b/onprc_ehr/resources/web/onprc_ehr/panel/MultiAnimalFilterType.js new file mode 100644 index 000000000..f433f0f4d --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/panel/MultiAnimalFilterType.js @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2013 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +//Created: 11-15-2017 R.Blasa + + +Ext4.define('EHR.panel.MultiAnimalFilterType', { + extend: 'LDK.panel.MultiSubjectFilterType', + alias: 'widget.onprc_ehr-multianimalfiltertype', + + statics: { + filterName: 'multiSubject', + label: 'Multiple Animals' + }, + + getItems: function(){ + var ctx = this.filterContext || {}; + + var toAdd = this.callParent(); + var items = [{ + layout: 'hbox', + border: false, + defaults: { + border: false + }, + items: toAdd + }] + + items.push({ + xtype: 'ldk-linkbutton', + text: '[Search By Room/Cage]', + minWidth: 80, + style: 'padding-left:200px;', + handler: function(btn){ + var panel = btn.up('onprc_ehr-multianimalfiltertype'); + + Ext4.create('Ext.window.Window', { + modal: true, + width: 330, + closeAction: 'destroy', + title: 'Search By Room/Cage', + items: [{ + xtype: 'form', + bodyStyle:'padding:5px', + items: [{ + xtype: 'ehr-roomfield', + itemId: 'room', + name: 'roomField', + multiSelect: false, + showOccupiedOnly: true, + width: 300 + },{ + xtype: 'ehr-cagefield', + fieldLabel: 'Cage', + name: 'cageField', + itemId: 'cage', + width: 300 + }] + }], + buttons: [{ + text:'Submit', + disabled:false, + itemId: 'submit', + scope: panel, + handler: panel.loadRoom + },{ + text: 'Close', + handler: function(btn){ + btn.up('window').hide(); + } + }] + }).show(btn); + } + }); + + items.push({ + xtype: 'ldk-linkbutton', + text: '[Search By Project/Protocol]', + minWidth: 80, + handler: function(btn){ + var panel = btn.up('onprc_ehr-multianimalfiltertype'); + + Ext4.create('Ext.window.Window', { + modal: true, + width: 330, + closeAction: 'destroy', + title: 'Search By Project/Protocol', + items: [{ + xtype: 'form', + bodyStyle:'padding:5px', + items: [{ + xtype: 'ehr-projectfield', + itemId: 'project', + onlyIncludeProjectsWithAssignments: true + },{ + xtype: 'ehr-protocolfield', + itemId: 'protocol', + onlyIncludeProtocolsWithAssignments: true + }] + }], + buttons: [{ + text:'Submit', + disabled:false, + itemId: 'submit', + scope: panel, + handler: panel.loadProject + },{ + text: 'Close', + handler: function(btn){ + btn.up('window').close(); + } + }] + }).show(btn); + }, + style: 'margin-bottom:10px;padding-left:200px;' + }); + //Added: 11-15-2017 R.Blasa + items.push({ + xtype: 'ldk-linkbutton', + text: '[Search By Animal Groups]', + minWidth: 80, + handler: function(btn){ + var panel = btn.up('onprc_ehr-multianimalfiltertype'); + + Ext4.create('Ext.window.Window', { + modal: true, + width: 300, + height:100, + closeAction: 'destroy', + title: 'Search By Animal Groups', + items: [{ + xtype: 'labkey-combo', + fieldLabel: '
Animal Groups
', + itemId: 'animalGroup', + displayField: 'name', + valueField: 'rowid', + store: { + type: 'labkey-store', + containerPath: ctx['EHRStudyContainer'], + schemaName: 'ehr', + queryName: 'animal_groups', + viewName: 'Active Groups', + columns: 'name, rowid', + filterArray: [LABKEY.Filter.create('enddate', null, LABKEY.Filter.Types.ISBLANK)], + autoLoad: true + } + }], + buttons: [{ + text:'Submit', + disabled:false, + itemId: 'submit', + scope: panel, + handler: panel.loadGroups + },{ + text: 'Close', + handler: function(btn){ + btn.up('window').close(); + } + }] + }).show(btn); + }, + style: 'margin-bottom:10px;padding-left:200px;' + }); + + + + return [{ + xtype: 'panel', + width: 500, + border: false, + defaults: { + border: false + }, + items: items + }]; + }, + + loadProject: function(btn){ + var win = btn.up('window'); + var project = win.down('#project').getValue(); + var protocol = win.down('#protocol').getValue(); + win.down('#project').reset(); + win.down('#protocol').reset(); + + win.close(); + + Ext4.Msg.wait("Loading.."); + + if(!project && !protocol){ + Ext4.Msg.hide(); + return; + } + + var filters = []; + + if(project){ + filters.push(LABKEY.Filter.create('project', project, LABKEY.Filter.Types.EQUAL)) + } + + if(protocol){ + protocol = protocol.toLowerCase(); + filters.push(LABKEY.Filter.create('project/protocol', protocol, LABKEY.Filter.Types.EQUAL)) + } + + LABKEY.Query.selectRows({ + schemaName: 'study', + queryName: 'Assignment', + viewName: 'Active Assignments', + sort: 'Id', + filterArray: filters, + scope: this, + success: function(rows){ + var subjectArray = []; + Ext4.each(rows.rows, function(r){ + subjectArray.push(r.Id); + }, this); + subjectArray = Ext4.unique(subjectArray); + if(subjectArray.length){ + this.tabbedReportPanel.setSubjGrid(true, false, subjectArray); + } + Ext4.Msg.hide(); + }, + failure: LDK.Utils.getErrorCallback() + }); + }, + + loadGroups: function(btn){ + var win = btn.up('window'); + var groups = win.down('#animalGroup').getValue(); + win.down('#animalGroup').reset(); + + win.close(); + + Ext4.Msg.wait("Loading.."); + + if(!groups){ + Ext4.Msg.hide(); + return; + } + + var filters = []; + + if(groups){ + filters.push(LABKEY.Filter.create('groupId/rowid', groups, LABKEY.Filter.Types.EQUAL)); + filters.push(LABKEY.Filter.create('enddate', null, LABKEY.Filter.Types.ISBLANK)) + } + + + LABKEY.Query.selectRows({ + schemaName: 'study', + queryName: 'animal_group_members', + //viewName: 'Active Assignments', + sort: 'Id', + filterArray: filters, + scope: this, + success: function(rows){ + var subjectArray = []; + Ext4.each(rows.rows, function(r){ + subjectArray.push(r.Id); + }, this); + subjectArray = Ext4.unique(subjectArray); + if(subjectArray.length){ + this.tabbedReportPanel.setSubjGrid(true, false, subjectArray); + } + Ext4.Msg.hide(); + }, + failure: LDK.Utils.getErrorCallback() + }); + }, + + loadRoom: function(btn){ + var housingWin = btn.up('window'); + var room = housingWin.down('#room').getValue(); + var cage = housingWin.down('#cage').getValue(); + housingWin.down('#room').reset(); + housingWin.down('#cage').reset(); + + housingWin.close(); + + Ext4.Msg.wait("Loading..."); + + if(!room && !cage){ + Ext4.Msg.hide(); + return; + } + + var filters = []; + + if(room){ + room = room.toLowerCase(); + filters.push(LABKEY.Filter.create('room', room, LABKEY.Filter.Types.STARTS_WITH)) + } + + if(cage){ + filters.push(LABKEY.Filter.create('cage', cage, LABKEY.Filter.Types.EQUAL)) + } + + LABKEY.Query.selectRows({ + schemaName: 'study', + queryName: 'housing', + viewName: 'Active Housing', + sort: 'Id', + filterArray: filters, + scope: this, + success: function(rows){ + var subjectArray = []; + Ext4.each(rows.rows, function(r){ + subjectArray.push(r.Id); + }, this); + subjectArray = Ext4.unique(subjectArray); + if(subjectArray.length){ + this.tabbedReportPanel.setSubjGrid(true, false, subjectArray); + } + Ext4.Msg.hide(); + }, + failure: LDK.Utils.getErrorCallback() + }); + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/RoomLayoutPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/RoomLayoutPanel.js index f3b6f088a..2e02d1137 100644 --- a/onprc_ehr/resources/web/onprc_ehr/panel/RoomLayoutPanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/panel/RoomLayoutPanel.js @@ -234,6 +234,36 @@ Ext4.define('ONPRC.panel.RoomLayoutPanel', { style: 'margin-bottom: 10px;', border: false }); + + //Modified: 8-19-2019 R. Blasa Added Divider Legends Not eeded at this time + currentSection.push({ + // html: 'List of cage slides, and the display letters they represent:

' + + // ' Infant Feeding Slide ---------> IFS
' + + // ' Clear Slide -----------------------> C
' + + // ' Extension Solid Slide --------> ES
' + + // ' Extension Mesh Slide -------> EM
' + + // ' Window Slide -------------------> W
' + + // ' Double Mesh Slides ----------> DM
' + + // ' Double Solid Slides -----------> DS
' + + // ' Window Mesh Slide ----------> WM
' + + // ' Backward Grooming Slide -> B


', + // + // + // }, { + //Added: 10-9-2019 R.Blasa + xtype: 'button', + text: 'Slide Descriptions', + scope: this, + style: 'margin-bottom: 10px;', + handler: function(btn){ + + var url = LABKEY.ActionURL.buildURL('onprc_ehr', 'SliderDefinition', this.containerPath); + window.open(url); + }, + + style: 'margin-bottom: 10px;', + border: false + }); } table = ONPRC.panel.RoomLayoutPanel.getRowBlockCfg(maxCage); @@ -258,7 +288,7 @@ Ext4.define('ONPRC.panel.RoomLayoutPanel', { } var animalItems = []; - if (animals.length > 4){ + if (animals.length > 8){ //Modified: 7-5-2018 R.Blasa animalItems.push({ html: '' + animals.length + ' animals', border: false, @@ -378,8 +408,10 @@ Ext4.define('ONPRC.panel.RoomLayoutPanel', { defaults: { border: false }, - items: [{ - html: row.get('cage_type') == 'No Cage' ? 'No Cage' : ('' + ri + colIdx + '' + (cageType.sqft ? ' (' + (cageType.sqft / cageType.cageslots)+ suffix + ')' : '') + ''), + + //Modified: 4-8-2020 R.Blasa Contains symbol representing divider types + items: [{ + html: row.get('cage_type') == 'No Cage' ? 'No Cage' : ('' + ri + colIdx + '' + (cageType.sqft ? ' (' + (cageType.sqft / cageType.cageslots)+ suffix + ')' : '') + (dividerInfo.displaychar ? ' [' + (dividerInfo.displaychar) + ']' : '') + ''), bodyStyle: { 'background-color': 'transparent' }, diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/ServiceRequestsPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/ServiceRequestsPanel.js new file mode 100644 index 000000000..e9c0d7fa2 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/panel/ServiceRequestsPanel.js @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +//Created: 7-17-2017 R.Blasa + +Ext4.define('onprc_ehr.panel.ServiceRequestsPanel', { + extend: 'Ext.tab.Panel', + + minHeight: 300, + + initComponent: function(){ + Ext4.apply(this, { + items: this.getItems() + }); + + this.loadData(); + + this.callParent(); + }, + + loadData: function(){ + EHR.Utils.getDataEntryItems({ + includeFormElements: false, + scope: this, + success: this.onLoad + }); + }, + + onLoad: function(results){ + var formMap = {}; + Ext4.each(results.forms, function(form){ + if (form.canInsert && form.category == 'Requests'){ + formMap[form.category] = formMap[form.category] || []; + formMap[form.category].push({ + name: form.label, + url: LABKEY.ActionURL.buildURL('ehr', 'dataEntryForm', null, {formType: form.name}) + }); + } + }, this); + + var sections = []; + for (var i in formMap){ + var items = formMap[i]; + items = LDK.Utils.sortByProperty(items, 'name', false); + + if (items.length){ + sections.push({ + header: i, + items: items + }); + } + } + + var tab = this.down('#enterNew'); + tab.removeAll(); + + if (sections.length){ + tab.add({ + xtype: 'ldk-navpanel', + sections: sections + }); + } + else { + tab.add({ + html: 'You do not have permission to submit any types of requests. Please contact your administrator if you believe this is an error.', + border: false + }); + } + }, + + getItems: function(){ + return [{ +// xtype: 'ldk-querypanel', +// title: 'My Requests', +// style: 'padding: 5px;', +// queryConfig: { +// schemaName: 'ehr', +// queryName: 'my_requests' +// } +// },{ +// xtype: 'ldk-querypanel', +// title: 'All Requests', +// style: 'padding: 5px;', +// queryConfig: { +// schemaName: 'ehr', +// queryName: 'requests' +// } +// },{ + xtype: 'panel', + style: 'padding: 5px;', + title: 'New Request', + itemId: 'enterNew', + defaults: { + border: false + }, + items: [{ + html: 'Loading...' + }] + },{ + xtype: 'ldk-querypanel', + title: 'My Pending Blood Requests', + style: 'padding: 5px;', + queryConfig: { + schemaName: 'study', + queryName: 'blood', + viewName: 'Requests', + removeableFilters: [ + LABKEY.Filter.create('requestid/createdby/DisplayName', LABKEY.Security.currentUser.displayName, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('QCState/Label', 'Request', LABKEY.Filter.Types.STARTS_WITH) + ] + } + },{ + //Added: 7-18-2017 R.Blasa + xtype: 'ldk-querypanel', + title: 'My Pending Treatment Drugs Requests', + queryConfig: { + schemaName: 'study', + queryName: 'drug', + viewName: 'Requests', + removeableFilters: [ + LABKEY.Filter.create('requestid/createdby/DisplayName', LABKEY.Security.currentUser.displayName, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('QCState/Label', 'Request', LABKEY.Filter.Types.STARTS_WITH) + ] + } + },{ + //Modified: 1-5-2017 R.Blasa + xtype: 'ldk-querypanel', + title: 'My Pending Treatment Orders Requests', + queryConfig: { + schemaName: 'study', + queryName: 'Treatment Orders', + viewName: 'Requests', + removeableFilters: [ + //LABKEY.Filter.create('requestid/createdby/DisplayName', LABKEY.Security.currentUser.displayName, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('QCState/Label', 'Request', LABKEY.Filter.Types.STARTS_WITH) + ] + } + },{ + xtype: 'ldk-querypanel', + title: 'My Pending Labwork Requests', + queryConfig: { + schemaName: 'study', + queryName: 'Clinpath Runs', + viewName: 'Requests', + removeableFilters: [ + LABKEY.Filter.create('requestid/createdby/DisplayName', LABKEY.Security.currentUser.displayName, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('QCState/Label', 'Request', LABKEY.Filter.Types.STARTS_WITH) + ] + } + },{ + xtype: 'ldk-querypanel', + title: 'My Pending Procedure Requests', + queryConfig: { + schemaName: 'study', + queryName: 'encounters', + viewName: 'Requests', + removeableFilters: [ + LABKEY.Filter.create('requestid/createdby/DisplayName', LABKEY.Security.currentUser.displayName, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('QCState/Label', 'Request', LABKEY.Filter.Types.STARTS_WITH) + ] + } + },{ + xtype: 'ldk-querypanel', + title: 'My Pending Transfer Requests', + queryConfig: { + schemaName: 'onprc_ehr', + queryName: 'housing_transfer_requests', + //viewName: 'Requests', + removeableFilters: [ + LABKEY.Filter.create('requestid/createdby/DisplayName', LABKEY.Security.currentUser.displayName, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('QCState/Label', 'Request', LABKEY.Filter.Types.STARTS_WITH) + ] + } + }] + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/panel/SnapshotPanel.js b/onprc_ehr/resources/web/onprc_ehr/panel/SnapshotPanel.js index fbf17cbff..64a99c175 100644 --- a/onprc_ehr/resources/web/onprc_ehr/panel/SnapshotPanel.js +++ b/onprc_ehr/resources/web/onprc_ehr/panel/SnapshotPanel.js @@ -85,6 +85,10 @@ Ext4.define('onprc_ehr.panel.SnapshotPanel', { xtype: 'displayfield', fieldLabel: 'Active Cases', name: 'activeCases' + },{ + xtype: 'displayfield', + fieldLabel: 'Behavior Alert' , + name: 'behaviorflag' }] },{ xtype: 'container', @@ -152,6 +156,7 @@ Ext4.define('onprc_ehr.panel.SnapshotPanel', { if (this.showExtendedInformation){ items[0].items = items[0].items.concat(this.getExtendedItems()); + } items[0].items = items[0].items.concat([{ @@ -161,6 +166,15 @@ Ext4.define('onprc_ehr.panel.SnapshotPanel', { emptyText: 'There are no active medications' }]); + + //Sdded: 10-28-2019 R.Blasa + items[0].items = items[0].items.concat([{ + name: 'sdrug', + xtype: 'ehr-snapshotchildpanel', + headerLabel: 'Sustained Release Medication', + emptyText: 'There are no active medications' + }]); + if (this.showActionsButton){ items.push({ xtype: 'onprc_ehr-clinicalactionsbutton', //Modified: 6-13-2016 R.Blasa @@ -230,8 +244,13 @@ Ext4.define('onprc_ehr.panel.SnapshotPanel', { this.appendFosterChildtResults(toSet, results.getFosterChild()); + //Added: 12-20-2018 R.Blasa + this.appendLastKnownLocationResults(toSet, results.getLastKnownlocation()); + + //Added: 10-4-2019 R.Bl;asa + this.appendDrugRecords(toSet, results.getActiveDrugs()); - if (this.showExtendedInformation){ + if (this.showExtendedInformation){ this.appendBirthResults(toSet, results.getBirthInfo(), results.getBirth()); this.appendDeathResults(toSet, results.getDeathInfo()); this.appendParentageResults(toSet, results.getParents()); @@ -335,21 +354,122 @@ Ext4.define('onprc_ehr.panel.SnapshotPanel', { }, - //Added: 2-21-2017 R.Blasa Display Infant cage mate under 1 yr + //Added: 4-20-2017 R.Blasa Display Infant cage mate under 1 yr appendFosterChildtResults: function(toSet, results){ + var values = []; + if (results) + { + Ext4.each(results, function(row){ + var foster = row.FosterChild; + + values.push(foster); + + }, this); + + } + + toSet['fosterinfants'] = values.length ? values.join('
') : 'None'; + }, + + //Added: 12-20-2018 R.Blasa Last Known Locatoni + appendLastKnownLocationResults: function(toSet, results){ + var values = []; if (results) { - toSet['fosterinfants'] = results[0].FosterChild; + Ext4.each(results, function(row){ + var lastlocation = row.location; + + values.push(lastlocation); + + }, this); + } - else + + toSet['lastlocation'] = values.length ? values.join('
') : 'None'; + + }, + + + //Added: 10-4-2019 R.Blasa Display 72 hour Drug's given + appendDrugRecords2: function(toSet, results){ + var values = []; + if (results) { - toSet['fosterinfants'] = 'None'; + Ext4.each(results, function(row){ + var foster = row.FosterChild; + + values.push(foster); + + }, this); + } + toSet['fosterinfants'] = values.length ? values.join('
') : 'None'; + }, + //Added: 10-7-2019 R.Blasa + appendDrugRecords: function(toSet, rows){ + var el = this.down('panel[name=sdrug]'); + if (!el) + return; + + if (rows && rows.length){ + Ext4.each(rows, function(r){ + if (r.date){ + var date = LDK.ConvertUtils.parseDate(r.date); + //Modified: 11-6-2019 R.Blasa Compute elapse time in hours + var now = new Date(); + r.ElapseHours = Ext4.util.Format.round(Ext4.Date.getElapsed(date, now) / (1000 * 60 *60), 0); + + } + if (r.enddate){ + var enddate = LDK.ConvertUtils.parseDate(r.enddate); + + } + }, this); + } + + el.appendTable({ + rows: rows + }, this.getDrugColumns()); + }, + + getDrugColumns: function(){ + return [{ + name: 'meaning', + label: 'Medication' + + },{ + name: 'amountAndVolume', + label: 'Amount', + attrs: { + style: 'white-space: normal !important;"' + } + },{ + name: 'route', + label: 'Route' + },{ + name: 'date', + label: 'Start Date' + },{ + name: 'ElapseHours', + label: 'Hours Elapsed' + + },{ + name: 'enddate', + label: 'End Date' + + },{ + name: 'remark', + label: 'Remark' + },{ + name: 'category', + label: 'Category' + }]; + }, appendWeightResults: function(toSet, results){ var text = []; @@ -385,7 +505,64 @@ Ext4.define('onprc_ehr.panel.SnapshotPanel', { toSet['weights'] = text.length ? '' + text.join('') + '
' : null; }, + //Modified: 6-13-2017 R.Blasa + appendRoommateResults: function(toSet, results, id){ + var cagemates = 0; + var animals = []; + var pairingType; + + if (results && results.length){ + var row = results[0]; + if (row.animals){ + animals = row.animals.replace(/( )*,( )*/g, ','); + animals = animals.split(','); + animals.sort(); + animals = animals.remove(id); + + } + + pairingType = row.category; + } + + var values = []; + if (results){ + Ext4.each(results, function(row){ + if (row.animals){ + animals = row.animals.replace(/( )*,( )*/g, ','); + animals = animals.split(',') + animals.sort(); + animals = animals.remove(id); + values.push(animals); + + } + + }, this); + } + + //Modified: 8-22-2017 R.Blasa Provide link to Snapshot report + var url1 = '' + animals[0] +''; + var url2 = '' + animals[1] +''; + var url3 = '' + animals[2] +''; + toSet['cagemates'] = cagemates; + toSet['pairingType'] = pairingType; + + if (animals.length > 3){ + toSet['cagemates'] = animals.length + ' animals'; + } + else if (animals.length == 0){ + toSet['cagemates'] = 'None'; + } + else if (animals.length == 1) { + toSet['cagemates'] = url1; + } + else if (animals.length == 2) { + toSet['cagemates'] = url1 + '
' + url2 ; + } + else if (animals.length == 3) { + toSet['cagemates'] = url1 + '
' + url2 + '
' + url3; + } + }, appendParentageResults: function(toSet, results){ if (results){ var parentMap = {}; @@ -428,6 +605,109 @@ Ext4.define('onprc_ehr.panel.SnapshotPanel', { } }, + //Modified: 12-20-2018 R.Blasa + appendDemographicsResults: function(toSet, row, id){ + if (!row){ + console.log('Id not found'); + return; + } + + var animalId = row.getId() || id; + if (!Ext4.isEmpty(animalId)){ + toSet['animalId'] = id; + } + + var status = row.getCalculatedStatus() || 'Unknown'; + toSet['calculated_status'] = '' + status + ''; + + toSet['species'] = row.getSpecies(); + toSet['geographic_origin'] = row.getGeographicOrigin(); + toSet['gender'] = row.getGender(); + toSet['age'] = row.getAgeInYearsAndDays(); + + var location; + if (row.getActiveHousing() && row.getActiveHousing().length){ + var housingRow = row.getActiveHousing(); + location = ''; + if (!Ext4.isEmpty(row.getCurrentRoom())) + location = row.getCurrentRoom(); + if (!Ext4.isEmpty(row.getCurrentCage())) + location += ' / ' + row.getCurrentCage(); + + if (location){ + if (this.showLocationDuration && housingRow.date){ + var date = LDK.ConvertUtils.parseDate(housingRow.date); + if (date) + location += ' (' + date.format(LABKEY.extDefaultDateFormat) + ')'; + } + } + } + + toSet['location'] = location || 'No active housing'; + + }, + + //Modified: 5-10-2018 R.Blasa + appendFlags: function(toSet, results){ + var values = []; + var behavevalues = []; + var category; + if (results){ + Ext4.each(results, function(row){ + category = row['flag/category']; + var highlight = row['flag/category/doHighlight']; + var omit = row['flag/category/omitFromOverview']; + + //skip + if (omit === true) + return; + + if (category) + category = Ext4.String.trim(category); + + // var val = row['flag/value']; + var text ; + var behavetext; + + if (category == 'Behavior Flag') + { + behavetext = category + ': ' + row['flag/value']; + if (behavetext) + behavevalues.push(behavetext); + + } + else + { + text = category + ': ' + row['flag/value']; + if (text && highlight) + text = '' + text + ''; + if (text) + values.push(text); + } + + + }, this); + + if (values.length) { + values = Ext4.unique(values); + } + + if (behavevalues.length) { + behavevalues = Ext4.unique(behavevalues); + } + } + + toSet['flags'] = values.length ? '' + values.join('
') + '
' : null; + + if (behavevalues.length) { + toSet['behaviorflag'] = behavevalues.length ? '' + behavevalues.join('
') + '
' : null; + } + else + { + toSet['behaviorflag'] = 'None' + } + }, + //Modified: 11-25-2016 R.Blasa getExtendedItems: function(){ return [{ diff --git a/onprc_ehr/resources/web/onprc_ehr/window/AddAnimalsWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/AddAnimalsWindow.js new file mode 100644 index 000000000..1e5e86487 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/window/AddAnimalsWindow.js @@ -0,0 +1,394 @@ +/* + * Copyright (c) 2013-2015 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * @class + * This is the panel that appears when hitting the 'Add Bulk' button on EHR grids. It provides a popup to find the set of + * distinct animal IDs based on room, case, etc. + * + * @cfg targetStore + * @cfg formConfig + */ + +//Created: 1-9-2018 R.Blasa + +Ext4.define('EHR.window.AddAnimalsWindow', { + extend: 'Ext.window.Window', + + MAX_ANIMALS: 350, + + initComponent: function(){ + Ext4.apply(this, { + title: 'Choose Animals', + modal: true, + closeAction: 'destroy', + border: true, + bodyStyle: 'padding:5px', + width: 450, + defaults: { + width: 400, + labelWidth: 140, + border: false, + bodyBorder: false + }, + items: [{ + html: 'This helper is designed to quickly add records to the grid below. You can look up animals in a variety of different ways. For each animal, one record will be created. If you check the \'Bulk Edit\' box, you will be prompted to fill out values for the other fields. If not, one row will be created per animal with blank values.', + style: 'padding-bottom: 10px;' + },{ + xtype: 'radiogroup', + itemId: 'radio', + fieldLabel: 'Choose Type', + columns: 1, + defaults: { + xtype: 'radio', + name: 'type' + }, + items: [{ + inputValue: 'animal', + boxLabel: 'List of Animals', + checked: true + },{ + inputValue: 'location', + boxLabel: 'Location' + },{ + inputValue: 'animalGroup', + boxLabel: 'Animal Group' + },{ + inputValue: 'project', + boxLabel: 'Project/Protocol' + }], + listeners: { + scope: this, + change: this.onTypeChange + } + },{ + xtype: 'checkbox', + fieldLabel: 'Bulk Edit Values', + helpPopup: 'If checked, you will be prompted with a screen that lets you bulk edit the records that will be created. This is often very useful when adding many similar records.', + itemId: 'chooseValues' + },{ + html: '
', + style: 'padding-top: 5px;padding-bottom: 5px;' + },{ + xtype: 'form', + itemId: 'theForm', + defaults: { + width: 400, + labelWidth: 140, + border: false + } + }], + buttons: [{ + text: 'Submit', + scope: this, + handler: function(btn){ + this.getAnimals(); + } + },{ + text: 'Close', + handler: function(btn){ + btn.up('window').hide(); + } + }] + }); + + this.callParent(arguments); + + this.animalHandler(); + }, + + onTypeChange: function(field, val, oldVal){ + if (!val || !val.type) + return; + + var method = val.type + 'Handler'; + LDK.Assert.assertTrue('Unknown handler in AddAnimalsWindow: ' + method, Ext4.isFunction(this[method])); + + if (Ext4.isFunction(this[method])){ + this[method](); + } + + }, + + animalHandler: function(){ + var form = this.down('#theForm'); + form.removeAll(); + form.add({ + html: 'Either type of cut/paste a list of Animal IDs into the box below. They can be separated by either commas, spaces, or line breaks.', + style: 'padding-bottom: 10px;' + },{ + xtype: 'textarea', + height: 100, + itemId: 'subjArea', + fieldLabel: 'Id(s)' + }); + + form.getAnimals = function(){ + //we clean up, combine subjects + var subjectList = LDK.Utils.splitIds(this.down('#subjArea').getValue(), true); + if(subjectList.length > 0){ + this.addSubjects(subjectList) + } + else { + Ext4.Msg.alert('Error', 'Must enter at least 1 animal Id'); + } + } + }, + + addSubjects: function(subjectList){ + if (subjectList.length && this.targetStore){ + subjectList = Ext4.Array.unique(subjectList); + if (subjectList.length > this.MAX_ANIMALS){ + Ext4.Msg.alert('Error', 'Too many animals were returned: ' + subjectList.length); + return; + } + + var records = []; + Ext4.Array.forEach(subjectList, function(s){ + records.push(this.targetStore.createModel(Ext4.isObject(s) ? s : {Id: s})); + }, this); + + var choose = this.down('#chooseValues').getValue(); + if (choose){ + Ext4.create('EHR.window.BulkEditWindow', { + suppressConfirmMsg: true, + records: records, + targetStore: this.targetStore, + formConfig: this.formConfig + }).show(); + this.close(); + } + else { + this.targetStore.add(records); + } + } + + if (Ext4.Msg.isVisible()) + Ext4.Msg.hide(); + + this.close(); + }, + + locationHandler: function(){ + var form = this.down('#theForm'); + form.removeAll(); + form.add([{ + html: 'This will return any animals currently housed in the selected location. You can leave any of the fields blank.', + style: 'padding-bottom: 10px;' + },{ + xtype: 'ehr-areafield', + multiSelect: false, + emptyText: '', + fieldLabel: 'Area', + itemId: 'areaField', + pairedWithRoomField: true, + getRoomField: function(){ + return this.up('form').down('#roomField') + } + },{ + xtype: 'ehr-roomfield', + multiSelect: true, + emptyText: '', + showOccupiedOnly: true, + fieldLabel: 'Room(s)', + itemId: 'roomField', + listeners: { + change: function(field){ + var areaField = field.up('panel').down('#areaField'); + areaField.reset(); + } + } + },{ + xtype: 'ehr-cagefield', + itemId: 'cageField', + fieldLabel: 'Cage(s)' + }]); + + form.getAnimals = function(){ + var room = this.down('#roomField').getValue(); + room = !room || Ext4.isArray(room) ? room : [room]; + + var cage = this.down('#cageField').getValue(); + if (cage){ + cage = cage.split(','); + var cages = []; + Ext4.Array.forEach(cage, function(c){ + cages.push(Ext4.String.trim(c)); + }, this); + cage = cages.join(';'); + } + + var filterArray = this.getBaseFilterArray().concat([LABKEY.Filter.create('isActive', true, LABKEY.Filter.Types.EQUAL)]); + + if (!Ext4.isEmpty(room)) + filterArray.push(LABKEY.Filter.create('room', room.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)); + + if (!Ext4.isEmpty(cage)) + filterArray.push(LABKEY.Filter.create('cage', cage, LABKEY.Filter.Types.EQUALS_ONE_OF)); + + if (filterArray.length == 1){ + Ext4.Msg.alert('Error', 'Must choose a location'); + return; + } + + this.doQuery({ + schemaName: 'study', + queryName: 'housing', + sort: 'room,cage,Id', + filterArray: filterArray + }); + } + }, + + /** + * Can be overridden by subclasses, for example to return only females + */ + getBaseFilterArray: function(){ + return []; + }, + + animalGroupHandler: function(){ + var form = this.down('#theForm'); + form.removeAll(); + form.add([{ + html: 'This will return any animals currently assigned to the selected group. You are allowed to choose more than one animal gropu at a time.', + style: 'padding-bottom: 10px;' + },{ + xtype: 'onprc_ehr-animalgroupfield', + multiSelect: true, + emptyText: '', + itemId: 'groupField' + }]); + + form.getAnimals = function(){ + var group = this.down('#groupField').getValue(); + if (!group){ + Ext4.Msg.alert('Error', 'Must choose a group'); + return; + } + + var filterArray = this.getBaseFilterArray().concat([ + LABKEY.Filter.create('groupId', group.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF), + LABKEY.Filter.create('isActive', true, LABKEY.Filter.Types.EQUAL) + ]); + + this.doQuery({ + schemaName: 'study', + queryName: 'animal_group_members', + filterArray: filterArray + }); + } + }, + + projectHandler: function(){ + var form = this.down('#theForm'); + form.removeAll(); + form.add([{ + html: 'This will return any animals currently assigned to the selected project or protocol. Choose one or the other.', + style: 'padding-bottom: 10px;' + },{ + xtype: 'ehr-projectfield', + emptyText: '', + itemId: 'projectField', + width: 400, + labelWidth: 140, + onlyIncludeProjectsWithAssignments: true + },{ + xtype: 'ehr-protocolfield', + emptyText: '', + itemId: 'protocolField', + width: 400, + labelWidth: 140, + onlyIncludeProtocolsWithAssignments: true + }]); + + form.getAnimals = function(){ + var projectId = this.down('#projectField').getValue(); + var protocol = this.down('#protocolField').getValue(); + if (!projectId && !protocol){ + Ext4.Msg.alert('Error', 'Must choose a project or protocol'); + return; + } + + if (projectId && protocol){ + Ext4.Msg.alert('Error', 'Cannot pick both a project and protocol'); + return; + } + + var filterArray = this.getBaseFilterArray().concat([LABKEY.Filter.create('isActive', true, LABKEY.Filter.Types.EQUAL)]); + + if (projectId) + filterArray.push(LABKEY.Filter.create('project', projectId, LABKEY.Filter.Types.EQUAL)); + + if (protocol) + filterArray.push(LABKEY.Filter.create('project/protocol', protocol, LABKEY.Filter.Types.EQUAL)); + + this.doQuery({ + schemaName: 'study', + queryName: 'assignment', + filterArray: filterArray + }); + } + }, + + getAnimals: function(){ + this.down('#theForm').getAnimals.call(this); + }, + + doQuery: function(config){ + this.hide(); + Ext4.Msg.wait("Loading..."); + + //find distinct animals matching criteria + LABKEY.Query.selectRows(Ext4.applyIf(config, { + sort: 'Id', + columns: 'Id,Id/curLocation/location', + scope: this, + success: this.onSuccess, + failure: LDK.Utils.getErrorCallback() + })); + }, + + onSuccess: function(results){ + if (!results.rows || !results.rows.length){ + Ext4.Msg.hide(); + Ext4.Msg.alert('', 'No matching animals were found.'); + return; + } + + var records = []; + var hasLocation = this.targetStore.getFields().get('Id/curLocation/location'); + Ext4.Array.forEach(results.rows, function(row){ + if(row.Id){ + var obj = { + Id: row.Id + }; + + if (hasLocation){ + obj['Id/curLocation/location'] = row['Id/curLocation/location']; + } + + records.push(obj); + } + }, this); + + this.addSubjects(records); + } +}); + +EHR.DataEntryUtils.registerGridButton('ADDANIMALST', function(config){ + return Ext4.Object.merge({ + text: 'Add Batch', + tooltip: 'Click to add a batch of animals, either as a list or by location', + handler: function(btn){ + var grid = btn.up('gridpanel'); + + Ext4.create('EHR.window.AddAnimalsWindow', { + targetStore: grid.store, + formConfig: grid.formConfig + }).show(); + } + }, config); +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/window/AddClinicalCasesWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/AddClinicalCasesWindow.js new file mode 100644 index 000000000..2ae50c16d --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/window/AddClinicalCasesWindow.js @@ -0,0 +1,564 @@ + + +//Created: 10-24-2017 R.Blasa + +Ext4.define('EHR.window.AddClinicalCasesWindow', { + extend: 'Ext.window.Window', + caseCategory: 'Clinical', + templateName: 'Limited Visual Exam', + templateStoreId: 'Clinical Observations', + + allowNoSelection: false, + allowReviewAnimals: true, + showAssignedVetCombo: true, + caseDisplayField: 'problemCategories', + caseEmptyText: 'There are no problems associated with this case', + showAllowOpen: false, + + initComponent: function(){ + Ext4.applyIf(this, { + modal: true, + closeAction: 'destroy', + title: 'Add Open ' + this.caseCategory + ' Cases', + border: true, + bodyStyle: 'padding: 5px', + width: 420, + defaults: { + width: 400, + labelWidth: 150, + border: false + }, + items: [{ + html: 'This helper allows you to query open cases and add records for these animals.' + + (this.allowNoSelection ? ' Leave blank to load all areas.' : ''), + style: 'padding-bottom: 10px;' + },{ + xtype: 'ehr-areafield', + itemId: 'areaField' + },{ + xtype: 'ehr-roomfield', + itemId: 'roomField' + },{ + xtype: 'textarea', + fieldLabel: 'Animal(s)', + itemId: 'idField' + },{ + xtype: 'ehr-vetfieldcombo', + fieldLabel: 'Assigned Vet (blank for all)', + itemId: 'assignedVet', + hidden: !this.showAssignedVetCombo, + checked: true + },{ + xtype: 'xdatetime', + fieldLabel: 'Date', + value: new Date(), + itemId: 'date' + },{ + xtype: 'textfield', + fieldLabel: 'Entered By', + value: LABKEY.Security.currentUser.displayName, + itemId: 'performedBy' + },{ + xtype: 'checkbox', + fieldLabel: 'Exclude Animals w/ Obs Entered Today', + itemId: 'excludeToday', + checked: true + },{ + xtype: 'checkbox', + fieldLabel: 'Include Cases Closed For Review', + hidden: !this.showAllowOpen, + itemId: 'includeOpen', + checked: false + },{ + xtype: 'checkbox', + hidden: !this.allowReviewAnimals, + fieldLabel: 'Review Animals First', + itemId: 'reviewAnimals' + }], + buttons: [{ + text:'Submit', + itemId: 'submitBtn', + scope: this, + handler: this.getCases + },{ + text: 'Close', + scope: this, + handler: function(btn){ + btn.up('window').close(); + } + }] + }); + + this.callParent(arguments); + + if (this.templateName){ + LABKEY.Query.selectRows({ + schemaName: 'ehr', + queryName: 'formtemplates', + filterArray: [ + LABKEY.Filter.create('title', this.templateName), + LABKEY.Filter.create('formtype', 'Clinical Observations'), + LABKEY.Filter.create('category', 'Section') + ], + scope: this, + success: function(results){ + LDK.Assert.assertTrue('Unable to find template: ' + this.templateName, results.rows && results.rows.length == 1); + + this.obsTemplateId = results.rows[0].entityid; + }, + failure: LDK.Utils.getErrorCallback() + }); + } + }, + + getCasesFilterArray: function(){ + var filterArray = this.getBaseFilterArray(); + if (!filterArray) + return; + + var includeOpen = this.down('#includeOpen') ? this.down('#includeOpen').getValue() : false; + if (includeOpen){ + filterArray.push(LABKEY.Filter.create('isOpen', true, LABKEY.Filter.Types.EQUAL)); + } + else { + filterArray.push(LABKEY.Filter.create('isActive', true, LABKEY.Filter.Types.EQUAL)); + } + filterArray.push(LABKEY.Filter.create('category', this.caseCategory, LABKEY.Filter.Types.EQUAL)); + + if (this.down('#excludeToday').getValue()){ + filterArray.push(LABKEY.Filter.create('daysSinceLastRounds', 0, LABKEY.Filter.Types.GT)); + } + + var assignedVetField = this.down('#assignedVet'); + if (assignedVetField && assignedVetField.getValue()){ + filterArray.push(LABKEY.Filter.create('assignedvet', assignedVetField.getValue(), LABKEY.Filter.Types.EQUAL)); + } + + return filterArray; + }, + + getBaseFilterArray: function(){ + var area = this.down('#areaField').getValue() || []; + var rooms = EHR.DataEntryUtils.ensureArray(this.down('#roomField').getValue()) || []; + var ids = this.down('#idField').getValue(); + ids = LDK.Utils.splitIds(ids); + + if (!this.allowNoSelection && !area.length && !rooms.length && !ids.length){ + Ext4.Msg.alert('Error', 'Must provide at least one room or an area'); + return; + } + + if (ids.length && (rooms.length || area.length)){ + Ext4.Msg.alert('Error', 'Cannot search on both location and IDs at the same time'); + return; + } + + var filterArray = []; + + if (area.length) + filterArray.push(LABKEY.Filter.create('Id/curLocation/area', area.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)); + + if (rooms.length) + filterArray.push(LABKEY.Filter.create('Id/curLocation/room', rooms.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)); + + if (ids.length) + filterArray.push(LABKEY.Filter.create('Id', ids.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)); + + return filterArray; + }, + + getCases: function(button){ + var filterArray = this.getCasesFilterArray(); + if (!filterArray || !filterArray.length){ + return; + } + + Ext4.Msg.wait("Loading..."); + this.hide(); + + //find distinct animals matching criteria + LABKEY.Query.selectRows({ + requiredVersion: 9.1, + schemaName: 'study', + queryName: 'cases', + sort: 'Id/curlocation/room_sortValue,Id/curlocation/cage_sortValue,Id', + columns: 'Id,Id/curLocation/location,objectid,mostRecentP2,Id/Utilization/use,problemCategories,mostRecentCeg_Plan', + filterArray: filterArray, + scope: this, + success: this.onSuccess, + failure: LDK.Utils.getErrorCallback() + }); + }, + + onSuccess: function(results){ + if (!results || !results.rows || !results.rows.length){ + Ext4.Msg.hide(); + Ext4.Msg.alert('', 'No active cases were found' + (this.down('#excludeToday').getValue() ? '. Note: you selected to exclude those with obs today.' : '.')); + this.close(); + + return; + } + + LDK.Assert.assertNotEmpty('Unable to find targetStore in AddClinicalCasesWindow', this.targetStore); + + var records = []; + this.caseRecordMap = {}; + this.recordData = { + performedby: this.down('#performedBy').getValue(), + date: this.down('#date').getValue() + } + + var idMap = {}; + + Ext4.Array.each(results.rows, function(sr){ + var row = new LDK.SelectRowsRow(sr); + idMap[row.getValue('Id')] = row; + this.caseRecordMap[row.getValue('objectid')] = row; + + var obj = { + Id: row.getValue('Id'), + date: this.recordData.date, + category: 'Clinical', + s: null, + o: null, + a: null, + p: null, + p2: row.getValue('mostRecentP2'), + caseid: row.getValue('objectid'), + remark: null, + CEG_Plan: row.getValue('mostRecentCeg_Plan'), //Added: 10-24-2017 R.Blasa + performedby: this.recordData.performedby, + 'Id/curLocation/location': row.getValue('Id/curLocation/location') + }; + + records.push(this.targetStore.createModel(obj)); + }, this); + + if (this.down('#reviewAnimals').getValue()){ + this.doReviewAnimals(records, idMap); + } + else { + this.addRecords(records); + } + }, + + doReviewAnimals: function(caseRecords, idMap){ + var toAdd = [{ + html: 'Id' + },{ + html: 'Projects/Groups' + },{ + html: 'Include' + }]; + + Ext4.Array.forEach(caseRecords, function(rec){ + var ar = idMap[rec.get('Id')]; + + toAdd.push({ + html: rec.get('Id') + }); + + toAdd.push({ + html: ar.getDisplayValue('Id/Utilization/use') ? ar.getDisplayValue('Id/Utilization/use') : 'None' + }); + + toAdd.push({ + xtype: 'checkbox', + record: rec, + checked: true + }); + }, this); + + Ext4.Msg.hide(); + Ext4.create('Ext.window.Window', { + title: 'Choose Animals To Add', + ownerWindow: this, + closeAction: 'destroy', + width: 450, + modal: true, + defaults: { + border: false + }, + items: [{ + border: false, + bodyStyle: 'padding: 5px;', + items: [{ + border: false, + defaults: { + border: false, + style: 'margin-right: 10px;' + }, + maxHeight: Ext4.getBody().getHeight() * 0.8, + autoScroll: true, + layout: { + type: 'table', + columns: 3 + }, + items: toAdd + },{ + layout: 'hbox', + style: 'padding-top: 15px;', + border: false, + items: [{ + xtype: 'ldk-linkbutton', + text: '[Check All]', + handler: function(btn){ + var cbs = btn.up('window').query('checkbox'); + Ext4.Array.forEach(cbs, function(item){ + item.setValue(true); + }); + } + },{ + border: false, + html: ' ' + },{ + xtype: 'ldk-linkbutton', + style: 'margin-left:5px;', + text: '[Uncheck All]', + handler: function(btn){ + var cbs = btn.up('window').query('checkbox'); + Ext4.Array.forEach(cbs, function(item){ + item.setValue(false); + }); + } + }] + }] + }], + buttons: [{ + xtype: 'button', + text: 'Submit', + scope: this, + handler: this.onSubmit + },{ + xtype: 'button', + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }).show(); + }, + + onSubmit: function(btn){ + var win = btn.up('window'); + var cbs = win.query('checkbox'); + + var records = []; + Ext4.Array.forEach(cbs, function(cb){ + if (cb.getValue()){ + records.push(cb.record); + } + }, this); + + win.close(); + + if (records.length){ + Ext4.Msg.wait('Loading...'); + this.addRecords(records); + } + else { + win.ownerWindow.close(); + } + }, + + addRecords: function(records){ + //check for duplicates + var ids = []; + var duplicateIds = []; + Ext4.Array.forEach(records, function(r){ + if (ids.indexOf(r.get('Id')) > -1){ + duplicateIds.push(r.get('Id')); + } + else { + ids.push(r.get('Id')); + } + }, this); + + if (!duplicateIds.length){ + this.doAddRecords(records); + } + else { + var items = [{ + html: 'Below are animals with multiple open cases. For each animal, select the case to review. Leave blank to skip that animal.', + style: 'padding-bottom: 10px;', + border: false + }]; + + duplicateIds = duplicateIds.sort(); + Ext4.Array.forEach(duplicateIds, function(id){ + //find matching records + var data = []; + Ext4.Array.forEach(records, function(r){ + if (r.get('Id') == id){ + var caseRec = this.caseRecordMap[r.get('caseid')]; + LDK.Assert.assertNotEmpty('Unable to find case record', caseRec); + + data.push({ + value: r.get('caseid'), + display: caseRec.getValue(this.caseDisplayField) || this.caseEmptyText, + caseRecord: r + }); + } + }, this); + + items.push({ + xtype: 'combo', + fieldLabel: id, + animalId: id, + width: 400, + queryMode: 'local', + valueField: 'value', + displayField: 'display', + store: { + type: 'store', + fields: ['value', 'display', 'record'], + data: data + } + }); + }, this); + + Ext4.Msg.hide(); + Ext4.create('Ext.window.Window', { + modal: true, + title: 'Duplicate Open Cases', + bodyStyle: 'padding: 5px', + width: 450, + items: items, + buttons: [{ + text: 'Submit', + scope: this, + handler: function(btn){ + var win = btn.up('window'); + var combos = win.query('combo'); + var map = {}; + Ext4.Array.forEach(combos, function(c){ + map[c.animalId] = c.getValue(); + }, this); + + var nonDupes = []; + Ext4.Array.forEach(records, function(r){ + if (!r){ + console.log('no record'); + return; + } + + if (map.hasOwnProperty(r.get('Id')) && r.get('caseid') != map[r.get('Id')]){ + //no need to actually remove. + //records.remove(r); + } + else { + nonDupes.push(r); + } + }, this); + + win.close(); + this.doAddRecords(nonDupes); + } + },{ + text: 'Cancel', + scope: this, + handler: function(btn){ + btn.up('window').close(); + this.close(); + } + }] + }).show(); + } + }, + + doAddRecords: function(records){ + var toAdd = this.checkForExistingCases(records); + if (toAdd.length){ + this.targetStore.add(toAdd); + + if (this.obsTemplateId){ + this.applyObsTemplate(toAdd); + } + else { + this.onComplete(); + } + } + else { + this.onComplete(); + } + }, + + checkForExistingCases: function(records){ + //check for existing caseids + var existingIds = {}; + this.targetStore.each(function(r){ + if (r.get('caseid')){ + existingIds[r.get('caseid')] = true; + } + }, this); + + var toAdd = []; + Ext4.Array.forEach(records, function(r){ + if (!existingIds[r.get('caseid')]){ + toAdd.push(r); + } + else { + this.hasSkippedDuplicates = true; + } + }, this); + + return toAdd; + }, + + onComplete: function(){ + Ext4.Msg.hide(); + this.close(); + + if (this.hasSkippedDuplicates){ + Ext4.Msg.alert('Skipped Animals', 'One or more cases were skipped because they are already in this form'); + } + }, + + applyObsTemplate: function(caseRecords){ + var records = []; + Ext4.Array.forEach(caseRecords, function(rec){ + records.push({ + Id: rec.get('Id'), + caseid: rec.get('caseid'), + date: this.recordData.date, + performedby: this.recordData.performedby + }); + }, this); + + EHR.window.ApplyTemplateWindow.loadTemplateRecords(function(recMap){ + if (!recMap || LABKEY.Utils.isEmptyObj(recMap)){ + this.onComplete(); + return; + } + + for (var i in recMap){ + var store = Ext4.StoreMgr.get(i); + store.add(recMap[i]); + } + + this.onComplete(); + }, this, this.targetStore.storeCollection, this.obsTemplateId, records); + } +}); + +EHR.DataEntryUtils.registerGridButton('ADDCLINICALCASES', function(config){ + return Ext4.Object.merge({ + text: 'Add Open Cases', + tooltip: 'Click to automatically add SOAP notes based on open cases', + handler: function(btn){ + var grid = btn.up('gridpanel'); + if(!grid.store || !grid.store.hasLoaded()){ + console.log('no store or store hasnt loaded'); + return; + } + + var cellEditing = grid.getPlugin('cellediting'); + if(cellEditing) + cellEditing.completeEdit(); + + Ext4.create('EHR.window.AddClinicalCasesWindow', { + targetStore: grid.store + }).show(); + } + }, config); +}); diff --git a/onprc_ehr/resources/web/onprc_ehr/window/BulkChangeCasesWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/BulkChangeCasesWindow.js index fb8eb0945..d3176019d 100644 --- a/onprc_ehr/resources/web/onprc_ehr/window/BulkChangeCasesWindow.js +++ b/onprc_ehr/resources/web/onprc_ehr/window/BulkChangeCasesWindow.js @@ -48,6 +48,7 @@ Ext4.define('ONPRC_EHR.window.BulkChangeCasesWindow', { caseIds.push(rec.get('caseid')); }, this); + //Modified: 9-10-2018 R.Blasa caseIds = Ext4.unique(caseIds); LABKEY.Query.selectRows({ schemaName: 'study', @@ -56,7 +57,7 @@ Ext4.define('ONPRC_EHR.window.BulkChangeCasesWindow', { scope: this, failure: LDK.Utils.getErrorCallback(), success: this.onLoad, - columns: 'objectid,Id,date,remark,category,reviewdate,enddate' + columns: 'objectid,Id,date,remark,category,reviewdate,lsid,enddate' }); }, diff --git a/onprc_ehr/resources/web/onprc_ehr/window/BulkStrokeRoundsWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/BulkStrokeRoundsWindow.js index 3abdcb1fa..bbb6e7666 100644 --- a/onprc_ehr/resources/web/onprc_ehr/window/BulkStrokeRoundsWindow.js +++ b/onprc_ehr/resources/web/onprc_ehr/window/BulkStrokeRoundsWindow.js @@ -97,13 +97,13 @@ Ext4.define('ONPRC_EHR.window.BulkStrokeRoundsWindow', { errors.push('Row ' + rowIdx + ': not enough items in row'); continue; } - var id = parsed[0][1]; + var id = Ext4.String.trim(parsed[0][1]); if (!id){ errors.push('Row ' + rowIdx + ': missing Id'); return; } - var procedure = parsed[5][1]; - var narrative = parsed[6][1]; + var procedure = Ext4.String.trim(parsed[5][1]); + var narrative = Ext4.String.trim(parsed[6][1]); //var project = this.resolveProjectByName(parsed[4][1], errors, rowIdx); var project = EHR.DataEntryUtils.getDefaultClinicalProject(); var cnt = i; @@ -121,7 +121,7 @@ Ext4.define('ONPRC_EHR.window.BulkStrokeRoundsWindow', { //Procedure if (recordMap.encounters.length){ var clientStore = this.dataEntryPanel.storeCollection.getClientStoreByName('encounters'); - LDK.Assert.assertNotEmpty('Unable to find procedure store in BulkStrokeRoundsWindow', clientStore); + LDK.Assert.assertNotEmpty('Unable to find procedure store in BulkStrokeRoundsWindow ', clientStore); var records = []; for (var i=0;i -1){ + return; + } + + if (!Ext4.isEmpty(row.getValue(field.name))) + obj[field.name] = row.getValue(field.name); + }, this); + + var model = serverStore.addServerModel({}); + model.set(obj); + + this.toAddMap[serverStore.storeId].push(model); + }, this); + } + } + }); + }, this); + + multi.send(this.onLoad, this); + }, + + onLoad: function(){ + Ext4.Msg.hide(); + if (!Ext4.Object.isEmpty(this.toAddMap)){ + for (var storeId in this.toAddMap){ + var targetStore = this.dataEntryPanel.storeCollection.serverStores.get(storeId); + LDK.Assert.assertNotEmpty('Unable to find server store: ' + storeId, targetStore); + + targetStore.suspendEvents(); + targetStore.add(this.toAddMap[storeId]); + targetStore.resumeEvents(); + } + + this.dataEntryPanel.storeCollection.transformServerToClient(); + } + else { + Ext4.Msg.alert('No Records', 'There are no records to add'); + } + + this.close(); + } +}); + +EHR.DataEntryUtils.registerDataEntryFormButton('COPY_TASKS', { + text: 'Copy Previous Task', + name: 'copyFromTask', + itemId: 'copyFromTask', + tooltip: 'Click to copy records from a previously created task', + handler: function(btn){ + var dataEntryPanel = btn.up('ehr-dataentrypanel'); + LDK.Assert.assertNotEmpty('Unable to find dataentrypanel in COPY_TASKS', dataEntryPanel); + + Ext4.create('onprc_ehr.window.CopyTaskWindow', { + dataEntryPanel: dataEntryPanel + }).show(); + } +}); + diff --git a/onprc_ehr/resources/web/onprc_ehr/window/CreateProjectWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/CreateProjectWindow.js index ce613b252..342535c6f 100644 --- a/onprc_ehr/resources/web/onprc_ehr/window/CreateProjectWindow.js +++ b/onprc_ehr/resources/web/onprc_ehr/window/CreateProjectWindow.js @@ -78,6 +78,7 @@ Ext4.define('ONPRC_EHR.window.CreateProjectWindow', { var newForm = Ext4.DomHelper.append(document.getElementsByTagName('body')[0], '
' + '' + + '' + '
'); newForm.submit(); } diff --git a/onprc_ehr/resources/web/onprc_ehr/window/CreateTaskFromRecordsWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/CreateTaskFromRecordsWindow.js new file mode 100644 index 000000000..16d87b08a --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/window/CreateTaskFromRecordsWindow.js @@ -0,0 +1,377 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * @cfg formType + * @cfg taskLabel + */ + +//Created: 1-18-2019 R.Blasa + +Ext4.define('ONPRC_EHR.window.CreateTaskFromRecordsWindow', { + extend: 'Ext.window.Window', + + selectField: 'lsid', + title: 'Create Task', + + statics: { + /** + * This add a button that allows the user to create a task from a list of IDs, that contains one record per ID. It was originally + * created to allow users to create a weight task based on a list of IDs (like animals needed weights). + */ + createTaskFromRecordHandler: function(dataRegionName, formType, taskLabel){ + var dataRegion = LABKEY.DataRegions[dataRegionName]; + var checked = dataRegion.getChecked(); + if (!checked || !checked.length){ + Ext4.Msg.alert('Error', 'No records selected'); + return; + } + + Ext4.create('ONPRC_EHR.window.CreateTaskFromRecordsWindow', { + dataRegionName: dataRegionName, + title: 'Schedule ' + taskLabel + " For Selected Rows", + formType: formType, + taskLabel: taskLabel + }).show(); + } + }, + + initComponent: function(){ + LDK.Assert.assertNotEmpty('Missing formtype in CreateTaskFromRecordsWindow', this.formType); + + Ext4.apply(this, { + modal: true, + closeAction: 'destroy', + width: 400, + items: [{ + xtype: 'form', + itemId: 'theForm', + bodyStyle: 'padding: 5px;', + defaults: { + border: false, + width: 360 + }, + items: [{ + html: 'Total Selected: ' + '

', + border: false + },{ + xtype: 'radiogroup', + itemId: 'type', + defaults: { + name: 'type', + xtype: 'radio' + }, + items: [{ + boxLabel: 'Create New Task', + inputValue: 'createNew', + checked: true + },{ + boxLabel: 'Add To Existing Task', + inputValue: 'addToExisting' + }], + listeners: { + scope: this, + change: function(field, val){ + var panel = this.down('#taskItems'); + panel.removeAll(); + if (val.type == 'createNew'){ + panel.add(this.getTaskItems()); + } + else { + panel.add(this.getAddToExistingItems()); + } + } + } + },{ + xtype: 'form', + itemId: 'taskItems', + items: this.getTaskItems(), + defaults: { + border: false, + width: 360 + } + }] + }], + buttons: this.getButtonCfg() + }); + + this.callParent(); + + this.on('render', function(){ + this.setLoading(true); + this.loadData(); + }, this, {single: true, delay: 100}); + }, + + getAddToExistingItems: function(){ + return [{ + xtype: 'labkey-combo', + itemId: 'taskField', + fieldLabel: 'Choose Task', + labelAlign: 'top', + forceSelection: true, + displayField: 'title', + valueField: 'taskid', + listConfig: { + innerTpl: ['{rowid}: {title}'] + }, + store: { + type: 'labkey-store', + schemaName: 'ehr', + queryName: 'tasks', + filterArray: [ + LABKEY.Filter.create('qcstate/publicData', false, LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('formtype', this.formType, LABKEY.Filter.Types.EQUAL) + ], + columns: 'taskid,assignedto/DisplayName,title,rowid', + sort: '-rowid' + } + }] + }, + + getTaskItems: function(){ + return [{ + xtype: 'textfield', + fieldLabel: 'Task Title', + value: this.taskLabel, + itemId: 'titleField' + },{ + xtype: 'xdatetime', + fieldLabel: 'Date', + value: new Date(), + itemId: 'date' + },{ + xtype: 'combo', + fieldLabel: 'Assigned To', + forceSelection: true, + value: LABKEY.Security.currentUser.id, + queryMode: 'local', + store: { + type: 'labkey-store', + schemaName: 'core', + queryName: 'PrincipalsWithoutAdmin', + columns: 'UserId,DisplayName', + sort: 'Type,DisplayName', + autoLoad: true + }, + displayField: 'DisplayName', + valueField: 'UserId', + itemId: 'assignedTo' + },{ + xtype: 'checkbox', + fieldLabel: 'View Task After Created?', + itemId: 'viewAfterCreate', + checked: true + }] + }, + + getButtonCfg: function(){ + return [{ + text: 'Submit', + itemId: 'submitBtn', + scope: this, + disabled: true, + handler: this.onSubmit + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }]; + }, + + loadData: function(){ + var dataRegion = LABKEY.DataRegions[this.dataRegionName]; + LDK.Assert.assertNotEmpty('Unknown dataregion: ' + this.dataRegionName, dataRegion); + + this.checkedRows = dataRegion.getChecked(); + + LABKEY.Query.selectRows({ + method: 'POST', + requiredVersion: 9.1, + schemaName: dataRegion.schemaName, + queryName: dataRegion.queryName, + sort: 'Id,date', + columns: 'lsid,Id,date,requestid,taskid,qcstate,qcstate/label,qcstate/metadata/isRequest', + filterArray: [LABKEY.Filter.create('lsid', this.checkedRows.join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)], + scope: this, + success: this.onDataLoad, + failure: LDK.Utils.getErrorCallback() + }); + }, + + onDataLoad: function(data){ + if (!data || !data.rows){ + Ext4.Msg.hide(); + Ext4.Msg.alert('Error', 'No records found'); + return; + } + + this.records = []; + var errors = []; + + //first order these rows based on the source dataregion + var sortedRows = data.rows; + var checked = this.checkedRows; + var pk = this.pkCol; + sortedRows = sortedRows.sort(function(a, b){ + var rowA = new LDK.SelectRowsRow(a); + var rowB = new LDK.SelectRowsRow(b); + + var idxA = checked.indexOf(rowA.getValue('lsid')); + var idxB = checked.indexOf(rowB.getValue('lsid')); + LDK.Assert.assertTrue('Unable to find row matching: ' + rowA.getValue('lsid'), idxA > -1); + LDK.Assert.assertTrue('Unable to find row matching: ' + rowB.getValue('lsid'), idxB > -1); + + return idxA > idxB ? 1 : idxA < idxB ? -1 : 0; + }); + + Ext4.Array.forEach(sortedRows, function(json){ + var r = new LDK.SelectRowsRow(json); + if (r.getValue('taskid')){ + errors.push('One or more records is already part of a task and will be skipped.'); + } + else if (!r.getValue('qcstate/metadata/isRequest')){ + errors.push('Only requests can be added to tasks. One or more records was skipped.'); + } + else { + this.records.push(r); + } + }, this); + + if (errors.length){ + errors = Ext4.Array.unique(errors); + Ext4.Msg.alert('Error', errors.join('
')); + } + + var form = this.down('#theForm'); + form.remove(0); + form.insert(0, { + html: 'Total Selected: ' + this.records.length + '

', + border: false + }); + + this.down('#submitBtn').setDisabled(false); + this.setLoading(false); + }, + + onSubmit: function(){ + var records = this.getRecords(); + if (!records || !records.length) + return; + + var type = this.down('#type').getValue().type; + if (type == 'createNew'){ + this.doSaveNew(records); + } + else { + this.doAddToExisting(records); + } + }, + + doAddToExisting: function(records){ + var taskId = this.down('#taskField').getValue(); + if (!taskId){ + Ext4.Msg.alert('Error', 'Must choose a task'); + return; + } + + Ext4.Msg.wait('Saving...'); + + var toSave = []; + Ext4.Array.forEach(records, function(r, idx){ + toSave.push(Ext4.apply({ + taskid: taskId, + QCState: 25, //QCState: Scheduled Modified: 1-11-2019 R.Blasa Set after adding to an existing task id + formSort: idx + }, r)); + }, this); + + var dataRegion = LABKEY.DataRegions[this.dataRegionName]; + LABKEY.Query.updateRows({ + method: 'POST', + schemaName: dataRegion.schemaName, + queryName: dataRegion.queryName, + rows: toSave, + scope: this, + failure: LDK.Utils.getErrorCallback(), + success: this.onComplete + }); + }, + + doSaveNew: function(records){ + var date = this.down('#date').getValue(); + if(!date){ + Ext4.Msg.alert('Error', 'Must enter a date'); + } + + var assignedTo = this.down('#assignedTo').getValue(); + if(!assignedTo){ + Ext4.Msg.alert('Error', 'Must assign to someone'); + } + + var title = this.down('#titleField').getValue(); + if(!title){ + Ext4.Msg.alert('Error', 'Must enter a title'); + } + + Ext4.Msg.wait('Saving...'); + + var dataRegion = LABKEY.DataRegions[this.dataRegionName]; + var existingRecords = {}; + existingRecords[dataRegion.queryName] = []; + + Ext4.Array.forEach(records, function(r){ + LDK.Assert.assertNotEmpty('Record does not have an LSID', r.lsid); + existingRecords[dataRegion.queryName].push({lsid: r.lsid, formSort: r.formSort}); + }, this); + + EHR.Utils.createTask({ + initialQCState: 'Scheduled', + existingRecords: existingRecords, + taskRecord: {duedate: date, assignedTo: assignedTo, category: 'task', title: title, formType: this.formType}, + scope: this, + success: function(response, options, config){ + Ext4.Msg.hide(); + + var viewAfterCreate = this.down('#viewAfterCreate').getValue(); + this.close(); + + if (viewAfterCreate){ + window.location = LABKEY.ActionURL.buildURL('ehr', 'dataEntryForm', null, {taskid: config.taskId, formType: this.formType}); + } + else { + LABKEY.DataRegions[this.dataRegionName].refresh(); + } + }, + failure: LDK.Utils.getErrorCallback() + }); + }, + + getRecords: function(){ + var toSave = []; + Ext4.each(this.records, function(r, idx){ + toSave.push({ + lsid: r.getValue('lsid'), + formSort: idx + }); + }, this); + + if (!toSave.length){ + Ext4.Msg.alert('Nothing To Save', 'There are no records to save'); + return null; + } + + return toSave; + }, + + onComplete: function(){ + Ext4.Msg.hide(); + var dataRegion = LABKEY.DataRegions[this.dataRegionName]; + dataRegion.selectNone(); + dataRegion.refresh(); + this.close(); + } +}); diff --git a/onprc_ehr/resources/web/onprc_ehr/window/ManageCasesWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/ManageCasesWindow.js new file mode 100644 index 000000000..4b29415f8 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/window/ManageCasesWindow.js @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * @cfg {String} animalId + */ + +//Created: 1-22-2018 R.Blasa + +Ext4.define('ONPRC_EHR.window.ManageCasesWindow', { + extend: 'EHR.window.ManageCasesWindow', + + width: 1100, + minHeight: 50, + + initComponent: function(){ + Ext4.apply(this, { + title: 'Manage Cases: ' + this.animalId, + modal: true, + closeAction: 'destroy', + items: [{ + xtype: 'onprc_ehr-managecasespanel', + animalId: this.animalId, + date:this.date, + hideButtons: true + }], + buttons: this.getButtonConfig() + }); + + this.callParent(arguments); + }, + + getButtonConfig: function(){ + var buttons = ONPRC_EHR.panel.ManageCasesPanel.getButtonConfig(); + buttons.push({ + text: 'Close', + handler: function(btn){ + btn.up('window').close(); + } + }); + + return buttons; + } +}); + + + + + diff --git a/onprc_ehr/resources/web/onprc_ehr/window/ManageRecordWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/ManageRecordWindow.js new file mode 100644 index 000000000..04d2aaa45 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/window/ManageRecordWindow.js @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2013-2015 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * @cfg schemaName + * @cfg queryName + * @cfg pkCol + * @cfg pkValue + */ +Ext4.define('ONPRC_EHR.window.ManageRecordWindow', { + extend: 'Ext.window.Window', + + statics: { + buttonHandler: function(Id, objectId, queryName, dataRegionName){ + LDK.Assert.assertNotEmpty('No objectid provided to ManageRecordWindow.buttonHandler', objectId); + LDK.Assert.assertNotEmpty('No queryName provided to ManageRecordWindow.buttonHandler', queryName); + + Ext4.create('ONPRC_EHR.window.ManageRecordWindow', { + schemaName: 'study', + queryName: queryName, + maxItemsPerCol: 11, + pkCol: 'objectid', + pkValue: objectId, + listeners: { + scope: this, + save: function(){ + if (dataRegionName && LABKEY.DataRegions[dataRegionName]){ + LABKEY.DataRegions[dataRegionName].refresh(); + } + } + } + }).show(); + } + }, + initComponent: function(){ + Ext4.apply(this, { + modal: true, + closeAction: 'destroy', + minWidth: 600, + minHeight: 200, + items: [{ + border: false, + style: 'padding: 5px;', + html: 'Loading...' + }], + buttons: [{ + text: 'Submit', + scope: this, + requiredQC: 'Completed', + targetQC: 'Completed', + errorThreshold: 'INFO', + disableOn: 'WARN', + disabled: true, + handler: this.onSubmit + },{ + text: 'Re-validate Form', + scope: this, + handler: function(btn){ + var form = this.down('#formPanel'); + var rec = form.getRecord(); + if (!rec) + return; + + this.down('#dataEntryPanel').storeCollection.validateAll(); + } + },{ + text: 'Cancel', + handler: function(btn){ + btn.up('window').close(); + } + }] + }); + + this.callParent(); + this.addEvents('save'); + + LABKEY.Ajax.request({ + url: LABKEY.ActionURL.buildURL('ehr', 'dataEntryFormJsonForQuery', null), + params: { + schemaName: this.schemaName, + queryName: this.queryName + }, + scope: this, + failure: LDK.Utils.getErrorCallback(), + success: LABKEY.Utils.getCallbackWrapper(this.onFormLoad, this) + }) + }, + + onSubmit: function(btn) { + var form = this.down('#formPanel'); + var rec = form.getRecord(); + if (!rec) + return; + if (!rec.get('taskid')) { + var tsk = LABKEY.Utils.generateUUID().toUpperCase(); + LABKEY.Query.insertRows({ + schemaName: 'ehr', + queryName: 'tasks', + rows: [{ + taskid: tsk, + formtype: 'treatments', + title: 'Medication/Diet', + assignedto: LABKEY.Security.currentUser.userid, + qcstate: EHR.Security.getQCStateByLabel('Completed').RowId, + datecompleted: new Date(), + category: 'Task' + }], + scope: this, + failure: EHR.Utils.onError, + success: function () { + Ext4.Msg.hide(); + } + }); + rec.set('taskid', tsk); + } + this.down('#dataEntryPanel').onSubmit(btn); + }, + onFormLoad: function(results){ + this.formResults = results; + this.setTitle(this.formResults.formConfig.label); + + if (results.cssDependencies){ + LABKEY.requiresCss(results.cssDependencies); + } + + if (results.jsDependencies){ + LABKEY.requiresScript(results.jsDependencies, this.onJsLoad, this, true); + } + else { + this.onJsLoad(); + } + }, + + onJsLoad: function(){ + var name = Ext4.id(); + + Ext4.define(name, { + extend: this.formResults.formConfig.javascriptClass, + alias: 'widget.' + name, + extraMetaData: this.extraMetaData, + applyConfigToServerStore: function(cfg){ + cfg = this.callParent(arguments); + cfg.filterArray = cfg.filterArray || []; + cfg.filterArray.push(LABKEY.Filter.create(this.pkCol, this.pkValue, LABKEY.Filter.Types.EQUAL)); + + return cfg; + }, + onStoreCollectionInitialLoad: function(){ + var item = this.getItemConfig()[0]; + item.itemId = 'formPanel'; + item.maxItemsPerCol = item.maxItemsPerCol || 9; + item.maxFieldWidth = EHR.form.Panel.defaultFieldWidth; + + var win = this.ownerWindow; + if (win.maxItemsPerCol) + item.maxItemsPerCol = win.maxItemsPerCol; + + var formPanel = Ext4.widget(item); + var cols = formPanel.items.get(0).items.getCount(); + var width = cols * (EHR.form.Panel.defaultFieldWidth + 10); + + formPanel.down('#columnPanel').setWidth(width); + + this.removeAll(); + this.add(formPanel); + win.removeAll(); + win.setWidth(width + 20); + win.add(this); + win.center(); + + this.hasStoreCollectionLoaded = true; + }, + getToolbarItems: function(){ + var win = this.up('window'); + if (!win){ + //NOTE: this can occur once after the window is closed, but before the store returns + return; + } + + return win.getDockedItems('toolbar[dock="bottom"]'); + }, + getButtons: function(){ + return []; + } + }); + + var dataEntryPanel = Ext4.widget({ + xtype: name, + ownerWindow: this, + itemId: 'dataEntryPanel', + pkCol: this.pkCol, + pkValue: this.pkValue, + hideErrorPanel: true, + formConfig: this.formResults.formConfig, + onStoreCollectionCommitComplete: this.onStoreCollectionCommitComplete + }); + }, + + onStoreCollectionCommitComplete: function(sc, extraContext){ + Ext4.Msg.hide(); + var win = this.up('window'); + win.fireEvent('save', this, sc); + win.close(); + } +}); \ No newline at end of file diff --git a/onprc_ehr/resources/web/onprc_ehr/window/MarkAssignmentCompletedWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/MarkAssignmentCompletedWindow.js index c7707fe8e..1576b8e85 100644 --- a/onprc_ehr/resources/web/onprc_ehr/window/MarkAssignmentCompletedWindow.js +++ b/onprc_ehr/resources/web/onprc_ehr/window/MarkAssignmentCompletedWindow.js @@ -69,6 +69,9 @@ Ext4.define('ONPRC_EHR.window.MarkAssignmentCompletedWindow', { schemaName: 'ehr_lookups', queryName: 'animal_condition', columns: 'code,meaning', + filterArray: [ + LABKEY.Filter.create('datedisabled',null, LABKEY.Filter.Types.ISBLANK) + ], autoLoad: true, sort: 'code' } diff --git a/onprc_ehr/resources/web/onprc_ehr/window/ONPRC_AddScheduledTreatmentWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/ONPRC_AddScheduledTreatmentWindow.js index a66f6d1f2..43ebefc15 100644 --- a/onprc_ehr/resources/web/onprc_ehr/window/ONPRC_AddScheduledTreatmentWindow.js +++ b/onprc_ehr/resources/web/onprc_ehr/window/ONPRC_AddScheduledTreatmentWindow.js @@ -59,30 +59,32 @@ Ext4.define('ONPRC_EHR.window.AddScheduledTreatmentWindow', { xtype: 'ehr-roomfield', itemId: 'roomField' },*/{ - xtype: 'checkcombo', - forceSelection: true, - multiSelect: true, - addAllSelector: true, - fieldLabel: 'Treatment Time', - itemId: 'timeField', - displayField: 'treatmentTime', - valueField: 'timeValue', - store: { - type: 'array', - fields: ['timeValue','treatmentTime'], - data: [ - ['800', '8:00 AM'], - ['1200', '12:00 Noon'], - ['1600', '4:00 PM'], - ['2000', '8:00 PM'] - ] - } - },{ - xtype: 'ehr-snomedtreatmentcombo', - defaultSubset: 'Post Op Meds' , - fieldLabel: 'Treatment(s)', - itemId: 'code' - },/* + xtype: 'checkcombo', + forceSelection: true, + multiSelect: true, + addAllSelector: true, + fieldLabel: 'Treatment Time', + itemId: 'timeField', + displayField: 'treatmentTime', + valueField: 'timeValue', + store: { + type: 'array', + fields: ['timeValue','treatmentTime'], + data: [ + ['800', '8:00 AM'], + ['1200', '12:00 Noon'], + ['1400', '2:00 PM'], + ['1600', '4:00 PM'], + ['2000', '8:00 PM'] + ] + } + },{ + xtype: 'ehr-snomedtreatmentcombo', //Modified 6-22-2015 Blasa + defaultSubset: 'Post Op Meds' , + fieldLabel: 'Treatment(s)', + itemId: 'code' + }, + /* { xtype: 'checkcombo', forceSelection: true, diff --git a/onprc_ehr/resources/web/onprc_ehr/window/SedationWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/SedationWindow.js new file mode 100644 index 000000000..6afecefb4 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/window/SedationWindow.js @@ -0,0 +1,463 @@ +/* + * Copyright (c) 2013-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * @cfg targetGrid + * @cfg parentStore + * @cfg label + */ + +//Created: 8-28-2020 R.Blasa +Ext4.define('EHR.window.SedationWindow', { + extend: 'EHR.window.CopyFromSectionWindow', + alias: 'widget.ehr-sedationwindow', + + defaultRound: 5, + + initComponent: function(){ + this.getParentRecords(); + + Ext4.apply(this, { + width: 860, + title: 'Add Sedations', + items: [{ + html: 'This helper allows you to fill out sedation drugs for each animal in the ' + this.sourceName + ' section. Choose which IDs and type of sedation to use from the list below. Note: this will default to the most recent weight for the animal; however, the weight can be adjusted below.', + style: 'margin-bottom: 10px;' + },{ + layout: 'hbox', + style: 'margin-bottom: 10px;', + items: [{ + itemId: 'lotField', + labelWidth: 120, + style: 'margin-right: 10px;', + fieldLabel: 'Lot # (optional)', + xtype: 'textfield' + },{ + itemId: 'globalDose', + fieldLabel: 'Reset Dosage', + style: 'margin-right: 10px;', + width: 180, + labelWidth: 120, + triggerToolTip: 'If selected, this will change the dose used for all animals and recalculate the amount', + xtype: 'ehr-triggernumberfield', + triggerCls: 'x4-form-search-trigger', + onTriggerClick: function(){ + var val = this.getValue(); + if (Ext4.isNumber(val)){ + var dosageFields = this.up('ehr-sedationwindow').query("numberfield[fieldName='dosage']"); + Ext4.Array.forEach(dosageFields, function(field){ + field.setValue(val); + }, this); + } + } + },{ + itemId: 'roundField', + width: 220, + labelWidth: 150, + value: this.defaultRound, + fieldLabel: 'Round To Nearest', + triggerToolTip: 'If selected, this will change rounding used for drug amounts', + xtype: 'ehr-triggernumberfield', + triggerCls: 'x4-form-search-trigger', + onTriggerClick: function(){ + var val = this.getValue(); + if (val){ + var dosageFields = this.up('ehr-sedationwindow').query("numberfield[fieldName='dosage']"); + Ext4.Array.forEach(dosageFields, function(field){ + field.fireEvent('change', field, val); + }, this); + } + } + }] + },{ + itemId: 'animalIds', + items: this.getInitialItems() + }] + }); + + this.callParent(); + + this.on('beforeshow', function(window){ + if (!this.parentRecords.length){ + Ext4.Msg.alert('No Records', 'There are no records to copy. Note: only records with an Id/Date can be copied.'); + return false; + } + }, this); + + this.getWeights(); + }, + + getWeights: function(){ + var ids = {}; + Ext4.Array.forEach(this.parentRecords, function(r){ + ids[r.get('Id')] = true; + }, this); + + this.animalIds = Ext4.Object.getKeys(ids); + + EHR.DataEntryUtils.getWeights(this.targetGrid.store.storeCollection, this.animalIds, this.onLoad, this, true); + }, + + onLoad: function(weightMap){ + this.weights = weightMap; + + EHR.DemographicsCache.getDemographics(this.animalIds, this.onDemographicsLoad, this, -1); + }, + + onDemographicsLoad: function(ids, animalRecordMap){ + var target = this.down('#animalIds'); + target.removeAll(); + + this.animalRecordMap = animalRecordMap; + + var toAdd = this.getFinalItems(); + if (toAdd.length) + target.add(toAdd); + else + target.add({ + html: 'No animals found' + }); + }, + + getInitialItems: function(){ + return [{ + border: false, + html: 'Loading...' + }] + }, + + getFinalItems: function(){ + var numCols = 7; + var items = [{ + html: 'Animal' +// },{ +// html: '' //placeholder for project + },{ + html: 'Date' + },{ + html: 'Drug' + },{ + html: 'Weight (kg)' + },{ + html: 'Dosage (mg/kg)' + },{ + html: 'Amount (mg)' + },{ + html: 'Skip?' + }]; + + var keys = {}, key, orderedKeys = []; + Ext4.Array.forEach(this.parentRecords, function(record){ + key = record.get('Id'); + if (orderedKeys.indexOf(key) == -1) + orderedKeys.push(key); + + keys[key] = keys[key] || { + Id: record.get('Id'), + project: record.get('project'), + dates: [], + total: 0 + }; + + keys[key].total++; + keys[key].dates.push(record.get('date')) + }, this); + + var existingIds = this.getExistingIds(['Id']); + Ext4.Array.forEach(orderedKeys, function(key){ + var o = keys[key]; + var ar = this.animalRecordMap[key]; + var flags = ar.getActiveFlags(); + var msgs = []; + if (flags){ + Ext4.Array.forEach(flags, function(f){ + if ((f['flag/category'] == 'Alert' || f['flag/category'] == 'Flag') && (f['flag/value'] ) && (f['flag/value'].match(/Ketamine/i) || (f['flag/value'].match(/Sedation/i)) || f['flag/value'].match(/Telazol/i))){ + msgs.push(f['flag/value']); + } + }, this); + } + + items.push({ + xtype: 'displayfield', + value: o.Id, + key: key, + fieldName: 'Id' + }); + + items.push({ + xtype: 'hidden', + value: o.project, + key: key, + fieldName: 'project' + }); + + var dates = []; + var minDate; + + Ext4.Array.forEach(o.dates, function(date){ + if (!minDate || date < minDate) + minDate = date; + + dates.push(date.format(LABKEY.extDefaultDateTimeFormat)); + }, this); + + items.push({ + xtype: 'xdatetime', + width: 250, + format: LABKEY.extDefaultDateTimeFormat, + timeFormat: 'H:i', + fieldName: 'date', + key: key, + value: minDate + }); + + items.push({ + xtype: 'combo', + key: key, + fieldName: 'code', + valueField: 'code', + displayField: 'displayField', + value: 'E-70590', + store: { + type: 'store', + fields: ['code', 'displayField', 'dosage'], + data: [ + {code: 'E-70590', displayField: 'Ketamine', dosage: 10}, + {code: 'E-YY992', displayField: 'Telazol', dosage: 3}, + {code: 'none', displayField: 'None', dosage: null} + ] + }, + listeners: { + select: function(field, recs){ + if (!recs || recs.length != 1) + return; + + var round = field.up('ehr-sedationwindow').down('#roundField').getValue(); + var dose = recs[0].get('dosage'); + var weightField = field.up('panel').down("field[key='" + field.key + "][fieldName='weight']"); + var dosageField = field.up('panel').down("numberfield[key='" + field.key + "][fieldName='dosage']"); + var amountField = field.up('panel').down("numberfield[key='" + field.key + "][fieldName='amount']"); + LDK.Assert.assertNotEmpty('Unable to find target field in SedationWindow', dosageField); + + var amount = weightField.getValue() ? Ext4.util.Format.round(weightField.getValue() * dose, 1) : null; + + dosageField.setValue(dose); + + amountField.suspendEvents(); + amountField.setValue(EHR.Utils.roundToNearest(amount, round)); + amountField.resumeEvents(); + } + } + }); + + items.push({ + xtype: 'ldk-numberfield', + hideTrigger: true, + decimalPrecision: 3, + width: 70, + fieldName: 'weight', + key: key, + value: this.weights[o.Id] ? this.weights[o.Id].weight: null, + listeners: { + scope: this, + change: function(field, val){ + var round = field.up('ehr-sedationwindow').down('#roundField').getValue(); + var dosageField = field.up('panel').down("numberfield[key='" + field.key + "][fieldName='dosage']"); + var amountField = field.up('panel').down("numberfield[key='" + field.key + "][fieldName='amount']"); + var weightField = field; + LDK.Assert.assertNotEmpty('Unable to find target field in SedationWindow after weight change', dosageField); + + var amount = weightField.getValue() ? Ext4.util.Format.round(weightField.getValue() * dosageField.getValue(), 1) : null; + + amountField.suspendEvents(); + amountField.setValue(EHR.Utils.roundToNearest(amount, round)); + amountField.resumeEvents(); + } + } + }); + + items.push({ + xtype: 'ldk-numberfield', + hideTrigger: true, + fieldName: 'dosage', + decimalPrecision: 3, + width: 80, + key: key, + value: 10, + listeners: { + scope: this, + change: function(field, val){ + var round = field.up('ehr-sedationwindow').down('#roundField').getValue(); + var dosageField = field; + var weightField = field.up('panel').down("field[key='" + field.key + "][fieldName='weight']"); + var amountField = field.up('panel').down("numberfield[key='" + field.key + "][fieldName='amount']"); + LDK.Assert.assertNotEmpty('Unable to find target field in SedationWindow after dose change', dosageField); + + var amount = weightField.getValue() ? Ext4.util.Format.round(weightField.getValue() * dosageField.getValue(), 1) : null; + + amountField.suspendEvents(); + amountField.setValue(EHR.Utils.roundToNearest(amount, round)); + amountField.resumeEvents(); + } + } + }); + + items.push({ + xtype: 'ldk-numberfield', + hideTrigger: true, + fieldName: 'amount', + decimalPrecision: 3, + width: 80, + key: key, + value: (this.weights[o.Id] && this.weights[o.Id].weight) ? EHR.Utils.roundToNearest(this.weights[o.Id].weight * 10, this.defaultRound) : null, + listeners: { + change: function(field, value){ + var round = field.up('ehr-sedationwindow').down('#roundField').getValue(); + var dosageField = field.up('panel').down("numberfield[key='" + field.key + "][fieldName='dosage']"); + LDK.Assert.assertNotEmpty('Unable to find target field in SedationWindow', dosageField); + + dosageField.suspendEvents(); + dosageField.setValue(null); + dosageField.resumeEvents(); + } + } + }); + + items.push({ + xtype: 'checkbox', + fieldName: 'exclude', + key: key, + checked: existingIds[key] + }); + + items.push({ + colspan: numCols, + bodyStyle: 'padding-bottom: 5px;', + html: (msgs.length ? '**' + msgs.join('
**') + '
' : '') + }); + }, this); + + return [{ + border: false, + itemId: 'theTable', + layout: { + type: 'table', + columns: numCols + }, + defaults: { + border: false, + style: 'margin-left: 5px;margin-right: 5px;' + }, + items: items + }]; + }, + + onSubmit: function(btn){ + var toAdd = []; + var lot = this.down('#lotField').getValue(); + + Ext4.Array.forEach(this.getRows(), function(data){ + if (!data.amount || data.exclude) + return; + + delete data.weight; + + Ext4.apply(data, { + route: 'IM', + dosage_units: data.dosage ? 'mg/kg' : null, + amount_units: 'mg', + performedby: LABKEY.Security.currentUser.displayName, + lot: lot + }); + + toAdd.push(this.targetGrid.store.createModel(data)); + }, this); + + this.close(); + if (toAdd.length){ + this.targetGrid.store.add(toAdd); + } + else { + Ext4.Msg.alert('', 'There are no records to add. If you expected to add sedation records, please look at the \'Skip\' checkbox on the right.'); + } + } +}); + +EHR.DataEntryUtils.registerGridButton('SEDATIONHELPER', function(config){ + return Ext4.Object.merge({ + text: 'Add Sedation(s)', + xtype: 'button', + tooltip: 'Click to add sedation records based on the animals in another section of this form', + listeners: { + beforerender: function(btn){ + var grid = btn.up('gridpanel'); + LDK.Assert.assertNotEmpty('Unable to find gridpanel in COPYFROMSECTION button', grid); + + btn.grid = grid; + + btn.appendButtons.call(btn); + } + }, + menu: { + xtype: 'menu', + items: [{ + text: 'Loading...' + }] + }, + appendButtons: function(){ + this.dataEntryPanel = this.grid.up('ehr-dataentrypanel'); + LDK.Assert.assertNotEmpty('Unable to find dataEntryPanel in COPYFROMSECTION button', this.dataEntryPanel); + + var toAdd = []; + Ext4.Array.forEach(this.dataEntryPanel.formConfig.sections, function(section){ + if (section.name == this.grid.formConfig.name){ + return; + } + + var store = this.dataEntryPanel.storeCollection.getClientStoreByName(section.name); + if (store){ + //only allow copying from sections with an ID field + if (!store.getFields().get('Id')){ + return; + } + + toAdd.push({ + text: 'Copy Ids From: ' + section.label, + scope: this, + sourceSection: section, + handler: function(btn){ + var grid = btn.up('grid'); + LDK.Assert.assertNotEmpty('Unable to find grid in SEDATIONHELPER button', grid); + + var panel = grid.up('ehr-dataentrypanel'); + LDK.Assert.assertNotEmpty('Unable to find dataEntryPanel in SEDATIONHELPER button', panel); + + var store = panel.storeCollection.getClientStoreByName(btn.sourceSection.name); + LDK.Assert.assertNotEmpty('Unable to find client store: ' + btn.sourceSection.name + ' in SEDATIONHELPER button', store); + + if (store){ + Ext4.create('EHR.window.SedationWindow', { + sourceName: btn.sourceSection.label, + targetGrid: grid, + parentStore: store + }).show(); + } + } + }); + } + }, this); + + this.menu.removeAll(); + if (toAdd.length){ + this.menu.add(toAdd); + } + else { + this.menu.add({ + text: 'There are no other sections' + }) + } + } + }); +}); diff --git a/onprc_ehr/resources/web/onprc_ehr/window/SurgeryPostOpMedsWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/SurgeryPostOpMedsWindow.js new file mode 100644 index 000000000..671580d94 --- /dev/null +++ b/onprc_ehr/resources/web/onprc_ehr/window/SurgeryPostOpMedsWindow.js @@ -0,0 +1,483 @@ +/* + * Copyright (c) 2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ + +// Created: 10-4-2017 R.Blasa + + +Ext4.define('onprc_ehr.window.SurgeryPostOpMedsWindow', { + extend: 'Ext.window.Window', + + initComponent: function(){ + Ext4.apply(this, { + modal: true, + closeAction: 'destroy', + title: 'Order Post-Op Meds', + minWidth: 820, + bodyStyle: 'padding: 5px;', + buttons: [{ + text: 'Submit', + scope: this, + handler: this.onSubmit + },{ + text: 'Close', + handler: function(btn){ + btn.up('window').close(); + } + }], + items: [{ + html: 'Loading...', + border: false + }] + }); + + this.callParent(arguments); + + var store = this.getFrequencyStore(); + store.on('load', this.onStoreLoad, this); + }, + + getFrequencyStore: function(){ + if (this.frequencyStore) + return this.frequencyStore; + + this.frequencyStore = Ext4.create('LABKEY.ext4.data.Store', { + schemaName: 'ehr_lookups', + queryName: 'treatment_frequency', + columns: 'rowid,meaning,times', + autoLoad: true + }); + + return this.frequencyStore; + }, + + onStoreLoad: function(store){ + var ids = []; + this.encountersStore.each(function(r, recIdx){ + if (!r.get('Id') || !r.get('procedureid')){ + return; + } + + ids.push(r.get('Id')); + }); + + ids = Ext4.unique(ids); + + EHR.DataEntryUtils.getWeights(this.targetStore.storeCollection, ids, this.onDemographicsLoad, this, false); + }, + + onDemographicsLoad: function(weightMap){ + this.weightMap = weightMap; + this.removeAll(); + this.add(this.getItems()); + this.center(); + }, + + getItems: function(){ + var numCols = 7; + var items = [{ + xtype: 'displayfield', + value: 'Animal Id' + },{ + xtype: 'displayfield', + value: 'Procedure' + },{ + xtype: 'displayfield', + value: 'Weight' + },{ + xtype: 'displayfield', + value: 'Surg. Time' + },{ + xtype: 'displayfield', + value: '1st Dose' + },{ + xtype: 'displayfield', + value: 'Analgesia' + },{ + xtype: 'displayfield', + value: 'Antibiotics' + }]; + + var ids = []; + this.encountersStore.each(function(r, recIdx){ + if (!r.get('Id') || !r.get('procedureid')){ + return; + } + + items.push({ + xtype: 'displayfield', + value: r.get('Id'), + width: 100, + recIdx: recIdx + }); + + var procedureRec = this.getProcedureRec(r.get('procedureid')); + LDK.Assert.assertNotEmpty('Unable to find procedure matching rowid: ' + r.get('procedureid'), procedureRec); + items.push({ + xtype: 'displayfield', + width: 200, + value: procedureRec.get('name'), + recIdx: recIdx + }); + + if (ids.indexOf(r.get('Id')) > -1){ + items.push({ + xtype: 'displayfield', + value: 'Duplicate Animal', + colspan: (numCols - 2) + }); + + return; + } + ids.push(r.get('Id')); + + items.push({ + xtype: 'displayfield', + value: this.weightMap[r.get('Id')] ? this.weightMap[r.get('Id')].weight : '', + recIdx: recIdx + }); + + if (r.get('date')){ + items.push({ + xtype: 'displayfield', + value: r.get('date').format('H:i'), + recIdx: recIdx + }); + + //start meds on either 1200/1600/2000, 3 hours offset form surg time + var hour = r.get('date').getHours(); + hour += 3; + + //note: if more than 30 mins past the hour, round up + if (r.get('date').getMinutes() >= 30){ + hour++; + } + + if (hour > 16){ + hour = 20; + } + else if (hour > 12){ + hour = 16; + } + else { + hour = 12; + } + + var time = new Date(); + Ext4.Date.clearTime(time); + time.setHours(hour); + + items.push({ + xtype: 'timefield', + fieldName: 'time', + minValue: '8:00', + maxValue: '20:00', + increment: 240, + width: 80, + format: 'H:i', + value: time, + recIdx: recIdx + }); + } + else { + items.push({ + xtype: 'displayfield', + value: 'No Date' + }); + + items.push({ + xtype: 'displayfield', + value: null + }); + } + + items.push({ + xtype: 'labkey-combo', + forceSelection: true, + width: 225, + valueField: 'entityid', + displayField: 'title', + fieldName: 'analgesiaRx', + encountersRec: r, + store: this.getTemplateStoreCfg(recIdx, procedureRec, 'analgesiaRx'), + recIdx: recIdx + }); + + items.push({ + xtype: 'labkey-combo', + forceSelection: true, + width: 225, + valueField: 'entityid', + displayField: 'title', + fieldName: 'antibioticRx', + encountersRec: r, + store: this.getTemplateStoreCfg(recIdx, procedureRec, 'antibioticRx'), + recIdx: recIdx + }); + }, this); + + return { + border: false, + style: 'padding-top: 10px', + defaults: { + style: 'margin-right: 5px;' + }, + layout: { + type: 'table', + columns: numCols + }, + items: items + }; + }, + + getTemplateStoreCfg: function(recIdx, procedureRec, fieldName){ + return { + type: 'labkey-store', + schemaName: 'ehr', + queryName: 'my_formtemplates', + initialTemplate: procedureRec.get(fieldName), + fieldName: fieldName, + recIdx: recIdx, + sort: 'title', + autoLoad: true, + filterArray: [ + LABKEY.Filter.create('formtype', 'Treatment Orders', LABKEY.Filter.Types.EQUAL), + LABKEY.Filter.create('category', 'Section', LABKEY.Filter.Types.EQUAL) + ], + listeners: { + scope: this, + load: function(store){ + LDK.Assert.assertTrue('No records found in SurgeryPostOpMeds store', store.getCount() > 0); + + if (store.initialTemplate){ + var recIdx = store.findExact('title', store.initialTemplate); + if (recIdx != -1){ + var entityId = store.getAt(recIdx).get('entityid'); + var combo = this.down('combo[recIdx=' + store.recIdx + '][fieldName=' + store.fieldName + ']'); + LDK.Assert.assertNotEmpty('Unable to find combo for field: ' + store.fieldName, combo); + + if (combo){ + combo.setValue(entityId); + } + } + } + } + } + } + }, + + getProcedureRec: function(procedureId){ + var procedureRecIdx = EHR.DataEntryUtils.getProceduresStore().findExact('rowid', procedureId); + if (procedureRecIdx != -1){ + return EHR.DataEntryUtils.getProceduresStore().getAt(procedureRecIdx); + } + }, + + onSubmit: function(){ + var combos = this.query('combo[encountersRec]'); + this.templateMap = {}; + Ext4.Array.forEach(combos, function(combo){ + if (combo.getValue()){ + this.templateMap[combo.getValue()] = this.templateMap[combo.getValue()] || []; + this.templateMap[combo.getValue()].push(combo.encountersRec); + } + }, this); + + if (Ext4.Object.isEmpty(this.templateMap)){ + Ext4.Msg.alert('Error', 'Must choose at least one template'); + return; + } + + this.hide(); + LABKEY.Query.selectRows({ + requiredVersion: 9.1, + schemaName: 'ehr', + queryName: 'formtemplaterecords', + filterArray: [LABKEY.Filter.create('templateid', Ext4.Object.getKeys(this.templateMap).join(';'), LABKEY.Filter.Types.EQUALS_ONE_OF)], + scope: this, + failure: LDK.Utils.getErrorCallback(), + success: this.onTemplateLoad + }); + }, + + getFrequencyRec: function(meaning){ + if (!meaning) + return null; + + var frequencyIdx = this.getFrequencyStore().findExact('meaning', meaning, 0, false, false, true); + LDK.Assert.assertTrue('Unable to find frequency for: ' + meaning, frequencyIdx > -1); + + if (frequencyIdx > -1){ + return this.getFrequencyStore().getAt(frequencyIdx); + } + }, + + onTemplateLoad: function(results){ + if (!results || !results.rows || !results.rows.length){ + this.close(); + Ext4.Msg.alert('', 'No rows found for the selected templates'); + return; + } + + //build map of values + var templateRowMap = {}; + Ext4.Array.forEach(results.rows, function(row){ + row = new LDK.SelectRowsRow(row); + + var templateId = row.getValue('templateid'); + templateRowMap[templateId] = templateRowMap[templateId] ||[]; + + templateRowMap[templateId].push(row); + }, this); + + var combos = this.query('combo[encountersRec]'); + var records = []; + Ext4.Array.forEach(combos, function(combo){ + if (combo.getValue()){ + var encountersRec = combo.encountersRec; + var timeField = this.query('timefield[recIdx=' + combo.recIdx + ']')[0]; + + var toAdd = templateRowMap[combo.getValue()]; + if (toAdd){ + Ext4.Array.forEach(toAdd, function(templateRow){ + var json = templateRow.getValue('json'); + if (json){ + json = Ext4.decode(json); + + var date = Ext4.Date.clone(encountersRec.get('date')); + date = Ext4.Date.clearTime(date); + date.setHours(timeField.getValue().getHours()); + + //Modifed:10-4-2017 R.Blasa + if (json.offset){ + var offsetDate = Ext4.Date.add(Ext4.Date.clone(date), Ext4.Date.DAY, json.offset); + //offsetDate = Ext4.Date.clearTime(offsetDate); + //offsetDate.setHours(times[0] / 100); + date = offsetDate; + } + + //always set start to be the first normal dose after the start time + var frequencyRec = this.getFrequencyRec(json.frequency_meaning); + var frequency = frequencyRec ? frequencyRec.get('rowid') : null; + if (frequencyRec && frequencyRec.get('times')){ + var times = frequencyRec.get('times').split(','); + date = EHR.DataEntryUtils.getNextDoseTime(date, times); + } + + var enddate = null; + if (json.duration){ + //this is specifically to handle hydro, when administered ~noon + if (new String(json.duration).match(/H$/)){ + var duration = new String(json.duration); + duration = duration.replace('H', ''); + duration = Number(duration); + duration += encountersRec.get('date').getHours(); + duration = Math.floor(duration / 24); + + enddate = Ext4.Date.clone(encountersRec.get('date')); + endate = Ext4.Date.clearTime(enddate); + enddate = Ext4.Date.add(enddate, Ext4.Date.DAY, duration); + } + else { + enddate = Ext4.Date.clone(date); + enddate = Ext4.Date.add(enddate, Ext4.Date.DAY, json.duration); + } + + //always assume a full day, so end at the last scheduled time + var hour = 23; + if (frequencyRec && frequencyRec.get('times')){ + var times = frequencyRec.get('times').split(','); + hour = times[times.length - 1]; + hour = Math.min(hour / 100); + } + + enddate.setHours(hour); + } + + var obj = { + Id: encountersRec.get('Id'), + parentid: encountersRec.get('objectid'), + project: encountersRec.get('project'), + date: date, + enddate: enddate, + frequency: frequency + }; + + Ext4.apply(obj, json); + + //this isnt great, but hard code amount on hydro and buprenex for now + if (obj.code == 'E-77851' || obj.code == 'E-YY792'){ + var weight = this.weightMap[encountersRec.get('Id')] ? this.weightMap[encountersRec.get('Id')].weight : null; + if (weight){ + obj.amount_units = 'mg'; + obj.vol_units = 'mL'; + + //hyrdo + if (obj.code == 'E-77851'){ + if (weight < 3.0){ + obj.amount = 0.5; + obj.volume = 0.25; + } + else if (weight < 10.0){ + obj.amount = 1.0; + obj.volume = 0.5; + } + else { + obj.amount = 2.0; + obj.volume = 1.0; + } + } + //buprenex + else if (obj.code == 'E-YY792'){ + if (weight < 3.0){ + obj.amount = 0.15; + obj.volume = 0.5; + } + else { + obj.amount = 0.3; + obj.volume = 1.0; + } + } + } + } + + records.push(this.targetStore.createModel(obj)); + } + }, this); + } + else { + console.log('Unable to find template: ' + combo.getValue()); + } + } + }, this); + + if (records.length){ + this.targetStore.add(records); + } + + this.close(); + } +}); + +EHR.DataEntryUtils.registerGridButton('SURGERYMEDS', function(config){ + config = config || {}; + + return Ext4.Object.merge({ + text: 'Order Post-Op Meds', + itemId: 'postOpBtn', + handler: function(btn){ + var grid = btn.up('gridpanel'); + LDK.Assert.assertNotEmpty('Unable to find gridpanel in SURGERYMEDS button', grid); + + var encountersStore = grid.store.storeCollection.getClientStoreByName('encounters'); + LDK.Assert.assertNotEmpty('Unable to find encountersStore in SURGERYMEDS button', encountersStore); + + Ext4.create('onprc_ehr.window.SurgeryPostOpMedsWindow', { + targetStore: grid.store, + encountersStore: encountersStore + }).show(); + } + }); +}); \ No newline at end of file diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRController.java b/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRController.java index 9c6fa9a41..068609367 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRController.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRController.java @@ -91,6 +91,8 @@ public ApiResponse execute(Object form, BindException errors) //Added 6-5-2016 Blasa resultProperties.put("sla", getSection("/ONPRC/SLA")); + //Added by kollil 5/7/2019 + resultProperties.put("reservation", getSection("/ONPRC/Room Reservations")); //for now, EHR is hard coded List ehr = new ArrayList<>(); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRManager.java b/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRManager.java index d4d77cb87..e58afaa63 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRManager.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRManager.java @@ -50,6 +50,8 @@ public class ONPRC_EHRManager @Queryable public static final String U24_PROJECT = "0492-03"; @Queryable + public static final String JMAC_PROJECT = "0492-45"; + @Queryable public static final String TMB_PROJECT = "0300"; @Queryable public static final String VET_USER_GROUP = "DCM Veterinarians"; diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRModule.java b/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRModule.java index 2a89a4f33..edcc43dd9 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRModule.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012-2018 LabKey Corporation + * Copyright (c) 2012-2017 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import org.labkey.api.ehr.buttons.ChangeQCStateButton; import org.labkey.api.ehr.buttons.CreateTaskFromIdsButton; import org.labkey.api.ehr.buttons.CreateTaskFromRecordsButton; +import org.labkey.onprc_ehr.buttons.CreateTaskFromRecordButtons; import org.labkey.api.ehr.buttons.DiscardTaskButton; import org.labkey.api.ehr.buttons.EHRShowEditUIButton; import org.labkey.api.ehr.buttons.MarkCompletedButton; @@ -63,11 +64,15 @@ import org.labkey.onprc_ehr.dataentry.*; import org.labkey.onprc_ehr.demographics.ActiveAnimalGroupsDemographicsProvider; import org.labkey.onprc_ehr.demographics.ActiveCasesDemographicsProvider; +import org.labkey.onprc_ehr.demographics.ActiveDrugsGivenDemographicsProvider; +import org.labkey.onprc_ehr.demographics.ActiveTreatmentsXDemographicsProvider; import org.labkey.onprc_ehr.demographics.AssignedVetDemographicsProvider; import org.labkey.onprc_ehr.demographics.CagemateInfantDemographicsProvider; import org.labkey.onprc_ehr.demographics.CagematesDemographicsProvider; import org.labkey.onprc_ehr.demographics.FosterChildDemographicsProvider; +import org.labkey.onprc_ehr.demographics.GeneticAncestryDemographicsProvider; import org.labkey.onprc_ehr.demographics.HousingDemographicsProvider; +import org.labkey.onprc_ehr.demographics.LastHousingDemographicsProvider; import org.labkey.onprc_ehr.demographics.ParentsDemographicsProvider; import org.labkey.onprc_ehr.demographics.PregnancyConfirmDemographicsProvider; import org.labkey.onprc_ehr.demographics.SourceDemographicsProvider; @@ -76,13 +81,17 @@ import org.labkey.onprc_ehr.history.DefaultAnimalGroupsEndDataSource; import org.labkey.onprc_ehr.history.DefaultAnimalRecordFlagDataSource; import org.labkey.onprc_ehr.history.DefaultNHPTrainingDataSource; +import org.labkey.onprc_ehr.history.DefaultSustainedReleaseDatasource; import org.labkey.onprc_ehr.history.DefaultSnomedDataSource; +import org.labkey.onprc_ehr.history.ONPRCClinicalRemarksDataSource; import org.labkey.onprc_ehr.history.ONPRCUrinalysisLabworkType; +import org.labkey.onprc_ehr.history.ONPRCiStatLabworkType; import org.labkey.onprc_ehr.notification.*; import org.labkey.onprc_ehr.security.ONPRC_EHRCMUAdministrationPermission; import org.labkey.onprc_ehr.security.ONPRC_EHRCMUAdministrationRole; import org.labkey.onprc_ehr.security.ONPRC_EHRCustomerEditPermission; import org.labkey.onprc_ehr.security.ONPRC_EHRCustomerEditRole; +//import org.labkey.onprc_ehr.security.ONPRC_EHRPMICEditRole; import org.labkey.onprc_ehr.security.ONPRC_EHRTransferRequestRole; import org.labkey.onprc_ehr.table.ONPRC_EHRCustomizer; @@ -92,9 +101,9 @@ import java.util.Collections; /** - * User: bbimber - * Date: 5/16/12 - * Time: 1:52 P + * User: jonesga + * Date: 6/26/2018 + * Change of ONPRC Module Number */ public class ONPRC_EHRModule extends ExtendedSimpleModule { @@ -110,7 +119,7 @@ public String getName() @Override public @Nullable Double getSchemaVersion() { - return 18.10; + return 20.417; } @Override @@ -127,6 +136,9 @@ protected void init() RoleManager.registerRole(new ONPRC_EHRCustomerEditRole()); RoleManager.registerRole(new ONPRC_EHRCMUAdministrationRole()); RoleManager.registerRole(new ONPRC_EHRTransferRequestRole()); + +// Added: 12-5-2019 +// RoleManager.registerRole(new ONPRC_EHRPMICEditRole()); } @Override @@ -158,6 +170,26 @@ protected void doStartupAfterSpringConfig(ModuleContext moduleContext) //Added 3-8-2017 Blasa ns.registerNotification(new ObeseFlagNotification(this)); + //Added 4-25-2017 R.Blasa + ns.registerNotification(new InfantsBornAssignedNotification(this)); + + //Added April, 2017 Kollil + ns.registerNotification(new PregnantNHPsGestationAlert(this)); + + //Added May 12th, 2017 Kollil + ns.registerNotification(new DCMNotesNotification(this)); + + //Added May 12th, 2017 Kollil + ns.registerNotification(new BSUNotesNotification(this)); + + //Added 8-7-2018 R.Blasa + ns.registerNotification(new BirthHousingMismatchNotification(this)); + + //Added 3-6-2019 Blasa + ns.registerNotification(new ProjectAlertsNotification(this)); + + //Added 6-4-2019 Additional Scheduled for 55pm + ns.registerNotification(new TreatmentAlertsPostOpsNotificationThird(this)); ns.registerNotification(new RequestAdminNotification(this)); ns.registerNotification(new ColonyAlertsLiteNotification(this)); @@ -194,7 +226,7 @@ private void registerEHRResources() EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/ClinicalProcedures.js"), this); //Added 11-17-16 KOLLI - // EHRService.get().registerClientDependency(ClientDependency.fromPath("onprc_ehr/form/field/CohortField.js"), this); + // EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/form/field/CohortField.js"), this); //Added: 7-12-2016 R.Blasa EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/panel/SnapshotPanel.js"), this); @@ -210,6 +242,30 @@ private void registerEHRResources() EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/panel/NarrowSnapshotPanel.js"), this); + + //Added: 10-25-2017 R.Blasa References new Xtype + EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/form/field/CEG_PlantextArea.js"), this); + + //Added: 7-7-2017 R.Blasa +// EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/HousingReason.js"), this); + + //Added: 1-19-2018 R.Blasa + EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/form/field/AnimalGroupFieldsCombo.js"), this); + +// //Added: 10-5-2018 R.Blasa //needed for displaying wound subcategory + EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/panel/ManageCasesPanel.js"), this); + + // //Added: 10-8-2018 R.Blasa //needed for displaying wound subcategory + EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/window/ManageCasesWindow.js"), this); + + + //Added: 7-18-2018 R.Blasa + EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/window/ManageRecordWindow.js"), this); + + //Added: 10-7-2019 R.Blasa + EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/TreatmentDrugsClinical.js"), this); + + EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.housing, "List Single Housed Animals", this, DetailsURL.fromString("/query/executeQuery.view?schemaName=study&query.queryName=demographicsPaired&query.viewName=Single Housed"), "Commonly Used Queries"); EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.housing, "Find Animals Housed In A Given Room/Cage At A Specific Time", this, DetailsURL.fromString("/ehr/housingOverlaps.view?groupById=1"), "Commonly Used Queries"); @@ -247,16 +303,21 @@ private void registerEHRResources() //Added 1-30-2017 R.Blasa EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Clinical Snapshot Printable Report", this, DetailsURL.fromString("/onprc_ehr/SnapshotPrintableReport.view"), "Clinical"); - //Added 5-11-2015 New report for Lois Colgin + //Added 5-16-2018 R.Blasa + EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Date of Last Physical Exam by ID(s)", this, DetailsURL.fromString("/onprc_ehr/PE_ExamHistoryReportbyID.view"), "Routine Clinical Tasks"); + + //Modified: 1-17-2019 R.Blasa try { - EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Clinical Laboratory Test Summary", this, new URLHelper("http://primateapp.ohsu.edu/ReportServer/Pages/ReportViewer.aspx?%2fAnnual+Reports%2fPrimeLaboratory+Report&rs:Command=Render") + EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Clinical Pathology Laboratory Summary Report", this, new URLHelper("http://primateapp3.ohsu.edu/ReportServer/Pages/ReportViewer.aspx?%2fPrime+Reports%2fClinPath%2fPrimeLaboratory+Report&rs:Command=Render") { // SSRS is picky about the URI-encoding of the query parameters @Override + //Modified: 1-17-2019 R.Blasa public String toString() { - return "http://primateapp.ohsu.edu/ReportServer/Pages/ReportViewer.aspx?%2fAnnual+Reports%2fPrimeLaboratory+Report&rs:Command=Render"; + return "http://primateapp3.ohsu.edu/ReportServer/Pages/ReportViewer.aspx?%2fPrime+Reports%2fClinPath%2fPrimeLaboratory+Report&rs:Command=Render"; + } }, "Clinical Pathology"); } @@ -265,6 +326,25 @@ public String toString() throw new UnexpectedException(e); } + //Modified 9-9-2019 R.Blasa Show Full Exposure report instead of Basic Expsoure + try + { + EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Exposure Report", this, new URLHelper("http://primateapp3.ohsu.edu/ReportServer/Pages/ReportViewer.aspx?%2fPrime+Reports%2fExposure+Reports%2fBasicExposureMain&rs:Command=Render") + { + // SSRS is picky about the URI-encoding of the query parameters + @Override + //Modified: 1-17-2019 R.Blasa + public String toString() + { + return "http://primateapp3.ohsu.edu/ReportServer/Pages/ReportViewer.aspx?%2fPrime+Reports%2fExposure+Reports%2fDemographicsReportMain&rs:Command=Render"; + } + }, "Exposure Report"); + } + catch (URISyntaxException e) + { + throw new UnexpectedException(e); + } + try { EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Colony Census Excel Workbook", this, new URLHelper(AppProps.getInstance().getContextPath() + "/onprc_ehr/reports/Colony Census.xlsm"), "Colony Management"); @@ -294,9 +374,19 @@ public String toString() EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Mense Data With Cycle Date", this, DetailsURL.fromString("/query/executeQuery.view?schemaName=study&query.queryName=menseData"), "Reproductive Management"); EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "View Tissue Distribution Summary", this, DetailsURL.fromString("/query/executeQuery.view?schemaName=study&query.queryName=tissueDistributionSummary"), "Pathology"); + // Added: 1-2-2018 R.Blasa + EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "View Tissue Distribution Summary(Calendar Year)", this, DetailsURL.fromString("/query/executeQuery.view?schemaName=study&query.queryName=TissueDistributionSummaryCalendarYr"), "Pathology"); + EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "SNOMED Search", this, DetailsURL.fromString("/onprc_ehr/snomedSearch.view"), "Pathology"); EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "View Tissue Distribution Summary, By Recipient", this, DetailsURL.fromString("/query/executeQuery.view?schemaName=study&query.queryName=tissueDistributionSummaryByRecipient"), "Pathology"); +// Added 1-2-2018 R.Blasa + EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "View Tissue Distribution Summary, By Recipient(Calendar Year)", this, DetailsURL.fromString("/query/executeQuery.view?schemaName=study&query.queryName=tissueDistributionSummaryByRecipientCalendarYr"), "Pathology"); + + //Added: 12-7-2017 R.Blasa + // EHRService.get().registerReportLink(EHRService.REPORT_LINK_TYPE.moreReports, "Animal Census on a Given Date Range", this, DetailsURL.fromString("/onprc_ehr/CensusGivenDateRange.view"), "Colony Management"); + + EHRService.get().registerActionOverride("projectDetails", this, "views/projectDetails.html"); EHRService.get().registerActionOverride("protocolDetails", this, "views/protocolDetails.html"); EHRService.get().registerActionOverride("procedureDetails", this, "views/procedureDetails.html"); @@ -306,6 +396,9 @@ public String toString() EHRService.get().registerActionOverride("animalHistory", this, "views/animalHistory.html"); EHRService.get().registerActionOverride("serviceRequests", this, "views/serviceRequests.html"); + //Added: 10-2-2017 R.Blasa displays onperc version of enterData.view + EHRService.get().registerActionOverride("enterData", this, "views/enterData.html"); + //data entry EHRService.get().registerFormType(new DefaultDataEntryFormFactory(WeightFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(AnesthesiaFormType.class, this)); @@ -341,13 +434,16 @@ public String toString() EHRService.get().registerFormType(new DefaultDataEntryFormFactory(MatingFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(PregnancyConfirmationFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ParentageFormType.class, this)); + EHRService.get().registerFormType(new DefaultDataEntryFormFactory(GeneticAncestryFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ONPRCBloodDrawFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(AuxProcedureFormType.class, this)); //Modified: 12-13-2016 R.Blasa EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ASBRequestFormType.class, this)); - EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ColonyRequestFormType.class, this)); + //Modified: Kollil, 10/02/2020 + //Colony services request form is disabled as per ISE team's decision + //EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ColonyRequestFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(LabworkRequestFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(HousingRequestFormType.class, this)); @@ -355,11 +451,32 @@ public String toString() EHRService.get().registerFormType(new DefaultDataEntryFormFactory(DrugRequestBulkEditFormType.class, this)); EHRService.get().registerFormType(new DefaultDataEntryFormFactory(LabworkRequestBulkEditFormType.class, this)); + //Modified: 8-18-2020 R.Blasa + EHRService.get().registerFormType(new DefaultDataEntryFormFactory(PathDeathFormType.class, this)); + + //Added: 5/23/2019 Kolli +// EHRService.get().registerFormType(new DefaultDataEntryFormFactory(PMICRequestFormType.class, this)); + + //Added: 8/10/2019 Kolli +// EHRService.get().registerFormType(new DefaultDataEntryFormFactory(IPCRequestFormType.class, this)); + + //Added: 7/10/2019 by Kolli +// EHRService.get().registerFormType(new DefaultDataEntryFormFactory(PMICDataEntryFormType.class, this)); + +// Added: 11-21-2017 R.Blasa + EHRService.get().registerFormType(new DefaultDataEntryFormFactory(ProcedureRequestBulkEditFormType.class, this)); + EHRService.get().registerFormType(new DefaultDataEntryFormFactory(RecordAmendmentFormType.class, this)); //Added: 10-19-2016 R.Blasa EHRService.get().registerFormType(new DefaultDataEntryFormFactory(NHPTrainingFormType.class, this)); + //Added: 4-5-2017 R.Blasa + EHRService.get().registerFormType(new DefaultDataEntryFormFactory(NHPRProcessingFormType.class, this)); + + //Added: 11-4-2019 R.Blasa + EHRService.get().registerFormType(new DefaultDataEntryFormFactory(TBTestObservationFormType.class, this)); + //single section forms EHRService.get().registerSingleFormOverride(new SingleQueryFormProvider(this, "study", "treatment_order", new MedicationsQueryFormSection("study", "Treatment Orders", "Medication/Treatment Orders"))); EHRService.get().registerSingleFormOverride(new SingleQueryFormProvider(this, "study", "drug", new MedicationsQueryFormSection("study", "Drug Administration", "Medication/Treatments Given"))); @@ -369,6 +486,7 @@ public String toString() EHRService.get().registerDemographicsProvider(new CagematesDemographicsProvider(this)); EHRService.get().registerDemographicsProvider(new HousingDemographicsProvider(this)); EHRService.get().registerDemographicsProvider(new ParentsDemographicsProvider(this)); + EHRService.get().registerDemographicsProvider(new GeneticAncestryDemographicsProvider(this)); EHRService.get().registerDemographicsProvider(new SourceDemographicsProvider(this)); EHRService.get().registerDemographicsProvider(new ActiveFlagsDemographicsProvider(this)); EHRService.get().registerDemographicsProvider(new TBDemographicsProvider(this)); @@ -378,15 +496,24 @@ public String toString() //Created: 1-20-2017 R.Blasa EHRService.get().registerDemographicsProvider(new PregnancyConfirmDemographicsProvider(this)); + //Added: 3-27-2017 R.Blasa + EHRService.get().registerClientDependency(ClientDependency.supplierFromPath("onprc_ehr/panel/EnterDataPanel.js"), this); //Created: 2-21-2017 R.Blasa EHRService.get().registerDemographicsProvider(new CagemateInfantDemographicsProvider(this)); - - //Created: 3-10-2017 R.Blasa EHRService.get().registerDemographicsProvider(new FosterChildDemographicsProvider(this)); + //Created: 4-7-2015-10-2017 R.Blasa + EHRService.get().registerDemographicsProvider(new ActiveTreatmentsXDemographicsProvider(this)); + + //Created: 12-18-2018 R.Blasa + EHRService.get().registerDemographicsProvider(new LastHousingDemographicsProvider(this)); + + //Created: 10-4-2019 R.Blasa + EHRService.get().registerDemographicsProvider(new ActiveDrugsGivenDemographicsProvider(this)); + //buttons EHRService.get().registerMoreActionsButton(new DiscardTaskButton(this), "ehr", "my_tasks"); EHRService.get().registerMoreActionsButton(new DiscardTaskButton(this), "ehr", "tasks"); @@ -415,10 +542,16 @@ public String toString() //EHRService.get().registerMoreActionsButton(new CreateTaskFromIdsButton(this, "Schedule Weight For Selected", "Weight", "weight", new String[]{"Weight"}), "study", "weight"); EHRService.get().registerTbarButton(new HousingTransferButton(this), "onprc_ehr", "housing_transfer_requests"); - EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Blood Draws", ONPRCBloodDrawFormType.NAME), "study", "blood"); - EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Treatments/Medications", TreatmentsFormType.NAME), "study", "drug"); - EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Labwork", LabworkFormType.NAME), "study", "clinpathRuns"); - EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Surgeries", SurgeryFormType.NAME), "study", "surgery"); +// Modified: 8-22-2020 R.Blasa + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordButtons(this, "Create Task From Selected", "Blood Draws", ONPRCBloodDrawFormType.NAME), "study", "blood"); + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordButtons(this, "Create Task From Selected", "Treatments/Medications", TreatmentsFormType.NAME), "study", "drug"); + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordButtons(this, "Create Task From Selected", "Labwork", LabworkFormType.NAME), "study", "clinpathRuns"); + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordButtons(this, "Create Task From Selected", "Surgeries", SurgeryFormType.NAME), "study", "surgery"); + + + //Added: 8-22-2020 R.Blasa + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordButtons(this, "Create Task From Selected", "Procedures", AuxProcedureFormType.NAME), "study", "encounters"); + EHRService.get().registerMoreActionsButton(new ChangeQCStateButton(this), "study", "blood"); EHRService.get().registerMoreActionsButton(new ChangeQCStateButton(this, "ONPRC_EHR.window.ChangeLabworkStatusWindow", Collections.singletonList(ClientDependency.supplierFromPath("onprc_ehr/window/ChangeLabworkStatusWindow.js"))), "study", "clinpathRuns"); @@ -446,17 +579,37 @@ public String toString() EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Necropsy", NecropsyFormType.NAME), "study", "tissue_samples"); EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Necropsy", NecropsyFormType.NAME), "study", "organ_weights"); - EHRService.get().registerOptionalClinicalHistoryResources(this); +// Added: 10-9-2017 R.Blasa + EHRService.get().registerMoreActionsButton(new BulkEditRequestsButton(this, ProcedureRequestBulkEditFormType.NAME), "study", "encounters"); + EHRService.get().registerHistoryDataSource(new DefaultSnomedDataSource(this)); EHRService.get().registerHistoryDataSource(new DefaultAnimalGroupsDataSource(this)); EHRService.get().registerHistoryDataSource(new DefaultAnimalGroupsEndDataSource(this)); //R.Blasa 3-4-2015 EHRService.get().registerHistoryDataSource(new DefaultAnimalRecordFlagDataSource(this)); + //R.Blasa 1-23-2015 + EHRService.get().registerHistoryDataSource(new org.labkey.api.ehr.history.DefaultAnimalRecordFlagDataSource(this)); + EHRService.get().registerHistoryDataSource(new ONPRCClinicalRemarksDataSource(this)); + + EHRService.get().registerMoreActionsButton(new CreateNecropsyRequestButton(this), "study", "encounters"); + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Necropsy", NecropsyFormType.NAME), "study", "encounters"); + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Necropsy", NecropsyFormType.NAME), "study", "tissue_samples"); + EHRService.get().registerMoreActionsButton(new CreateTaskFromRecordsButton(this, "Create Task From Selected", "Necropsy", NecropsyFormType.NAME), "study", "organ_weights"); + EHRService.get().registerMoreActionsButton(new MarkCompletedButton(this, "study", "geneticAncestry", "End/Disable Selected", true), "study", "geneticAncestry"); + + EHRService.get().registerOptionalClinicalHistoryResources(this); EHRService.get().registerLabworkType(new ONPRCUrinalysisLabworkType(this)); + EHRService.get().registerLabworkType(new ONPRCiStatLabworkType(this)); //R.Blasa 11-28-2016 EHRService.get().registerHistoryDataSource(new DefaultNHPTrainingDataSource(this)); + + //R.Blasa 11-20-2019 + EHRService.get().registerHistoryDataSource(new DefaultSustainedReleaseDatasource(this)); + + + AdminLinkManager.getInstance().addListener((adminNavTree, container, user) -> { if (container.hasPermission(user, AdminPermission.class) && container.getActiveModules().contains(ONPRC_EHRModule.this)) diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/buttons/CreateTaskFromRecordButtons.java b/onprc_ehr/src/org/labkey/onprc_ehr/buttons/CreateTaskFromRecordButtons.java new file mode 100644 index 000000000..a51e4092e --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/buttons/CreateTaskFromRecordButtons.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013-2016 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.buttons; + +import org.labkey.api.data.TableInfo; +import org.labkey.api.ehr.security.EHRScheduledInsertPermission; +import org.labkey.api.ldk.table.SimpleButtonConfigFactory; +import org.labkey.api.module.Module; +import org.labkey.api.security.permissions.Permission; +import org.labkey.api.study.DatasetTable; +import org.labkey.api.view.template.ClientDependency; + +import java.util.Set; + +//Createdd: 1-18-2019 R.Blasa + +public class CreateTaskFromRecordButtons extends SimpleButtonConfigFactory +{ + public CreateTaskFromRecordButtons(Module owner, String btnLabel, String taskLabel, String formType) + { + super(owner, btnLabel, "ONPRC_EHR.window.CreateTaskFromRecordsWindow.createTaskFromRecordHandler(dataRegionName, '" + formType + "', '" + taskLabel + "')"); + setClientDependencies(ClientDependency.supplierFromPath("onprc_ehr/window/CreateTaskFromRecordsWindow.js")); //Modified: 1-19-2019 R.Blasa + + } + + public boolean isAvailable(TableInfo ti) + { + if (!super.isAvailable(ti)) + return false; + + if (ti instanceof DatasetTable) + { + Set> perms = ((DatasetTable) ti).getDataset().getPermissions(ti.getUserSchema().getUser()); + return perms.contains(EHRScheduledInsertPermission.class); + } + + return ti.hasPermission(ti.getUserSchema().getUser(), EHRScheduledInsertPermission.class); + } +} + diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ASBRequestFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ASBRequestFormType.java index c121a72c0..e933e8832 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ASBRequestFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ASBRequestFormType.java @@ -26,14 +26,10 @@ import java.util.Arrays; -/** - * User: bimber - * Date: 7/29/13 - * Time: 5:03 PM - */ +//Modified: 12-21-2016 R.blasa public class ASBRequestFormType extends RequestForm { - public static final String NAME = "ASB Services Request"; + public static final String NAME = "ASB SERVICES REQUEST"; public static final String DEFAULT_GROUP = "ASB Services"; public ASBRequestFormType(DataEntryFormContext ctx, Module owner) @@ -42,9 +38,12 @@ public ASBRequestFormType(DataEntryFormContext ctx, Module owner) new RequestFormSection(), //new RequestInstructionsFormSection(), new AnimalDetailsFormSection(), - new BloodDrawFormSection(true) + new ClinicalEncountersFormSection(), + new BloodDrawFormSection(true), + +// Modified: 7-18-2017 R.Blasa - // new DrugAdministrationRequestFormSection() Removed 6/17/2015 GJONES ISsue 1820 + new DrugAdministrationRequestFormSection() )); addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/ASB_Services.js")); diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.321-12.322.sql b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/AnimalDetailssFormSection.java similarity index 51% rename from onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.321-12.322.sql rename to onprc_ehr/src/org/labkey/onprc_ehr/dataentry/AnimalDetailssFormSection.java index d6b10476e..5492e7137 100644 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.321-12.322.sql +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/AnimalDetailssFormSection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 LabKey Corporation + * Copyright (c) 2013-2017 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package org.labkey.onprc_ehr.dataentry; -ALTER TABLE onprc_billing.invoiceRuns ALTER COLUMN objectid ENTITYID NOT NULL; -GO -EXEC core.fn_dropifexists 'invoiceRuns', 'onprc_billing', 'CONSTRAINT', 'pk_invoiceRuns'; +import org.labkey.api.ehr.dataentry. NonStoreFormSection; +import org.labkey.api.view.template.ClientDependency; -ALTER TABLE onprc_billing.invoiceRuns ADD CONSTRAINT pk_invoiceRuns PRIMARY KEY (objectid); +//Created:12-20-2018 R.Blasa -ALTER TABLE onprc_billing.invoicedItems ADD creditAccountId int; -ALTER TABLE onprc_billing.invoicedItems ADD invoiceId entityid; +public class AnimalDetailssFormSection extends NonStoreFormSection +{ + public AnimalDetailssFormSection() + { + super("AnimalDetails", "Animal Details", "onprc_ehr-animaldetailspanels"); + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/panel/AnimalDetailsPanel.js")); + + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ArrivalFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ArrivalFormType.java index 79841a3ba..3149d9cba 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ArrivalFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ArrivalFormType.java @@ -22,6 +22,7 @@ import org.labkey.api.ehr.dataentry.TaskFormSection; import org.labkey.api.ehr.dataentry.WeightFormSection; import org.labkey.api.module.Module; +import org.labkey.api.view.template.ClientDependency; import java.util.ArrayList; import java.util.Arrays; @@ -49,9 +50,12 @@ public ArrivalFormType(DataEntryFormContext ctx, Module owner) new WeightFormSection() )); - //setJavascriptClass("ONPRC_EHR.panel.NewAnimalDataEntryPanel"); - //addClientDependency(ClientDependency.fromFilePath("onprc_ehr/panel/NewAnimalDataEntryPanel.js")); +// Added: 8-6-2019 R.Blasa + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/panel/ArrivalDataEntryPanel.js")); + setJavascriptClass("ONPRC_EHR.panel.ArrivalDataEntryPanel"); + + } @Override diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/AuxProcedureFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/AuxProcedureFormType.java index f2788d8a0..da39d727c 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/AuxProcedureFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/AuxProcedureFormType.java @@ -23,7 +23,7 @@ import org.labkey.api.ehr.dataentry.TaskForm; import org.labkey.api.ehr.dataentry.TaskFormSection; import org.labkey.api.ehr.dataentry.WeightFormSection; -import org.labkey.api.ehr.dataentry.DrugAdministrationFormSection; +import org.labkey.onprc_ehr.dataentry.DrugAdministrationFormSection; import org.labkey.api.module.Module; import org.labkey.api.view.template.ClientDependency; @@ -53,7 +53,8 @@ public AuxProcedureFormType(DataEntryFormContext ctx, Module owner) new BloodDrawFormSection(false), new WeightFormSection(), new DrugAdministrationFormSection(ClientDependency.supplierFromPath("onprc_ehr/window/ONPRC_AddScheduledTreatmentWindow.js")), - new TreatmentOrdersFormSection() + new TreatmentOrdersFormSection(), + new StudyDetailsFormSection() //Added by Kolli, 2/20/2020 )); for (FormSection s : getFormSections()) @@ -70,7 +71,6 @@ public AuxProcedureFormType(DataEntryFormContext ctx, Module owner) protected List getButtonConfigs() { List ret = super.getButtonConfigs(); - ret.add("APPLYFORMTEMPLATE"); return ret; @@ -80,7 +80,7 @@ protected List getButtonConfigs() protected List getMoreActionButtonConfigs() { List defaultButtons = super.getMoreActionButtonConfigs(); - defaultButtons.add("COPY_TASK"); + defaultButtons.add("COPY_TASKS"); defaultButtons.add("BULK_BLOOD_DRAW"); return defaultButtons; diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BehaviorExamFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BehaviorExamFormType.java index d6d8e7164..d889bc93f 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BehaviorExamFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BehaviorExamFormType.java @@ -79,6 +79,17 @@ public BehaviorExamFormType(DataEntryFormContext ctx, Module owner) addClientDependency(ClientDependency.supplierFromPath("ehr/panel/ExamDataEntryPanel.js")); addClientDependency(ClientDependency.supplierFromPath("ehr/model/sources/ClinicalReportChild.js")); setJavascriptClass("EHR.panel.ExamDataEntryPanel"); + + // //Added: 12-18-2017 R.Blasa + setStoreCollectionClass("ONPRC_EHR.data.sources.BehaviorExamStoreCollection"); + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/data/sources/BehaviorExamStoreCollection.js")); + + // //Added: 1-23-2018 R.Blasa +// Disable as temporary workaround to ticket Ticket 33579: Clinical Staff unsable to Create new Cases +// addClientDependency(ClientDependency.fromPath("onprc_ehr/window/ManageCasesWindow.js")); + + + } @Override @@ -86,6 +97,7 @@ protected List getButtonConfigs() { List ret = super.getButtonConfigs(); +// ret.add("OPEN_BEHAVIORCASE"); ret.add("OPENBEHAVIORCASE"); return ret; diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BiopsyFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BiopsyFormType.java index 5524575cf..c8ff5b16d 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BiopsyFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/BiopsyFormType.java @@ -23,9 +23,13 @@ import org.labkey.api.ehr.dataentry.TaskFormSection; import org.labkey.api.ehr.security.EHRPathologyEntryPermission; import org.labkey.api.module.Module; +import org.labkey.api.security.Group; +import org.labkey.api.security.GroupManager; import org.labkey.api.security.PrincipalType; import org.labkey.api.security.UserPrincipal; +import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.view.template.ClientDependency; +import org.labkey.security.xml.GroupEnumType; import java.util.Arrays; import java.util.HashMap; @@ -62,6 +66,7 @@ public BiopsyFormType(DataEntryFormContext ctx, Module owner) s.addConfigSource("Encounter"); s.addConfigSource("Pathology"); s.addConfigSource("Biopsy"); + s.addConfigSource("Biopsy_Staff"); } addClientDependency(ClientDependency.supplierFromPath("ehr/model/sources/Pathology.js")); @@ -114,8 +119,20 @@ protected Integer getDefaultReviewRequiredPrincipal() UserPrincipal up = org.labkey.api.security.SecurityManager.getPrincipal(NecropsyFormType.DEFAULT_GROUP, getCtx().getContainer(), true); return up != null && up.getPrincipalType() == PrincipalType.GROUP ? up.getUserId() : null; } - + //Modified: 12-3-2019 R.Blasa @Override + public boolean isVisible() + { + Group g = GroupManager.getGroup(getCtx().getContainer(), "Pathology External Entry", GroupEnumType.SITE); + if (g != null && getCtx().getUser().isInGroup(g.getUserId()) && !getCtx().getContainer().hasPermission(getCtx().getUser(), AdminPermission.class)) + { + return false; + } + + return super.isVisible(); + } + + @Override public JSONObject toJSON() { JSONObject ret = super.toJSON(); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/CagemateClinicalReportFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/CagemateClinicalReportFormType.java new file mode 100644 index 000000000..25714ace3 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/CagemateClinicalReportFormType.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2013-2016 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.AbstractFormSection; +import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.ExtendedAnimalDetailsFormSection; +import org.labkey.api.ehr.dataentry.FormSection; +import org.labkey.api.ehr.dataentry.SimpleFormPanelSection; +import org.labkey.api.ehr.dataentry.SimpleFormSection; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.ehr.dataentry.TaskForm; +import org.labkey.api.ehr.dataentry.TaskFormSection; +import org.labkey.api.ehr.security.EHRClinicalEntryPermission; +import org.labkey.api.module.Module; +import org.labkey.api.query.Queryable; +import org.labkey.api.view.template.ClientDependency; + +import java.util.Arrays; +import java.util.List; + +//Created: 1-31-2018 R.Blasa + +public class CagemateClinicalReportFormType extends TaskForm +{ + public static final String NAME = "Cagemate Soaps"; + + public CagemateClinicalReportFormType(DataEntryFormContext ctx, Module owner) + { + super(ctx, owner, NAME, "Cagemates Soaps", "Clinical", Arrays.asList( + new TaskFormSection(), + new AnimalDetailsFormSection(), + new SimpleGridPanel("study", "Clinical Remarks", "SOAPs") + + )); + + setStoreCollectionClass("EHR.data.ClinicalReportStoreCollection"); + addClientDependency(ClientDependency.supplierFromPath("ehr/data/ClinicalReportStoreCollection.js")); + + setTemplateMode(AbstractFormSection.TEMPLATE_MODE.NO_ID); + setDisplayReviewRequired(true); + + for (FormSection s : this.getFormSections()) + { + s.addConfigSource("ClinicalDefaults"); + //Added 6-4-2015 Blasa + s.addConfigSource("ClinicalProcedures"); + } + + addClientDependency(ClientDependency.supplierFromPath("ehr/model/sources/ClinicalDefaults.js")); + + + } + + + + @Override + protected boolean canInsert() + { + if (!getCtx().getContainer().hasPermission(getCtx().getUser(), EHRClinicalEntryPermission.class)) + return false; + + return super.canInsert(); + } + +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalReportFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalReportFormType.java index 1888d9404..c2ec73700 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalReportFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalReportFormType.java @@ -49,13 +49,13 @@ public class ClinicalReportFormType extends TaskForm public ClinicalReportFormType(DataEntryFormContext ctx, Module owner) { - super(ctx, owner, NAME, LABEL, "Clinical", Arrays.asList( + super(ctx, owner, NAME, LABEL, "Clinical", Arrays.asList( new NonStoreFormSection("Instructions", "Instructions", "ehr-examinstructionspanel", Arrays.asList(ClientDependency.supplierFromPath("ehr/panel/ExamInstructionsPanel.js"))), new TaskFormSection(), new ExtendedAnimalDetailsFormSection(), new SimpleFormPanelSection("study", "Clinical Remarks", "SOAP", false, EHRService.FORM_SECTION_LOCATION.Tabs), new ClinicalObservationsFormSection(EHRService.FORM_SECTION_LOCATION.Tabs), - new SimpleGridPanel("study", "encounters", "Procedures", EHRService.FORM_SECTION_LOCATION.Tabs), + new EncounterProcedureFormSection(EHRService.FORM_SECTION_LOCATION.Tabs), new WeightFormSection(EHRService.FORM_SECTION_LOCATION.Tabs), new DrugAdministrationFormSection(EHRService.FORM_SECTION_LOCATION.Tabs, DrugAdministrationFormSection.LABEL, ClientDependency.supplierFromPath("onprc_ehr/window/ONPRC_AddScheduledTreatmentWindow.js")), new TreatmentOrdersFormSection(EHRService.FORM_SECTION_LOCATION.Tabs), @@ -63,8 +63,7 @@ public ClinicalReportFormType(DataEntryFormContext ctx, Module owner) new SimpleGridPanel("ehr", "snomed_tags", "Diagnostic Codes", EHRService.FORM_SECTION_LOCATION.Tabs), //Added 5-23-2015 Blasa new SimpleGridPanel("study", "housing", "Housing Transfers",EHRService.FORM_SECTION_LOCATION.Tabs) - //Removed temporarily 7-2-2015 Blasa - // new SimpleGridPanel("study", "encounters", "TB Tests",EHRService.FORM_SECTION_LOCATION.Tabs) + )); @@ -74,10 +73,8 @@ public ClinicalReportFormType(DataEntryFormContext ctx, Module owner) for (FormSection s : this.getFormSections()) { s.addConfigSource("ClinicalDefaults"); - s.addConfigSource("ClinicalReport"); - - //Removed temporarily 7-2-2015 Blasa - // s.addConfigSource("TBProcedure"); +// s.addConfigSource("ClinicalReport"); + s.addConfigSource("ClinicalReport_ONPRC"); if (!s.getName().equals("Clinical Remarks")) s.addConfigSource("ClinicalReportChild"); @@ -103,8 +100,6 @@ public ClinicalReportFormType(DataEntryFormContext ctx, Module owner) addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/panel/HousingDataEntryPanel.js")); setJavascriptClass("ONPRC_EHR.panel.HousingDataEntryPanel"); - //Removed temporarily 7-2-2015 Blasa - // addClientDependency(ClientDependency.fromFilePath("ehr/model/sources/TBProcedure.js")); } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalRoundsFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalRoundsFormType.java index acb9b02ca..8f06f3c4b 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalRoundsFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ClinicalRoundsFormType.java @@ -63,7 +63,9 @@ public ClinicalRoundsFormType(DataEntryFormContext ctx, Module owner) for (FormSection s : this.getFormSections()) { s.addConfigSource("ClinicalDefaults"); - s.addConfigSource("ClinicalRounds"); + + //Modified: 10-5-2017 R.Blasa + s.addConfigSource("ClinicalRounds_ONPRC"); s.setTemplateMode(AbstractFormSection.TEMPLATE_MODE.NONE); } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/DrugAdministrationFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/DrugAdministrationFormSection.java new file mode 100644 index 000000000..2aff3aa75 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/DrugAdministrationFormSection.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2017-2018 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.SimpleFormSection; +import org.labkey.api.view.template.ClientDependency; + +import java.util.List; +import java.util.function.Supplier; + +/** + * User: bimber + * Date: 7/7/13 + * Time: 10:36 AM + */ +public class DrugAdministrationFormSection extends SimpleFormSection +{ + protected boolean _showAddTreatments = true; + public static final String LABEL = "Medications/Treatments Given"; + + public DrugAdministrationFormSection() + { + this(EHRService.FORM_SECTION_LOCATION.Body, LABEL, false); + } + + public DrugAdministrationFormSection(String label) + { + this(EHRService.FORM_SECTION_LOCATION.Body, label, false); + } + + public DrugAdministrationFormSection(EHRService.FORM_SECTION_LOCATION location) + { + this(location, LABEL, false); + } + + public DrugAdministrationFormSection(boolean includeAddScheduledTreatmentButton) + { + this(EHRService.FORM_SECTION_LOCATION.Body, LABEL, includeAddScheduledTreatmentButton); + } + + public DrugAdministrationFormSection(Supplier addScheduledTreatmentWindowClientDependency) + { + this(EHRService.FORM_SECTION_LOCATION.Body, LABEL, addScheduledTreatmentWindowClientDependency); + } + + public DrugAdministrationFormSection(EHRService.FORM_SECTION_LOCATION location, String label, boolean includeAddScheduledTreatmentButton) + { + this(location, label, includeAddScheduledTreatmentButton ? ClientDependency.supplierFromPath("ehr/window/AddScheduledTreatmentWindow.js") : null); + } + + public DrugAdministrationFormSection(EHRService.FORM_SECTION_LOCATION location, String label, Supplier addScheduledTreatmentWindowClientDependency) + { + super("study", "Drug Administration", label, "ehr-gridpanel"); + setClientStoreClass("EHR.data.DrugAdministrationRunsClientStore"); + addClientDependency(ClientDependency.supplierFromPath("ehr/data/DrugAdministrationRunsClientStore.js")); + +// Added: 8-28-2020 R.Blasa + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/window/SedationWindow.js")); + + addClientDependency(ClientDependency.supplierFromPath("ehr/window/RepeatSelectedWindow.js")); + if (addScheduledTreatmentWindowClientDependency != null) + { + addClientDependency(addScheduledTreatmentWindowClientDependency); + addClientDependency(ClientDependency.supplierFromPath("ehr/form/field/SnomedTreatmentCombo.js")); + } + + setLocation(location); + setTabName("Medications"); + } + + @Override + public List getTbarButtons() + { + List defaultButtons = super.getTbarButtons(); + defaultButtons.add(0, "SEDATIONHELPER"); + + int idx = defaultButtons.indexOf("SELECTALL"); + if (idx > -1) + defaultButtons.add(idx + 1, "DRUGAMOUNTHELPER"); + else + defaultButtons.add("DRUGAMOUNTHELPER"); + + return defaultButtons; + } + + @Override + public List getTbarMoreActionButtons() + { + List defaultButtons = super.getTbarMoreActionButtons(); + defaultButtons.add("REPEAT_SELECTED"); + + if (_showAddTreatments) + defaultButtons.add("ADDTREATMENTS"); + + return defaultButtons; + } +} + diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/EncounterProcedureFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/EncounterProcedureFormSection.java new file mode 100644 index 000000000..14cc5b5d4 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/EncounterProcedureFormSection.java @@ -0,0 +1,40 @@ + +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.view.template.ClientDependency; + +//Created: 3-30-2017 R.Blasa +public class EncounterProcedureFormSection extends SimpleGridPanel +{ + public EncounterProcedureFormSection() + { + this(EHRService.FORM_SECTION_LOCATION.Body); + } + + public EncounterProcedureFormSection(EHRService.FORM_SECTION_LOCATION location) + { + super("study", "encounters", "Procedures", location); + //Added 3-30-2017 R.Blasa + addClientDependency(ClientDependency.supplierFromPath("ehr/data/ClinicalEncountersClientStore.js")); + setClientStoreClass("EHR.data.ClinicalEncountersClientStore"); + + + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/GeneticAncestryFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/GeneticAncestryFormType.java new file mode 100644 index 000000000..6c45fb295 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/GeneticAncestryFormType.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.FormSection; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.ehr.dataentry.TaskFormSection; +import org.labkey.api.ehr.dataentry.UnsaveableTask; +import org.labkey.api.module.Module; + +import java.util.Arrays; + +/** + * User: bimber + * Date: 7/29/13 + * Time: 5:03 PM + */ +public class GeneticAncestryFormType extends UnsaveableTask +{ + public static final String NAME = "geneticAncestry"; + + public GeneticAncestryFormType(DataEntryFormContext ctx, Module owner) + { + super(ctx, owner, NAME, "Genetic Ancestry", "Colony Management", Arrays.asList( + new TaskFormSection(), + new AnimalDetailsFormSection(), + new SimpleGridPanel("study", "geneticAncestry", "Genetic Ancestry") + )); + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/GrossFindingsFormPanelSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/GrossFindingsFormPanelSection.java index 027594fb9..8d2c13b3b 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/GrossFindingsFormPanelSection.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/GrossFindingsFormPanelSection.java @@ -33,6 +33,9 @@ public GrossFindingsFormPanelSection() addClientDependency(ClientDependency.supplierFromPath("ehr/model/sources/EncounterChild.js")); addClientDependency(ClientDependency.supplierFromPath("ehr/window/EncounterAddRecordWindow.js")); + //Added: 5-17-2018 R.Blasa + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/Gross_Finding.css")); + addConfigSource("Encounter"); addConfigSource("EncounterChild"); } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/LabworkRequestFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/LabworkRequestFormType.java index 5ad0da829..3d1715692 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/LabworkRequestFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/LabworkRequestFormType.java @@ -40,7 +40,10 @@ public LabworkRequestFormType(DataEntryFormContext ctx, Module owner) { super(ctx, owner, NAME, LABEL, "Requests", Arrays.asList( new RequestFormSection(), - new LabworkRequestInstructionsFormSection(), + + //Modified: 1-14-2019 R. Blasa No longer need Merge web link +// new LabworkRequestInstructionsFormSection(), + new AnimalDetailsFormSection(), new ClinpathRunsFormSection(true) )); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/MedSignoffFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/MedSignoffFormType.java index 0b3606454..bd3b95dee 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/MedSignoffFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/MedSignoffFormType.java @@ -25,7 +25,11 @@ import org.labkey.api.ehr.security.EHRClinicalEntryPermission; import org.labkey.api.module.Module; import org.labkey.api.module.ModuleLoader; +import org.labkey.api.security.Group; +import org.labkey.api.security.GroupManager; +import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.view.template.ClientDependency; +import org.labkey.security.xml.GroupEnumType; import java.util.Arrays; @@ -68,4 +72,17 @@ protected boolean canInsert() return super.canInsert(); } + + //Modified: 12-5-2019 R.Blasa + @Override + public boolean isVisible() + { + Group g = GroupManager.getGroup(getCtx().getContainer(), "ASB Support", GroupEnumType.SITE); + if (g != null && getCtx().getUser().isInGroup(g.getUserId()) && !getCtx().getContainer().hasPermission(getCtx().getUser(), AdminPermission.class)) + { + return false; + } + + return super.isVisible(); + } } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NHPRProcessingFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NHPRProcessingFormType.java new file mode 100644 index 000000000..d2bcec99f --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NHPRProcessingFormType.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.FormSection; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.ehr.dataentry.TaskForm; +import org.labkey.api.ehr.dataentry.TaskFormSection; +import org.labkey.api.ehr.dataentry.UnsaveableTask; +import org.labkey.api.ehr.security.EHRClinicalEntryPermission; +import org.labkey.api.module.Module; +import org.labkey.api.view.template.ClientDependency; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +//Created: 4-5-2017 R.Blasa +public class NHPRProcessingFormType extends UnsaveableTask +{ + public static final String NAME = "NHPRProcess"; + + public NHPRProcessingFormType(DataEntryFormContext ctx, Module owner) + { + super(ctx, owner, NAME, "NHPR Processing", "Colony Management", Arrays.asList( + new TaskFormSection(), + new AnimalDetailsFormSection(), + new AssignmentFormSection(), + new SimpleGridPanel("study", "notes", "DCM Notes"), + new SimpleGridPanel("study", "flags", "Flags") + )); + + //Added 2-23-2016 R.Blasa + for (FormSection s : this.getFormSections()) + { + s.addConfigSource("ProjectAnimalConditions"); + } + + + //Added 5-26-2016 R.Blasa + addClientDependency(ClientDependency.supplierFromPath("/onprc_ehr/model/sources/ProjectAnimalConditions.js")); + + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyFormType.java index 5579a065e..99013427c 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyFormType.java @@ -51,7 +51,8 @@ public NecropsyFormType(DataEntryFormContext ctx, Module owner) new NonStoreFormSection("Instructions", "Instructions", "ehr-necropsyinstructionspanel", Arrays.asList(ClientDependency.supplierFromPath("ehr/panel/NecropsyInstructionsPanel.js"))), new TaskFormSection(), new ClinicalEncountersFormPanelSection("Necropsy"), - new AnimalDetailsFormSection(), + //Modified: 12-20-2018 R.Blasa + new AnimalDetailssFormSection(), new GrossFindingsFormPanelSection(), new PathologyFormSection("ehr", "encounter_participants", "Staff"), new PathologyNotesFormPanelSection(), @@ -61,9 +62,13 @@ public NecropsyFormType(DataEntryFormContext ctx, Module owner) //new PathologyTissueDistFormSection(), //new PathologyFormSection("study", "measurements", "Measurements"), new PathologyDiagnosesFormSection("study", "histology", "Histologic Findings"), - new PathologyDiagnosesFormSection("study", "pathologyDiagnoses", "Diagnoses"), - new SimpleFormSection("study", "tissue_samples", "Tissue Samples", "onprc_ehr-dragdropgridpanel"), - new SimpleFormSection("study", "organ_weights", "Organ Weights", "onprc_ehr-dragdropgridpanel") + new PathologyDiagnosesFormSection("study", "pathologyDiagnoses", "Diagnoses") + + //Removed: 2-4-2020 R.Blassa Commented temporarily Note: This form was excluded 17.2 version +// new SimpleFormSection("study", "tissue_samples", "Tissue Samples", "onprc_ehr-dragdropgridpanel") + + //Removed: 1-29-2020 R.Blassa Commented temporarily Note: This form was excluded 17.2 version + // new SimpleFormSection("study", "organ_weights", "Organ Weights", "onprc_ehr-dragdropgridpanel") )); for (FormSection s : this.getFormSections()) diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyRequestInfoFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyRequestInfoFormSection.java index d3ab7e041..7b2db6847 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyRequestInfoFormSection.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/NecropsyRequestInfoFormSection.java @@ -9,10 +9,12 @@ public class NecropsyRequestInfoFormSection extends RequestFormSection protected Integer maxItemsPerColumn = 3; @Override - public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) { + public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) + { JSONObject ret = super.toJSON(ctx, includeFormElements); - if ( maxItemsPerColumn != null ) { + if (maxItemsPerColumn != null) + { // Make the form appear in two columns JSONObject formConfig = new JSONObject(ret.get("formConfig")); formConfig.put("maxItemsPerCol", maxItemsPerColumn); @@ -21,4 +23,4 @@ public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) return ret; } -} \ No newline at end of file +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ParentageFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ParentageFormType.java index 307419aae..29ab619bf 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ParentageFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ParentageFormType.java @@ -17,10 +17,12 @@ import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.FormSection; import org.labkey.api.ehr.dataentry.SimpleGridPanel; import org.labkey.api.ehr.dataentry.TaskFormSection; import org.labkey.api.ehr.dataentry.UnsaveableTask; import org.labkey.api.module.Module; +import org.labkey.api.view.template.ClientDependency; import java.util.Arrays; @@ -40,5 +42,15 @@ public ParentageFormType(DataEntryFormContext ctx, Module owner) new AnimalDetailsFormSection(), new SimpleGridPanel("study", "parentage", "Parentage") )); + + //Added 12-27-2017 R.Blasa + for (FormSection s : this.getFormSections()) + { + s.addConfigSource("ParentageProperty"); + } + + + //Added 5-26-2016 R.Blasa + addClientDependency(ClientDependency.supplierFromPath("/onprc_ehr/model/sources/Parentage_Properties.js")); } } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathDeathFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathDeathFormType.java new file mode 100644 index 000000000..8b7a32f33 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathDeathFormType.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2014-2018 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.ehr.dataentry.TaskFormSection; +import org.labkey.api.ehr.dataentry.UnsaveableTask; +import org.labkey.api.ehr.security.EHRCompletedInsertPermission; +import org.labkey.api.ehr.security.EHRPathologyEntryPermission; +import org.labkey.api.ehr.security.EHRSurgeryEntryPermission; +import org.labkey.api.module.Module; + +import java.util.Arrays; + +//Created: 8-18-2020 R.Blasa + + +public class PathDeathFormType extends UnsaveableTask +{ + public static final String NAME = "Pathologydeath"; + + public PathDeathFormType(DataEntryFormContext ctx, Module owner) + { + super(ctx, owner, NAME, "Death", "Pathology", Arrays.asList( + new DeathInstructionsFormSection(), + new TaskFormSection(), + new AnimalDetailsFormSection(), + new SimpleGridPanel("study", "deaths", "Deaths") + )); + } + + @Override + protected boolean canInsert() + { + if (!getCtx().getContainer().hasPermission(getCtx().getUser(), EHRPathologyEntryPermission.class)) + return false; + + return EHRService.get().hasPermission("study", "deaths", getCtx().getContainer(), getCtx().getUser(), EHRCompletedInsertPermission.class); + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyDiagnosesFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyDiagnosesFormSection.java index ce99ce277..270701803 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyDiagnosesFormSection.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyDiagnosesFormSection.java @@ -15,6 +15,8 @@ */ package org.labkey.onprc_ehr.dataentry; +import org.json.JSONObject; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; import org.labkey.api.view.template.ClientDependency; import java.util.ArrayList; @@ -36,6 +38,26 @@ public PathologyDiagnosesFormSection(String schemaName, String queryName, String addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/grid/DragDropGridPanel.js")); addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/buttons/pathologyButtons.js")); setXtype("onprc_ehr-dragdropgridpanel"); + + //Added: 10-31-2018 R.Blasa address issues with text font size + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/Gross_Finding.css")); + } + +// Added: 6-26-2017 R.Blasa Include tool bar at bottom grid + @Override + public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) + { + JSONObject jsonObject = super.toJSON(ctx, includeFormElements); + jsonObject.put("topAndBottomButtons", true); + return jsonObject; + } + + @Override + public List getTbarButtons() + { + List result = super.getTbarButtons(); + result.add("PATH_SAVE_DRAFT"); + return result; } @Override diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyTissuesFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyTissuesFormType.java index a4cc04103..4d6295e28 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyTissuesFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/PathologyTissuesFormType.java @@ -16,9 +16,11 @@ package org.labkey.onprc_ehr.dataentry; import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.AbstractFormSection; import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; import org.labkey.api.ehr.dataentry.DataEntryFormContext; import org.labkey.api.ehr.dataentry.FormSection; +import org.labkey.api.ehr.dataentry.SimpleFormPanelSection; import org.labkey.api.ehr.dataentry.SimpleFormSection; import org.labkey.api.ehr.dataentry.TaskForm; import org.labkey.api.ehr.dataentry.TaskFormSection; @@ -51,7 +53,9 @@ public PathologyTissuesFormType(DataEntryFormContext ctx, Module owner) new DrugAdministrationFormSection(EHRService.FORM_SECTION_LOCATION.Tabs, DrugAdministrationFormSection.LABEL, ClientDependency.supplierFromPath("onprc_ehr/window/ONPRC_AddScheduledTreatmentWindow.js")), new SimpleFormSection("study", "tissue_samples", "Tissues/Weights", "onprc_ehr-dragdropgridpanel", EHRService.FORM_SECTION_LOCATION.Tabs), new TissueDistFormSection(), - new SimpleFormSection("study", "measurements", "Measurements", "onprc_ehr-dragdropgridpanel", EHRService.FORM_SECTION_LOCATION.Tabs) + +// Added: 6-26-2017 R.Blasa + new TissueMeasurementsFormSection() )); if (ctx.getContainer().getActiveModules().contains(ModuleLoader.getInstance().getModule("onprc_billing"))) @@ -63,6 +67,12 @@ public PathologyTissuesFormType(DataEntryFormContext ctx, Module owner) { s.addConfigSource("Pathology"); s.addConfigSource("Necropsy"); + s.addConfigSource("PathTissues"); + +// Added: 6-1-2017 R.Blasa + if (s instanceof SimpleFormSection ) + s.setTemplateMode(AbstractFormSection.TEMPLATE_MODE.NO_ID); + } addClientDependency(ClientDependency.supplierFromPath("ehr/model/sources/Pathology.js")); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ProcedureRequestBulkEditFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ProcedureRequestBulkEditFormType.java new file mode 100644 index 000000000..e7959f2ce --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/ProcedureRequestBulkEditFormType.java @@ -0,0 +1,27 @@ + + +//Created: 10-9-2017 R.Blasa ASB Service Request (Procedures) + +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.dataentry.BulkEditFormType; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.FormSection; +import org.labkey.api.module.Module; + +import java.util.Arrays; + +/** + + */ +public class ProcedureRequestBulkEditFormType extends BulkEditFormType +{ + public static final String NAME = "ProcedureBulkEdit"; + + public ProcedureRequestBulkEditFormType(DataEntryFormContext ctx, Module owner) + { + super(ctx, owner, NAME, "Procedure Requests", "Clinical", "lsid", Arrays.asList( + new EncounterProcedureFormSection() + )); + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SingleSurgeryFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SingleSurgeryFormType.java index 50ba175e1..e98836ab0 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SingleSurgeryFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SingleSurgeryFormType.java @@ -74,6 +74,12 @@ public SingleSurgeryFormType(DataEntryFormContext ctx, Module owner) { s.addConfigSource("Encounter"); s.addConfigSource("Surgery"); + + //Added: 9-6-2017 R.Blasa + s.addConfigSource("Surgery_Blood"); + + //Added: 10-13-2017 R.Blasa + s.addConfigSource("Biopsy_Staff"); } } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/StudyDetailsFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/StudyDetailsFormSection.java new file mode 100644 index 000000000..8c60bd880 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/StudyDetailsFormSection.java @@ -0,0 +1,25 @@ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.view.template.ClientDependency; + +/** + * User: Kolli + * Date: 02/20/2020 + */ +public class StudyDetailsFormSection extends SimpleGridPanel +{ + public StudyDetailsFormSection() + { + this(EHRService.FORM_SECTION_LOCATION.Body); + } + + public StudyDetailsFormSection(EHRService.FORM_SECTION_LOCATION location) + { + super("study", "StudyDetails", "Study Details", location); + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/StudyDetailsProperties.js")); + addConfigSource("StudyDetails"); + _showLocation = true; + } +} \ No newline at end of file diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgeryFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgeryFormType.java index 9eb28fb10..d53b31f0d 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgeryFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgeryFormType.java @@ -74,6 +74,12 @@ public SurgeryFormType(DataEntryFormContext ctx, Module owner) { s.addConfigSource("Encounter"); s.addConfigSource("Surgery"); + + //Added: 9-6-2017 R.Blasa + s.addConfigSource("Surgery_Blood"); + + //Added: 10-13-2017 R.Blasa + s.addConfigSource("Biopsy_Staff"); } } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgicalRoundsFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgicalRoundsFormType.java index 9695aa954..7bd3cd163 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgicalRoundsFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/SurgicalRoundsFormType.java @@ -26,6 +26,10 @@ import org.labkey.api.security.SecurityManager; import org.labkey.api.security.UserPrincipal; import org.labkey.api.view.template.ClientDependency; +import org.labkey.security.xml.GroupEnumType; +import org.labkey.api.security.GroupManager; +import org.labkey.api.security.Group; +import org.labkey.api.security.permissions.AdminPermission; import java.util.Arrays; @@ -59,6 +63,19 @@ public SurgicalRoundsFormType(DataEntryFormContext ctx, Module owner) setDisplayReviewRequired(true); } + //Added: 7-26-2018 R.Blasa + @Override + public boolean isVisible() + { + Group g = GroupManager.getGroup(getCtx().getContainer(), "Surgery Research", GroupEnumType.SITE); + if (g != null && getCtx().getUser().isInGroup(g.getUserId()) && !getCtx().getContainer().hasPermission(getCtx().getUser(), AdminPermission.class)) + { + return false; + } + return super.isVisible(); + } + + @Override protected boolean canInsert() { diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TBObservationFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TBObservationFormSection.java new file mode 100644 index 000000000..7a3ff4041 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TBObservationFormSection.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.AbstractFormSection; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; + + +//Created: 6-27-2019 R.Blasa + +public class TBObservationFormSection extends SimpleGridPanel +{ + public TBObservationFormSection() + { + this(EHRService.FORM_SECTION_LOCATION.Body); + setTemplateMode(AbstractFormSection.TEMPLATE_MODE.NONE); + } + + public TBObservationFormSection(EHRService.FORM_SECTION_LOCATION location) + { + super("study", "Clinical Observations", "TB TST Scores", location); + + + + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TBTestObservationFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TBTestObservationFormType.java new file mode 100644 index 000000000..d6b80ece2 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TBTestObservationFormType.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2013-2016 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.FormSection; +import org.labkey.api.ehr.dataentry.TaskForm; +import org.labkey.api.ehr.dataentry.TaskFormSection; +import org.labkey.api.ehr.security.EHRClinicalEntryPermission; +import org.labkey.api.module.Module; +import org.labkey.api.view.template.ClientDependency; + +import java.util.Arrays; + +//Created: 6-27-2019 R.Blasa +public class TBTestObservationFormType extends TaskForm +{ + public static final String NAME = "TB TST Scores"; + + public TBTestObservationFormType(DataEntryFormContext ctx, Module owner) + { + super(ctx, owner, NAME, "TB TST Scores", "Clinical", Arrays.asList( + new TaskFormSection(), + new AnimalDetailsFormSection(), + new TBObservationFormSection() + + )); + + for (FormSection s : this.getFormSections()) + { + s.addConfigSource("TB_TestObservation"); + + } + + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/TB_TestObservation.js")); + + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/form/field/TB_TST_Scores_Type.js")); + + + + } + + + + @Override + protected boolean canInsert() + { + if (!getCtx().getContainer().hasPermission(getCtx().getUser(), EHRClinicalEntryPermission.class)) + return false; + + return super.canInsert(); + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueDistFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueDistFormSection.java index 26c25fb90..95afd3874 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueDistFormSection.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueDistFormSection.java @@ -15,8 +15,10 @@ */ package org.labkey.onprc_ehr.dataentry; +import org.json.JSONObject; import org.labkey.api.ehr.EHRService; import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; import org.labkey.api.view.template.ClientDependency; import java.util.List; @@ -36,6 +38,14 @@ public TissueDistFormSection() addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/window/CopyTissuesWindow.js")); addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/grid/DragDropGridPanel.js")); } +// Added: 6-26-2017 R.Blasa Include tool bar at bottom grid + @Override + public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) + { + JSONObject jsonObject = super.toJSON(ctx, includeFormElements); + jsonObject.put("topAndBottomButtons", true); + return jsonObject; + } @Override public List getTbarMoreActionButtons() diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueMeasurementsFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueMeasurementsFormSection.java new file mode 100644 index 000000000..032b9e9f2 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueMeasurementsFormSection.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.json.JSONObject; +import org.labkey.api.ehr.EHRService; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.view.template.ClientDependency; + +//Created: 6-26-2017 R.Blasa + +public class TissueMeasurementsFormSection extends SimpleGridPanel +{ + public TissueMeasurementsFormSection() + { + super("study", "measurements", "Measurements"); + setLocation(EHRService.FORM_SECTION_LOCATION.Tabs); + setXtype("onprc_ehr-dragdropgridpanel"); + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/grid/DragDropGridPanel.js")); + } + + // Added: 6-26-2017 R.Blasa Include tool bar at bottom grid + @Override + public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) + { + JSONObject jsonObject = super.toJSON(ctx, includeFormElements); + jsonObject.put("topAndBottomButtons", true); + return jsonObject; + } + +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueWeightsFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueWeightsFormSection.java new file mode 100644 index 000000000..3327da6b2 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TissueWeightsFormSection.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.dataentry; + +import org.json.JSONObject; +import org.labkey.api.ehr.*; +import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.SimpleGridPanel; +import org.labkey.api.view.template.ClientDependency; + + +//Created: 6-26-2017 R.Blasa + +public class TissueWeightsFormSection extends SimpleGridPanel +{ + public TissueWeightsFormSection() + { + super("study", "tissue_samples", "Tissues/Weights"); + setLocation(EHRService.FORM_SECTION_LOCATION.Tabs); + setXtype("onprc_ehr-dragdropgridpanel"); + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/grid/DragDropGridPanel.js")); + } + + // Added: 6-26-2017 R.Blasa Include tool bar at bottom grid + @Override + public JSONObject toJSON(DataEntryFormContext ctx, boolean includeFormElements) + { + JSONObject jsonObject = super.toJSON(ctx, includeFormElements); + jsonObject.put("topAndBottomButtons", true); + return jsonObject; + } + +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentOrdersFormSection.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentOrdersFormSection.java index 2bb208325..e55cb1c1f 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentOrdersFormSection.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentOrdersFormSection.java @@ -16,7 +16,6 @@ package org.labkey.onprc_ehr.dataentry; import org.labkey.api.ehr.EHRService; -import org.labkey.api.ehr.dataentry.DrugAdministrationFormSection; import org.labkey.api.view.template.ClientDependency; import java.util.List; @@ -40,6 +39,11 @@ public TreatmentOrdersFormSection(EHRService.FORM_SECTION_LOCATION location) setLabel("Medication/Treatment Orders"); setQueryName("Treatment Orders"); _showAddTreatments = false; + +// Modified: 7-29-2020 Set Remarks information + setClientStoreClass("ONPRC_EHR.data.TreatmentOrdersClientStore"); + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/data/sources/TreatmentOrdersClientStore.js")); + } @Override diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentsFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentsFormType.java index 6bd6f1c45..8b6319e44 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentsFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/TreatmentsFormType.java @@ -18,6 +18,7 @@ import org.labkey.api.ehr.EHRService; import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; import org.labkey.api.ehr.dataentry.DataEntryFormContext; +import org.labkey.api.ehr.dataentry.FormSection; import org.labkey.api.ehr.dataentry.TaskForm; import org.labkey.api.ehr.dataentry.TaskFormSection; import org.labkey.api.ehr.dataentry.DrugAdministrationFormSection; @@ -50,6 +51,14 @@ public TreatmentsFormType(DataEntryFormContext ctx, Module owner) new TreatmentOrdersFormSection() )); + //Added: 10-7-2019 R.Blasa + for (FormSection s : this.getFormSections()) + { + s.addConfigSource("TreatmentDrugsClinical"); + + } + addClientDependency(ClientDependency.supplierFromPath("onprc_ehr/model/sources/TreatmentDrugsClinical.js")); + if (ctx.getContainer().getActiveModules().contains(ModuleLoader.getInstance().getModule("onprc_billing"))) { addSection(new MiscChargesFormSection(EHRService.FORM_SECTION_LOCATION.Body)); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/WeightFormType.java b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/WeightFormType.java index 17ca8f841..05323d736 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/WeightFormType.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/dataentry/WeightFormType.java @@ -15,6 +15,7 @@ */ package org.labkey.onprc_ehr.dataentry; + import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection; import org.labkey.api.ehr.dataentry.DataEntryFormContext; import org.labkey.api.ehr.dataentry.FormSection; @@ -23,10 +24,15 @@ import org.labkey.api.ehr.dataentry.WeightFormSection; import org.labkey.api.ehr.dataentry.DrugAdministrationFormSection; import org.labkey.api.module.Module; +import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.view.template.ClientDependency; +import org.labkey.api.security.GroupManager; +import org.labkey.api.security.Group; +import org.labkey.security.xml.GroupEnumType; import java.util.Arrays; + /** * User: bimber * Date: 7/29/13 @@ -54,4 +60,15 @@ public WeightFormType(DataEntryFormContext ctx, Module owner) s.addConfigSource("Weight"); } } +//Added: 5-16-2018 R.Blasa + @Override + public boolean isVisible() + { + Group g = GroupManager.getGroup(getCtx().getContainer(), "Research Clinical Entry", GroupEnumType.SITE); + if (g != null && getCtx().getUser().isInGroup(g.getUserId()) && !getCtx().getContainer().hasPermission(getCtx().getUser(), AdminPermission.class)) + { + return false; + } + return super.isVisible(); + } } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/ActiveDrugsGivenDemographicsProvider.java b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/ActiveDrugsGivenDemographicsProvider.java new file mode 100644 index 000000000..3305e0603 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/ActiveDrugsGivenDemographicsProvider.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.demographics; + +import org.labkey.api.data.CompareType; +import org.labkey.api.data.SimpleFilter; +import org.labkey.api.ehr.demographics.AbstractListDemographicsProvider; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; +import org.apache.commons.lang3.time.DateUtils; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.Calendar; + + +//Created: 10-4-2019 R.Blasa 72 hours Drugs Given +public class ActiveDrugsGivenDemographicsProvider extends AbstractListDemographicsProvider +{ + public ActiveDrugsGivenDemographicsProvider(Module module) + { + super(module, "study", "DrugsGiven72hours", "activeDrugs"); + _supportsQCState = false; + } + + protected Set getFieldKeys() + { + Set keys = new HashSet(); + keys.add(FieldKey.fromString("Id")); + keys.add(FieldKey.fromString("code")); + keys.add(FieldKey.fromString("meaning")); + keys.add(FieldKey.fromString("enddate")); + keys.add(FieldKey.fromString("date")); + keys.add(FieldKey.fromString("route")); + keys.add(FieldKey.fromString("ElapseHours")); + keys.add(FieldKey.fromString("amountAndVolume")); + + keys.add(FieldKey.fromString("remark")); + keys.add(FieldKey.fromString("category")); + + return keys; + } + + @Override + public boolean requiresRecalc(String schema, String query) + { + return ("study".equalsIgnoreCase(schema) && ("drug".equalsIgnoreCase(query) || "treatment_order".equalsIgnoreCase(query))) ; + + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/ActiveTreatmentsXDemographicsProvider.java b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/ActiveTreatmentsXDemographicsProvider.java new file mode 100644 index 000000000..17dff8712 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/ActiveTreatmentsXDemographicsProvider.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.demographics; + +import org.labkey.api.data.CompareType; +import org.labkey.api.data.SimpleFilter; +import org.labkey.api.ehr.demographics.AbstractListDemographicsProvider; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; +import org.apache.commons.lang3.time.DateUtils; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.Calendar; + + +//Created: 4-7-2017 R.Blasa +public class ActiveTreatmentsXDemographicsProvider extends AbstractListDemographicsProvider +{ + public ActiveTreatmentsXDemographicsProvider(Module module) + { + super(module, "study", "Treatment Orders", "activeTreatments"); + _supportsQCState = false; + } + + protected Set getFieldKeys() + { + Set keys = new HashSet(); + keys.add(FieldKey.fromString("lsid")); + keys.add(FieldKey.fromString("Id")); + keys.add(FieldKey.fromString("code")); + keys.add(FieldKey.fromString("code/meaning")); + keys.add(FieldKey.fromString("date")); + keys.add(FieldKey.fromString("enddate")); + keys.add(FieldKey.fromString("performedby")); + keys.add(FieldKey.fromString("route")); + + keys.add(FieldKey.fromString("dosage")); + keys.add(FieldKey.fromString("dosage_units")); + keys.add(FieldKey.fromString("amount")); + keys.add(FieldKey.fromString("amount_units")); + keys.add(FieldKey.fromString("concentration")); + keys.add(FieldKey.fromString("concentration_units")); + keys.add(FieldKey.fromString("volume")); + keys.add(FieldKey.fromString("vol_units")); + keys.add(FieldKey.fromString("amountAndVolume")); + + keys.add(FieldKey.fromString("remark")); + keys.add(FieldKey.fromString("frequency")); + keys.add(FieldKey.fromString("frequency/meaning")); + + keys.add(FieldKey.fromString("amountWithUnits")); + keys.add(FieldKey.fromString("category")); + + return keys; + } + + @Override + public Collection getKeysToTest() + { + //for now, simply skip the whole provider. because different records can be active from day to day, this makes validation tricky + Set keys = new HashSet<>(super.getKeysToTest()); + keys.remove(_propName); + + return keys; + } + + @Override + protected SimpleFilter getFilter(Collection ids) + { Date roundedMax = new Date(); + roundedMax = DateUtils.truncate(roundedMax, Calendar.DATE); + + SimpleFilter filter = super.getFilter(ids); + filter.addCondition(FieldKey.fromString("enddateTimeCoalesced"),roundedMax, CompareType.GTE); + filter.addCondition(FieldKey.fromString("category"), "Husbandry", CompareType.NEQ_OR_NULL); + + return filter; + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/AssignedVetDemographicsProvider.java b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/AssignedVetDemographicsProvider.java index 5c63b71d6..10ac21f35 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/AssignedVetDemographicsProvider.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/AssignedVetDemographicsProvider.java @@ -63,6 +63,8 @@ public Collection getKeysToTest() @Override public boolean requiresRecalc(String schema, String query) { - return "study".equalsIgnoreCase(schema) && ("housing".equalsIgnoreCase(query) || "assignment".equalsIgnoreCase(query) || "cases".equalsIgnoreCase(query)); + return "study".equalsIgnoreCase(schema) && ("Demographics".equalsIgnoreCase(query) || "housing".equalsIgnoreCase(query) || "assignment".equalsIgnoreCase(query) || "cases".equalsIgnoreCase(query)) || + ("onprc_ehr".equalsIgnoreCase(schema) && "vet_assignment".equalsIgnoreCase(query)); } } + diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/FosterChildDemographicsProvider.java b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/FosterChildDemographicsProvider.java index 8eea6c269..854c06421 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/FosterChildDemographicsProvider.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/FosterChildDemographicsProvider.java @@ -15,6 +15,7 @@ */ package org.labkey.onprc_ehr.demographics; +import org.labkey.api.data.Sort; import org.labkey.api.ehr.demographics.AbstractListDemographicsProvider; import org.labkey.api.module.Module; import org.labkey.api.query.FieldKey; @@ -45,12 +46,18 @@ protected Collection getFieldKeys() return keys; } + @Override + protected Sort getSort() + { + + return new Sort("-date"); + } + @Override public boolean requiresRecalc(String schema, String query) { - return ("study".equalsIgnoreCase(schema) && "Parentage".equalsIgnoreCase(query)) || - ("study".equalsIgnoreCase(schema) && "Birth".equalsIgnoreCase(query)) || - ("study".equalsIgnoreCase(schema) && "Demographics".equalsIgnoreCase(query)); + return ("study".equalsIgnoreCase(schema) && "Parentage".equalsIgnoreCase(query)) ; + } } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/GeneticAncestryDemographicsProvider.java b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/GeneticAncestryDemographicsProvider.java new file mode 100644 index 000000000..40e503473 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/GeneticAncestryDemographicsProvider.java @@ -0,0 +1,41 @@ +package org.labkey.onprc_ehr.demographics; + +import org.labkey.api.ehr.demographics.AbstractDemographicsProvider; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by bimber on 3/23/2017. + */ +public class GeneticAncestryDemographicsProvider extends AbstractDemographicsProvider +{ + public GeneticAncestryDemographicsProvider(Module module) + { + super(module, "study", "demographicsGeneticAncestry"); + _supportsQCState = false; + } + + @Override + public String getName() + { + return "Genetic Ancestry"; + } + + protected Collection getFieldKeys() + { + Set keys = new HashSet<>(); + keys.add(FieldKey.fromString("geneticAncestry")); + + return keys; + } + + @Override + public boolean requiresRecalc(String schema, String query) + { + return "study".equalsIgnoreCase(schema) && ("geneticAncestry".equalsIgnoreCase(query) || "Genetic Ancestry".equalsIgnoreCase(query)); + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/demographics/LastHousingDemographicsProvider.java b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/LastHousingDemographicsProvider.java new file mode 100644 index 000000000..514a2c155 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/demographics/LastHousingDemographicsProvider.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2013-2016 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.demographics; + +import org.labkey.api.ehr.demographics.AbstractDemographicsProvider; +import org.labkey.api.ehr.demographics.AbstractListDemographicsProvider; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +// Created: 12-19-2018 R.Blasa + +public class LastHousingDemographicsProvider extends AbstractListDemographicsProvider +{ + public LastHousingDemographicsProvider(Module module) + { + super(module, "study", "LastHousingLocation", "lastlocation"); + _supportsQCState = false; + } + + protected Collection getFieldKeys() + { + Set keys = new HashSet<>(); + keys.add(FieldKey.fromString("location")); + + + return keys; + } + + @Override + public boolean requiresRecalc(String schema, String query) + { + return ("study".equalsIgnoreCase(schema) && "Housing".equalsIgnoreCase(query)) || + ("study".equalsIgnoreCase(schema) && "Death".equalsIgnoreCase(query)) || + ("study".equalsIgnoreCase(schema) && "Departure".equalsIgnoreCase(query)) || + ("ehr_lookups".equalsIgnoreCase(schema) && "cage".equalsIgnoreCase(query)); + } + +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/history/DefaultSustainedReleaseDatasource.java b/onprc_ehr/src/org/labkey/onprc_ehr/history/DefaultSustainedReleaseDatasource.java new file mode 100644 index 000000000..5c016bfcb --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/history/DefaultSustainedReleaseDatasource.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2016-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.history; + +import org.apache.commons.lang3.StringUtils; +import org.labkey.api.data.Container; +import org.labkey.api.data.Results; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; +import org.labkey.api.util.DateUtil; +import org.labkey.api.util.PageFlowUtil; +import org.labkey.onprc_ehr.ONPRC_EHRModule; + +import java.sql.Date; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.Set; + +//Created: 11-20-2019 R.Blasa +public class DefaultSustainedReleaseDatasource extends AbstractEHRDataSource +{ + public DefaultSustainedReleaseDatasource(Module module) + { + super("study", "DrugsGiven72hours", "Clinical Sustained Release Medication", "Clinical", module); + } + + @Override + protected String getHtml(Container c, Results rs, boolean redacted) throws SQLException + { + + + String end = rs.getString(FieldKey.fromString("enddate")); + String start = rs.getString(FieldKey.fromString("date")); + + + StringBuilder sb = new StringBuilder(); + + + sb.append("Starting Date: ").append(start); + sb.append("\n"); + + + if (rs.getObject(FieldKey.fromString("enddate")) != null) + { + sb.append("Ending Date: ").append(end); + sb.append("\n"); + } +// sb.append(safeAppend(rs, "Starting Date: ", "start")); +// sb.append(safeAppend(rs, "Ending Date:", "end")); + sb.append(safeAppend(rs, "Category", "category")); + sb.append(safeAppend(rs, "Medicaion", "meaning")); + sb.append(safeAppend(rs, "Medication Code", "code")); + sb.append(safeAppend(rs, "Amount/Volume", "amountAndVolume")); + sb.append(safeAppend(rs, "Route", "route")); + sb.append(safeAppend(rs, "Elapased Hours", "ElapseHours")); + sb.append(safeAppend(rs, "Remarks", "remark")); + + + return sb.toString(); + } + + @Override + protected Set getColumnNames() + { + + return PageFlowUtil.set("Id", "date", "enddate", "catgory", "meaning","route", "code","amountAndVolume","ElapseHours", "remark"); + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/history/ONPRCClinicalRemarksDataSource.java b/onprc_ehr/src/org/labkey/onprc_ehr/history/ONPRCClinicalRemarksDataSource.java new file mode 100644 index 000000000..bb3adb665 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/history/ONPRCClinicalRemarksDataSource.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.history; + +import org.labkey.api.data.Container; +import org.labkey.api.data.Results; +import org.labkey.api.ehr.history.AbstractDataSource; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; +import org.labkey.api.util.PageFlowUtil; + +import java.sql.SQLException; +import java.util.Set; + +/** + * User: bimber + * Date: 2/17/13 + * Time: 4:52 PM + */ +public class ONPRCClinicalRemarksDataSource extends AbstractDataSource +{ + public static final String REPLACED_SOAP = "Replaced SOAP"; + public static final String REPLACEMENT_SOAP = "Replacement SOAP"; + + public ONPRCClinicalRemarksDataSource(Module module) + { + super("study", "Clinical Remarks", "Clinical Remark", "Clinical", module); + setShowTime(true); + } + + @Override + protected String getCategoryText(Results rs) throws SQLException + { + String category = rs.getString("category"); + return (category == null || REPLACED_SOAP.equals(category) || REPLACEMENT_SOAP.equals(category) ? "Clinical" : category) + " Remark"; + } + + + @Override + protected String getPrimaryGroup(Results rs) throws SQLException + { + String category = rs.getString("category"); + return (category == null ? "Clinical" : category); + } + + @Override + protected String getHtml(Container c, Results rs, boolean redacted) throws SQLException + { + StringBuilder sb = new StringBuilder(); + sb.append(""); + + String category = rs.getString(FieldKey.fromString("category")); + + //this is a mechanism to allow individual notes to be replaced, yet remain in the record + if (REPLACED_SOAP.equals(category)) + { + return null; + } + + if (!redacted && rs.getObject(FieldKey.fromString("performedby")) != null) + { + String label; + if ("Replacement SOAP".equals(category)) + { + label = "Amended By"; + } + else + { + label = "Entered By"; + } + + appendNote(rs, "performedby", "" + label + "", sb); + } + + appendNote(rs, "hx", "Hx", sb); + appendNote(rs, "so", "S/O", sb); + appendNote(rs, "s", "S", sb); + appendNote(rs, "o", "O", sb); + appendNote(rs, "a", "A", sb); + appendNote(rs, "p", "P", sb); + appendNote(rs, "p2", "P2", sb); + appendNote(rs, "CEG_Plan", "CEG Plan", sb); + appendNote(rs, "remark", "Other Remark", sb); + + sb.append("
"); + + return sb.toString(); + } + + @Override + protected Set getColumnNames() + { + return PageFlowUtil.set("Id", "date", "enddate", "category", "hx", "so", "s", "o", "a", "p", "p2", "remark","CEG_Plan", "performedby"); + } + + private void appendNote(Results rs, String field, String label, StringBuilder sb) throws SQLException + { + if (rs.hasColumn(FieldKey.fromString(field)) && rs.getObject(FieldKey.fromString(field)) != null) + { + sb.append("" + PageFlowUtil.filter(label) + ":"); + sb.append(PageFlowUtil.filter(rs.getString(FieldKey.fromString(field)))); + sb.append(""); + } + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/history/ONPRCiStatLabworkType.java b/onprc_ehr/src/org/labkey/onprc_ehr/history/ONPRCiStatLabworkType.java new file mode 100644 index 000000000..8175d5bd2 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/history/ONPRCiStatLabworkType.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2013-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.history; + +import org.labkey.api.ehr.history.SortingLabworkType; +import org.labkey.api.module.Module; + +/** + * User: bimber + * Date: 3/19/13 + * Time: 11:02 PM + */ +public class ONPRCiStatLabworkType extends SortingLabworkType +{ + public ONPRCiStatLabworkType(Module module) + { + super("iStat", "study", "iStatRefRange", "iStat", module); + _normalRangeField = "range"; + _normalRangeStatusField = "status"; + } + + @Override + public boolean showPerformedBy() + { + return false; + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/BSUNotesNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/BSUNotesNotification.java new file mode 100644 index 000000000..f1b934277 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/BSUNotesNotification.java @@ -0,0 +1,59 @@ +package org.labkey.onprc_ehr.notification; + +import org.labkey.api.data.Container; +import org.labkey.api.module.Module; +import org.labkey.api.security.User; + +import java.util.Date; + +/** + * Created by kollil on 5/12/2017. + */ + +public class BSUNotesNotification extends ColonyAlertsNotification +{ + public BSUNotesNotification(Module owner) + { + super(owner); + } + + @Override + public String getName() + { + return "BSU Notes Notification"; + } + + @Override + public String getEmailSubject(Container c) + { + return "BSU Notes Alerts: " + getDateTimeFormat(c).format(new Date()); + } + + @Override + public String getCronString() + { + return "0 0 5 * * ?"; + } + + @Override + public String getScheduleDescription() + { + return "every day at 5:00AM"; + } + + @Override + public String getDescription() + { + return "The report is designed to send BSU Notes alerts on the day indicated by the action date!"; + } + + @Override + public String getMessageBodyHTML(Container c, User u) + { + StringBuilder msg = new StringBuilder(); + + bsuNotesAlert(c, u, msg); + + return msg.toString(); + } +} \ No newline at end of file diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/BehaviorNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/BehaviorNotification.java index 1f1dfacbb..b323ee611 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/BehaviorNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/BehaviorNotification.java @@ -114,17 +114,17 @@ public String getMessageBodyHTML(Container c, User u) return msg.toString(); } +// Modified: 9-7-2018 R.Blasa private void behaviorCaseSummary(Container c, User u, final StringBuilder msg) { - TableInfo ti = getStudySchema(c, u).getTable("cases"); + TableInfo ti = getStudySchema(c, u).getTable("mostRecentObservationsBehavior"); SimpleFilter filter = new SimpleFilter(FieldKey.fromString("isActive"), true); - filter.addCondition(FieldKey.fromString("category"), "Behavior"); TableSelector ts = new TableSelector(ti, PageFlowUtil.set("Id"), filter, null); long total = ts.getRowCount(); msg.append("Behavior Cases:

"); msg.append("There are " + total + " active behavior cases (this does not include cases closed for review). "); - String url = getExecuteQueryUrl(c, "study", "cases", "Open Behavior Cases") + "&query.isActive~eq=true"; + String url = getExecuteQueryUrl(c, "study", "mostRecentObservationsBehavior", "Open Behavior Case") + "&query.isActive~eq=true"; msg.append("Click here to view them"); msg.append("


"); } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/BirthHousingMismatchNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/BirthHousingMismatchNotification.java new file mode 100644 index 000000000..394da9fa1 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/BirthHousingMismatchNotification.java @@ -0,0 +1,60 @@ +package org.labkey.onprc_ehr.notification; + +import org.labkey.api.data.Container; +import org.labkey.api.module.Module; +import org.labkey.api.security.User; + +import java.util.Date; + +// Created: 8-7-2018 R.Blasa +public class BirthHousingMismatchNotification extends ColonyAlertsNotification +{ + public BirthHousingMismatchNotification(Module owner) + { + super(owner); + } + + @Override + public String getName() + { + return "Birth Initial Housing Locations Discrepancies Notification"; + } + + @Override + public String getEmailSubject(Container c) + { + return "Discrepancies between Birth and Initial Housing Locations Alerts: " + getDateTimeFormat(c).format(new Date()); + } + + @Override + public String getCronString() + { + return "0 0 6 * * ?"; + } + + @Override + public String getScheduleDescription() + { + return "every day at 6:00AM"; + } + + @Override + public String getDescription() + { + return "The report is designed to provide a daily summary of discrepancies between Birth and Initial Housing Locations."; + } + + @Override + public String getMessageBodyHTML(Container c, User u) + { + StringBuilder msg = new StringBuilder(); + + ValidateBiirthHousingHistory(c, u, msg); + + return msg.toString(); + } +} + + + + diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/ColonyAlertsNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/ColonyAlertsNotification.java index 7f72bb35e..1cef24377 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/ColonyAlertsNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/ColonyAlertsNotification.java @@ -45,9 +45,13 @@ import org.labkey.api.ehr.notification.AbstractEHRNotification; import org.labkey.onprc_ehr.ONPRC_EHRManager; +import org.labkey.api.data.ContainerFilter; +import org.labkey.api.data.ContainerFilterable; + import java.sql.ResultSet; import java.sql.SQLException; import java.text.DecimalFormat; +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -143,6 +147,7 @@ public String getMessageBodyHTML(final Container c, User u) //misc demographicsWithoutGender(c, u, msg); + getGeographicOriginConflicts(c, u, msg); incompleteBirthRecords(c, u, msg); birthRecordsWithoutDemographics(c, u, msg); @@ -340,13 +345,13 @@ protected void eventsInLast5Days(Container c, User u, StringBuilder msg) protected void roomsWithMixedViralStatus(final Container c, User u, final StringBuilder msg) { SimpleFilter filter = new SimpleFilter(FieldKey.fromString("distinctStatuses"), 1 , CompareType.GT); - filter.addCondition(FieldKey.fromString("room/housingCondition/value"), "ABSL2+;ABSL3", CompareType.CONTAINS_NONE_OF); + filter.addCondition(FieldKey.fromString("room/housingCondition/value"), "ABSL2+;Sequester/Containment;ABSL3", CompareType.CONTAINS_NONE_OF); TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("housingMixedViralStatus"), filter, new Sort("area,room")); long count = ts.getRowCount(); if (count > 0) { - msg.append("WARNING: The following " + count + " rooms have animals with mixed viral statuses, excluding ABSL2+ and ABSL3 rooms:

\n"); + msg.append("WARNING: The following " + count + " rooms have animals with mixed viral statuses, excluding ABSL2+,Sequester/Containment, and ABSL3 rooms:

\n"); msg.append("Click here to view this list

\n"); msg.append("\n"); @@ -399,6 +404,10 @@ protected void livingAnimalsWithoutWeight(final Container c, User u, final Strin { SimpleFilter filter = new SimpleFilter(FieldKey.fromString("calculated_status"), "Alive"); filter.addCondition(FieldKey.fromString("Id/MostRecentWeight/MostRecentWeightDate"), null, CompareType.ISBLANK); + //Added by Kolli1, 6/11. Excluding the Guinea pigs & Rabbits and showing only primates + //filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG+;RABBIT", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG", CompareType.NEQ); + Sort sort = new Sort(getStudy(c).getSubjectColumnName()); TableInfo ti = getStudySchema(c, u).getTable("Demographics"); @@ -449,6 +458,10 @@ protected void deadAnimalsWithActiveHousing(final Container c, User u, final Str Sort sort = new Sort(getStudy(c).getSubjectColumnName()); SimpleFilter filter = new SimpleFilter(FieldKey.fromString("Id/Dataset/Demographics/calculated_status"), "Alive", CompareType.NEQ_OR_NULL); filter.addCondition(FieldKey.fromString("enddate"), null, CompareType.ISBLANK); + //Added by Kolli1, 6/11. Excluding the Guinea pigs & Rabbits and showing only primates + //filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG+;RABBIT", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG", CompareType.NEQ); + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("Housing"), filter, sort); long count = ts.getRowCount(); if (count > 0) @@ -474,6 +487,10 @@ protected void livingAnimalsWithoutHousing(final Container c, User u, final Stri Sort sort = new Sort(getStudy(c).getSubjectColumnName()); SimpleFilter filter = new SimpleFilter(FieldKey.fromString("calculated_status"), "Alive"); filter.addCondition(FieldKey.fromString("Id/curLocation/room/room"), null, CompareType.ISBLANK); + //Added by Kolli1, 6/11. Excluding the Guinea pigs & Rabbits and showing only primates + //filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG+;RABBIT", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG", CompareType.NEQ); + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("Demographics"), filter, sort); long count = ts.getRowCount(); if (count > 0) @@ -603,6 +620,9 @@ protected void infantsNotAssignedToDamSPF(final Container c, User u, final Strin SimpleFilter filter = new SimpleFilter(FieldKey.fromString("matchesDamStatus"), false, CompareType.EQUAL); filter.addCondition(FieldKey.fromString("dam"), null, CompareType.NONBLANK); +// Added: 6-21-2017 R.Blasa + filter.addCondition(FieldKey.fromString("dam"), "", CompareType.NEQ); + Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1 * duration); filter.addCondition(FieldKey.fromString("birth"), cal.getTime(), CompareType.DATE_GTE); @@ -689,7 +709,7 @@ protected void duplicateCases(final Container c, User u, final StringBuilder msg long count = ts.getRowCount(); if (count > 0) { - msg.append("WARNING: There are " + count + " animals with multiple active cases of the same category. One of the duplicates should be closed or set for review
\n"); + msg.append("WARNING: There are " + count + " animals with multiple active cases of the same category. One of the duplicates should be closed or set for review
\n"); msg.append("

Click here to view them
\n\n"); msg.append("


\n\n"); } @@ -702,8 +722,6 @@ protected void recordsEnteredMoreThan7DaysAfter(final Container c, User u, final { int offset = 7; - - } @@ -912,6 +930,11 @@ protected void incompleteBirthRecords(final Container c, User u, final StringBui keys.add(FieldKey.fromString("Id/demographics/calculated_status")); keys.add(FieldKey.fromString("Id/demographics/geographic_origin")); +// Modified: 2-20-2020 R. Blasa + keys.add(FieldKey.fromString("date")); + keys.add(FieldKey.fromString("remark")); + + final Map cols = QueryService.get().getColumns(ti, keys); TableSelector ts = new TableSelector(ti, cols.values(), filter, new Sort(getStudy(c).getSubjectColumnName())); long count = ts.getRowCount(); @@ -919,7 +942,7 @@ protected void incompleteBirthRecords(final Container c, User u, final StringBui { msg.append("WARNING: There are " + count + " finalized birth records within the past 30 days lacking information:

\n"); msg.append("
"); - msg.append(""); + msg.append(""); ts.forEach(new Selector.ForEachBlock() { @Override @@ -933,6 +956,11 @@ public void exec(ResultSet object) throws SQLException msg.append(""); msg.append(""); msg.append(""); + + //Added: 2-20-2020 R.Blasa + msg.append(""); + msg.append(""); + msg.append(""); msg.append(""); msg.append(""); @@ -960,6 +988,198 @@ protected void protocolsExpiringSoon(final Container c, User u, final StringBuil } } + /** + * Kollil : Find the pregnant NHPs whose gestation time is past 30 days + */ + protected void checkPregnantGestation(final Container c, User u, final StringBuilder msg) + { + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("thirty_days_pastGestation_date"), new Date(), CompareType.DATE_LTE); + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("pregnancyGestationOverdue"), filter, null); + long count = ts.getRowCount(); + if (count > 0) + { + msg.append("WARNING: There are " + count + " pregnant animals 30 days past the gestation period.
\n"); + msg.append("

Click here to view them
\n\n"); + msg.append("


\n\n"); + } + else + { + msg.append("WARNING: There are no pregnant animals 30 days past the gestation period.
\n"); + } + } + + /** + * Kollil, 5/12/2017 : Send DCM Notes notification on the action date + */ + protected void dcmNotesAlert(final Container c, User u, final StringBuilder msg) + { + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("actiondate"), new Date(), CompareType.DATE_EQUAL); + filter.addCondition(FieldKey.fromString("category"), "Notes Pertaining to DAR", CompareType.EQUAL); + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("notes"), filter, null); + long count = ts.getRowCount(); + if (count > 0) + { + msg.append("WARNING: There are " + count + " DCM action items.
\n"); + msg.append("

Click here to view them
\n\n"); + msg.append("


\n\n"); + } + else + { + msg.append("WARNING: There are no DCM action items!
\n"); + } + } + + /** + * Kollil, 5/12/2017 : Send BSU Notes notification on the action date + */ + protected void bsuNotesAlert(final Container c, User u, final StringBuilder msg) + { + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("actiondate"), new Date(), CompareType.DATE_EQUAL); + filter.addCondition(FieldKey.fromString("category"), "BSU Notes", CompareType.EQUAL); + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("notes"), filter, null); + long count = ts.getRowCount(); + if (count > 0) + { + msg.append("WARNING: There are " + count + " BSU action items.
\n"); + msg.append("

Click here to view them
\n\n"); + msg.append("


\n\n"); + } + else + { + msg.append("WARNING: There are no BSU action items!
\n"); + } + } + + /** + * Kollil, 10/24/2019 : PMIC scheduler alert notifications Daily & Weekly + */ + protected void pmicSchedulerAlert(final Container c, User u, final StringBuilder msg) + { + //PMIC container: 783D2EA5-C6AC-1036-A33C-BD25D0574070 + if (QueryService.get().getUserSchema(u, c, "extscheduler") == null) { + msg.append("Warning: The extscheduler schema has not been enabled in this folder, so the alert cannot run!


"); + return; + } + //Daily events query + TableInfo ti = QueryService.get().getUserSchema(u, c, "extscheduler").getTable("PMIC_Scheduler"); + ((ContainerFilterable) ti).setContainerFilter(ContainerFilter.Type.AllFolders.create(c, u)); + TableSelector ts = new TableSelector(ti, null, null); + long count = ts.getRowCount(); + + //Weekly events query + TableInfo ti1 = QueryService.get().getUserSchema(u, c, "extscheduler").getTable("PMIC_Scheduler_Weekly"); + ((ContainerFilterable) ti1).setContainerFilter(ContainerFilter.Type.AllFolders.create(c, u)); + TableSelector ts1 = new TableSelector(ti1, null, null); + long count1 = ts1.getRowCount(); + + if (count > 0) {//Daily events count + msg.append("There are " + count + " PMIC events scheduled for today:"); + msg.append("

Click here to view them

\n"); + msg.append("
"); + } + if (count1 > 0) {//Weekly events count + msg.append("There are " + count1 + " PMIC events scheduled this week:"); + msg.append("

Click here to view them

\n"); + msg.append("
"); + } + //Display the daily report in the email + if (count > 0) { + Set columns = new HashSet<>(); + columns.add(FieldKey.fromString("resourceid")); + columns.add(FieldKey.fromString("startdate")); + columns.add(FieldKey.fromString("enddate")); + columns.add(FieldKey.fromString("name")); + columns.add(FieldKey.fromString("alias")); + columns.add(FieldKey.fromString("quantity")); + columns.add(FieldKey.fromString("comments")); + columns.add(FieldKey.fromString("color")); + columns.add(FieldKey.fromString("room")); + columns.add(FieldKey.fromString("bldg")); + + final Map colMap = QueryService.get().getColumns(ti, columns); + TableSelector ts2 = new TableSelector(ti, colMap.values(), null, null); + count = ts2.getRowCount(); + + if (count == 0) { + msg.append("There are no scheduled PMIC events"); + } + else { + msg.append("
Daily PMIC events:

\n"); + msg.append("
IdStatusGenderSpeciesGeographic Origin
IdStatusBirth DateRemarksGenderSpeciesGeographic Origin
" + rs.getString("Id") + "" + (rs.getString(FieldKey.fromString("Id/demographics/calculated_status")) == null ? "Unknown" : rs.getString(FieldKey.fromString("Id/demographics/calculated_status"))) + "" + (rs.getString("date") == null ? "Unknown" : rs.getDate("date")) + "" + (rs.getString("remark") == null ? " " : rs.getString("remark")) + "" + (rs.getString(FieldKey.fromString("Id/demographics/gender/meaning")) == null ? "MISSING" : rs.getString(FieldKey.fromString("Id/demographics/gender/meaning"))) + "" + (rs.getString(FieldKey.fromString("Id/demographics/species")) == null ? "MISSING" : rs.getString(FieldKey.fromString("Id/demographics/species"))) + "" + (rs.getString(FieldKey.fromString("Id/demographics/geographic_origin")) == null ? "MISSING" : rs.getString(FieldKey.fromString("Id/demographics/geographic_origin"))) + "
"); + msg.append(""); + msg.append(""); + + ts2.forEach(new Selector.ForEachBlock() { + @Override + public void exec(ResultSet object) throws SQLException { + Results rs = new ResultsImpl(object, colMap); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + } + }); + msg.append("
Resource Id Start Date End Date Name Alias Quantity Comments Color Room Bldg
" + rs.getString("resourceid") + "" + rs.getString("startdate") + "" + rs.getString("enddate") + "" + rs.getString("name") + "" + rs.getString("alias") + "" + rs.getString("quantity") + "" + rs.getString("comments") + "" + rs.getString("color") + "" + rs.getString("room") + "" + rs.getString("bldg") + "
"); + } + //Display the weekly report in the email + if (count1 > 0) { + Set columns1 = new HashSet<>(); + columns1.add(FieldKey.fromString("resourceid")); + columns1.add(FieldKey.fromString("startdate")); + columns1.add(FieldKey.fromString("enddate")); + columns1.add(FieldKey.fromString("name")); + columns1.add(FieldKey.fromString("alias")); + columns1.add(FieldKey.fromString("quantity")); + columns1.add(FieldKey.fromString("comments")); + columns1.add(FieldKey.fromString("color")); + columns1.add(FieldKey.fromString("room")); + columns1.add(FieldKey.fromString("bldg")); + + final Map colMap1 = QueryService.get().getColumns(ti1, columns1); + TableSelector ts3 = new TableSelector(ti1, colMap1.values(), null, null); + count1 = ts3.getRowCount(); + + if (count1 == 0) { + msg.append("There are no scheduled PMIC events"); + } + else { + msg.append("

Weekly PMIC events:

\n"); + msg.append(""); + msg.append(""); + msg.append(""); + + ts3.forEach(new Selector.ForEachBlock() { + @Override + public void exec(ResultSet object) throws SQLException { + Results rs1 = new ResultsImpl(object, colMap1); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + } + }); + msg.append("
Resource Id Start Date End Date Name Alias Quantity Comments Color Room Bldg
" + rs1.getString("resourceid") + "" + rs1.getString("startdate") + "" + rs1.getString("enddate") + "" + rs1.getString("name") + "" + rs1.getString("alias") + "" + rs1.getString("quantity") + "" + rs1.getString("comments") + "" + rs1.getString("color") + "" + rs1.getString("room") + "" + rs1.getString("bldg") + "
"); + } + } + } + } + /** * we find protocols over the animal limit */ @@ -1006,6 +1226,24 @@ protected void assignmentsNotAllowed(final Container c, User u, final StringBuil } } + //Added: 8-7-2018 R.Blasa + protected void ValidateBiirthHousingHistory(final Container c, User u, final StringBuilder msg) + { + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("BirthInitialHousingMismatch"), null, null); + long count = ts.getRowCount(); + if (count > 0) + { + msg.append("WARNING: There are " + count + " several Birth ids having mismatched initial locations
\n"); + msg.append("

Click here to view them
\n\n"); + msg.append("


\n\n"); + } + else + { + msg.append("WARNING: There are no Birth Initial Housing mismtached locations to report.
\n"); + } + } + + protected void overlappingProtocolCounts(final Container c, User u, final StringBuilder msg) { TableSelector ts = new TableSelector(getEHRSchema(c, u).getTable("protocolGroupsOverlapping")); @@ -1021,6 +1259,19 @@ protected void overlappingProtocolCounts(final Container c, User u, final String } } + protected void getGeographicOriginConflicts(final Container c, User u, final StringBuilder msg) + { + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("geographicOriginConflicts")); + long count = ts.getRowCount(); + + if (count > 0) + { + msg.append("WARNING: There are " + count + " animals where the demographics table value for geographic origin conflicts with genetic ancestry.
\n"); + msg.append("

Click here to view them
\n\n"); + msg.append("


\n\n"); + } + } + /** * we find all animals that died in the past 90 days where there isnt a weight within 7 days of death: */ @@ -1747,8 +1998,26 @@ else if (count > 65) protected void infantsNotWithMother(final Container c, User u, final StringBuilder msg) { SimpleFilter filter = new SimpleFilter(FieldKey.fromString("Id/age/ageInDays"), 180, CompareType.LTE); + //Added by Kollil, 6/11. Excluding the Guinea pigs & Rabbits and showing only primates + //filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG;RABBIT", CompareType.CONTAINS_NONE_OF); + filter.addCondition(FieldKey.fromString("Id/demographics/species/common"), "GUINEA PIG", CompareType.NEQ); filter.addCondition(FieldKey.fromString("Id/demographics/calculated_status"), "Alive", CompareType.EQUAL); - filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "ASB RM 191", CompareType.NEQ_OR_NULL); + // Changed by Kolli on 3/6/2020 + /*Rm 191 used to be a nursery, but below are the current rooms where infants are likely to be housed without dams. Can you exclude these rooms, rather than ASB RM 191? + ASB RM 213 + ASB RM 236 + ASB RM 240 + ASB RM 185 + COL RM 4 + */ + //Added ASB 239 to this list on 5/14/2020 byt kolli + //filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "ASB RM 191", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "ASB RM 213", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "ASB RM 236", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "ASB RM 240", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "ASB RM 185", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "ASB RM 239", CompareType.NEQ_OR_NULL); + filter.addCondition(FieldKey.fromString("Id/curLocation/room"), "COL RM 4", CompareType.NEQ_OR_NULL); filter.addCondition(FieldKey.fromString("withMother"), 0, CompareType.EQUAL); TableInfo ti = getStudySchema(c, u).getTable("infantsSeparateFromMother"); @@ -1763,7 +2032,7 @@ protected void infantsNotWithMother(final Container c, User u, final StringBuild long count = ts.getRowCount(); if (count > 0) { - msg.append("NOTE: There are " + count + " animals under 180 days old not housed with their dam or foster dam, excluding animals in ASB RM 191

"); + msg.append("NOTE: There are " + count + " animals under 180 days old not housed with their dam or foster dam, excluding animals in ASB RM 213, ASB RM 236, ASB RM 240, ASB RM 185, ASB RM 239 & COL RM 4

"); ts.forEach(new Selector.ForEachBlock() { @Override diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/DCMNotesNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/DCMNotesNotification.java new file mode 100644 index 000000000..aeaea239e --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/DCMNotesNotification.java @@ -0,0 +1,58 @@ +package org.labkey.onprc_ehr.notification; + +import org.labkey.api.data.Container; +import org.labkey.api.module.Module; +import org.labkey.api.security.User; + +import java.util.Date; + +/** + * Created by kollil on 5/12/2017. + */ +public class DCMNotesNotification extends ColonyAlertsNotification +{ + public DCMNotesNotification(Module owner) + { + super(owner); + } + + @Override + public String getName() + { + return "DCM Notes Notification"; + } + + @Override + public String getEmailSubject(Container c) + { + return "DCM Notes Alerts: " + getDateTimeFormat(c).format(new Date()); + } + + @Override + public String getCronString() + { + return "0 0 5 * * ?"; + } + + @Override + public String getScheduleDescription() + { + return "every day at 5:00AM"; + } + + @Override + public String getDescription() + { + return "The report is designed to send DCM Notes alerts on the day indicated by the action date!"; + } + + @Override + public String getMessageBodyHTML(Container c, User u) + { + StringBuilder msg = new StringBuilder(); + + dcmNotesAlert(c, u, msg); + + return msg.toString(); + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/InfantsBornAssignedNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/InfantsBornAssignedNotification.java new file mode 100644 index 000000000..ebb4710f0 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/InfantsBornAssignedNotification.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.notification; + +import org.apache.commons.lang3.time.DateUtils; +import org.json.JSONObject; +import org.labkey.api.data.CompareType; +import org.labkey.api.data.Container; +import org.labkey.api.data.SQLFragment; +import org.labkey.api.data.Selector; +import org.labkey.api.data.SimpleFilter; +import org.labkey.api.data.Sort; +import org.labkey.api.data.SqlSelector; +import org.labkey.api.data.TableInfo; +import org.labkey.api.data.TableSelector; +import org.labkey.api.ehr.notification.AbstractEHRNotification; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; +import org.labkey.api.query.QueryDefinition; +import org.labkey.api.query.QueryException; +import org.labkey.api.query.QueryService; +import org.labkey.api.query.UserSchema; +import org.labkey.api.security.User; +import org.labkey.api.util.DateUtil; +import org.labkey.api.util.PageFlowUtil; +import org.labkey.api.data.ColumnInfo; +import org.labkey.api.data.Results; +import org.labkey.api.data.ResultsImpl; +import org.apache.commons.lang3.StringUtils; + + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.text.ParseException; + +//Created: 3-8-2017 R.Blasa +public class InfantsBornAssignedNotification extends AbstractEHRNotification +{ + public InfantsBornAssignedNotification(Module owner) + { + super(owner); + } + + @Override + public String getName() + { + return "Infants Born to Assigned Animals Notification"; + } + + @Override + public String getEmailSubject(Container c) + { + return "Infants Born To Assigned Animals Alerts: " + getDateTimeFormat(c).format(new Date()); + } + + @Override + public String getCronString() + { + return "0 0 7 * * ?"; + } + + @Override + public String getScheduleDescription() + { + return "every day at 7:00AM"; + } + + @Override + public String getDescription() + { + return "The report is designed to warn users of infants that are born to Assigned Animals"; + } + + @Override + public String getMessageBodyHTML(Container c, User u) + { + Map saved = getSavedValues(c); + Map toSave = new HashMap(); + + StringBuilder msg = new StringBuilder(); + + AssignedInfantprocess(c, u, msg); + + return msg.toString(); + } + + private void AssignedInfantprocess(Container c, User u, final StringBuilder msg) + { + + Calendar date = Calendar.getInstance(); + date.setTime(new Date()); + date.add(Calendar.DATE, -45); + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("date"), date.getTime(), CompareType.DATE_GTE); //birth date + + + Sort sort = new Sort("-date"); + + TableInfo ti = getStudySchema(c, u).getTable("InfantsBorntoAssigned"); + List colKeys = new ArrayList<>(); + colKeys.add(FieldKey.fromString(getStudy(c).getSubjectColumnName())); + colKeys.add(FieldKey.fromString("Id")); + colKeys.add(FieldKey.fromString("date")); + colKeys.add(FieldKey.fromString("dam")); + colKeys.add(FieldKey.fromString("ProjectName")); + + final Map columns = QueryService.get().getColumns(ti, colKeys); + + TableSelector ts = new TableSelector(ti, columns.values(), filter, sort); + long total = ts.getRowCount(); + if (total == 0) + { + msg.append("There are no records of infants that were born to Assigned Animals.\n"); + } + else + { + //Create header information on this report + msg.append(""); + msg.append("\n"); + + + ts.forEach(new Selector.ForEachBlock() + { + @Override + public void exec(ResultSet rs) throws SQLException + { + Results results = new ResultsImpl(rs, columns); + String Ids = results.getString(FieldKey.fromString("Id")); + Date datess = results.getDate(FieldKey.fromString("date")); + String dams = results.getString(FieldKey.fromString("dam")); + String projectname = results.getString(FieldKey.fromString("ProjectName")); + + msg.append("\n"); + + } + }); + + msg.append("
Monkey IDDateProject NameDam
" + PageFlowUtil.filter(Ids) + "" + PageFlowUtil.filter(getDateTimeFormat(c).format(datess)) + "" + PageFlowUtil.filter(projectname) + "" + PageFlowUtil.filter(dams) + "
\n"); + + } + } + + + + + + + +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/ObeseFlagNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/ObeseFlagNotification.java index da1f6f5b7..746d4e37f 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/ObeseFlagNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/ObeseFlagNotification.java @@ -130,6 +130,15 @@ private void ObeseFlagprocess(Container c, User u, final StringBuilder msg) colKeys.add(FieldKey.fromString("enddate")); colKeys.add(FieldKey.fromString("flag/category")); colKeys.add(FieldKey.fromString("flag/value")); + +// Added: 10-25-2019 R.Blasa + colKeys.add(FieldKey.fromString("Id/assignedVet/assignedVet")); + colKeys.add(FieldKey.fromString("Id/MostRecentWeight/MostRecentWeight")); + colKeys.add(FieldKey.fromString("Id/curLocation/room")); + colKeys.add(FieldKey.fromString("Id/curLocation/cage")); + + + final Map columns = QueryService.get().getColumns(ti, colKeys); TableSelector ts = new TableSelector(ti, columns.values(), filter, sort); @@ -142,7 +151,7 @@ private void ObeseFlagprocess(Container c, User u, final StringBuilder msg) { //Create header information on this report msg.append(""); - msg.append("\n"); + msg.append("\n"); ts.forEach(new Selector.ForEachBlock() @@ -156,7 +165,20 @@ public void exec(ResultSet rs) throws SQLException Date datess = results.getDate(FieldKey.fromString("date")); String categorys = results.getString(FieldKey.fromString("flag/category")); String valuess = results.getString(FieldKey.fromString("flag/value")); - msg.append("\n"); + +// Added: 10-25-2019 R,Blasa + String vetname = results.getString(FieldKey.fromString("Id/assignedVet/assignedVet")); + String weights = results.getString(FieldKey.fromString("Id/MostRecentWeight/MostRecentWeight")); + String rooms = results.getString(FieldKey.fromString("Id/curLocation/room")); + String cages = results.getString(FieldKey.fromString("Id/curLocation/cage")); + + + + msg.append("" + + "" + + "\n"); + } }); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/PregnantNHPsGestationAlert.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/PregnantNHPsGestationAlert.java new file mode 100644 index 000000000..19d4e14b6 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/PregnantNHPsGestationAlert.java @@ -0,0 +1,62 @@ +package org.labkey.onprc_ehr.notification; + +import org.labkey.api.data.Container; +import org.labkey.api.module.Module; +import org.labkey.api.security.User; + +import java.util.Date; + +/** + * Created by kollil + */ +public class PregnantNHPsGestationAlert extends ColonyAlertsNotification +{ + public PregnantNHPsGestationAlert(Module owner) + { + super(owner); + } + + @Override + public String getName() + { + return "Pregnant NHPs Gestation Notification"; + } + + @Override + public String getEmailSubject(Container c) + { + return "Pregnant Animal Alerts: " + getDateTimeFormat(c).format(new Date()); + } + + @Override + public String getCronString() + { + return "0 0 5 * * ?"; + } + + @Override + public String getScheduleDescription() + { + return "every day at 5:00AM"; + } + + @Override + public String getDescription() + { + return "The report is designed to provide a daily summary of pregnant NHPs past 30 days of gestation for the colony!"; + } + + @Override + public String getMessageBodyHTML(Container c, User u) + { + StringBuilder msg = new StringBuilder(); + + checkPregnantGestation(c, u, msg); + + return msg.toString(); + } +} + + + + diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/ProjectAlertsNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/ProjectAlertsNotification.java new file mode 100644 index 000000000..cf8b22a54 --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/ProjectAlertsNotification.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015-2017 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.notification; + +import org.jetbrains.annotations.Nullable; +import org.labkey.api.data.Container; +import org.labkey.api.ehr.notification.AbstractEHRNotification; +import org.labkey.api.module.Module; +import org.labkey.api.security.User; +import org.labkey.api.util.DateUtil; + +import java.util.Date; + +//Added 3-6-2019 R.Blasa + +public class ProjectAlertsNotification extends AbstractEHRNotification +{ + public ProjectAlertsNotification(Module owner) + { + super(owner); + } + + @Override + public String getName() + { + return "Center Project Notification"; + } + + @Override + public String getEmailSubject(Container c) + { + return "Project Alerts Notification: " + DateUtil.formatDateTime(c); + } + + @Override + public String getCronString() + { + return null; + } + + @Override + public String getScheduleDescription() + { + return "Sent immediately when a Center Project record is created"; + } + + @Override + public String getDescription() + { + return "The report sends an alert whenever a new Center Project record is created."; + } + + @Override + @Nullable + public String getMessageBodyHTML(Container c, User u) + { + //this is used as a placeholder so we can use it to track the list of subscribed users + return null ; + } +} diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/RoutineClinicalTestsNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/RoutineClinicalTestsNotification.java index cf9741337..db046437b 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/RoutineClinicalTestsNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/RoutineClinicalTestsNotification.java @@ -260,7 +260,7 @@ protected void getAnimalsNotWeightedInPast60Days(StringBuilder msg, Container c, msg.append("Weights:

\n"); SimpleFilter filter = new SimpleFilter(FieldKey.fromString("calculated_status"), "Alive"); - filter.addCondition(FieldKey.fromString("Id/MostRecentWeight/DaysSinceWeight"), 60, CompareType.GT); + filter.addCondition(FieldKey.fromString("Id/MostRecentWeight/DaysSinceWeight"), 45, CompareType.GT); filter.addCondition(FieldKey.fromString("Id/curLocation/Room/housingType/value"), "Cage Location", CompareType.EQUAL); TableInfo ti = getStudySchema(c, u).getTable("demographics"); @@ -272,8 +272,8 @@ protected void getAnimalsNotWeightedInPast60Days(StringBuilder msg, Container c, if (count > 0) { - msg.append("WARNING: There are " + count + " animals in cage locations and have not been weighed in the past 60 days: "); - String url = getExecuteQueryUrl(c, "study", "Demographics", "By Location") + "&query.Id/MostRecentWeight/DaysSinceWeight~gt=60&query.calculated_status~eq=Alive&query.Id/curLocation/Room/housingType/value~eq=Cage Location"; + msg.append("WARNING: There are " + count + " animals in cage locations and have not been weighed in the past 45 days: "); + String url = getExecuteQueryUrl(c, "study", "Demographics", "By Location") + "&query.Id/MostRecentWeight/DaysSinceWeight~gt=45&query.calculated_status~eq=Alive&query.Id/curLocation/Room/housingType/value~eq=Cage Location"; msg.append("Click here to view them.

\n"); msg.append("Summary by area:
\n"); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotification.java index 5d8bde536..dd6fc98c8 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotification.java @@ -60,7 +60,7 @@ public String getName() @Override public String getDescription() { - return "This runs every day at 9AM, 1PM, 5PM if there are treatments scheduled that have not yet been marked complete"; + return "This runs every day at 9AM,1PM,3PM if there are treatments scheduled that have not yet been marked complete"; } @Override @@ -70,12 +70,12 @@ public String getEmailSubject(Container c) } @Override - public String getCronString() {return "0 0 9,13,17 * * ?";} + public String getCronString() {return "0 0 9,13,15 * * ?";} @Override public String getScheduleDescription() { - return "daily at 9AM,1PM, 5PM"; + return "daily at 9AM,1PM,3PM"; } @Override @@ -87,7 +87,6 @@ public String getMessageBodyHTML(Container c, User u) Date now = new Date(); msg.append("This email contains any treatments not marked as completed. It was run on: " + getDateFormat(c).format(now) + " at " + _timeFormat.format(now) + ".

"); - processPostOpsTreatments(c, u, msg, new Date()); return msg.toString(); @@ -176,13 +175,111 @@ public void exec(ResultSet object) throws SQLException msg.append("Treatments:

"); msg.append("There are " + (totals.get(completed) + totals.get(incomplete)) + " scheduled treatments on or before " + _timeFormat.format(maxDate) + ". Click here to view them. Of these, " + totals.get(completed) + " have been marked completed.

\n"); + //////////////////////////////////////////////////////////////////////////////////////////////////////////// + //Add code to display report, by Kollil + + TableInfo ti1 = QueryService.get().getUserSchema(u, c, "study").getTable("treatmentSchedulePostOps"); + + //All fields + Set columns1 = new HashSet<>(); + columns1.add(FieldKey.fromString("id")); + columns1.add(FieldKey.fromString("calculated_status")); + columns1.add(FieldKey.fromString("treatmentStatus")); + columns1.add(FieldKey.fromString("room")); + columns1.add(FieldKey.fromString("cage")); + columns1.add(FieldKey.fromString("date")); + columns1.add(FieldKey.fromString("startDate")); + columns1.add(FieldKey.fromString("endDate")); + columns1.add(FieldKey.fromString("dayselapsed")); + columns1.add(FieldKey.fromString("category")); + columns1.add(FieldKey.fromString("medication")); + columns1.add(FieldKey.fromString("volume")); + columns1.add(FieldKey.fromString("vol_units")); + columns1.add(FieldKey.fromString("concentration")); + columns1.add(FieldKey.fromString("conc_units")); + columns1.add(FieldKey.fromString("amountWithUnits")); + columns1.add(FieldKey.fromString("amountAndVolume")); + columns1.add(FieldKey.fromString("dosage")); + columns1.add(FieldKey.fromString("dosage_units")); + columns1.add(FieldKey.fromString("frequency")); + columns1.add(FieldKey.fromString("route")); + columns1.add(FieldKey.fromString("reason")); + columns1.add(FieldKey.fromString("remark")); + columns1.add(FieldKey.fromString("performedby")); + + final Map colMap1 = QueryService.get().getColumns(ti1, columns1); + TableSelector ts1 = new TableSelector(ti1, colMap1.values(), filter, new Sort("id")); + ts1.setNamedParameters(params); + //url = getExecuteQueryUrl(c, "study", "treatmentSchedulePostOps", null) ; + total = ts1.getRowCount(); + + if (total == 0) + { + msg.append("There are no post op meds"); + } + else + { + msg.append("


Post Op Meds:

\n"); + msg.append("
Monkey IDStart DateRemoval DateCategoryMeaning
Monkey IDRoomCageCurrent Weight (kg)Start DateRemoval DateAssigned Vet
" + Ids + "" + DateUtil.formatDateTime(c, datess) + "" + DateUtil.formatDateTime(c, enddates) + "" + categorys + "" + valuess + "
" + PageFlowUtil.filter(Ids) + "" + PageFlowUtil.filter(rooms) + "" + PageFlowUtil.filter(cages) + "" + PageFlowUtil.filter(" ") + PageFlowUtil.filter(weights) + "" + + PageFlowUtil.filter(DateUtil.formatDateTime(c, datess)) + "" + PageFlowUtil.filter(DateUtil.formatDateTime(c, enddates)) + "" + " " + PageFlowUtil.filter(vetname) + "
"); + msg.append(""); + + ts1.forEach(new Selector.ForEachBlock() + { + @Override + public void exec(ResultSet object) throws SQLException + + { + Results rs = new ResultsImpl(object, colMap1); + String status = rs.getString("TreatmentStatus"); + if ("completed".equalsIgnoreCase(status)) + { + msg.append(""); + } + else { + //If not "completed", highlight the record with yellow color + msg.append(""); + } + + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + } + }); + + msg.append("
IdStatusTreatment StatusRoomCageTreatment DateTreatment Start DateTreatment End DateDays ElapsedCategoryTreatmentVolumeVolume UnitsDrug ConcConc UnitsAmountAmount And VolumeDosageDosage UnitsFrequencyRouteReasonRemarkOrdered By
" + PageFlowUtil.filter(rs.getString("id")) + "" + PageFlowUtil.filter(rs.getString("calculated_status")) + "" + PageFlowUtil.filter(rs.getString("TreatmentStatus")) + "" + PageFlowUtil.filter(rs.getString("room")) + "" + PageFlowUtil.filter(rs.getString("cage")) + "" + PageFlowUtil.filter(rs.getString("date")) + "" + PageFlowUtil.filter(rs.getString("startDate")) + "" + PageFlowUtil.filter(rs.getString("endDate")) + "" + PageFlowUtil.filter(rs.getString("dayselapsed")) + "" + PageFlowUtil.filter(rs.getString("category")) + "" + PageFlowUtil.filter(rs.getString("medication")) + "" + PageFlowUtil.filter(rs.getString("volume")) + "" + PageFlowUtil.filter(rs.getString("vol_units")) + "" + PageFlowUtil.filter(rs.getString("concentration")) + "" + PageFlowUtil.filter(rs.getString("conc_units")) + "" + PageFlowUtil.filter(rs.getString("amountWithUnits")) + "" + PageFlowUtil.filter(rs.getString("amountAndVolume")) + "" + PageFlowUtil.filter(rs.getString("dosage")) + "" + PageFlowUtil.filter(rs.getString("dosage_units")) + "" + PageFlowUtil.filter(rs.getString("frequency")) + "" + PageFlowUtil.filter(rs.getString("route")) + "" + PageFlowUtil.filter(rs.getString("reason")) + "" + PageFlowUtil.filter(rs.getString("remark"))+ "" + PageFlowUtil.filter(rs.getString("performedby")) + "
"); + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////// + if (totals.get(incomplete) == 0) { - msg.append("All treatments scheduled prior to " + _timeFormat.format(maxDate) + " have been marked complete as of " + getDateTimeFormat(c).format(curDate) + ".

\n"); + msg.append("
All treatments scheduled prior to " + _timeFormat.format(maxDate) + " have been marked complete as of " + getDateTimeFormat(c).format(curDate) + ".

\n"); } else { - msg.append("There are " + totals.get(incomplete) + " treatments that have not been marked complete:

\n"); + msg.append("
There are " + totals.get(incomplete) + " treatments that have not been marked complete:

\n"); msg.append(""); for (String area : totalByArea.keySet()) @@ -194,5 +291,6 @@ public void exec(ResultSet object) throws SQLException } msg.append("
\n"); } + } } \ No newline at end of file diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotificationSecondary.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotificationSecondary.java index 4f4550474..b6ff7b39f 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotificationSecondary.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotificationSecondary.java @@ -31,6 +31,7 @@ import org.labkey.api.query.QueryService; import org.labkey.api.security.User; import org.labkey.api.ehr.notification.AbstractEHRNotification; +import org.labkey.api.util.PageFlowUtil; import java.sql.ResultSet; import java.sql.SQLException; @@ -171,6 +172,104 @@ public void exec(ResultSet object) throws SQLException msg.append("Treatments:

"); msg.append("There are " + (totals.get(completed) + totals.get(incomplete)) + " scheduled treatments on or before " + _timeFormat.format(maxDate) + ". Click here to view them. Of these, " + totals.get(completed) + " have been marked completed.

\n"); + //////////////////////////////////////////////////////////////////////////////////////////////////////////// + //Add code to display report, by Kollil + + TableInfo ti1 = QueryService.get().getUserSchema(u, c, "study").getTable("treatmentSchedulePostOps"); + + //All fields + Set columns1 = new HashSet<>(); + columns1.add(FieldKey.fromString("id")); + columns1.add(FieldKey.fromString("calculated_status")); + columns1.add(FieldKey.fromString("treatmentStatus")); + columns1.add(FieldKey.fromString("room")); + columns1.add(FieldKey.fromString("cage")); + columns1.add(FieldKey.fromString("date")); + columns1.add(FieldKey.fromString("startDate")); + columns1.add(FieldKey.fromString("endDate")); + columns1.add(FieldKey.fromString("dayselapsed")); + columns1.add(FieldKey.fromString("category")); + columns1.add(FieldKey.fromString("medication")); + columns1.add(FieldKey.fromString("volume")); + columns1.add(FieldKey.fromString("vol_units")); + columns1.add(FieldKey.fromString("concentration")); + columns1.add(FieldKey.fromString("conc_units")); + columns1.add(FieldKey.fromString("amountWithUnits")); + columns1.add(FieldKey.fromString("amountAndVolume")); + columns1.add(FieldKey.fromString("dosage")); + columns1.add(FieldKey.fromString("dosage_units")); + columns1.add(FieldKey.fromString("frequency")); + columns1.add(FieldKey.fromString("route")); + columns1.add(FieldKey.fromString("reason")); + columns1.add(FieldKey.fromString("remark")); + columns1.add(FieldKey.fromString("performedby")); + + final Map colMap1 = QueryService.get().getColumns(ti1, columns1); + TableSelector ts1 = new TableSelector(ti1, colMap1.values(), filter, new Sort("id")); + ts1.setNamedParameters(params); + //url = getExecuteQueryUrl(c, "study", "treatmentSchedulePostOps", null) ; + total = ts1.getRowCount(); + + if (total == 0) + { + msg.append("There are no post op meds"); + } + else + { + msg.append("


Post Op Meds:

\n"); + msg.append("
"); + msg.append(""); + + ts1.forEach(new Selector.ForEachBlock() + { + @Override + public void exec(ResultSet object) throws SQLException + + { + Results rs = new ResultsImpl(object, colMap1); + String status = rs.getString("TreatmentStatus"); + if ("completed".equalsIgnoreCase(status)) + { + msg.append(""); + } + else { + //If not "completed", highlight the record with yellow color + msg.append(""); + } + + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + } + }); + + msg.append("
IdStatusTreatment StatusRoomCageTreatment DateTreatment Start DateTreatment End DateDays ElapsedCategoryTreatmentVolumeVolume UnitsDrug ConcConc UnitsAmountAmount And VolumeDosageDosage UnitsFrequencyRouteReasonRemarkOrdered By
" + PageFlowUtil.filter(rs.getString("id")) + "" + PageFlowUtil.filter(rs.getString("calculated_status")) + "" + PageFlowUtil.filter(rs.getString("TreatmentStatus")) + "" + PageFlowUtil.filter(rs.getString("room")) + "" + PageFlowUtil.filter(rs.getString("cage")) + "" + PageFlowUtil.filter(rs.getString("date")) + "" + PageFlowUtil.filter(rs.getString("startDate")) + "" + PageFlowUtil.filter(rs.getString("endDate")) + "" + PageFlowUtil.filter(rs.getString("dayselapsed")) + "" + PageFlowUtil.filter(rs.getString("category")) + "" + PageFlowUtil.filter(rs.getString("medication")) + "" + PageFlowUtil.filter(rs.getString("volume")) + "" + PageFlowUtil.filter(rs.getString("vol_units")) + "" + PageFlowUtil.filter(rs.getString("concentration")) + "" + PageFlowUtil.filter(rs.getString("conc_units")) + "" + PageFlowUtil.filter(rs.getString("amountWithUnits")) + "" + PageFlowUtil.filter(rs.getString("amountAndVolume")) + "" + PageFlowUtil.filter(rs.getString("dosage")) + "" + PageFlowUtil.filter(rs.getString("dosage_units")) + "" + PageFlowUtil.filter(rs.getString("frequency")) + "" + PageFlowUtil.filter(rs.getString("route")) + "" + PageFlowUtil.filter(rs.getString("reason")) + "" + PageFlowUtil.filter(rs.getString("remark")) + "" + PageFlowUtil.filter(rs.getString("performedby")) + "
"); + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////// + if (totals.get(incomplete) == 0) { msg.append("All treatments scheduled prior to " + _timeFormat.format(maxDate) + " have been marked complete as of " + getDateTimeFormat(c).format(curDate) + ".

\n"); diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotificationThird.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotificationThird.java new file mode 100644 index 000000000..3df709f6e --- /dev/null +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/TreatmentAlertsPostOpsNotificationThird.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2015-2016 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.onprc_ehr.notification; + +import org.apache.commons.lang3.time.DateUtils; +import org.labkey.api.data.ColumnInfo; +import org.labkey.api.data.CompareType; +import org.labkey.api.data.Container; +import org.labkey.api.data.Results; +import org.labkey.api.data.ResultsImpl; +import org.labkey.api.data.Selector; +import org.labkey.api.data.SimpleFilter; +import org.labkey.api.data.Sort; +import org.labkey.api.data.TableInfo; +import org.labkey.api.data.TableSelector; +import org.labkey.api.ehr.notification.AbstractEHRNotification; +import org.labkey.api.module.Module; +import org.labkey.api.query.FieldKey; +import org.labkey.api.query.QueryService; +import org.labkey.api.security.User; +import org.labkey.api.util.PageFlowUtil; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +//Added 6-4-2019 Blasa Post Op Meds 5Pm Schedule Only +public class TreatmentAlertsPostOpsNotificationThird extends AbstractEHRNotification +{ + public TreatmentAlertsPostOpsNotificationThird(Module owner) + { + super(owner); + } + + public String getName() + { + return "Treatment PostOpsMed Third Alert"; + } + + public String getDescription() + { + return "This runs every evening at 5:00PM if there are treatments scheduled that have not yet been marked complete"; + } + + public String getEmailSubject(Container c) + { + return "Daily Treatment PostOpsMed Alerts: " + getDateTimeFormat(c).format(new Date()); + } + + @Override //Modified 7/29/2015 Blasa + public String getCronString() { return "0 0 17 * * ?";} + + public String getScheduleDescription() + { + return "Evenings at 5:00 PM"; + } + + @Override + public String getMessageBodyHTML(Container c, User u) + { + StringBuilder msg = new StringBuilder(); + + //Find today's date + Date now = new Date(); + msg.append("This email contains any treatments not marked as completed. It was run on: " + getDateFormat(c).format(now) + " at " + _timeFormat.format(now) + ".

"); + + + processPostOpsTreatments(c, u, msg, new Date()); + + return msg.toString(); + } + + + + // Added 7-21-2015 Blasa Address Notifications for only Post Ops Meds + private void processPostOpsTreatments(Container c, User u, final StringBuilder msg, final Date maxDate) + { + Date curDate = new Date(); + Date roundedMax = new Date(); + roundedMax.setTime(maxDate.getTime()); + roundedMax = DateUtils.truncate(roundedMax, Calendar.DATE); + + TableInfo ti = QueryService.get().getUserSchema(u, c, "study").getTable("treatmentSchedulePostOps"); + + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("date"), roundedMax, CompareType.DATE_EQUAL); + filter.addCondition(FieldKey.fromString("date"), maxDate, CompareType.LTE); + filter.addCondition(FieldKey.fromString("Id/DataSet/Demographics/calculated_status"), "Alive"); + + + Set columns = new HashSet<>(); + columns.add(FieldKey.fromString("Id")); + columns.add(FieldKey.fromString("Id/curLocation/area")); + columns.add(FieldKey.fromString("Id/curLocation/room")); + columns.add(FieldKey.fromString("Id/curLoation/cage")); + columns.add(FieldKey.fromString("projectStatus")); + columns.add(FieldKey.fromString("treatmentStatus")); + columns.add(FieldKey.fromString("treatmentStatus/Label")); + columns.add(FieldKey.fromString("code")); + columns.add(FieldKey.fromString("code/meaning")); + + Map params = new HashMap<>(); + params.put("StartDate", roundedMax); + params.put("NumDays", 1); + + final Map colMap = QueryService.get().getColumns(ti, columns); + TableSelector ts = new TableSelector(ti, colMap.values(), filter, new Sort("Id/curLocation/area,Id/curLocation/room")); + ts.setNamedParameters(params); + + String url = getExecuteQueryUrl(c, "study", "treatmentSchedulePostOps", null) + "&" + filter.toQueryString("query") + getParameterUrlString(c, params); + long total = ts.getRowCount(); + if (total == 0) + { + msg.append("There are no treatments scheduled on " + getDateFormat(c).format(maxDate) + " on or before " + _timeFormat.format(maxDate) + ". Treatments could be added after this email was sent, so please click here to check online closer to the time.


\n"); + } + else + { + final String completed = "completed"; + final String incomplete = "incomplete"; + final Map totals = new HashMap<>(); + totals.put(completed, 0); + totals.put(incomplete, 0); + + final Map totalByArea = new TreeMap<>(); + + ts.forEach(new Selector.ForEachBlock() + { + @Override + public void exec(ResultSet object) throws SQLException + { + Results rs = new ResultsImpl(object, colMap); + //Modified 7-2-2015 Blasa Comparing QC state to column values + if ("Completed".equals(rs.getString(FieldKey.fromString("treatmentStatus")))) + { + totals.put(completed, totals.get(completed) + 1); + } + else + { + totals.put(incomplete, totals.get(incomplete) + 1); + + String area = rs.getString(FieldKey.fromString("Id/curLocation/area")); + Integer areaVal = totalByArea.containsKey(area) ? totalByArea.get(area) : 0; + areaVal++; + + totalByArea.put(area, areaVal); + } + } + }); + + msg.append("Treatments:

"); + msg.append("There are " + (totals.get(completed) + totals.get(incomplete)) + " scheduled treatments on or before " + _timeFormat.format(maxDate) + ". Click here to view them. Of these, " + totals.get(completed) + " have been marked completed.

\n"); + + //////////////////////////////////////////////////////////////////////////////////////////////////////////// + //Add code to display report, by Kollil + + TableInfo ti1 = QueryService.get().getUserSchema(u, c, "study").getTable("treatmentSchedulePostOps"); + + //All fields + Set columns1 = new HashSet<>(); + columns1.add(FieldKey.fromString("id")); + columns1.add(FieldKey.fromString("calculated_status")); + columns1.add(FieldKey.fromString("treatmentStatus")); + columns1.add(FieldKey.fromString("room")); + columns1.add(FieldKey.fromString("cage")); + columns1.add(FieldKey.fromString("date")); + columns1.add(FieldKey.fromString("startDate")); + columns1.add(FieldKey.fromString("endDate")); + columns1.add(FieldKey.fromString("dayselapsed")); + columns1.add(FieldKey.fromString("category")); + columns1.add(FieldKey.fromString("medication")); + columns1.add(FieldKey.fromString("volume")); + columns1.add(FieldKey.fromString("vol_units")); + columns1.add(FieldKey.fromString("concentration")); + columns1.add(FieldKey.fromString("conc_units")); + columns1.add(FieldKey.fromString("amountWithUnits")); + columns1.add(FieldKey.fromString("amountAndVolume")); + columns1.add(FieldKey.fromString("dosage")); + columns1.add(FieldKey.fromString("dosage_units")); + columns1.add(FieldKey.fromString("frequency")); + columns1.add(FieldKey.fromString("route")); + columns1.add(FieldKey.fromString("reason")); + columns1.add(FieldKey.fromString("remark")); + columns1.add(FieldKey.fromString("performedby")); + + final Map colMap1 = QueryService.get().getColumns(ti1, columns1); + TableSelector ts1 = new TableSelector(ti1, colMap1.values(), filter, new Sort("id")); + ts1.setNamedParameters(params); + //url = getExecuteQueryUrl(c, "study", "treatmentSchedulePostOps", null) ; + total = ts1.getRowCount(); + + if (total == 0) + { + msg.append("There are no post op meds"); + } + else + { + msg.append("


Post Op Meds:

\n"); + msg.append(""); + msg.append(""); + + ts1.forEach(new Selector.ForEachBlock() + { + @Override + public void exec(ResultSet object) throws SQLException + + { + Results rs = new ResultsImpl(object, colMap1); + String status = rs.getString("TreatmentStatus"); + if ("completed".equalsIgnoreCase(status)) + { + msg.append(""); + } + else { + //If not "completed", highlight the record with yellow color + msg.append(""); + } + + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + } + }); + + msg.append("
IdStatusTreatment StatusRoomCageTreatment DateTreatment Start DateTreatment End DateDays ElapsedCategoryTreatmentVolumeVolume UnitsDrug ConcConc UnitsAmountAmount And VolumeDosageDosage UnitsFrequencyRouteReasonRemarkOrdered By
" + PageFlowUtil.filter(rs.getString("id")) + "" + PageFlowUtil.filter(rs.getString("calculated_status")) + "" + PageFlowUtil.filter(rs.getString("TreatmentStatus")) + "" + PageFlowUtil.filter(rs.getString("room")) + "" + PageFlowUtil.filter(rs.getString("cage"))+ "" + PageFlowUtil.filter(rs.getString("date")) + "" + PageFlowUtil.filter(rs.getString("startDate")) + "" + PageFlowUtil.filter(rs.getString("endDate")) + "" + PageFlowUtil.filter(rs.getString("dayselapsed")) + "" + PageFlowUtil.filter(rs.getString("category"))+ "" + PageFlowUtil.filter(rs.getString("medication")) + "" + PageFlowUtil.filter(rs.getString("volume")) + "" + PageFlowUtil.filter(rs.getString("vol_units")) + "" + PageFlowUtil.filter(rs.getString("concentration")) + "" + PageFlowUtil.filter(rs.getString("conc_units")) + "" + PageFlowUtil.filter(rs.getString("amountWithUnits")) + "" + PageFlowUtil.filter(rs.getString("amountAndVolume")) + "" + PageFlowUtil.filter(rs.getString("dosage")) + "" + PageFlowUtil.filter(rs.getString("dosage_units")) + "" + PageFlowUtil.filter(rs.getString("frequency")) + "" + PageFlowUtil.filter(rs.getString("route")) + "" + PageFlowUtil.filter(rs.getString("reason")) + "" + PageFlowUtil.filter(rs.getString("remark")) + "" + PageFlowUtil.filter(rs.getString("performedby")) + "
"); + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////// + + if (totals.get(incomplete) == 0) + { + msg.append("All treatments scheduled prior to " + _timeFormat.format(maxDate) + " have been marked complete as of " + getDateTimeFormat(c).format(curDate) + ".

\n"); + } + else + { + msg.append("There are " + totals.get(incomplete) + " treatments that have not been marked complete:

\n"); + msg.append(""); + + for (String area : totalByArea.keySet()) + { + msg.append("\n"); + } + + msg.append("
" + area + ":" + totalByArea.get(area) + "

\n"); + } + msg.append("


\n"); + } + } +} \ No newline at end of file diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/UnoccupiedRoomsNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/UnoccupiedRoomsNotification.java index 3e41bf290..7648d9e57 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/UnoccupiedRoomsNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/UnoccupiedRoomsNotification.java @@ -15,6 +15,7 @@ */ package org.labkey.onprc_ehr.notification; +import org.apache.commons.lang3.StringUtils; import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.CompareType; import org.labkey.api.data.Container; @@ -23,15 +24,28 @@ import org.labkey.api.data.Sort; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; +import org.labkey.api.ehr.EHRService; import org.labkey.api.ldk.LDKService; import org.labkey.api.module.Module; import org.labkey.api.query.FieldKey; +import org.labkey.api.query.QueryService; +import org.labkey.api.query.UserSchema; import org.labkey.api.security.User; +import org.labkey.api.settings.AppProps; import org.labkey.api.util.PageFlowUtil; +import org.labkey.api.data.ColumnInfo; +import org.labkey.api.data.Results; +import org.labkey.api.data.ResultsImpl; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashSet; import java.util.Date; +import java.util.Map; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; /** * User: bimber @@ -82,31 +96,38 @@ public String getMessageBodyHTML(Container c, User u) unoccupiedNHPRooms(c, u, msg); - + unoccupiedSLARooms(c, u, msg); return msg.toString(); } + private void unoccupiedNHPRooms(Container c, User u, final StringBuilder msg) { TableInfo ti = getEHRLookupsSchema(c, u).getTable("rooms", null , true, true); assert ti instanceof AbstractTableInfo; - LDKService.get().applyNaturalSort((AbstractTableInfo)ti, "room"); + LDKService.get().applyNaturalSort((AbstractTableInfo) ti, "room"); + + //NHP Locations SimpleFilter filter = new SimpleFilter(FieldKey.fromString("utilization/TotalAnimals"), 0); + + //NHP Location filters filter.addCondition(FieldKey.fromString("housingType/value"), "Rodent Location", CompareType.NEQ_OR_NULL); filter.addCondition(FieldKey.fromString("housingType/value"), "Off Campus", CompareType.NEQ_OR_NULL); filter.addCondition(FieldKey.fromString("datedisabled"), null, CompareType.ISBLANK); filter.addCondition(FieldKey.fromString("building"), null, CompareType.NONBLANK); Sort sort = new Sort("building,room"); + //NHP unoccupied locations TableSelector ts = new TableSelector(ti, PageFlowUtil.set("room", "building", "room_sortValue"), filter, sort); if (ts.getRowCount() == 0) { - msg.append("There are no empty rooms"); + msg.append("There are no empty NHP rooms"); } else { + msg.append("Unoccupied NHP Locations:
\n"); msg.append(""); msg.append(""); @@ -122,4 +143,62 @@ public void exec(ResultSet rs) throws SQLException msg.append("
BuildingRoom
"); } } + + private void unoccupiedSLARooms(Container c, User u, final StringBuilder msg) + { + /***************************** + //SLA Unoccupied Locations// + ******************************/ + TableInfo ti = QueryService.get().getUserSchema(u, c, "study").getTable("SLAOccupiedLocations"); + + + //SLA Locations + + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("Cage_Count"),null, CompareType.ISBLANK); + + //SLA Location filters + filter.addCondition(FieldKey.fromString("building"), null, CompareType.NONBLANK); + + + //SLA unoccupied locations + Set columns = new HashSet<>(); + columns.add(FieldKey.fromString("room")); + columns.add(FieldKey.fromString("building")); + columns.add(FieldKey.fromString("Date")); + columns.add(FieldKey.fromString("Animal_Count")); + columns.add(FieldKey.fromString("Cage_Count")); + + final Map colMap = QueryService.get().getColumns(ti, columns); + TableSelector ts = new TableSelector(ti, colMap.values(), filter, new Sort("building,room")); + + + String url = getExecuteQueryUrl(c, "sla", "SLAOccupiedLocations", null) ; + long total = ts.getRowCount(); + + if (total == 0) + { + msg.append("There are no empty SLA rooms"); + } + else + { + msg.append("


Unoccupied SLA Locations:

\n"); + msg.append(""); + msg.append(""); + + ts.forEach(new Selector.ForEachBlock() + { + @Override + public void exec(ResultSet object) throws SQLException + + { + Results rs = new ResultsImpl(object, colMap); + msg.append("")); + } + }); + + msg.append("
BuildingRoom
" + (rs.getString("building") == null ? PageFlowUtil.filter("") : PageFlowUtil.filter(rs.getString("building"))) + "" + PageFlowUtil.filter(rs.getString("room") + "
"); + + + } + } } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/VetReviewNotification.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/VetReviewNotification.java index d95ff8907..3e30b8c7e 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/VetReviewNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/VetReviewNotification.java @@ -13,6 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +/*promoting to uat for verification*/ package org.labkey.onprc_ehr.notification; import org.labkey.api.data.ColumnInfo; @@ -43,7 +45,7 @@ */ public class VetReviewNotification extends ColonyAlertsNotification { - public VetReviewNotification(Module owner) + public VetReviewNotification (Module owner) { super(owner); } @@ -83,7 +85,7 @@ public String getMessageBodyHTML(Container c, User u) { StringBuilder msg = new StringBuilder(); - remarksWithoutAssignedVet(c, u, msg); + /* remarksWithoutAssignedVet(c, u, msg);*/ vetRecordsUnderReview(c, u, msg); animalsWithoutAssignedVet(c, u, msg); @@ -97,22 +99,25 @@ public void vetRecordsUnderReview(Container c, User u, final StringBuilder msg) doRemarkQuery(c, u, msg, filter, "ALERT: The following animals that have remarks entered at least " + duration + " days ago, but have not yet been reviewed."); } - public void remarksWithoutAssignedVet(Container c, User u, final StringBuilder msg) - { + /*public void remarksWithoutAssignedVet(Container c, User u, final StringBuilder msg); + { SimpleFilter filter = new SimpleFilter(FieldKey.fromString("Id/assignedVet/assignedVet"), null, CompareType.ISBLANK); filter.addCondition(FieldKey.fromString("totalRemarksEnteredSinceReview"), 0, CompareType.GT); doRemarkQuery(c, u, msg, filter, "ALERT: The following animals that have remarks entered, but the animal is not currently assigned to a vet."); - } + }*/ public void doRemarkQuery(Container c, User u, final StringBuilder msg, SimpleFilter filter, String header) { - TableInfo ti = QueryService.get().getUserSchema(u, c, "study").getTable("demographics"); + //TableInfo ti = QueryService.get().getUserSchema(u, c, "study").getTable("demographics_AssignedVetNotification"); +// TableInfo ti = QueryService.get().getUserSchema(u, c, "study").getTable("demographics_VetAssignment_Notification"); + //Changed by Kollil on 6/19/2019. Created a new query to get the vet assignment info + TableInfo ti = QueryService.get().getUserSchema(u, c, "study").getTable("demographics_Vet_Assignment_Alert"); final Map cols = QueryService.get().getColumns(ti, PageFlowUtil.set( FieldKey.fromString("Id"), FieldKey.fromString("calculated_status"), FieldKey.fromString("earliestRemarkSinceReview"), FieldKey.fromString("lastVetReview"), - FieldKey.fromString("Id/assignedVet/assignedVet") + FieldKey.fromString("assignedVet") )); TableSelector ts = new TableSelector(ti, cols.values(), filter, new Sort("Id")); @@ -127,7 +132,7 @@ public void exec(ResultSet object) throws SQLException rows.add("" + "" + rs.getString(FieldKey.fromString("Id")) + "" + - "" + (rs.getString(FieldKey.fromString("Id/assignedVet/assignedVet")) == null ? "NONE" : rs.getString(FieldKey.fromString("Id/assignedVet/assignedVet"))) + "" + + "" + (rs.getString(FieldKey.fromString("assignedVet")) == null ? "NONE" : rs.getString(FieldKey.fromString("assignedVet"))) + "" + "" + getDateFormat(c).format(rs.getDate(FieldKey.fromString("earliestRemarkSinceReview"))) + "" + "" + (rs.getDate(FieldKey.fromString("lastVetReview")) == null ? "Never" : getDateFormat(c).format(rs.getDate(FieldKey.fromString("lastVetReview")))) + "" + "" + rs.getString(FieldKey.fromString("calculated_status")) + "" + @@ -152,7 +157,10 @@ protected void animalsWithoutAssignedVet(final Container c, User u, final String { SimpleFilter filter = new SimpleFilter(FieldKey.fromString("calculated_status"), "Alive"); filter.addCondition(FieldKey.fromString("Id/assignedVet/assignedVet"), null, CompareType.ISBLANK); - TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("demographics"), filter, null); + //TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("demographics_AssignedVetNotification"), filter, null); +// TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("demographics_VetAssignment_Notification"), filter, null); + //Changed by Kollil on 6/19/2019. Created a new query to get the vet assignment info + TableSelector ts = new TableSelector(getStudySchema(c, u).getTable("demographics_Vet_Assignment_Alert"), filter, null); long count = ts.getRowCount(); if (count > 0) { diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/query/ONPRC_EHRTriggerHelper.java b/onprc_ehr/src/org/labkey/onprc_ehr/query/ONPRC_EHRTriggerHelper.java index 3e17cead0..2e2d936e4 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/query/ONPRC_EHRTriggerHelper.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/query/ONPRC_EHRTriggerHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013-2018 LabKey Corporation + * Copyright (c) 2013-2015 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package org.labkey.onprc_ehr.query; -import org.apache.commons.beanutils.ConversionException; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.CaseInsensitiveHashMap; @@ -25,7 +25,6 @@ import org.labkey.api.data.CompareType; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; -import org.labkey.api.data.ConvertHelper; import org.labkey.api.data.DbSchema; import org.labkey.api.data.DbScope; import org.labkey.api.data.Results; @@ -39,7 +38,6 @@ import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; import org.labkey.api.ehr.EHRDemographicsService; -import org.labkey.api.ehr.EHRQCState; import org.labkey.api.ehr.EHRService; import org.labkey.api.ehr.demographics.AnimalRecord; import org.labkey.api.exp.api.StorageProvisioner; @@ -58,30 +56,30 @@ import org.labkey.api.security.UserPrincipal; import org.labkey.api.settings.AppProps; import org.labkey.api.study.DatasetTable; -import org.labkey.api.study.StudyService; import org.labkey.api.util.GUID; import org.labkey.api.util.MailHelper; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.Pair; -//import org.labkey.ehr.demographics.EHRDemographicsServiceImpl; -//import org.labkey.ehr.security.EHRSecurityManager; import org.labkey.onprc_ehr.ONPRC_EHRManager; import org.labkey.onprc_ehr.ONPRC_EHRModule; import org.labkey.onprc_ehr.ONPRC_EHRSchema; import org.labkey.onprc_ehr.notification.CullListNotification; import org.labkey.onprc_ehr.notification.MensesTMBNotification; +import org.labkey.onprc_ehr.notification.ProjectAlertsNotification; import org.labkey.onprc_ehr.notification.ProtocolAlertsNotification; import javax.mail.Address; import javax.mail.Message; import java.sql.ResultSet; import java.sql.SQLException; +import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -90,6 +88,9 @@ import java.util.Set; import java.util.TreeMap; +//import org.labkey.ehr.demographics.EHRDemographicsServiceImpl; +//import org.labkey.ehr.security.EHRSecurityManager; + /** * User: bimber * Date: 11/26/13 @@ -123,6 +124,9 @@ public class ONPRC_EHRTriggerHelper private static final String NONRESTRICTED = "Nonrestricted"; private static final String EXPERIMENTAL_EUTHANASIA = "EUTHANASIA, EXPERIMENTAL"; + private static final String NON_EXPERIMENTAL_EUTHANASIA = "EUTHANASIA, NONEXPERIMENTAL"; + private static final String SPONTANEOUS_DEATH = "Spontaneous Death"; + private SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm"); public ONPRC_EHRTriggerHelper(int userId, String containerId) @@ -180,6 +184,84 @@ public Map getExtraContext() return map; } + //Added by Kolli 3/3/20 + //This function automatically sets the study details endDate if previous study details endDate is empty when a new study is created. + public void closeStudyDetailsRecords(List> records) throws Exception + { + TableInfo housing = getTableInfo("study", "StudyDetails"); + List> toUpdate = new ArrayList<>(); + List> oldKeys = new ArrayList<>(); + + //sort on date + records = new ArrayList<>(records); + records.sort(new Comparator>() + { + @Override + public int compare(Map o1, Map o2) + { + try + { + Date date = dateTimeFormat.parse(o1.get("date").toString()); + Date date2 = dateTimeFormat.parse(o2.get("date").toString()); + + return date == null ? -1 : date.compareTo(date2); + } + catch (ParseException e) + { + return 0; + } + } + }); + + Set encounteredLsids = new HashSet<>(); + for (Map row : records) + { + Date date = dateTimeFormat.parse(row.get("date").toString()); + if (date.getHours() == 0 && date.getMinutes() == 0) + { + Exception e = new Exception(); + _log.error("Attempting to terminate study details records with a rounded date. This might indicate upstream code is rounding the date: " + dateTimeFormat.format(date), e); + } + + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("Id"), row.get("Id")); + filter.addCondition(FieldKey.fromString("enddate"), null, CompareType.ISBLANK); + + //we want to only close those records starting prior to this record + filter.addCondition(FieldKey.fromString("date"), date, CompareType.LTE); + filter.addCondition(FieldKey.fromString("objectid"), row.get("objectid"), CompareType.NEQ_OR_NULL); + if (!encounteredLsids.isEmpty()) + { + filter.addCondition(FieldKey.fromString("lsid"), encounteredLsids, CompareType.NOT_IN); + } + + TableSelector ts = new TableSelector(housing, Collections.singleton("lsid"), filter, null); + List ret = ts.getArrayList(String.class); + if (!ret.isEmpty()) + { + encounteredLsids.addAll(ret); + for (String lsid : ret) + { + Map r = new CaseInsensitiveHashMap<>(); + r.put("lsid", lsid); + r.put("enddate", date); + toUpdate.add(r); + + Map keyMap = new CaseInsensitiveHashMap<>(); + keyMap.put("lsid", lsid); + oldKeys.add(keyMap); + } + } + } + + if (!toUpdate.isEmpty()) + { + _log.info("closing study details records: " + toUpdate.size()); + Map context = getExtraContext(); + context.put("skipAnnounceChangedParticipants", true); + housing.getUpdateService().updateRows(getUser(), getContainer(), toUpdate, oldKeys, null, context); + } + } + public Date onTreatmentOrderChange(Map row, Map oldRow) throws Exception { if (row != null) @@ -201,24 +283,24 @@ public Date onTreatmentOrderChange(Map row, Map Object current = row.get(field); if (current instanceof Number) { - current = ((Number)current).doubleValue(); + current = ((Number) current).doubleValue(); } else if (current instanceof String) { - current = StringUtils.trimToNull((String)current); + current = StringUtils.trimToNull((String) current); } Object old = oldRow.get(field); if (old instanceof Number) { - old = ((Number)old).doubleValue(); + old = ((Number) old).doubleValue(); } else if (old instanceof String) { - old = StringUtils.trimToNull((String)old); + old = StringUtils.trimToNull((String) old); } - if ((current == null && old != null ) || (current != null && old != null && !current.equals(old))) + if ((current == null && old != null) || (current != null && old != null && !current.equals(old))) { _log.info("change: " + field); hasChanged = true; @@ -232,8 +314,8 @@ else if (old instanceof String) // hasChanged = true; //} } - - if (hasChanged && hasTreatmentBeenGiven((Date)oldRow.get("date"), (Integer)oldRow.get("frequency")) && !hasTerminated((Date)oldRow.get("enddate"))) +// Modified: 7-13-2017 R.Blasa + if (hasChanged && hasTreatmentBeenGiven((Date) oldRow.get("date"), (Integer) oldRow.get("frequency")) && !hasTerminated((Date) oldRow.get("enddate"))) { return createUpdatedTreatmentRow(row, oldRow); } @@ -267,33 +349,19 @@ private List getEarliestFrequencyHours(int frequency) private boolean hasTreatmentBeenGiven(Date startDate, Integer frequency) { - if (frequency == null) - { - return false; - } - Date earliestDose = null; - List hours = getEarliestFrequencyHours(frequency); - if (hours != null) + Date earliestDose = null; + Boolean results =false; + Date curDate = new Date(); + earliestDose = startDate; + if (earliestDose.before(new Date())) { - for (Integer hour : hours) - { - Calendar timeToTest = Calendar.getInstance(); - timeToTest.setTime(startDate); - timeToTest.set(Calendar.HOUR_OF_DAY, (int) Math.floor(hour / 100)); - timeToTest.set(Calendar.MINUTE, hour % 100); - - if (timeToTest.getTime().getTime() >= startDate.getTime()) - { - earliestDose = timeToTest.getTime(); - break; - } - } + results = true; } - + return results; // return true if the earliest expected dose is before now - return earliestDose == null ? false : earliestDose.before(new Date()); +// return earliestDose == null ? false : earliestDose.before(new Date()); } public Date createUpdatedTreatmentRow(Map row, Map oldRow) throws Exception @@ -303,7 +371,7 @@ public Date createUpdatedTreatmentRow(Map row, Map> getAnimalLocationsAfterMove(String room, List row : housingRecords) { - String rowRoom = (String)row.get("room"); - String rowCage = (String)row.get("cage"); - String id = (String)row.get("Id"); + String rowRoom = (String) row.get("room"); + String rowCage = (String) row.get("cage"); + String id = (String) row.get("Id"); if (row.get("enddate") == null) { @@ -875,9 +943,9 @@ private Double getRequiredCageSize(Double weight, String requirementset) { if (requirementset == null || requirementset.equals(row.get("requirementset"))) { - if (weight >= (Double)row.get("low") && weight < (Double)row.get("high")) + if (weight >= (Double) row.get("low") && weight < (Double) row.get("high")) { - return (Double)row.get("sqft"); + return (Double) row.get("sqft"); } } } @@ -891,9 +959,9 @@ private Double getRequiredCageHeight(Double weight, String requirementset) { if (requirementset == null || requirementset.equals(row.get("requirementset"))) { - if (weight >= (Double)row.get("low") && weight < (Double)row.get("high")) + if (weight >= (Double) row.get("low") && weight < (Double) row.get("high")) { - return (Double)row.get("height"); + return (Double) row.get("height"); } } } @@ -907,7 +975,7 @@ public Integer getHousingType(String room) if (roomRec == null) return null; - return (Integer)roomRec.get("housingTypeInt"); + return (Integer) roomRec.get("housingTypeInt"); } public Integer getHousingCondition(String room) @@ -916,7 +984,7 @@ public Integer getHousingCondition(String room) if (roomRec == null) return null; - return (Integer)roomRec.get("housingConditionInt"); + return (Integer) roomRec.get("housingConditionInt"); } private List> getCageSizeRecords() @@ -1016,7 +1084,8 @@ else if (ret.size() > 1) } // Taken from DateUtils. should remove if we upgrade core - private Date maxDate(Date d1, Date d2) { + private Date maxDate(Date d1, Date d2) + { if (d1 == null && d2 == null) return null; if (d1 == null) return d2; if (d2 == null) return d1; @@ -1046,12 +1115,12 @@ public void closeActiveAssignmentRecords(String id, Date deathDate, String cause row.put("enddate", deathDate); + //Modified: 6-8-2018 R.Blasa All experimetal and Euthenized cause of death are automitaclly assigned 206 at release + if (EXPERIMENTAL_EUTHANASIA.equals(causeOfDeath) || NON_EXPERIMENTAL_EUTHANASIA.equals(causeOfDeath) || SPONTANEOUS_DEATH.equals(causeOfDeath) ) - //Modified: 6-28-2016 R.Blasa All experimetal and Euthenized cause of death are automitaclly assigned 206 at release - if (EXPERIMENTAL_EUTHANASIA.equals(causeOfDeath) ) { - row.put("releaseCondition", 206); + row.put("releaseCondition", 206); } @@ -1078,7 +1147,7 @@ public void closeActiveAssignmentRecords(String id, Date deathDate, String cause } //Added on 10/5/2016, L.Kolli - public Map onAnimalArrival_AddDemographics(String id, Map row) + public Map onAnimalArrival_AddDemographics(String id, Map row) throws QueryUpdateServiceException, DuplicateKeyException, SQLException, BatchValidationException { Map demographicsProps = new HashMap(); @@ -1097,12 +1166,103 @@ public Map onAnimalArrival_AddDemographics(String id, Map row) throws QueryUpdateServiceException, DuplicateKeyException, SQLException, BatchValidationException + { + if (row.get("birth") != null) + { + Map birthProps = new HashMap<>(); + for (String key : new String[]{"Id", "dam", "sire"}) + { + if (row.containsKey(key)) + { + birthProps.put(key, row.get(key)); + } + } + birthProps.put("date", row.get("birth")); + birthProps.put("gender", row.get("gender")); + birthProps.put("species", row.get("species")); + birthProps.put("geographic_origin", row.get("geographic_origin")); + + //Added: 10-14-2016 R.Blasa + birthProps.put("Arrival_Date", row.get("date")); + + createBirthRecord_ONPRC(id, birthProps); + } + } + + //Added on 09/30/2016, L.Kolli + public void createBirthRecord_ONPRC(String id, Map props) throws QueryUpdateServiceException, DuplicateKeyException, SQLException, BatchValidationException + { + if (id == null) ///If AId is null, return + return; + + //Check if the AId exists in the Birth table + TableInfo ti1 = getTableInfo("study", "birth"); + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("Id"), id, CompareType.EQUAL); + + TableSelector ts = new TableSelector(ti1, filter, null); + if (ts.exists()) + { + //Birth record found. Don't make duplicate entry + return; + } + else //Enter newly entered AnimalID into Birth table + { + TableInfo ti = getTableInfo("study", "birth"); + Map row = new CaseInsensitiveHashMap<>(); + row.putAll(props); + if (!row.containsKey("objectid")) + { + row.put("objectid", new GUID().toString()); + } + + List> rows = new ArrayList<>(); + rows.add(row); + BatchValidationException errors = new BatchValidationException(); + ti.getUpdateService().insertRows(getUser(), getContainer(), rows, errors, null, getExtraContext()); + + if (errors.hasErrors()) + throw errors; + } + + } + // Added: 6-27-2017 F.Blasa Process when transitioning from Prenatal - Fetus to Live + public void doBirthConditionAfterPrenatal(String id, Date date, String dam, Date Arrival_Date, String birthCondition, boolean isBecomingPublic) throws Exception + { + //is the infant is dead, terminate the assignments + Date enddate = isBirthAlive(birthCondition) ? null : date; + + String nonRestrictedFlag = getFlag("Condition", NONRESTRICTED, null, true); + if (nonRestrictedFlag != null) + { + //Modified: 10-14-2016 R.Blasa + Date Arrival_date = null; + if (Arrival_Date != null) + { + Arrival_date = Arrival_Date; + + } + else + { + Arrival_date = date; + } + //only add initial status if born alive + EHRService.get().ensureFlagActive(getUser(), getContainer(), nonRestrictedFlag, Arrival_date, enddate, null, Collections.singletonList(id), false); + } + else + { + _log.warn("Unable to find active flag for condition nonrestricted"); + } + } + + //Modified: 10-13-2016 R.Blasa to include assign Arrival date + public void doBirthTriggers(String id, Date date, String dam, Date Arrival_Date, String birthCondition, String species, boolean isBecomingPublic) throws Exception { //is the infant is dead, terminate the assignments Date enddate = isBirthAlive(birthCondition) ? null : date; + //also check for a pre-existing death record: Date deathDate = new TableSelector(getTableInfo("study", "deaths"), Collections.singleton("date"), new SimpleFilter(FieldKey.fromString("Id"), id), null).getObject(Date.class); if (deathDate != null) @@ -1116,18 +1276,60 @@ public void doBirthTriggers(String id, Date date, String dam, Date flagStartDate String nonRestrictedFlag = getFlag("Condition", NONRESTRICTED, null, true); if (nonRestrictedFlag != null) { - if (flagStartDate == null) + //Modified: 10-14-2016 R.Blasa + Date Arrival_date = null; + if (Arrival_Date != null) + { + Arrival_date = Arrival_Date; + + } + else { - flagStartDate = date; + Arrival_date = date; } + //only add initial status if born alive - EHRService.get().ensureFlagActive(getUser(), getContainer(), nonRestrictedFlag, flagStartDate, enddate, null, Collections.singletonList(id), false); + EHRService.get().ensureFlagActive(getUser(), getContainer(), nonRestrictedFlag, Arrival_date, enddate, null, Collections.singletonList(id), false); } else { _log.warn("Unable to find active flag for condition nonrestricted"); } + + + } +// Added: 10-27-2017 R.Blasa Create an SPR4 entries for Rhesus macaques +// Modified: 6-19-2019 R.Blasa to Create SP4 when Rhesus and no Dam assigned to Infant + if ("Live Birth".equalsIgnoreCase(birthCondition) && "RHESUS MACAQUE".equalsIgnoreCase(species) && dam == null ) + + { + + String SPFFlag = getFlag("SPF", "SPF 4", null, true); + + TableInfo flagsSP4 = getTableInfo("study", "flags"); + SimpleFilter flagFilter = new SimpleFilter(FieldKey.fromString("Id"), id); + + //Note: Validate if SPF 4 is active + flagFilter.addCondition(FieldKey.fromString("flag/value"), "SPF 4"); + flagFilter.addClause(new SimpleFilter.OrClause( + new CompareType.CompareClause(FieldKey.fromString("enddate"), CompareType.DATE_GTE, date), + new CompareType.CompareClause(FieldKey.fromString("enddate"), CompareType.ISBLANK, null) + )); + + + TableSelector existingSP4 = new TableSelector(flagsSP4, Collections.singleton("flag"), flagFilter, null); + if (existingSP4.exists()) + { + _log.info("SP4 Flag active record exist for this monkey id: " + id + "Value") ; + } + else + { + _log.info("adding SP4 Animal : " + id + "Value"); + + EHRService.get().ensureFlagActive(getUser(), getContainer(), SPFFlag, date, enddate, null, Collections.singletonList(id), false); + + } } //NOTE: we allow this to run the first time this record is public with a non-null dam. this allows the record to be created without dam, then updated @@ -1154,6 +1356,41 @@ else if (flagList.size() > 1) { _log.error("dam has more than 1 active SPF flag: " + dam); } + else if (flagList.size() == 0) + { + // Added: 6-19-2019 R.Blasa Create new flag if dam is not assigned to SPRF and Rhesus Macaque + if ("Live Birth".equalsIgnoreCase(birthCondition) && "RHESUS MACAQUE".equalsIgnoreCase(species) ) + + { + + String SPFFlag = getFlag("SPF", "SPF 4", null, true); + + TableInfo flagsSP4 = getTableInfo("study", "flags"); + SimpleFilter flagFilter2 = new SimpleFilter(FieldKey.fromString("Id"), id); + + //Note: Validate if SPF 4 is active + flagFilter2.addCondition(FieldKey.fromString("flag/value"), "SPF 4"); + flagFilter2.addClause(new SimpleFilter.OrClause( + new CompareType.CompareClause(FieldKey.fromString("enddate"), CompareType.DATE_GTE, date), + new CompareType.CompareClause(FieldKey.fromString("enddate"), CompareType.ISBLANK, null) + )); + + + TableSelector existingSP4 = new TableSelector(flagsSP4, Collections.singleton("flag"), flagFilter2, null); + if (existingSP4.exists()) + { + _log.info("SP4 Flag active record exist for this monkey id: " + id + "Value") ; + } + else + { + _log.info("adding SP4 Animal : " + id + "Value"); + + EHRService.get().ensureFlagActive(getUser(), getContainer(), SPFFlag, date, enddate, null, Collections.singletonList(id), false); + + } + } + } + //also breeding groups TableInfo animalGroups = getTableInfo("study", "animal_group_members"); @@ -1210,7 +1447,8 @@ else if (flagList.size() > 1) new CompareType.CompareClause(FieldKey.fromString("enddate"), CompareType.DATE_GTE, date), new CompareType.CompareClause(FieldKey.fromString("enddate"), CompareType.ISBLANK, null) )); - assignmentFilter.addCondition(FieldKey.fromString("project/displayName"), PageFlowUtil.set(ONPRC_EHRManager.U42_PROJECT, ONPRC_EHRManager.U24_PROJECT), CompareType.IN); +// Modified:5-12-2017 Added Japanese Macaque Assignments + assignmentFilter.addCondition(FieldKey.fromString("project/displayName"), PageFlowUtil.set(ONPRC_EHRManager.U42_PROJECT, ONPRC_EHRManager.U24_PROJECT, ONPRC_EHRManager.JMAC_PROJECT), CompareType.IN); TableSelector ts3 = new TableSelector(assignment, Collections.singleton("project"), assignmentFilter, null); List assignmentList = ts3.getArrayList(Integer.class); @@ -1301,7 +1539,7 @@ public String checkForConditionDowngrade(String id, Date date, final Integer con List foundCodes = findHigherActiveConditonCodes(id, date, condition); if (!foundCodes.isEmpty()) { - return "Animal already has a higher condition code (" + (StringUtils.join(foundCodes, ","))+ "), cannot choose a lower code unless the existing code is removed or disabled"; + return "Animal already has a higher condition code (" + (StringUtils.join(foundCodes, ",")) + "), cannot choose a lower code unless the existing code is removed or disabled"; } return null; @@ -1389,8 +1627,8 @@ public void exec(ResultSet rs) throws SQLException { for (Map r : recordsInTransaction) { - String id = (String)r.get("Id"); - Number project = (Number)r.get("project"); + String id = (String) r.get("Id"); + Number project = (Number) r.get("project"); if (id == null || project == null) { continue; @@ -1559,7 +1797,7 @@ public String validateHousingConditionInsert(String id, String flag, String obje filter.addCondition(FieldKey.fromString("isActive"), true, CompareType.EQUAL); filter.addCondition(FieldKey.fromString("Id"), id, CompareType.EQUAL); - TableInfo flagsTable = getTableInfo("study", "flags"); + TableInfo flagsTable = getTableInfo("study", "Animal Record Flags"); TableSelector ts = new TableSelector(flagsTable, PageFlowUtil.set("flag"), filter, null); List values = ts.getArrayList(String.class); if (values != null && !values.isEmpty()) @@ -1600,7 +1838,7 @@ public String updateDividers(String id, String room, String cage, Integer divide } //first gather all animals currently housed, by cage - //Map> animalMap = getAnimalLocationsAfterMove(room, rowsInTransaction); + Map> animalMap = getAnimalLocationsAfterMove(room, rowsInTransaction); Set errors = new HashSet<>(); //also build list of existing dividers and changes @@ -1747,35 +1985,25 @@ else if (DbScope.getLabKeyScope().getSqlDialect().isSqlServer()) return _nextProtocolId; } - public boolean requiresAssistingStaff(Object procedureText) + public boolean requiresAssistingStaff(Integer procedureId) { - if (procedureText == null) + if (procedureId == null) { return false; } - try + if (!_cachedProcedureCategories.containsKey(procedureId)) { - Integer procedureId = ConvertHelper.convert(procedureText, Integer.class); - if (!_cachedProcedureCategories.containsKey(procedureId)) - { - TableInfo ti = getTableInfo("ehr_lookups", "procedures"); - TableSelector ts = new TableSelector(ti, PageFlowUtil.set("category"), new SimpleFilter(FieldKey.fromString("rowid"), procedureId), null); - String category = ts.getObject(String.class); - - _cachedProcedureCategories.put(procedureId, category); - } - - String category = _cachedProcedureCategories.get(procedureId); + TableInfo ti = getTableInfo("ehr_lookups", "procedures"); + TableSelector ts = new TableSelector(ti, PageFlowUtil.set("category"), new SimpleFilter(FieldKey.fromString("rowid"), procedureId), null); + String category = ts.getObject(String.class); - return "Surgery".equals(category); - } - catch (ConversionException e) - { - _log.warn("unable to convert procedureId to integer: [" + procedureText + "]", new Exception()); + _cachedProcedureCategories.put(procedureId, category); } - return false; + String category = _cachedProcedureCategories.get(procedureId); + + return "Surgery".equals(category); } public String getSpeciesForDam(String dam) @@ -1821,22 +2049,24 @@ public String validateObservation(String category, String observation) private Map> _cachedObservations = new HashMap<>(); - private @NotNull Set getAllowableObservations(String category) + private + @NotNull + Set getAllowableObservations(String category) { if (!_cachedObservations.containsKey(category)) { TableInfo ti = getTableInfo("ehr", "observation_types"); TableSelector ts = new TableSelector(ti, PageFlowUtil.set("schemaName", "queryName", "valuecolumn"), new SimpleFilter(FieldKey.fromString("value"), category), null); - Map record = ts.getMap(); + Map record = ts.getObject(Map.class); Set allowable; if (record != null && record.get("schemaname") != null && record.get("queryname") != null && record.get("valuecolumn") != null) { - TableInfo valuesTable = getTableInfo((String)record.get("schemaname"), (String)record.get("queryname")); + TableInfo valuesTable = getTableInfo((String) record.get("schemaname"), (String) record.get("queryname")); if (valuesTable != null) { allowable = new CaseInsensitiveHashSet(); - TableSelector ts2 = new TableSelector(valuesTable, PageFlowUtil.set((String)record.get("valuecolumn")), null, null); + TableSelector ts2 = new TableSelector(valuesTable, PageFlowUtil.set((String) record.get("valuecolumn")), null, null); allowable.addAll(ts2.getArrayList(String.class)); } else @@ -1964,7 +2194,6 @@ public void sendMenseNotifications(String id) } - //Added 9-2-2015 Blasa public void sendCullListNotifications(String id, String date, String flag) { @@ -2071,44 +2300,135 @@ public void sendProtocolNotifications(String protocolid) html.append("Iacuc Protocol Investigator Iacuc Approval Date\n"); ts.forEach(new Selector.ForEachBlock() - { + { + + @Override + public void exec(ResultSet rs) throws SQLException + { + + //Translate Investigator id to its true name + TableInfo ti2 = getTableInfo("onprc_ehr", "investigators"); + SimpleFilter filter2 = new SimpleFilter(FieldKey.fromString("rowid"), rs.getString("investigatorId")); + filter2.addCondition(FieldKey.fromString("datedisabled"), true, CompareType.ISBLANK); + + TableSelector ts2 = new TableSelector(ti2, PageFlowUtil.set("lastname"), filter2, null); + List ret2 = ts2.getArrayList(String.class); + if (ret2 != null && !ret2.isEmpty()) + { + for (String Investname : ret2) + { + html.append("" + (rs.getString("external_id") == null ? PageFlowUtil.filter("") : PageFlowUtil.filter(rs.getString("external_id"))) + " " + PageFlowUtil.filter(Investname) + " " + PageFlowUtil.filter(rs.getString("approve")) + "\n"); + break; + } + } + } + + } + + ); + + } + + + html.append("\n"); + + sendMessage(subject, html.toString(), recipients); + + } + + + //Added 3-6-2019 Blasa + public void sendProjectNotifications(Integer projectid) + { + + if (!NotificationService.get().isServiceEnabled()) + { + _log.info("notification service is not enabled, will not send Project notification."); + return; + } + + String subject = "Center Project Notification: "; + + Set recipients = NotificationService.get().getRecipients(new ProjectAlertsNotification(ModuleLoader.getInstance().getModule(ONPRC_EHRModule.class)), getContainer()); + + if (recipients.size() == 0) + { + _log.warn("No recipients, Center Project notification"); + return; + } + final StringBuilder html = new StringBuilder(); + +// Added: 4-3-2019 R.Blasa + Date roundedMax = new Date(); + roundedMax = DateUtils.truncate(roundedMax, Calendar.DATE); - @Override - public void exec(ResultSet rs) throws SQLException - { + TableInfo ti = getTableInfo("ehr", "project"); + SimpleFilter filter = new SimpleFilter(FieldKey.fromString("project"), projectid); + filter.addCondition(FieldKey.fromString("enddateCoalesced"), roundedMax, CompareType.GTE); - //Translate Investigator id to its true name - TableInfo ti2 = getTableInfo("onprc_ehr", "investigators"); - SimpleFilter filter2 = new SimpleFilter(FieldKey.fromString("rowid"), rs.getString("investigatorId")); - filter2.addCondition(FieldKey.fromString("datedisabled"), true, CompareType.ISBLANK); + Sort sort = new Sort("name"); - TableSelector ts2 = new TableSelector(ti2, PageFlowUtil.set("lastname"), filter2, null); - List ret2 = ts2.getArrayList(String.class); - if (ret2 != null && !ret2.isEmpty()) + List names= new ArrayList<>(); + FieldKey protocolFieldKey = FieldKey.fromString("protocol/external_id"); + names.add(protocolFieldKey); + names.add(FieldKey.fromString("name")); + names.add(FieldKey.fromString("investigatorId")); + names.add(FieldKey.fromString("startdate")); + names.add(FieldKey.fromString("project")); + + final Map colKeys = QueryService.get().getColumns(ti, names); + final ColumnInfo protocolColumn = colKeys.get(protocolFieldKey); + TableSelector ts = new TableSelector(ti, colKeys.values(), filter, sort); + + if (ts.getRowCount() == 0) + { + html.append("There are no Center Projects to display"); + _log.info("Success Section Part 1X"); + return; + } + else + { + //Create header information on the report + + html.append(""); + html.append("\n"); + ts.forEach(new Selector.ForEachBlock() { - for (String Investname : ret2) + + @Override + public void exec(ResultSet rs) throws SQLException { - //html.append("\n"); - html.append("\n"); - break; + + TableInfo ti2 = getTableInfo("onprc_ehr", "investigators"); + SimpleFilter filter2 = new SimpleFilter(FieldKey.fromString("rowid"), rs.getString("investigatorId")); + filter2.addCondition(FieldKey.fromString("datedisabled"), true, CompareType.ISBLANK); + + TableSelector ts2 = new TableSelector(ti2, PageFlowUtil.set("lastname"), filter2, null); + List ret2 = ts2.getArrayList(String.class); + if (ret2 != null && !ret2.isEmpty()) + { + for (String Investname : ret2) + { + html.append("\n"); + break; + + } + } } - } - } - } + } ); } - html.append("
Center ProjectProject IDIacuc Protocol Investigator Center Project Start Date
" + (rs.getString("external_id") == null ? "" : rs.getString("external_id")) + "" + Investname + "" + rs.getString("approve") + "
" + (rs.getString("external_id") == null ? "" : rs.getString("external_id")) + " " + Investname + " " + rs.getString("approve") + "
" + PageFlowUtil.filter(rs.getString("name")) + "" + PageFlowUtil.filter(rs.getString("project")) + " " + PageFlowUtil.filter(rs.getString(protocolColumn.getAlias())) + " " + PageFlowUtil.filter(Investname) + " " + PageFlowUtil.filter(rs.getString("startdate")) + "
\n"); sendMessage(subject, html.toString(), recipients); } - //Added 9-2-2015 Blasa + //Added 9-2-2015 Blasa private void sendMessage(String subject, String bodyHtml, Collection recipients) { try @@ -2148,4 +2468,97 @@ private void sendMessage(String subject, String bodyHtml, Collection ids) throws Exception + { + TableInfo ti = getTableInfo("study", "demographicsGeneticAncestry"); + if (ti == null) + { + return; + } + + Set keys = new HashSet<>(); + keys.add(FieldKey.fromString("Id")); + keys.add(FieldKey.fromString("Id/demographics/lsid")); + keys.add(FieldKey.fromString("Id/demographics/geographic_origin")); + keys.add(FieldKey.fromString("geneticAncestry")); + final Map colMap = QueryService.get().getColumns(ti, keys); + + final List> toUpdate = new ArrayList<>(); + final List> oldKeys = new ArrayList<>(); + TableSelector ts = new TableSelector(ti, colMap.values(), new SimpleFilter(FieldKey.fromString("Id"), ids, CompareType.IN), null); + ts.forEach(new Selector.ForEachBlock() + { + @Override + public void exec(ResultSet object) throws SQLException + { + ResultsImpl rs = new ResultsImpl(object, colMap); + String origin = rs.getString(FieldKey.fromString("Id/demographics/geographic_origin")); + String geneticAncestry = rs.getString(FieldKey.fromString("geneticAncestry")); + String lsid = rs.getString(FieldKey.fromString("Id/demographics/lsid")); + if (lsid != null && geneticAncestry != null && !geneticAncestry.equals(origin)) + { + Map row = new CaseInsensitiveHashMap<>(); + row.put("lsid", lsid); + row.put("geographic_origin", geneticAncestry); + Map keyRow = new CaseInsensitiveHashMap<>(); + keyRow.put("lsid", lsid); + + oldKeys.add(keyRow); + toUpdate.add(row); + } + + } + }); + + if (!toUpdate.isEmpty()) + { + TableInfo demographics = getTableInfo("study", "demographics"); + demographics.getUpdateService().updateRows(_user, _container, toUpdate, oldKeys, null, getExtraContext()); + } + } + + //New blood draw validation code by LKolli, 2/1/2019 + public String verifyBloodVolume_New(String id, Date date, List> recordsInTransaction, List> weightsInTransaction, String objectId, Double quantity) + { + //Check for valid AnimalId, date and quantity + if (id == null || date == null || quantity == null) + return null; + + //Get ABV data from onprc_ehr.AvailableBloodVolume + Double maxAllowable = getABV(id); + if (maxAllowable == null) + return "Couldn't find available blood volume for AnimalId: " + id ; + + if (quantity > maxAllowable) + return "The quantity requested, " + quantity + "ml exceeds the available blood volume, " + maxAllowable + "ml for AnimalId: " + id ; + + return null; + } + + //Query the db table, onprc_ehr.AvailableBloodVolume for the max allowable blood. + //This table is populated every hour during business hours by Mathematica. + public Double getABV(String id) + { + TableInfo ti = getTableInfo("onprc_ehr", "AvailableBloodVolume"); + TableSelector ts = new TableSelector(ti, PageFlowUtil.set("ABV"), new SimpleFilter(FieldKey.fromString("Id"), id), null); + + return ts.getObject(Double.class); + } + } diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/table/ONPRC_EHRCustomizer.java b/onprc_ehr/src/org/labkey/onprc_ehr/table/ONPRC_EHRCustomizer.java index 0ecc0d611..ad062be9f 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/table/ONPRC_EHRCustomizer.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/table/ONPRC_EHRCustomizer.java @@ -26,6 +26,7 @@ import org.labkey.api.data.DisplayColumn; import org.labkey.api.data.DisplayColumnFactory; import org.labkey.api.data.JdbcType; +import org.labkey.api.data.MutableColumnInfo; import org.labkey.api.data.RenderContext; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.TableInfo; @@ -267,6 +268,8 @@ private void addCalculatedCols(AbstractTableInfo ds, String dateColName) appendGroupsAtTimeCol(ehrSchema, ds, dateColName); appendProblemsAtTimeCol(ehrSchema, ds, dateColName); appendFlagsAtTimeCol(ehrSchema, ds, dateColName); +// Added:7-16-2019 R.Blasa + appendFlagsAlertActiveCol(ehrSchema, ds); appendIsAssignedAtTimeCol(ehrSchema, ds, dateColName); } } @@ -852,6 +855,7 @@ private void customizeCasesTable(AbstractTableInfo ti) { appendLatestHxCol(ti); appendSurgeryCol(ti); + appendSurgeryFollupDaysyCol(ti); //Added: 11/1/2017 R.Blasa appendCaseHistoryCol(ti); String problemCategories = "problemCategories"; @@ -1061,6 +1065,12 @@ private void customizeTreatmentOrdersTable(AbstractTableInfo ti) { ti.getMutableColumn("qualifier").setHidden(true); } + + if (ti.getColumn("isActive") != null) + { + ti.removeColumn(ti.getColumn("isActive")); + EHRService.get().addIsActiveCol(ti, true, EHRService.EndingOption.endsToday, EHRService.EndingOption.activeAfterMidnightTonight); + } } private void customizeTreatmentFrequency(AbstractTableInfo ti) @@ -1118,7 +1128,7 @@ private void customizeDemographicsTable(AbstractTableInfo ti) @Override public DisplayColumn createRenderer(ColumnInfo colInfo) { - return new FixedWidthDisplayColumn(colInfo, 200); + return new FixedWidthDisplayColumn(colInfo, 100); } }); @@ -1147,37 +1157,29 @@ public DisplayColumn createRenderer(ColumnInfo colInfo) //clinical remarks entered since last vet review is a proxy for whether it needs to be reviewed again EHRQCState completedQCState = EHRService.get().getQCStates(ti.getUserSchema().getContainer()).get(EHRService.QCSTATES.Completed.name()); - if (completedQCState != null) + // Even if QC states aren't loaded, inject the columns for query validation purposes + int qcStateRowId = completedQCState == null ? -1 : completedQCState.getRowId(); + + SQLFragment totalRemarkSql = new SQLFragment("(SELECT count(*) FROM " + remarksTable.getSelectName() + " cr WHERE cr.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND cr.qcstate = ? AND cr.datefinalized >= COALESCE((SELECT max(t.date) as expr FROM " + obsRealTable.getSelectName() + " t WHERE t.category = ? AND " + ExprColumn.STR_TABLE_ALIAS + ".participantId = t.participantId), ?) AND (cr.category IS NULL or cr.category = ? or cr.category = ?))", qcStateRowId, ONPRC_EHRManager.VET_REVIEW, getDefaultVetReviewDate(ti.getUserSchema().getContainer()), ONPRC_EHRManager.CLINICAL_SOAP_CATEGORY, ONPRC_EHRManager.RECORD_AMENDMENT); + ExprColumn totalRemarkCol = new ExprColumn(ti, "totalRemarksEnteredSinceReview", totalRemarkSql, JdbcType.INTEGER, ti.getColumn("Id")); + totalRemarkCol.setLabel("# Remarks Entered Since Last Vet Review"); + ti.addColumn(totalRemarkCol); + + SQLFragment earliestRemarkSql = new SQLFragment("(SELECT min(cr.datefinalized) as expr FROM " + remarksTable.getSelectName() + " cr WHERE cr.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND cr.qcstate = ? AND cr.datefinalized >= COALESCE((SELECT max(t.date) as expr FROM " + obsRealTable.getSelectName() + " t WHERE t.category = ? AND " + ExprColumn.STR_TABLE_ALIAS + ".participantId = t.participantId), ?) AND (cr.category IS NULL or cr.category = ? or cr.category = ?))", qcStateRowId, ONPRC_EHRManager.VET_REVIEW, getDefaultVetReviewDate(ti.getUserSchema().getContainer()), ONPRC_EHRManager.CLINICAL_SOAP_CATEGORY, ONPRC_EHRManager.RECORD_AMENDMENT); + ExprColumn earliestRemarkCol = new ExprColumn(ti, "earliestRemarkSinceReview", earliestRemarkSql, JdbcType.TIMESTAMP, ti.getColumn("Id")); + earliestRemarkCol.setLabel("Earliest Remark Entered Since Last Vet Review"); + ti.addColumn(earliestRemarkCol); + + //date part not supported in postgres + if (ti.getSqlDialect().isSqlServer()) { - SQLFragment totalRemarkSql = new SQLFragment("(SELECT count(*) FROM " + remarksTable.getSelectName() + " cr WHERE cr.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND cr.qcstate = ? AND cr.datefinalized >= COALESCE((SELECT max(t.date) as expr FROM " + obsRealTable.getSelectName() + " t WHERE t.category = ? AND " + ExprColumn.STR_TABLE_ALIAS + ".participantId = t.participantId), ?) AND (cr.category IS NULL or cr.category = ? or cr.category = ?))", completedQCState.getRowId(), ONPRC_EHRManager.VET_REVIEW, getDefaultVetReviewDate(ti.getUserSchema().getContainer()), ONPRC_EHRManager.CLINICAL_SOAP_CATEGORY, ONPRC_EHRManager.RECORD_AMENDMENT); - ExprColumn totalRemarkCol = new ExprColumn(ti, "totalRemarksEnteredSinceReview", totalRemarkSql, JdbcType.INTEGER, ti.getColumn("Id")); - totalRemarkCol.setLabel("# Remarks Entered Since Last Vet Review"); - ti.addColumn(totalRemarkCol); - - SQLFragment earliestRemarkSql = new SQLFragment("(SELECT min(cr.datefinalized) as expr FROM " + remarksTable.getSelectName() + " cr WHERE cr.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND cr.qcstate = ? AND cr.datefinalized >= COALESCE((SELECT max(t.date) as expr FROM " + obsRealTable.getSelectName() + " t WHERE t.category = ? AND " + ExprColumn.STR_TABLE_ALIAS + ".participantId = t.participantId), ?) AND (cr.category IS NULL or cr.category = ? or cr.category = ?))", completedQCState.getRowId(), ONPRC_EHRManager.VET_REVIEW, getDefaultVetReviewDate(ti.getUserSchema().getContainer()), ONPRC_EHRManager.CLINICAL_SOAP_CATEGORY, ONPRC_EHRManager.RECORD_AMENDMENT); - ExprColumn earliestRemarkCol = new ExprColumn(ti, "earliestRemarkSinceReview", earliestRemarkSql, JdbcType.TIMESTAMP, ti.getColumn("Id")); - earliestRemarkCol.setLabel("Earliest Remark Entered Since Last Vet Review"); - ti.addColumn(earliestRemarkCol); - - //date part not supported in postgres - if (ti.getSqlDialect().isSqlServer()) - { - //NOTE: the first token in the group_concat() is used for sorting - SQLFragment groupConatSql = new SQLFragment(ti.getSqlDialect().concatenate("LEFT(CONVERT(VARCHAR, cr.date, 120), 19)", "'<>'", "CAST(" + ti.getSqlDialect().getDatePart(Calendar.MONTH, "cr.date") + " AS VARCHAR)", "'/'", "CAST(" + ti.getSqlDialect().getDatePart(Calendar.DATE, "cr.date") + " AS VARCHAR)", "': '", getChr(ti) + "(10)", "CASE WHEN cr.description IS NULL THEN '' ELSE " + ti.getSqlDialect().concatenate("COALESCE(cr.description, '')", getChr(ti) + "(10)") + " END", "CASE WHEN cr.remark IS NULL THEN '' ELSE " + ti.getSqlDialect().concatenate("'Remark: '", "COALESCE(cr.remark, '')", getChr(ti) + "(10)") + " END", "CASE WHEN cr.performedby IS NULL THEN '' ELSE " + ti.getSqlDialect().concatenate("'Entered By: '", "COALESCE(cr.performedby, '')", getChr(ti) + "(10)") + " END", "'<>'","cr.objectid", "'<:>'")); - SQLFragment remarkSql = new SQLFragment("(SELECT " + ti.getSqlDialect().getGroupConcat(groupConatSql, false, true, ti.getSqlDialect().concatenate(getChr(ti) + "(10)", getChr(ti) + "(10)")).getSqlCharSequence() + " as expr1 FROM " + remarksTable.getSelectName() + " cr WHERE cr.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND cr.qcstate = ? AND cr.datefinalized <= {fn now()} AND (cr.category IS NULL or cr.category = ? or cr.category = ?) AND cr.datefinalized >= COALESCE((SELECT max(t.date) as expr FROM " + obsRealTable.getSelectName() + " t WHERE t.category = ? AND " + ExprColumn.STR_TABLE_ALIAS + ".participantId = t.participantId), ?))", completedQCState.getRowId(), ONPRC_EHRManager.CLINICAL_SOAP_CATEGORY, ONPRC_EHRManager.RECORD_AMENDMENT, ONPRC_EHRManager.VET_REVIEW, getDefaultVetReviewDate(ti.getUserSchema().getContainer())); - ExprColumn remarkCol = new ExprColumn(ti, "remarksEnteredSinceReview", remarkSql, JdbcType.VARCHAR, ti.getColumn("Id"), ti.getColumn("date")); - remarkCol.setLabel("Remarks Entered Since Last Vet Review"); - remarkCol.setDisplayWidth("200"); - remarkCol.setDisplayColumnFactory(new DisplayColumnFactory() - { - @Override - public DisplayColumn createRenderer(ColumnInfo colInfo) - { - return new VetReviewDisplayColumn(colInfo); - } - }); - ti.addColumn(remarkCol); - } + //NOTE: the first token in the group_concat() is used for sorting + SQLFragment groupConatSql = new SQLFragment(ti.getSqlDialect().concatenate("LEFT(CONVERT(VARCHAR, cr.date, 120), 19)", "'<>'", "CAST(" + ti.getSqlDialect().getDatePart(Calendar.MONTH, "cr.date") + " AS VARCHAR)", "'/'", "CAST(" + ti.getSqlDialect().getDatePart(Calendar.DATE, "cr.date") + " AS VARCHAR)", "': '", getChr(ti) + "(10)", "CASE WHEN cr.description IS NULL THEN '' ELSE " + ti.getSqlDialect().concatenate("COALESCE(cr.description, '')", getChr(ti) + "(10)") + " END", "CASE WHEN cr.remark IS NULL THEN '' ELSE " + ti.getSqlDialect().concatenate("'Remark: '", "COALESCE(cr.remark, '')", getChr(ti) + "(10)") + " END", "CASE WHEN cr.performedby IS NULL THEN '' ELSE " + ti.getSqlDialect().concatenate("'Entered By: '", "COALESCE(cr.performedby, '')", getChr(ti) + "(10)") + " END", "'<>'","cr.objectid", "'<:>'")); + SQLFragment remarkSql = new SQLFragment("(SELECT " + ti.getSqlDialect().getGroupConcat(groupConatSql, false, true, ti.getSqlDialect().concatenate(getChr(ti) + "(10)", getChr(ti) + "(10)")).getSqlCharSequence() + " as expr1 FROM " + remarksTable.getSelectName() + " cr WHERE cr.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND cr.qcstate = ? AND cr.datefinalized <= {fn now()} AND (cr.category IS NULL or cr.category = ? or cr.category = ?) AND cr.datefinalized >= COALESCE((SELECT max(t.date) as expr FROM " + obsRealTable.getSelectName() + " t WHERE t.category = ? AND " + ExprColumn.STR_TABLE_ALIAS + ".participantId = t.participantId), ?))", qcStateRowId, ONPRC_EHRManager.CLINICAL_SOAP_CATEGORY, ONPRC_EHRManager.RECORD_AMENDMENT, ONPRC_EHRManager.VET_REVIEW, getDefaultVetReviewDate(ti.getUserSchema().getContainer())); + ExprColumn remarkCol = new ExprColumn(ti, "remarksEnteredSinceReview", remarkSql, JdbcType.VARCHAR, ti.getColumn("Id"), ti.getColumn("date")); + remarkCol.setLabel("Remarks Entered Since Last Vet Review"); + remarkCol.setDisplayColumnFactory(VetReviewDisplayColumn::new); + ti.addColumn(remarkCol); } } } @@ -1335,6 +1337,17 @@ private void appendLatestHxCol(AbstractTableInfo ti) recentRemark.setDisplayWidth("200"); ti.addColumn(recentRemark); + //don't use caseId. CEg Plan info Added: 10-25-2017 R.Blasa + SQLFragment recentCeg_Plansql = new SQLFragment("(SELECT " + prefix + " (" + "r.CEG_Plan" + ") as _expr FROM " + realTable.getSelectName() + + " r WHERE " +// + " r.caseid = " + ExprColumn.STR_TABLE_ALIAS + ".objectid AND " + + " r.participantId = " + ExprColumn.STR_TABLE_ALIAS + ".participantId AND r.CEG_Plan IS NOT NULL AND (r.category != ? OR r.category IS NULL) ORDER BY r.date desc " + suffix + ")", ONPRC_EHRManager.REPLACED_SOAP); + ExprColumn recentCeg_plan = new ExprColumn(ti, "mostRecentCeg_Plan", recentCeg_Plansql, JdbcType.VARCHAR, objectId); + recentCeg_plan.setLabel("Most Recent Ceg Plan For Case"); + recentCeg_plan.setDescription("This column will display the most recent CEG Plan that has been entered for the animal."); + recentCeg_plan.setDisplayWidth("200"); + ti.addColumn(recentCeg_plan); + //does not use caseId SQLFragment p2Sql = new SQLFragment("(SELECT " + ti.getSqlDialect().getGroupConcat(new SQLFragment(ti.getSqlDialect().concatenate("'P2: '", "r.p2")), true, false, chr + "(10)").getSqlCharSequence() + " FROM " + realTable.getSelectName() + " r WHERE " @@ -1420,6 +1433,35 @@ private void appendSurgeryCol(AbstractTableInfo ti) ti.addColumn(procedureCol); } + //Added: 11-1-2017 R.Blasa + private void appendSurgeryFollupDaysyCol(AbstractTableInfo ti) + { + String name = "surgeryfollowupDays"; + if (ti.getColumn(name) != null) + return; + + TableInfo realTable = getRealTableForDataset(ti, "Clinical Encounters"); + if (realTable == null) + { + _log.warn("Unable to find real table for clin encounters"); + return; + } + + //find any surgical procedures from the same date as this case + String chr = ti.getSqlDialect().isPostgreSQL() ? "chr" : "char"; + SQLFragment procedureSql = new SQLFragment("(SELECT cast(max(p.followupDays) as varchar(2))" + + " FROM " + realTable.getSelectName() + " r " + + " JOIN ehr_lookups.procedures p ON (p.rowid = r.procedureid) " + + //r.caseid = " + ExprColumn.STR_TABLE_ALIAS + ".objectid AND + " WHERE r.participantId = " + ExprColumn.STR_TABLE_ALIAS + ".participantId " + + " AND CAST(r.date AS date) = CAST(" + ExprColumn.STR_TABLE_ALIAS + ".date as date) " + + " AND r.type = 'Surgery' )"); + ExprColumn procedureCol = new ExprColumn(ti, name, procedureSql, JdbcType.VARCHAR, ti.getColumn("date")); + procedureCol.setLabel("Procedures Surgery Follow up Days"); + procedureCol.setDisplayWidth("100"); + ti.addColumn(procedureCol); + } + private void customizeTasks(AbstractTableInfo ti) { DetailsURL detailsURL = DetailsURL.fromString("/ehr/dataEntryFormDetails.view?formType=${formtype}&taskid=${taskid}"); @@ -1464,7 +1506,6 @@ private void customizeTasks(AbstractTableInfo ti) updateCol.setLabel("Title"); updateCol.setHidden(true); - updateCol.setDisplayWidth("150"); updateTaskId.setLabel("Task Id"); updateTaskId.setHidden(true); @@ -2096,6 +2137,71 @@ public TableInfo getLookupTableInfo() ds.addColumn(col); } +// Added:7-19-2019 R.Blasa Show Alert Flag categories only +private void appendFlagsAlertActiveCol(final UserSchema ehrSchema, AbstractTableInfo ds) +{ + String name = "flagsAlertsActive"; + if (ds.getColumn(name) != null) + return; + + final ColumnInfo pkCol = getPkCol(ds); + if (pkCol == null) + return; + + if (ds.getColumn("Id") == null) + return; + + if (!hasTable(ds, "study", "flags", ehrSchema.getContainer())) + return; + + final String tableName = ds.getName(); + final String queryName = ds.getPublicName(); + final String schemaName = ds.getPublicSchemaName(); + final UserSchema targetSchema = ds.getUserSchema(); + final String ehrPath = ehrSchema.getContainer().getPath(); + + WrappedColumn col = new WrappedColumn(pkCol, name); + col.setLabel("Flags Alerts Active"); + col.setReadOnly(true); + col.setIsUnselectable(true); + col.setUserEditable(false); + col.setFk(new LookupForeignKey(){ + public TableInfo getLookupTableInfo() + { + String name = tableName + "_flagsAtTime"; + QueryDefinition qd = QueryService.get().createQueryDef(targetSchema.getUser(), targetSchema.getContainer(), targetSchema, name); + qd.setSql("SELECT\n" + + "sd." + pkCol.getColumnName() + ",\n" + + "group_concat(DISTINCT h.flag.value, chr(10)) as flagsAlertsActive\n" + + "FROM \"" + schemaName + "\".\"" + queryName + "\" sd\n" + + "JOIN \"" + ehrPath + "\".study.flags h\n" + + " ON (sd.id = h.id AND h.flag.category = 'Alert' AND (h.dateOnly <= CAST(NOW() AS DATE) AND ((CAST(NOW() AS DATE) <= h.enddateCoalesced) or h.enddate is null)) AND h.qcstate.publicdata = true)\n" + + "group by sd." + pkCol.getColumnName()); + qd.setIsTemporary(true); + + List errors = new ArrayList<>(); + TableInfo ti = qd.getTable(errors, true); + if (errors.size() > 0) + { + _log.error("Error creating lookup table for: " + schemaName + "." + queryName + " in container: " + targetSchema.getContainer().getPath()); + for (QueryException error : errors) + { + _log.error(error.getMessage(), error); + } + return null; + } + + ((MutableColumnInfo)ti.getColumn(pkCol.getName())).setHidden(true); + ((MutableColumnInfo)ti.getColumn(pkCol.getName())).setKeyField(true); + + ((MutableColumnInfo)ti.getColumn("flagsAlertsActive")).setLabel("Flags Alerts Active"); + + return ti; + } + }); + + ds.addColumn(col); +} private void appendProblemsAtTimeCol(final UserSchema ehrSchema, AbstractTableInfo ds, final String dateColName) { diff --git a/onprc_reports/resources/queries/genotypeassays/genotypesWithSignificance.query.xml b/onprc_reports/resources/queries/genotypeassays/genotypesWithSignificance.query.xml new file mode 100644 index 000000000..5fa2cc95d --- /dev/null +++ b/onprc_reports/resources/queries/genotypeassays/genotypesWithSignificance.query.xml @@ -0,0 +1,12 @@ + + + + + Genetic Tests + + + +
+
+
+
diff --git a/onprc_reports/resources/queries/genotypeassays/genotypesWithSignificance.sql b/onprc_reports/resources/queries/genotypeassays/genotypesWithSignificance.sql new file mode 100644 index 000000000..0b7d213db --- /dev/null +++ b/onprc_reports/resources/queries/genotypeassays/genotypesWithSignificance.sql @@ -0,0 +1,8 @@ +SELECT +d.subjectId as Id, +d.date, +t.label, +t.comment + +FROM assay.SSP_Assay.TaqMan.data d +JOIN geneticscore.test_significance t ON (d.primerPair = t.probe AND d.result = t.genotype) \ No newline at end of file diff --git a/onprc_reports/resources/queries/study/processingBloodDraws.query.xml b/onprc_reports/resources/queries/study/processingBloodDraws.query.xml index fa9bd4fed..e0e1213be 100644 --- a/onprc_reports/resources/queries/study/processingBloodDraws.query.xml +++ b/onprc_reports/resources/queries/study/processingBloodDraws.query.xml @@ -7,6 +7,9 @@ Is U42? + + PCR Blood Volume (mL) + Serology Blood Vol (mL) diff --git a/onprc_reports/resources/queries/study/processingBloodDraws.sql b/onprc_reports/resources/queries/study/processingBloodDraws.sql index 3034a9392..d020c227b 100644 --- a/onprc_reports/resources/queries/study/processingBloodDraws.sql +++ b/onprc_reports/resources/queries/study/processingBloodDraws.sql @@ -2,12 +2,19 @@ SELECT d.Id, g.isU42, s.spfStatus, + Case when g.isU42 = 'Y' And (s.bloodVol > 0 ) then 2 + ELSE + 0 + End as PCRBloodVolume, s.bloodVol as serologyBloodVol, g.parentageBloodDrawVol, g.mhcBloodDrawVol, g.dnaBloodDrawVol, g.totalBloodDrawVol as geneticsBloodVol, - coalesce(s.bloodVol, 0) + coalesce(g.totalBloodDrawVol, 0) as totalBloodDrawVol + coalesce(s.bloodVol, 0) + Case when g.isU42 = 'Y'And (s.bloodVol > 0 ) then 2 + ELSE + 0 + End + coalesce(g.totalBloodDrawVol, 0) as totalBloodDrawVol FROM study.demographics d diff --git a/onprc_reports/resources/queries/study/processingBloodDraws/.qview.xml b/onprc_reports/resources/queries/study/processingBloodDraws/.qview.xml index fb7cc3262..c1bac19ad 100644 --- a/onprc_reports/resources/queries/study/processingBloodDraws/.qview.xml +++ b/onprc_reports/resources/queries/study/processingBloodDraws/.qview.xml @@ -1,15 +1,16 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/onprc_reports/resources/queries/study/processingGeneticsBloodDraws.sql b/onprc_reports/resources/queries/study/processingGeneticsBloodDraws.sql index 52b872ba9..5c72fce67 100644 --- a/onprc_reports/resources/queries/study/processingGeneticsBloodDraws.sql +++ b/onprc_reports/resources/queries/study/processingGeneticsBloodDraws.sql @@ -6,6 +6,7 @@ SELECT t.geographic_origin, t.gender, t.isU42, + t.isESPF, t.flags, t.parentageBloodDrawVol, t.mhcBloodDrawVol, @@ -24,6 +25,10 @@ SELECT WHEN (a.Id IS NULL) THEN 'N' ELSE 'Y' END as isU42, + CASE + WHEN (u.Id IS NULL) THEN 'N' + ELSE 'Y' + END as isESPF, f.flags, CASE WHEN (f.flags LIKE '%Parentage Blood Draw Needed%') THEN 1 @@ -36,11 +41,13 @@ SELECT END as parentageBloodDrawVol, --Note: MHC draws are being taken on all U42 Animals (Males and females) and non-U42 males only --Note: if changing this logic, mhcFlagSummary.sql should also be updated + --Note: Issue Tracker 4128 changed the method relating to ESPF Animals as depicted in line 48 and 49 CASE WHEN (f.flags LIKE '%MHC Blood Draw Needed%') THEN 1 WHEN (f.flags LIKE '%MHC Typing Not Needed%') THEN 0 WHEN (f.flags LIKE '%MHC Blood Draw Collected%') THEN 0 - WHEN (d.species = 'RHESUS MACAQUE' AND d.Id.age.ageInYears <= 5.0 AND d.geographic_origin = 'India' AND m.Id IS NULL AND (a.Id IS NOT NULL OR d.gender = 'm')) THEN 1 + WHEN (d.species = 'RHESUS MACAQUE' AND d.Id.age.ageInYears <= 5.0 AND d.geographic_origin = 'India' AND m.Id IS NULL AND (a.Id IS NOT NULL OR d.gender = 'm' ) and u.id is null ) THEN 1 + WHEN (u.id is not Null and d.Id.age.ageInYears <= 10.0 and d.Id.age.ageInMonths >= 6 ) then 1 ELSE 0 END as mhcBloodDrawVol, CASE @@ -133,6 +140,17 @@ LEFT JOIN ( GROUP BY a.Id ) a ON (a.Id = d.Id) +--U24 ESPF +LEFT JOIN ( + SELECT + u.Id + --count(*) as total + FROM study.assignment u + WHERE u.isActive = true and u.project.name = javaConstant('org.labkey.onprc_ehr.ONPRC_EHRManager.U24_PROJECT') + GROUP BY u.Id +) u ON (u.Id = d.Id) + + WHERE d.calculated_status = 'Alive' ) t \ No newline at end of file diff --git a/onprc_reports/resources/queries/study/samples.sql b/onprc_reports/resources/queries/study/samples.sql index a6d976be9..66573f909 100644 --- a/onprc_reports/resources/queries/study/samples.sql +++ b/onprc_reports/resources/queries/study/samples.sql @@ -9,6 +9,7 @@ concentration, concentration_units, quantity, quantity_units, -comment +comment, +dateremoved --retain this column since downstream queries still filter on it. more complete fix added to trunk FROM laboratory.samples WHERE dateremoved IS NULL \ No newline at end of file diff --git a/onprc_reports/resources/schemas/GeneticTesting.template.xml b/onprc_reports/resources/schemas/GeneticTesting.template.xml new file mode 100644 index 000000000..9c3e690f2 --- /dev/null +++ b/onprc_reports/resources/schemas/GeneticTesting.template.xml @@ -0,0 +1,12 @@ + + + genotypesWithSignificance + + + + + + + + + \ No newline at end of file diff --git a/onprc_ssu/resources/queries/onprc_ssu/schedule.js b/onprc_ssu/resources/queries/onprc_ssu/schedule.js index d08f3c964..4a69359e4 100644 --- a/onprc_ssu/resources/queries/onprc_ssu/schedule.js +++ b/onprc_ssu/resources/queries/onprc_ssu/schedule.js @@ -9,8 +9,6 @@ var LABKEY = require("labkey"); var helper = org.labkey.ldk.query.LookupValidationHelper.create(LABKEY.Security.currentContainer.id, LABKEY.Security.currentUser.id, 'onprc_ssu', 'schedule'); -console.log("** evaluating: " + this['javax.script.filename']); - function beforeInsert(row, errors){ beforeUpsert(row, errors); diff --git a/sla/resources/queries/sla/PlandProtocols.sql b/sla/resources/queries/sla/PlandProtocols.sql index ad303b132..26d5091ff 100644 --- a/sla/resources/queries/sla/PlandProtocols.sql +++ b/sla/resources/queries/sla/PlandProtocols.sql @@ -1,5 +1,6 @@ SELECT a.project as ProjectID, +aa.species, a.account as Alias, y.grantNumber as OGAGrantNumber, a.protocol as ParentIACUC, @@ -11,12 +12,12 @@ i.FirstName, i.LastName, i.Division, p.external_id, -i.LastName + ': ' + a.name + '('+ p.external_id +')' + ' - ' + a.title as PIIacuc +i.LastName + ': ' + a.name + '('+ p.external_id +')' + ' - ' + a.title + ' (Species: ' + aa.species + ')' as PIIacuc FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.project a LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.protocol p ON p.protocol = a.protocol LEFT JOIN onprc_ehr.investigators i ON i.rowId = a.investigatorId LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.allowableAnimals aa ON a.protocol = aa.protocol -LEFT JOIN "/onprc/admin/finance/public".onprc_billing_public.aliases y ON y.alias = a.account +LEFT JOIN Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer_Public')}.onprc_billing_public.aliases y ON y.alias = a.account WHERE -- filter based on the current date compared with the start and end dates ( @@ -24,6 +25,9 @@ WHERE (aa.StartDate IS NULL AND aa.EndDate IS NOT NULL AND now() < aa.EndDate) OR (now() between aa.StartDate AND aa.EndDate) ) + AND + --Check for the project enddate. Added by LK on 1/16/2019 + (now() between a.StartDate AND a.EndDate) -- and filtered based on dataAccess for the given user AND ( diff --git a/sla/resources/queries/sla/ProtocolProjectsUsage.sql b/sla/resources/queries/sla/ProtocolProjectsUsage.sql index d554dafc6..f7f7aab1f 100644 --- a/sla/resources/queries/sla/ProtocolProjectsUsage.sql +++ b/sla/resources/queries/sla/ProtocolProjectsUsage.sql @@ -1,4 +1,77 @@ + +SELECT +a.project as ProjectID, +a.name AS Project, +p.external_id as eIACUCNum, +a.title as Title, +i.LastName || ', ' || i.FirstName AS PIName, +x.account as Alias, +y.projectNumber as OGAProjectNumber, +y.grantNumber as OGAGrantNumber, +f.lastname || ', ' || f.firstName as FiscalAuthorityName, +aa.Species, +aa.Gender, +aa.Strain, +aa.Allowed AS NumAllowed, +calc.NumUsed, +aa.StartDate, +aa.EndDate +FROM Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.project a +LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.protocol p ON p.protocol = a.protocol +LEFT JOIN onprc_ehr.investigators i ON i.rowId = a.investigatorId +LEFT JOIN onprc_billing.fiscalAuthorities f ON f.rowid = i.financialanalyst +LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.allowableAnimals aa ON a.protocol = aa.protocol +LEFT JOIN (select * from onprc_billing.projectAccountHistory z where (z.StartDate IS NOT NULL AND z.EndDate IS NOT NULL AND now() between z.StartDate AND z.EndDate)) x ON a.project = x.project +LEFT JOIN Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer_Public')}.onprc_billing_public.aliases y ON y.alias = x.account +LEFT JOIN ( +-- SELECT i.protocol,species,gender,sum(animalsreceived) AS NumUsed +-- FROM sla.purchasedetails pd, sla.purchase p +-- LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.project i ON p.project = i.project +-- WHERE p.objectid = pd.purchaseid AND animalsreceived IS NOT NULL +-- GROUP BY i.protocol,species,gender + +--Changed by LK on 5/30 to get the accurate numused. +--Ignore the gender when counting the usage if the approval data gender is: "Male or Female". Count both Male and Female usage. + (SELECT i.protocol,pd.species,sum(animalsreceived) AS NumUsed + FROM sla.purchasedetails pd, sla.purchase p, Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.project i, + Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.allowableAnimals aa1 + Where p.project = i.project AND p.objectid = pd.purchaseid + AND aa1.protocol = i.protocol AND aa1.species = pd.species AND aa1.gender = 'Male or Female' + AND animalsreceived IS NOT NULL + AND (p.orderdate between aa1.StartDate AND aa1.EndDate) AND aa1.enddate > now() + GROUP BY i.protocol, pd.species) + +) AS calc ON a.protocol = calc.protocol + AND (aa.species = calc.species OR (aa.species IS NULL AND calc.species IS NULL)) + --AND (aa.gender = calc.gender OR (aa.gender IS NULL AND calc.gender IS NULL)) + --AND (aa.strain = calc.strain OR (aa.strain IS NULL AND calc.strain IS NULL)) +WHERE + -- filter based on the current date compared with the start and end dates + ( + (aa.StartDate IS NOT NULL AND aa.EndDate IS NULL AND now() > aa.StartDate) OR + (aa.StartDate IS NULL AND aa.EndDate IS NOT NULL AND now() < aa.EndDate) OR + (aa.StartDate IS NOT NULL AND aa.EndDate IS NOT NULL AND now() between aa.StartDate AND aa.EndDate) + AND (aa.gender = 'Male or Female') + ) + AND + --Check for the project enddate. Added by LK on 1/16/2019 + (now() between a.StartDate AND a.EndDate) + -- and filtered based on dataAccess for the given user + AND + ( + (SELECT max(rowid) as expr FROM onprc_billing.dataAccess da + -- current logged in user is the dataAccess user + WHERE isMemberOf(da.userid) + -- has access to all data + AND (da.allData = true + -- has access to the specified investigatorId and the specified project (if applicable) + OR (da.investigatorId = i.rowId AND (da.project IS NULL OR da.project = a.project))) + ) IS NOT NULL + ) + +UNION ALL + SELECT a.project as ProjectID, a.name AS Project, @@ -22,13 +95,25 @@ LEFT JOIN onprc_ehr.investigators i ON i.rowId = a.investigatorId LEFT JOIN onprc_billing.fiscalAuthorities f ON f.rowid = i.financialanalyst LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.allowableAnimals aa ON a.protocol = aa.protocol LEFT JOIN (select * from onprc_billing.projectAccountHistory z where (z.StartDate IS NOT NULL AND z.EndDate IS NOT NULL AND now() between z.StartDate AND z.EndDate)) x ON a.project = x.project -LEFT JOIN "/onprc/admin/finance/public".onprc_billing_public.aliases y ON y.alias = x.account +LEFT JOIN Site.{substitutePath moduleProperty('ONPRC_Billing','BillingContainer_Public')}.onprc_billing_public.aliases y ON y.alias = x.account LEFT JOIN ( - SELECT i.protocol,species,gender,sum(animalsreceived) AS NumUsed - FROM sla.purchasedetails pd, sla.purchase p - LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.project i ON p.project = i.project - WHERE p.objectid = pd.purchaseid AND animalsreceived IS NOT NULL - GROUP BY i.protocol,species,gender +-- SELECT i.protocol,species,gender,sum(animalsreceived) AS NumUsed +-- FROM sla.purchasedetails pd, sla.purchase p +-- LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.project i ON p.project = i.project +-- WHERE p.objectid = pd.purchaseid AND animalsreceived IS NOT NULL +-- GROUP BY i.protocol,species,gender + +--Changed by LK on 5/30 to get the accurate numused. +-- Count only the usage for the "Male" or "Female" gender + (SELECT i.protocol,pd.species,pd.gender,sum(animalsreceived) AS NumUsed + FROM sla.purchasedetails pd, sla.purchase p, Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.project i, + Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.sla.allowableAnimals aa1 + Where p.project = i.project AND p.objectid = pd.purchaseid + AND aa1.protocol = i.protocol AND aa1.species = pd.species AND aa1.gender = pd.gender AND aa1.gender <> 'Male or Female' + AND animalsreceived IS NOT NULL + AND (p.orderdate between aa1.StartDate AND aa1.EndDate) AND aa1.enddate > now() + GROUP BY i.protocol, pd.species, pd.gender) + ) AS calc ON a.protocol = calc.protocol AND (aa.species = calc.species OR (aa.species IS NULL AND calc.species IS NULL)) AND (aa.gender = calc.gender OR (aa.gender IS NULL AND calc.gender IS NULL)) @@ -38,9 +123,12 @@ WHERE ( (aa.StartDate IS NOT NULL AND aa.EndDate IS NULL AND now() > aa.StartDate) OR (aa.StartDate IS NULL AND aa.EndDate IS NOT NULL AND now() < aa.EndDate) OR - (now() between aa.StartDate AND aa.EndDate) - --(x.StartDate IS NOT NULL AND x.EndDate IS NOT NULL AND now() between x.StartDate AND x.EndDate) + (aa.StartDate IS NOT NULL AND aa.EndDate IS NOT NULL AND now() between aa.StartDate AND aa.EndDate) + AND (aa.gender <> 'Male or Female') ) + AND + --Check for the project enddate. Added by LK on 1/16/2019 + (now() between a.StartDate AND a.EndDate) -- and filtered based on dataAccess for the given user AND ( diff --git a/sla/resources/queries/sla/SLACageSize.sql b/sla/resources/queries/sla/SLACageSize.sql index 3abf57b9f..d811d9159 100644 --- a/sla/resources/queries/sla/SLACageSize.sql +++ b/sla/resources/queries/sla/SLACageSize.sql @@ -6,10 +6,9 @@ /* Created Blasa 2-13-2015 Provide Distinct SLA Cage Size Reference table */ - select distinct cagesize - from onprc_billing.slaPerDiemFeeDefinition b - Where active = True - order by cagesize - + select value + from sla.Reference_Data + Where columnName = 'cagesize' + order by sort_order diff --git a/sla/resources/queries/sla/SLACageType.sql b/sla/resources/queries/sla/SLACageType.sql index 9c34883e0..d1a216b51 100644 --- a/sla/resources/queries/sla/SLACageType.sql +++ b/sla/resources/queries/sla/SLACageType.sql @@ -5,11 +5,12 @@ */ /* Created Blasa 2-13-2015 Provide Distinct SLA Cage Type Reference table */ +-- Modified:R.blasa 5-23-2017 - select distinct cagetype - from onprc_billing.slaPerDiemFeeDefinition b - Where active = True - order by cagetype + select value + from sla.Reference_Data + Where columnName = 'cagetype' + order by sort_order diff --git a/sla/resources/queries/sla_public/PurchaseOrderDetailsAdmin.sql b/sla/resources/queries/sla_public/PurchaseOrderDetailsAdmin.sql index 111d37264..d9c3c2f35 100644 --- a/sla/resources/queries/sla_public/PurchaseOrderDetailsAdmin.sql +++ b/sla/resources/queries/sla_public/PurchaseOrderDetailsAdmin.sql @@ -3,6 +3,7 @@ SELECT '[Update order]' AS updatelink, '[Print view]' AS printviewlink, p.rowid, +p.requestdate, p.projectname, p.protocol, p.investigator, @@ -16,14 +17,13 @@ pd.weight, pd.gestation, pd.room, pd.animalsordered, -p.requestdate, pd.expectedarrivaldate, -pd.housingInstructions, p.confirmationnum, p.housingconfirmed, p.orderdate, pd.sla_DOB, pd.vendorLocation, +pd.housingInstructions, pd.receiveddate, pd.receivedby, pd.datecancelled, diff --git a/sla/resources/schemas/sla.xml b/sla/resources/schemas/sla.xml index f3160402a..36018f4f1 100644 --- a/sla/resources/schemas/sla.xml +++ b/sla/resources/schemas/sla.xml @@ -63,7 +63,7 @@ /ONPRC/EHR sla SLACageType - cagetype + value
@@ -73,7 +73,7 @@ /ONPRC/EHR sla SLACageSize - cagesize + value
diff --git a/sla/resources/web/sla/form/CreatePurchaseOrder.js b/sla/resources/web/sla/form/CreatePurchaseOrder.js index 6e0664a21..32faa2780 100644 --- a/sla/resources/web/sla/form/CreatePurchaseOrder.js +++ b/sla/resources/web/sla/form/CreatePurchaseOrder.js @@ -1,8 +1,10 @@ + /** * Ext component for creating the input form and species grid for collecting/updating information about * a purchase order (see createPurchaseOrder.html and updatePurchaseOrder.html for usages). */ Ext4.define('SLA.panel.PurchaseOrderRequest', { + extend: 'Ext.panel.Panel', bodyStyle: 'background-color: transparent;', @@ -20,6 +22,26 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { */ initComponent: function() { + //Ext4.apply(this, { + // bodyStyle: 'padding: 5px;', + // defaults: { + // border: false + // }, + // items: [{ + // html: 'The birth/arrival screen will be disabled as a default. You must enable the form in order to:
  • Get an Animal ID(s)
  • Secure the numbers for processing
  • Finish entering data on acquired numbers

When you enable the form for data entry all others will automatically be blocked from using the form.
Once you "Submit for Review" or "Save and Close", the birth/arrival form will be automatically be available for all other users. If you do not submit/save please click the button below to exit data entry before leaving, otherwise all other users will be permanently locked out.

If the birth/arrival form is unavailable and you believe it has been kept locked by mistake please first contact the person who locked the form. If they cannot be reached and it is a weekday please e-mail onprcitsupport@ohsu.edu with the subject "Priority 1 Work Stoppage: birth/arrival Form Locked". If it is a weekend please contact an RFO lead tech. Please take care not to request the birth/arrival form be unlocked unless you are confident the lock is in error, otherwise you will kick a user out of the birth/arrival form and prevent data entry.' , + // style: 'padding-bottom: 10px;' + // },{ + // itemId: 'infoArea', + // border: false + // },{ + // layout: 'hbox', + // defaults: { + // style: 'margin-right: 5px;' + // }, + // }] + //}); + + // add the initial form sections, start with just the protocol form if this is not an update var items = [ this.getProtocolForm(), @@ -42,6 +64,8 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { this.callParent(); }, + + /** * Initialize the Ext panel for selecting the IACUC protocol for a purchase order. * @returns {SLA.form.ProtocolForm} @@ -105,8 +129,8 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { noRequestorRecord: function(form) { Ext4.get('purchaseOrderErrors').update('

' - + 'No requestor record found for your user account. Please contact an administrator to get ' - + 'this issue resolved.

'); + + 'No requestor record found for your user account. Please contact an administrator to get ' + + 'this issue resolved.

'); this.disable(); } } @@ -228,8 +252,8 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { toggleSubmitButton : function() { var protocolValid = this.getProtocolForm().isValid(), - formValid = this.getPurchaseForm().isValid(), - speciesGridValid = this.getPurchaseSpeciesGrid().isValid(); + formValid = this.getPurchaseForm().isValid(), + speciesGridValid = this.getPurchaseSpeciesGrid().isValid(); this.getSubmitButton().setDisabled(this.adminContainer == null || !protocolValid || !formValid || !speciesGridValid); }, @@ -434,15 +458,17 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { } //added by Kolli - if (speciesRowData.location == 'NSI 0123D' || speciesRowData.location == 'NSI 0125D' ) + //Added the new room to the list: NSI 134 by Kolli on 4/19 + if (speciesRowData.room == 'NSI 0123D' || speciesRowData.room == 'NSI 0125D' || speciesRowData.room == 'NSI 0134') { isHazardsRequired = true; } }, this); - if (isHazardsRequired && (purchaseData.listHazard == null || purchaseData.listHazard == '')) + //if (isHazardsRequired && (purchaseData.listHazard == null || purchaseData.listHazard == '')) + if (isHazardsRequired && (purchaseData.hazardslist == null || purchaseData.hazardslist == '')) { - this.showErrorMsg('You have selected Location(s): NSI 0123D or NSI 0125D. Please list the biological or chemical agents! '); + this.showErrorMsg('You have selected Location(s): NSI 0123D or NSI 0125D or NSI 134. Please list the biological or chemical agents! '); return; } @@ -529,13 +555,13 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { Ext4.Msg.confirm('Confirmation Message', warnMsg, function (btn) { if (btn == 'yes') - //successCallback.call(scope); + //successCallback.call(scope); this.insertPurchaseOrder(purchaseData); else this.getSubmitButton().enable(); }, this); - // this.insertPurchaseOrder(purchaseData); + // this.insertPurchaseOrder(purchaseData); }, this); } }, @@ -672,15 +698,15 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { if (value.PercentUsed > 105) { errorMsg += errorSep + 'With the current order, you have exceeded 100% plus 5% more animal usage of the approved quantity. ' + baseMsg - + ' You are not authorized to purchase any more animals at this point. If you wish to purchase more animals, please contact the IACUC committee for approval!'; + + ' You are not authorized to purchase any more animals at this point. If you wish to purchase more animals, please contact the IACUC committee for approval!'; errorSep = '

'; } else if (value.PercentUsed > 100) { warnMsg += warnSep + 'With the current order, you have exceeded 100% animal usage of the approved quantity. ' + baseMsg - + ' According to IACUC committee, you can order 5% more animals than the approved quantity without IACUC approval. ' - + 'Therefore in this order, you can order an extra ' + Math.floor(value.NumAllowed * 0.05) + ' animal(s). ' - + 'If you wish to purchase more animals, please contact the IACUC committee for approval!'; + + ' According to IACUC committee, you can order 5% more animals than the approved quantity without IACUC approval. ' + + 'Therefore in this order, you can order an extra ' + Math.floor(value.NumAllowed * 0.05) + ' animal(s). ' + + 'If you wish to purchase more animals, please contact the IACUC committee for approval!'; warnSep = '

'; } else if (value.PercentUsed == 100) @@ -785,11 +811,11 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { if (!sendNotification && this.initData != null) { var prevConfNum = this.initData.purchase['confirmationnum'], - newConfNum = newPurchaseData['confirmationnum'], - prevOrderDt = this.trimDateToYMDStr(this.initData.purchase['orderdate']), - newOrderDt = this.trimDateToYMDStr(newPurchaseData['orderdate']), - prevHousingAvail = this.initData.purchase['housingconfirmed'], - newHousingAvail = newPurchaseData['housingconfirmed']; + newConfNum = newPurchaseData['confirmationnum'], + prevOrderDt = this.trimDateToYMDStr(this.initData.purchase['orderdate']), + newOrderDt = this.trimDateToYMDStr(newPurchaseData['orderdate']), + prevHousingAvail = this.initData.purchase['housingconfirmed'], + newHousingAvail = newPurchaseData['housingconfirmed']; sendNotification = prevConfNum != newConfNum || prevOrderDt != newOrderDt; @@ -809,21 +835,21 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { Ext4.each(newPurchaseData.details, function (detailsRow) { var objectid = detailsRow['objectid'], - receiveddate = Ext4.isDate(detailsRow['receiveddate']) ? Ext4.util.Format.date(detailsRow['receiveddate'], 'Y-m-d') : this.trimDateToYMDStr(detailsRow['receiveddate']), - receivedby = detailsRow['receivedby'], - datecancelled = Ext4.isDate(detailsRow['datecancelled']) ? Ext4.util.Format.date(detailsRow['datecancelled'], 'Y-m-d') : this.trimDateToYMDStr(detailsRow['datecancelled']), - cancelledby = detailsRow['cancelledby']; + receiveddate = Ext4.isDate(detailsRow['receiveddate']) ? Ext4.util.Format.date(detailsRow['receiveddate'], 'Y-m-d') : this.trimDateToYMDStr(detailsRow['receiveddate']), + receivedby = detailsRow['receivedby'], + datecancelled = Ext4.isDate(detailsRow['datecancelled']) ? Ext4.util.Format.date(detailsRow['datecancelled'], 'Y-m-d') : this.trimDateToYMDStr(detailsRow['datecancelled']), + cancelledby = detailsRow['cancelledby']; // compare new values to previous, or if this is a new species row, check for non-null key values if (Ext4.isDefined(prevDetailsMap[objectid])) { var prevReceiveddate = this.trimDateToYMDStr(prevDetailsMap[objectid]['receiveddate']), - prevReceivedby = prevDetailsMap[objectid]['receivedby'], - prevDatecancelled = this.trimDateToYMDStr(prevDetailsMap[objectid]['datecancelled']), - prevCancelledby = prevDetailsMap[objectid]['cancelledby']; + prevReceivedby = prevDetailsMap[objectid]['receivedby'], + prevDatecancelled = this.trimDateToYMDStr(prevDetailsMap[objectid]['datecancelled']), + prevCancelledby = prevDetailsMap[objectid]['cancelledby']; sendNotification = prevReceiveddate != receiveddate || prevReceivedby != receivedby - || prevDatecancelled != datecancelled || prevCancelledby != cancelledby; + || prevDatecancelled != datecancelled || prevCancelledby != cancelledby; } else if (receiveddate != null || receivedby != null || datecancelled != null || cancelledby != null) { @@ -855,15 +881,246 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { success: function (response) { this.showSuccess(rowId); + this.insertMiscCharges(rowId,newPurchaseData); } }); } else { this.showSuccess(rowId); + this.insertMiscCharges(rowId,newPurchaseData); } + }, + ////Kollil: If the new receiving info is entered, Insert a row into the onprc_billing.miscCharges table + //insertMiscCharges : function (rowId,newPurchaseData) + //{ + // var miscCharges=[]; + // var prevDetailsMap = {}; + // var vendor_id ; + // + // //Get the vendor id for the given name + // LABKEY.Query.executeSql({ + // method: 'POST', + // schemaName: 'sla_public', + // sql: "Select objectid from vendors where name = 'ONPRC Weaning - SLA'", + // //failure: LDK.Utils.getErrorCallback(), + // success: function(data) + // { + // // we expect exactly one row in the response, so if that is not the case return an 'Invalid' error + // if (data.rows.length != 1) + // { + // response.error = 'Invalid vendorid'; + // callback.call(scope, response); + // } + // else + // { + // vendor_id = data.rows[0].objectid; + // + // // } + // // } + // //}); + // // Get previous purchase data + // Ext4.each(this.initData.species, function (speciesRow) + // { + // prevDetailsMap[speciesRow['objectid']] = speciesRow; + // }); + // // Get New purchase data + // Ext4.each(newPurchaseData.details, function (detailsRow) + // { + // var objectid = detailsRow['objectid'], + // receiveddate = Ext4.isDate(detailsRow['receiveddate']) ? Ext4.util.Format.date(detailsRow['receiveddate'], 'Y-m-d') : this.trimDateToYMDStr(detailsRow['receiveddate']), + // receivedby = detailsRow['receivedby']; + // + // if (Ext4.isDefined(prevDetailsMap[objectid])) + // { + // var prevReceiveddate = this.trimDateToYMDStr(prevDetailsMap[objectid]['receiveddate']), + // prevReceivedby = prevDetailsMap[objectid]['receivedby']; + // + // //Compare the receiving info with the previous data + // if ((prevReceiveddate == null & receiveddate != null) || (prevReceivedby == null & receivedby != null)) + // { + // //if (newPurchaseData['vendorid.name'] == 'ONPRC Weaning - SLA') + // if (newPurchaseData['vendorid'] == vendor_id) + // { + // miscCharges.push({ + // "date": receiveddate, + // "project": newPurchaseData['project'], + // "objectid": LABKEY.Utils.generateUUID(), + // //"category": 'SLA Fees', + // "chargeType": 'SLAU', + // "chargeId": 5398, //Chargeableitem: ChargeName = 'SLAU Weaning Fee', ChargeID = 5398 + // "quantity": 1, //detailsRow['NumAnimalsReceived'], + // "comment": 'SLA Weaning', + // }); + // } + // else + // { + // miscCharges.push({ + // "date": receiveddate, + // "project": newPurchaseData['project'], + // "objectid": LABKEY.Utils.generateUUID(), + // //"category": 'SLA Fees', + // "chargeType": 'SLAU', + // "chargeId": 5331, //Chargeableitem: ChargeName = 'SLAU Animal Purchase', ChargeID = 5331 + // "quantity": 1, //detailsRow['NumAnimalsReceived'], + // "comment": 'SLA Purchase billing', + // }); + // } + // } + // } + // },this); + // + // if (miscCharges.length > 0 ) + // { + // LABKEY.Query.insertRows({ + // containerPath: '/ONPRC/EHR', + // schemaName: 'onprc_billing', + // queryName: 'miscCharges', + // rows: miscCharges, + // scope: this, + // success: function () + // { + // this.showSuccess(rowId); + // }, + // failure: function(response) + // { + // console.error(response.exception); + // this.showErrorMsg(response.exception); + // } + // }); + // } + // else + // { + // this.showSuccess(rowId); + // } + // + // } + // } + // }); + //}, + + + //Kollil: If the new receiving info is entered, Insert a row into the onprc_billing.miscCharges table + insertMiscCharges : function (rowId,newPurchaseData) + { + var miscCharges=[]; + var prevDetailsMap = {}; + //var vendor_id ; + + ////Get the vendor id for the given name + //LABKEY.Query.executeSql({ + // method: 'POST', + // schemaName: 'sla_public', + // sql: "Select objectid from vendors where name = 'ONPRC Weaning - SLA'", + // //failure: LDK.Utils.getErrorCallback(), + // success: function(data) + // { + // // we expect exactly one row in the response, so if that is not the case return an 'Invalid' error + // if (data.rows.length != 1) + // { + // response.error = 'Invalid vendorid'; + // callback.call(scope, response); + // } + // else + // { + // vendor_id = data.rows[0].objectid; + // } + // } + //}); + + // Get previous purchase data + Ext4.each(this.initData.species, function (speciesRow) + { + prevDetailsMap[speciesRow['objectid']] = speciesRow; + }); + // Get New purchase data + Ext4.each(newPurchaseData.details, function (detailsRow) + { + var objectid = detailsRow['objectid'], + receiveddate = Ext4.isDate(detailsRow['receiveddate']) ? Ext4.util.Format.date(detailsRow['receiveddate'], 'Y-m-d') : this.trimDateToYMDStr(detailsRow['receiveddate']), + receivedby = detailsRow['receivedby']; + + if (Ext4.isDefined(prevDetailsMap[objectid])) + { + var prevReceiveddate = this.trimDateToYMDStr(prevDetailsMap[objectid]['receiveddate']), + prevReceivedby = prevDetailsMap[objectid]['receivedby']; + + //Compare the receiving info with the previous data + if ((prevReceiveddate == null & receiveddate != null) || (prevReceivedby == null & receivedby != null)) + { + if (this.initData.purchase.vendor == 'ONPRC Weaning - SLA') + //if (newPurchaseData['vendorid'] == vendor_id) + { + miscCharges.push({ + "date": receiveddate, + "project": newPurchaseData['project'], + "objectid": LABKEY.Utils.generateUUID(), + //"category": 'SLA Fees', + "chargeType": 'SLAU', + "chargeId": 5398, //Chargeableitem: ChargeName = 'SLAU Weaning Fee', ChargeID = 5398 + "quantity": 1, //detailsRow['NumAnimalsReceived'], + "comment": 'SLA Weaning' + }); + } + //Added by Kolli on 03-01-2019 + else if (this.initData.purchase.vendor == 'ONPRC Weaning - Self Prepared') + { + miscCharges.push({ + "date": receiveddate, + "project": newPurchaseData['project'], + "objectid": LABKEY.Utils.generateUUID(), + //"category": 'SLA Fees', + "chargeType": 'SLAU', + "chargeId": 5614, //Chargeableitem: ChargeName = 'SLAU Weaning - No Staff', ChargeID = 5398 + "quantity": 1, //detailsRow['NumAnimalsReceived'], + "comment": 'SLA Weaning - Self Prepared' + }); + } + else + { + miscCharges.push({ + "date": receiveddate, + "project": newPurchaseData['project'], + "objectid": LABKEY.Utils.generateUUID(), + //"category": 'SLA Fees', + "chargeType": 'SLAU', + "chargeId": 5331, //Chargeableitem: ChargeName = 'SLAU Animal Purchase', ChargeID = 5331 + "quantity": 1, //detailsRow['NumAnimalsReceived'], + "comment": 'SLA Purchase billing' + }); + } + } + } + },this); + + if (miscCharges.length > 0 ) + { + LABKEY.Query.insertRows({ + containerPath: '/ONPRC/EHR', + schemaName: 'onprc_billing', + queryName: 'miscCharges', + rows: miscCharges, + scope: this, + success: function () + { + this.showSuccess(rowId); + }, + failure: function(response) + { + console.error(response.exception); + this.showErrorMsg(response.exception); + } + }); + } + else + { + this.showSuccess(rowId); + } + }, + + trimDateToYMDStr : function(val) { var newVal = val != null && val.indexOf(' ') > 0 ? val.substring(0, val.indexOf(' ')) : val; @@ -945,3 +1202,7 @@ Ext4.define('SLA.panel.PurchaseOrderRequest', { }); } }); + + + + diff --git a/sla/resources/web/sla/form/PurchaseOrder.css b/sla/resources/web/sla/form/PurchaseOrder.css index b0d9ec600..574ab5f6b 100644 --- a/sla/resources/web/sla/form/PurchaseOrder.css +++ b/sla/resources/web/sla/form/PurchaseOrder.css @@ -14,6 +14,11 @@ border-radius: 5px; } +.order-dashboard-warning { + color: #ff0000; + font-weight: bold; +} + .order-dashboard-summary .order-dashboard-item a { font-weight: bold; } diff --git a/sla/resources/web/sla/form/PurchaseOrderDashboard.js b/sla/resources/web/sla/form/PurchaseOrderDashboard.js index 46193d212..354ee4fd7 100644 --- a/sla/resources/web/sla/form/PurchaseOrderDashboard.js +++ b/sla/resources/web/sla/form/PurchaseOrderDashboard.js @@ -159,7 +159,7 @@ Ext4.define('SLA.panel.PurchaseOrderDashboard', { data: data, tpl: new Ext4.XTemplate( '', - + '
Note: All purchase requests must be recieved no later than WEDNESDAY NOON for shipments next week. If you have any questions, Please contact, Kati Marshall: marshalk@ohsu.edu

', '
', '
Data Entry
', '', diff --git a/sla/resources/web/sla/form/PurchaseOrderDetails.js b/sla/resources/web/sla/form/PurchaseOrderDetails.js index 328296f7e..bd13ce256 100644 --- a/sla/resources/web/sla/form/PurchaseOrderDetails.js +++ b/sla/resources/web/sla/form/PurchaseOrderDetails.js @@ -123,12 +123,11 @@ Ext4.define('SLA.panel.PurchaseOrderDetails', { 'WEIGHT: {weight:htmlEncode}
', 'GESTATION: {gestation:htmlEncode}
', 'NUM ANIMALS ORDERED: {animalsordered}
', + 'SPECIAL INSTRUCTIONS: {housinginstructions:htmlEncode}
', 'REQUESTED ARRIVAL DATE: {requestedarrivaldate}
', 'EXPECTED ARRIVAL DATE: {expectedarrivaldate}
', 'SLA_DOB: {sla_DOB}
', 'SLA VENDOR LOCATION: {vendorLocation}
', - 'SPECIAL INSTRUCTIONS: {housinginstructions:htmlEncode}
', - '
', '
', '' diff --git a/sla/resources/web/sla/form/PurchaseOrderForm.js b/sla/resources/web/sla/form/PurchaseOrderForm.js index fc31b66ff..c144dc27a 100644 --- a/sla/resources/web/sla/form/PurchaseOrderForm.js +++ b/sla/resources/web/sla/form/PurchaseOrderForm.js @@ -170,7 +170,7 @@ Ext4.define('SLA.form.PurchaseForm', { name: 'hazardslist', value: this.initData['hazardslist'], disabled: this.isUpdate && !LABKEY.user.canUpdate, - fieldLabel: 'List Biological or Chemical agents (Required for NSI 0123D, NSI 0125D)', + fieldLabel: 'List Biological or Chemical agents (Required for NSI 0123D, NSI 0125D, NSI 0134)', labelWidth: this.FIELD_LABEL_WIDTH }); diff --git a/sla/resources/web/sla/form/PurchaseSpeciesGrid.js b/sla/resources/web/sla/form/PurchaseSpeciesGrid.js index 5f2147a44..2d5e3eb04 100644 --- a/sla/resources/web/sla/form/PurchaseSpeciesGrid.js +++ b/sla/resources/web/sla/form/PurchaseSpeciesGrid.js @@ -207,7 +207,7 @@ Ext4.define('SLA.form.SpeciesGrid', { editor: { // use the input field that validates input as text xtype: 'datefield', - minValue: new Date() + //minValue: new Date() } }, { @@ -303,7 +303,7 @@ Ext4.define('SLA.form.SpeciesGrid', { } }, { - hidden: !LABKEY.user.canUpdate, // fields in this form should only be seen by Editors + //hidden: !LABKEY.user.canUpdate, // fields in this form should only be seen by Editors dataIndex: 'sla_DOB', text: 'SLA DOB', width: 250, diff --git a/sla/resources/web/sla/window/AddCensusWindow.js b/sla/resources/web/sla/window/AddCensusWindow.js index d4d306f98..ec202d7a8 100644 --- a/sla/resources/web/sla/window/AddCensusWindow.js +++ b/sla/resources/web/sla/window/AddCensusWindow.js @@ -17,6 +17,7 @@ Ext4.define('SLA.window.AddCensusWindow', { MAX_RECORDS: 350, initComponent: function(){ + var ctx = EHR.Utils.getEHRContext(); Ext4.apply(this, { title: 'Choose Location(s)', modal: true, @@ -39,39 +40,15 @@ Ext4.define('SLA.window.AddCensusWindow', { border: false, width: 400 }, - /* items: [{ - xtype: 'ehr-areafield', - multiSelect: false, - emptyText: '', - fieldLabel: 'Area', - itemId: 'areaField', - pairedWithRoomField: true, - getRoomField: function(){ - return this.up('form').down('#roomField') - } - },{ */ + items: [{ - xtype: 'ehr-roomfield', + xtype: 'onprc_RoomfieldExtended', multiSelect: true, addAllSelector: true, typeAhead: true, emptyText: '', - // showOccupiedOnly: true, fieldLabel: 'Room(s)', - itemId: 'roomField', - getStoreFilterArray: function(){ - var ret = [ - LABKEY.Filter.create('datedisabled', null, LABKEY.Filter.Types.ISBLANK), - LABKEY.Filter.create('housingType', 589, LABKEY.Filter.Types.EQUAL) - ]; - return ret; - }, - listeners: { - change: function (field) { - var areaField = field.up('panel').down('#areaField'); - areaField.reset(); - } - } + itemId: 'roomField' }] }], buttons: [{ diff --git a/treatmentETL/resources/etls/TreatmentToDrug.xml b/treatmentETL/resources/etls/TreatmentToDrug.xml deleted file mode 100644 index c5df5d329..000000000 --- a/treatmentETL/resources/etls/TreatmentToDrug.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - TreatmentToDrug - Transfers from the treatmentProcessing table in Study to the Drug table in Study - - - Transfer to Drug Table - - - - - - - diff --git a/treatmentETL/resources/queries/study/treatmentScheduleUpdate.sql b/treatmentETL/resources/queries/study/treatmentScheduleUpdate.sql index 5f5cbb563..4efde2469 100644 --- a/treatmentETL/resources/queries/study/treatmentScheduleUpdate.sql +++ b/treatmentETL/resources/queries/study/treatmentScheduleUpdate.sql @@ -1,3 +1,7 @@ +--Date 2019-03-15 +--By jonesga +--inserted missing code at line 87 + SELECT d.id, d.calculated_status, @@ -84,6 +88,7 @@ JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.study."Trea ON (dr.dateOnly >= t1.dateOnly and dr.dateOnly <= t1.enddateCoalesced AND --technically the first day of the treatment is day 1, not day 0 mod(CAST(timestampdiff('SQL_TSI_DAY', CAST(t1.dateOnly as timestamp), dr.dateOnly) as integer), t1.frequency.intervalindays) = 0 + OR (t1.frequency.dayofweek is not null And t1.frequency.intervalindays is null And dr.DayOfWeek in (select k.value from onprc_ehr.Frequency_DayofWeek k where k.FreqKey = t1.frequency.rowid )) ) LEFT JOIN Site.{substitutePath moduleProperty('EHR','EHRStudyContainer')}.ehr.treatment_times tt ON (tt.treatmentid = t1.objectid) @@ -106,7 +111,8 @@ WHERE t1.date is not null ) s ON (s.animalid = d.id) -WHERE d.calculated_status = 'Alive' +WHERE --d.calculated_status = 'Alive' --account for date/time in schedule -and s.date >= s.startDate and s.date <= s.enddate +--and +s.date >= s.startDate and s.date <= s.enddate